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 eilang.Interpreting;
namespace eilang.OperationCodes
{
public class StringToUpper : IOperationCode
{
public void Execute(State state)
{
var str = state.Scopes.Peek().GetVariable(SpecialVariables.String).Get<string>();
state.Stack.Push(state.ValueFactory.String(str.ToUpperInvariant()));
}
}
} | 27.692308 | 93 | 0.655556 | [
"MIT"
] | Szune/eilang | eilang/OperationCodes/StringToUpper.cs | 362 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
namespace CoreCmdPlayground.Commands
{
class NamedPipeCommand
{
public void NamedServer()
{
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out))
{
Console.WriteLine("NamedPipeServerStream object created.");
// Wait for a client to connect
Console.Write("Waiting for client connection...");
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
try
{
// Read user input and send that to the client process.
using (StreamWriter sw = new StreamWriter(pipeServer))
{
sw.AutoFlush = true;
Console.Write("Enter text: ");
sw.WriteLine(Console.ReadLine());
}
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException e)
{
Console.WriteLine("ERROR: {0}", e.Message);
}
}
}
public void NamedClient()
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In))
{
// Connect to the pipe or wait until the pipe is available.
Console.Write("Attempting to connect to pipe...");
pipeClient.Connect();
Console.WriteLine("Connected to pipe.");
Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances);
using (StreamReader sr = new StreamReader(pipeClient))
{
// Display the read text to the console
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", temp);
}
}
}
Console.Write("Press Enter to continue...");
Console.ReadLine();
}
}
}
| 35.462687 | 125 | 0.501684 | [
"MIT"
] | li-rongcheng/CoreCmdPlayground | CoreCmdPlayground/Commands/NamedPipeCommand.cs | 2,378 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace IdentityServer.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 43.099548 | 122 | 0.498688 | [
"MIT"
] | StefanGP88/IdentityServerAddOn | IdentityServerAddOn/IdentityServer/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,527 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Refit;
namespace TailwindTraders.Mobile.Features.LogIn
{
public interface IProfilesAPI
{
[Get("/")]
Task<IEnumerable<ProfileDTO>> GetAsync(
[Header(Settings.Settings.ApiAuthorizationHeader)] string authorizationHeader);
}
}
| 24 | 91 | 0.71131 | [
"MIT"
] | Lazareena/TailwindTraders-Mobile | Source/TailwindTraders.Mobile/TailwindTraders.Mobile/Features/LogIn/IProfilesAPI.cs | 338 | C# |
namespace JoinRpg.Dal.Impl.Migrations
{
using System.Data.Entity.Migrations;
public partial class CommentExtraAction : DbMigration
{
public override void Up() => AddColumn("dbo.Comments", "ExtraAction", c => c.Int());
public override void Down() => DropColumn("dbo.Comments", "ExtraAction");
}
}
| 27.5 | 92 | 0.669697 | [
"MIT"
] | HeyLaurelTestOrg/joinrpg-net | src/JoinRpg.Dal.Impl/Migrations/201512022027489_CommentExtraAction.cs | 330 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\opmapi.h(436,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[Guid("0a15159d-41c7-4456-93e1-284cd61d4e8d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IOPMVideoOutput
{
[PreserveSig]
HRESULT StartInitialization(/* [annotation][out] _Out_ */ out _OPM_RANDOM_NUMBER prnRandomNumber, /* [annotation][out] _Outptr_result_bytebuffer_(*pulCertificateLength) */ out IntPtr ppbCertificate, /* [annotation][out] _Out_ */ out uint pulCertificateLength);
[PreserveSig]
HRESULT FinishInitialization(/* [annotation][in] _In_ */ ref _OPM_ENCRYPTED_INITIALIZATION_PARAMETERS pParameters);
[PreserveSig]
HRESULT GetInformation(/* [annotation][in] _In_ */ ref _OPM_GET_INFO_PARAMETERS pParameters, /* [annotation][out] _Out_ */ out _OPM_REQUESTED_INFORMATION pRequestedInformation);
[PreserveSig]
HRESULT COPPCompatibleGetInformation(/* [annotation][in] _In_ */ ref _OPM_COPP_COMPATIBLE_GET_INFO_PARAMETERS pParameters, /* [annotation][out] _Out_ */ out _OPM_REQUESTED_INFORMATION pRequestedInformation);
[PreserveSig]
HRESULT Configure(/* [annotation][in] _In_ */ ref _OPM_CONFIGURE_PARAMETERS pParameters, /* [annotation][in] _In_ */ int ulAdditionalParametersSize, /* [annotation][in] _In_reads_bytes_opt_(ulAdditionalParametersSize) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pbAdditionalParameters);
}
}
| 60.615385 | 315 | 0.734772 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IOPMVideoOutput.cs | 1,578 | C# |
using System;
using System.Runtime.Remoting;
namespace CountHost
{
class Class1
{
static void Main(string[] args)
{
try
{
RemotingConfiguration.Configure(@"..\..\CountHost.exe.config");
}
catch (Exception e)
{
System.Console.WriteLine("Failed to configure host application: " + e.Message,System.Diagnostics.EventLogEntryType.Error);
}
System.Console.WriteLine("Press [Enter] to exit...");
System.Console.ReadLine();
}
}
}
| 19.583333 | 126 | 0.67234 | [
"MIT"
] | wf539/CSharpDotNETWebDevsGuide | code_06/Servers/CountHost/Class1.cs | 470 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using TeamIHOC.Library.Identity;
using TeamIHOC.Library.Model;
namespace TeamIHOC.Library
{
public class ViewHelper
{
public static ApplicationRoleManager RoleManager()
{
return HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
}
public static ApplicationUserManager UserManager()
{
return HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>();
}
//public static bool UserInRole(string roleName)
//{
// ApplicationUser user = UserManager().FindByName(HttpContext.Current.User.Identity.Name);
//}
}
}
| 26.294118 | 102 | 0.686801 | [
"Unlicense"
] | IHOC/Website | TeamIHOC.Library/ViewHelper.cs | 896 | C# |
// <auto-generated>
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFilterRulesOperations operations.
/// </summary>
internal partial class RouteFilterRulesOperations : IServiceOperations<NetworkManagementClient>, IRouteFilterRulesOperations
{
/// <summary>
/// Initializes a new instance of the RouteFilterRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteFilterRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2021-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilterRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2021-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilter", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2021-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (routeFilterRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters");
}
if (routeFilterRuleParameters != null)
{
routeFilterRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2021-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilterNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 46.658781 | 338 | 0.569035 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/network/Microsoft.Azure.Management.Network/src/Generated/RouteFilterRulesOperations.cs | 51,278 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("UnityEditor.TestRunner")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Editor")]
[assembly: InternalsVisibleTo("Unity.IntegrationTests")]
[assembly: InternalsVisibleTo("UnityEditor.TestRunner.Tests")]
[assembly: InternalsVisibleTo("Unity.TestTools.CodeCoverage.Editor")]
[assembly: InternalsVisibleTo("Unity.PackageManagerUI.Develop.Editor")]
[assembly: InternalsVisibleTo("Unity.PackageManagerUI.Develop.EditorTests")]
[assembly: InternalsVisibleTo("Unity.PackageValidationSuite.Editor")]
[assembly: AssemblyVersion("1.0.0")]
| 47.1875 | 76 | 0.825166 | [
"MIT"
] | 16pxdesign/genetic-algorithm-unity | Library/PackageCache/com.unity.test-framework@1.1.9/UnityEditor.TestRunner/AssemblyInfo.cs | 755 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MefCalculator.Editors.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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;
}
}
}
}
| 34.709677 | 151 | 0.584572 | [
"MIT"
] | evilC/NodeNetworkMefCalculator | MefCalculator.Editors/Properties/Settings.Designer.cs | 1,078 | C# |
using RemoteControlWithUndo.Commands;
using RemoteControlWithUndo.Receivers;
namespace RemoteControlWithUndo.Commands
{
public class CeilingFanMediumCommand : ICommand
{
private readonly CeilingFan _ceilingFan;
private int _prevSpeed;
public CeilingFanMediumCommand(CeilingFan ceilingFan)
{
_ceilingFan = ceilingFan;
}
public void Execute()
{
_prevSpeed = _ceilingFan.GetSpeed();
_ceilingFan.Medium();
}
public void Undo()
{
switch (_prevSpeed)
{
case CeilingFan.HIGH:
_ceilingFan.High();
break;
case CeilingFan.MEDIUM:
_ceilingFan.Medium();
break;
case CeilingFan.LOW:
_ceilingFan.Low();
break;
case CeilingFan.OFF:
_ceilingFan.Off();
break;
}
}
}
} | 26.609756 | 62 | 0.476627 | [
"MIT"
] | EugenieAmalfitano/design-patterns | src/command/RemoteControlWithUndo/Commands/CeilingFanMediumCommand.cs | 1,093 | C# |
using Net.Share;
using System;
using System.Reflection;
using Net.Server;
using System.Threading;
using Net.Event;
namespace Net.Adapter
{
public class RPCPTR
{
public object target;
public byte cmd;
public virtual void Invoke(object[] pars) {}
}
public class RPCPTRMethod : RPCPTR
{
public MethodInfo method;
public override void Invoke(object[] pars)
{
method.Invoke(target, pars);
}
}
public class RPCPTRNull : RPCPTR
{
public Action ptr;
public override void Invoke(object[] pars)
{
ptr();
}
}
public class RPCPTR<T> : RPCPTR
{
public Action<T> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0]);
}
}
public class RPCPTR<T, T1> : RPCPTR
{
public Action<T, T1> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1]);
}
}
public class RPCPTR<T, T1, T2> : RPCPTR
{
public Action<T, T1, T2> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2]);
}
}
public class RPCPTR<T, T1, T2, T3> : RPCPTR
{
public Action<T, T1, T2, T3> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3]);
}
}
public class RPCPTR<T, T1, T2, T3, T4> : RPCPTR
{
public Action<T, T1, T2, T3, T4> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5, T6> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5, T6> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5], (T6)pars[6]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5, T6, T7> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5, T6, T7> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5], (T6)pars[6], (T7)pars[7]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5, T6, T7, T8> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5, T6, T7, T8> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5], (T6)pars[6], (T7)pars[7], (T8)pars[8]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5, T6, T7, T8, T9> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5, T6, T7, T8, T9> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5], (T6)pars[6], (T7)pars[7], (T8)pars[8], (T9)pars[9]);
}
}
public class RPCPTR<T, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : RPCPTR
{
public Action<T, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ptr;
public override void Invoke(object[] pars)
{
ptr((T)pars[0], (T1)pars[1], (T2)pars[2], (T3)pars[3], (T4)pars[4], (T5)pars[5], (T6)pars[6], (T7)pars[7], (T8)pars[8], (T9)pars[9], (T10)pars[10]);
}
}
/// <summary>
/// 服务器远程过程调用适配器
/// </summary>
/// <typeparam name="Player"></typeparam>
public class CallSiteRpcAdapter<Player> : CallSiteRpcAdapter, IRPCAdapter<Player> where Player : NetPlayer
{
public void OnRpcExecute(Player client, RPCModel model)
{
if (model.methodMask != 0)
if (!RpcMask.TryGetValue(model.methodMask, out model.func)) model.func = $"[mask:{model.methodMask}]";
if (string.IsNullOrEmpty(model.func))
return;
if (RPCS.TryGetValue(model.func, out RPCPTR model1))
{
if (model1.cmd == NetCmd.SafeCall)
{
object[] pars = new object[model.pars.Length + 1];
pars[0] = client;
Array.Copy(model.pars, 0, pars, 1, model.pars.Length);
model1.Invoke(pars);
}
else model1.Invoke(model.pars);
}
}
}
/// <summary>
/// 客户端远程过程调用适配器
/// </summary>
public class CallSiteRpcAdapter : IRPCAdapter
{
internal SynchronizationContext Context;
internal MyDictionary<string, RPCPTR> RPCS = new MyDictionary<string, RPCPTR>();
internal MyDictionary<ushort, string> RpcMask = new MyDictionary<ushort, string>();
internal MyDictionary<string, RPCModelTask> rpcTasks = new MyDictionary<string, RPCModelTask>();
#if UNITY_EDITOR
private readonly bool useIL2CPP;
#endif
public CallSiteRpcAdapter()
{
Context = SynchronizationContext.Current;
#if UNITY_EDITOR
#pragma warning disable CS0618 // 类型或成员已过时
useIL2CPP = UnityEditor.PlayerSettings.GetPropertyInt("ScriptingBackend", UnityEditor.BuildTargetGroup.Standalone) == 1;
#pragma warning restore CS0618 // 类型或成员已过时
#endif
}
public void AddRpcHandle(object target, bool append)
{
Type type = target.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MethodInfo info in methods)
{
RPCFun rpc = info.GetCustomAttribute<RPCFun>();
if (rpc != null)
{
if (rpc.mask != 0)
{
if (!RpcMask.TryGetValue(rpc.mask, out string func))
RpcMask.Add(rpc.mask, info.Name);
else if (func != info.Name)
NDebug.LogError($"错误! 请修改Rpc方法{info.Name}或{func}的mask值, mask值必须是唯一的!");
}
if (info.ReturnType != typeof(void))
{
RPCPTRMethod met1 = new RPCPTRMethod
{
target = target,
method = info,
cmd = rpc.cmd
};
RPCS.Add(info.Name, met1);
continue;
}
var pars = info.GetParameters();
#if UNITY_EDITOR
if (rpc.il2cpp == null & useIL2CPP)
throw new Exception("如果在unity编译为il2cpp后端脚本,则需要先声明类型出来,因为编译后,类型被固定,将无法创建出来! 例子: void Test(int num, string str); 则需要这样添加 [Rpc(il2cpp = typeof(RPCPTR<int, string>))]");
if (useIL2CPP)
{
var pars1 = rpc.il2cpp.GetGenericArguments();
if (pars.Length != pars1.Length)
throw new Exception($"{type}类的:{info.Name}方法定义Rpc的参数长度不一致!");
for (int i = 0; i < pars.Length; i++)
if(pars[i].ParameterType != pars1[i])
throw new Exception($"{type}类的:{info.Name}方法定义Rpc的参数类型不一致!");
}
#endif
Type[] parTypes = new Type[pars.Length];
for (int i = 0; i < pars.Length; i++)
parTypes[i] = pars[i].ParameterType;
Type gt = null;
switch (parTypes.Length)
{
case 0:
gt = typeof(RPCPTRNull);
break;
case 1:
gt = typeof(RPCPTR<>).MakeGenericType(parTypes);
break;
case 2:
gt = typeof(RPCPTR<,>).MakeGenericType(parTypes);
break;
case 3:
gt = typeof(RPCPTR<,,>).MakeGenericType(parTypes);
break;
case 4:
gt = typeof(RPCPTR<,,,>).MakeGenericType(parTypes);
break;
case 5:
gt = typeof(RPCPTR<,,,,>).MakeGenericType(parTypes);
break;
case 6:
gt = typeof(RPCPTR<,,,,,>).MakeGenericType(parTypes);
break;
case 7:
gt = typeof(RPCPTR<,,,,,,>).MakeGenericType(parTypes);
break;
case 8:
gt = typeof(RPCPTR<,,,,,,,>).MakeGenericType(parTypes);
break;
case 9:
gt = typeof(RPCPTR<,,,,,,,,>).MakeGenericType(parTypes);
break;
case 10:
gt = typeof(RPCPTR<,,,,,,,,,>).MakeGenericType(parTypes);
break;
case 11:
gt = typeof(RPCPTR<,,,,,,,,,,>).MakeGenericType(parTypes);
break;
}
RPCPTR metPtr = (RPCPTR)Activator.CreateInstance(gt);
var ptr = metPtr.GetType().GetField("ptr", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
var met = Delegate.CreateDelegate(ptr.FieldType, target, info);
ptr.SetValue(metPtr, met);
metPtr.target = target;
metPtr.cmd = rpc.cmd;
RPCS.Add(info.Name, metPtr);
}
}
}
public void OnRpcExecute(RPCModel model)
{
if (model.methodMask != 0)
if (!RpcMask.TryGetValue(model.methodMask, out model.func)) model.func = $"[mask:{model.methodMask}]";
if (string.IsNullOrEmpty(model.func))
return;
if (rpcTasks.TryGetValue(model.func, out RPCModelTask model1))
{
model1.model = model;
model1.IsCompleted = true;
rpcTasks.Remove(model.func);
return;
}
if (RPCS.TryGetValue(model.func, out RPCPTR model2))
{
if (Context != null)
Context.Post((obj) => { model2.Invoke(model.pars); }, null);
else
model2.Invoke(model.pars);
}
}
public void RemoveRpc(object target)
{
if (target is string key)
{
if (RPCS.ContainsKey(key))
RPCS.Remove(key);
return;
}
var entries = RPCS.entries;
for (int i = 0; i < entries.Length; i++)
{
if (entries[i].hashCode == 0)
continue;
var rpc = entries[i].value;
if (rpc == null)
continue;
if (rpc.target == null | rpc.target == target)
{
RPCS.Remove(entries[i].key);
continue;
}
if (rpc.target.Equals(null) | rpc.target.Equals(target))
{
RPCS.Remove(entries[i].key);
}
}
}
public void CheckRpcUpdate()
{
var entries = RPCS.entries;
for (int i = 0; i < entries.Length; i++)
{
if (entries[i].hashCode == 0)
continue;
var rpc = entries[i].value;
if (rpc == null)
continue;
if (rpc.target == null)
{
RPCS.Remove(entries[i].key);
continue;
}
if (rpc.target.Equals(null))
{
RPCS.Remove(entries[i].key);
}
}
}
}
} | 37.610119 | 189 | 0.455567 | [
"MIT"
] | RedAWM/GDNet | GameDesigner/Network/Adapter/CallSiteRpcAdapter.cs | 12,909 | 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 medialive-2017-10-14.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.MediaLive.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaLive.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Input Object
/// </summary>
public class InputUnmarshaller : IUnmarshaller<Input, XmlUnmarshallerContext>, IUnmarshaller<Input, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
Input IUnmarshaller<Input, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Input Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
Input unmarshalledObject = new Input();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("arn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Arn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("attachedChannels", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.AttachedChannels = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("destinations", targetDepth))
{
var unmarshaller = new ListUnmarshaller<InputDestination, InputDestinationUnmarshaller>(InputDestinationUnmarshaller.Instance);
unmarshalledObject.Destinations = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("inputClass", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InputClass = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("inputDevices", targetDepth))
{
var unmarshaller = new ListUnmarshaller<InputDeviceSettings, InputDeviceSettingsUnmarshaller>(InputDeviceSettingsUnmarshaller.Instance);
unmarshalledObject.InputDevices = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("inputPartnerIds", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.InputPartnerIds = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("inputSourceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InputSourceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("mediaConnectFlows", targetDepth))
{
var unmarshaller = new ListUnmarshaller<MediaConnectFlow, MediaConnectFlowUnmarshaller>(MediaConnectFlowUnmarshaller.Instance);
unmarshalledObject.MediaConnectFlows = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("roleArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RoleArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("securityGroups", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.SecurityGroups = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("sources", targetDepth))
{
var unmarshaller = new ListUnmarshaller<InputSource, InputSourceUnmarshaller>(InputSourceUnmarshaller.Instance);
unmarshalledObject.Sources = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("state", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.State = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tags", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.Tags = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("type", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Type = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static InputUnmarshaller _instance = new InputUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InputUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 43.335165 | 180 | 0.583492 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/InputUnmarshaller.cs | 7,887 | 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.
namespace Microsoft.AspNetCore.Rewrite.IISUrlRewrite
{
internal enum LogicalGrouping
{
MatchAll,
MatchAny
}
}
| 25.583333 | 111 | 0.713355 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Middleware/Rewrite/src/IISUrlRewrite/LogicalGrouping.cs | 309 | C# |
namespace CoreWiki.Infrastructure.Mapping
{
using System;
using System.Linq;
using AutoMapper;
using Domain.Mapping;
public class MappingProfile : Profile
{
public MappingProfile()
{
var allTypes = AppDomain
.CurrentDomain
.GetAssemblies()
.Where(a => a.GetName().Name.Contains("CoreWiki"))
.SelectMany(a => a.GetTypes());
allTypes
.Where(t => t.IsClass && !t.IsAbstract && t
.GetInterfaces()
.Where(i => i.IsGenericType)
.Select(i => i.GetGenericTypeDefinition())
.Contains(typeof(IMapFrom<>)))
.Select(t => new
{
Destination = t,
Source = t
.GetInterfaces()
.Where(i => i.IsGenericType)
.Select(i => new
{
Definition = i.GetGenericTypeDefinition(),
Arguments = i.GetGenericArguments()
})
.Where(i => i.Definition == typeof(IMapFrom<>))
.SelectMany(i => i.Arguments)
.First(),
})
.ToList()
.ForEach(mapping => this.CreateMap(mapping.Source, mapping.Destination));
allTypes
.Where(t => t.IsClass
&& !t.IsAbstract
&& typeof(IHaveCustomMapping).IsAssignableFrom(t))
.Select(Activator.CreateInstance)
.Cast<IHaveCustomMapping>()
.ToList()
.ForEach(mapping => mapping.ConfigureMapping(this));
}
}
} | 36.5 | 89 | 0.420969 | [
"MIT"
] | stoyanov7/CoreWiki | src/CoreWiki.Infrastructure/Mapping/MappingProfile.cs | 1,900 | C# |
using BB.Common.WinForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace Appy.Core
{
public class AppyTheme : JaffasTheme
{
public override string Name
{
get
{
return "AppyTheme";
}
}
protected override void LoadProperties()
{
base.LoadProperties();
Color electricBlue = Color.FromArgb(255, 0, 148, 255);
Color lightGray = Color.FromArgb(255, 212, 212, 212);
Units["PanelBorderWidth"] = 0;
Colors["PanelBorder"] = Color.DarkGray;
Colors["FormBorder"] = Color.DarkGray;
Colors["FormBackground"] = Color.White;
Colors["ButtonMouseOverForeground"] = Color.White;
Colors["ButtonMouseOverBorder"] = electricBlue;
Colors["ButtonMouseOverBackground"] = electricBlue;
Colors["ButtonMouseDownBackground"] = electricBlue;
Colors["ButtonForeground"] = Color.DarkGray;
Units["ButtonBorderSize"] = 2;
Colors["ButtonBorder"] = Color.White;
Colors["ButtonBackground"] = Color.White;
Colors["ResizeButtonMouseOverForeground"] = electricBlue;
Colors["ResizeButtonMouseOverBorder"] = electricBlue;
Colors["ResizeButtonMouseOverBackground"] = electricBlue;
Colors["ResizeButtonMouseDownBackground"] = electricBlue;
Colors["ResizeButtonForeground"] = Color.DarkGray;
Units["ResizeButtonBorderSize"] = 2;
Colors["ResizeButtonBorder"] = lightGray;
Colors["ResizeButtonBackground"] = lightGray;
Colors["ToolTipBackground"] = Color.White;
Colors["ToolTipForeground"] = Color.Black;
Units["FormBorderWidth"] = 1;
}
}
}
| 35.735849 | 69 | 0.603485 | [
"Apache-2.0"
] | bberak/Appy | Appy.Core/App/AppyTheme.cs | 1,896 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.BssOpenApi.Model.V20171214
{
public class QueryBillResponse : AcsResponse
{
private string requestId;
private bool? success;
private string code;
private string message;
private QueryBill_Data data;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public QueryBill_Data Data
{
get
{
return data;
}
set
{
data = value;
}
}
public class QueryBill_Data
{
private string billingCycle;
private string accountID;
private string accountName;
private int? pageNum;
private int? pageSize;
private int? totalCount;
private List<QueryBill_Item> items;
public string BillingCycle
{
get
{
return billingCycle;
}
set
{
billingCycle = value;
}
}
public string AccountID
{
get
{
return accountID;
}
set
{
accountID = value;
}
}
public string AccountName
{
get
{
return accountName;
}
set
{
accountName = value;
}
}
public int? PageNum
{
get
{
return pageNum;
}
set
{
pageNum = value;
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
}
}
public int? TotalCount
{
get
{
return totalCount;
}
set
{
totalCount = value;
}
}
public List<QueryBill_Item> Items
{
get
{
return items;
}
set
{
items = value;
}
}
public class QueryBill_Item
{
private string recordID;
private string item;
private string ownerID;
private string usageStartTime;
private string usageEndTime;
private string paymentTime;
private string productCode;
private string productType;
private string subscriptionType;
private string productName;
private string productDetail;
private float? pretaxGrossAmount;
private float? deductedByCoupons;
private float? invoiceDiscount;
private float? pretaxAmount;
private string currency;
private float? pretaxAmountLocal;
private float? tax;
private float? paymentAmount;
private float? deductedByCashCoupons;
private float? deductedByPrepaidCard;
private float? outstandingAmount;
private float? afterTaxAmount;
private string status;
private string paymentCurrency;
private string paymentTransactionID;
public string RecordID
{
get
{
return recordID;
}
set
{
recordID = value;
}
}
public string Item
{
get
{
return item;
}
set
{
item = value;
}
}
public string OwnerID
{
get
{
return ownerID;
}
set
{
ownerID = value;
}
}
public string UsageStartTime
{
get
{
return usageStartTime;
}
set
{
usageStartTime = value;
}
}
public string UsageEndTime
{
get
{
return usageEndTime;
}
set
{
usageEndTime = value;
}
}
public string PaymentTime
{
get
{
return paymentTime;
}
set
{
paymentTime = value;
}
}
public string ProductCode
{
get
{
return productCode;
}
set
{
productCode = value;
}
}
public string ProductType
{
get
{
return productType;
}
set
{
productType = value;
}
}
public string SubscriptionType
{
get
{
return subscriptionType;
}
set
{
subscriptionType = value;
}
}
public string ProductName
{
get
{
return productName;
}
set
{
productName = value;
}
}
public string ProductDetail
{
get
{
return productDetail;
}
set
{
productDetail = value;
}
}
public float? PretaxGrossAmount
{
get
{
return pretaxGrossAmount;
}
set
{
pretaxGrossAmount = value;
}
}
public float? DeductedByCoupons
{
get
{
return deductedByCoupons;
}
set
{
deductedByCoupons = value;
}
}
public float? InvoiceDiscount
{
get
{
return invoiceDiscount;
}
set
{
invoiceDiscount = value;
}
}
public float? PretaxAmount
{
get
{
return pretaxAmount;
}
set
{
pretaxAmount = value;
}
}
public string Currency
{
get
{
return currency;
}
set
{
currency = value;
}
}
public float? PretaxAmountLocal
{
get
{
return pretaxAmountLocal;
}
set
{
pretaxAmountLocal = value;
}
}
public float? Tax
{
get
{
return tax;
}
set
{
tax = value;
}
}
public float? PaymentAmount
{
get
{
return paymentAmount;
}
set
{
paymentAmount = value;
}
}
public float? DeductedByCashCoupons
{
get
{
return deductedByCashCoupons;
}
set
{
deductedByCashCoupons = value;
}
}
public float? DeductedByPrepaidCard
{
get
{
return deductedByPrepaidCard;
}
set
{
deductedByPrepaidCard = value;
}
}
public float? OutstandingAmount
{
get
{
return outstandingAmount;
}
set
{
outstandingAmount = value;
}
}
public float? AfterTaxAmount
{
get
{
return afterTaxAmount;
}
set
{
afterTaxAmount = value;
}
}
public string Status
{
get
{
return status;
}
set
{
status = value;
}
}
public string PaymentCurrency
{
get
{
return paymentCurrency;
}
set
{
paymentCurrency = value;
}
}
public string PaymentTransactionID
{
get
{
return paymentTransactionID;
}
set
{
paymentTransactionID = value;
}
}
}
}
}
}
| 14.362039 | 64 | 0.499878 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-bssopenapi/BssOpenApi/Model/V20171214/QueryBillResponse.cs | 8,172 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using UnityEngine;
public class ElectronController : MonoBehaviour
{
public float speed = 0f;
private const float electronCharge = -1.602f * (float)1e-19;
private const float electronMass = 9.109f * (float)1e-31;
private Stopwatch stopwatch = new Stopwatch();
// Start is called before the first frame update
void Start()
{
speed = 0f;
}
public void AddConstantSpeed(float speed)
{
this.speed += speed;
}
void OnBecameInvisible()
{
speed = 0f;
stopwatch.Reset();
transform.position = new Vector3(-9f, 2f, 0f);
}
// Update is called once per frame
void Update()
{
var lines = FindObjectOfType<PowerLinesAnimationController>();
if (transform.position.x >= 0f)
{
stopwatch.Start();
}
else if (transform.position.x > 13f)
{
stopwatch.Stop();
}
var capacitorController = FindObjectOfType<CapacitorController>();
var horizontalSpeed = speed * Time.deltaTime / (float)1e14;
transform.position = new Vector3(transform.position.x + horizontalSpeed, transform.position.y);
if (lines.enabled)
{
var tension = capacitorController.voltage / capacitorController.distanceBetweenPlates;
var acceleration = electronCharge * tension / electronMass;
float verticalSpeed = 0f;
if (speed >= Mathf.Epsilon)
verticalSpeed = acceleration * ((float)stopwatch.ElapsedMilliseconds / 1000) / speed;
transform.position =
new Vector3(transform.position.x, transform.position.y - verticalSpeed * Time.deltaTime);
}
}
}
| 25.861111 | 105 | 0.62406 | [
"MIT"
] | riiji/PhysicsModel2 | Scripts/ElectronController.cs | 1,864 | C# |
// Copyright (c) 2018 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT licence. See License.txt in the project root for license information.
using GenericServices;
using Tests.EfClasses;
namespace Tests.Dtos
{
public abstract class IdPropAbstract
{
public int Id { get; private set; }
}
public class NormalEntityKeyAbstractDto : IdPropAbstract, ILinkToEntity<NormalEntity>
{
public int MyInt { get; set; }
public string MyString { get; set; }
}
} | 28.736842 | 97 | 0.697802 | [
"MIT"
] | abuzaforfagun/EfCore.GenericServices | Tests/Dtos/NormalEntityKeyAbstractDto.cs | 548 | C# |
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc5;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
namespace SWNI.Web
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
/*asp.net Identity*/
container.RegisterType(typeof(UserManager<>), new InjectionConstructor(typeof(IUserStore<>)));
container.RegisterType(typeof(IUserStore<>), typeof(UserStore<>));
container.RegisterType<Microsoft.AspNet.Identity.IUser>(new InjectionFactory(c => c.Resolve<Microsoft.AspNet.Identity.IUser>()));
container.RegisterType<IdentityUser, ApplicationUser>(new ContainerControlledLifetimeManager());
container.RegisterType<DbContext, ApplicationDbContext>(new ContainerControlledLifetimeManager());
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<ManageController>(new InjectionConstructor());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
} | 46 | 141 | 0.705882 | [
"MIT"
] | mrememisaac/DonationPortal | SWNI.Web/App_Start/UnityConfig.cs | 1,564 | C# |
using MCS.Core;
using MCS.Core.Helper;
using MCS.Core.Plugins.Message;
using MCS.Plugin.MessagePlugin;
using System;
using System.IO;
using System.Xml.Serialization;
namespace MCS.Plugin.Message.SMS
{
class SMSCore
{
/// <summary>
/// 工作目录
/// </summary>
public static string WorkDirectory { get; set; }
/// <summary>
/// 获取配置
/// </summary>
/// <returns></returns>
public static MessageSMSConfig GetConfig()
{
MessageSMSConfig config = new MessageSMSConfig();
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/SMS.config";
if (MCSIO.ExistFile(sDirectory))
{
XmlSerializer xs = new XmlSerializer(typeof(MessageSMSConfig));
byte[] b = MCSIO.GetFileContent(sDirectory);
string str = System.Text.Encoding.Default.GetString(b);
MemoryStream fs = new MemoryStream(b);
config = (MessageSMSConfig)xs.Deserialize(fs);
}
return config;
}
/// <summary>
/// 获取信息内容
/// </summary>
/// <returns></returns>
public static MessageContent GetMessageContentConfig()
{
MessageContent config = Core.Cache.Get<MessageContent>("SMSMessageContent");
if (config == null)
{
//using (FileStream fs = new FileStream(WorkDirectory + "\\Data\\MessageContent.xml", FileMode.Open))
//{
// XmlSerializer xs = new XmlSerializer(typeof(MessageContent));
// config = (MessageContent)xs.Deserialize(fs);
// Core.Cache.Insert("MessageContent", config);
//}
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/MessageContent.xml";
if (MCSIO.ExistFile(sDirectory))
{
XmlSerializer xs = new XmlSerializer(typeof(MessageContent));
byte[] b = MCSIO.GetFileContent(sDirectory);
string str = System.Text.Encoding.Default.GetString(b);
MemoryStream fs = new MemoryStream(b);
config = (MessageContent)xs.Deserialize(fs);
Core.Cache.Insert("SMSMessageContent", config);
}
}
return config;
}
/// <summary>
/// 获取发送状态
/// </summary>
/// <returns></returns>
public static MessageStatus GetMessageStatus()
{
MessageStatus config = new MessageStatus();
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/config.xml";
if (MCSIO.ExistFile(sDirectory))
{
XmlSerializer xs = new XmlSerializer(typeof(MessageStatus));
byte[] b = MCSIO.GetFileContent(sDirectory);
MemoryStream fs = new MemoryStream(b);
config = (MessageStatus)xs.Deserialize(fs);
}
return config;
}
/// <summary>
/// 保存配置
/// </summary>
/// <param name="config"></param>
public static void SaveConfig(MessageSMSConfig config)
{
//using (FileStream fs = new FileStream(WorkDirectory + "\\Data\\SMS.config", FileMode.Create))
//{
// XmlSerializer xs = new XmlSerializer(typeof(MessageSMSConfig));
// xs.Serialize(fs, config);
//}
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/SMS.config";
XmlSerializer xml = new XmlSerializer(typeof(MessageSMSConfig));
MemoryStream Stream = new MemoryStream();
xml.Serialize(Stream, config);
byte[] b = Stream.ToArray();
MemoryStream stream2 = new MemoryStream(b);
MCSIO.CreateFile(sDirectory, stream2, Core.FileCreateType.Create);
}
/// <summary>
/// 保存短信内容配置
/// </summary>
/// <param name="config"></param>
public static void SaveMessageContentConfig(MessageContent config)
{
//using (FileStream fs = new FileStream(WorkDirectory + "\\Data\\MessageContent.xml", FileMode.Create))
//{
// XmlSerializer xs = new XmlSerializer(typeof(MessageContent));
// xs.Serialize(fs, config);
// Core.Cache.Insert("MessageContent", config);
//}
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/MessageContent.xml";
XmlSerializer xml = new XmlSerializer(typeof(MessageContent));
MemoryStream Stream = new MemoryStream();
xml.Serialize(Stream, config);
byte[] b = Stream.ToArray();
MemoryStream stream2 = new MemoryStream(b);
MCSIO.CreateFile(sDirectory, stream2, Core.FileCreateType.Create);
}
/// <summary>
/// 保持消息发送状态
/// </summary>
/// <param name="config"></param>
public static void SaveMessageStatus(MessageStatus config)
{
string sDirectory = IOHelper.UrlToVirtual(WorkDirectory) + "/Data/config.xml";
XmlSerializer xml = new XmlSerializer(typeof(MessageStatus));
MemoryStream Stream = new MemoryStream();
xml.Serialize(Stream, config);
byte[] b = Stream.ToArray();
MemoryStream stream2 = new MemoryStream(b);
MCSIO.CreateFile(sDirectory, stream2, Core.FileCreateType.Create);
}
}
}
| 36.616883 | 117 | 0.5579 | [
"MIT"
] | MiZoneRom/MiZoneCommerce | src/MCS.Plugin.Message.SMS/Helper/SMSCore.cs | 5,721 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using HC.WeChat.Activities.Dtos;
using System;
namespace HC.WeChat.Activities
{
/// <summary>
/// Activity应用层服务的接口方法
/// </summary>
public interface IActivityAppService : IApplicationService
{
/// <summary>
/// 获取Activity的分页列表信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<PagedResultDto<ActivityListDto>> GetPagedActivitys(GetActivitysInput input);
/// <summary>
/// 通过指定id获取ActivityListDto信息
/// </summary>
Task<ActivityListDto> GetActivityByIdAsync(EntityDto<Guid> input);
/// <summary>
/// 导出Activity为excel表
/// </summary>
/// <returns></returns>
//Task<FileDto> GetActivitysToExcel();
/// <summary>
/// MPA版本才会用到的方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<GetActivityForEditOutput> GetActivityForEdit(NullableIdDto<Guid> input);
//todo:缺少Dto的生成GetActivityForEditOutput
/// <summary>
/// 添加或者修改Activity的公共方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task CreateOrUpdateActivity(CreateOrUpdateActivityInput input);
/// <summary>
/// 删除Activity信息的方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task DeleteActivity(EntityDto<Guid> input);
/// <summary>
/// 批量删除Activity
/// </summary>
Task BatchDeleteActivitysAsync(List<Guid> input);
//// custom codes
//// custom codes end
}
}
| 24.873239 | 89 | 0.592299 | [
"MIT"
] | DonaldTdz/syq | aspnet-core/src/HC.WeChat.Application/Activities/IActivityAppService.cs | 1,900 | 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 Microsoft.Data.DataView;
using Microsoft.ML;
using Microsoft.ML.CommandLine;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Data;
using Microsoft.ML.Data.Conversion;
using Microsoft.ML.EntryPoints;
using Microsoft.ML.Internal.Internallearn;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Learners;
using Microsoft.ML.Trainers;
using Microsoft.ML.Training;
[assembly: LoadableClass(SdcaRegressionTrainer.Summary, typeof(SdcaRegressionTrainer), typeof(SdcaRegressionTrainer.Options),
new[] { typeof(SignatureRegressorTrainer), typeof(SignatureTrainer), typeof(SignatureFeatureScorerTrainer) },
SdcaRegressionTrainer.UserNameValue,
SdcaRegressionTrainer.LoadNameValue,
SdcaRegressionTrainer.ShortName)]
namespace Microsoft.ML.Trainers
{
/// <include file='doc.xml' path='doc/members/member[@name="SDCA"]/*' />
public sealed class SdcaRegressionTrainer : SdcaTrainerBase<SdcaRegressionTrainer.Options, RegressionPredictionTransformer<LinearRegressionModelParameters>, LinearRegressionModelParameters>
{
internal const string LoadNameValue = "SDCAR";
internal const string UserNameValue = "Fast Linear Regression (SA-SDCA)";
internal const string ShortName = "sasdcar";
internal const string Summary = "The SDCA linear regression trainer.";
public sealed class Options : ArgumentsBase
{
[Argument(ArgumentType.Multiple, HelpText = "Loss Function", ShortName = "loss", SortOrder = 50)]
public ISupportSdcaRegressionLossFactory LossFunction = new SquaredLossFactory();
public Options()
{
// Using a higher default tolerance for better RMS.
ConvergenceTolerance = 0.01f;
// Default to use unregularized bias in regression.
BiasLearningRate = 1;
}
}
private readonly ISupportSdcaRegressionLoss _loss;
public override PredictionKind PredictionKind => PredictionKind.Regression;
/// <summary>
/// Initializes a new instance of <see cref="SdcaRegressionTrainer"/>
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="labelColumn">The label, or dependent variable.</param>
/// <param name="featureColumn">The features, or independent variables.</param>
/// <param name="weights">The optional example weights.</param>
/// <param name="loss">The custom loss.</param>
/// <param name="l2Const">The L2 regularization hyperparameter.</param>
/// <param name="l1Threshold">The L1 regularization hyperparameter. Higher values will tend to lead to more sparse model.</param>
/// <param name="maxIterations">The maximum number of passes to perform over the data.</param>
internal SdcaRegressionTrainer(IHostEnvironment env,
string labelColumn = DefaultColumnNames.Label,
string featureColumn = DefaultColumnNames.Features,
string weights = null,
ISupportSdcaRegressionLoss loss = null,
float? l2Const = null,
float? l1Threshold = null,
int? maxIterations = null)
: base(env, featureColumn, TrainerUtils.MakeR4ScalarColumn(labelColumn), TrainerUtils.MakeR4ScalarWeightColumn(weights),
l2Const, l1Threshold, maxIterations)
{
Host.CheckNonEmpty(featureColumn, nameof(featureColumn));
Host.CheckNonEmpty(labelColumn, nameof(labelColumn));
_loss = loss ?? Args.LossFunction.CreateComponent(env);
Loss = _loss;
}
internal SdcaRegressionTrainer(IHostEnvironment env, Options options, string featureColumn, string labelColumn, string weightColumn = null)
: base(env, options, TrainerUtils.MakeR4ScalarColumn(labelColumn), TrainerUtils.MakeR4ScalarWeightColumn(weightColumn))
{
Host.CheckValue(labelColumn, nameof(labelColumn));
Host.CheckValue(featureColumn, nameof(featureColumn));
_loss = options.LossFunction.CreateComponent(env);
Loss = _loss;
}
internal SdcaRegressionTrainer(IHostEnvironment env, Options options)
: this(env, options, options.FeatureColumn, options.LabelColumn)
{
}
protected override LinearRegressionModelParameters CreatePredictor(VBuffer<float>[] weights, float[] bias)
{
Host.CheckParam(Utils.Size(weights) == 1, nameof(weights));
Host.CheckParam(Utils.Size(bias) == 1, nameof(bias));
Host.CheckParam(weights[0].Length > 0, nameof(weights));
VBuffer<float> maybeSparseWeights = default;
// below should be `in weights[0]`, but can't because of https://github.com/dotnet/roslyn/issues/29371
VBufferUtils.CreateMaybeSparseCopy(weights[0], ref maybeSparseWeights,
Conversions.Instance.GetIsDefaultPredicate<float>(NumberType.Float));
return new LinearRegressionModelParameters(Host, in maybeSparseWeights, bias[0]);
}
private protected override float GetInstanceWeight(FloatLabelCursor cursor)
{
return cursor.Weight;
}
private protected override void CheckLabel(RoleMappedData examples, out int weightSetCount)
{
examples.CheckRegressionLabel();
weightSetCount = 1;
}
// REVIEW: No extra benefits from using more threads in training.
private protected override int ComputeNumThreads(FloatLabelCursor.Factory cursorFactory)
{
int maxThreads;
if (Host.ConcurrencyFactor < 1)
maxThreads = Math.Min(2, Math.Max(1, Environment.ProcessorCount / 2));
else
maxThreads = Host.ConcurrencyFactor;
return maxThreads;
}
// Using a different logic for default L2 parameter in regression.
protected override float TuneDefaultL2(IChannel ch, int maxIterations, long rowCount, int numThreads)
{
Contracts.AssertValue(ch);
Contracts.Assert(maxIterations > 0);
Contracts.Assert(rowCount > 0);
Contracts.Assert(numThreads > 0);
float l2;
if (rowCount > 10000)
l2 = 1e-04f;
else if (rowCount < 200)
l2 = 1e-02f;
else
l2 = 1e-03f;
ch.Info("Auto-tuning parameters: L2 = {0}.", l2);
return l2;
}
protected override SchemaShape.Column[] GetOutputColumnsCore(SchemaShape inputSchema)
{
return new[]
{
new SchemaShape.Column(DefaultColumnNames.Score, SchemaShape.Column.VectorKind.Scalar, NumberType.R4, false, new SchemaShape(MetadataUtils.GetTrainerOutputMetadata()))
};
}
protected override RegressionPredictionTransformer<LinearRegressionModelParameters> MakeTransformer(LinearRegressionModelParameters model, Schema trainSchema)
=> new RegressionPredictionTransformer<LinearRegressionModelParameters>(Host, model, trainSchema, FeatureColumn.Name);
}
/// <summary>
///The Entry Point for the SDCA regressor.
/// </summary>
internal static partial class Sdca
{
[TlcModule.EntryPoint(Name = "Trainers.StochasticDualCoordinateAscentRegressor",
Desc = SdcaRegressionTrainer.Summary,
UserName = SdcaRegressionTrainer.UserNameValue,
ShortName = SdcaRegressionTrainer.ShortName)]
public static CommonOutputs.RegressionOutput TrainRegression(IHostEnvironment env, SdcaRegressionTrainer.Options input)
{
Contracts.CheckValue(env, nameof(env));
var host = env.Register("TrainSDCA");
host.CheckValue(input, nameof(input));
EntryPointUtils.CheckInputArgs(host, input);
return LearnerEntryPointsUtils.Train<SdcaRegressionTrainer.Options, CommonOutputs.RegressionOutput>(host, input,
() => new SdcaRegressionTrainer(host, input),
() => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.LabelColumn));
}
}
} | 45.491979 | 193 | 0.667215 | [
"MIT"
] | HerraHak/machinelearning | src/Microsoft.ML.StandardLearners/Standard/SdcaRegression.cs | 8,507 | 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("volleyball")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("volleyball")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[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("e911b594-2724-4487-b0a0-d8a7cc8a1266")]
// 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.135135 | 84 | 0.747697 | [
"MIT"
] | dhtveso/SoftUni | Programming Basics/ComplexConditionalStatements/Volleyball/Properties/AssemblyInfo.cs | 1,414 | C# |
using PrAnalyzer.Contracts.Enum;
using System.Collections.Generic;
namespace PrAnalyzer.Contracts.Interface
{
public interface IHandlerResult
{
IEnumerable<string> Messages { get; }
HandlerCallStatus Status { get; }
}
}
| 20.833333 | 45 | 0.708 | [
"MIT"
] | AMatijevic/PrAnalyzer | src/PrAnalyzer.Contracts/Interface/IHandlerResult.cs | 252 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarTracker.Common.Entities;
using CarTracker.Common.Services;
using CarTracker.Common.ViewModels;
using CarTracker.Data;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
namespace CarTracker.Logic.Services
{
public class ReadingService : IReadingService
{
private readonly CarTrackerDbContext _db;
public ReadingService(CarTrackerDbContext db)
{
this._db = db;
}
public Reading Get(long id)
{
return _db.Readings.FirstOrDefault(r => r.ReadingId == id);
}
public IEnumerable<Reading> GetForTrip(long tripId)
{
return _db.Readings.Where(r => r.TripId == tripId).OrderBy(r => r.ReadDate);
}
public Reading Create(ReadingViewModel toCreate, bool save = true)
{
var reading = new Reading()
{
TripId = toCreate.TripId,
AirIntakeTemperature = toCreate.AirIntakeTemperature,
AmbientAirTemperature = toCreate.AmbientAirTemperature,
EngineCoolantTemperature = toCreate.EngineCoolantTemperature,
EngineRpm = toCreate.EngineRpm,
FuelLevel = toCreate.FuelLevel,
FuelType = toCreate.FuelType,
Latitude = toCreate.Latitude,
Longitude = toCreate.Longitude,
MassAirFlow = toCreate.MassAirFlow,
OilTemperature = toCreate.OilTemperature,
ReadDate = toCreate.ReadDate,
Speed = toCreate.Speed,
ThrottlePosition = toCreate.ThrottlePosition
};
_db.Readings.Add(reading);
if (save)
{
_db.SaveChanges();
}
return reading;
}
public IEnumerable<BulkUploadResultViewModel> BulkUpload(long tripId,
IEnumerable<BulkUploadViewModel<ReadingViewModel>> readings)
{
var results = new List<BulkUploadResultViewModel>();
foreach (var reading in readings)
{
var result = new BulkUploadResultViewModel()
{
Uuid = reading.Uuid
};
try
{
var res = Create(reading.Data);
result.Id = res.ReadingId;
result.Successful = true;
}
catch (Exception e)
{
result.Successful = false;
result.ErrorMessage = e.Message;
}
results.Add(result);
}
return results;
}
}
}
| 31.483146 | 88 | 0.547823 | [
"MIT"
] | mwcaisse/car-tracker-server | CarTracker/CarTracker.Logic/Services/ReadingService.cs | 2,804 | C# |
using Microsoft.EntityFrameworkCore;
using NoteList.Domain.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NoteList.Service.Impl
{
public class NoteItemRepository : Repository<NoteItem>, INoteItemRepository
{
public NoteItemRepository(DataContext context, IDateTimeService dateTimeService)
: base(context, dateTimeService)
{ }
public async Task<List<Tag>> GetTags(int id)
{
var noteItems = this.context.Set<NoteItem>().Include(x => x.Tags);
var note = await noteItems.SingleAsync(x => x.Id == id);
return note.Tags;
}
}
}
| 29.954545 | 88 | 0.664643 | [
"MIT"
] | evgenynazarchuk/NoteListSamples | NoteList.Service.Impl/NoteItemRepository.cs | 661 | C# |
using System;
using System.Linq;
using Bing.Reflection;
using Bing.Text;
namespace Bing.Helpers
{
/// <summary>
/// 映射器帮助类
/// </summary>
public static class MapperHelper
{
/// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <typeparam name="TDestination">目标类型</typeparam>
/// <param name="source">源对象</param>
/// <exception cref="ArgumentNullException"></exception>
public static TDestination Map<TSource, TDestination>(TSource source) where TDestination : new()
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var destinationProperties = TypeReflections.TypeCacheManager.GetTypeProperties(destinationType);
var sourceProperties = TypeReflections.TypeCacheManager.GetTypeProperties(sourceType)
.Where(x => destinationProperties.Any(_ => _.Name.EqualsIgnoreCase(x.Name)))
.ToArray();
var result = new TDestination();
if (destinationProperties.Length > 0)
{
foreach (var destinationProperty in destinationProperties)
{
var sourceProperty = sourceProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase(destinationProperty.Name));
if (sourceProperty == null)
continue;
var propGetter = sourceProperty.GetValueGetter();
if (propGetter != null)
destinationProperty.GetValueSetter()?.Invoke(result, propGetter.Invoke(source));
}
}
return result;
}
/// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <typeparam name="TDestination">目标类型</typeparam>
/// <param name="source">源对象</param>
/// <param name="propertiesToMap">属性映射数组,可指定映射部分属性</param>
/// <exception cref="ArgumentNullException"></exception>
public static TDestination MapWith<TSource, TDestination>(TSource source, params string[] propertiesToMap) where TDestination : new()
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var destinationProperties = TypeReflections.TypeCacheManager.GetTypeProperties(destinationType)
.Where(x => propertiesToMap.Any(_ => string.Equals(_, x.Name, StringComparison.OrdinalIgnoreCase)))
.ToArray();
var sourceProperties = TypeReflections.TypeCacheManager.GetTypeProperties(sourceType)
.Where(x => propertiesToMap.Any(_ => _.EqualsIgnoreCase(x.Name)))
.ToArray();
var result = new TDestination();
if (destinationProperties.Length > 0)
{
foreach (var destinationProperty in destinationProperties)
{
var sourceProperty = sourceProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase(destinationProperty.Name));
if (sourceProperty == null || !sourceProperty.CanRead || !destinationProperty.CanWrite)
continue;
var propGetter = sourceProperty.GetValueGetter();
if (propGetter != null)
destinationProperty.GetValueSetter()?.Invoke(result, propGetter.Invoke(source));
}
}
return result;
}
/// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <typeparam name="TDestination">目标类型</typeparam>
/// <param name="source">源对象</param>
/// <param name="propertiesNoMap">忽略属性映射数组,忽略指定映射部分属性</param>
/// <exception cref="ArgumentNullException"></exception>
public static TDestination MapWithout<TSource, TDestination>(TSource source, params string[] propertiesNoMap) where TDestination : new()
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var destinationProperties = TypeReflections.TypeCacheManager.GetTypeProperties(destinationType)
.Where(x => !propertiesNoMap.Any(_ => string.Equals(_, x.Name, StringComparison.OrdinalIgnoreCase)))
.ToArray();
var sourceProperties = TypeReflections.TypeCacheManager.GetTypeProperties(sourceType)
.Where(x => !destinationProperties.Any(_ => _.Name.EqualsIgnoreCase(x.Name)))
.ToArray();
var result = new TDestination();
if (destinationProperties.Length > 0)
{
foreach (var destinationProperty in destinationProperties)
{
var sourceProperty = sourceProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase(destinationProperty.Name));
if (sourceProperty == null || !sourceProperty.CanRead || !destinationProperty.CanWrite)
continue;
var propGetter = sourceProperty.GetValueGetter();
if (propGetter != null)
destinationProperty.GetValueSetter()?.Invoke(result, propGetter.Invoke(source));
}
}
return result;
}
}
}
| 42.850746 | 144 | 0.587948 | [
"MIT"
] | bing-framework/Bing.Utils | src/Bing.Utils/Bing/Helpers/MapperHelper.cs | 5,952 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace BuildXL.Engine.Cache.Fingerprints
{
/// <nodoc />
public partial class PipGraphInputDescriptor : IPipFingerprintEntryData
{
/// <inheritdoc />
public PipFingerprintEntryKind Kind => PipFingerprintEntryKind.GraphInputDescriptor;
/// <inheritdoc />
public IEnumerable<BondContentHash> ListRelatedContent()
{
yield break;
}
/// <inheritdoc />
public PipFingerprintEntry ToEntry()
{
return PipFingerprintEntry.CreateFromData(this);
}
}
}
| 28.851852 | 102 | 0.636714 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/Engine/Cache/Fingerprints/PipGraphInputDescriptor.cs | 779 | C# |
using UnityEditor;
namespace SuperSystems.UnityBuild
{
[System.Serializable]
public class BuildAndroid : BuildPlatform
{
#region Constants
private const string _name = "Android";
private const string _binaryNameFormat = "{0}.apk";
private const string _dataDirNameFormat = "{0}_Data";
private const BuildTargetGroup _targetGroup = BuildTargetGroup.Android;
#endregion
public BuildAndroid()
{
enabled = false;
Init();
}
public override void Init()
{
platformName = _name;
binaryNameFormat = _binaryNameFormat;
dataDirNameFormat = _dataDirNameFormat;
targetGroup = _targetGroup;
if (architectures == null || architectures.Length == 0)
{
architectures = new BuildArchitecture[] {
new BuildArchitecture(BuildTarget.Android, "Android", true)
};
}
if (variants == null || variants.Length == 0)
{
variants = new BuildVariant[] {
new BuildVariant("Device Type", new string[] { "FAT", "ARMv7", "x86" }, 0),
new BuildVariant("Texture Compression", new string[] { "ETC", "ETC2", "ASTC", "DXT", "PVRTC", "ATC", "Generic" }, 0),
new BuildVariant("Build System", new string[] { "Internal", "Gradle", "ADT (Legacy)" }, 0)
};
}
}
public override void ApplyVariant()
{
foreach (var variantOption in variants)
{
switch (variantOption.variantName)
{
case "DeviceType":
SetDeviceType(variantOption.variantKey);
break;
case "Texture Compression":
SetTextureCompression(variantOption.variantKey);
break;
case "Build System":
SetBuildSystem(variantOption.variantKey);
break;
}
}
}
private void SetDeviceType(string key)
{
#if UNITY_2018_1_OR_NEWER
PlayerSettings.Android.targetArchitectures = (AndroidArchitecture)System.Enum.Parse(typeof(AndroidArchitecture), key);
#else
PlayerSettings.Android.targetDevice = (AndroidTargetDevice)System.Enum.Parse(typeof(AndroidTargetDevice), key);
#endif
}
private void SetTextureCompression(string key)
{
EditorUserBuildSettings.androidBuildSubtarget
= (MobileTextureSubtarget)System.Enum.Parse(typeof(MobileTextureSubtarget), key);
}
private void SetBuildSystem(string key)
{
EditorUserBuildSettings.androidBuildSystem
= (AndroidBuildSystem)System.Enum.Parse(typeof(AndroidBuildSystem), key);
}
}
} | 31.840909 | 134 | 0.584939 | [
"MIT"
] | TrutzX/9Nations | Assets/Plugins/UnityBuild/Editor/Build/Platform/BuildAndroid.cs | 2,804 | C# |
using System;
using Xunit;
using BrewCrewLib;
using BrewCrewDB.Models;
using BrewCrewDB;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace BrewCrewTest
{
public class DBTest
{
DBRepo repo;
private readonly Customer TestCustomer = new Customer()
{
ID = "1",
FName = "Michael",
LName = "Scott",
Email = "customer1@email.net",
Password = "qqqqqq"
};
private readonly Manager TestManager = new Manager()
{
ID = "1",
FName = "John",
LName = "Deer",
Email = "manager1@email.net",
Password = "qqqqqq",
BreweryID = "1"
};
private readonly Brewery TestBrewery = new Brewery()
{
ID = "1",
Name = "Lewis and Clark Brewery",
State = "MT",
City = "Helena",
Address = "123 Beer Ave",
Zip = "12345"
};
private readonly Beer TestBeer = new Beer()
{
ID = "1",
BreweryID = "1",
Name = "White Stout",
Type = "Stout",
ABV = "9.5",
IBU = "44",
Keg = "100"
};
private readonly Order TestOrder = new Order()
{
ID = "1",
CustomerID = "1",
BeerId = "1",
Date = DateTime.Now.ToString(),
TableNumber = "1",
BreweryId = "1",
LineItemId = "1"
};
private readonly List<Manager> TestManagers = new List<Manager>()
{
new Manager()
{
ID = "1",
FName = "John",
LName = "Deer",
Email = "manager1@email.net",
Password = "qqqqqq",
BreweryID = "1"
},
new Manager()
{
ID = "2",
FName = "Dwight",
LName = "Schrute",
Email = "manager2@email.net",
Password = "qqqqqq",
BreweryID = "2"
}
};
private readonly List<Brewery> TestBreweries = new List<Brewery>()
{
new Brewery()
{
ID = "1",
Name = "Lewis and Clark Brewery",
State = "MT",
City = "Helena",
Address = "123 Beer Ave",
Zip = "12345"
},
new Brewery()
{
ID = "2",
Name = "Missouri River Brewing Co",
State = "MT",
City = "East Helena",
Address = "123 Stout Ave",
Zip = "12345"
}
};
private readonly List<Beer> TestBeers = new List<Beer>()
{
new Beer()
{
ID = "2",
BreweryID = "1",
Name = "Vanilla Creamsickle",
Type = "Ale",
ABV = "9.5",
IBU = "44",
Keg = "100"
},
new Beer()
{
ID = "3",
BreweryID = "1",
Name = "Miners Gold",
Type = "Stout",
ABV = "9.5",
IBU = "44",
Keg = "100"
}
};
private readonly List<Order> TestOrders = new List<Order>()
{
new Order()
{
ID = "2",
CustomerID = "1",
BeerId = "1",
Date = DateTime.Now.ToString(),
TableNumber = "1",
BreweryId = "1",
LineItemId = "1"
},
new Order()
{
ID = "3",
CustomerID = "1",
BeerId = "1",
Date = DateTime.Now.ToString(),
TableNumber = "1",
BreweryId = "1",
LineItemId = "1"
}
};
private void Seed(BrewCrewContext testContext)
{
testContext.Managers.AddRange(TestManagers);
testContext.Breweries.AddRange(TestBreweries);
testContext.Beers.AddRange(TestBeers);
testContext.Orders.AddRange(TestOrders);
testContext.Beers.Add(TestBeer);
testContext.Customers.Add(TestCustomer);
testContext.SaveChanges();
}
[Fact]
public void TestAddCustomer()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestAddCustomer").Options;
using var testContext = new BrewCrewContext(options);
repo = new DBRepo(testContext);
//Act
repo.AddCustomerAsync(TestCustomer);
//Assert
using var assertContext = new BrewCrewContext(options);
Assert.NotNull(assertContext.Customers.SingleAsync(c => c.FName == TestCustomer.FName));
}
[Fact]
public void TestAddManager()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestAddManager").Options;
using var testContext = new BrewCrewContext(options);
repo = new DBRepo(testContext);
//Act
repo.AddManagerAsync(TestManager);
//Assert
using var assertContext = new BrewCrewContext(options);
Assert.NotNull(assertContext.Managers.SingleAsync(c => c.FName == TestManager.FName));
}
[Fact]
public void TestAddBrewery()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestAddBrewery").Options;
using var testContext = new BrewCrewContext(options);
repo = new DBRepo(testContext);
//Act
repo.AddBreweryAsync(TestBrewery);
//Assert
using var assertContext = new BrewCrewContext(options);
Assert.NotNull(assertContext.Breweries.SingleAsync(c => c.Name == TestBrewery.Name));
}
[Fact]
public void TestGetManagers()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetManagers").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetAllManagersAsync();
//Assert
Assert.NotNull(result.Result);
Assert.Equal(2, result.Result.Count);
}
[Fact]
public void TestGetBreweries()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetBreweries").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetAllBreweriesAsync();
//Assert
Assert.NotNull(result.Result);
Assert.Equal(2, result.Result.Count);
}
[Fact]
public void TestGetBeerById()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetBeerById").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetBeerByIdAsync("1");
//Assert
Assert.NotNull(result.Result);
}
[Fact]
public void TestGetAllBeersByBreweryId()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetAllBeersByBreweryId").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetAllBeersByBreweryIdAsync("1");
//Assert
Assert.NotNull(result.Result);
Assert.Equal(3, result.Result.Count);
}
[Fact]
public void TestPlaceOrder()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestPlaceOrder").Options;
using var testContext = new BrewCrewContext(options);
repo = new DBRepo(testContext);
//Act
repo.PlaceOrderAsync(TestOrder);
//Assert
using var assertContext = new BrewCrewContext(options);
Assert.NotNull(assertContext.Orders.SingleAsync(c => c.ID == TestOrder.ID));
}
[Fact]
public void TestGetAllOrdersByCustomerBreweryId()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetAllOrdersByCustomerBreweryId").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetAllOrdersByCustomerBreweryIdAsync("1", "1");
//Assert
Assert.NotNull(result.Result);
Assert.Equal(2, result.Result.Count);
}
[Fact]
public void TestGetUserByEmail()
{
//Arrange
var options = new DbContextOptionsBuilder<BrewCrewContext>().UseInMemoryDatabase("TestGetUserByEmail").Options;
using var testContext = new BrewCrewContext(options);
Seed(testContext);
//Act
using var assertContext = new BrewCrewContext(options);
repo = new DBRepo(assertContext);
var result = repo.GetUserByEmailAsync("customer1@email.net");
//Assert
Assert.NotNull(result);
Assert.Equal("customer1@email.net", result.Email);
}
}
}
| 31.817143 | 141 | 0.483836 | [
"MIT"
] | 201019-UiPath/FoleyBrian-Project0 | BrewCrew/BrewCrewTest/DBTest.cs | 11,136 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.SafeHandles
{
// Class of safe handle which uses only -1 as an invalid handle.
public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
{
protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
{
}
public override bool IsInvalid => handle == new IntPtr(-1);
}
}
| 29.894737 | 97 | 0.711268 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs | 568 | C# |
// ---------------------------------------------------------
// IObjectProvider.cs
//
// Created on: 08/27/2015 at 5:44 PM
// Last Modified: 08/27/2015 at 5:44 PM
//
// Last Modified by: Matt Eland
// ---------------------------------------------------------
using System;
using MattEland.Common.Annotations;
namespace MattEland.Common.Providers
{
/// <summary>
/// Defines a class capable of providing an object
/// </summary>
public interface IObjectProvider
{
/// <summary>
/// Creates an instance of the requested type.
/// </summary>
/// <param name="requestedType">The type that was requested.</param>
/// <param name="args">The arguments</param>
/// <returns>A new instance of the requested type</returns>
[CanBeNull]
object CreateInstance([NotNull] Type requestedType, [CanBeNull] params object[] args);
}
} | 29.83871 | 94 | 0.540541 | [
"MIT"
] | IntegerMan/MattEland.Common | MattEland.Common/Providers/IObjectProvider.cs | 927 | C# |
//==============================================================================
// Copyright (c) NT Prime LLC. All Rights Reserved.
//==============================================================================
using System;
using System.Activities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace Construct.Tfs.Activities
{
/// <summary>
/// A Workflow activity for committing the incrementing of a branch-based build number stored in a version file.
/// The Build Number in the version file will be a single integer.
/// </summary>
[BuildActivity(HostEnvironmentOption.Agent)]
public sealed class IncrementBranchBuildNumber : CodeActivity<int>
{
#region properties
/// <summary>
/// Gets or sets the relative path to the version file for this branch.
/// </summary>
[RequiredArgument()]
public InArgument<string> VersionFile { get; set; }
/// <summary>
/// Gets or sets the local workspace.
/// </summary>
[RequiredArgument()]
public InArgument<Workspace> Workspace { get; set; }
#endregion
#region methods
/// <summary>
/// Opens the version file for this branch by finding it in the local
/// workspace and increments the build number contained within it.
/// </summary>
/// <param name="context">The current workflow <see cref="CodeActivityContext"/>.</param>
/// <returns>The incremented build number.</returns>
protected override int Execute(CodeActivityContext context)
{
string versionFile = context.GetValue(this.VersionFile);
Workspace wkspc = context.GetValue(this.Workspace);
if (string.IsNullOrWhiteSpace(versionFile))
{
context.TrackBuildError("A version file containing a Version number to read and increment is required.");
return 0;
}
foreach (var folder in wkspc.Folders)
{
var fullpathVersionFile = Path.Combine(folder.LocalItem, versionFile);
if (File.Exists(fullpathVersionFile))
{
return VersionHelper.ReadVersionFile(fullpathVersionFile, true, true);
}
}
context.TrackBuildError(
string.Format("The provided version file '{0}' does not exist.", versionFile));
return 0;
}
#endregion
}
}
| 36.026667 | 121 | 0.589193 | [
"MIT"
] | nnieslan/Construct | Dev/BuildActivities/IncrementBranchBuildNumber.cs | 2,704 | 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a pointer type such as "int *". Pointer types
/// are used only in unsafe code.
/// </summary>
internal sealed partial class PointerTypeSymbol : TypeSymbol
{
private readonly TypeWithAnnotations _pointedAtType;
/// <summary>
/// Create a new PointerTypeSymbol.
/// </summary>
/// <param name="pointedAtType">The type being pointed at.</param>
internal PointerTypeSymbol(TypeWithAnnotations pointedAtType)
{
Debug.Assert(pointedAtType.HasType);
_pointedAtType = pointedAtType;
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.NotApplicable; }
}
public override bool IsStatic
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
/// <summary>
/// Gets the type of the storage location that an instance of the pointer type points to, along with its annotations.
/// </summary>
public TypeWithAnnotations PointedAtTypeWithAnnotations
{
get
{
return _pointedAtType;
}
}
/// <summary>
/// Gets the type of the storage location that an instance of the pointer type points to.
/// </summary>
public TypeSymbol PointedAtType => PointedAtTypeWithAnnotations.Type;
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
// Pointers do not support boxing, so they really have no base type.
return null;
}
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
// Pointers do not support boxing, so they really have no interfaces
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override bool IsReferenceType
{
get
{
return false;
}
}
public override bool IsValueType
{
get
{
return true;
}
}
internal sealed override ManagedKind GetManagedKind(ref HashSet<DiagnosticInfo> useSiteDiagnostics) => ManagedKind.Unmanaged;
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
public override ImmutableArray<Symbol> GetMembers()
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override SymbolKind Kind
{
get
{
return SymbolKind.PointerType;
}
}
public override TypeKind TypeKind
{
get
{
return TypeKind.Pointer;
}
}
public override Symbol ContainingSymbol
{
get
{
return null;
}
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitPointerType(this, argument);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitPointerType(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitPointerType(this);
}
public override int GetHashCode()
{
// We don't want to blow the stack if we have a type like T***************...***,
// so we do not recurse until we have a non-array.
int indirections = 0;
TypeSymbol current = this;
while (current.TypeKind == TypeKind.Pointer)
{
indirections += 1;
current = ((PointerTypeSymbol)current).PointedAtType;
}
return Hash.Combine(current, indirections);
}
internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary<TypeParameterSymbol, bool> isValueTypeOverrideOpt = null)
{
return this.Equals(t2 as PointerTypeSymbol, comparison, isValueTypeOverrideOpt);
}
private bool Equals(PointerTypeSymbol other, TypeCompareKind comparison, IReadOnlyDictionary<TypeParameterSymbol, bool> isValueTypeOverrideOpt)
{
if (ReferenceEquals(this, other))
{
return true;
}
if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison, isValueTypeOverrideOpt))
{
return false;
}
return true;
}
internal override void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
PointedAtTypeWithAnnotations.AddNullableTransforms(transforms);
}
internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result)
{
TypeWithAnnotations oldPointedAtType = PointedAtTypeWithAnnotations;
TypeWithAnnotations newPointedAtType;
if (!oldPointedAtType.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newPointedAtType))
{
result = this;
return false;
}
result = WithPointedAtType(newPointedAtType);
return true;
}
internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform)
{
return WithPointedAtType(transform(PointedAtTypeWithAnnotations));
}
internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance)
{
Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
TypeWithAnnotations pointedAtType = PointedAtTypeWithAnnotations.MergeEquivalentTypes(((PointerTypeSymbol)other).PointedAtTypeWithAnnotations, VarianceKind.None);
return WithPointedAtType(pointedAtType);
}
internal PointerTypeSymbol WithPointedAtType(TypeWithAnnotations newPointedAtType)
{
return PointedAtTypeWithAnnotations.IsSameAs(newPointedAtType) ? this : new PointerTypeSymbol(newPointedAtType);
}
internal override DiagnosticInfo GetUseSiteDiagnostic()
{
DiagnosticInfo result = null;
// Check type, custom modifiers
DeriveUseSiteDiagnosticFromType(ref result, this.PointedAtTypeWithAnnotations, AllowedRequiredModifierType.None);
return result;
}
internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return this.PointedAtTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes);
}
protected override ISymbol CreateISymbol()
{
return new PublicModel.PointerTypeSymbol(this, DefaultNullableAnnotation);
}
protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != DefaultNullableAnnotation);
return new PublicModel.PointerTypeSymbol(this, nullableAnnotation);
}
internal override bool IsRecord => false;
}
}
| 31.15873 | 174 | 0.603362 | [
"MIT"
] | HurricanKai/roslyn | src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs | 9,817 | C# |
/*
* BSD Licence:
* Copyright (c) 2001, 2002 Ben Houston [ ben@exocortex.org ]
* Exocortex Technologies [ www.exocortex.org ]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the <ORGANIZATION> 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 REGENTS 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 System.Diagnostics;
// Comments? Questions? Bugs? Tell Ben Houston at ben@exocortex.org
// Version: May 4, 2002
/// <summary>
/// <p>A set of statistical utilities for complex number arrays</p>
/// </summary>
public class ComplexStats
{
//---------------------------------------------------------------------------------------------
private ComplexStats() {
}
//---------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
/// <summary>
/// Calculate the sum
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public ComplexF Sum( ComplexF[] data ) {
Debug.Assert( data != null );
return SumRecursion( data, 0, data.Length );
}
static private ComplexF SumRecursion( ComplexF[] data, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= data.Length, "end = " + end + " and data.Length = " + data.Length );
if( ( end - start ) <= 1000 ) {
ComplexF sum = ComplexF.Zero;
for( int i = start; i < end; i ++ ) {
sum += data[ i ];
}
return sum;
}
else {
int middle = ( start + end ) >> 1;
return SumRecursion( data, start, middle ) + SumRecursion( data, middle, end );
}
}
/// <summary>
/// Calculate the sum
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public Complex Sum( Complex[] data ) {
Debug.Assert( data != null );
return SumRecursion( data, 0, data.Length );
}
static private Complex SumRecursion( Complex[] data, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= data.Length, "end = " + end + " and data.Length = " + data.Length );
if( ( end - start ) <= 1000 ) {
Complex sum = Complex.Zero;
for( int i = start; i < end; i ++ ) {
sum += data[ i ];
}
return sum;
}
else {
int middle = ( start + end ) >> 1;
return SumRecursion( data, start, middle ) + SumRecursion( data, middle, end );
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
/// <summary>
/// Calculate the sum of squares
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public ComplexF SumOfSquares( ComplexF[] data ) {
Debug.Assert( data != null );
return SumOfSquaresRecursion( data, 0, data.Length );
}
static private ComplexF SumOfSquaresRecursion( ComplexF[] data, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= data.Length, "end = " + end + " and data.Length = " + data.Length );
if( ( end - start ) <= 1000 ) {
ComplexF sumOfSquares = ComplexF.Zero;
for( int i = start; i < end; i ++ ) {
sumOfSquares += data[ i ] * data[ i ];
}
return sumOfSquares;
}
else {
int middle = ( start + end ) >> 1;
return SumOfSquaresRecursion( data, start, middle ) + SumOfSquaresRecursion( data, middle, end );
}
}
/// <summary>
/// Calculate the sum of squares
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public Complex SumOfSquares( Complex[] data ) {
Debug.Assert( data != null );
return SumOfSquaresRecursion( data, 0, data.Length );
}
static private Complex SumOfSquaresRecursion( Complex[] data, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= data.Length, "end = " + end + " and data.Length = " + data.Length );
if( ( end - start ) <= 1000 ) {
Complex sumOfSquares = Complex.Zero;
for( int i = start; i < end; i ++ ) {
sumOfSquares += data[ i ] * data[ i ];
}
return sumOfSquares;
}
else {
int middle = ( start + end ) >> 1;
return SumOfSquaresRecursion( data, start, middle ) + SumOfSquaresRecursion( data, middle, end );
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
/// <summary>
/// Calculate the mean (average)
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public ComplexF Mean( ComplexF[] data ) {
return ComplexStats.Sum( data ) / data.Length;
}
/// <summary>
/// Calculate the mean (average)
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public Complex Mean( Complex[] data ) {
return ComplexStats.Sum( data ) / data.Length;
}
/// <summary>
/// Calculate the variance
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public ComplexF Variance( ComplexF[] data ) {
Debug.Assert( data != null );
if( data.Length == 0 ) {
throw new DivideByZeroException( "length of data is zero" );
}
return ComplexStats.SumOfSquares( data ) / data.Length - ComplexStats.Sum( data );
}
/// <summary>
/// Calculate the variance
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public Complex Variance( Complex[] data ) {
Debug.Assert( data != null );
if( data.Length == 0 ) {
throw new DivideByZeroException( "length of data is zero" );
}
return ComplexStats.SumOfSquares( data ) / data.Length - ComplexStats.Sum( data );
}
/// <summary>
/// Calculate the standard deviation
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public ComplexF StdDev( ComplexF[] data ) {
Debug.Assert( data != null );
if( data.Length == 0 ) {
throw new DivideByZeroException( "length of data is zero" );
}
return ComplexMath.Sqrt( ComplexStats.Variance( data ) );
}
/// <summary>
/// Calculate the standard deviation
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
static public Complex StdDev( Complex[] data ) {
Debug.Assert( data != null );
if( data.Length == 0 ) {
throw new DivideByZeroException( "length of data is zero" );
}
return ComplexMath.Sqrt( ComplexStats.Variance( data ) );
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
/// <summary>
/// Calculate the root mean squared (RMS) error between two sets of data.
/// </summary>
/// <param name="alpha"></param>
/// <param name="beta"></param>
/// <returns></returns>
static public float RMSError( ComplexF[] alpha, ComplexF[] beta ) {
Debug.Assert( alpha != null );
Debug.Assert( beta != null );
Debug.Assert( beta.Length == alpha.Length );
return (float) Math.Sqrt( SumOfSquaredErrorRecursion( alpha, beta, 0, alpha.Length ) );
}
static private float SumOfSquaredErrorRecursion( ComplexF[] alpha, ComplexF[] beta, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= alpha.Length, "end = " + end + " and alpha.Length = " + alpha.Length );
Debug.Assert( beta.Length == alpha.Length );
if( ( end - start ) <= 1000 ) {
float sumOfSquaredError = 0;
for( int i = start; i < end; i ++ ) {
ComplexF delta = beta[ i ] - alpha[ i ];
sumOfSquaredError += ( delta.Re * delta.Re ) + ( delta.Im * delta.Im );
}
return sumOfSquaredError;
}
else {
int middle = ( start + end ) >> 1;
return SumOfSquaredErrorRecursion( alpha, beta, start, middle ) + SumOfSquaredErrorRecursion( alpha, beta, middle, end );
}
}
/// <summary>
/// Calculate the root mean squared (RMS) error between two sets of data.
/// </summary>
/// <param name="alpha"></param>
/// <param name="beta"></param>
/// <returns></returns>
static public double RMSError( Complex[] alpha, Complex[] beta ) {
Debug.Assert( alpha != null );
Debug.Assert( beta != null );
Debug.Assert( beta.Length == alpha.Length );
return Math.Sqrt( SumOfSquaredErrorRecursion( alpha, beta, 0, alpha.Length ) );
}
static private double SumOfSquaredErrorRecursion( Complex[] alpha, Complex[] beta, int start, int end ) {
Debug.Assert( 0 <= start, "start = " + start );
Debug.Assert( start < end, "start = " + start + " and end = " + end );
Debug.Assert( end <= alpha.Length, "end = " + end + " and alpha.Length = " + alpha.Length );
Debug.Assert( beta.Length == alpha.Length );
if( ( end - start ) <= 1000 ) {
double sumOfSquaredError = 0;
for( int i = start; i < end; i ++ ) {
Complex delta = beta[ i ] - alpha[ i ];
sumOfSquaredError += ( delta.Re * delta.Re ) + ( delta.Im * delta.Im );
}
return sumOfSquaredError;
}
else {
int middle = ( start + end ) >> 1;
return SumOfSquaredErrorRecursion( alpha, beta, start, middle ) + SumOfSquaredErrorRecursion( alpha, beta, middle, end );
}
}
} | 36.712871 | 125 | 0.574074 | [
"MIT"
] | Prion6/FantasyVR | Assets/Ocean/Plugins/Exocortex_FFT/ComplexStats.cs | 11,124 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Models.DB;
namespace API.Controllers.DB
{
[Route("api/[controller]")]
[ApiController]
public class EreservationInfoController : ControllerBase
{
private readonly DBContext _context;
public EreservationInfoController(DBContext context)
{
_context = context;
}
// GET: api/EreservationInfo
[HttpGet]
public async Task<ActionResult<IEnumerable<EreservationInfo>>> GetEreservationInfo()
{
return await _context.EreservationInfo.ToListAsync();
}
// GET: api/EreservationInfo/5
[HttpGet("{id}")]
public async Task<ActionResult<EreservationInfo>> GetEreservationInfo(long id)
{
var ereservationInfo = await _context.EreservationInfo.FindAsync(id);
if (ereservationInfo == null)
{
return NotFound();
}
return ereservationInfo;
}
// PUT: api/EreservationInfo/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutEreservationInfo(long id, EreservationInfo ereservationInfo)
{
if (id != ereservationInfo.EreservationInfoId)
{
return BadRequest();
}
_context.Entry(ereservationInfo).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EreservationInfoExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/EreservationInfo
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<EreservationInfo>> PostEreservationInfo(EreservationInfo ereservationInfo)
{
_context.EreservationInfo.Add(ereservationInfo);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (EreservationInfoExists(ereservationInfo.EreservationInfoId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetEreservationInfo", new { id = ereservationInfo.EreservationInfoId }, ereservationInfo);
}
// DELETE: api/EreservationInfo/5
[HttpDelete("{id}")]
public async Task<ActionResult<EreservationInfo>> DeleteEreservationInfo(long id)
{
var ereservationInfo = await _context.EreservationInfo.FindAsync(id);
if (ereservationInfo == null)
{
return NotFound();
}
_context.EreservationInfo.Remove(ereservationInfo);
await _context.SaveChangesAsync();
return ereservationInfo;
}
private bool EreservationInfoExists(long id)
{
return _context.EreservationInfo.Any(e => e.EreservationInfoId == id);
}
}
}
| 30.604839 | 126 | 0.566798 | [
"Apache-2.0"
] | LightosLimited/RailML | v2.4/API/Controllers/DB/EreservationInfoController.cs | 3,795 | C# |
using System;
using System.Linq;
using System.Text;
namespace Lnk.ExtraData
{
public class ShimDataBlock : ExtraDataBase
{
public ShimDataBlock(byte[] rawBytes)
{
Signature = ExtraDataTypes.ShimDataBlock;
Size = BitConverter.ToUInt32(rawBytes, 0);
LayerName = Encoding.Unicode.GetString(rawBytes, 8, rawBytes.Length - 8).Split('\0').First();
}
public string LayerName { get; }
public override string ToString()
{
return $"Shimcache data block" +
$"\r\nLayerName: {LayerName}";
}
}
} | 23.961538 | 105 | 0.582665 | [
"MIT"
] | EricZimmerman/Lnk | Lnk/ExtraData/ShimDataBlock.cs | 625 | C# |
using AutoMapper;
using TeknoLabs.Habit.Authorization.Users;
namespace TeknoLabs.Habit.Users.Dto
{
public class UserMapProfile : Profile
{
public UserMapProfile()
{
CreateMap<UserDto, User>();
CreateMap<UserDto, User>()
.ForMember(x => x.Roles, opt => opt.Ignore())
.ForMember(x => x.CreationTime, opt => opt.Ignore());
CreateMap<CreateUserDto, User>();
CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore());
}
}
}
| 27.9 | 90 | 0.569892 | [
"MIT"
] | teknolabs/hab | aspnet-core/src/TeknoLabs.Habit.Application/Users/Dto/UserMapProfile.cs | 560 | C# |
using System;
using System.Collections.Generic;
using Quaver.API.Enums;
using Quaver.API.Maps.Processors.Scoring;
using Quaver.Shared.Assets;
using Quaver.Shared.Database.Scores;
using Quaver.Shared.Modifiers;
using Quaver.Shared.Online;
using Wobble.Assets;
using Wobble.Bindables;
using Wobble.Graphics;
using Wobble.Graphics.Sprites;
namespace Quaver.Shared.Screens.Results.UI.Header.Contents.Tabs
{
public class ResultsTabSelector : Sprite
{
/// <summary>
/// </summary>
private Bindable<ResultsScreenTabType> ActiveTab { get; }
/// <summary>
/// </summary>
private Bindable<ScoreProcessor> Processor { get; }
/// <summary>
/// </summary>
private List<Sprite> ModifierSprites { get; } = new List<Sprite>();
/// <summary>
/// </summary>
/// <param name="activeTab"></param>
/// <param name="processor"></param>
/// <param name="size"></param>
public ResultsTabSelector(Bindable<ResultsScreenTabType> activeTab, Bindable<ScoreProcessor> processor, ScalableVector2 size)
{
ActiveTab = activeTab;
Processor = processor;
Size = size;
Image = UserInterface.ResultsTabSelectorBackground;
CreateTabs();
CreateModifiers();
}
/// <summary>
/// </summary>
private void CreateTabs()
{
var values = Enum.GetValues(typeof(ResultsScreenTabType));
var posX = 202f;
for (var i = 0; i < values.Length; i++)
{
var item = new ResultsTabItem(ActiveTab, (ResultsScreenTabType) i, Height)
{
Parent = this,
Alignment = Alignment.MidLeft,
X = posX
};
posX += item.Width + 44;
if ((ResultsScreenTabType) i == ResultsScreenTabType.Multiplayer && OnlineManager.CurrentGame == null)
item.Button.IsClickable = false;
item.SetTint();
}
}
/// <summary>
/// </summary>
private void CreateModifiers()
{
ModifierSprites.ForEach(x => x.Destroy());
ModifierSprites.Clear();
var modsList = ModManager.GetModsList(Processor.Value.Mods);
if (modsList.Count == 0)
modsList.Add(ModIdentifier.None);
var posX = -38f;
for (var i = modsList.Count - 1; i >= 0; i--)
{
var mod = modsList[i];
// HealthAdjust doesn't have a proper icon
if (mod == ModIdentifier.HeatlthAdjust)
continue;
var texture = ModManager.GetTexture(mod);
const float width = 72f;
var sprite = new Sprite()
{
Parent = this,
Alignment = Alignment.MidRight,
Image = texture,
Size = new ScalableVector2(width, (float) texture.Height / texture.Width * width),
X = posX
};
posX -= sprite.Width - 4;
ModifierSprites.Add(sprite);
}
}
}
} | 29.526786 | 133 | 0.523435 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Adrriii/Quaver | Quaver.Shared/Screens/Results/UI/Header/Contents/Tabs/ResultsTabSelector.cs | 3,307 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dontDestroy : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad(this.gameObject);
}
}
| 17.375 | 53 | 0.647482 | [
"MIT"
] | VivekSingal98/financeSimulationGame | HomeSim/Assets/Scripts/dontDestroy.cs | 280 | C# |
using System.Collections.Generic;
using System.Web;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Host.Handlers
{
public class ForbiddenHttpHandler : HttpAsyncTaskHandler
{
public bool? IsIntegratedPipeline { get; set; }
public string WebHostPhysicalPath { get; set; }
public List<string> WebHostRootFileNames { get; set; }
public string WebHostUrl { get; set; }
public string DefaultRootFileName { get; set; }
public string DefaultHandler { get; set; }
public override void ProcessRequest(IRequest request, IResponse response, string operationName)
{
response.ContentType = "text/plain";
response.StatusCode = 403;
response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r =>
{
r.Write("Forbidden\n\n");
r.Write("\nRequest.HttpMethod: " + request.Verb);
r.Write("\nRequest.PathInfo: " + request.PathInfo);
r.Write("\nRequest.QueryString: " + request.QueryString);
if (HostContext.Config.DebugMode)
{
r.Write("\nRequest.RawUrl: " + request.RawUrl);
if (IsIntegratedPipeline.HasValue)
r.Write("\nApp.IsIntegratedPipeline: " + IsIntegratedPipeline);
if (!WebHostPhysicalPath.IsNullOrEmpty())
r.Write("\nApp.WebHostPhysicalPath: " + WebHostPhysicalPath);
if (!WebHostRootFileNames.IsEmpty())
r.Write("\nApp.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
if (!WebHostUrl.IsNullOrEmpty())
r.Write("\nApp.WebHostUrl: " + WebHostUrl);
if (!DefaultRootFileName.IsNullOrEmpty())
r.Write("\nApp.DefaultRootFileName: " + DefaultRootFileName);
if (!DefaultHandler.IsNullOrEmpty())
r.Write("\nApp.DefaultHandler: " + DefaultHandler);
if (!HttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
r.Write("\nApp.DebugLastHandlerArgs: " + HttpHandlerFactory.DebugLastHandlerArgs);
}
});
}
public override void ProcessRequest(HttpContextBase context)
{
var request = context.Request;
var response = context.Response;
response.ContentType = "text/plain";
response.StatusCode = 403;
response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r =>
{
r.Write("Forbidden\n\n");
r.Write("\nRequest.HttpMethod: " + request.HttpMethod);
r.Write("\nRequest.PathInfo: " + request.PathInfo);
r.Write("\nRequest.QueryString: " + request.QueryString);
if (HostContext.Config.DebugMode)
{
r.Write("\nRequest.RawUrl: " + request.RawUrl);
if (IsIntegratedPipeline.HasValue)
r.Write("\nApp.IsIntegratedPipeline: " + IsIntegratedPipeline);
if (!WebHostPhysicalPath.IsNullOrEmpty())
r.Write("\nApp.WebHostPhysicalPath: " + WebHostPhysicalPath);
if (!WebHostRootFileNames.IsEmpty())
r.Write("\nApp.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
if (!WebHostUrl.IsNullOrEmpty())
r.Write("\nApp.ApplicationBaseUrl: " + WebHostUrl);
if (!DefaultRootFileName.IsNullOrEmpty())
r.Write("\nApp.DefaultRootFileName: " + DefaultRootFileName);
}
});
}
public override bool IsReusable
{
get { return true; }
}
}
} | 44.582418 | 122 | 0.547695 | [
"Apache-2.0"
] | softwx/ServiceStack | src/ServiceStack/Host/Handlers/ForbiddenHttpHandler.cs | 3,969 | C# |
using FubuCore.Configuration;
using FubuTestingSupport;
using NUnit.Framework;
using StructureMap;
namespace FubuMVC.StructureMap.Testing.Internals
{
[TestFixture]
public class AppSettingProviderRegistrySmokeTester
{
[SetUp]
public void SetUp()
{
}
[Test]
public void can_build_an_app_settings_provider_object()
{
var container = new Container(new AppSettingProviderRegistry());
container.GetInstance<AppSettingsProvider>().ShouldNotBeNull();
}
}
} | 25.043478 | 77 | 0.642361 | [
"Apache-2.0"
] | DovetailSoftware/fubumvc | src/FubuMVC.StructureMap.Testing/Internals/AppSettingProviderRegistrySmokeTester.cs | 576 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FunBrainDomain;
using FunBrainInfrastructure.Models;
using Functional;
using Functional.Option;
using Unit = System.ValueTuple;
using static Functional.F;
namespace FunBrainInfrastructure.Repositories
{
public class UserRepositoryInMemory //: IUserRepository
{
public IList<User> Users { get; set; } = new List<User>();
public UserRepositoryInMemory()
{
Users.Add(new User
{
Id = 1,
Name = "User 1",
Email = "user1@email.com",
});
Users.Add(new User
{
Id = 2,
Name = "User 2",
Email = "user2@email.com"
});
}
public Option<IList<User>> Get()
=> Some(Users);
public User GetById(int id)
{
return Users.FirstOrDefault(u => u.Id == id);
}
public Either<Error, User> Create(UserCreate newUser)
{
throw new NotImplementedException();
}
public User CreateOld(UserCreate newUser)
{
var createdUser = new User
{
Id = Users.Count + 1,
Name = newUser.Name,
Email = newUser.Email
};
Users.Add(createdUser);
return createdUser;
}
public User Update(UserUpdate updateUser)
{
if (updateUser == null)
{
return null;
}
// First? or default?
var userToUpdate = Users.FirstOrDefault(u => u.Id == updateUser.Id);
if (userToUpdate == null)
{
return null;
}
userToUpdate.Name = updateUser.Name;
userToUpdate.Email = updateUser.Email;
return userToUpdate;
}
public bool DeleteOld(int userId)
{
foreach (var user in Users)
{
if (user.Id == userId)
{
Users.Remove(user);
return true;
}
}
return false;
}
public Either<Error, Unit>Delete(int userId)
{
throw new NotImplementedException();
}
public Option<bool> DeleteWithOption(int userId)
{
throw new NotImplementedException();
}
}
}
| 23.254545 | 80 | 0.48749 | [
"MIT"
] | ralbu/FunBrain-DotNetCSharpFunctional | src/FunBrainInfrastructure/Repositories/UserRepositoryInMemory.cs | 2,560 | 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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Threading;
using TestLibrary;
using Console = Internal.Console;
public class Program
{
public static class NativeMethods
{
[DllImport("NativeCallableDll")]
public static extern int CallManagedProc(IntPtr callbackProc, int n);
}
private delegate int IntNativeMethodInvoker();
private delegate void NativeMethodInvoker();
public static int Main(string[] args)
{
try
{
TestNativeCallableValid();
NegativeTest_ViaDelegate();
NegativeTest_NonBlittable();
NegativeTest_GenericArguments();
if (args.Length != 0 && args[0].Equals("calli"))
{
NegativeTest_ViaCalli();
}
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
return 100;
}
[NativeCallable]
public static int ManagedDoubleCallback(int n)
{
return DoubleImpl(n);
}
private static int DoubleImpl(int n)
{
return 2 * n;
}
public static void TestNativeCallableValid()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function");
/*
void TestNativeCallable()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 ManagedDoubleCallback(int32)
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4 <n> local
IL_000e: call bool NativeMethods::CallManagedProc(native int, int)
IL_0013: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallable", typeof(int), null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(ManagedDoubleCallback)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
int n = 12345;
il.Emit(OpCodes.Ldc_I4, n);
il.Emit(OpCodes.Call, typeof(NativeMethods).GetMethod("CallManagedProc"));
il.Emit(OpCodes.Ret);
var testNativeMethod = (IntNativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(IntNativeMethodInvoker));
int expected = DoubleImpl(n);
Assert.AreEqual(expected, testNativeMethod());
}
public static void NegativeTest_ViaDelegate()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function as delegate");
// Try invoking method directly
try
{
CallAsDelegate();
Assert.Fail($"Invalid to call {nameof(ManagedDoubleCallback)} as delegate");
}
catch (NotSupportedException)
{
}
// Local function to delay exception thrown during JIT
void CallAsDelegate()
{
Func<int, int> invoker = ManagedDoubleCallback;
invoker(0);
}
}
[NativeCallable]
public static int CallbackMethodNonBlittable(bool x1)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot have non-blittable arguments");
return -1;
}
public static void NegativeTest_NonBlittable()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function with non-blittable arguments");
/*
void TestNativeCallableNonBlittable()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 CallbackMethodNonBlittable(bool)
IL_0007: stloc.0
IL_0008: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableNonBlittable", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackMethodNonBlittable)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ret);
var testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// Try invoking method
try
{
testNativeMethod();
Assert.Fail($"Function {nameof(CallbackMethodNonBlittable)} has non-blittable types");
}
catch (NotSupportedException)
{
}
}
[NativeCallable]
public static int CallbackMethodGeneric<T>(T arg)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot have generic arguments");
return -1;
}
public static void NegativeTest_GenericArguments()
{
/*
void TestNativeCallableGenericArguments()
{
.locals init ([0] native int ptr)
IL_0000: nop
IL_0001: ldftn int32 CallbackMethodGeneric(T)
IL_0007: stloc.0
IL_0008: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableGenericArguments", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackMethodGeneric)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ret);
var testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// Try invoking method
try
{
testNativeMethod();
Assert.Fail($"Function {nameof(CallbackMethodGeneric)} has generic types");
}
catch (InvalidProgramException)
{
}
}
[NativeCallable]
public static void CallbackViaCalli(int val)
{
Assert.Fail($"Functions with attribute {nameof(NativeCallableAttribute)} cannot be called via calli");
}
public static void NegativeTest_ViaCalli()
{
Console.WriteLine($"{nameof(NativeCallableAttribute)} function via calli instruction. The CLR _will_ crash.");
/*
void TestNativeCallableViaCalli()
{
.locals init (native int V_0)
IL_0000: nop
IL_0001: ldftn void CallbackViaCalli(int32)
IL_0007: stloc.0
IL_0008: ldc.i4 1234
IL_000d: ldloc.0
IL_000e: calli void(int32)
IL_0013: nop
IL_0014: ret
}
*/
DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableViaCalli", null, null, typeof(Program).Module);
ILGenerator il = testNativeCallable.GetILGenerator();
il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Nop);
// Get native function pointer of the callback
il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackViaCalli)));
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldc_I4, 1234);
il.Emit(OpCodes.Ldloc_0);
il.EmitCalli(OpCodes.Calli, CallingConventions.Standard, null, new Type[] { typeof(int) }, null);
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ret);
NativeMethodInvoker testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));
// It is not possible to catch the resulting ExecutionEngineException exception.
// To observe the crashing behavior set a breakpoint in the ReversePInvokeBadTransition() function
// located in src/vm/dllimportcallback.cpp.
testNativeMethod();
}
}
| 32.965116 | 135 | 0.617989 | [
"MIT"
] | AlexejLiebenthal/coreclr | tests/src/Interop/NativeCallable/NativeCallableTest.cs | 8,505 | 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("Hideout")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hideout")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("e440f38e-6ed6-4266-a68c-760356044054")]
// 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")]
| 37.351351 | 84 | 0.74602 | [
"MIT"
] | VeselinBPavlov/programming-fundamentals | 25. Strings and Regular Expressions - More Exercises/Hideout/Properties/AssemblyInfo.cs | 1,385 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.Email
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class EmailMailboxChangeReader
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public void AcceptChanges()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxChangeReader", "void EmailMailboxChangeReader.AcceptChanges()");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public void AcceptChangesThrough( global::Windows.ApplicationModel.Email.EmailMailboxChange lastChangeToAcknowledge)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxChangeReader", "void EmailMailboxChangeReader.AcceptChangesThrough(EmailMailboxChange lastChangeToAcknowledge)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::Windows.Foundation.IAsyncOperation<global::System.Collections.Generic.IReadOnlyList<global::Windows.ApplicationModel.Email.EmailMailboxChange>> ReadBatchAsync()
{
throw new global::System.NotImplementedException("The member IAsyncOperation<IReadOnlyList<EmailMailboxChange>> EmailMailboxChangeReader.ReadBatchAsync() is not implemented in Uno.");
}
#endif
}
}
| 46.030303 | 234 | 0.794602 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Email/EmailMailboxChangeReader.cs | 1,519 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Robert te Kaat")]
[assembly: AssemblyProduct("Resonance")]
//[assembly: AssemblyTrademark("")]
[assembly: AssemblyTitle("Resonance.APIClient")]
[assembly: AssemblyDescription("Client-library for the REST-api of the Resonance Eventing library")]
[assembly: AssemblyCopyright("Copyright © 2016 - Robert te Kaat")]
// 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: AssemblyConfiguration("")]
// 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("4537bb6a-d14a-4520-9cb9-a5d3e86b3a35")]
| 39.111111 | 100 | 0.779356 | [
"MIT"
] | kwaazaar/resonance.web | Resonance.Web.Client/Properties/AssemblyInfo.cs | 1,059 | C# |
namespace Entities.Enums
{
public enum PaymentLevelEnum
{
Base,
Premium,
Ultimate
}
}
| 12.3 | 32 | 0.544715 | [
"Apache-2.0"
] | e1ement/RT-BACK | Entities/Enums/PaymentLevelEnum.cs | 125 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoMoqCore;
using Moq;
using NUnit.Framework;
using SFA.DAS.Payments.Audit.Application.Data.EarningEvent;
using SFA.DAS.Payments.Audit.Application.PaymentsEventProcessing;
using SFA.DAS.Payments.Audit.Application.PaymentsEventProcessing.EarningEvent;
using SFA.DAS.Payments.Model.Core.Audit;
using SFA.DAS.Payments.Monitoring.Jobs.Messages.Events;
namespace SFA.DAS.Payments.Audit.Application.UnitTests.EarningEvent
{
[TestFixture]
public class EarningEventSubmissionFailedProcessorTests
{
private AutoMoqer mocker;
private SubmissionJobFailed failedEvent;
[SetUp]
public void SetUp()
{
mocker = new AutoMoqer();
failedEvent = new SubmissionJobFailed
{
JobId = 99,
AcademicYear = 1920,
CollectionPeriod = 01,
EventTime = DateTimeOffset.UtcNow,
IlrSubmissionDateTime = DateTime.Now,
Ukprn = 1234
};
}
[Test]
public async Task Deletes_Failed_Job_Earning_Event_Data()
{
var processor = mocker.Create<EarningEventSubmissionFailedProcessor>();
await processor.Process(failedEvent, CancellationToken.None).ConfigureAwait(false);
mocker.GetMock<IEarningEventRepository>()
.Verify(repo => repo.RemoveFailedSubmissionEvents(It.Is<long>(jobId => jobId == failedEvent.JobId),
It.IsAny<CancellationToken>()),
Times.Once);
}
[Test]
public async Task Writes_Pending_Earning_Events_To_Db_Before_Deletion()
{
var processor = mocker.Create<EarningEventSubmissionFailedProcessor>();
await processor.Process(failedEvent, CancellationToken.None).ConfigureAwait(false);
mocker.GetMock<IPaymentsEventModelBatchService<EarningEventModel>>()
.Verify(service => service.StorePayments(It.IsAny<CancellationToken>()), Times.Once);
}
}
} | 35.79661 | 115 | 0.656723 | [
"MIT"
] | PJChamley/das-payments-V2 | src/SFA.DAS.Payments.Audit.Application.UnitTests/EarningEvent/EarningEventSubmissionFailedProcessorTests.cs | 2,114 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VVVV.PluginInterfaces.V1;
using VVVV.PluginInterfaces.V2;
namespace VVVV.DX11
{
/// <summary>
/// Allows to create a manual dependency in the dx11 graph.
/// Usually update graphi is handled by node having resource pins, but there might be cases where we can't apply those and want a manual perform
/// </summary>
public interface IDX11RenderDependencyFactory
{
/// <summary>
/// Creates a dependency in the dx11 graph
/// </summary>
/// <param name="inputPin">Input pin</param>
/// <param name="outputPin">Output pin</param>
void CreateDependency(IPin inputPin, IPin outputPin);
/// <summary>
/// Deletes dependency from the dx11 graph
/// </summary>
/// <param name="inputPin">Input pin</param>
void DeleteDependency(IPin inputPin);
}
}
| 31.612903 | 148 | 0.657143 | [
"BSD-3-Clause"
] | laurensrinke/dx11-vvvv | Core/VVVV.DX11.Core/NodeInterfaces/IDX11RenderDependencyFactory.cs | 982 | C# |
using UnityEngine;
using System.Collections;
public class Missile : MonoBehaviour
{
new private Rigidbody2D rigidbody;
private float boost = 1f;
public Transform target;
public float speed = 2000f;
public float turn = 3000f;
public float angle = 30f;
public float launchPeriod = 0.3f;
void Awake()
{
rigidbody = GetComponent<Rigidbody2D>();
angle *= Mathf.Deg2Rad;
}
void OnEnable()
{
boost = 10.0f;
StartCoroutine(Later());
gameObject.layer = 8;
}
IEnumerator Later()
{
yield return new WaitForSeconds(launchPeriod);
gameObject.layer = 0;
boost = 1.0f;
}
public void Setup(Rigidbody2D launcher, float acc, Transform target)
{
speed = acc;
this.target = target;
rigidbody.isKinematic = true;
Vector2 offset = (Vector2)launcher.transform.up * 15f;
rigidbody.position = launcher.position + offset;
rigidbody.rotation = launcher.rotation;
rigidbody.velocity = offset + launcher.velocity;
rigidbody.angularVelocity = 0f;
rigidbody.isKinematic = false;
}
void FixedUpdate()
{
if (target != null)
{
PhysicsFunctions.RigidBodyFollow(rigidbody, target.position, speed*boost, turn, angle);
}
else
{
gameObject.SetActive(false);
}
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Sun")
{
gameObject.SetActive(false);
}
else if (collision.gameObject.tag == "Planet")
{
gameObject.SetActive(false);
Planet p = collision.gameObject.GetComponent<Planet>();
p.food = (int)0.9 * p.food;
p.products = (int)0.9 * p.products;
p.population = (int)0.9 * p.population;
}
}
}
| 20.506329 | 90 | 0.692593 | [
"Apache-2.0"
] | Aggrathon/LudumDare34 | Assets/Scripts/Missile.cs | 1,622 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace dashboard.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
| 24.117647 | 84 | 0.704878 | [
"MIT"
] | shivapbhusal/dashboard | dashboard/dashboard/Data/ApplicationDbContext.cs | 412 | C# |
using System;
namespace FirstConsole
{
class Program_Day0001_0006
{
static void Main(string[] args)
{
//Master In C#
// 5/6 points
// Practice
// String
// Number
// Boolean
// Collection
// Date/time
// File System
// Emogies
//Or Preparing for interview
string str = "";
//number
//
string[] employeeNames = { "Abhay", "Shridhar", "Akash", "Ajay", "Vijay", "Karan" };
var result= GetCondition(employeeNames, "A", "StartsWith");
Console.WriteLine("All Employees Start With A");
Print(result);
result = GetCondition(employeeNames,x=>x.StartsWith("P"));
Console.WriteLine("All Employees Start With P");
Print(result);
result = GetCondition(employeeNames, x => x.StartsWith("K"));
Console.WriteLine("All Employees Start With K");
Print(result);
result = GetCondition(employeeNames, x => x.EndsWith("r"));
Console.WriteLine("All Employees End With r");
Print(result);
result = GetCondition(employeeNames, x => x.EndsWith("y"));
Console.WriteLine("All Employees End With y");
Print(result);
result = GetCondition(employeeNames, x => x.Contains("b"));
Console.WriteLine("All Employees Conatains b");
Print(result);
//Want to start with "A";
Console.WriteLine("Hello World!");
}
public static void Print(string[] result)
{
for (int i = 0; i < result.Length; i++)
{
if (result[i] != null)
{
Console.WriteLine(result[i]);
}
}
}
public static string[] GetCondition(string[] employeeNames, Func<string,bool> predicate)
{
string[] result = new string[employeeNames.Length];
int j = 0;
for (int i = 0; i < employeeNames.Length; i++)
{
if (predicate(employeeNames[i]))
{
result[j++] = employeeNames[i];
}
}
return result;
}
public static string[] GetCondition(string[] employeeNames, string Key, string condition)
{
string[] result = new string[employeeNames.Length];
int j = 0;
for (int i = 0; i < employeeNames.Length; i++)
{
if (condition.Equals("StartsWith"))
{
if (employeeNames[i].StartsWith(Key))
{
result[j++] = employeeNames[i];
}
} else if (condition.Equals("EndsWith"))
{
if (employeeNames[i].EndsWith(Key))
{
result[j++] = employeeNames[i];
}
}
else if (condition.Equals("Contains"))
{
if (employeeNames[i].Contains(Key))
{
result[j++] = employeeNames[i];
}
}
}
return result;
}
public static string[] GetStartWith(string[] employeeNames, string Key)
{
string[] result = new string[employeeNames.Length];
int j = 0;
for (int i = 0; i < employeeNames.Length; i++)
{
if (employeeNames[i].StartsWith(Key))
{
result[j++] = employeeNames[i];
}
}
return result;
}
public static string[] GetEndWith(string[] employeeNames, string Key)
{
string[] result = new string[employeeNames.Length];
int j = 0;
for (int i = 0; i < employeeNames.Length; i++)
{
if (employeeNames[i].EndsWith(Key))
{
result[j++] = employeeNames[i];
}
}
return result;
}
public static string[] GetContains(string[] employeeNames, string Key)
{
string[] result = new string[employeeNames.Length];
int j = 0;
for (int i = 0; i < employeeNames.Length; i++)
{
if (employeeNames[i].Contains(Key))
{
result[j++] = employeeNames[i];
}
}
return result;
}
}
}
| 26.73743 | 97 | 0.43878 | [
"MIT"
] | Amrutaquickitdotnet/ShridhardDotnet | Dotnet/FirstConsole/FirstConsole/Program_Day0001_0006.cs | 4,788 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/codecapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("E3D00F8A-C6F5-4E14-A588-0EC87A726F9B")]
public partial struct CODECAPI_AVEncWMVInterlacedEncoding
{
}
}
| 32.066667 | 145 | 0.762994 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/codecapi/CODECAPI_AVEncWMVInterlacedEncoding.cs | 483 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
namespace VueExample.Services.Abstract
{
public interface IDieWithCodeService
{
Task<DieWithCode> GetById(ObjectId objectId);
Task<List<ObjectId>> CreateDieWithCodes(List<DieWithCode> dieWithCodes);
Task<bool> DeleteDieWithCodes(List<ObjectId> dieWithCodesIds);
}
} | 29.692308 | 80 | 0.753886 | [
"MIT"
] | 7is7/SVR2.0 | Services/Abstract/IDieWithCodeService.cs | 386 | C# |
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace MvpWebForms.Controls
{
using MvpWebForms.Views;
using Narvalo.Mvp.Web;
public partial class HelloWorldControl : MvpUserControl<StringModel> { }
}
| 28.3 | 112 | 0.756184 | [
"BSD-2-Clause"
] | chtoucas/Narvalo.NET | samples/MvpWebForms/Controls/HelloWorldControl.ascx.cs | 285 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Materia.Nodes
{
public struct NodeConnection
{
//we ignore parent and order
//as those are only used for
//the undo redo system
//so no need to save the
//extra data on export
[JsonIgnore]
public string parent;
public string node;
public int index;
public int outIndex;
[JsonIgnore]
public int order;
public NodeConnection(string p, string n, int oi, int i, int ord)
{
parent = p;
node = n;
outIndex = oi;
index = i;
order = ord;
}
}
public class NodeOutput
{
public List<NodeInput> To { get; protected set; }
protected NodeType type;
public NodeType Type
{
get
{
return type;
}
set
{
type = value;
}
}
public Node ParentNode { get; protected set; }
public Node Node { get; protected set; }
public string Name { get; set; }
protected object data;
public object Data
{
get
{
return data;
}
set
{
data = value;
}
}
public NodeOutput(NodeType t, Node n, string name = "")
{
type = t;
Node = n;
ParentNode = n;
Name = name;
To = new List<NodeInput>();
}
public NodeOutput(NodeType t, Node n, Node parent, string name = "")
{
type = t;
Node = n;
ParentNode = parent;
Name = name;
To = new List<NodeInput>();
}
public void InsertAt(int index, NodeInput inp, bool assign = false)
{
if (inp.Reference != null)
{
inp.Reference.Remove(inp);
}
if (assign)
{
inp.AssignReference(this);
}
else
{
inp.Reference = this;
}
if (index >= To.Count)
{
To.Add(inp);
}
else
{
To.Insert(index, inp);
}
}
public void Add(NodeInput inp, bool assign = false)
{
if(inp.Reference != null)
{
inp.Reference.Remove(inp);
}
if (assign)
{
inp.AssignReference(this);
}
else
{
inp.Reference = this;
}
To.Add(inp);
}
public void Remove(NodeInput inp)
{
if (To.Remove(inp))
{
inp.Reference = null;
}
}
}
}
| 21.151724 | 76 | 0.415064 | [
"MIT"
] | mauricepape/Materia | Core/Nodes/NodeOutput.cs | 3,069 | C# |
using System;
namespace XPT.Core.Scripting {
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)]
public class LoxFieldAttribute : Attribute {
public readonly string Name;
public LoxFieldAttribute(string name) {
Name = name;
}
}
}
| 25.846154 | 99 | 0.651786 | [
"MIT"
] | ZaneDubya/LoxScript | LoxScript/Core/Scripting/LoxFieldAttribute.cs | 338 | C# |
using AzureDevOpsJanitor.Application.Commands.Build;
using AzureDevOpsJanitor.Domain.ValueObjects;
using System;
using System.Text.Json;
using Xunit;
namespace AzureDevOpsJanitor.Application.UnitTest.Commands.Build
{
public class CreateBuildCommandTests
{
[Fact]
public void CanBeConstructed()
{
//Arrange
var sut = new CreateBuildCommand(Guid.NewGuid(), Guid.NewGuid().ToString(), new BuildDefinition("my-def", "my-yaml", 1));
//Act
var hashCode = sut.GetHashCode();
//Assert
Assert.NotNull(sut);
Assert.Equal(hashCode, sut.GetHashCode());
Assert.True(sut.ProjectId != Guid.Empty);
Assert.True(!string.IsNullOrEmpty(sut.CapabilityId));
Assert.NotNull(sut.BuildDefinition);
Assert.Equal(1, sut.BuildDefinition.Id);
Assert.Equal("my-def", sut.BuildDefinition.Name);
Assert.Equal("my-yaml", sut.BuildDefinition.Yaml);
}
[Fact]
public void CanBeSerialized()
{
//Arrange
var sut = new CreateBuildCommand(Guid.NewGuid(), Guid.NewGuid().ToString(), new BuildDefinition("my-def", "my-yaml", 1));
//Act
var json = JsonSerializer.Serialize(sut);
//Assert
Assert.False(string.IsNullOrEmpty(json));
}
[Fact]
public void CanBeDeserialized()
{
//Arrange
CreateBuildCommand sut;
var json = "{\"projectId\":\"6def4aee-1467-4613-9b1b-5c4bf4cbbe89\",\"buildDefinition\":{\"id\":1,\"name\":\"my-def\",\"yaml\":\"my-yaml\"},\"capabilityId\":\"12d44c07-8950-4eb9-9398-6a815c35a08c\"}";
//Act
sut = JsonSerializer.Deserialize<CreateBuildCommand>(json);
//Assert
Assert.NotNull(sut);
Assert.Equal("6def4aee-1467-4613-9b1b-5c4bf4cbbe89", sut.ProjectId.ToString());
Assert.Equal("12d44c07-8950-4eb9-9398-6a815c35a08c", sut.CapabilityId);
Assert.NotNull(sut.BuildDefinition);
Assert.Equal(1, sut.BuildDefinition.Id);
Assert.Equal("my-def", sut.BuildDefinition.Name);
Assert.Equal("my-yaml", sut.BuildDefinition.Yaml);
}
}
}
| 35.4 | 212 | 0.593655 | [
"MIT"
] | dfds/azure-devops-janitor | test/AzureDevOpsJanitor.Application.UnitTest/Commands/Build/CreateBuildCommandTests.cs | 2,303 | 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 apigateway-2015-07-09.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.APIGateway.Model
{
/// <summary>
/// Represents the response of the test invoke request in the HTTP method.
///
/// <div class="seeAlso"> <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-test-method.html#how-to-test-method-console">Test
/// API using the API Gateway console</a> </div>
/// </summary>
public partial class TestInvokeMethodResponse : AmazonWebServiceResponse
{
private string _body;
private Dictionary<string, string> _headers = new Dictionary<string, string>();
private long? _latency;
private string _log;
private Dictionary<string, List<string>> _multiValueHeaders = new Dictionary<string, List<string>>();
private int? _status;
/// <summary>
/// Gets and sets the property Body.
/// <para>
/// The body of the HTTP response.
/// </para>
/// </summary>
public string Body
{
get { return this._body; }
set { this._body = value; }
}
// Check to see if Body property is set
internal bool IsSetBody()
{
return this._body != null;
}
/// <summary>
/// Gets and sets the property Headers.
/// <para>
/// The headers of the HTTP response.
/// </para>
/// </summary>
public Dictionary<string, string> Headers
{
get { return this._headers; }
set { this._headers = value; }
}
// Check to see if Headers property is set
internal bool IsSetHeaders()
{
return this._headers != null && this._headers.Count > 0;
}
/// <summary>
/// Gets and sets the property Latency.
/// <para>
/// The execution latency of the test invoke request.
/// </para>
/// </summary>
public long Latency
{
get { return this._latency.GetValueOrDefault(); }
set { this._latency = value; }
}
// Check to see if Latency property is set
internal bool IsSetLatency()
{
return this._latency.HasValue;
}
/// <summary>
/// Gets and sets the property Log.
/// <para>
/// The API Gateway execution log for the test invoke request.
/// </para>
/// </summary>
public string Log
{
get { return this._log; }
set { this._log = value; }
}
// Check to see if Log property is set
internal bool IsSetLog()
{
return this._log != null;
}
/// <summary>
/// Gets and sets the property MultiValueHeaders.
/// <para>
/// The headers of the HTTP response as a map from string to list of values.
/// </para>
/// </summary>
public Dictionary<string, List<string>> MultiValueHeaders
{
get { return this._multiValueHeaders; }
set { this._multiValueHeaders = value; }
}
// Check to see if MultiValueHeaders property is set
internal bool IsSetMultiValueHeaders()
{
return this._multiValueHeaders != null && this._multiValueHeaders.Count > 0;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The HTTP status code.
/// </para>
/// </summary>
public int Status
{
get { return this._status.GetValueOrDefault(); }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status.HasValue;
}
}
} | 30.270968 | 157 | 0.568841 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/TestInvokeMethodResponse.cs | 4,692 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CGooseDynamicWander : CAIDynamicWander
{
public CGooseDynamicWander(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CGooseDynamicWander(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 32.217391 | 131 | 0.748988 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CGooseDynamicWander.cs | 741 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Calculator_CSharp.Models
{
public class Calculator
{
public Calculator()
{
this.Result = 0;
}
public decimal LeftOperand { get; set; }
public decimal RightOperand { get; set; }
public string Operator { get; set; }
public decimal Result { get; set; }
}
} | 20.571429 | 49 | 0.604167 | [
"MIT"
] | msotiroff/Softuni-learning | Tech Module/Software Technologies/C#/Calculator/Calculator-CSharp/Models/Calculator.cs | 434 | C# |
using System;
namespace Yggdrasil.Models {
public abstract class YggdrasilPatch {
public abstract Type DeclaringType { get; }
public abstract string MethodName { get; }
public abstract Type[] ParameterTypes { get; }
public virtual string PrefixFuncName { get; } = "Prefix";
public virtual string PostfixFuncName { get; } = "Postfix";
}
}
| 32.333333 | 67 | 0.659794 | [
"MIT"
] | Kasuromi/Yggdrasil | Yggdrasil/Models/YggdrasilPatch.cs | 390 | C# |
#region Copyright
//=======================================================================================
// Microsoft Azure Customer Advisory Team
//
// This sample is supplemental to the technical guidance published on my personal
// blog at http://blogs.msdn.com/b/paolos/.
//
// Author: Paolo Salvatori
//=======================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE
// FILES 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.
//=======================================================================================
#endregion
#region Using Directives
using System;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
#endregion
namespace Microsoft.WindowsAzure.CAT.ServiceBusExplorer
{
public partial class CollectionEditorForm : Form
{
#region Private Constants
//***************************
// Constants
//***************************
private const string DefaultLabel = "Value";
#endregion
#region Public Constructor
public CollectionEditorForm(string text, string groupTitle, object value)
{
InitializeComponent();
Text = text;
Value = value;
grouperCaption.GroupTitle = string.IsNullOrWhiteSpace(groupTitle) ? DefaultLabel : groupTitle;
// Initialize bindingSource
bindingSource.DataSource = Value;
// Initialize the DataGridView.
dataGridView.AutoGenerateColumns = true;
dataGridView.AutoSize = true;
dataGridView.DataSource = bindingSource;
dataGridView.ForeColor = SystemColors.WindowText;
//// Create the Name column
//textBoxColumn = new DataGridViewTextBoxColumn
//{
// DataPropertyName = HeaderName,
// Name = HeaderName,
// Width = 80
//};
//dataGridView.Columns.Add(textBoxColumn);
//// Create the Value column
//textBoxColumn = new DataGridViewTextBoxColumn
//{
// DataPropertyName = HeaderValue,
// Name = HeaderValue,
// Width = 150
//};
//dataGridView.Columns.Add(textBoxColumn);
// Set Grid style
dataGridView.EnableHeadersVisualStyles = false;
//dataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
// Set the selection background color for all the cells.
dataGridView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(92, 125, 150);
dataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;
// Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
// value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
dataGridView.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(153, 180, 209);
// Set the background color for all rows and for alternating rows.
// The value for alternating rows overrides the value for all rows.
dataGridView.RowsDefaultCellStyle.BackColor = SystemColors.Window;
dataGridView.RowsDefaultCellStyle.ForeColor = SystemColors.ControlText;
// Set the row and column header styles.
dataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
dataGridView.RowHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;
dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;
}
#endregion
#region Event Handlers
private void btnOk_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Value = null;
Close();
}
private void button_MouseEnter(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
control.ForeColor = Color.White;
}
}
private void button_MouseLeave(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
control.ForeColor = SystemColors.ControlText;
}
}
private void grouperCaption_CustomPaint(PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(SystemColors.ActiveBorder, 1),
dataGridView.Location.X - 1,
dataGridView.Location.Y - 1,
dataGridView.Size.Width + 1,
dataGridView.Size.Height + 1);
}
private void dataGridView_Resize(object sender, EventArgs e)
{
CalculateColumnWidth();
}
private void dataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
CalculateColumnWidth();
}
private void dataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
CalculateColumnWidth();
}
#endregion
#region Public Properties
public override sealed string Text
{
get { return base.Text; }
set { base.Text = value; }
}
public object Value { get; set; }
#endregion
#region Private Methods
private void CalculateColumnWidth()
{
if (dataGridView.Columns.Count == 0)
{
return;
}
var width = dataGridView.Width - dataGridView.RowHeadersWidth;
var verticalScrollbar = dataGridView.Controls.OfType<VScrollBar>().First();
if (verticalScrollbar.Visible)
{
width -= verticalScrollbar.Width;
}
var columnWith = width/dataGridView.Columns.Count;
for (var i = 0; i < dataGridView.Columns.Count; i++)
{
dataGridView.Columns[i].Width = i == 0 ? columnWith + (width - (columnWith * dataGridView.Columns.Count)) : columnWith;
}
}
private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
#endregion
}
}
| 37.283505 | 135 | 0.577216 | [
"Apache-2.0"
] | HydAu/ServiceBusExplorer | Forms/CollectionEditorForm.cs | 7,235 | C# |
using System;
using System.Linq;
using System.Windows;
using Microsoft.Extensions.Logging;
using MonBand.Core.Util.Threading;
using MonBand.Windows.Bootstrap;
using MonBand.Windows.Services;
using MonBand.Windows.Standalone.UI;
namespace MonBand.Windows.Standalone
{
public partial class App
{
readonly LogLevelSignal _logLevelSignal;
ILoggerFactory _loggerFactory;
ILogger _log;
public App()
{
this._logLevelSignal = new LogLevelSignal();
}
protected override void OnStartup(StartupEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
try
{
base.OnStartup(e);
var appSettingsService = new AppSettingsService();
var processSignal = new CrossProcessSignal(IAppSettingsService.ReloadEventName);
if (e.Args.FirstOrDefault() == "deskband-test")
{
this._loggerFactory = LoggerConfiguration.CreateLoggerFactory(
LogLevel.Information,
appSettingsService.GetLogFilePath("DeskbandTest"),
this._logLevelSignal);
this._log = this._loggerFactory.CreateLogger(this.GetType().Name);
this.MainWindow = new DeskbandTestWindow(
this._loggerFactory,
this._logLevelSignal,
appSettingsService,
processSignal);
}
else
{
this._loggerFactory = LoggerConfiguration.CreateLoggerFactory(
LogLevel.Information,
appSettingsService.GetLogFilePath("Settings"),
this._logLevelSignal);
this._log = this._loggerFactory.CreateLogger(this.GetType().Name);
this.MainWindow = new SettingsWindow(
this._loggerFactory,
this._logLevelSignal,
appSettingsService,
processSignal);
}
this.MainWindow.Show();
}
catch (Exception ex)
{
this._log.LogError(ex, "MonBand initialization failed");
MessageBox.Show(
ex.Message,
"MonBand initialization failed",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
}
| 34.0375 | 97 | 0.502754 | [
"MIT"
] | rwasef1830/MonBand | src/MonBand.Windows.Standalone/App.xaml.cs | 2,725 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AntMerchantExpandAssetinfoDeliverySyncModel Data Structure.
/// </summary>
public class AntMerchantExpandAssetinfoDeliverySyncModel : AlipayObject
{
/// <summary>
/// 传入需要反馈的物料信息对象列表。
/// </summary>
[JsonPropertyName("asset_infos")]
public List<AssetInfoItem> AssetInfos { get; set; }
}
}
| 27.777778 | 75 | 0.678 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AntMerchantExpandAssetinfoDeliverySyncModel.cs | 534 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using AgGateway.ADAPT.ISOv4Plugin.ImportMappers.LogMappers.XmlReaders;
using AgGateway.ADAPT.ISOv4Plugin.Models;
using AgGateway.ADAPT.ISOv4Plugin.ObjectModel;
using Moq;
using NUnit.Framework;
namespace ISOv4PluginLogTest.ImportMappers.LogMappers.XmlReaders
{
[TestFixture]
public class TimReaderTest
{
private Mock<IPtnReader> _ptnReaderMock;
private Mock<IDlvReader> _dlvReaderMock;
private TimReader _timReader;
private MemoryStream _memStream;
[SetUp]
public void Setup()
{
_ptnReaderMock = new Mock<IPtnReader>();
_dlvReaderMock = new Mock<IDlvReader>();
_timReader = new TimReader(_ptnReaderMock.Object, _dlvReaderMock.Object);
}
[Test]
public void GivenXdocumentWhenReadThenStartTimeIsMapped()
{
var a = new DateTime(2015, 05, 15);
CreateTimMemStream("A", a.ToString(CultureInfo.InvariantCulture));
var xpathDoc = CreateXDoc();
var result = _timReader.Read(xpathDoc).First();
Assert.AreEqual(a, Convert.ToDateTime(result.A.Value));
}
[Test]
public void GivenXdocumentWhenReadThenStopIsMapped()
{
var b = new DateTime(2015, 05, 15);
CreateTimMemStream("B", b.ToString(CultureInfo.InvariantCulture));
var xpathDoc = CreateXDoc();
var result = _timReader.Read(xpathDoc).First();
Assert.AreEqual(b, Convert.ToDateTime(result.B.Value));
}
[Test]
public void GivenXdocumentWhenReadThenDurationIsMapped()
{
var c = 1500;
CreateTimMemStream("C", c.ToString(CultureInfo.InvariantCulture));
var xpathDoc = CreateXDoc();
var result = _timReader.Read(xpathDoc).First();
Assert.AreEqual(c, result.C.Value);
}
[Test]
public void GivenXdocumentWhenReadThenTypeIsMapped()
{
var d = TIMD.Item4;
CreateTimMemStream("D", d.ToString());
var xpathDoc = CreateXDoc();
var result = _timReader.Read(xpathDoc).First();
Assert.AreEqual(d, result.D.Value);
}
[Test]
public void GivenXdocumentWhenReadThenPtnHeaderIsMapped()
{
_memStream = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
xmlWriter.WriteStartElement("TIM");
xmlWriter.WriteStartElement("PTN");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();
}
var xpathDoc = CreateXDoc();
var ptn = new PTN();
_ptnReaderMock.Setup(x => x.Read(It.IsAny<XPathNodeIterator>())).Returns(new List<PTN> {ptn});
var result = _timReader.Read(xpathDoc).First();
var ptnResult = result.Items[0];
Assert.AreSame(ptn, ptnResult);
}
[Test]
public void GivenXdocumentWhenReadThenDlvsAreMapped()
{
_memStream = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
xmlWriter.WriteStartElement("TIM");
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();
}
var xpathDoc = CreateXDoc();
var dlvs = new List<DLV> { new DLV(), new DLV(), new DLV() };
_dlvReaderMock.Setup(x => x.Read(It.Is<XPathNodeIterator>( y => y.Count == 3))).Returns(dlvs);
var result = _timReader.Read(xpathDoc).First();
Assert.AreSame(dlvs[0], result.Items[0]);
Assert.AreSame(dlvs[1], result.Items[1]);
Assert.AreSame(dlvs[2], result.Items[2]);
}
[Test]
public void GivenXdocumentWhenReadThenDlvAndPtnsAreMapped()
{
_memStream = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
xmlWriter.WriteStartElement("TIM");
xmlWriter.WriteStartElement("PTN");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("DLV");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();
}
var xpathDoc = CreateXDoc();
var ptn = new PTN();
_ptnReaderMock.Setup(x => x.Read(It.IsAny<XPathNodeIterator>())).Returns(new List<PTN> { ptn });
var dlvs = new List<DLV> { new DLV(), new DLV(), new DLV() };
_dlvReaderMock.Setup(x => x.Read(It.Is<XPathNodeIterator>(y => y.Count == 3))).Returns(dlvs);
var result = _timReader.Read(xpathDoc).First();
Assert.AreSame(ptn, result.Items[0]);
Assert.AreSame(dlvs[0], result.Items[1]);
Assert.AreSame(dlvs[1], result.Items[2]);
Assert.AreSame(dlvs[2], result.Items[3]);
}
//todo both ptn and dlvs test
[Test]
public void GivenXdocumentWithoutTimWhenReadThenIsNull()
{
_memStream = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
xmlWriter.WriteStartElement("NOTTIM");
xmlWriter.WriteAttributeString("A", "AValue");
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();
}
var xDocument = CreateXDoc();
var result = _timReader.Read(xDocument);
Assert.IsNull(result);
}
private void CreateTimMemStream(string attributeName, string attributeValue)
{
_memStream = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(_memStream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
xmlWriter.WriteStartElement("TIM");
xmlWriter.WriteAttributeString(attributeName, attributeValue);
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();
}
}
private XPathDocument CreateXDoc()
{
_memStream.Position = 0;
var xpathDoc = new XPathDocument(_memStream);
return xpathDoc;
}
}
}
| 34.981308 | 126 | 0.576009 | [
"EPL-1.0"
] | ADAPT/ISOv4Plugin | ISOv4PluginLogTest/ImportMappers/LogMappers/XmlReaders/TimReaderTest.cs | 7,488 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NiXnetTestApp.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute( "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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;
}
}
}
}
| 33.903226 | 152 | 0.591817 | [
"Apache-2.0"
] | CAN-YJ/ni-xnet-dot-net | NiXnetTestApp/Properties/Settings.Designer.cs | 1,053 | C# |
using System;
using System.Collections.Generic;
using Xunit;
using Carambolas.Net.Tests.Attributes;
namespace Carambolas.Net.Tests
{
public class MemoryTests
{
[Fact]
public void Disposal()
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
var version = m.Version;
m.Dispose();
Assert.NotEqual(version, m.Version);
Assert.Equal(0, m.Capacity);
Assert.Equal(0, m.Length);
}
[Fact]
public void InitialCapacity()
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
Assert.Equal(0, m.Capacity);
}
[Fact]
public void InitialLength()
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
Assert.Equal(0, m.Length);
}
[Theory]
[InlineData(3, 64)]
[InlineData(251, 256)]
[InlineData(1021, 1024)]
[InlineData(3071, 3072)]
[InlineData(60001, 65536)]
public void SetLength(int expectedLength, int expectedCapacity)
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
m.Length = expectedLength;
Assert.Equal(expectedLength, m.Length);
Assert.Equal(expectedCapacity, m.Capacity);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(16)]
[InlineData(64)]
[InlineData(512)]
[InlineData(1024)]
[InlineData(4096)]
[InlineData(65536)]
public void CopyFromAndTo(int length)
{
var source = new byte[length];
var destination = new byte[length];
var expected = new byte[length];
for (int i = 0; i < length; ++i)
expected[i] = source[i] = (byte)i;
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
m.CopyFrom(source);
Assert.Equal(expected, source);
m.CopyTo(destination);
Assert.Equal(new ArraySegment<byte>(expected, 0, length) as IEnumerable<byte>, new ArraySegment<byte>(destination, 0, length) as IEnumerable<byte>);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(70001)]
public void InvalidGetterIndexFails(int index)
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
Assert.Throws<ArgumentOutOfRangeException>(() => { var x = m[index]; });
}
[Theory]
[InlineData(-1)]
[InlineData(70000)]
public void InvalidSetterIndexFails(int index)
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
Assert.Throws<ArgumentOutOfRangeException>(() => m[index] = 0);
}
[Theory]
[InlineData(0, 1, 2, 3, 4, 64)]
[InlineData(0, 1, 2, 250, 251, 256)]
[InlineData(0, 1, 2, 1020, 1021, 1024)]
[InlineData(0, 1, 2, 3070, 3071, 3072)]
[InlineData(0, 1, 2, 60001, 60002, 65536)]
public void ValidGetterSetterIndexes(int i0, int i1, int i2, int i3, int expectedLength, int expectedCapacity)
{
var pool = new Carambolas.Net.Memory.Pool();
var m = pool.Get();
m[i0] = (byte)i0;
m[i1] = (byte)i1;
m[i2] = (byte)i2;
Assert.Equal(3, m.Length);
Assert.Equal(64, m.Capacity);
m[i3] = (byte)i3;
Assert.Equal(expectedLength, m.Length);
Assert.Equal(expectedCapacity, m.Capacity);
Assert.Equal((byte)i0, m[i0]);
Assert.Equal((byte)i1, m[i1]);
Assert.Equal((byte)i2, m[i2]);
Assert.Equal((byte)i3, m[i3]);
}
}
}
| 28.528571 | 160 | 0.512268 | [
"MIT"
] | nlebedenco/Carambolas | Carambolas.Net.Tests/MemoryTests.cs | 3,996 | C# |
using System;
using System.Globalization;
using System.Threading;
namespace InclusionList
{
/// <summary>
/// Demonstrate the exchange of an inclusion list.
/// </summary>
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine("Bring the system to On mode and start an acquisition with a PRM experiment to replace the inclusion list.");
Console.WriteLine("Check the scans later in the generated rawfile.");
new ReplaceInclList().DoJob();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
| 25.16 | 130 | 0.72655 | [
"MIT"
] | thermofisherlsms/iapi | docs/exactive/6 InclusionList/InclusionList/Program.cs | 631 | C# |
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Mvc.Client.Controllers
{
public class HomeController : Controller
{
private readonly HttpClient _client;
public HomeController(HttpClient client)
{
_client = client;
}
[HttpGet("~/")]
public ActionResult Index()
{
return View("Home");
}
[Authorize, HttpPost("~/")]
public async Task<ActionResult> Index(CancellationToken cancellationToken)
{
var token = await HttpContext.GetTokenAsync(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectParameterNames.AccessToken);
if (string.IsNullOrEmpty(token))
{
throw new InvalidOperationException("The access token cannot be found in the authentication ticket. " +
"Make sure that SaveTokens is set to true in the OIDC options.");
}
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:54540/api/message");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await _client.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return View("Home", model: await response.Content.ReadAsStringAsync());
}
}
} | 35.625 | 148 | 0.661404 | [
"Apache-2.0"
] | Amialc/openiddict-core | samples/Mvc.Client/Controllers/HomeController.cs | 1,712 | C# |
namespace ODMIdentity.STS.Identity.Configuration.Intefaces
{
public interface IRootConfiguration
{
IAdminConfiguration AdminConfiguration { get; }
IRegisterConfiguration RegisterConfiguration { get; }
}
} | 26 | 61 | 0.735043 | [
"MIT"
] | omikolaj/IdentityServer4-Admin | ODMIdentity/src/ODMIdentity.STS.Identity/Configuration/Intefaces/IRootConfiguration.cs | 236 | 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 OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadValue
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadValue : TCXMLReaderBaseGeneral
{
public const String ST_TEST_NAME = "CHARS1";
public const String ST_GEN_ENT_NAME = "e1";
public const String ST_GEN_ENT_VALUE = "e1foo";
private bool VerifyInvalidReadValue(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
Char[] buffer = new Char[iBufferSize];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return bPassed;
}
catch (NotSupportedException)
{
return true;
}
}
try
{
DataReader.ReadValueChunk(buffer, iIndex, iCount);
}
catch (Exception e)
{
CError.WriteLine("Actual exception:{0}", e.GetType().ToString());
CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
bPassed = (e.GetType().ToString() == exceptionType.ToString());
}
return bPassed;
}
[Variation("ReadValue", Pri = 0)]
public int TestReadValuePri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didn't read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue on Element", Pri = 0)]
public int TestReadValuePri0onElement()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
}
catch (InvalidOperationException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on Attribute", Pri = 0)]
public int TestReadValueOnAttribute0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root name=\"value\">value</root>"));
DataReader.PositionOnElement("root");
DataReader.MoveToNextAttribute(); //This takes to text node of attribute.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars");
return TEST_PASS;
}
[Variation("ReadValue on Attribute after ReadAttributeValue", Pri = 2)]
public int TestReadValueOnAttribute1()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root name=\"value\">value</root>"));
DataReader.PositionOnElement("root");
DataReader.MoveToNextAttribute(); //This takes to text node of attribute.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadAttributeValue(), true, "Didnt read attribute value");
CError.Compare(DataReader.Value, "value", "Didnt read correct attribute value");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars");
CError.WriteLineIgnore(DataReader.MoveToElement() + "");
DataReader.Read();
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars on text node");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars on text node");
return TEST_PASS;
}
[Variation("ReadValue on empty buffer", Pri = 0)]
public int TestReadValue2Pri0()
{
char[] buffer = new char[0];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
}
catch (ArgumentException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on negative count", Pri = 0)]
public int TestReadValue3Pri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, -1);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, -1);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on negative offset", Pri = 0)]
public int TestReadValue4Pri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, -1, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, -1, 5);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue with buffer = element content / 2", Pri = 0)]
public int TestReadValue1()
{
Char[] buffer = new Char[5];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read first 5");
CError.Compare("01234", new string(buffer), "First strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read second 5 chars");
CError.Compare("56789", new string(buffer), "Second strings don't match");
return TEST_PASS;
}
[Variation("ReadValue entire value in one call", Pri = 0)]
public int TestReadValue2()
{
Char[] buffer = new Char[10];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 10), 10, "Didnt read 10");
CError.Compare("0123456789", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue bit by bit", Pri = 0)]
public int TestReadValue3()
{
Char[] buffer = new Char[10];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare("0123456789", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue for value more than 4K", Pri = 0)]
public int TestReadValue4()
{
int size = 8192;
Char[] buffer = new Char[size];
string val = new string('x', size);
ReloadSource(new StringReader("<root>" + val + "</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare(val, new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue for value more than 4K and invalid element", Pri = 1)]
public int TestReadValue5()
{
int size = 8192;
Char[] buffer = new Char[size];
string val = new string('x', size);
if (IsRoundTrippedReader())
return TEST_SKIPPED;
ReloadSource(new StringReader("<root>" + val + "</notroot>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare(val, new string(buffer), "Strings don't match");
try
{
DataReader.Read();
return TEST_FAIL;
}
catch (XmlException)
{
return TEST_PASS;
}
}
[Variation("ReadValue with count > buffer size")]
public int TestReadValue7()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with index > buffer size")]
public int TestReadValue8()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with index + count exceeds buffer")]
public int TestReadValue10()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 2, 5, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with combination Text, CDATA and Whitespace")]
public int TestReadChar11()
{
string strExpected = "AB";
ReloadSource();
DataReader.PositionOnElement("CAT");
DataReader.Read();
char[] buffer = new char[strExpected.Length];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
[Variation("ReadValue with combination Text, CDATA and SignificantWhitespace")]
public int TestReadChar12()
{
string strExpected = "AB";
ReloadSource();
DataReader.PositionOnElement("CATMIXED");
DataReader.Read();
char[] buffer = new char[strExpected.Length];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
[Variation("ReadValue with buffer == null")]
public int TestReadChar13()
{
ReloadSource();
DataReader.PositionOnElement("CHARS1");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(null, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(null, 0, 0);
}
catch (ArgumentNullException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadValue with multiple different inner nodes")]
public int TestReadChar14()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue<![CDATA[somevalue]]>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue1");
CError.Compare(new string(buffer), strExpected, "str1");
DataReader.Read();//Now on CDATA.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue2");
CError.Compare(new string(buffer), strExpected, "str2");
DataReader.Read();//Now back on Text
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue3");
CError.Compare(new string(buffer), strExpected, "str3");
return TEST_PASS;
}
[Variation("ReadValue after failed ReadValue")]
public int TestReadChar15()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int nChars;
try
{
nChars = DataReader.ReadValueChunk(buffer, strExpected.Length, 3);
}
catch (ArgumentException)
{
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue Count");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
CError.WriteLine("Couldnt read after ArgumentException");
return TEST_FAIL;
}
[Variation("Read after partial ReadValue")]
public int TestReadChar16()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int nChars = DataReader.ReadValueChunk(buffer, 0, 2);
CError.Compare(nChars, 2, "Read 2");
DataReader.Read();
CError.Compare(DataReader.VerifyNode(XmlNodeType.EndElement, "ROOT", String.Empty), "1vn");
return TEST_PASS;
}
[Variation("Test error after successful ReadValue")]
public int TestReadChar19()
{
if (IsRoundTrippedReader() || IsSubtreeReader()) return TEST_SKIPPED;
Char[] buffer = new Char[9];
ReloadSource(new StringReader("<root>somevalue</root></root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare("somevalue", new string(buffer), "Strings don't match");
try
{
while (DataReader.Read()) ;
}
catch (XmlException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("Call on invalid element content after 4k boundary", Pri = 1, Params = new object[] { false, 1024 * 4})]
//[Variation("Call on invalid element content after 64k boundary for Async", Pri = 1, Params = new object[] { true, 1024 * 64 })]
public int TestReadChar21()
{
if (IsRoundTrippedReader()) return TEST_SKIPPED;
bool forAsync = (bool)CurVariation.Params[0];
if (forAsync != AsyncUtil.IsAsyncEnabled)
return TEST_SKIPPED;
int size = (int)CurVariation.Params[1];
string somechar = new string('x', size);
string strxml = String.Format("<ROOT>a" + somechar + "{0}c</ROOT>", Convert.ToChar(0));
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
char[] buffer = new char[1];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
DataReader.Read();
try
{
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
}
catch (XmlException xe)
{
CError.WriteLineIgnore(xe.ToString());
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadValue with whitespaces")]
public int TestTextReadValue25()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue<![CDATA[somevalue]]><test1/> <test2/></ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue1");
CError.Compare(new string(buffer), strExpected, "str1");
DataReader.Read();//Now on CDATA.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue2");
CError.Compare(new string(buffer), strExpected, "str2");
DataReader.Read();//Now on test
char[] spaces = new char[4];
DataReader.Read();//Now on whitespace.
CError.Compare(DataReader.ReadValueChunk(spaces, 0, spaces.Length), spaces.Length, "ReadValue3");
CError.Compare(new string(spaces), " ", "str3");
return TEST_PASS;
}
[Variation("ReadValue when end tag doesn't exist")]
public int TestTextReadValue26()
{
if (IsRoundTrippedReader()) return TEST_SKIPPED;
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</notroot>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
try
{
DataReader.Read();
return TEST_FAIL;
}
catch (XmlException)
{
return TEST_PASS;
}
}
[Variation("Testing with character entities")]
public int TestCharEntities0()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<root>va</root>lue</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing with character entities when value more than 4k")]
public int TestCharEntities1()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<root>va" + new string('x', 5000) + "l</root>ue</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing with character entities with another pattern")]
public int TestCharEntities2()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<!DOCTYPE root[<!ENTITY x \"somevalue\"><!ELEMENT root ANY>]><root>value&x;</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing a usecase pattern with large file")]
public int TestReadValueOnBig()
{
ReloadSource();
char[] buffer = new char[1];
while (DataReader.Read())
{
if (DataReader.HasValue && DataReader.CanReadValueChunk)
{
Random rand = new Random();
if (rand.Next(1) == 1)
{
CError.WriteLineIgnore(DataReader.Value);
}
int count;
do
{
count = rand.Next(4) + 1;
buffer = new char[count];
if (rand.Next(1) == 1)
{
CError.WriteLineIgnore(DataReader.Value);
break;
}
}
while (DataReader.ReadValueChunk(buffer, 0, count) > 0);
CError.WriteLineIgnore(DataReader.Value);
}
else
{
if (!DataReader.CanReadValueChunk)
{
try
{
buffer = new char[1];
DataReader.ReadValueChunk(buffer, 0, 1);
}
catch (NotSupportedException)
{
}
}
else
{
try
{
buffer = new char[1];
DataReader.ReadValueChunk(buffer, 0, 1);
}
catch (InvalidOperationException)
{
}
}
}
}
return TEST_PASS;
}
[Variation("ReadValue on Comments with IgnoreComments")]
public int TestReadValueOnComments0()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
char[] buffer = null;
buffer = new char[3];
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
MyDict<string, object> ht = new MyDict<string, object>();
ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<!--Comment-->ue</root>");
ht[ReaderFactory.HT_READERSETTINGS] = settings;
ReloadSource(ht);
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars");
CError.Compare("val", new string(buffer), "Strings don't match");
buffer = new char[2];
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars");
CError.Compare("ue", new string(buffer), "Strings don't match");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("ReadValue on PI with IgnorePI")]
public int TestReadValueOnPIs0()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
char[] buffer = null;
buffer = new char[3];
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreProcessingInstructions = true;
MyDict<string, object> ht = new MyDict<string, object>();
ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<?pi target?>ue</root>");
ht[ReaderFactory.HT_READERSETTINGS] = settings;
ReloadSource(ht);
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars");
CError.Compare("val", new string(buffer), "Strings don't match");
buffer = new char[2];
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars");
CError.Compare("ue", new string(buffer), "Strings don't match");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Skip after ReadAttributeValue/ReadValueChunk")]
public int SkipAfterReadAttributeValueAndReadValueChunkDoesNotThrow()
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XmlReader reader = XmlReader.Create(FilePathUtil.getStream(this.StandardPath + @"\XML10\ms_xml\vs084.xml"), settings);
reader.ReadToFollowing("a");
reader.MoveToNextAttribute();
reader.ReadAttributeValue();
reader.ReadValueChunk(new char[3], 0, 3); //<< removing this line works fine.
reader.Skip();
CError.Compare(reader.NodeType, XmlNodeType.Whitespace, "NT");
reader.Read();
CError.Compare(reader.NodeType, XmlNodeType.Element, "NT1");
CError.Compare(reader.Name, "a", "Name");
return TEST_PASS;
}
[Variation("ReadValueChunk - doesn't work correctly on attributes")]
public int ReadValueChunkDoesWorkProperlyOnAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = @"<root a1='12345' a2='value'/>";
ReloadSource(new StringReader(xml));
Char[] buffer = new Char[10];
CError.Compare(DataReader.Read(), "Read");
CError.Compare(DataReader.MoveToNextAttribute(), "MoveToNextAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer1");
CError.Compare(buffer[1].ToString(), "2", "buffer1");
CError.Compare(buffer[2].ToString(), "3", "buffer1");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
CError.Compare(DataReader.MoveToNextAttribute(), "MoveToNextAttribute");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer2");
CError.Compare(buffer[1].ToString(), "2", "buffer2");
CError.Compare(buffer[2].ToString(), "3", "buffer2");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
return TEST_PASS;
}
[Variation("ReadValueChunk - doesn't work correctly on special attributes")]
public int ReadValueChunkDoesWorkProperlyOnSpecialAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = @"<?xml version='1.0'?><root/>";
ReloadSource(new StringReader(xml));
Char[] buffer = new Char[10];
CError.Compare(DataReader.Read(), "Read");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.Name, "version", "Name");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer1");
CError.Compare(buffer[1].ToString(), ".", "buffer1");
CError.Compare(buffer[2].ToString(), "0", "buffer1");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
CError.Compare(DataReader.MoveToElement(), "MoveToElement");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer2");
CError.Compare(buffer[1].ToString(), ".", "buffer2");
CError.Compare(buffer[2].ToString(), "0", "buffer2");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
return TEST_PASS;
}
[Variation("SubtreeReader inserted attributes don't work with ReadValueChunk")]
public int ReadValueChunkWorksProperlyWithSubtreeReaderInsertedAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = "<root xmlns='foo'><bar/></root>";
ReloadSource(new StringReader(xml));
DataReader.Read();
DataReader.Read();
using (XmlReader sr = DataReader.ReadSubtree())
{
sr.Read();
sr.MoveToFirstAttribute();
CError.WriteLine("Value: " + sr.Value);
sr.MoveToFirstAttribute();
char[] chars = new char[100];
int i = sr.ReadValueChunk(chars, 0, 100);
CError.WriteLine("ReadValueChunk: length = " + i + " value = '" + new string(chars, 0, i) + "'");
}
return TEST_PASS;
}
[Variation("goto to text node, ask got.Value, ReadValueChunk")]
public int TestReadValue_1()
{
string xml = "<elem0>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
CError.Compare(DataReader.Value, "123", "value");
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 1), 1, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to text node, ReadValueChunk, ask got.Value")]
public int TestReadValue_2()
{
string xml = "<elem0>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 1), 1, "size");
CError.Compare(DataReader.Value, "23", "value");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node, read several chars with ReadValueChank and Move forward with .Read()")]
public int TestReadValue_3()
{
string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 5), 5, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Read();
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node with invalid chars, read several chars with ReadValueChank and Move forward with .Read()")]
public int TestReadValue_4()
{
string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 5), 5, "size");
DataReader.Read();
}
catch (XmlException e) { CError.WriteLine(e); }
catch (NotSupportedException e) { CError.WriteLine(e); }
finally
{
DataReader.Close();
}
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes")]
public int TestReadValue_5()
{
string xml = "<elem0>123<elem1>123<elem2>123</elem2>123</elem1>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(chars[0].ToString(), "1", "buffer1");
CError.Equals(chars[1].ToString(), "2", "buffer2");
CError.Equals(chars[2].ToString(), "3", "buffer3");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
DataReader.Close();
return TEST_PASS;
}
//[Variation("ReadValueChunk on an xmlns attribute", Param = "<foo xmlns='default'> <bar > id='1'/> </foo>")]
//[Variation("ReadValueChunk on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")]
//[Variation("ReadValueChunk on an xml:space attribute", Param = "<foo xml:space='default'> <bar > id='1'/> </foo>")]
//[Variation("ReadValueChunk on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>")]
public int TestReadValue_6()
{
string xml = (string)this.CurVariation.Param;
ReloadSource(new StringReader(xml));
char[] chars = new char[8];
DataReader.Read();
DataReader.MoveToAttribute(0);
try
{
CError.Equals(DataReader.Value, "default", "value");
CError.Equals(DataReader.ReadValueChunk(chars, 0, 8), 7, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes and whitespace")]
public int TestReadValue_7()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
try
{
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes and whitespace after call Value")]
public int TestReadValue_8()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
try
{
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
CError.Equals(DataReader.Value.Contains("123"), "Value");
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
}
}
| 35.890555 | 137 | 0.504616 | [
"MIT"
] | FrancisFYK/corefx | src/System.Private.Xml/tests/XmlReaderLib/ReadValue.cs | 47,878 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BTL_CaPhe.User
{
public partial class User : Form
{
private string sMaNV;
private string sTenNV;
public User()
{
InitializeComponent();
UserControl gioithieu = new GioiThieu();
this.Text = "Xin Chào " + this.sTenNV;
loadPanel(gioithieu);
}
public User(string sMaNV, string sTenNV)
{
this.sMaNV = sMaNV;
this.sTenNV = sTenNV;
InitializeComponent();
UserControl gioithieu = new GioiThieu();
this.Text = "Xin Chào " + this.sTenNV;
loadPanel(gioithieu);
}
private void btnLapHD_Click(object sender, EventArgs e)
{
UserControl laphoadon = new LapHD(this.sMaNV, this.sTenNV);
loadPanel(laphoadon);
}
private void loadPanel(System.Windows.Forms.Control obj)
{
pnUser.Controls.Clear();
obj.Dock = DockStyle.Fill;
pnUser.Controls.Add(obj);
}
private void btnThongTin_Click(object sender, EventArgs e)
{
UserControl thongtincanhan = new QuanLyThongTin(this.sMaNV);
loadPanel(thongtincanhan);
}
private void BtnLogout_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnKhachHang_Click(object sender, EventArgs e)
{
}
}
}
| 26.109375 | 72 | 0.582286 | [
"MIT"
] | thanhpcc96/HuongSuKienC- | BTL CaPhe/User/User.cs | 1,675 | C# |
// The MIT License(MIT)
//
// Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors
//
// 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.
namespace LiveChartsCore.Drawing
{
/// <summary>
/// Defines a sized visual chart point.
/// </summary>
/// <typeparam name="TDrawingContext">The type of the drawing context.</typeparam>
/// <seealso cref="ISizedGeometry{TDrawingContext}" />
/// <seealso cref="IVisualChartPoint{TDrawingContext}" />
public interface ISizedVisualChartPoint<TDrawingContext> : ISizedGeometry<TDrawingContext>, IVisualChartPoint<TDrawingContext>
where TDrawingContext : DrawingContext
{ }
}
| 48.228571 | 130 | 0.75 | [
"MIT"
] | hefan1/LiveCharts2 | src/LiveChartsCore/Drawing/ISizedVisualChartPoint.cs | 1,690 | C# |
using Prism.Commands;
using Prism.Events;
using Prism.Interactivity.InteractionRequest;
using Prism.Regions;
using QIQO.Business.Client.Contracts;
using QIQO.Business.Client.Core;
using QIQO.Business.Client.Core.Infrastructure;
using QIQO.Business.Client.Core.UI;
using QIQO.Business.Client.Entities;
using QIQO.Business.Client.Wrappers;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Transactions;
using Unity.Interception.Utilities;
namespace QIQO.Business.Module.Orders.ViewModels
{
public class OrderViewModel : ViewModelBase, IRegionMemberLifetime, IConfirmNavigationRequest, IInteractionRequestAware
{
private readonly IEventAggregator event_aggregator;
private readonly IServiceFactory service_factory;
private readonly IProductListService _product_service;
private readonly IRegionManager region_manager;
private readonly IReportService report_service;
private OrderWrapper _order;
private Client.Entities.Account _currentAccount;
private object _selected_order_item;
private AddressWrapper _ship_address;
private AddressWrapper _bill_address;
private ObservableCollection<Product> _productlist;
private ObservableCollection<Representative> _accountreps;
private ObservableCollection<Representative> _salesreps;
private ObservableCollection<FeeSchedule> _feeschedulelist;
private ObservableCollection<AccountPerson> _account_contacts;
private string _viewTitle = ApplicationStrings.TabTitleNewOrder;
private bool _grid_enabled = true;
private ItemEditNotification notification;
public OrderViewModel(IEventAggregator event_aggtr, IServiceFactory service_fctry,
IProductListService product_service, IRegionManager region_mgr,
IReportService reportService) //
{
event_aggregator = event_aggtr;
service_factory = service_fctry;
_product_service = product_service;
region_manager = region_mgr;
report_service = reportService;
GetProductList();
BindCommands();
GetCompanyRepLists();
InitNewOrder();
RegisterApplicationCommands();
IsActive = true;
IsActiveChanged += OrderViewModel_IsActiveChanged;
event_aggregator.GetEvent<OrderUnloadingEvent>().Subscribe(ParentViewUnloadingEvent);
event_aggregator.GetEvent<OrderLoadedEvent>().Publish(string.Empty);
}
private void ParentViewUnloadingEvent(object obj)
{
var canClose = true;
var navContext = obj as NavigationContext;
if (navContext != null)
{
ConfirmNavigationRequest(navContext, result =>
{
canClose = result;
});
if (canClose)
{
OnNavigatedFrom(null);
}
}
}
private void OrderViewModel_IsActiveChanged(object sender, EventArgs e)
{
IsActive = true;
}
public bool KeepAlive
{
get
{
if (Order.IsChanged && Order.Account.AccountCode != null)
{
return true;
}
return false;
}
}
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
//********** Do some sort fo confirmation with the end user here
if (Order.IsChanged && !string.IsNullOrWhiteSpace(Order.Account.AccountCode))
{
var confirm = new Confirmation();
confirm.Title = ApplicationStrings.SaveChangesTitle;
confirm.Content = ApplicationStrings.SaveChangesPrompt;
SaveChangesConfirmationRequest.Raise(confirm,
r =>
{
if (r != null && r.Confirmed)
{
if (Order.IsValid)
{
DoSave();
continuationCallback(false);
}
continuationCallback(true);
}
else
{
continuationCallback(true);
}
});
}
else
{
continuationCallback(true);
}
}
//public bool KeepAlive => Order.IsChanged;
public OrderWrapper Order
{
get { return _order; }
private set { SetProperty(ref _order, value); }
}
public AddressWrapper DefaultBillingAddress
{
get { return _bill_address; }
private set { SetProperty(ref _bill_address, value); }
}
public AddressWrapper DefaultShippingAddress
{
get { return _ship_address; }
private set { SetProperty(ref _ship_address, value); }
}
public ObservableCollection<AccountPerson> AccountContacts
{
get { return _account_contacts; }
private set { SetProperty(ref _account_contacts, value); }
}
public ObservableCollection<Product> ProductList
{
get { return _productlist; }
private set { SetProperty(ref _productlist, value); }
}
public ObservableCollection<Representative> AccountRepList
{
get { return _accountreps; }
private set { SetProperty(ref _accountreps, value); }
}
public ObservableCollection<Representative> SalesRepList
{
get { return _salesreps; }
private set { SetProperty(ref _salesreps, value); }
}
public ObservableCollection<FeeSchedule> FeeScheduleList
{
get { return _feeschedulelist; }
private set { SetProperty(ref _feeschedulelist, value); }
}
public object SelectedOrderItem
{
get { return _selected_order_item; }
set
{
SetProperty(ref _selected_order_item, value);
InvalidateCommands();
}
}
public bool GridIsEnabled
{
get { return _grid_enabled; }
private set { SetProperty(ref _grid_enabled, value); }
}
public override string ViewTitle
{
get { return _viewTitle; }
protected set { SetProperty(ref _viewTitle, value); }
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
var paramAccountCode = navigationContext.Parameters.Where(item => item.Key == "AccountCode").FirstOrDefault();
var paramOrderNumber = navigationContext.Parameters.Where(item => item.Key == "OrderKey").FirstOrDefault();
if (paramAccountCode.Value != null)
{
Order.Account.AccountCode = (string)navigationContext.Parameters["AccountCode"];
GetAccount(Order.Account.AccountCode);
return;
}
if (paramOrderNumber.Value != null)
{
GetOrder((int)paramOrderNumber.Value);
return;
}
}
public override bool IsNavigationTarget(NavigationContext navigationContext)
{
//return true;
var paramAccountCode = navigationContext.Parameters.Where(item => item.Key == "AccountCode").FirstOrDefault();
var paramOrderNumber = navigationContext.Parameters.Where(item => item.Key == "OrderKey").FirstOrDefault();
return (paramAccountCode.Value != null || paramOrderNumber.Value != null) ? true : false;
//return navigationContext.Parameters.Conta ? true : false;
}
private void RegisterApplicationCommands()
{
ApplicationCommands.SaveOrderCommand.RegisterCommand(SaveCommand);
ApplicationCommands.DeleteOrderCommand.RegisterCommand(DeleteCommand);
ApplicationCommands.CancelOrderCommand.RegisterCommand(CancelCommand);
ApplicationCommands.PrintOrderCommand.RegisterCommand(PrintCommand);
}
public override void OnNavigatedFrom(NavigationContext navigationContext)
{
ApplicationCommands.SaveOrderCommand.UnregisterCommand(SaveCommand);
ApplicationCommands.DeleteOrderCommand.UnregisterCommand(DeleteCommand);
ApplicationCommands.CancelOrderCommand.UnregisterCommand(CancelCommand);
ApplicationCommands.PrintOrderCommand.UnregisterCommand(PrintCommand);
event_aggregator.GetEvent<OrderUnloadingEvent>().Unsubscribe(ParentViewUnloadingEvent);
}
public int SelectedOrderItemIndex { get; set; }
public DelegateCommand CancelCommand { get; set; }
public DelegateCommand SaveCommand { get; set; }
public DelegateCommand DeleteCommand { get; set; }
public DelegateCommand PrintCommand { get; set; }
public DelegateCommand<string> GetAccountCommand { get; set; }
public DelegateCommand<object> UpdateProdInfoCommand { get; set; }
public DelegateCommand UpdateItemTotalCommand { get; set; }
public DelegateCommand UpdateHeaderFromDetailCommand { get; set; }
public DelegateCommand NewOrderItemCommand { get; set; }
public DelegateCommand EditOrderItemCommand { get; set; }
public DelegateCommand DeleteOrderItemCommand { get; set; }
public DelegateCommand FindAccountCommand { get; set; }
public DelegateCommand NewAccountCommand { get; set; }
public InteractionRequest<ItemEditNotification> EditOrderItemRequest { get; set; }
public InteractionRequest<ItemSelectionNotification> FindAccountRequest { get; set; }
public InteractionRequest<IConfirmation> SaveChangesConfirmationRequest { get; set; }
public InteractionRequest<IConfirmation> DeleteConfirmationRequest { get; set; }
public INotification Notification
{
get { return notification; }
set
{
if (value is ItemEditNotification)
{
notification = value as ItemEditNotification;
var passed_object = notification.EditibleObject as OrderWrapper;
if (passed_object != null)
{
GetOrder(passed_object.OrderKey);
}
RaisePropertyChanged(nameof(Notification));
}
}
}
public Action FinishInteraction { get; set; }
//public bool KeepAlive => false;
protected override void DisplayErrorMessage(Exception ex, [CallerMemberName] string methodName = "")
{
event_aggregator.GetEvent<GeneralErrorEvent>().Publish(methodName + " - " + ex.Message);
}
protected void DisplayErrorMessage(string msg)
{
event_aggregator.GetEvent<GeneralErrorEvent>().Publish(msg);
}
private void InitNewOrder()
{
var new_order = new Order() //*** GET this initializatoin stuff into the objects themselves!! (complete)
{
OrderEntryDate = DateTime.Now,
OrderStatusDate = DateTime.Now,
DeliverByDate = DateTime.Now.AddDays(7), // think about a defaul lead time for each account
SalesRep = SalesRepList[0],
AccountRep = AccountRepList[0]
};
new_order.OrderItems.Add(InitNewOrderItem(1));
SelectedOrderItemIndex = 0;
Order = new OrderWrapper(new_order);
DefaultBillingAddress = new AddressWrapper(new Address());
DefaultShippingAddress = new AddressWrapper(new Address());
Order.PropertyChanged += Context_PropertyChanged;
Order.AcceptChanges();
GridIsEnabled = false;
}
private OrderItem InitNewOrderItem(int order_item_seq)
{
return new OrderItem()
{
//OrderItemSeq = order_item_seq,
SalesRep = SalesRepList[0],
AccountRep = AccountRepList[0]
};
}
private void GetOrder(int order_key)
{
ExecuteFaultHandledOperation(() =>
{
var order_service = service_factory.CreateClient<IOrderService>();
using (order_service)
{
Order = new OrderWrapper(order_service.GetOrder(order_key));
AccountContacts = new ObservableCollection<AccountPerson>(Order.Account.Model.Employees.Where(item =>
item.CompanyRoleType == QIQOPersonType.AccountContact).ToList());
Order.PropertyChanged += Context_PropertyChanged;
Order.AcceptChanges();
_currentAccount = Order.Account.Model;
}
DefaultBillingAddress = Order.OrderItems[0].OrderItemBillToAddress;
DefaultShippingAddress = Order.OrderItems[0].OrderItemShipToAddress;
ViewTitle = Order.OrderNumber;
GridIsEnabled = Order.OrderStatus != QIQOOrderStatus.Complete ? true : false;
//AccountContacts = new ObservableCollection<AccountPerson>(Order.Account.Model.Employees.Where(item =>
// item.CompanyRoleType == QIQOPersonType.AccountContact).ToList());
event_aggregator.GetEvent<GeneralMessageEvent>().Publish($"Order {Order.OrderNumber} loaded successfully");
event_aggregator.GetEvent<OrderLoadedEvent>().Publish(Order.OrderNumber);
});
}
private void GetCompanyRepLists()
{
var employee_service = service_factory.CreateClient<IEmployeeService>();
using (employee_service)
{
AccountRepList = new ObservableCollection<Representative>(employee_service.GetAccountRepsByCompany(CurrentCompanyKey));
SalesRepList = new ObservableCollection<Representative>(employee_service.GetSalesRepsByCompany(CurrentCompanyKey));
}
}
private void GetProductList()
{
ProductList = new ObservableCollection<Product>(_product_service.ProductList);
}
private void BindCommands()
{
CancelCommand = new DelegateCommand(DoCancel, CanDoCancel);
CancelCommand.IsActive = true;
SaveCommand = new DelegateCommand(DoSave, CanDoSave);
SaveCommand.IsActive = true;
DeleteCommand = new DelegateCommand(DoDelete, CanDoDelete);
DeleteCommand.IsActive = true;
PrintCommand = new DelegateCommand(DoPrint, CanDoDelete);
PrintCommand.IsActive = true;
GetAccountCommand = new DelegateCommand<string>(GetAccount, CanGetAccount);
UpdateProdInfoCommand = new DelegateCommand<object>(PopulateProductInfo);
UpdateItemTotalCommand = new DelegateCommand(UpdateItemTotals);
UpdateHeaderFromDetailCommand = new DelegateCommand(UpdateHeaderFromDetail);
NewOrderItemCommand = new DelegateCommand(AddOrderItem, CanAddOrderItem);
EditOrderItemCommand = new DelegateCommand(EditOrderItem, CanEditOrderItem);
DeleteOrderItemCommand = new DelegateCommand(DeleteOrderItem, CanDeleteOrderItem);
FindAccountCommand = new DelegateCommand(FindAccount);
NewAccountCommand = new DelegateCommand(NewAccount);
EditOrderItemRequest = new InteractionRequest<ItemEditNotification>();
FindAccountRequest = new InteractionRequest<ItemSelectionNotification>();
SaveChangesConfirmationRequest = new InteractionRequest<IConfirmation>();
DeleteConfirmationRequest = new InteractionRequest<IConfirmation>();
}
private void DoPrint()
{
report_service.ExecuteReport(Reports.Order, $"order_key={Order.OrderKey.ToString()}");
}
private void NewAccount()
{
region_manager.RequestNavigate(RegionNames.RibbonRegion, ViewNames.AccountRibbonView);
region_manager.RequestNavigate(RegionNames.ContentRegion, ViewNames.AccountView);
}
private bool CanDoCancel()
{
return Order.IsChanged;
}
private void DoCancel()
{
var confirm = new Confirmation();
confirm.Title = ApplicationStrings.ConfirmCancelTitle;
confirm.Content = ApplicationStrings.ConfirmCancelPrompt;
SaveChangesConfirmationRequest.Raise(confirm,
r =>
{
if (r != null && r.Confirmed)
{
InitNewOrder();
}
});
}
private bool CanDoDelete()
{
return Order.OrderKey > 0;
}
private void DoDelete()
{
var confirm = new Confirmation();
confirm.Title = ApplicationStrings.DeleteOrderTitle;
confirm.Content = $"Are you sure you want to delete order {Order.OrderNumber}?\n\nClick OK to delete. Click Cancel to return to the form.";
DeleteConfirmationRequest.Raise(confirm,
r =>
{
if (r != null && r.Confirmed)
{
DeleteOrder(Order.OrderNumber);
}
});
}
private void DeleteOrder(string order_number)
{
ExecuteFaultHandledOperation(() =>
{
var order_service = service_factory.CreateClient<IOrderService>();
using (var scope = new TransactionScope())
{
using (order_service)
{
var ret_val = order_service.DeleteOrder(Order.Model);
InitNewOrder();
ViewTitle = ApplicationStrings.TabTitleNewOrder;
event_aggregator.GetEvent<OrderDeletedEvent>().Publish($"Order {order_number} deleted successfully");
}
scope.Complete();
}
});
}
private void Context_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
InvalidateCommands();
}
private void InvalidateCommands()
{
SaveCommand.RaiseCanExecuteChanged();
DeleteCommand.RaiseCanExecuteChanged();
CancelCommand.RaiseCanExecuteChanged();
PrintCommand.RaiseCanExecuteChanged();
GetAccountCommand.RaiseCanExecuteChanged();
EditOrderItemCommand.RaiseCanExecuteChanged();
DeleteOrderItemCommand.RaiseCanExecuteChanged();
NewOrderItemCommand.RaiseCanExecuteChanged();
}
private void FindAccount()
{
var notification = new ItemSelectionNotification();
notification.Title = ApplicationStrings.NotificationFindAccount;
FindAccountRequest.Raise(notification,
r =>
{
if (r != null && r.Confirmed && r.SelectedItem != null)
{
var found_account = r.SelectedItem as Client.Entities.Account;
if (found_account != null)
{
GetAccount(found_account.AccountCode);
}
}
});
}
private bool CanDeleteOrderItem()
{
return (SelectedOrderItem != null && ((OrderItemWrapper)SelectedOrderItem).ProductKey > 0);
}
private void DeleteOrderItem()
{
var item_to_del = SelectedOrderItem as OrderItemWrapper;
if (item_to_del != null)
{
if (item_to_del.OrderItemKey == 0)
{
Order.OrderItems.Remove(item_to_del);
}
else
{
item_to_del.OrderItemStatus = QIQOOrderItemStatus.Canceled;
item_to_del.OrderItemQuantity = 0;
item_to_del.OrderItemLineSum = 0M;
item_to_del.ItemPricePer = 0M;
item_to_del.ProductDesc = item_to_del.ProductDesc + " (Deleted)";
item_to_del.OrderItemCompleteDate = DateTime.Now;
}
UpdateItemTotals();
//InvalidateCommands();
}
}
private bool CanEditOrderItem()
{
return (SelectedOrderItem != null && ((OrderItemWrapper)SelectedOrderItem).ProductKey > 0);
}
private void EditOrderItem()
{
var item_to_edit = SelectedOrderItem as OrderItemWrapper;
if (item_to_edit != null)
{
ChangeOrderItem(item_to_edit.Model.Copy(), ApplicationStrings.NotificationEdit);
}
}
private bool CanAddOrderItem()
{
return Order.Account.AccountKey != 0;
}
private void AddOrderItem()
{
var existing_empty_item = Order.OrderItems.Where(i => i.ProductCode == null).FirstOrDefault().Model;
if (existing_empty_item != null)
{
existing_empty_item.OrderItemQuantity = 1;
existing_empty_item.OrderKey = Order.OrderKey;
existing_empty_item.AccountRep = Order.AccountRep.Model;
existing_empty_item.SalesRep = Order.SalesRep.Model;
existing_empty_item.OrderItemBillToAddress = DefaultBillingAddress.Model;
existing_empty_item.OrderItemShipToAddress = DefaultShippingAddress.Model;
ChangeOrderItem(existing_empty_item, ApplicationStrings.NotificationEdit);
}
else
{
var new_ord_item = new OrderItem()
{
AccountRep = Order.AccountRep.Model,
OrderItemBillToAddress = DefaultBillingAddress.Model,
//OrderItemSeq = Order.OrderItems.Max(item => item.OrderItemSeq) + 1,
OrderItemQuantity = 1,
OrderItemShipToAddress = DefaultShippingAddress.Model,
OrderKey = Order.OrderKey,
SalesRep = Order.SalesRep.Model
};
ChangeOrderItem(new_ord_item, ApplicationStrings.NotificationAdd);
}
}
private void ChangeOrderItem(OrderItem order_item, string action)
{
//var item_to_edit = order_item as OrderItem;
if (order_item != null)
{
GridIsEnabled = false;
var bill_addresses = _currentAccount.Addresses.Where(item => item.AddressType == QIQOAddressType.Billing).ToList();
var ship_addresses = _currentAccount.Addresses.Where(item => item.AddressType == QIQOAddressType.Shipping).ToList();
var needed_objects = new Tuple<object, object, object>(order_item, bill_addresses, ship_addresses);
var notification = new ItemEditNotification(needed_objects);
notification.Title = action + " Order Item"; //+ emp_to_edit.PersonCode + " - " + emp_to_edit.PersonFullNameFML;
EditOrderItemRequest.Raise(notification,
r =>
{
if (r != null && r.Confirmed && r.EditibleObject != null) //
{
var obj = r.EditibleObject as OrderItem;
if (obj != null)
{
if (action == ApplicationStrings.NotificationEdit)
{
var changed_prod = ProductList.Where(item => item.ProductKey == obj.ProductKey).FirstOrDefault();
var item_to_update = SelectedOrderItem as OrderItemWrapper;
item_to_update.ProductKey = obj.ProductKey;
item_to_update.ProductCode = changed_prod.ProductCode;
item_to_update.ProductName = obj.ProductName;
item_to_update.ProductDesc = obj.ProductDesc;
item_to_update.OrderItemQuantity = obj.OrderItemQuantity;
item_to_update.ItemPricePer = obj.ItemPricePer;
item_to_update.OrderItemLineSum = order_item.OrderItemQuantity * order_item.ItemPricePer;
item_to_update.OrderItemStatus = obj.OrderItemStatus;
item_to_update.OrderItemProduct.ProductKey = obj.ProductKey;
item_to_update.OrderItemProduct.ProductCode = changed_prod.ProductCode;
item_to_update.OrderItemProduct.ProductDesc = obj.ProductDesc;
item_to_update.OrderItemProduct.ProductName = obj.ProductName;
item_to_update.OrderItemBillToAddress.AddressKey = obj.OrderItemBillToAddress.AddressKey;
item_to_update.OrderItemShipToAddress.AddressKey = obj.OrderItemShipToAddress.AddressKey;
item_to_update.SalesRep.EntityPersonKey = obj.SalesRep.EntityPersonKey;
item_to_update.AccountRep.EntityPersonKey = obj.AccountRep.EntityPersonKey;
item_to_update.OrderItemShipDate = obj.OrderItemShipDate;
item_to_update.OrderItemCompleteDate = obj.OrderItemCompleteDate;
}
else
{
Order.OrderItems.Add(new OrderItemWrapper(obj));
}
UpdateItemTotals();
}
}
});
GridIsEnabled = true;
}
}
private void PopulateProductInfo(object param)
{
var order_item = Order.OrderItems[SelectedOrderItemIndex];
//OrderItem order_item = OrderItems[SelectedOrderItemIndex];
if (order_item != null && order_item.ProductKey > 0)
{
var sp = ProductList.Where(item => item.ProductKey == order_item.ProductKey).FirstOrDefault();
//MessageToDisplay = order_item.ProductKey.ToString() + ": " + sp[0].ProductName;
if (order_item.ProductName == "" || order_item.ProductName == null || order_item.ProductName != sp.ProductName)
{
if (sp.ProductName != "")
{
var rp = sp.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODBASE).FirstOrDefault();
var dq = sp.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODDFQTY).FirstOrDefault();
//var.ProductKey = sp[0].ProductKey;
// order_item.ProductKey = sp.ProductKey;
order_item.ProductCode = sp.ProductCode;
order_item.ProductName = sp.ProductName;
order_item.ProductDesc = sp.ProductDesc;
order_item.OrderItemQuantity = int.Parse(dq.AttributeValue);
// Check for Fee Schedule here!
var fsp = ApplyFeeSchedule(sp.ProductKey, decimal.Parse(rp.AttributeValue));
order_item.ItemPricePer = (fsp != 0M) ? fsp : decimal.Parse(rp.AttributeValue);
order_item.OrderItemLineSum = order_item.OrderItemQuantity * order_item.ItemPricePer;
//order_item.OrderItemProduct = new ProductWrapper(sp);
order_item.OrderItemProduct.ProductKey = sp.ProductKey;
order_item.OrderItemProduct.ProductCode = sp.ProductCode;
order_item.OrderItemProduct.ProductDesc = sp.ProductDesc;
order_item.OrderItemProduct.ProductName = sp.ProductName;
order_item.OrderItemProduct.ProductType = sp.ProductType;
//order_item.OrderItemBillToAddress = DefaultBillingAddress;
FillFromDefaultAddress(order_item, QIQOAddressType.Billing);
//order_item.OrderItemShipToAddress = DefaultShippingAddress;
FillFromDefaultAddress(order_item, QIQOAddressType.Shipping);
order_item.AccountRep.EntityPersonKey = _accountreps[0].EntityPersonKey;
order_item.SalesRep.EntityPersonKey = _salesreps[0].EntityPersonKey;
order_item.OrderItemSeq = SelectedOrderItemIndex + 1;
}
}
}
Order.OrderItemCount = Order.OrderItems.Sum(item => item.OrderItemQuantity);
Order.OrderValueSum = Order.OrderItems.Sum(item => item.OrderItemLineSum);
var seq = Order.OrderItems.Count;
// Need to think about whether this is the best way to do this. What if they change an existing item?
var new_order_line = Order.OrderItems.Where(item => item.ProductKey == 0).FirstOrDefault();
if (new_order_line == null)
{
var new_item = new OrderItemWrapper(InitNewOrderItem(seq + 1));
FillFromDefaultAddress(new_item, QIQOAddressType.Billing);
FillFromDefaultAddress(new_item, QIQOAddressType.Shipping);
Order.OrderItems.Add(new_item);
}
}
private void FillFromDefaultAddress(OrderItemWrapper order_item, QIQOAddressType addr_type)
{
if (addr_type == QIQOAddressType.Billing)
{
if (DefaultBillingAddress != null)
{
order_item.OrderItemBillToAddress.AddressKey = DefaultBillingAddress.AddressKey;
order_item.OrderItemBillToAddress.AddressType = QIQOAddressType.Billing;
order_item.OrderItemBillToAddress.AddressLine1 = DefaultBillingAddress.AddressLine1;
order_item.OrderItemBillToAddress.AddressLine2 = DefaultBillingAddress.AddressLine2;
order_item.OrderItemBillToAddress.AddressCity = DefaultBillingAddress.AddressCity;
order_item.OrderItemBillToAddress.AddressState = DefaultBillingAddress.AddressState;
order_item.OrderItemBillToAddress.AddressPostalCode = DefaultBillingAddress.AddressPostalCode;
}
}
else
{
if (DefaultShippingAddress != null)
{
order_item.OrderItemShipToAddress.AddressKey = DefaultShippingAddress.AddressKey;
order_item.OrderItemShipToAddress.AddressType = QIQOAddressType.Shipping;
order_item.OrderItemShipToAddress.AddressLine1 = DefaultShippingAddress.AddressLine1;
order_item.OrderItemShipToAddress.AddressLine2 = DefaultShippingAddress.AddressLine2;
order_item.OrderItemShipToAddress.AddressCity = DefaultShippingAddress.AddressCity;
order_item.OrderItemShipToAddress.AddressState = DefaultShippingAddress.AddressState;
order_item.OrderItemShipToAddress.AddressPostalCode = DefaultShippingAddress.AddressPostalCode;
}
}
}
private decimal ApplyFeeSchedule(int product_key, decimal def_price) // think about if this needs to be in a service
{
var charge = 0M; string type;
if (FeeScheduleList != null)
{
var fs = FeeScheduleList.Where(item => item.ProductKey == product_key).FirstOrDefault();
if (fs != null)
{
charge = fs.FeeScheduleValue;
type = fs.FeeScheduleTypeCode;
if (type == "P")
{
charge = def_price * charge;
}
}
}
else
{
charge = def_price;
}
return charge;
}
private void UpdateItemTotals()
{
if (SelectedOrderItemIndex != -1 && Order.OrderItems.Count > 0)
{
var order_item = Order.OrderItems[SelectedOrderItemIndex];
//OrderItem order_item = OrderItems[SelectedOrderItemIndex];
if (order_item != null & order_item.OrderItemStatus != QIQOOrderItemStatus.Canceled)
{
if (order_item.ItemPricePer <= 0)
{
if (order_item.OrderItemProduct != null)
{
var rp = order_item.OrderItemProduct.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODBASE).FirstOrDefault();
if (rp != null)
{
order_item.ItemPricePer = ApplyFeeSchedule(order_item.ProductKey, Decimal.Parse(rp.AttributeValue));
}
}
}
if (order_item.OrderItemQuantity <= 0)
{
if (order_item.OrderItemProduct != null)
{
var dq = order_item.OrderItemProduct.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODDFQTY).FirstOrDefault();
if (dq != null)
{
order_item.OrderItemQuantity = Int32.Parse(dq.AttributeValue);
}
}
}
order_item.OrderItemLineSum = order_item.OrderItemQuantity * order_item.ItemPricePer;
}
}
Order.OrderItemCount = Order.OrderItems.Sum(item => item.OrderItemQuantity);
Order.OrderValueSum = Order.OrderItems.Sum(item => item.OrderItemLineSum);
Order.OrderItems.ForEach(item => item.OrderItemSeq = Order.OrderItems.IndexOf(item) + 1);
}
private void UpdateHeaderFromDetail()
{
if (SelectedOrderItemIndex != -1 && Order.OrderItems.Count > 0)
{
var order_item = Order.OrderItems[SelectedOrderItemIndex];
//OrderItem order_item = OrderItems[SelectedOrderItemIndex];
if (order_item != null)
{
var current_bill_address = order_item.OrderItemBillToAddress as AddressWrapper;
if (current_bill_address != null && current_bill_address.AddressKey != 0 && current_bill_address.AddressLine1 != null)
{
DefaultBillingAddress = current_bill_address;
}
var current_ship_address = order_item.OrderItemShipToAddress as AddressWrapper;
if (current_ship_address != null && current_ship_address.AddressKey != 0 && current_ship_address.AddressLine1 != null)
{
DefaultShippingAddress = current_ship_address;
}
var current_sales_rep = order_item.SalesRep as RepresentativeWrapper;
if (current_sales_rep != null && current_sales_rep.EntityPersonKey != 0)
{
Order.SalesRep.EntityPersonKey = current_sales_rep.EntityPersonKey;
}
var current_account_rep = order_item.AccountRep as RepresentativeWrapper;
if (current_account_rep != null && current_account_rep.EntityPersonKey != 0)
{
Order.AccountRep.EntityPersonKey = current_account_rep.EntityPersonKey;
}
}
}
}
private bool CanGetAccount(string account_code)
{
return account_code.Length > 2;
}
private void GetAccount(string account_code)
{
//throw new NotImplementedException();
ExecuteFaultHandledOperation(() =>
{
var acct_service = service_factory.CreateClient<IAccountService>();
var comp = CurrentCompany as Company;
using (acct_service)
{
var account = acct_service.GetAccountByCode(account_code, comp.CompanyCode);
if (account != null)
{
if (account.Employees != null)
{
AccountContacts = new ObservableCollection<AccountPerson>(account.Employees.Where(item => item.CompanyRoleType == QIQOPersonType.AccountContact).ToList());
}
// Get the accounts main contact key
var contact = account.Employees.Where(item => item.CompanyRoleType == QIQOPersonType.AccountContact).FirstOrDefault();
var cnt_key = contact != null ? contact.EntityPersonKey : 1;
Order.Account.AccountKey = account.AccountKey;
Order.Account.AccountName = account.AccountName;
Order.Account.AccountCode = account.AccountCode;
Order.Account.AccountDBA = account.AccountDBA;
Order.Account.AccountDesc = account.AccountDesc;
Order.AccountKey = account.AccountKey;
Order.Account.AccountType = account.AccountType;
Order.AccountContactKey = cnt_key; // account.Employees[0].EntityPersonKey;
Order.OrderAccountContact.PersonFullNameFML = contact != null ? contact.PersonFullNameFML : "N/A";
Order.AccountRepKey = AccountRepList[0].EntityPersonKey;
Order.SalesRepKey = SalesRepList[0].EntityPersonKey;
DefaultBillingAddress = new AddressWrapper(account.Addresses.Where(item => item.AddressType == QIQOAddressType.Billing).FirstOrDefault());
DefaultShippingAddress = new AddressWrapper(account.Addresses.Where(item => item.AddressType == QIQOAddressType.Shipping).FirstOrDefault());
FeeScheduleList = new ObservableCollection<FeeSchedule>(account.FeeSchedules);
_currentAccount = account;
RaisePropertyChanged(nameof(Order));
GridIsEnabled = true;
}
else
{
DisplayErrorMessage($"Account with code '{account_code}' not found");
}
}
});
}
private bool CanDoSave()
{
return Order.IsChanged && Order.IsValid;
}
private void DoSave()
{
event_aggregator.GetEvent<GeneralMessageEvent>().Publish(ApplicationStrings.BeginningSave);
ExecuteFaultHandledOperation(() =>
{
var order_service = service_factory.CreateClient<IOrderService>();
using (var scope = new TransactionScope())
{
using (order_service)
{
if (Order.OrderKey == 0)
{
var account_service = service_factory.CreateClient<IAccountService>();
Order.OrderNumber = account_service.GetAccountNextNumber(Order.Account.Model, QIQOEntityNumberType.OrderNumber);
account_service.Dispose();
}
//TODO: Do something to make sure the order items are in the object properly
var new_order_line = Order.OrderItems.Where(item => item.ProductKey == 0).FirstOrDefault();
if (new_order_line != null)
{
Order.OrderItems.Remove(new_order_line);
}
// For some reason, these don't seem to get set properly when I add the account object to the Order object
Order.Model.OrderItems.ForEach(item => item.OrderItemBillToAddress = DefaultBillingAddress.Model);
Order.Model.OrderItems.ForEach(item => item.OrderItemShipToAddress = DefaultShippingAddress.Model);
var order_key = order_service.CreateOrder(Order.Model);
if (Order.OrderKey == 0)
{
Order.OrderKey = order_key;
}
Order.AcceptChanges();
ViewTitle = Order.OrderNumber;
//event_aggregator.GetEvent<OrderUpdatedEvent>().Publish($"Order {Order.OrderNumber} updated successfully");
}
scope.Complete();
}
});
if (Order.OrderKey > 0)
{
GetOrder(Order.OrderKey);
event_aggregator.GetEvent<OrderUpdatedEvent>().Publish($"Order {Order.OrderNumber} updated successfully");
}
}
}
}
| 45.875403 | 183 | 0.567174 | [
"MIT"
] | rdrrichards/QIQO.Business.Client.Solution | QIQO.Business.Module.Orders/ViewModels/OrderViewModel.cs | 42,712 | C# |
using Fizzyo;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace Assets.Scripts.Fizzyo
{
public class StartCalibrate : MonoBehaviour
{
//public
public Text startText;
//public GameObject pressureBar;
public Slider slider;
//private
private float maxPressureReading = 0;
private float minPressureThreshold = 0.1f;
private System.Diagnostics.Stopwatch blowingStopwatch;
private int countdownToStart = 3;
private float smoothing = 0.00001f;
// Use this for initialization
void Start()
{
// Create new stopwatch.
blowingStopwatch = new System.Diagnostics.Stopwatch();
startText.text = countdownToStart.ToString();
}
// Update is called once per frame
void Update()
{
float pressure = FizzyoDevice.Instance().Pressure();
//float y = transform.position.y + ((pressure * 5) - pressureBar.transform.position.y) * smoothing;
//pressureBar.transform.position = new Vector3(pressureBar.transform.position.x,y , pressureBar.transform.position.z);
slider.value = (pressure * 5) * smoothing;
if (pressure > minPressureThreshold)
{
maxPressureReading = pressure;
blowingStopwatch.Start();
int timeToStart = (int)(countdownToStart - (blowingStopwatch.ElapsedMilliseconds / 1000));
if (timeToStart > 0)
{
startText.text = "" + timeToStart;
}
else
{
//Save the max recorded pressure to use to scale sensor input during gameplay.
PlayerPrefs.SetFloat("Max Fizzyo Pressure", maxPressureReading);
SceneManager.LoadScene("JetpackLevel");
}
}
else
{
blowingStopwatch.Stop();
}
}
}
} | 32.634921 | 130 | 0.564689 | [
"MIT"
] | ichealthhack/Ringo | Ringo/Assets/Scripts/Fizzyo/StartCalibrate.cs | 2,058 | C# |
// <copyright file="SettingsWindow.xaml.cs" company="Horror">
// Copyright (c) 2014 Open source under MIT License
// </copyright>
// <author>rewso</author>
// <date>2014-12-20 05:53</date>
// <summary>Class for Horror.Keywords</summary>
// <copyright file="SettingsWindow.xaml.cs" company="Horror">
// Copyright (c) 2014 Open source under MIT License
// </copyright>
// <author>rewso</author>
// <date>2014-12-20 05:53</date>
// <summary>Class for Horror.Keywords</summary>
// <copyright file="SettingsWindow.xaml.cs" company="Vestas">
// Copyright (c) 2014 License
// </copyright>
// <author>rewso</author>
// <date>2014-12-20 05:53</date>
// <summary>Class for Horror.Keywords</summary>
namespace Horror.Keywords.View
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
/// <summary>
/// Interaction logic for SettingsWindow.xaml
/// </summary>
public partial class SettingsWindow : Window
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SettingsWindow"/> class.
/// </summary>
public SettingsWindow()
{
InitializeComponent();
}
#endregion
}
}
| 24.791667 | 77 | 0.677311 | [
"MIT"
] | horrorcode/keymaster | src/Horror.KeyWords/View/SettingsWindow.xaml.cs | 1,192 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main() // 100/100
{
List<int> insertionList = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
string newDigit = Console.ReadLine();
ConvertAndInputInTheList(insertionList, newDigit);
Console.WriteLine(string.Join(" ", insertionList));
}
static List<int> ConvertAndInputInTheList(List<int> insertionList, string newDigit)
{
while (newDigit != "end")
{
int parsedInt = int.Parse(newDigit);
int toBeInserted = parsedInt;
while (parsedInt > 10)
{
parsedInt /= 10;
}
insertionList.Insert(parsedInt, toBeInserted);
newDigit = Console.ReadLine();
}
return insertionList;
}
} | 28.766667 | 91 | 0.588644 | [
"MIT"
] | GabrielRezendi/Programming-Fundamentals-2017 | 02.Extented Fundamentals/16.LISTS - MORE EXERCISES/02.02 Integer Insertion/Program.cs | 865 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.ReadabilityRules
{
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Helpers;
/// <summary>
/// Implements a code fix for <see cref="SA1131UseReadableConditions"/>.
/// </summary>
/// <remarks>
/// <para>To fix a violation of this rule, switch the arguments of the comparison.</para>
/// </remarks>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SA1131CodeFixProvider))]
[Shared]
internal class SA1131CodeFixProvider : CodeFixProvider
{
/// <inheritdoc/>
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(SA1131UseReadableConditions.DiagnosticId);
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return FixAll.Instance;
}
/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create(
ReadabilityResources.SA1131CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1131CodeFixProvider)),
diagnostic);
}
return SpecializedTasks.CompletedTask;
}
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var binaryExpression = (BinaryExpressionSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
var newBinaryExpression = TransformExpression(binaryExpression);
return document.WithSyntaxRoot(syntaxRoot.ReplaceNode(binaryExpression, newBinaryExpression));
}
private static BinaryExpressionSyntax TransformExpression(BinaryExpressionSyntax binaryExpression)
{
var newLeft = binaryExpression.Right.WithTriviaFrom(binaryExpression.Left);
var newRight = binaryExpression.Left.WithTriviaFrom(binaryExpression.Right);
return binaryExpression.WithLeft(newLeft).WithRight(newRight).WithOperatorToken(GetCorrectOperatorToken(binaryExpression.OperatorToken));
}
private static SyntaxToken GetCorrectOperatorToken(SyntaxToken operatorToken)
{
switch (operatorToken.Kind())
{
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
return operatorToken;
case SyntaxKind.GreaterThanToken:
return SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.LessThanToken, operatorToken.TrailingTrivia);
case SyntaxKind.GreaterThanEqualsToken:
return SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.LessThanEqualsToken, operatorToken.TrailingTrivia);
case SyntaxKind.LessThanToken:
return SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.GreaterThanToken, operatorToken.TrailingTrivia);
case SyntaxKind.LessThanEqualsToken:
return SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.GreaterThanEqualsToken, operatorToken.TrailingTrivia);
default:
return SyntaxFactory.Token(SyntaxKind.None);
}
}
private class FixAll : DocumentBasedFixAllProvider
{
public static FixAllProvider Instance { get; } =
new FixAll();
protected override string CodeActionTitle =>
ReadabilityResources.SA1131CodeFix;
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
{
if (diagnostics.IsEmpty)
{
return null;
}
var syntaxRoot = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
var nodes = diagnostics.Select(diagnostic => (BinaryExpressionSyntax)syntaxRoot.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true));
return syntaxRoot.ReplaceNodes(nodes, (originalNode, rewrittenNode) => TransformExpression(rewrittenNode));
}
}
}
}
| 42.834711 | 168 | 0.679336 | [
"Apache-2.0"
] | Andreyul/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1131CodeFixProvider.cs | 5,185 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client20204.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class ODataQueryOptionsTenantDto
{
/// <summary>
/// Initializes a new instance of the ODataQueryOptionsTenantDto class.
/// </summary>
public ODataQueryOptionsTenantDto()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ODataQueryOptionsTenantDto class.
/// </summary>
public ODataQueryOptionsTenantDto(object ifMatch = default(object), object ifNoneMatch = default(object), ODataQueryContext context = default(ODataQueryContext), object request = default(object), ODataRawQueryOptions rawValues = default(ODataRawQueryOptions), SelectExpandQueryOption selectExpand = default(SelectExpandQueryOption), ApplyQueryOption apply = default(ApplyQueryOption), FilterQueryOption filter = default(FilterQueryOption), OrderByQueryOption orderBy = default(OrderByQueryOption), SkipQueryOption skip = default(SkipQueryOption), TopQueryOption top = default(TopQueryOption), CountQueryOption count = default(CountQueryOption), object validator = default(object))
{
IfMatch = ifMatch;
IfNoneMatch = ifNoneMatch;
Context = context;
Request = request;
RawValues = rawValues;
SelectExpand = selectExpand;
Apply = apply;
Filter = filter;
OrderBy = orderBy;
Skip = skip;
Top = top;
Count = count;
Validator = validator;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IfMatch")]
public object IfMatch { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IfNoneMatch")]
public object IfNoneMatch { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Context")]
public ODataQueryContext Context { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Request")]
public object Request { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "RawValues")]
public ODataRawQueryOptions RawValues { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SelectExpand")]
public SelectExpandQueryOption SelectExpand { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Apply")]
public ApplyQueryOption Apply { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Filter")]
public FilterQueryOption Filter { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "OrderBy")]
public OrderByQueryOption OrderBy { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Skip")]
public SkipQueryOption Skip { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Top")]
public TopQueryOption Top { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Count")]
public CountQueryOption Count { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Validator")]
public object Validator { get; set; }
}
}
| 34.869565 | 688 | 0.601247 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20204/Models/ODataQueryOptionsTenantDto.cs | 4,010 | C# |
using Microsoft.Practices.Unity;
using Prism.Unity;
using ViewInjection.Views;
using System.Windows;
namespace ViewInjection
{
class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
}
}
| 20.857143 | 57 | 0.648402 | [
"MIT"
] | Arc3D/Prism-Samples-Wpf | 05-ViewInjection/ViewInjection/Bootstrapper.cs | 440 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Rebus.Bus;
using Rebus.Bus.Advanced;
using Rebus.DataBus.InMem;
using Rebus.IntegrationTesting.Threading;
using Rebus.Pipeline;
using Rebus.Sagas;
using Rebus.Serialization;
using Rebus.Transport;
namespace Rebus.IntegrationTesting
{
public class IntegrationTestingBusDecorator : IIntegrationTestingBus
{
private readonly IBus _inner;
private readonly ISerializer _serializer;
private readonly IPipelineInvoker _pipelineInvoker;
private readonly IntegrationTestingAsyncTaskFactory _asyncTaskFactory;
public IntegrationTestingOptions Options { get; }
public IAdvancedApi Advanced => _inner.Advanced;
public InMemDataStore DataBusData => Options.DataStore;
public IMessages PendingMessages { get; }
public IMessages PublishedMessages { get; }
public IMessages RepliedMessages { get; }
private readonly MessageList _overallProcessedMessages;
public IMessages ProcessedMessages => _overallProcessedMessages;
public IntegrationTestingBusDecorator(
[NotNull] IBus inner,
[NotNull] ISerializer serializer,
[NotNull] IntegrationTestingOptions options,
[NotNull] IPipelineInvoker pipelineInvoker,
[NotNull] IntegrationTestingAsyncTaskFactory asyncTaskFactory)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
Options = options ?? throw new ArgumentNullException(nameof(options));
_pipelineInvoker = pipelineInvoker ?? throw new ArgumentNullException(nameof(pipelineInvoker));
_asyncTaskFactory = asyncTaskFactory ?? throw new ArgumentNullException(nameof(asyncTaskFactory));
PendingMessages = GetMessages(Options.InputQueueName);
PublishedMessages = GetMessages(Options.SubscriberQueueName);
RepliedMessages = GetMessages(Options.ReplyQueueName);
_overallProcessedMessages = new MessageList(_serializer, this);
}
public async Task ProcessPendingMessages(CancellationToken cancellationToken = default)
{
var currentlyProcessedMessages = new MessageList(_serializer, this);
while (!cancellationToken.IsCancellationRequested)
{
using (var scope = new RebusTransactionScope())
{
var transportMessage = Options.Network.Receive(Options.InputQueueName, scope.TransactionContext);
if (transportMessage == null)
break;
if (currentlyProcessedMessages.Count >= Options.MaxProcessedMessages)
throw new TooManyMessagesProcessedException(currentlyProcessedMessages);
scope.TransactionContext.OnCompleted(async () =>
{
await currentlyProcessedMessages.Add(transportMessage);
await _overallProcessedMessages.Add(transportMessage);
});
var incomingStepContext = new IncomingStepContext(transportMessage, scope.TransactionContext);
await _pipelineInvoker.Invoke(incomingStepContext);
await scope.CompleteAsync();
}
await _asyncTaskFactory.ExecuteDueTasks(cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
}
public void ShiftTime(TimeSpan timeSpan)
{
Options.Network.ShiftTime(Options.InputQueueName, timeSpan);
}
public IMessages GetMessages([NotNull] string queueName)
{
if (queueName == null) throw new ArgumentNullException(nameof(queueName));
var queue = Options.Network.GetQueue(queueName);
return new MessagesQueueAdapter(queue, _serializer, this);
}
public IReadOnlyCollection<ISagaData> GetSagaDatas()
{
return Options.SagaStorage.Instances.ToList();
}
public Task Send(object commandMessage, Dictionary<string, string> optionalHeaders = null)
=> _inner.Send(commandMessage, optionalHeaders);
public Task SendLocal(object commandMessage, Dictionary<string, string> optionalHeaders = null)
=> _inner.SendLocal(commandMessage, optionalHeaders);
public Task Defer(TimeSpan delay, object message, Dictionary<string, string> optionalHeaders = null)
=> _inner.Defer(delay, message, optionalHeaders);
public Task DeferLocal(TimeSpan delay, object message, Dictionary<string, string> optionalHeaders = null)
=> _inner.DeferLocal(delay, message, optionalHeaders);
public Task Publish(object eventMessage, Dictionary<string, string> optionalHeaders = null)
=> _inner.Publish(eventMessage, optionalHeaders);
public Task Reply(object replyMessage, Dictionary<string, string> optionalHeaders = null)
=> _inner.Reply(replyMessage, optionalHeaders);
public Task Subscribe<TEvent>() => _inner.Subscribe<TEvent>();
public Task Subscribe(Type eventType) => _inner.Subscribe(eventType);
public Task Unsubscribe<TEvent>() => _inner.Unsubscribe<TEvent>();
public Task Unsubscribe(Type eventType) => _inner.Unsubscribe(eventType);
public void Reset()
{
_overallProcessedMessages.Clear();
Options.Network.Reset();
Options.DataStore.Reset();
Options.SubscriberStore.Reset();
Options.SagaStorage.Reset();
}
public void Dispose() => _inner.Dispose();
}
}
| 42.830986 | 118 | 0.650937 | [
"MIT"
] | oliverhanappi/Rebus.IntegrationTesting | src/Core/IntegrationTestingBusDecorator.cs | 6,084 | C# |
namespace SpotifyWebApi.Model
{
using System;
using Newtonsoft.Json;
/// <summary>
/// The <see cref="CurrentlyPlayingContext" />.
/// </summary>
public class CurrentlyPlayingContext
{
/// <summary>
/// Gets or sets the device that is currently active.
/// </summary>
[JsonProperty("device")]
public Device Device { get; set; }
/// <summary>
/// Gets or sets the repeat state: off, track, context.
/// </summary>
[JsonProperty("repeat_state")]
public string RepeatState { get; set; }
/// <summary>
/// Gets or sets a value indicating whether shuffle is on or off
/// </summary>
[JsonProperty("shuffle_state")]
public bool ShuffleState { get; set; }
/// <summary>
/// Gets or sets the context.
/// </summary>
[JsonProperty("context")]
public Context Context { get; set; }
/// <summary>
/// Gets or sets the Unix Millisecond Timestamp when data was fetched
/// </summary>
[JsonProperty("timestamp")]
public long TimestampMs { get; set; }
/// <summary>
/// Gets the <see cref="DateTime"/> object of the <see cref="TimestampMs"/>
/// </summary>
public DateTime Timestamp => DateTimeOffset.FromUnixTimeMilliseconds(this.TimestampMs).LocalDateTime;
/// <summary>
/// Gets or sets the progress into the currently playing track. Can be null.
/// </summary>
[JsonProperty("progress_ms")]
public int? ProgressMs { get; set; }
/// <summary>
/// Gets or sets a value indicating whether if something is currently playing.
/// </summary>
[JsonProperty("is_playing")]
public bool IsPlaying { get; set; }
/// <summary>
/// Gets or sets the currently playing track. Can be null.
/// </summary>
[JsonProperty("item")]
public FullTrack Item { get; set; }
}
}
| 31.276923 | 109 | 0.564191 | [
"MIT"
] | AlBarker/SpotifyWebApi | SpotifyWebApi/Model/CurrentlyPlayingContext.cs | 2,033 | C# |
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Plugins.SoundCloud.ClientApi.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Plugins.SoundCloud.ClientApi
{
public class SoundCloudApi
{
public const string ClientId = "78fd88dde7ebf8fdcad08106f6d56ab6";
public const string ClientSecret = "ef6b3dbe724eff1d03298c2e787a69bd";
public const string BaseUrl = "https://api.soundcloud.com";
public const string ClientIdForTracks = "fDoItMDbsbZz8dY16ZzARCZmzgHBPotA";
public const bool EnableGZip = true;
private AccessToken accessToken;
private ILogger _logger;
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
public SoundCloudApi(ILogger logManager, IJsonSerializer jsonSerializer, IHttpClient httpClient)
{
_logger = logManager;
_jsonSerializer = jsonSerializer;
_httpClient = httpClient;
}
internal bool IsAuthenticated
{
get
{
return this.accessToken != null;
}
}
public async Task<User> GetMe(CancellationToken cancellationToken)
{
var user = await this.Execute<User>("/me", cancellationToken);
return user;
}
public async Task<User> GetUser(int userId, CancellationToken cancellationToken)
{
var query = string.Format("/users/{0}", userId);
var user = await this.Execute<User>(query, cancellationToken);
return user;
}
public async Task<Playlist> GetPlaylist(int playlistId, CancellationToken cancellationToken)
{
var query = string.Format("/playlists/{0}", playlistId);
return await this.Execute<Playlist>(query, cancellationToken, HttpMethod.Get, true, ClientIdForTracks);
}
public async Task<ActivityResult> GetActivities(CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var result = await this.ExecutePaged<ActivityResult>("/me/activities", pagingInfo, cancellationToken);
return result;
}
public async Task<UserResult> GetFollowings(int userId, CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = string.Format("/users/{0}/followings", userId);
var result = await this.ExecutePaged<UserResult>(query, pagingInfo, cancellationToken);
return result;
}
public async Task<UserResult> GetFollowers(int userId, CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = string.Format("/users/{0}/followers", userId);
var result = await this.ExecutePaged<UserResult>(query, pagingInfo, cancellationToken);
return result;
}
public async Task<TrackResult> GetUserTracks(int userId, CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = string.Format("/users/{0}/tracks", userId);
var result = await this.ExecutePaged<TrackResult>(query, pagingInfo, cancellationToken, ClientIdForTracks);
return result;
}
public async Task<TrackResult> GetLatestTracks(CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = "/tracks?filter=streamable&order=created_at";
var result = await this.ExecutePaged<TrackResult>(query, pagingInfo, cancellationToken, ClientIdForTracks);
return result;
}
public async Task<TrackResult> GetFavorites(int userId, CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = string.Format("/users/{0}/favorites", userId);
var result = await this.ExecutePaged<TrackResult>(query, pagingInfo, cancellationToken);
return result;
}
public async Task<List<Playlist>> GetPlaylists(int userId, CancellationToken cancellationToken, PagingInfo pagingInfo)
{
var query = string.Format("/users/{0}/playlists", userId);
////var result = await this.ExecutePaged<PlaylistResult>(query, pagingInfo, cancellationToken);
var result = await this.Execute<List<Playlist>>(query, cancellationToken);
return result;
}
public async Task<bool> Authenticate(string username, string password, CancellationToken cancellationToken)
{
this.accessToken = null;
var query = string.Format("/oauth2/token?client_id={0}&client_secret={1}&grant_type=password&username={2}&password={3}", ClientId, ClientSecret, username, password);
var newToken = await this.Execute<AccessToken>(query, cancellationToken, HttpMethod.Post, false);
if (!string.IsNullOrEmpty(newToken.access_token))
{
this.accessToken = newToken;
}
return this.accessToken != null;
}
private async Task<T> ExecutePaged<T>(string queryString, PagingInfo pagingInfo, CancellationToken cancellationToken, string clientId = null)
where T : BaseResult
{
Uri uri = new Uri(BaseUrl + queryString);
uri = uri.UriAppendingQueryString("linked_partitioning", "1");
uri = uri.UriAppendingQueryString("limit", pagingInfo.PageSize.ToString());
int currentPage = 0;
var result = await this.Execute<T>(uri.PathAndQuery, cancellationToken, HttpMethod.Get, true, clientId);
while (currentPage < pagingInfo.PageIndex && !string.IsNullOrEmpty(result.GetNextUrl()))
{
currentPage++;
var nextUri = new Uri(result.GetNextUrl());
result = await this.Execute<T>(nextUri, cancellationToken);
}
if (currentPage == pagingInfo.PageIndex)
{
return result;
}
return default(T);
}
private async Task<T> Execute<T>(string queryString, CancellationToken cancellationToken, HttpMethod method = HttpMethod.Get, bool requireAuthentication = true, string clientId = null)
{
Uri uri = new Uri(BaseUrl + queryString);
if (!string.IsNullOrEmpty(clientId))
{
uri = uri.UriWithClientID(clientId);
}
else if (requireAuthentication)
{
await this.CheckRefreshAccessToken(cancellationToken);
if (this.accessToken == null)
{
// try an unauthenticated request
uri = uri.UriWithClientID(ClientId);
}
else
{
uri = uri.UriWithAuthorizedUri(this.accessToken.access_token);
}
}
return await this.Execute<T>(uri, cancellationToken, method);
}
private async Task<T> Execute<T>(Uri uri, CancellationToken cancellationToken, HttpMethod method = HttpMethod.Get)
{
var options = new HttpRequestOptions
{
Url = uri.ToString(),
CancellationToken = cancellationToken,
EnableHttpCompression = false
};
options.RequestHeaders.Add("Accept-Encoding", "gzip, deflate");
switch (method)
{
case HttpMethod.Get:
using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
{
return this.UnzipAndDeserialize<T>(stream, uri);
}
case HttpMethod.Post:
using (var stream = await _httpClient.Post(options, new Dictionary<string, string>()).ConfigureAwait(false))
{
return this.UnzipAndDeserialize<T>(stream, uri);
}
}
throw new Exception("Unsupported http method");
}
private async Task<bool> CheckRefreshAccessToken(CancellationToken cancellationToken)
{
if (this.accessToken == null)
{
return false;
}
if (!this.accessToken.HasExpired())
{
return true;
}
var query = string.Format("/oauth2/token?client_id={0}&client_secret={1}&grant_type=refresh_token&refresh_token={2}", ClientId, ClientSecret, this.accessToken.refresh_token);
this.accessToken = null;
var newToken = await this.Execute<AccessToken>(query, cancellationToken, HttpMethod.Post, false);
if (!string.IsNullOrEmpty(newToken.access_token))
{
this.accessToken = newToken;
return true;
}
return false;
}
private T UnzipAndDeserialize<T>(Stream stream, Uri uri)
{
try
{
using (var unzipStream = new GZipStream(stream, CompressionMode.Decompress))
{
return _jsonSerializer.DeserializeFromStream<T>(unzipStream);
}
}
catch (Exception ex)
{
_logger.ErrorException("Error deserializing gzipped response from uri: {0}", ex, uri);
}
stream.Seek(0, SeekOrigin.Begin);
return _jsonSerializer.DeserializeFromStream<T>(stream);
}
}
}
| 36.567164 | 192 | 0.604898 | [
"MIT"
] | MediaBrowser/Emby.Channels | MediaBrowser.Plugins.SoundCloud/ClientApi/SoundCloudApi.cs | 9,802 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Overtop.Utils
{
public class MaterialChanger : MonoBehaviour
{
private bool m_activeMaterialOn = true;
private MeshRenderer m_Mesh;
public Material m_Material1;
public Material m_Material2;
public void Awake()
{
m_Mesh = GetComponent<MeshRenderer>();
}
public void SwapMaterial()
{
m_Mesh.material = m_activeMaterialOn ? m_Material1 : m_Material2;
m_activeMaterialOn = !m_activeMaterialOn;
}
}
} | 24.64 | 77 | 0.636364 | [
"MIT"
] | ncgreco1440/Unity_GC_Monitor | GC/Scripts/MaterialChanger.cs | 618 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
* 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.
*/
namespace TencentCloud.Mrs.V20200910.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class TextToClassRequest : AbstractModel
{
/// <summary>
/// 报告文本
/// </summary>
[JsonProperty("Text")]
public string Text{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Text", this.Text);
}
}
}
| 28.818182 | 81 | 0.65142 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Mrs/V20200910/Models/TextToClassRequest.cs | 1,276 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UniGLTF;
using UnityEngine;
namespace VRM
{
public class VRMFirstPerson : MonoBehaviour
{
// If no layer names are set, use the default layer IDs.
// Otherwise use the two Unity layers called "VRMFirstPersonOnly" and "VRMThirdPersonOnly".
public static bool TriedSetupLayer = false;
public static int FIRSTPERSON_ONLY_LAYER = 9;
public static int THIRDPERSON_ONLY_LAYER = 10;
[SerializeField]
public Transform FirstPersonBone;
[SerializeField]
public Vector3 FirstPersonOffset;
[Serializable]
public struct RendererFirstPersonFlags
{
public Renderer Renderer;
public FirstPersonFlag FirstPersonFlag;
public Mesh SharedMesh
{
get
{
var renderer = Renderer as SkinnedMeshRenderer;
if (renderer != null)
{
return renderer.sharedMesh;
}
var filter = Renderer.GetComponent<MeshFilter>();
if (filter != null)
{
return filter.sharedMesh;
}
return null;
}
}
}
[SerializeField]
public List<RendererFirstPersonFlags> Renderers = new List<RendererFirstPersonFlags>();
static IEnumerable<Transform> Traverse(Transform parent)
{
yield return parent;
foreach (Transform child in parent)
{
foreach (var x in Traverse(child))
{
yield return x;
}
}
}
public void CopyTo(GameObject _dst, Dictionary<Transform, Transform> map)
{
var dst = _dst.AddComponent<VRMFirstPerson>();
dst.FirstPersonBone = FirstPersonBone;
dst.FirstPersonOffset = FirstPersonOffset;
dst.Renderers = Renderers.Select(x =>
{
var renderer = map[x.Renderer.transform].GetComponent<Renderer>();
return new VRMFirstPerson.RendererFirstPersonFlags
{
Renderer = renderer,
FirstPersonFlag = x.FirstPersonFlag,
};
}).ToList();
}
public void SetDefault()
{
FirstPersonOffset = new Vector3(0, 0.06f, 0);
var animator = GetComponent<Animator>();
if (animator != null)
{
FirstPersonBone = animator.GetBoneTransform(HumanBodyBones.Head);
}
}
private void Reset()
{
SetDefault();
TraverseRenderers();
}
public void TraverseRenderers(VRMImporterContext context = null)
{
Renderers = Traverse(transform)
.Select(x => x.GetComponent<Renderer>())
.Where(x => x != null)
.Select(x => new RendererFirstPersonFlags
{
Renderer = x,
FirstPersonFlag = context == null
? FirstPersonFlag.Auto
: GetFirstPersonFlag(context, x)
})
.ToList()
;
}
static FirstPersonFlag GetFirstPersonFlag(VRMImporterContext context, Renderer r)
{
var mesh = r.transform.GetSharedMesh();
if (mesh == null)
{
return FirstPersonFlag.Auto;
}
var index = context.Meshes.FindIndex(x => x.Mesh == mesh);
if (index == -1)
{
return FirstPersonFlag.Auto;
}
foreach(var x in context.GLTF.extensions.VRM.firstPerson.meshAnnotations)
{
if (x.mesh == index)
{
return EnumUtil.TryParseOrDefault<FirstPersonFlag>(x.firstPersonFlag);
}
}
return FirstPersonFlag.Auto;
}
void CreateHeadlessModel(Renderer _renderer, Transform EraseRoot)
{
{
var renderer = _renderer as SkinnedMeshRenderer;
if (renderer != null)
{
CreateHeadlessModelForSkinnedMeshRenderer(renderer, EraseRoot);
return;
}
}
{
var renderer = _renderer as MeshRenderer;
if (renderer != null)
{
CreateHeadlessModelForMeshRenderer(renderer, EraseRoot);
return;
}
}
// ここには来ない
}
public static void SetupLayers()
{
if (!TriedSetupLayer) {
TriedSetupLayer = true;
int layer = LayerMask.NameToLayer("VRMFirstPersonOnly");
FIRSTPERSON_ONLY_LAYER = (layer == -1) ? FIRSTPERSON_ONLY_LAYER : layer;
layer = LayerMask.NameToLayer("VRMThirdPersonOnly");
THIRDPERSON_ONLY_LAYER = (layer == -1) ? THIRDPERSON_ONLY_LAYER : layer;
}
}
private static void CreateHeadlessModelForMeshRenderer(MeshRenderer renderer, Transform eraseRoot)
{
if (renderer.transform.Ancestors().Any(x => x == eraseRoot))
{
// 祖先に削除ボーンが居る
SetupLayers();
renderer.gameObject.layer = THIRDPERSON_ONLY_LAYER;
}
else
{
// 特に変更しない => 両方表示
}
}
private static void CreateHeadlessModelForSkinnedMeshRenderer(SkinnedMeshRenderer renderer, Transform eraseRoot)
{
SetupLayers();
renderer.gameObject.layer = THIRDPERSON_ONLY_LAYER;
var go = new GameObject("_headless_" + renderer.name);
go.layer = FIRSTPERSON_ONLY_LAYER;
go.transform.SetParent(renderer.transform, false);
var m_eraseBones = renderer.bones.Select(x =>
{
var eb = new BoneMeshEraser.EraseBone
{
Bone = x,
};
if (eraseRoot != null)
{
// 首の子孫を消去
if (eb.Bone.Ancestor().Any(y => y == eraseRoot))
{
//Debug.LogFormat("erase {0}", x);
eb.Erase = true;
}
}
return eb;
})
.ToArray();
var bones = renderer.bones;
var eraseBones = m_eraseBones
.Where(x => x.Erase)
.Select(x => bones.IndexOf(x.Bone))
.ToArray();
var mesh = BoneMeshEraser.CreateErasedMesh(renderer.sharedMesh, eraseBones);
var erased = go.AddComponent<SkinnedMeshRenderer>();
erased.sharedMesh = mesh;
erased.sharedMaterials = renderer.sharedMaterials;
erased.bones = renderer.bones;
erased.rootBone = renderer.rootBone;
erased.updateWhenOffscreen = true;
}
bool m_done;
/// <summary>
/// 配下のモデルのレイヤー設定など
/// </summary>
public void Setup()
{
SetupLayers();
if (m_done) return;
m_done = true;
foreach (var x in Renderers)
{
switch (x.FirstPersonFlag)
{
case FirstPersonFlag.Auto:
CreateHeadlessModel(x.Renderer, FirstPersonBone);
break;
case FirstPersonFlag.FirstPersonOnly:
x.Renderer.gameObject.layer = FIRSTPERSON_ONLY_LAYER;
break;
case FirstPersonFlag.ThirdPersonOnly:
x.Renderer.gameObject.layer = THIRDPERSON_ONLY_LAYER;
break;
case FirstPersonFlag.Both:
//x.Renderer.gameObject.layer = 0;
break;
}
}
}
}
}
| 31.291045 | 120 | 0.488075 | [
"MIT"
] | hashilus/UniVRM | Assets/VRM/UniVRM/Scripts/FirstPerson/VRMFirstPerson.cs | 8,490 | C# |
#region License
/*
MIT License
Copyright(c) 2021 Petteri Kautonen
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.
*/
#endregion
using System.Windows.Forms;
namespace VPKSoft.MessageBoxExtended
{
/// <summary>
/// A class to control open modal <see cref="MessageBoxBase"/> class instances.
/// </summary>
public class MessageBoxExtendedControl
{
/// <summary>
/// Closes all <see cref="MessageBoxBase"/> class instances with the specified result.
/// </summary>
/// <param name="dialogResult">The dialog result to return upon close.</param>
// ReSharper disable once UnusedMember.Global, A class library..
public static void CloseAllBoxesWithResult(DialogResultExtended dialogResult)
{
for (int i = MessageBoxBase.MessageBoxInstances.Count - 1; i >= 0; i--)
{
MessageBoxBase.MessageBoxInstances[i].Result = dialogResult;
MessageBoxBase.MessageBoxInstances[i].DialogResult = DialogResult.Cancel;
MessageBoxBase.MessageBoxInstances[i].Close();
}
}
}
}
| 41.384615 | 95 | 0.704926 | [
"MIT"
] | VPKSoft/VPKSoft.MessageBoxExtended | VPKSoft.MessageBoxExtended/MessageBoxExtendedControl.cs | 2,154 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace SevenDigital.Messaging.Infrastructure
{
/// <summary>
/// Thread safe version implementation of Set
/// </summary>
public class ConcurrentSet<T> : ISet<T>
{
private readonly ConcurrentDictionary<T, byte> _dictionary = new ConcurrentDictionary<T, byte>();
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
return _dictionary.Keys.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(T item)
{
return TryRemove(item);
}
/// <summary>
/// Gets the number of elements in the set.
/// </summary>
public int Count
{
get { return _dictionary.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly { get { return false; } }
/// <summary>
/// Gets a value that indicates if the set is empty.
/// </summary>
public bool IsEmpty
{
get { return _dictionary.IsEmpty; }
}
/// <summary>
/// Values stored in the set
/// </summary>
public ICollection<T> Values
{
get { return _dictionary.Keys; }
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
void ICollection<T>.Add(T item)
{
if (!Add(item))
throw new ArgumentException("Item already exists in set.");
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public void UnionWith(IEnumerable<T> other)
{
foreach (var item in other)
TryAdd(item);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public void IntersectWith(IEnumerable<T> other)
{
var enumerable = other as IList<T> ?? other.ToArray();
foreach (var item in this)
{
if (!enumerable.Contains(item))
TryRemove(item);
}
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public void ExceptWith(IEnumerable<T> other)
{
foreach (var item in other)
TryRemove(item);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// NOT CURRENTLY IMPLEMENTED
/// </summary>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public void SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotImplementedException();
}
/// <summary>
/// Determines whether a set is a subset of a specified collection.
/// </summary>
/// <returns>
/// true if the current set is a subset of <paramref name="other"/>; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool IsSubsetOf(IEnumerable<T> other)
{
var enumerable = other as IList<T> ?? other.ToArray();
return this.AsParallel().All(enumerable.Contains);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <returns>
/// true if the current set is a superset of <paramref name="other"/>; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool IsSupersetOf(IEnumerable<T> other)
{
return other.AsParallel().All(Contains);
}
/// <summary>
/// Determines whether the current set is a correct superset of a specified collection.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.ISet`1"/> object is a correct superset of <paramref name="other"/>; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set. </param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
var enumerable = other as IList<T> ?? other.ToArray();
return Count != enumerable.Count && IsSupersetOf(enumerable);
}
/// <summary>
/// Determines whether the current set is a property (strict) subset of a specified collection.
/// </summary>
/// <returns>
/// true if the current set is a correct subset of <paramref name="other"/>; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
var enumerable = other as IList<T> ?? other.ToArray();
return Count != enumerable.Count && IsSubsetOf(enumerable);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <returns>
/// true if the current set and <paramref name="other"/> share at least one common element; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool Overlaps(IEnumerable<T> other)
{
return other.AsParallel().Any(Contains);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <returns>
/// true if the current set is equal to <paramref name="other"/>; otherwise, false.
/// </returns>
/// <param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
public bool SetEquals(IEnumerable<T> other)
{
var enumerable = other as IList<T> ?? other.ToArray();
return Count == enumerable.Count && enumerable.AsParallel().All(Contains);
}
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the element was successfully added.
/// </summary>
/// <returns>
/// true if the element is added to the set; false if the element is already in the set.
/// </returns>
/// <param name="item">The element to add to the set.</param>
public bool Add(T item)
{
return TryAdd(item);
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
_dictionary.Clear();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
public bool Contains(T item)
{
return _dictionary.ContainsKey(item);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type T cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
Values.CopyTo(array, arrayIndex);
}
/// <summary>
/// Return values as an Array
/// </summary>
public T[] ToArray()
{
return _dictionary.Keys.ToArray();
}
/// <summary>
/// Try to add the item to the set, returning true if it was added
/// </summary>
public bool TryAdd(T item)
{
return _dictionary.TryAdd(item, default(byte));
}
/// <summary>
/// Try to remove the item to the set, returning true if it was removed
/// </summary>
public bool TryRemove(T item)
{
byte donotcare;
return _dictionary.TryRemove(item, out donotcare);
}
}
} | 42.591398 | 991 | 0.675419 | [
"BSD-3-Clause"
] | i-e-b/SevenDigital.Messaging | src/SevenDigital.Messaging/Infrastructure/ConcurrentHashSet.cs | 11,885 | C# |
using System;
using System.Collections.Generic;
namespace WDE.Common.History
{
public abstract class HistoryHandler
{
private readonly List<IHistoryAction> bulkEditing = new();
private bool inBulkEditing;
public event EventHandler<IHistoryAction> ActionPush = delegate { };
protected void StartBulkEdit()
{
inBulkEditing = true;
bulkEditing.Clear();
}
protected void EndBulkEdit(string name)
{
if (inBulkEditing)
{
inBulkEditing = false;
if (bulkEditing.Count > 0)
PushAction(new CompoundHistoryAction(name, bulkEditing.ToArray()));
}
}
protected void PushAction(IHistoryAction action)
{
if (inBulkEditing)
bulkEditing.Add(action);
else
ActionPush(this, action);
}
}
} | 26.361111 | 87 | 0.555321 | [
"Unlicense"
] | Crypticaz/WoWDatabaseEditor | WoWDatabaseEditor.Common/WDE.Common/History/HistoryHandler.cs | 951 | C# |
// Copyright © 2017 Chromely Projects. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the LICENSE file.
namespace Chromely.Browser;
/// <summary>
/// Default CEF render process handler.
/// </summary>
public class DefaultRenderProcessHandler : CefRenderProcessHandler
{
protected readonly IChromelyConfiguration _config;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultRenderProcessHandler"/> class.
/// </summary>
public DefaultRenderProcessHandler(IChromelyConfiguration config)
{
_config = config;
MessageRouter = new CefMessageRouterRendererSide(new CefMessageRouterConfig());
}
/// <summary>
/// Gets the message router.
/// </summary>
public CefMessageRouterRendererSide MessageRouter { get; }
/// <summary>
/// The on context created.
/// </summary>
/// <param name="browser">
/// The browser.
/// </param>
/// <param name="frame">
/// The frame.
/// </param>
/// <param name="context">
/// The context.
/// </param>
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context)
{
MessageRouter.OnContextCreated(context);
// MessageRouter.OnContextCreated doesn't capture CefV8Context immediately,
// so we able to release it immediately in this call.
context.Dispose();
}
/// <summary>
/// The on context released.
/// </summary>
/// <param name="browser">
/// The browser.
/// </param>
/// <param name="frame">
/// The frame.
/// </param>
/// <param name="context">
/// The context.
/// </param>
protected override void OnContextReleased(CefBrowser browser, CefFrame frame, CefV8Context context)
{
// MessageRouter.OnContextReleased releases captured CefV8Context (if have).
MessageRouter.OnContextReleased(browser, frame, context);
// Release CefV8Context.
context.Dispose();
}
protected override bool OnProcessMessageReceived(CefBrowser browser, CefFrame frame, CefProcessId sourceProcess, CefProcessMessage message)
{
var handled = MessageRouter.OnProcessMessageReceived(browser, sourceProcess, message);
if (handled)
{
return true;
}
return false;
}
} | 30.265823 | 143 | 0.64701 | [
"MIT",
"BSD-3-Clause"
] | ScriptBox99/Chromely | src_5.2/Chromely/Browser/Handlers/DefaultRenderProcessHandler.cs | 2,394 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 System;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Apache.NMS;
using Apache.NMS.Util;
using Amqp.Framing;
using Amqp.Types;
namespace Apache.NMS.AMQP.Message.AMQP
{
using Amqp;
using Cloak;
using Util;
using Util.Types;
class AMQPObjectMessageCloak : AMQPMessageCloak, IObjectMessageCloak
{
public static AMQPObjectEncodingType DEFAULT_ENCODING_TYPE = AMQPObjectEncodingType.AMQP_TYPE;
private IAMQPObjectSerializer objectSerializer;
#region Contructors
internal AMQPObjectMessageCloak(Apache.NMS.AMQP.Connection c, AMQPObjectEncodingType type) : base(c)
{
InitializeObjectSerializer(type);
Body = null;
}
internal AMQPObjectMessageCloak(MessageConsumer mc, Amqp.Message message) : base(mc, message)
{
if (message.Properties.ContentType.Equals(SymbolUtil.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE))
{
if(message.MessageAnnotations.Map.ContainsKey(MessageSupport.JMS_JAVA_ENCODING)
&& message.MessageAnnotations.Map[MessageSupport.JMS_JAVA_ENCODING].Equals(SymbolUtil.BOOLEAN_TRUE))
{
InitializeObjectSerializer(AMQPObjectEncodingType.JAVA_SERIALIZABLE);
}
else
{
InitializeObjectSerializer(AMQPObjectEncodingType.DOTNET_SERIALIZABLE);
}
}
else
{
InitializeObjectSerializer(AMQPObjectEncodingType.AMQP_TYPE);
}
}
#endregion
#region Internal Properties Fields
internal override byte JMSMessageType { get { return MessageSupport.JMS_TYPE_OBJ; } }
#endregion
#region Public IObjectMessageCloak Properties
public AMQPObjectEncodingType Type { get { return this.objectSerializer.Type; } }
public object Body
{
get
{
return this.objectSerializer.GetObject();
}
set
{
this.objectSerializer.SetObject(value);
}
}
public override byte[] Content
{
get
{
return null;
}
set
{
}
}
#endregion
#region IMessageCloak Copy Methods
IObjectMessageCloak IObjectMessageCloak.Copy()
{
IObjectMessageCloak ocloak = new AMQPObjectMessageCloak(connection, this.objectSerializer.Type);
this.CopyInto(ocloak);
return ocloak;
}
protected override void CopyInto(IMessageCloak msg)
{
base.CopyInto(msg);
if (msg is IObjectMessageCloak)
{
IObjectMessageCloak copy = msg as IObjectMessageCloak;
if (copy is AMQPObjectMessageCloak)
{
this.objectSerializer.CopyInto((copy as AMQPObjectMessageCloak).objectSerializer);
}
else
{
this.objectSerializer.SetObject(copy.Body);
}
}
}
#endregion
#region Private Methods
private void InitializeObjectSerializer(AMQPObjectEncodingType type)
{
switch (type)
{
case AMQPObjectEncodingType.AMQP_TYPE:
objectSerializer = new AMQPTypeSerializer(this);
break;
case AMQPObjectEncodingType.DOTNET_SERIALIZABLE:
objectSerializer = new DotnetObjectSerializer(this);
break;
case AMQPObjectEncodingType.JAVA_SERIALIZABLE:
objectSerializer = new JavaObjectSerializer(this);
break;
default:
throw NMSExceptionSupport.Create(new ArgumentException("Unsupported object encoding."));
}
}
#endregion
}
#region IAMQPObjectSerializer
#region IAMQPObjectSerializer Interface
internal interface IAMQPObjectSerializer
{
Amqp.Message Message { get; }
void SetObject(object o);
object GetObject();
void CopyInto(IAMQPObjectSerializer serializer);
AMQPObjectEncodingType Type { get; }
}
#endregion
#region AMQP Type IAMQPObjectSerializer Implementation
class AMQPTypeSerializer : IAMQPObjectSerializer
{
private readonly Amqp.Message amqpMessage;
private readonly AMQPObjectMessageCloak message;
internal AMQPTypeSerializer(AMQPObjectMessageCloak msg)
{
amqpMessage = msg.AMQPMessage;
message = msg;
msg.SetMessageAnnotation(MessageSupport.JMS_AMQP_TYPE_ENCODING, SymbolUtil.BOOLEAN_TRUE);
}
public Message Message { get { return amqpMessage; } }
public AMQPObjectEncodingType Type { get { return AMQPObjectEncodingType.AMQP_TYPE; } }
public void CopyInto(IAMQPObjectSerializer serializer)
{
serializer.SetObject(GetObject());
}
public object GetObject()
{
RestrictedDescribed body = amqpMessage.BodySection;
if(body == null)
{
return null;
}
else if (body is AmqpValue)
{
AmqpValue value = body as AmqpValue;
return value.Value;
}
else if (body is Data)
{
return (body as Data).Binary;
}
else if (body is AmqpSequence)
{
return (body as AmqpSequence).List;
}
else
{
throw new IllegalStateException("Unexpected body type: " + body.GetType().Name);
}
}
public void SetObject(object o)
{
if(o == null)
{
amqpMessage.BodySection = MessageSupport.NULL_AMQP_VALUE_BODY;
}
else if (IsNMSObjectTypeSupported(o))
{
object value = null;
if(o is IList)
{
value = ConversionSupport.ListToAmqp(o as IList);
}
else if (o is IPrimitiveMap)
{
value = ConversionSupport.NMSMapToAmqp(o as IPrimitiveMap);
}
else
{
value = o;
}
// to copy the object being set encode a message then decode and take body
Amqp.Message copy = new Amqp.Message(value);
ByteBuffer buffer = copy.Encode();
copy = Message.Decode(buffer);
amqpMessage.BodySection = new AmqpValue { Value = copy.Body };
}
else
{
throw new ArgumentException("Encoding unexpected object type: " + o.GetType().Name);
}
}
private bool IsNMSObjectTypeSupported(object o)
{
return ConversionSupport.IsNMSType(o) || o is List || o is Map || o is IPrimitiveMap || o is IList;
}
}
#endregion
#region Dotnet Serializable IAMQPObjectSerializer Implementation
class DotnetObjectSerializer : IAMQPObjectSerializer
{
private readonly Amqp.Message amqpMessage;
private readonly AMQPObjectMessageCloak message;
internal DotnetObjectSerializer(AMQPObjectMessageCloak msg)
{
amqpMessage = msg.AMQPMessage;
message = msg;
msg.SetContentType(SymbolUtil.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE);
msg.SetMessageAnnotation(MessageSupport.JMS_DONET_ENCODING, SymbolUtil.BOOLEAN_TRUE);
}
public Message Message { get { return amqpMessage; } }
public AMQPObjectEncodingType Type { get { return AMQPObjectEncodingType.DOTNET_SERIALIZABLE; } }
public void CopyInto(IAMQPObjectSerializer serializer)
{
serializer.SetObject(GetObject());
}
public object GetObject()
{
byte[] bin = null;
if(Message.BodySection == null)
{
return null;
}
else if (Message.BodySection is Data)
{
Data data = Message.BodySection as Data;
bin = data.Binary;
}
// TODO handle other body types.
if (bin == null || bin.Length == 0)
{
return null;
}
else
{
return GetDeserializedObject(bin);
}
}
public void SetObject(object o)
{
byte[] bin = GetSerializedObject(o);
if(bin == null || bin.Length == 0)
{
amqpMessage.BodySection = MessageSupport.EMPTY_DATA;
}
else
{
amqpMessage.BodySection = new Data() { Binary = bin };
}
}
private object GetDeserializedObject(byte[] binary)
{
object result = null;
MemoryStream stream = null;
IFormatter formatter = null;
try
{
stream = new MemoryStream(binary);
formatter = new BinaryFormatter();
result = formatter.Deserialize(stream);
}
finally
{
stream?.Close();
}
return result;
}
private byte[] GetSerializedObject(object o)
{
if (o == null) return new byte[] { 0xac,0xed,0x00,0x05,0x70 };
MemoryStream stream = null;
IFormatter formatter = null;
byte[] result = null;
try
{
stream = new MemoryStream();
formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
result = stream.ToArray();
}
finally
{
if(stream!= null)
{
stream.Close();
}
}
return result;
}
}
#endregion
#region Java Serializable IAMQPObjectSerializer Implementation
class JavaObjectSerializer : IAMQPObjectSerializer
{
private readonly Amqp.Message amqpMessage;
private readonly AMQPObjectMessageCloak message;
internal JavaObjectSerializer(AMQPObjectMessageCloak msg)
{
amqpMessage = msg.AMQPMessage;
message = msg;
message.SetContentType(SymbolUtil.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE);
message.SetMessageAnnotation(MessageSupport.JMS_JAVA_ENCODING, SymbolUtil.BOOLEAN_TRUE);
}
public Message Message { get { return amqpMessage; } }
public AMQPObjectEncodingType Type { get { return AMQPObjectEncodingType.JAVA_SERIALIZABLE; } }
public void CopyInto(IAMQPObjectSerializer serializer)
{
// TODO fix to copy java serialized object as binary.
serializer.SetObject(GetObject());
}
public object GetObject()
{
throw new NotImplementedException("Java Serialized Object body Not Supported.");
}
public void SetObject(object o)
{
throw new NotImplementedException("Java Serialized Object body Not Supported.");
}
}
#endregion // Java IAMQPObjectSerializer Impl
#endregion // IAMQPObjectSerializer
}
| 30.751208 | 120 | 0.5606 | [
"Apache-2.0"
] | Havret/activemq-nms-amqp | src/main/csharp/Message/AMQP/AMQPObjectMessageCloak.cs | 12,731 | C# |
// ---------------------------------------------------------------------------------
// <copyright file="LoadVolumeMessageComposer.cs" company="https://github.com/sant0ro/Yupi">
// Copyright (c) 2016 Claudio Santoro, TheDoctor
// </copyright>
// <license>
// 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.
// </license>
// ---------------------------------------------------------------------------------
namespace Yupi.Messages.Contracts
{
using Yupi.Model.Domain.Components;
using Yupi.Protocol.Buffers;
public abstract class LoadVolumeMessageComposer : AbstractComposer<UserPreferences>
{
#region Methods
public override void Compose(Yupi.Protocol.ISender session, UserPreferences preferences)
{
// Do nothing by default.
}
#endregion Methods
}
} | 45.829268 | 96 | 0.660458 | [
"MIT"
] | TheDoct0r11/Yupi | Yupi.Messages.Contracts/Composer/User/LoadVolumeMessageComposer.cs | 1,881 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.DocAsCode.Common;
internal class DfmCodeExtractor
{
private static readonly string RemoveIndentSpacesRegexString = @"^[ \t]{{1,{0}}}";
public DfmExtractCodeResult ExtractFencesCode(DfmFencesBlockToken token, string fencesPath)
{
if (token == null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(fencesPath))
{
throw new ArgumentNullException(nameof(fencesPath));
}
var fencesCode = File.ReadAllLines(fencesPath);
if (token.PathQueryOption == null)
{
// Add the full file when no query option is given
return new DfmExtractCodeResult { IsSuccessful = true, FencesCodeLines = fencesCode };
}
if (!token.PathQueryOption.ValidateAndPrepare(fencesCode, token))
{
Logger.LogError(token.PathQueryOption.ErrorMessage);
return new DfmExtractCodeResult { IsSuccessful = false, ErrorMessage = token.PathQueryOption.ErrorMessage, FencesCodeLines = fencesCode };
}
var includedLines = new List<string>();
foreach (var line in token.PathQueryOption.GetQueryLines(fencesCode))
{
includedLines.Add(line);
}
if (!token.PathQueryOption.ValidateHighlightLinesAndDedentLength(includedLines.Count))
{
Logger.LogWarning(token.PathQueryOption.ErrorMessage);
}
var dedentLength = token.PathQueryOption.DedentLength ??
(from line in includedLines
where !string.IsNullOrEmpty(line) && !string.IsNullOrWhiteSpace(line)
select (int?)DfmCodeExtractorHelper.GetIndentLength(line)).Min() ?? 0;
return new DfmExtractCodeResult
{
IsSuccessful = true,
ErrorMessage = token.PathQueryOption.ErrorMessage,
FencesCodeLines = (dedentLength == 0 ? includedLines : includedLines.Select(s => Regex.Replace(s, string.Format(RemoveIndentSpacesRegexString, dedentLength), string.Empty))).ToArray()
};
}
}
} | 39.626866 | 199 | 0.60678 | [
"MIT"
] | MorganOBN/KoA-Story | src/Microsoft.DocAsCode.Dfm/DfmCodeExtractor.cs | 2,657 | C# |
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using FluentAssertions;
using NUnit.Framework;
using Orckestra.Composer.Utils;
using Orckestra.ForTests;
namespace Orckestra.Composer.Tests.Util
{
[TestFixture]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class CultureInfoEqualityComparer_Equals : BaseTestForAutocreatedSutOfType<CultureInfoEqualityComparer>
{
[TestCase("en-US", "en-us")]
[TestCase("fr-CA", "fr-CA")]
[TestCase("en", "EN")]
[TestCase(null, null)]
public void WHEN_culture_match_SHOULD_return_true(string culture1Name, string culture2Name)
{
//Arrange
var culture1 = string.IsNullOrWhiteSpace(culture1Name) ? null : CultureInfo.GetCultureInfo(culture1Name);
var culture2 = string.IsNullOrWhiteSpace(culture2Name) ? null : CultureInfo.GetCultureInfo(culture2Name);
var equalityComparer = Container.CreateInstance<CultureInfoEqualityComparer>();
//Act
var result = equalityComparer.Equals(culture1, culture2);
//Assert
result.Should().BeTrue();
}
[TestCase("en-US", "en")]
[TestCase("fr", "fr-CA")]
[TestCase(null, "fr-CA")]
[TestCase("en-US", null)]
public void WHEN_culture_does_not_match_SHOULD_return_false(string culture1Name, string culture2Name)
{
//Arrange
var culture1 = string.IsNullOrWhiteSpace(culture1Name) ? null : CultureInfo.GetCultureInfo(culture1Name);
var culture2 = string.IsNullOrWhiteSpace(culture2Name) ? null : CultureInfo.GetCultureInfo(culture2Name);
var equalityComparer = Container.CreateInstance<CultureInfoEqualityComparer>();
//Act
var result = equalityComparer.Equals(culture1, culture2);
//Assert
result.Should().BeFalse();
}
}
}
| 38.078431 | 117 | 0.662719 | [
"MIT"
] | InnaBoitsun/BetterRetailGroceryTest | tests/Orckestra.Composer.Tests/Util/CultureInfoEqualityComparer_Equals.cs | 1,944 | 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;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Peek;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek
{
[Export(typeof(IPeekableItemFactory))]
internal class PeekableItemFactory : IPeekableItemFactory
{
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
[ImportingConstructor]
private PeekableItemFactory(IMetadataAsSourceFileService metadataAsSourceFileService)
{
_metadataAsSourceFileService = metadataAsSourceFileService;
}
public async Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken)
{
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
if (peekResultFactory == null)
{
throw new ArgumentNullException(nameof(peekResultFactory));
}
var results = new List<IPeekableItem>();
var solution = project.Solution;
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
// And if our definition actually is from source, then let's re-figure out what project it came from
if (sourceDefinition != null)
{
var originatingProject = solution.GetProject(sourceDefinition.ContainingAssembly, cancellationToken);
project = originatingProject ?? project;
}
string filePath;
int lineNumber;
int charOffset;
var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>();
if (symbolNavigationService.WouldNavigateToSymbol(symbol, solution, out filePath, out lineNumber, out charOffset))
{
var position = new LinePosition(lineNumber, charOffset);
results.Add(new ExternalFilePeekableItem(new FileLinePositionSpan(filePath, position, position), PredefinedPeekRelationships.Definitions, peekResultFactory));
}
else
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var symbolKey = SymbolKey.Create(symbol, compilation, cancellationToken);
var firstLocation = symbol.Locations.FirstOrDefault();
if (firstLocation != null)
{
if (firstLocation.IsInSource || _metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
results.Add(new DefinitionPeekableItem(solution.Workspace, project.Id, symbolKey, peekResultFactory, _metadataAsSourceFileService));
}
}
}
return results;
}
}
}
| 40.556818 | 183 | 0.663211 | [
"Apache-2.0"
] | 0x53A/roslyn | src/EditorFeatures/Core/Implementation/Peek/PeekableItemFactory.cs | 3,569 | C# |
using MaterialDesignControls.Options.Settings;
using Prism.Ioc;
using Prism.Modularity;
namespace MaterialDesignControls.Options
{
public class OptionViewsModule : IModule
{
public void OnInitialized(IContainerProvider containerProvider)
{
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<SettingPanel, SettingPanelViewModel>();
containerRegistry.RegisterForNavigation<AboutPanel, AboutPanelViewModel>();
}
}
} | 25.65 | 83 | 0.783626 | [
"Apache-2.0"
] | YouseiSakusen/WpfUiGallery | 03_MaterialDesignControls01/OptionViews/OptionViewsModule.cs | 515 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.