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 |
|---|---|---|---|---|---|---|---|---|
// <copyright file="TargettedSkillHandler.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameServer.MessageHandler
{
using MUnique.OpenMU.GameLogic;
using MUnique.OpenMU.GameLogic.PlayerActions;
using MUnique.OpenMU.GameLogic.Views;
using MUnique.OpenMU.Network;
/// <summary>
/// Handler for targetted skill packets.
/// </summary>
internal class TargettedSkillHandler : BasePacketHandler
{
private readonly TargettedSkillAction attackAction;
/// <summary>
/// Initializes a new instance of the <see cref="TargettedSkillHandler"/> class.
/// </summary>
/// <param name="gameContext">The game context.</param>
public TargettedSkillHandler(IGameContext gameContext)
: base(gameContext)
{
this.attackAction = new TargettedSkillAction();
}
/// <inheritdoc/>
public override void HandlePacket(Player player, byte[] packet)
{
//// skill targt
////C3 len 19 XX XX TT TT
ushort skillId = NumberConversionExtensions.MakeWord(packet[4], packet[3]);
if (!player.SkillList.ContainsSkill(skillId))
{
return;
}
// The target can be the own player too, for example when using buff skills.
ushort targetId = NumberConversionExtensions.MakeWord(packet[6], packet[5]);
if (player.GetObject(targetId) is IAttackable target)
{
this.attackAction.PerformSkill(player, target, skillId);
}
}
}
}
| 34.64 | 101 | 0.619515 | [
"MIT"
] | ThisMushroom/OpenMU-1 | src/GameServer/MessageHandler/TargettedSkillHandler.cs | 1,734 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class Reports
{
public string personel_isim { get; set; }
public string personel_soyisim { get; set; }
public int aksiyon_sayisi { get; set; }
}
}
| 20.5625 | 52 | 0.680851 | [
"MIT"
] | atasenturk/Personnel-Tracking-System | applicationUI/PersonnelTrackingSystem/Entities/Reports.cs | 331 | C# |
namespace Sitecore.Feature.Blog.Repositories
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using ContentSearch.Linq;
using ContentSearch.SearchTypes;
using Data;
using Search;
public interface IBlogRepository<T> where T : SearchResultItem
{
T Get(ID id);
T Get(string slug);
ISearchQuery<T> MakeQuery();
IEnumerable<T> Query(ISearchQuery<T> query);
FacetResults Archives<TKey>(ISearchQuery<T> query, Expression<Func<T, TKey>> keySelector);
}
} | 24.521739 | 98 | 0.675532 | [
"MIT"
] | KKings/Sitecore.Feature.Blog | src/Feature/Blog/code/Repositories/IBlogRepository.cs | 566 | C# |
using nanoFramework.CoAP.Channels;
using nanoFramework.CoAP.Exceptions;
using nanoFramework.CoAP.Helpers;
using nanoFramework.CoAP.Message;
using nanoFramework.Networking;
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
namespace nanoFramework.CoAP.Samples
{
public class ObserverClient
{
/// <summary>
/// Holds an instance of the CoAP client
/// </summary>
private static CoAPClientChannel coapClient = null;
/// <summary>
/// Will keep a count of how many notifications we received so far
/// </summary>
private static int countOfNotifications = 0;
/// <summary>
/// The last observed sequence number
/// </summary>
private static int lastObsSeq = 0;
/// <summary>
/// Last time the observable notification was received.
/// </summary>
private static DateTime lastObsRx = DateTime.MinValue;
/// <summary>
/// Entry point
/// </summary>
public static void Main()
{
NetworkHelpers.SetupAndConnectNetwork();
SetupClient();
SendRequest();
while (true)
{
Thread.Sleep(3000);
}
}
/// <summary>
/// Setup the client
/// </summary>
public static void SetupClient()
{
coapClient = new CoAPClientChannel();
coapClient.Initialize("localhost", 5683);
coapClient.CoAPError += new CoAPErrorHandler(OnCoAPError);
coapClient.CoAPRequestReceived += new CoAPRequestReceivedHandler(OnCoAPRequestReceived);
coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPResponseReceived);
}
/// <summary>
/// Send the request to get the temperature
/// </summary>
public static void SendRequest()
{
string urlToCall = "coap://localhost:5683/sensors/temp/observe";
UInt16 mId = coapClient.GetNextMessageID();//Using this method to get the next message id takes care of pending CON requests
CoAPRequest tempReq = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.GET, mId);
tempReq.SetURL(urlToCall);
//Important::Add the Observe option
tempReq.AddOption(CoAPHeaderOption.OBSERVE, null);//Value of observe option has no meaning in request
tempReq.AddTokenValue(DateTime.Today.ToString("HHmmss"));//must be <= 8 bytes
/*Uncomment the two lines below to use non-default values for timeout and retransmission count*/
/*Dafault value for timeout is 2 secs and retransmission count is 4*/
//tempReq.Timeout = 10;
//tempReq.RetransmissionCount = 5;
coapClient.Send(tempReq);
}
/// <summary>
/// We should receive an ACK to indicate we successfully registered with
/// the server to observe the resource
/// </summary>
/// <param name="coapResp">CoAPResponse</param>
static void OnCoAPResponseReceived(CoAPResponse coapResp)
{
if (coapResp.MessageType.Value == CoAPMessageType.ACK &&
coapResp.Code.Value == CoAPMessageCode.EMPTY)
Debug.WriteLine("Registered successfully to observe temperature");
else
Debug.WriteLine("Failed to register for temperature observation");
}
/// <summary>
/// Going forward, we will receive temperature notifications from
/// server in a CON request
/// </summary>
/// <param name="coapReq">CoAPRequest</param>
static void OnCoAPRequestReceived(CoAPRequest coapReq)
{
if (coapReq.MessageType.Value == CoAPMessageType.CON)
{
//Extract the temperature..but first, check if the notification is fresh
//The server sends a 4-digit sequence number
int newObsSeq = AbstractByteUtils.ToUInt16(coapReq.Options.GetOption(CoAPHeaderOption.OBSERVE).Value);
if ((lastObsSeq < newObsSeq && ((newObsSeq - lastObsSeq) < (System.Math.Pow(2.0, 23.0)))) ||
(lastObsSeq > newObsSeq && ((lastObsSeq - newObsSeq) > (System.Math.Pow(2.0, 23.0)))) ||
DateTime.Today > lastObsRx.AddSeconds(128))
{
//The value received from server is new....read the new temperature
//We got the temperature..it will be in payload in JSON
string payload = AbstractByteUtils.ByteToStringUTF8(coapReq.Payload.Value);
Hashtable keyVal = JSONResult.FromJSON(payload);
int temp = Convert.ToInt32(keyVal["temp"].ToString());
//do something with the temperature now
Debug.WriteLine(coapReq.ToString());
}
//update how many notifications received
countOfNotifications++;
if (countOfNotifications > 5)
{
//We are no longer interested...send RST to de-register
CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.EMPTY, coapReq.ID.Value);
resp.RemoteSender = coapReq.RemoteSender;
resp.Token = coapReq.Token;//Do not forget this...this is how messages are correlated
coapClient.Send(resp);
}
else
{
//we are still interested...send ACK
CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.EMPTY, coapReq.ID.Value);
resp.RemoteSender = coapReq.RemoteSender;
resp.Token = coapReq.Token;//Do not forget this...this is how messages are correlated
coapClient.Send(resp);
}
lastObsSeq = newObsSeq;
lastObsRx = DateTime.Today;
}
}
/// <summary>
/// Handle error
/// </summary>
/// <param name="e">The exception that occurred</param>
/// <param name="associatedMsg">The associated message (if any)</param>
static void OnCoAPError(Exception e, AbstractCoAPMessage associatedMsg)
{
if (e.GetType() == typeof(UndeliveredException))
{
//Some CON message never got delivered...
CoAPRequest undeliveredCONReq = (CoAPRequest)associatedMsg;
//Now take action on this underlivered request
}
}
}
}
| 45.253333 | 136 | 0.579847 | [
"MIT"
] | vgolovanov/nanoFramework.CoAP | nanoFramework.CoAP.Samples/ObserverClient.cs | 6,790 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Razor.Language.Intermediate;
using Xunit;
using static Microsoft.AspNetCore.Razor.Language.Intermediate.IntermediateNodeAssert;
namespace Microsoft.AspNetCore.Razor.Language.Extensions;
public class SectionDirectivePassTest
{
[Fact]
public void Execute_SkipsDocumentWithNoClassNode()
{
// Arrange
var projectEngine = CreateProjectEngine();
var pass = new SectionDirectivePass()
{
Engine = projectEngine.Engine,
};
var sourceDocument = TestRazorSourceDocument.Create("@section Header { <p>Hello World</p> }");
var codeDocument = RazorCodeDocument.Create(sourceDocument);
var irDocument = new DocumentIntermediateNode();
irDocument.Children.Add(new DirectiveIntermediateNode() { Directive = SectionDirective.Directive, });
// Act
pass.Execute(codeDocument, irDocument);
// Assert
Children(
irDocument,
node => Assert.IsType<DirectiveIntermediateNode>(node));
}
[Fact]
public void Execute_WrapsStatementInSectionNode()
{
// Arrange
var projectEngine = CreateProjectEngine();
var pass = new SectionDirectivePass()
{
Engine = projectEngine.Engine,
};
var content = "@section Header { <p>Hello World</p> }";
var sourceDocument = TestRazorSourceDocument.Create(content);
var codeDocument = RazorCodeDocument.Create(sourceDocument);
var irDocument = Lower(codeDocument, projectEngine);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
Children(
irDocument,
node => Assert.IsType<NamespaceDeclarationIntermediateNode>(node));
var @namespace = irDocument.Children[0];
Children(
@namespace,
node => Assert.IsType<ClassDeclarationIntermediateNode>(node));
var @class = @namespace.Children[0];
var method = SingleChild<MethodDeclarationIntermediateNode>(@class);
Children(
method,
node => Assert.IsType<DirectiveIntermediateNode>(node),
node => Assert.IsType<SectionIntermediateNode>(node));
var section = method.Children[1] as SectionIntermediateNode;
Assert.Equal("Header", section.SectionName);
Children(section, c => Html(" <p>Hello World</p> ", c));
}
private static RazorProjectEngine CreateProjectEngine()
{
return RazorProjectEngine.Create(b =>
{
SectionDirective.Register(b);
});
}
private static DocumentIntermediateNode Lower(RazorCodeDocument codeDocument, RazorProjectEngine projectEngine)
{
for (var i = 0; i < projectEngine.Phases.Count; i++)
{
var phase = projectEngine.Phases[i];
phase.Execute(codeDocument);
if (phase is IRazorDocumentClassifierPhase)
{
break;
}
}
var irDocument = codeDocument.GetDocumentIntermediateNode();
Assert.NotNull(irDocument);
return irDocument;
}
}
| 31.09434 | 115 | 0.637743 | [
"MIT"
] | MitrichDot/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/SectionDirectivePassTest.cs | 3,298 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.CommandLine.Parsing;
using Microsoft.Deployment.DotNet.Releases;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using Microsoft.NET.Sdk.WorkloadManifestReader;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Workloads.Workload.Install.InstallRecord;
using Microsoft.DotNet.Cli.NuGetPackageDownloader;
using Microsoft.Extensions.EnvironmentAbstractions;
using Microsoft.DotNet.Workloads.Workload.Install;
using NuGet.Common;
namespace Microsoft.DotNet.Workloads.Workload.Repair
{
internal class WorkloadRepairCommand : CommandBase
{
private readonly IReporter _reporter;
private readonly PackageSourceLocation _packageSourceLocation;
private readonly VerbosityOptions _verbosity;
private readonly IInstaller _workloadInstaller;
private IWorkloadResolver _workloadResolver;
private readonly ReleaseVersion _sdkVersion;
private readonly string _dotnetPath;
public WorkloadRepairCommand(
ParseResult parseResult,
IReporter reporter = null,
IWorkloadResolver workloadResolver = null,
IInstaller workloadInstaller = null,
INuGetPackageDownloader nugetPackageDownloader = null,
string dotnetDir = null,
string tempDirPath = null,
string version = null,
string userProfileDir = null)
: base(parseResult)
{
_reporter = reporter ?? Reporter.Output;
_verbosity = parseResult.GetValueForOption(WorkloadRepairCommandParser.VerbosityOption);
_dotnetPath = dotnetDir ?? Path.GetDirectoryName(Environment.ProcessPath);
userProfileDir ??= CliFolderPathCalculator.DotnetUserProfileFolderPath;
_sdkVersion = WorkloadOptionsExtensions.GetValidatedSdkVersion(parseResult.GetValueForOption(WorkloadRepairCommandParser.VersionOption), version, _dotnetPath, userProfileDir);
var configOption = parseResult.GetValueForOption(WorkloadRepairCommandParser.ConfigOption);
var sourceOption = parseResult.GetValueForOption(WorkloadRepairCommandParser.SourceOption);
_packageSourceLocation = string.IsNullOrEmpty(configOption) && (sourceOption == null || !sourceOption.Any()) ? null :
new PackageSourceLocation(string.IsNullOrEmpty(configOption) ? null : new FilePath(configOption), sourceFeedOverrides: sourceOption);
var workloadManifestProvider = new SdkDirectoryWorkloadManifestProvider(_dotnetPath, _sdkVersion.ToString(), userProfileDir);
_workloadResolver = workloadResolver ?? WorkloadResolver.Create(workloadManifestProvider, _dotnetPath, _sdkVersion.ToString(), userProfileDir);
var sdkFeatureBand = new SdkFeatureBand(_sdkVersion);
tempDirPath = tempDirPath ?? (string.IsNullOrWhiteSpace(parseResult.GetValueForOption(WorkloadInstallCommandParser.TempDirOption)) ?
Path.GetTempPath() :
parseResult.GetValueForOption(WorkloadInstallCommandParser.TempDirOption));
var tempPackagesDir = new DirectoryPath(Path.Combine(tempDirPath, "dotnet-sdk-advertising-temp"));
NullLogger nullLogger = new NullLogger();
nugetPackageDownloader ??= new NuGetPackageDownloader(
tempPackagesDir,
filePermissionSetter: null,
new FirstPartyNuGetPackageSigningVerifier(tempPackagesDir, nullLogger), nullLogger, restoreActionConfig: _parseResult.ToRestoreActionConfig());
_workloadInstaller = workloadInstaller ??
WorkloadInstallerFactory.GetWorkloadInstaller(_reporter, sdkFeatureBand,
_workloadResolver, _verbosity, userProfileDir, nugetPackageDownloader, dotnetDir, tempDirPath,
_packageSourceLocation, _parseResult.ToRestoreActionConfig());
}
public override int Execute()
{
try
{
_reporter.WriteLine();
var workloadIds = _workloadInstaller.GetWorkloadInstallationRecordRepository().GetInstalledWorkloads(new SdkFeatureBand(_sdkVersion));
if (!workloadIds.Any())
{
_reporter.WriteLine(LocalizableStrings.NoWorkloadsToRepair);
return 0;
}
_reporter.WriteLine(string.Format(LocalizableStrings.RepairingWorkloads, string.Join(" ", workloadIds)));
ReinstallWorkloadsBasedOnCurrentManifests(workloadIds, new SdkFeatureBand(_sdkVersion));
WorkloadInstallCommand.TryRunGarbageCollection(_workloadInstaller, _reporter, _verbosity);
_reporter.WriteLine();
_reporter.WriteLine(string.Format(LocalizableStrings.RepairSucceeded, string.Join(" ", workloadIds)));
_reporter.WriteLine();
}
catch (Exception e)
{
// Don't show entire stack trace
throw new GracefulException(string.Format(LocalizableStrings.WorkloadRepairFailed, e.Message), e, isUserError: false);
}
finally
{
_workloadInstaller.Shutdown();
}
return _workloadInstaller.ExitCode;
}
private void ReinstallWorkloadsBasedOnCurrentManifests(IEnumerable<WorkloadId> workloadIds, SdkFeatureBand sdkFeatureBand)
{
if (_workloadInstaller.GetInstallationUnit().Equals(InstallationUnit.Packs))
{
var installer = _workloadInstaller.GetPackInstaller();
var packsToInstall = workloadIds
.SelectMany(workloadId => _workloadResolver.GetPacksInWorkload(workloadId))
.Distinct()
.Select(packId => _workloadResolver.TryGetPackInfo(packId))
.Where(pack => pack != null);
foreach (var packId in packsToInstall)
{
installer.RepairWorkloadPack(packId, sdkFeatureBand);
}
}
else
{
throw new NotImplementedException();
}
}
}
}
| 48.731343 | 187 | 0.672282 | [
"MIT"
] | 01xOfFoo/sdk | src/Cli/dotnet/commands/dotnet-workload/repair/WorkloadRepairCommand.cs | 6,530 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
//using System.Windows.Controls;
//using System.Windows.Data;
//using System.Windows.Documents;
//using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Imaging;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
namespace PreviewForms
{
class PreviewForm
{
}
}
| 20.52381 | 37 | 0.761021 | [
"MIT"
] | evkapsal/SCSM-2016-IT-Asset-Management | PreviewForms/PreviewForm.cs | 433 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SecurityGroupExtensionMethods.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.AWS.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon;
using Amazon.EC2;
using Naos.AWS.Domain;
/// <summary>
/// Extensions on <see cref="SecurityGroup" />.
/// </summary>
public static class SecurityGroupExtensionMethods
{
/// <summary>
/// Checks to see if the object exists on the AWS servers.
/// </summary>
/// <param name="securityGroup">Object to operate on.</param>
/// <param name="credentials">Credentials to use (will use the credentials from CredentialManager.Cached if null...).</param>
/// <returns>Whether or not is was found.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Aws", Justification = "Spelling/name is correct.")]
public static async Task<bool> ExistsOnAwsAsync(this SecurityGroup securityGroup, CredentialContainer credentials = null)
{
var awsCredentials = CredentialManager.GetAwsCredentials(credentials);
var regionEndpoint = RegionEndpoint.GetBySystemName(securityGroup.Region);
using (var client = new AmazonEC2Client(awsCredentials, regionEndpoint))
{
var request = new Amazon.EC2.Model.DescribeSecurityGroupsRequest() { GroupIds = new[] { securityGroup.Id }.ToList() };
var response = await client.DescribeSecurityGroupsAsync(request);
Validator.ThrowOnBadResult(request, response);
return response.SecurityGroups.Any(_ => _.GroupId == securityGroup.Id);
}
}
}
}
| 45.297872 | 187 | 0.590418 | [
"MIT"
] | NaosFramework/Naos.AWS | Naos.AWS.Core/SecurityGroupExtensionMethods.cs | 2,131 | C# |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.Samples.VisualStudio.CodeSweep.UnitTests
{
class MockDTESolution : EnvDTE.Solution
{
readonly IServiceProvider _serviceProvider;
readonly MockDTEProjects _projects;
public MockDTESolution(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_projects = new MockDTEProjects(_serviceProvider);
}
#region _Solution Members
public EnvDTE.Project AddFromFile(string FileName, bool Exclusive)
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.Project AddFromTemplate(string FileName, string Destination, string ProjectName, bool Exclusive)
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.AddIns AddIns
{
get { throw new Exception("The method or operation is not implemented."); }
}
public void Close(bool SaveFirst)
{
throw new Exception("The method or operation is not implemented.");
}
public int Count
{
get { throw new Exception("The method or operation is not implemented."); }
}
public void Create(string Destination, string Name)
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.DTE DTE
{
get { throw new Exception("The method or operation is not implemented."); }
}
public string ExtenderCATID
{
get { throw new Exception("The method or operation is not implemented."); }
}
public object ExtenderNames
{
get { throw new Exception("The method or operation is not implemented."); }
}
public string FileName
{
get { throw new Exception("The method or operation is not implemented."); }
}
public EnvDTE.ProjectItem FindProjectItem(string FileName)
{
throw new Exception("The method or operation is not implemented.");
}
public string FullName
{
get { throw new Exception("The method or operation is not implemented."); }
}
public System.Collections.IEnumerator GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.Globals Globals
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool IsDirty
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public bool IsOpen
{
get { throw new Exception("The method or operation is not implemented."); }
}
public EnvDTE.Project Item(object index)
{
throw new Exception("The method or operation is not implemented.");
}
public void Open(string FileName)
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.DTE Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
public string ProjectItemsTemplatePath(string ProjectKind)
{
throw new Exception("The method or operation is not implemented.");
}
public EnvDTE.Projects Projects
{
get { return _projects; }
}
public EnvDTE.Properties Properties
{
get { throw new Exception("The method or operation is not implemented."); }
}
public void Remove(EnvDTE.Project proj)
{
throw new Exception("The method or operation is not implemented.");
}
public void SaveAs(string FileName)
{
throw new Exception("The method or operation is not implemented.");
}
public bool Saved
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public EnvDTE.SolutionBuild SolutionBuild
{
get { throw new Exception("The method or operation is not implemented."); }
}
public object get_Extender(string ExtenderName)
{
throw new Exception("The method or operation is not implemented.");
}
public string get_TemplatePath(string ProjectType)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| 29.582011 | 118 | 0.57217 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Visual Studio Product Team/Visual Studio 2010 SDK Samples/60968-Visual Studio 2010 SDK Samples/Code Sweep/C#,C++/TDD/Mocks/MockDTESolution.cs | 5,591 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
namespace Amazon.PowerShell.Cmdlets.CFN
{
/// <summary>
/// Returns summary information about stack sets that are associated with the user.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration.
/// </summary>
[Cmdlet("Get", "CFNStackSetList")]
[OutputType("Amazon.CloudFormation.Model.StackSetSummary")]
[AWSCmdlet("Calls the AWS CloudFormation ListStackSets API operation.", Operation = new[] {"ListStackSets"}, SelectReturnType = typeof(Amazon.CloudFormation.Model.ListStackSetsResponse))]
[AWSCmdletOutput("Amazon.CloudFormation.Model.StackSetSummary or Amazon.CloudFormation.Model.ListStackSetsResponse",
"This cmdlet returns a collection of Amazon.CloudFormation.Model.StackSetSummary objects.",
"The service call response (type Amazon.CloudFormation.Model.ListStackSetsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetCFNStackSetListCmdlet : AmazonCloudFormationClientCmdlet, IExecutor
{
#region Parameter Status
/// <summary>
/// <para>
/// <para>The status of the stack sets that you want to get summary information about.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
[AWSConstantClassSource("Amazon.CloudFormation.StackSetStatus")]
public Amazon.CloudFormation.StackSetStatus Status { get; set; }
#endregion
#region Parameter MaxResult
/// <summary>
/// <para>
/// <para>The maximum number of results to be returned with a single call. If the number of
/// available results exceeds this maximum, the response includes a <code>NextToken</code>
/// value that you can assign to the <code>NextToken</code> request parameter to get the
/// next set of results.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet.
/// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call.
/// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("MaxItems","MaxResults")]
public int? MaxResult { get; set; }
#endregion
#region Parameter NextToken
/// <summary>
/// <para>
/// <para>If the previous paginated request didn't return all of the remaining results, the
/// response object's <code>NextToken</code> parameter value is set to a token. To retrieve
/// the next set of results, call <code>ListStackSets</code> again and assign that token
/// to the request object's <code>NextToken</code> parameter. If there are no remaining
/// results, the previous response object's <code>NextToken</code> parameter is set to
/// <code>null</code>.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call.
/// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String NextToken { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'Summaries'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CloudFormation.Model.ListStackSetsResponse).
/// Specifying the name of a property of type Amazon.CloudFormation.Model.ListStackSetsResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "Summaries";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the Status parameter.
/// The -PassThru parameter is deprecated, use -Select '^Status' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Status' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter NoAutoIteration
/// <summary>
/// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple
/// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken
/// as the start point.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoAutoIteration { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.CloudFormation.Model.ListStackSetsResponse, GetCFNStackSetListCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.Status;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.MaxResult = this.MaxResult;
#if !MODULAR
if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue)
{
WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." +
" This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" +
" retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" +
" to the service to specify how many items should be returned by each service call.");
}
#endif
context.NextToken = this.NextToken;
context.Status = this.Status;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
#if MODULAR
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
// create request and set iteration invariants
var request = new Amazon.CloudFormation.Model.ListStackSetsRequest();
if (cmdletContext.MaxResult != null)
{
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
}
if (cmdletContext.Status != null)
{
request.Status = cmdletContext.Status;
}
// Initialize loop variant and commence piping
var _nextToken = cmdletContext.NextToken;
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
_nextToken = response.NextToken;
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#else
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
// create request and set iteration invariants
var request = new Amazon.CloudFormation.Model.ListStackSetsRequest();
if (cmdletContext.Status != null)
{
request.Status = cmdletContext.Status;
}
// Initialize loop variants and commence piping
System.String _nextToken = null;
int? _emitLimit = null;
int _retrievedSoFar = 0;
if (AutoIterationHelpers.HasValue(cmdletContext.NextToken))
{
_nextToken = cmdletContext.NextToken;
}
if (AutoIterationHelpers.HasValue(cmdletContext.MaxResult))
{
// The service has a maximum page size of 100. If the user has
// asked for more items than page max, and there is no page size
// configured, we rely on the service ignoring the set maximum
// and giving us 100 items back. If a page size is set, that will
// be used to configure the pagination.
// We'll make further calls to satisfy the user's request.
_emitLimit = cmdletContext.MaxResult;
}
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
if (_emitLimit.HasValue)
{
int correctPageSize = AutoIterationHelpers.Min(100, _emitLimit.Value);
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
}
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
int _receivedThisCall = response.Summaries.Count;
_nextToken = response.NextToken;
_retrievedSoFar += _receivedThisCall;
if (_emitLimit.HasValue)
{
_emitLimit -= _receivedThisCall;
}
}
catch (Exception e)
{
if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
{
output = new CmdletOutput { ErrorResponse = e };
}
else
{
break;
}
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#endif
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.CloudFormation.Model.ListStackSetsResponse CallAWSServiceOperation(IAmazonCloudFormation client, Amazon.CloudFormation.Model.ListStackSetsRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CloudFormation", "ListStackSets");
try
{
#if DESKTOP
return client.ListStackSets(request);
#elif CORECLR
return client.ListStackSetsAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public int? MaxResult { get; set; }
public System.String NextToken { get; set; }
public Amazon.CloudFormation.StackSetStatus Status { get; set; }
public System.Func<Amazon.CloudFormation.Model.ListStackSetsResponse, GetCFNStackSetListCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.Summaries;
}
}
}
| 47.146667 | 319 | 0.583767 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/CloudFormation/Basic/Get-CFNStackSetList-Cmdlet.cs | 17,680 | C# |
using UnityEngine;
namespace Fps.Movement
{
public struct MovementRequest
{
public int Timestamp;
public Vector3 Movement;
public MovementRequest(int timestamp, Vector3 movement)
{
Timestamp = timestamp;
Movement = movement;
}
}
}
| 18.176471 | 63 | 0.595469 | [
"MIT"
] | AllTradesGames/gdk-for-unity-fps-starter-project | workers/unity/Assets/Fps/Scripts/Movement/Behaviours/MovementRequest.cs | 309 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。
// 如果重新生成代码,将覆盖对此文件的手动更改。
// author MEIAM
// </auto-generated>
//------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
using System;
using System.Linq;
using System.Text;
using SqlSugar;
namespace Meiam.System.Model
{
///<summary>
///计划任务
///</summary>
[SugarTable("Sys_TasksQz")]
public class Sys_TasksQz
{
public Sys_TasksQz()
{
}
/// <summary>
/// 描述 : UID
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "UID")]
[SugarColumn(IsPrimaryKey=true)]
public string ID {get;set;}
/// <summary>
/// 描述 : 任务名称
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "任务名称")]
public string Name {get;set;}
/// <summary>
/// 描述 : 任务分组
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "任务分组")]
public string JobGroup {get;set;}
/// <summary>
/// 描述 : 运行时间表达式
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "运行时间表达式")]
public string Cron {get;set;}
/// <summary>
/// 描述 : 程序集名称
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "程序集名称")]
public string AssemblyName {get;set;}
/// <summary>
/// 描述 : 任务所在类
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "任务所在类")]
public string ClassName {get;set;}
/// <summary>
/// 描述 : 任务描述
/// 空值 : True
/// 默认 :
/// </summary>
[Display(Name = "任务描述")]
public string Remark {get;set;}
/// <summary>
/// 描述 : 执行次数
/// 空值 : False
/// 默认 : 0
/// </summary>
[Display(Name = "执行次数")]
public int RunTimes {get;set;}
/// <summary>
/// 描述 : 开始时间
/// 空值 : True
/// 默认 :
/// </summary>
[Display(Name = "开始时间")]
public DateTime? BeginTime {get;set;}
/// <summary>
/// 描述 : 结束时间
/// 空值 : True
/// 默认 :
/// </summary>
[Display(Name = "结束时间")]
public DateTime? EndTime {get;set;}
/// <summary>
/// 描述 : 触发器类型(0、simple 1、cron)
/// 空值 : False
/// 默认 : 1
/// </summary>
[Display(Name = "触发器类型(0、simple 1、cron)")]
public int TriggerType {get;set;}
/// <summary>
/// 描述 : 执行间隔时间(单位:秒)
/// 空值 : False
/// 默认 : 0
/// </summary>
[Display(Name = "执行间隔时间(单位:秒)")]
public int IntervalSecond {get;set;}
/// <summary>
/// 描述 : 是否启动
/// 空值 : False
/// 默认 : 0
/// </summary>
[Display(Name = "是否启动")]
public bool IsStart {get;set;}
/// <summary>
/// 描述 : 传入参数
/// 空值 : True
/// 默认 :
/// </summary>
[Display(Name = "传入参数")]
public string JobParams {get;set;}
/// <summary>
/// 描述 : 创建时间
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "创建时间")]
public DateTime CreateTime {get;set;}
/// <summary>
/// 描述 : 最后更新时间
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "最后更新时间")]
public DateTime UpdateTime {get;set;}
/// <summary>
/// 描述 : 创建人编码
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "创建人编码")]
public string CreateID {get;set;}
/// <summary>
/// 描述 : 创建人
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "创建人")]
public string CreateName {get;set;}
/// <summary>
/// 描述 : 更新人编码
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "更新人编码")]
public string UpdateID {get;set;}
/// <summary>
/// 描述 : 更新人
/// 空值 : False
/// 默认 :
/// </summary>
[Display(Name = "更新人")]
public string UpdateName {get;set;}
}
} | 26.689474 | 81 | 0.347663 | [
"Apache-2.0"
] | 91270/Meiam.System | Meiam.System.Model/Entity/Sys_TasksQz.cs | 5,801 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using EOSNewYork.EOSCore.ActionArgs;
using EOSNewYork.EOSCore.Response.API;
using EOSNewYork.EOSCore.Utilities;
using NextGenSoftware.OASIS.API.Core;
using NextGenSoftware.OASIS.API.Core.Managers;
using NextGenSoftware.OASIS.API.Core.Interfaces;
using NextGenSoftware.OASIS.API.Core.Enums;
using NextGenSoftware.OASIS.API.Providers.SEEDSOASIS.Membranes;
using NextGenSoftware.OASIS.API.Core.Helpers;
namespace NextGenSoftware.OASIS.API.Providers.SEEDSOASIS
{
public class SEEDSOASIS : OASISProvider, IOASISApplicationProvider
{
private static Random _random = new Random();
private AvatarManager _avatarManager = null;
public const string ENDPOINT_TEST = "https://test.hypha.earth";
public const string ENDPOINT_LIVE = "https://node.hypha.earth";
public const string SEEDS_EOSIO_ACCOUNT_TEST = "seeds";
public const string SEEDS_EOSIO_ACCOUNT_LIVE = "seed.seeds";
public const string CHAINID_TEST = "1eaa0824707c8c16bd25145493bf062aecddfeb56c736f6ba6397f3195f33c9f";
public const string CHAINID_LIVE = "4667b205c6838ef70ff7988f6e8257e8be0e1284a2f59699054a018f743b1d11";
public const string PUBLICKEY_TEST = "EOS8MHrY9xo9HZP4LvZcWEpzMVv1cqSLxiN2QMVNy8naSi1xWZH29";
public const string PUBLICKEY_TEST2 = "EOS8C9tXuPMkmB6EA7vDgGtzA99k1BN6UxjkGisC1QKpQ6YV7MFqm";
public const string PUBLICKEY_LIVE = "EOS6kp3dm9Ug5D3LddB8kCMqmHg2gxKpmRvTNJ6bDFPiop93sGyLR";
public const string PUBLICKEY_LIVE2 = "EOS6kp3dm9Ug5D3LddB8kCMqmHg2gxKpmRvTNJ6bDFPiop93sGyLR";
public const string APIKEY_TEST = "EOS7YXUpe1EyMAqmuFWUheuMaJoVuY3qTD33WN4TrXbEt8xSKrdH9";
public const string APIKEY_LIVE = "EOS7YXUpe1EyMAqmuFWUheuMaJoVuY3qTD33WN4TrXbEt8xSKrdH9";
public TelosOASIS.TelosOASIS TelosOASIS { get; }
//TODO: Not sure if this should share the EOSOASIS AvatarManagerInstance? May be better to have seperate?
private AvatarManager AvatarManagerInstance
{
get
{
if (_avatarManager == null)
{
if (TelosOASIS != null)
_avatarManager = new AvatarManager(ProviderManager.GetStorageProvider(Core.Enums.ProviderType.MongoDBOASIS));
//_avatarManager = new AvatarManager(TelosOASIS); // TODO: URGENT: PUT THIS BACK IN ASAP! TEMP USING MONGO UNTIL EOSIO METHODS IMPLEMENTED...
else
{
if (!ProviderManager.IsProviderRegistered(Core.Enums.ProviderType.TelosOASIS))
throw new Exception("TelosOASIS Provider Not Registered. Please register and try again.");
else
throw new Exception("TelosOASIS Provider Is Registered But Was Not Injected Into SEEDSOASIS Provider.");
}
}
return _avatarManager;
}
}
public SEEDSOASIS(TelosOASIS.TelosOASIS telosOASIS)
// public SEEDSOASIS(string telosConnectionString)
{
this.ProviderName = "SEEDSOASIS";
this.ProviderDescription = "SEEDS Provider";
this.ProviderType = new EnumValue<ProviderType>(Core.Enums.ProviderType.SEEDSOASIS);
this.ProviderCategory = new EnumValue<ProviderCategory>(Core.Enums.ProviderCategory.Application);
TelosOASIS = telosOASIS;
// TelosOASIS = new TelosOASIS.TelosOASIS(telosConnectionString);
}
public async Task<string> GetBalanceAsync(string telosAccountName)
{
return await TelosOASIS.GetBalanceAsync(telosAccountName, "token.seeds", "SEEDS");
}
public string GetBalanceForTelosAccount(string telosAccountName)
{
return TelosOASIS.GetBalanceForTelosAccount(telosAccountName, "token.seeds", "SEEDS");
}
public string GetBalanceForAvatar(Guid avatarId)
{
return TelosOASIS.GetBalanceForAvatar(avatarId, "token.seeds", "SEEDS");
}
public async Task<TableRows> GetAllOrganisationsAsync()
{
TableRows rows = await TelosOASIS.EOSIOOASIS.ChainAPI.GetTableRowsAsync("orgs.seeds", "orgs.seeds", "organization", "true", 0, -1, 99999);
return rows;
}
public TableRows GetAllOrganisations()
{
TableRows rows = TelosOASIS.EOSIOOASIS.ChainAPI.GetTableRows("orgs.seeds", "orgs.seeds", "organization", "true", 0, -1, 99999);
return rows;
}
public string GetOrganisation(string orgName)
{
TableRows rows = TelosOASIS.EOSIOOASIS.ChainAPI.GetTableRows("orgs.seeds", "orgs.seeds", "organization", "true", 0, -1, 99999);
//TODO: Come back to this...
//for (int i = 0; i < rows.rows.Count; i++)
//{
// int orgNameBegins = rows.rows[i].ToString().IndexOf("org_name");
// string orgName = rows.rows[i].ToString().Substring(orgNameBegins + 10, 12);
//}
string json = JsonConvert.SerializeObject(rows);
//rows.rows.Where(x => x.)
return JsonConvert.SerializeObject(rows);
}
public async Task<string> GetAllOrganisationsAsJSONAsync()
{
TableRows rows = await TelosOASIS.EOSIOOASIS.ChainAPI.GetTableRowsAsync("orgs.seeds", "orgs.seeds", "organization", "true", 0, -1, 99999);
return JsonConvert.SerializeObject(rows);
}
public string GetAllOrganisationsAsJSON()
{
TableRows rows = TelosOASIS.EOSIOOASIS.ChainAPI.GetTableRows("orgs.seeds", "orgs.seeds", "organization", "true", 0, -1, 99999);
return JsonConvert.SerializeObject(rows);
}
public OASISResult<string> PayWithSeedsUsingTelosAccount(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return PayWithSeeds(fromTelosAccountName, fromTelosAccountPrivateKey, toTelosAccountName, quanitity, KarmaTypePositive.PayWithSeeds, KarmaTypePositive.BeAHero, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<string> PayWithSeedsUsingAvatar(Guid fromAvatarId, Guid toAvatarId, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return PayWithSeedsUsingTelosAccount(TelosOASIS.GetTelosAccountNameForAvatar(fromAvatarId), TelosOASIS.GetTelosAccountPrivateKeyForAvatar(toAvatarId), TelosOASIS.GetTelosAccountNameForAvatar(toAvatarId), quanitity, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<string> DonateWithSeedsUsingTelosAccount(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return PayWithSeeds(fromTelosAccountName, fromTelosAccountPrivateKey, toTelosAccountName, quanitity, KarmaTypePositive.DonateWithSeeds, KarmaTypePositive.BeASuperHero, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<string> DonateWithSeedsUsingAvatar(Guid fromAvatarId, Guid toAvatarId, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return DonateWithSeedsUsingTelosAccount(TelosOASIS.GetTelosAccountNameForAvatar(fromAvatarId), TelosOASIS.GetTelosAccountPrivateKeyForAvatar(toAvatarId), TelosOASIS.GetTelosAccountNameForAvatar(toAvatarId), quanitity, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<string> RewardWithSeedsUsingTelosAccount(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return PayWithSeeds(fromTelosAccountName, fromTelosAccountPrivateKey, toTelosAccountName, quanitity, KarmaTypePositive.RewardWithSeeds, KarmaTypePositive.BeASuperHero, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<string> RewardWithSeedsUsingAvatar(Guid fromAvatarId, Guid toAvatarId, int quanitity, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
return RewardWithSeedsUsingTelosAccount(TelosOASIS.GetTelosAccountNameForAvatar(fromAvatarId), TelosOASIS.GetTelosAccountPrivateKeyForAvatar(toAvatarId), TelosOASIS.GetTelosAccountNameForAvatar(toAvatarId), quanitity, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, memo);
}
public OASISResult<SendInviteResult> SendInviteToJoinSeedsUsingTelosAccount(string sponsorTelosAccountName, string sponsorTelosAccountNamePrivateKey, string referrerTelosAccountName, int transferQuantitiy, int sowQuantitiy, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null)
{
OASISResult<SendInviteResult> result = new OASISResult<SendInviteResult>();
try
{
result.Result = SendInviteToJoinSeeds(sponsorTelosAccountName, sponsorTelosAccountNamePrivateKey, referrerTelosAccountName, transferQuantitiy, sowQuantitiy);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured pushing the transaction onto the EOSIO chain. Error Message: ", ex.ToString());
}
// If there was no error then now add the karma.
if (!result.IsError && !string.IsNullOrEmpty(result.Result.TransactionId))
{
try
{
AddKarmaForSeeds(TelosOASIS.GetAvatarIdForTelosAccountName(sponsorTelosAccountName), KarmaTypePositive.SendInviteToJoinSeeds, KarmaTypePositive.BeAHero, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured adding karma points to account ", sponsorTelosAccountName, ". Was attempting to add points for SendInviteToJoinSeeds & BeAHero. KarmaSource Type: ", Enum.GetName(receivingKarmaFor), ". Karma Source: ", appWebsiteServiceName, ", Karma Source Desc: ", appWebsiteServiceDesc, ", Website Link: ", appWebsiteServiceLink, ". Error Message: ", ex.ToString());
}
}
else
{
if (!result.IsError)
{
result.IsError = true;
result.Message = "Unknown error occured pushing the transaction onto the EOSIO chain.";
}
}
return result;
}
public OASISResult<SendInviteResult> SendInviteToJoinSeedsUsingAvatar(Guid sponsorAvatarId, Guid referrerAvatarId, int transferQuantitiy, int sowQuantitiy, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null)
{
return SendInviteToJoinSeedsUsingTelosAccount(TelosOASIS.GetTelosAccountNameForAvatar(sponsorAvatarId), TelosOASIS.GetTelosAccountPrivateKeyForAvatar(sponsorAvatarId), TelosOASIS.GetTelosAccountNameForAvatar(referrerAvatarId), transferQuantitiy, sowQuantitiy, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink);
}
public OASISResult<string> AcceptInviteToJoinSeedsUsingTelosAccount(string telosAccountName, string inviteSecret, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null)
{
OASISResult<string> result = new OASISResult<string>();
try
{
result.Result = AcceptInviteToJoinSeeds(telosAccountName, inviteSecret);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured pushing the transaction onto the EOSIO chain. Error Message: ", ex.ToString());
}
// If there was no error then now add the karma.
if (!result.IsError && !string.IsNullOrEmpty(result.Result))
{
try
{
AddKarmaForSeeds(TelosOASIS.GetAvatarIdForTelosAccountName(telosAccountName), KarmaTypePositive.AcceptInviteToJoinSeeds, KarmaTypePositive.BeAHero, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured adding karma points to account ", telosAccountName, ". Was attempting to add points for AcceptInviteToJoinSeeds & BeAHero. KarmaSource Type: ", Enum.GetName(receivingKarmaFor), ". Karma Source: ", appWebsiteServiceName, ", Karma Source Desc: ", appWebsiteServiceDesc, ", Website Link: ", appWebsiteServiceLink, ". Error Message: ", ex.ToString());
}
}
else
{
if (!result.IsError)
{
result.IsError = true;
result.Message = "Unknown error occured pushing the transaction onto the EOSIO chain.";
}
}
return result;
}
public OASISResult<string> AcceptInviteToJoinSeedsUsingAvatar(Guid avatarId, string inviteSecret, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null)
{
return AcceptInviteToJoinSeedsUsingTelosAccount(TelosOASIS.GetTelosAccountNameForAvatar(avatarId), inviteSecret, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink);
}
public string GenerateSignInQRCode(string telosAccountName)
{
//https://github.com/JoinSEEDS/encode-transaction-service/blob/master/buildTransaction.js
return "";
}
public string GenerateSignInQRCodeForAvatar(Guid avatarId)
{
return GenerateSignInQRCode(TelosOASIS.GetTelosAccountNameForAvatar(avatarId));
}
private OASISResult<string> PayWithSeeds(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, int quanitity, KarmaTypePositive seedsKarmaType, KarmaTypePositive seedsKarmaHeroType, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null, string memo = null)
{
// TODO: Make generic and apply to all other calls...
OASISResult<string> result = new OASISResult<string>();
try
{
result.Result = PayWithSeeds(fromTelosAccountName, fromTelosAccountPrivateKey, toTelosAccountName, quanitity, memo);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured pushing the transaction onto the EOSIO chain. Error Message: ", ex.ToString());
}
// If there was no error then now add the karma.
if (!result.IsError && !string.IsNullOrEmpty(result.Result))
{
try
{
AddKarmaForSeeds(TelosOASIS.GetAvatarIdForTelosAccountName(fromTelosAccountName), seedsKarmaType, seedsKarmaHeroType, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink);
}
catch (Exception ex)
{
result.IsError = true;
result.Message = string.Concat("Error occured adding karma points to account ", fromTelosAccountName, ". Was attempting to add points for ", Enum.GetName(seedsKarmaType), " & ", Enum.GetName(seedsKarmaHeroType), ". KarmaSource Type: ", Enum.GetName(receivingKarmaFor), ". Karma Source: ", appWebsiteServiceName, ", Karma Source Desc: ", appWebsiteServiceDesc, ", Website Link: ", appWebsiteServiceLink, ". Error Message: ", ex.ToString());
}
}
else
{
if (!result.IsError)
{
result.IsError = true;
result.Message = "Unknown error occured pushing the transaction onto the EOSIO chain.";
}
}
return result;
}
private string PayWithSeeds(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, int quanitity, string memo)
{
return PayWithSeeds(fromTelosAccountName, fromTelosAccountPrivateKey, toTelosAccountName, ConvertTokenToSEEDSFormat(quanitity), memo);
}
private string PayWithSeeds(string fromTelosAccountName, string fromTelosAccountPrivateKey, string toTelosAccountName, string quanitity, string memo)
{
//Use standard TELOS/EOS Token API.Use Transfer action.
//https://developers.eos.io/manuals/eosjs/latest/basic-usage/browser
//string _code = "eosio.token", _action = "transfer", _memo = "";
//TransferArgs _args = new TransferArgs() { from = "yatendra1", to = "yatendra1", quantity = "1.0000 EOS", memo = _memo };
//var abiJsonToBin = chainAPI.GetAbiJsonToBin(_code, _action, _args);
//logger.Info("For code {0}, action {1}, args {2} and memo {3} recieved bin {4}", _code, _action, _args, _memo, abiJsonToBin.binargs);
//var abiBinToJson = chainAPI.GetAbiBinToJson(_code, _action, abiJsonToBin.binargs);
//logger.Info("Received args json {0}", JsonConvert.SerializeObject(abiBinToJson.args));
//TransferArgs args = new TransferArgs() { from = fromTelosAccountName, to = toTelosAccountName, quantity = "1.0000 EOS", memo = memo };
TransferArgs args = new TransferArgs() { from = fromTelosAccountName, to = toTelosAccountName, quantity = quanitity, memo = memo };
// var abiJsonToBin = EOSIOOASIS.ChainAPI.GetAbiJsonToBin("eosio.token", "transfer", args);
//prepare action object
//EOSNewYork.EOSCore.Params.Action action = new ActionUtility(ENDPOINT_TEST).GetActionObject("transfer", fromTelosAccountName, "active", "eosio.token", args);
//EOSNewYork.EOSCore.Params.Action action = new ActionUtility(ENDPOINT_TEST).GetActionObject("transfer", fromTelosAccountName, "active", "seed.seeds", args);
EOSNewYork.EOSCore.Params.Action action = new ActionUtility(ENDPOINT_TEST).GetActionObject("transfer", fromTelosAccountName, "active", "token.seeds", args);
var keypair = KeyManager.GenerateKeyPair();
//List<string> privateKeysInWIF = new List<string> { keypair.PrivateKey }; //TODO: Set Private Key
List<string> privateKeysInWIF = new List<string> { fromTelosAccountPrivateKey };
//push transaction
var transactionResult = TelosOASIS.EOSIOOASIS.ChainAPI.PushTransaction(new[] { action }, privateKeysInWIF);
// logger.Info(transactionResult.transaction_id);
//transactionResult.processed
return transactionResult.transaction_id;
// string accountName = "eosio";
//var abi = EOSIOOASIS.ChainAPI.GetAbi(accountName);
//abi.abi.actions[0].
//abi.abi.tables
//logger.Info("For account {0} recieved abi {1}", accountName, JsonConvert.SerializeObject(abi));
}
private SendInviteResult SendInviteToJoinSeeds(string sponsorTelosAccountName, string sponsorTelosAccountNamePrivateKey, string referrerTelosAccountName, int transferQuantitiy, int sowQuantitiy)
{
//https://joinseeds.github.io/seeds-smart-contracts/onboarding.html
//https://github.com/JoinSEEDS/seeds-smart-contracts/blob/master/scripts/onboarding-helper.js
string randomHex = GetRandomHexNumber(64); //16
string inviteHash = GetSHA256Hash(randomHex);
var keypair = KeyManager.GenerateKeyPair();
//List<string> privateKeysInWIF = new List<string> { keypair.PrivateKey }; //TODO: Set Private Key
List<string> privateKeysInWIF = new List<string> { sponsorTelosAccountNamePrivateKey };
EOSNewYork.EOSCore.Params.Action action = new ActionUtility(ENDPOINT_TEST).GetActionObject("invitefor", sponsorTelosAccountName, "active", "join.seeds", new Invite() { sponsor = sponsorTelosAccountName, referrer = referrerTelosAccountName, invite_hash = inviteHash, transfer_quantity = ConvertTokenToSEEDSFormat(transferQuantitiy), sow_quantity = ConvertTokenToSEEDSFormat(sowQuantitiy) });
var transactionResult = TelosOASIS.EOSIOOASIS.ChainAPI.PushTransaction(new[] { action }, privateKeysInWIF);
return new SendInviteResult() { TransactionId = transactionResult.transaction_id, InviteSecret = inviteHash };
}
private string AcceptInviteToJoinSeeds(string telosAccountName, string inviteSecret)
{
//https://joinseeds.github.io/seeds-smart-contracts/onboarding.html
//inviteSecret = inviteHash
var keypair = KeyManager.GenerateKeyPair();
List<string> privateKeysInWIF = new List<string> { keypair.PrivateKey };
EOSNewYork.EOSCore.Params.Action action = new ActionUtility(ENDPOINT_TEST).GetActionObject("accept", telosAccountName, "active", "join.seeds", new Accept() { account = telosAccountName, invite_secret = inviteSecret, publicKey = keypair.PublicKey });
var transactionResult = TelosOASIS.EOSIOOASIS.ChainAPI.PushTransaction(new[] { action }, privateKeysInWIF);
return transactionResult.transaction_id;
}
private bool AddKarmaForSeeds(Guid avatarId, KarmaTypePositive seedsKarmaType, KarmaTypePositive seedsKarmaHeroType, KarmaSourceType receivingKarmaFor, string appWebsiteServiceName, string appWebsiteServiceDesc, string appWebsiteServiceLink = null)
{
//TODO: Add new karma methods OASIS.API.CORE that allow bulk/batch karma to be added in one call (maybe use params?)
bool karmaHeroResult = !AvatarManagerInstance.AddKarmaToAvatar(avatarId, seedsKarmaHeroType, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, Core.Enums.ProviderType.SEEDSOASIS).IsError;
bool karmaSeedsResult = AvatarManagerInstance.AddKarmaToAvatar(avatarId, seedsKarmaType, receivingKarmaFor, appWebsiteServiceName, appWebsiteServiceDesc, appWebsiteServiceLink, Core.Enums.ProviderType.SEEDSOASIS).IsError;
return karmaHeroResult && karmaSeedsResult;
}
private string ConvertTokenToSEEDSFormat(int amount)
{
//return string.Concat(Math.Round(amount, 4).ToString().PadRight(4, '0'), " SEEDS");
return string.Concat(amount, ".0000 SEEDS");
}
private static string GetRandomHexNumber(int digits)
{
byte[] buffer = new byte[digits / 2];
_random.NextBytes(buffer);
string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
if (digits % 2 == 0)
return result;
return result + _random.Next(16).ToString("X");
}
private static string GetSHA256Hash(string value)
{
using (SHA256 sha256Hash = SHA256.Create())
{
string hash = GetHash(sha256Hash, value);
/*
Console.WriteLine($"The SHA256 hash of {value} is: {hash}.");
Console.WriteLine("Verifying the hash...");
if (VerifyHash(sha256Hash, value, hash))
Console.WriteLine("The hashes are the same.");
else
Console.WriteLine("The hashes are not same.");
*/
return hash;
}
}
private static string GetHash(HashAlgorithm hashAlgorithm, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
var sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
sBuilder.Append(data[i].ToString("x2"));
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
private static bool VerifyHash(HashAlgorithm hashAlgorithm, string input, string hash)
{
// Hash the input.
var hashOfInput = GetHash(hashAlgorithm, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return comparer.Compare(hashOfInput, hash) == 0;
}
}
}
| 57.019355 | 459 | 0.682658 | [
"CC0-1.0"
] | neurip/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK | NextGenSoftware.OASIS.API.Providers.SEEDSOASIS/SEEDSOASIS.cs | 26,516 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CRM.Areas.AppPage.Controllers
{
public class AtencionClienteController : Controller
{
// GET: AppPage/AtencionCliente
public ActionResult Index()
{
return View();
}
}
} | 20.176471 | 55 | 0.655977 | [
"MIT"
] | araucanosland/MDN | CRM/Areas/AppPage/Controllers/AtencionClienteController.cs | 345 | C# |
using System;
using System.Threading;
using SFA.DAS.Payments.ServiceFabric.Core.Infrastructure.Ioc;
namespace SFA.DAS.Payments.EarningEvents.EarningEventsService
{
internal static class Program
{
private static void Main()
{
try
{
using (ServiceFabricContainerFactory.CreateContainerForStatelessService<EarningEventsService>())
{
Thread.Sleep(Timeout.Infinite);
}
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
}
}
| 26.423077 | 112 | 0.56623 | [
"MIT"
] | PJChamley/das-payments-V2 | src/SFA.DAS.Payments.EarningEvents.EarningEventsService/Program.cs | 689 | C# |
using System.Reflection;
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("AWSSDK.CloudHSMV2")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS CloudHSM V2. CloudHSM provides hardware security modules for protecting sensitive data and cryptographic keys within an EC2 VPC, and enable the customer to maintain control over key access and use. This is a second-generation of the service that will improve security, lower cost and provide better customer usability.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.1.7")] | 52.34375 | 402 | 0.76 | [
"Apache-2.0"
] | phillip-haydon/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/CloudHSMV2/Properties/AssemblyInfo.cs | 1,675 | C# |
using static PacketType;
var input = File.ReadAllLines("input.txt");
var stopWatch = Stopwatch.StartNew();
var stringBuilder = new StringBuilder();
for (var i = 0; i < input[0].Length; i++)
{
stringBuilder.Append(Convert.ToString(Convert.ToInt32(input[0][i].ToString(), 16), 2).PadLeft(4, '0'));
}
var binary = stringBuilder.ToString();
var position = 0;
var part1 = 0;
var part2 = ParsePacket(binary, ref position, ref part1);
stopWatch.Stop();
Console.WriteLine($"{stopWatch.ElapsedMilliseconds}ms");
Console.WriteLine($"Part 1: {part1}");
Console.WriteLine($"Part 2: {part2}");
static long ParsePacket(in ReadOnlySpan<char> binary, ref int position, ref int part1)
{
if (binary.Length - position < 8)
{
// Skip remainder
position = binary.Length;
return 0;
}
var version = Convert.ToInt32(binary[position..(position += 3)].ToString(), 2);
part1 += version;
var type = (PacketType)Convert.ToInt32(binary[position..(position += 3)].ToString(), 2);
return type switch
{
Literal => ParseLiteral(binary, ref position),
_ => ParseOperator(binary, type, ref position, ref part1),
};
}
static long ParseLiteral(in ReadOnlySpan<char> binary, ref int position)
{
var value = new StringBuilder();
bool stopAfterLiteral;
do
{
stopAfterLiteral = binary[position++] == '0';
value.Append(binary[position..(position += 4)]);
} while (!stopAfterLiteral);
return Convert.ToInt64(value.ToString(), 2);
}
static long ParseOperator(in ReadOnlySpan<char> binary, in PacketType type, ref int position, ref int part1)
{
var bits = new StringBuilder();
var values = new List<long>();
switch (binary[position++])
{
case '0':
{
var length = Convert.ToInt32(binary[position..(position += 15)].ToString(), 2);
var start = position;
while (position < start + length)
{
values.Add(ParsePacket(binary, ref position, ref part1));
}
break;
}
case '1':
{
var length = Convert.ToInt32(binary[position..(position += 11)].ToString(), 2);
for (var i = 0; i < length; i++)
{
values.Add(ParsePacket(binary, ref position, ref part1));
}
break;
}
}
return type switch
{
Sum => values.Sum(),
Product => values.Aggregate(1L, (s, a) => s * a),
Minimum => values.Min(),
Maximum => values.Max(),
GreaterThan => values[0] > values[1] ? 1 : 0,
LessThan => values[0] < values[1] ? 1 : 0,
EqualTo => values[0] == values[1] ? 1 : 0,
_ => 0L,
};
}
enum PacketType
{
Sum,
Product,
Minimum,
Maximum,
Literal,
GreaterThan,
LessThan,
EqualTo
}
| 25.136752 | 108 | 0.566814 | [
"Apache-2.0"
] | eNeRGy164/AdventOfCode2021 | Day16/Day16.cs | 2,943 | C# |
using System;
using System.Runtime.InteropServices;
namespace Memoria.Prime.WinAPI
{
public static class Kernel32
{
[DllImport("kernel32.dll", EntryPoint = "RtlFillMemory", SetLastError = false)]
public static extern void FillMemory(IntPtr destination, UInt32 length, Byte fill);
}
} | 28.454545 | 91 | 0.71885 | [
"MIT"
] | Albeoris/Memoria | Memoria.Prime/WinAPI/Kernel32.cs | 315 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MNIST {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MNIST.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 45.125 | 161 | 0.608726 | [
"Apache-2.0"
] | JanHarmoshka/MNIST | Resources.Designer.cs | 3,399 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace Network_Core
{
public class TcpServer
{
public delegate void AcceptConnectionHandler(TcpConnection tcon);
protected List<TcpConnection> connectionList;
protected bool listening;
protected TcpListener listener;
protected Packager packager;
public event AcceptConnectionHandler AcceptConnectionEvent;
public List<TcpConnection> ConnectionList
{
get { return connectionList; }
}
public TcpServer(string ip, int port)
{
connectionList = new List<TcpConnection>();
listener = new TcpListener(IPAddress.Parse(ip), port);
listening = false;
packager = new Packager();
}
public bool StartListeningAsync()
{
if (listening == true)
return false;
listening = true;
ListeningAsync();
return true;
}
protected async void ListeningAsync()
{
listener.Start();
while(listening)
{
TcpConnection tc = new TcpConnection(await listener.AcceptTcpClientAsync(), packager);
connectionList.Add(tc);
AcceptConnectionEvent?.Invoke(tc);
}
listener.Stop();
}
public void StopListeningAsync()
{
listening = false;
}
public void RemoveConnection(TcpConnection tc)
{
connectionList.Remove(tc);
}
public async void Send(TcpConnection tc,object obj)
{
await tc.Send(obj);
}
public void Broadcast(object obj)
{
foreach(TcpConnection tc in connectionList)
{
Send(tc, obj);
}
}
}
}
| 26.906667 | 102 | 0.563925 | [
"MIT"
] | yuyyi51/ProjectNetwork | Network-Core/TcpServer.cs | 2,020 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Kurento.NET
{
public class ElementConnectionData
{
public MediaElement source;
public MediaElement sink;
public MediaType type;
public string sourceDescription;
public string sinkDescription;
}
}
| 17.782609 | 39 | 0.789731 | [
"BSD-2-Clause"
] | oBears/Kurento.NET | Kurento.NET/ComplexTypes/ElementConnectionData.cs | 409 | C# |
using Microsoft.Extensions.Configuration;
using System;
namespace XPNet
{
/// <summary>
/// Provides access to the X-Plane API from a plugin.
/// </summary>
public interface IXPlaneApi
{
/// <summary>
/// Raised when the configuration in the xpnetcfg.json file has changed.
/// </summary>
event EventHandler ConfigChanged;
/// <summary>
/// Gets the log.
/// </summary>
ILog Log { get; }
/// <summary>
/// Gets the configuration for the plugin (from the xpnetcfg.json file).
/// </summary>
IConfiguration Config { get; }
/// <summary>
/// Gets the X-Plane messages API. Use this API to get access
/// to events that map closely to the X-Plane API documentation.
/// Sometimes, there will also be a higher-level API provided by
/// XPNet, as an alternative to the Messages API.
/// </summary>
IXPlaneMessages Messages { get; }
/// <summary>
/// Gets the data access API (i.e., DataRefs).
/// </summary>
IXPlaneData Data { get; }
/// <summary>
/// Gets the commands API.
/// </summary>
IXPlaneCommands Commands { get; }
/// <summary>
/// Gets the processing API.
/// </summary>
IXPlaneProcessing Processing { get; }
/// <summary>
/// Gets the display API.
/// </summary>
IXPlaneDisplay Display { get; }
/// <summary>
/// Gets the scenery API.
/// </summary>
IXPlaneScenery Scenery { get; }
/// <summary>
/// Gets the graphics API.
/// </summary>
IXPlaneGraphics Graphics { get; }
/// <summary>
/// Gets the instance API.
/// </summary>
IXPlaneInstance Instance { get; }
}
internal class XPlaneApi : IXPlaneApi, IDisposable
{
public event EventHandler ConfigChanged;
public XPlaneApi(ILog log, IConfiguration config)
{
Log = log;
Config = config;
Messages = new XPlaneMessages();
Data = new XPlaneData();
Commands = new XPlaneCommands();
Processing = new XPlaneProcessing();
Display = new XPlaneDisplay();
Scenery = new XPlaneScenery();
Graphics = new XPlaneGraphics();
Instance = new XPlaneInstance();
}
public void Dispose()
{
// Currently nothing to do.
}
public ILog Log
{
get;
internal set;
}
public IConfiguration Config
{
get;
}
IXPlaneMessages IXPlaneApi.Messages
{
get { return Messages; }
}
public XPlaneMessages Messages
{
get;
}
IXPlaneData IXPlaneApi.Data
{
get { return Data; }
}
public XPlaneData Data
{
get;
}
IXPlaneCommands IXPlaneApi.Commands
{
get { return Commands; }
}
public XPlaneCommands Commands
{
get;
}
IXPlaneProcessing IXPlaneApi.Processing
{
get { return Processing; }
}
public XPlaneProcessing Processing
{
get;
}
IXPlaneDisplay IXPlaneApi.Display
{
get { return Display; }
}
public IXPlaneDisplay Display
{
get;
}
IXPlaneScenery IXPlaneApi.Scenery
{
get { return Scenery; }
}
public IXPlaneScenery Scenery
{
get;
}
IXPlaneGraphics IXPlaneApi.Graphics
{
get { return Graphics; }
}
public IXPlaneGraphics Graphics
{
get;
}
IXPlaneInstance IXPlaneApi.Instance
{
get { return Instance; }
}
public IXPlaneInstance Instance
{
get;
}
internal void RaiseConfigChanged()
{
ConfigChanged?.Invoke(this, EventArgs.Empty);
}
}
}
| 17.394737 | 74 | 0.64115 | [
"MIT"
] | mbrachner/XPNet | XPNet.CLR/Plugin/XPlaneApi.cs | 3,307 | C# |
using System;
using NUnit.Framework;
namespace TNValidate
{
/// ***********************************************************************
/// <summary>
/// Tests for Boolean validation.
/// </summary>
[TestFixture]
public class Bool_Tests
{
[Test]
public void Test_Bool_True_1()
{
Validator Validate = new Validator();
Validate.That(true, "Bool Value").IsTrue();
Assert.IsFalse(Validate.HasErrors());
}
[Test]
public void Test_Bool_True_2()
{
Validator Validate = new Validator();
Validate.That(false, "Bool Value").IsTrue();
Assert.IsTrue(Validate.HasErrors());
}
[Test]
public void Test_Bool_False_1()
{
Validator Validate = new Validator();
Validate.That(false, "Bool Value").IsFalse();
Assert.IsFalse(Validate.HasErrors());
}
[Test]
public void Test_Bool_False_2()
{
Validator Validate = new Validator();
Validate.That(true, "Bool Value").IsFalse();
Assert.IsTrue(Validate.HasErrors());
}
}
}
| 26.173913 | 79 | 0.501661 | [
"MIT"
] | tndataab/TNValidate | Tests/Bool_Tests.cs | 1,206 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
namespace Tasks
{
public class A
{
public static void Main(string[] args)
{
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
Console.SetOut(sw);
Solve();
Console.Out.Flush();
}
public static void Solve()
{
var (A, B, C) = Scanner.Scan<int, int, int>();
var answer = (double)C * B / A;
Console.WriteLine(answer);
}
public static class Scanner
{
private static Queue<string> queue = new Queue<string>();
public static T Next<T>()
{
if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item);
return (T)Convert.ChangeType(queue.Dequeue(), typeof(T));
}
public static T Scan<T>() => Next<T>();
public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>());
public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>());
public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>());
public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>());
public static (T1, T2, T3, T4, T5, T6) Scan<T1, T2, T3, T4, T5, T6>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>(), Next<T6>());
public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T)));
}
}
}
| 40.133333 | 158 | 0.519934 | [
"CC0-1.0"
] | AconCavy/AtCoder.Tasks.CS | Other/DDCC2016-QUAL/Tasks/A.cs | 1,806 | C# |
namespace Hagar.Configuration
{
/// <summary>
/// Holds configuration of the specified type.
/// </summary>
/// <typeparam name="TConfiguration">The configuration type.</typeparam>
public interface IConfiguration<TConfiguration> where TConfiguration : class, new()
{
/// <summary>
/// Gets the configuration value.
/// </summary>
TConfiguration Value { get; }
}
} | 30.285714 | 87 | 0.622642 | [
"MIT"
] | ReubenBond/Hagar | src/Hagar/Configuration/IConfiguration.cs | 424 | C# |
using System.Buffers;
namespace FastDFSCore.Protocols
{
/// <summary>
/// 查询全部Group
///
/// Reqeust
/// Cmd: TRACKER_PROTO_CMD_SERVER_LIST_ALL_GROUP 91
/// Body:
/// Response
/// Cmd: TRACKER_PROTO_CMD_RESP
/// Status: 0 right other wrong
/// Body:
/// @ FDFS_GROUP_NAME_MAX_LEN+1 bytes: group name
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: total disk storage in MB
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: free disk storage in MB
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: trunk free storage in MB
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: storage server count
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: storage server port
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: storage server http port
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: active server count
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: current write server index
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: store path count on storage server
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: subdir count per path on storage server
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: current_trunk_file_id
/// </summary>
public class ListAllGroup : FastDFSReq<ListAllGroupResp>
{
/// <summary>Ctor
/// </summary>
public ListAllGroup()
{
Header = new FastDFSHeader(0, Consts.TRACKER_PROTO_CMD_SERVER_LIST_ALL_GROUPS, 0);
}
/// <summary>EncodeBody
/// </summary>
public override byte[] EncodeBody(FastDFSOption option)
{
//Header = new FDFSHeader(0, Consts.TRACKER_PROTO_CMD_SERVER_LIST_ALL_GROUPS, 0);
var bodyBuffer = new byte[0];
return bodyBuffer;
}
}
}
| 37.148936 | 94 | 0.628866 | [
"MIT"
] | kerryjiang/FastDFSCore | src/FastDFSCore/Protocols/Request/ListAllGroup.cs | 1,756 | C# |
namespace Sidekick.Domain.Game.Items.Models
{
public enum Category
{
Undefined = 0,
Accessory = 1,
Armour = 2,
DivinationCard = 3,
Currency = 4,
Flask = 5,
Gem = 6,
Jewel = 7,
Map = 8,
Weapon = 9,
Leaguestone = 10,
Prophecy = 11,
ItemisedMonster = 12,
Watchstone = 13,
Contract = 14,
}
}
| 19.090909 | 43 | 0.466667 | [
"MIT"
] | 5c0r/Sidekick | src/Sidekick.Domain/Game/Items/Models/Category.cs | 420 | C# |
using System;
namespace Redola.ActorModel
{
public class ActorConnectedEventArgs : EventArgs
{
public ActorConnectedEventArgs(string actorChannelIdentifier, ActorIdentity remoteActor)
{
if (string.IsNullOrEmpty(actorChannelIdentifier))
throw new ArgumentNullException("actorChannelIdentifier");
if (remoteActor == null)
throw new ArgumentNullException("remoteActor");
this.ActorChannelIdentifier = actorChannelIdentifier;
this.RemoteActor = remoteActor;
}
public string ActorChannelIdentifier { get; private set; }
public ActorIdentity RemoteActor { get; private set; }
public override string ToString()
{
return string.Format("ActorChannelIdentifier[{0}], RemoteActor[{1}]", ActorChannelIdentifier, RemoteActor);
}
}
}
| 33.074074 | 119 | 0.659574 | [
"MIT"
] | gaochundong/Redola | Redola/Redola.ActorModel/Actor/EventArgs/ActorConnectedEventArgs.cs | 895 | C# |
using OpenTK.Graphics.OpenGL;
using Ryujinx.Common.Logging;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.OpenGL.Image;
using Ryujinx.Graphics.OpenGL.Queries;
using Ryujinx.Graphics.Shader;
using System;
namespace Ryujinx.Graphics.OpenGL
{
public sealed class Renderer : IRenderer
{
private readonly Pipeline _pipeline;
public IPipeline Pipeline => _pipeline;
private readonly Counters _counters;
private readonly Window _window;
public IWindow Window => _window;
internal TextureCopy TextureCopy { get; }
public string GpuVendor { get; private set; }
public string GpuRenderer { get; private set; }
public string GpuVersion { get; private set; }
public Renderer()
{
_pipeline = new Pipeline();
_counters = new Counters();
_window = new Window(this);
TextureCopy = new TextureCopy(this);
}
public IShader CompileShader(ShaderProgram shader)
{
return new Shader(shader);
}
public BufferHandle CreateBuffer(int size)
{
return Buffer.Create(size);
}
public IProgram CreateProgram(IShader[] shaders)
{
return new Program(shaders);
}
public ISampler CreateSampler(SamplerCreateInfo info)
{
return new Sampler(info);
}
public ITexture CreateTexture(TextureCreateInfo info)
{
return info.Target == Target.TextureBuffer ? new TextureBuffer(info) : new TextureStorage(this, info).CreateDefaultView();
}
public void DeleteBuffer(BufferHandle buffer)
{
Buffer.Delete(buffer);
}
public byte[] GetBufferData(BufferHandle buffer, int offset, int size)
{
return Buffer.GetData(buffer, offset, size);
}
public Capabilities GetCapabilities()
{
return new Capabilities(
HwCapabilities.SupportsAstcCompression,
HwCapabilities.SupportsImageLoadFormatted,
HwCapabilities.SupportsNonConstantTextureOffset,
HwCapabilities.SupportsViewportSwizzle,
HwCapabilities.MaximumComputeSharedMemorySize,
HwCapabilities.MaximumSupportedAnisotropy,
HwCapabilities.StorageBufferOffsetAlignment);
}
public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
{
Buffer.SetData(buffer, offset, data);
}
public void UpdateCounters()
{
_counters.Update();
}
public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler)
{
return _counters.QueueReport(type, resultHandler);
}
public void Initialize()
{
PrintGpuInformation();
_counters.Initialize();
}
private void PrintGpuInformation()
{
GpuVendor = GL.GetString(StringName.Vendor);
GpuRenderer = GL.GetString(StringName.Renderer);
GpuVersion = GL.GetString(StringName.Version);
Logger.PrintInfo(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})");
}
public void ResetCounter(CounterType type)
{
_counters.QueueReset(type);
}
public void Dispose()
{
TextureCopy.Dispose();
_pipeline.Dispose();
_window.Dispose();
_counters.Dispose();
}
}
}
| 28.155039 | 134 | 0.59967 | [
"MIT"
] | Octolimar/Ryujinx | Ryujinx.Graphics.OpenGL/Renderer.cs | 3,634 | 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 Newtonsoft.Json;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class DeleteHpcClusterResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.860465 | 63 | 0.720346 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Model/V20140526/DeleteHpcClusterResponse.cs | 1,155 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using EnsureThat;
using Microsoft.Extensions.Options;
using Microsoft.Health.Client.Exceptions;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.Health.Client
{
public class OAuth2ClientCertificateCredentialProvider : CredentialProvider
{
private const string JwtAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
private const string Rs256Algorithm = "RS256";
private readonly OAuth2ClientCertificateCredentialConfiguration _oAuth2ClientCertificateCredentialConfiguration;
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="OAuth2ClientCertificateCredentialProvider"/> class.
/// This class is used to obtain a token for the configured resource via the OAuth2 token endpoint via client certificate credentials.
/// </summary>
/// <param name="oAuth2ClientCertificateCredentialConfiguration">The configuration to use when obtaining a token.</param>
/// <param name="httpClient">The <see cref="HttpClient" /> to use when calling the token uri.</param>
public OAuth2ClientCertificateCredentialProvider(IOptions<OAuth2ClientCertificateCredentialConfiguration> oAuth2ClientCertificateCredentialConfiguration, HttpClient httpClient)
{
EnsureArg.IsNotNull(oAuth2ClientCertificateCredentialConfiguration?.Value, nameof(oAuth2ClientCertificateCredentialConfiguration));
EnsureArg.IsNotNull(httpClient, nameof(httpClient));
_httpClient = httpClient;
_oAuth2ClientCertificateCredentialConfiguration = oAuth2ClientCertificateCredentialConfiguration.Value;
}
protected override async Task<string> BearerTokenFunction(CancellationToken cancellationToken)
{
// Values specified for the assertion JWT specified here: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials
var additionalClaims = new List<Claim>
{
new (JwtRegisteredClaimNames.Sub, _oAuth2ClientCertificateCredentialConfiguration.ClientId),
new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var signingCredentials = new X509SigningCredentials(_oAuth2ClientCertificateCredentialConfiguration.Certificate, Rs256Algorithm);
var jwtSecurityToken = new JwtSecurityToken(
issuer: _oAuth2ClientCertificateCredentialConfiguration.ClientId,
audience: _oAuth2ClientCertificateCredentialConfiguration.TokenUri.AbsoluteUri,
claims: additionalClaims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddMinutes(10),
signingCredentials: signingCredentials);
var handler = new JwtSecurityTokenHandler();
var encodedCert = handler.WriteToken(jwtSecurityToken);
var formData = new List<KeyValuePair<string, string>>
{
new (OpenIdConnectParameterNames.ClientId, _oAuth2ClientCertificateCredentialConfiguration.ClientId),
new (OpenIdConnectParameterNames.ClientAssertionType, JwtAssertionType),
new (OpenIdConnectParameterNames.GrantType, OpenIdConnectGrantTypes.ClientCredentials),
new (OpenIdConnectParameterNames.Scope, _oAuth2ClientCertificateCredentialConfiguration.Scope),
new (OpenIdConnectParameterNames.Resource, _oAuth2ClientCertificateCredentialConfiguration.Resource),
new (OpenIdConnectParameterNames.ClientAssertion, encodedCert),
};
using var formContent = new FormUrlEncodedContent(formData);
using HttpResponseMessage tokenResponse = await _httpClient.PostAsync(_oAuth2ClientCertificateCredentialConfiguration.TokenUri, formContent, cancellationToken).ConfigureAwait(false);
var openIdConnectMessage = new OpenIdConnectMessage(await tokenResponse.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
if (tokenResponse.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
throw new FailToRetrieveTokenException(openIdConnectMessage.ErrorDescription);
}
return openIdConnectMessage.AccessToken;
}
}
}
| 56.488636 | 194 | 0.7069 | [
"MIT"
] | kolosovpetro/healthcare-shared-components | src/Microsoft.Health.Client/OAuth2ClientCertificateCredentialProvider.cs | 4,973 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Guest {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
}
| 22.45 | 59 | 0.688196 | [
"MIT"
] | sebastienadam/ephec_projet_sgbd | Sources/CSharp/Guest/Program.cs | 451 | C# |
using Dummiesman;
using System.IO;
using UnityEngine;
public class ObjFromFile : MonoBehaviour
{
string objPath = string.Empty;
string error = string.Empty;
GameObject loadedObject;
void OnGUI() {
//objPath = GUI.TextField(new Rect(0, 0, 256, 32), objPath);
//GUI.Label(new Rect(0, 0, 256, 32), "Obj Path:");
//if(GUI.Button(new Rect(256, 32, 64, 32), "Load File"))
//{
// //file path
// if (!File.Exists(objPath))
// {
// error = "File doesn't exist.";
// }else{
// if(loadedObject != null)
// Destroy(loadedObject);
// loadedObject = new OBJLoader().Load(objPath);
// error = string.Empty;
// }
//}
//if(!string.IsNullOrWhiteSpace(error))
//{
// GUI.color = Color.red;
// GUI.Box(new Rect(0, 64, 256 + 64, 32), error);
// GUI.color = Color.white;
//}
}
}
| 27.702703 | 68 | 0.48 | [
"MIT"
] | Procdox/moddingtalespire | Mods/PreviewAssetPlugin/PreviewAssetPlugin/OBJImport/Samples/ObjFromFile.cs | 1,027 | C# |
using MollieApi.Net.Resources;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MollieApi.Net.Endpoints
{
public class OnboardingEndpoint : EndpointAbstract<Onboarding, BaseCollection<Onboarding>>
{
public OnboardingEndpoint(MollieApiClient client) : base(client)
{
SetResourcePath("onboarding/me");
}
/// <summary>
/// Submit data that will be prefilled in the merchant’s onboarding.
/// Please note that the data you submit will only be processed when the onboarding status is needs-data.
///
/// Information that the merchant has entered in their dashboard will not be overwritten.
///
/// Will throw a ApiException if the resource cannot be found.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public async Task<Onboarding> Submit(Onboarding data, Dictionary<string, string> filters = null)
{
return await _client.PerformHttpCall<Onboarding>(MollieApiClient.HTTP_POST, GetResourcePath() + BuildQueryString(filters), ParseRequestBody(data));
}
/// <summary>
/// Retrieve the organization's onboarding status from Mollie.
///
/// Will throw a ApiException if the resource cannot be found.
/// </summary>
/// <returns></returns>
public async Task<Onboarding> Get(Dictionary<string, string> filters = null)
{
return await _client.PerformHttpCall<Onboarding>(MollieApiClient.HTTP_GET, GetResourcePath() + BuildQueryString(filters));
}
}
}
| 41.04878 | 160 | 0.633987 | [
"MIT"
] | janssenr/MollieApi.Net | src/MollieApi.Net/Endpoints/OnboardingEndpoint.cs | 1,687 | C# |
using Microsoft.VisualStudio.Shell;
using OpenInApp.Common.Helpers;
using OpenInAppAltovaXmlSpy.Commands;
using OpenInAppAltovaXmlSpy.Options.AltovaXmlSpy;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace OpenInAppAltovaXmlSpy
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration(productName: "#110", productDetails: "#112", productId: Vsix.Version, IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(PackageGuids.guidOpenInAppPackageString)]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
[ProvideOptionPage(typeof(GeneralOptions), Vsix.Name, CommonConstants.CategorySubLevel, 0, 0, true)]
public sealed class VSPackage : AsyncPackage
{
public static GeneralOptions Options { get; private set; }
protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await JoinableTaskFactory.SwitchToMainThreadAsync();
Options = (GeneralOptions)GetDialogPage(typeof(GeneralOptions));
new OpenInAppCommand(this).Initialize();
}
}
}
| 43.606061 | 178 | 0.770674 | [
"MIT"
] | GregTrevellick/OpenInApp.Launcher | src/OpenInAltovaXmlSpy/VSPackage.cs | 1,441 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.FSharp.Core.CompilerServices;
namespace TypeProviderInCSharp
{
public class TypeThatHasToStringThatThrows
{
public override string ToString()
{
throw new Exception("Intentional exception to cover an obscure code path");
}
}
public class ArtificialType : Type
{
string _Namespace;
string _Name;
Type _BaseType;
ArtificialConstructorInfo _Ctor1;
FieldInfo _Field_null;
FieldInfo _Field_single;
FieldInfo _Field_double;
FieldInfo _Field_bool;
FieldInfo _Field_char;
FieldInfo _Field_string;
FieldInfo _Field_sbyte;
FieldInfo _Field_byte;
FieldInfo _Field_int16;
FieldInfo _Field_uint16;
FieldInfo _Field_int;
FieldInfo _Field_uint32;
FieldInfo _Field_int64;
FieldInfo _Field_uint64;
FieldInfo _Field_decimal;
FieldInfo _Field_TypeThatHasToStringThatThrows;
FieldInfo _Field_enum;
FieldInfo _InstField_null;
FieldInfo _InstField_single;
FieldInfo _InstField_double;
FieldInfo _InstField_bool;
FieldInfo _InstField_char;
FieldInfo _InstField_string;
FieldInfo _InstField_sbyte;
FieldInfo _InstField_byte;
FieldInfo _InstField_int16;
FieldInfo _InstField_uint16;
FieldInfo _InstField_int;
FieldInfo _InstField_uint32;
FieldInfo _InstField_int64;
FieldInfo _InstField_uint64;
FieldInfo _InstField_decimal;
FieldInfo _InstField_enum;
FieldInfo _InstField_TypeThatHasToStringThatThrows;
public ArtificialType(string @namespace, string name, Type basetype)
{
_Name = name;
_Namespace = @namespace;
_BaseType = basetype;
_Field_null = new ArtificialFieldInfo("Field_null", this, typeof(object), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: null);
_Field_single = new ArtificialFieldInfo("Field_single", this, typeof(float), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: 2.1f);
_Field_double = new ArtificialFieldInfo("Field_double", this, typeof(double), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: 1.2d);
_Field_bool = new ArtificialFieldInfo("Field_bool", this, typeof(bool), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: true);
_Field_char = new ArtificialFieldInfo("Field_char", this, typeof(char), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: 'A');
_Field_string = new ArtificialFieldInfo("Field_string", this, typeof(string), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: "Hello");
_Field_sbyte = new ArtificialFieldInfo("Field_sbyte", this, typeof(sbyte), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: SByte.MaxValue);
_Field_byte = new ArtificialFieldInfo("Field_byte", this, typeof(byte), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: Byte.MaxValue);
_Field_int16 = new ArtificialFieldInfo("Field_int16", this, typeof(short), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: Int16.MaxValue);
_Field_uint16 = new ArtificialFieldInfo("Field_uint16", this, typeof(ushort), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: UInt16.MaxValue);
_Field_int = new ArtificialFieldInfo("Field_int", this, typeof(int), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: Int32.MaxValue);
_Field_uint32 = new ArtificialFieldInfo("Field_uint32", this, typeof(uint), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: UInt32.MaxValue);
_Field_int64 = new ArtificialFieldInfo("Field_int64", this, typeof(Int64), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: Int64.MaxValue);
_Field_uint64 = new ArtificialFieldInfo("Field_uint64", this, typeof(UInt64), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: UInt64.MaxValue );
_Field_decimal =new ArtificialFieldInfo("Field_decimal", this, typeof(decimal), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: 10M);
_Field_enum = new ArtificialFieldInfo("Field_enum", this, typeof(System.DayOfWeek), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: System.DayOfWeek.Friday);
_Field_TypeThatHasToStringThatThrows = new ArtificialFieldInfo("Field_TypeThatHasToStringThatThrows", this, typeof(TypeThatHasToStringThatThrows), IsLiteral: true, IsStatic: true, IsInitOnly: true, RawConstantValue: new TypeThatHasToStringThatThrows());
_InstField_null = new ArtificialFieldInfo("Instance_Field_null", this, typeof(object), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: null);
_InstField_single = new ArtificialFieldInfo("Instance_Field_single", this, typeof(float), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: 2.1f);
_InstField_double = new ArtificialFieldInfo("Instance_Field_double", this, typeof(double), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: 1.2d);
_InstField_bool = new ArtificialFieldInfo("Instance_Field_bool", this, typeof(bool), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: true);
_InstField_char = new ArtificialFieldInfo("Instance_Field_char", this, typeof(char), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: 'A');
_InstField_string = new ArtificialFieldInfo("Instance_Field_string", this, typeof(string), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: "Hello");
_InstField_sbyte = new ArtificialFieldInfo("Instance_Field_sbyte", this, typeof(sbyte), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: SByte.MaxValue);
_InstField_byte = new ArtificialFieldInfo("Instance_Field_byte", this, typeof(byte), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: Byte.MaxValue);
_InstField_int16 = new ArtificialFieldInfo("Instance_Field_int16", this, typeof(short), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: Int16.MaxValue);
_InstField_uint16 = new ArtificialFieldInfo("Instance_Field_uint16", this, typeof(ushort), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: UInt16.MaxValue);
_InstField_int = new ArtificialFieldInfo("Instance_Field_int", this, typeof(int), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: Int32.MaxValue);
_InstField_uint32 = new ArtificialFieldInfo("Instance_Field_uint32", this, typeof(uint), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: UInt32.MaxValue);
_InstField_int64 = new ArtificialFieldInfo("Instance_Field_int64", this, typeof(Int64), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: Int64.MaxValue);
_InstField_uint64 = new ArtificialFieldInfo("Instance_Field_uint64", this, typeof(UInt64), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: UInt64.MaxValue);
_InstField_decimal = new ArtificialFieldInfo("Instance_Field_decimal", this, typeof(decimal), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: 10M);
_InstField_enum = new ArtificialFieldInfo("Instance_Field_enum", this, typeof(System.DayOfWeek), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: System.DayOfWeek.Friday);
_InstField_TypeThatHasToStringThatThrows = new ArtificialFieldInfo("Instance_Field_TypeThatHasToStringThatThrows", this, typeof(TypeThatHasToStringThatThrows), IsLiteral: true, IsStatic: false, IsInitOnly: true, RawConstantValue: new TypeThatHasToStringThatThrows());
_Ctor1 = new ArtificialConstructorInfo(this, new ParameterInfo[] { });
}
public override System.Reflection.Assembly Assembly
{
get
{
Helpers.TraceCall();
return Assembly.GetExecutingAssembly();
}
}
public override string Name
{
get
{
Helpers.TraceCall();
return _Name;
}
}
public override Type BaseType
{
get
{
Helpers.TraceCall();
return _BaseType;
}
}
public override string Namespace
{
get
{
Helpers.TraceCall();
return _Namespace;
}
}
public override string FullName
{
get
{
Helpers.TraceCall();
return string.Format("{0}.{1}", _Namespace, _Name);
}
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
Helpers.TraceCall();
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
public override object[] GetCustomAttributes(bool inherit)
{
Helpers.TraceCall();
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
// TODO: what is this?
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
Helpers.TraceCall();
return TypeAttributes.Class | TypeAttributes.Public | (TypeAttributes)TypeProviderTypeAttributes.IsErased;
}
// This one seems to be invoked when in IDE, I type something like:
// let _ = typeof<N.
// In this case => no constructors
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new System.Reflection.ConstructorInfo[] { _Ctor1 };
}
// When you start typing more interesting things like...
// let a = N.T.M()
// this one gets invoked...
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new System.Reflection.MethodInfo[] { };
}
// This method is called when in the source file we have something like:
// - N.T.StaticProp
// (most likely also when we have an instance prop...)
// name -> "StaticProp"
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
Debug.Assert(binder == null && returnType == null && types == null && modifiers == null, "One of binder, returnType, types, or modifiers was not null");
return null;
}
// Advertise our property...
// I think that is this one returns an empty array => you don't get intellisense/autocomplete in IDE/FSI
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new PropertyInfo[] { };
}
// This on is invoked by the compiler by passing a (possible) field name
// (i.e. the one it is looking for)
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
switch (name)
{
case "Field_null": return _Field_null;
case "Field_single": return _Field_single;
case "Field_double": return _Field_double;
case "Field_bool": return _Field_bool;
case "Field_char": return _Field_char;
case "Field_string": return _Field_string;
case "Field_sbyte": return _Field_sbyte;
case "Field_byte": return _Field_byte;
case "Field_int16": return _Field_int16;
case "Field_uint16": return _Field_uint16;
case "Field_int": return _Field_int;
case "Field_uint32": return _Field_uint32;
case "Field_int64": return _Field_int64;
case "Field_uint64": return _Field_uint64;
case "Field_decimal": return _Field_decimal;
case "Field_enum": return _Field_enum;
case "Field_TypeThatHasToStringThatThrows": return _Field_TypeThatHasToStringThatThrows;
case "Instance_Field_null": return _InstField_null;
case "Instance_Field_single": return _InstField_single;
case "Instance_Field_double": return _InstField_double;
case "Instance_Field_bool": return _InstField_bool;
case "Instance_Field_char": return _InstField_char;
case "Instance_Field_string": return _InstField_string;
case "Instance_Field_sbyte": return _InstField_sbyte;
case "Instance_Field_byte": return _InstField_byte;
case "Instance_Field_int16": return _InstField_int16;
case "Instance_Field_uint16": return _InstField_uint16;
case "Instance_Field_int": return _InstField_int;
case "Instance_Field_uint32": return _InstField_uint32;
case "Instance_Field_int64": return _InstField_int64;
case "Instance_Field_uint64": return _InstField_uint64;
case "Instance_Field_decimal": return _InstField_decimal;
case "Instance_Field_enum": return _InstField_enum;
case "Instance_Field_TypeThatHasToStringThatThrows": return _InstField_TypeThatHasToStringThatThrows;
default:
return null;
}
}
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new System.Reflection.FieldInfo[]
{
_Field_null,
_Field_single,
_Field_double,
_Field_bool,
_Field_char,
_Field_string,
_Field_sbyte,
_Field_byte,
_Field_int16,
_Field_uint16,
_Field_int,
_Field_uint32,
_Field_int64,
_Field_uint64,
_Field_decimal,
_Field_enum,
_Field_TypeThatHasToStringThatThrows,
_InstField_null,
_InstField_single,
_InstField_double,
_InstField_bool,
_InstField_char,
_InstField_string,
_InstField_sbyte,
_InstField_byte,
_InstField_int16,
_InstField_uint16,
_InstField_int,
_InstField_uint32,
_InstField_int64,
_InstField_uint64,
_InstField_decimal,
_InstField_enum,
_InstField_TypeThatHasToStringThatThrows
};
}
// Events
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return null;
}
// Events...
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
return new System.Reflection.EventInfo[] { };
}
// TODO: according to the spec, this should not be invoked... instead it seems like it may be invoked...
// ?? I have no idea what this is used for... ??
public override Type UnderlyingSystemType
{
get
{
Helpers.TraceCall();
return null;
}
}
// According to the spec, this should always be 'false'
protected override bool IsArrayImpl()
{
Helpers.TraceCall();
return false;
}
// No interfaces...
public override Type[] GetInterfaces()
{
Helpers.TraceCall();
return new Type[] { };
}
// No nested type
// This method is invoked on the type 'T', e.g.:
// let _ = N.T.M
// to figure out if M is a nested type.
public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
return null;
}
public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new Type[] { };
}
// This one is invoked when the type has a .ctor
// and the code looks like
// let _ = new N.T()
// for example.
// It was observed that the
// TODO: cover both cases!
public override bool IsGenericType
{
get
{
Helpers.TraceCall();
return false;
}
}
// This is invoked if the IsGenericType is true
public override Type[] GetGenericArguments()
{
Helpers.TraceCall();
Debug.Assert(false, "Why are we here?");
throw new NotImplementedException();
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool IsGenericTypeDefinition
{
get
{
Helpers.TraceCall();
return false;
}
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool ContainsGenericParameters
{
get
{
Helpers.TraceCall();
return false;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsValueTypeImpl()
{
Helpers.TraceCall();
return false;
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsByRefImpl()
{
Helpers.TraceCall();
return false;
}
// This one seems to be checked when in IDE.
// let b = N.T(
public override bool IsEnum
{
get
{
Helpers.TraceCall();
return false;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsPointerImpl()
{
Helpers.TraceCall();
return false;
}
// I've seen this one being invoked when I had something like this:
// let t = new N.T()
// t.Event1.AddHandler( System.EventHandler( fun a b -> printfn "%A" System.DateTime.Now ) )
// // Raise the event:
// t.RaiseEvent1() <--
protected override TypeCode GetTypeCodeImpl()
{
Helpers.TraceCall();
return TypeCode.Object;
}
public override string AssemblyQualifiedName
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override Guid GUID
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type GetElementType()
{
Helpers.TraceCall();
Debug.Assert(false, "Why are we calling GetElementType()?");
throw new NotImplementedException();
}
public override Type GetInterface(string name, bool ignoreCase)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool HasElementTypeImpl()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsCOMObjectImpl()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsPrimitiveImpl()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.Module Module
{
get {
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override bool IsDefined(Type attributeType, bool inherit)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override MethodBase DeclaringMethod
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.DeclaringMethod;
}
}
// This one is invoked by the F# compiler!
public override Type DeclaringType
{
get
{
Helpers.TraceCall();
return null; // base.DeclaringType;
}
}
public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.FindInterfaces(filter, filterCriteria);
}
public override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.FindMembers(memberType, bindingAttr, filter, filterCriteria);
}
public override GenericParameterAttributes GenericParameterAttributes
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GenericParameterAttributes;
}
}
public override int GenericParameterPosition
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GenericParameterPosition;
}
}
public override int GetArrayRank()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetArrayRank();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
Helpers.TraceCall();
var attrs = new List<CustomAttributeData>();
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderXmlDocAttribute("This is a synthetic type created by me!")));
var f = System.IO.Path.GetTempFileName() + ".fs";
System.IO.File.WriteAllText(f, string.Format("// This is a fake definition file to test TypeProviderDefinitionLocationAttribute for type {0}.{1}\nnamespace {0}\ntype {1} = // blah", _Namespace, _Name));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderDefinitionLocationAttribute() { Column = 5, FilePath = f, Line = 3 }));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderEditorHideMethodsAttribute()));
return attrs;
}
public override MemberInfo[] GetDefaultMembers()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetDefaultMembers();
}
public override string GetEnumName(object value)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetEnumName(value);
}
public override string[] GetEnumNames()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetEnumNames();
}
public override Type GetEnumUnderlyingType()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetEnumUnderlyingType();
}
public override Array GetEnumValues()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetEnumValues();
}
public override EventInfo[] GetEvents()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetEvents();
}
public override Type[] GetGenericParameterConstraints()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetGenericParameterConstraints();
}
public override Type GetGenericTypeDefinition()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetGenericTypeDefinition();
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetInterfaceMap(interfaceType);
}
public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetMember(name, bindingAttr);
}
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.GetMember(name, type, bindingAttr);
}
public override bool IsAssignableFrom(Type c)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsAssignableFrom(c);
}
protected override bool IsContextfulImpl()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsContextfulImpl();
}
public override bool IsEnumDefined(object value)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsEnumDefined(value);
}
public override bool IsEquivalentTo(Type other)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsEquivalentTo(other);
}
// This one seems to be invoked when I do something like:
// type I = interface
// inherit N.I1
// end
//
// (I :> N.I1).M
// As per spec, this is supposed to return 'false'
public override bool IsGenericParameter
{
get
{
Helpers.TraceCall();
return false;
}
}
public override bool IsInstanceOfType(object o)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsInstanceOfType(o);
}
protected override bool IsMarshalByRefImpl()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsMarshalByRefImpl();
}
public override bool IsSecurityCritical
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsSecurityCritical;
}
}
public override bool IsSecuritySafeCritical
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsSecuritySafeCritical;
}
}
public override bool IsSecurityTransparent
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsSecurityTransparent;
}
}
public override bool IsSerializable
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsSerializable;
}
}
public override bool IsSubclassOf(Type c)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
return base.IsSubclassOf(c);
}
// This method is invoked when I try to create a method that
// returns an array of synthetic types...
// N.T
// N.T.M() -> N.T[]
public override Type MakeArrayType()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type MakeArrayType(int rank)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type MakeByRefType()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type MakeGenericType(params Type[] typeArguments)
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type MakePointerType()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override MemberTypes MemberType
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override int MetadataToken
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override Type ReflectedType
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override RuntimeTypeHandle TypeHandle
{
get
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override string ToString()
{
Helpers.TraceCall();
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
// By spec this NOT supposed to be called!
public override bool Equals(object o)
{
Helpers.TraceCall();
Debug.Assert(false, "BUG: You should not call Equals");
throw new NotImplementedException();
}
// By spec this NOT supposed to be called!
public override bool Equals(Type o)
{
Helpers.TraceCall();
Debug.Assert(false, "BUG: You should not call Equals");
throw new NotImplementedException();
}
// By spec this NOT supposed to be called!
public override int GetHashCode()
{
Helpers.TraceCall();
Debug.Assert(false, "BUG: You should not call GetHashCode");
throw new NotImplementedException();
}
}
}
| 40.068783 | 279 | 0.581513 | [
"Apache-2.0"
] | AliBaghernejad/visualfsharp | tests/fsharpqa/Source/TypeProviders/Fields/Literals/TestTP/ArtificialType.cs | 37,867 | C# |
using System.Reflection;
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("XamarinTemplate.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CompanyName")]
[assembly: AssemblyProduct("XamarinTemplate.Droid")]
[assembly: AssemblyCopyright("Copyright © CompanyName Year")]
[assembly: AssemblyTrademark("CompanyTrademark")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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.785714 | 84 | 0.748582 | [
"MIT"
] | BrunoMoureau/XamarinTemplate | XamarinTemplate/XamarinTemplate.Droid/Properties/AssemblyInfo.cs | 1,061 | C# |
/* Copyright 2015-2016 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace MongoDB.Bson.TestHelpers
{
[AttributeUsage(AttributeTargets.Method)]
public class Requires64BitProcessAttribute : CategoryAttribute, ITestAction
{
// constructors
public Requires64BitProcessAttribute()
: base("Requires64Bit")
{
}
// public properties
public ActionTargets Targets
{
get { return ActionTargets.Test; }
}
// public methods
public void AfterTest(ITest details)
{
}
public void BeforeTest(ITest details)
{
Ensure64Bit();
}
// private methods
private void Ensure64Bit()
{
if (IntPtr.Size < 8)
{
Assert.Ignore("This test requires a 64-bit process.");
}
}
}
}
| 26.210526 | 79 | 0.633199 | [
"Apache-2.0"
] | hgGeorg/mongo-csharp-driver | src/MongoDB.Bson.TestHelpers/Requires64BitProcessAttribute.cs | 1,496 | 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 Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
internal partial class Worker
{
private void ClassifyPreprocessorDirective(DirectiveTriviaSyntax node)
{
if (!_textSpan.OverlapsWith(node.Span))
{
return;
}
switch (node.Kind())
{
case SyntaxKind.IfDirectiveTrivia:
ClassifyIfDirective((IfDirectiveTriviaSyntax)node);
break;
case SyntaxKind.ElifDirectiveTrivia:
ClassifyElifDirective((ElifDirectiveTriviaSyntax)node);
break;
case SyntaxKind.ElseDirectiveTrivia:
ClassifyElseDirective((ElseDirectiveTriviaSyntax)node);
break;
case SyntaxKind.EndIfDirectiveTrivia:
ClassifyEndIfDirective((EndIfDirectiveTriviaSyntax)node);
break;
case SyntaxKind.RegionDirectiveTrivia:
ClassifyRegionDirective((RegionDirectiveTriviaSyntax)node);
break;
case SyntaxKind.EndRegionDirectiveTrivia:
ClassifyEndRegionDirective((EndRegionDirectiveTriviaSyntax)node);
break;
case SyntaxKind.ErrorDirectiveTrivia:
ClassifyErrorDirective((ErrorDirectiveTriviaSyntax)node);
break;
case SyntaxKind.WarningDirectiveTrivia:
ClassifyWarningDirective((WarningDirectiveTriviaSyntax)node);
break;
case SyntaxKind.BadDirectiveTrivia:
ClassifyBadDirective((BadDirectiveTriviaSyntax)node);
break;
case SyntaxKind.DefineDirectiveTrivia:
ClassifyDefineDirective((DefineDirectiveTriviaSyntax)node);
break;
case SyntaxKind.UndefDirectiveTrivia:
ClassifyUndefDirective((UndefDirectiveTriviaSyntax)node);
break;
case SyntaxKind.LineDirectiveTrivia:
ClassifyLineDirective((LineDirectiveTriviaSyntax)node);
break;
case SyntaxKind.PragmaChecksumDirectiveTrivia:
ClassifyPragmaChecksumDirective((PragmaChecksumDirectiveTriviaSyntax)node);
break;
case SyntaxKind.PragmaWarningDirectiveTrivia:
ClassifyPragmaWarningDirective((PragmaWarningDirectiveTriviaSyntax)node);
break;
case SyntaxKind.ReferenceDirectiveTrivia:
ClassifyReferenceDirective((ReferenceDirectiveTriviaSyntax)node);
break;
case SyntaxKind.LoadDirectiveTrivia:
ClassifyLoadDirective((LoadDirectiveTriviaSyntax)node);
break;
case SyntaxKind.NullableDirectiveTrivia:
ClassifyNullableDirective((NullableDirectiveTriviaSyntax)node);
break;
}
}
private void ClassifyDirectiveTrivia(DirectiveTriviaSyntax node, bool allowComments = true)
{
var lastToken = node.EndOfDirectiveToken.GetPreviousToken(includeSkipped: false);
foreach (var trivia in lastToken.TrailingTrivia)
{
// skip initial whitespace
if (trivia.Kind() == SyntaxKind.WhitespaceTrivia)
{
continue;
}
ClassifyPreprocessorTrivia(trivia, allowComments);
}
foreach (var trivia in node.EndOfDirectiveToken.LeadingTrivia)
{
ClassifyPreprocessorTrivia(trivia, allowComments);
}
}
private void ClassifyPreprocessorTrivia(SyntaxTrivia trivia, bool allowComments)
{
if (allowComments && trivia.Kind() == SyntaxKind.SingleLineCommentTrivia)
{
AddClassification(trivia, ClassificationTypeNames.Comment);
}
else
{
AddClassification(trivia, ClassificationTypeNames.PreprocessorText);
}
}
private void ClassifyPreprocessorExpression(ExpressionSyntax node)
{
if (node == null)
{
return;
}
if (node is LiteralExpressionSyntax literal)
{
// true or false
AddClassification(literal.Token, ClassificationTypeNames.Keyword);
}
else if (node is IdentifierNameSyntax identifier)
{
// DEBUG
AddClassification(identifier.Identifier, ClassificationTypeNames.Identifier);
}
else if (node is ParenthesizedExpressionSyntax parenExpression)
{
// (true)
AddClassification(parenExpression.OpenParenToken, ClassificationTypeNames.Punctuation);
ClassifyPreprocessorExpression(parenExpression.Expression);
AddClassification(parenExpression.CloseParenToken, ClassificationTypeNames.Punctuation);
}
else if (node is PrefixUnaryExpressionSyntax prefixExpression)
{
// !
AddClassification(prefixExpression.OperatorToken, ClassificationTypeNames.Operator);
ClassifyPreprocessorExpression(prefixExpression.Operand);
}
else if (node is BinaryExpressionSyntax binaryExpression)
{
// &&, ||, ==, !=
ClassifyPreprocessorExpression(binaryExpression.Left);
AddClassification(binaryExpression.OperatorToken, ClassificationTypeNames.Operator);
ClassifyPreprocessorExpression(binaryExpression.Right);
}
}
private void ClassifyIfDirective(IfDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.IfKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyPreprocessorExpression(node.Condition);
ClassifyDirectiveTrivia(node);
}
private void ClassifyElifDirective(ElifDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.ElifKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyPreprocessorExpression(node.Condition);
ClassifyDirectiveTrivia(node);
}
private void ClassifyElseDirective(ElseDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.ElseKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node);
}
private void ClassifyEndIfDirective(EndIfDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.EndIfKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node);
}
private void ClassifyErrorDirective(ErrorDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.ErrorKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node, allowComments: false);
}
private void ClassifyWarningDirective(WarningDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node, allowComments: false);
}
private void ClassifyRegionDirective(RegionDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.RegionKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node, allowComments: false);
}
private void ClassifyEndRegionDirective(EndRegionDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.EndRegionKeyword, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node);
}
private void ClassifyDefineDirective(DefineDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.DefineKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.Name, ClassificationTypeNames.Identifier);
ClassifyDirectiveTrivia(node);
}
private void ClassifyUndefDirective(UndefDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.UndefKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.Name, ClassificationTypeNames.Identifier);
ClassifyDirectiveTrivia(node);
}
private void ClassifyBadDirective(BadDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.Identifier, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node);
}
private void ClassifyLineDirective(LineDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword);
switch (node.Line.Kind())
{
case SyntaxKind.HiddenKeyword:
case SyntaxKind.DefaultKeyword:
AddClassification(node.Line, ClassificationTypeNames.PreprocessorKeyword);
break;
case SyntaxKind.NumericLiteralToken:
AddClassification(node.Line, ClassificationTypeNames.NumericLiteral);
break;
}
if (node.File.Kind() != SyntaxKind.None)
{
AddClassification(node.File, ClassificationTypeNames.StringLiteral);
}
ClassifyDirectiveTrivia(node);
}
private void ClassifyPragmaChecksumDirective(PragmaChecksumDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.ChecksumKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.File, ClassificationTypeNames.StringLiteral);
AddClassification(node.Guid, ClassificationTypeNames.StringLiteral);
AddClassification(node.Bytes, ClassificationTypeNames.StringLiteral);
ClassifyDirectiveTrivia(node);
}
private void ClassifyPragmaWarningDirective(PragmaWarningDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.DisableOrRestoreKeyword, ClassificationTypeNames.PreprocessorKeyword);
foreach (var nodeOrToken in node.ErrorCodes.GetWithSeparators())
{
ClassifyNodeOrToken(nodeOrToken);
}
if (node.ErrorCodes.Count == 0)
{
// When there are no error codes, we need to classify the directive's trivia.
// (When there are error codes, ClassifyNodeOrToken above takes care of that.)
ClassifyDirectiveTrivia(node);
}
}
private void ClassifyReferenceDirective(ReferenceDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.ReferenceKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.File, ClassificationTypeNames.StringLiteral);
ClassifyDirectiveTrivia(node);
}
private void ClassifyLoadDirective(LoadDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.LoadKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.File, ClassificationTypeNames.StringLiteral);
ClassifyDirectiveTrivia(node);
}
private void ClassifyNullableDirective(NullableDirectiveTriviaSyntax node)
{
AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.NullableKeyword, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.SettingToken, ClassificationTypeNames.PreprocessorKeyword);
AddClassification(node.TargetToken, ClassificationTypeNames.PreprocessorKeyword);
ClassifyDirectiveTrivia(node);
}
}
}
| 45.938312 | 161 | 0.654322 | [
"Apache-2.0"
] | GKotfis/roslyn | src/Workspaces/CSharp/Portable/Classification/Worker_Preprocesser.cs | 14,151 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Properties of the database error resource.</summary>
public partial class DatabaseMigrateEventProperties :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IDatabaseMigrateEventProperties,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IDatabaseMigrateEventPropertiesInternal,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventProperties"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventProperties __migrateEventProperties = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.MigrateEventProperties();
/// <summary>
/// Gets or sets the client request Id of the payload for which the event is being reported.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string ClientRequestId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ClientRequestId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ClientRequestId = value ?? null; }
/// <summary>Backing field for <see cref="Database" /> property.</summary>
private string _database;
/// <summary>Gets or sets the database for which the error is being reported.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string Database { get => this._database; set => this._database = value; }
/// <summary>Backing field for <see cref="DatabaseInstanceId" /> property.</summary>
private string _databaseInstanceId;
/// <summary>Gets or sets the database instance for which the error is being reported.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string DatabaseInstanceId { get => this._databaseInstanceId; set => this._databaseInstanceId = value; }
/// <summary>Gets or sets the error code.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string ErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ErrorCode = value ?? null; }
/// <summary>Gets or sets the error message.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string ErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).ErrorMessage = value ?? null; }
/// <summary>Gets the Instance type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).InstanceType; }
/// <summary>Internal Acessors for InstanceType</summary>
string Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal.InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).InstanceType = value; }
/// <summary>Gets or sets the possible causes for the error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string PossibleCaus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).PossibleCaus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).PossibleCaus = value ?? null; }
/// <summary>Gets or sets the recommendation for the error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string Recommendation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).Recommendation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).Recommendation = value ?? null; }
/// <summary>Gets or sets the solution for which the error is being reported.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string Solution { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).Solution; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal)__migrateEventProperties).Solution = value ?? null; }
/// <summary>Creates an new <see cref="DatabaseMigrateEventProperties" /> instance.</summary>
public DatabaseMigrateEventProperties()
{
}
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__migrateEventProperties), __migrateEventProperties);
await eventListener.AssertObjectIsValid(nameof(__migrateEventProperties), __migrateEventProperties);
}
}
/// Properties of the database error resource.
public partial interface IDatabaseMigrateEventProperties :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventProperties
{
/// <summary>Gets or sets the database for which the error is being reported.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Gets or sets the database for which the error is being reported.",
SerializedName = @"database",
PossibleTypes = new [] { typeof(string) })]
string Database { get; set; }
/// <summary>Gets or sets the database instance for which the error is being reported.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Gets or sets the database instance for which the error is being reported.",
SerializedName = @"databaseInstanceId",
PossibleTypes = new [] { typeof(string) })]
string DatabaseInstanceId { get; set; }
}
/// Properties of the database error resource.
internal partial interface IDatabaseMigrateEventPropertiesInternal :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IMigrateEventPropertiesInternal
{
/// <summary>Gets or sets the database for which the error is being reported.</summary>
string Database { get; set; }
/// <summary>Gets or sets the database instance for which the error is being reported.</summary>
string DatabaseInstanceId { get; set; }
}
} | 79.426087 | 441 | 0.747646 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20180901Preview/DatabaseMigrateEventProperties.cs | 9,020 | C# |
using Android.App;
using Android.Content.PM;
using Android.OS;
namespace SharpConstraintLayout.Maui.Example;
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
}
| 38.272727 | 254 | 0.821853 | [
"Apache-2.0"
] | xtuzy/SharpConstraintLayout | SharpConstraintLayout.Maui.Example/Platforms/Android/MainActivity.cs | 423 | 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
using System.IO;
namespace System.Drawing.Text
{
/// <summary>
/// Encapsulates a collection of <see cref='System.Drawing.Font'/> objecs.
/// </summary>
public sealed class PrivateFontCollection : FontCollection
{
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Text.PrivateFontCollection'/> class.
/// </summary>
public PrivateFontCollection() : base()
{
int status = SafeNativeMethods.Gdip.GdipNewPrivateFontCollection(out _nativeFontCollection);
SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
/// Cleans up Windows resources for this <see cref='System.Drawing.Text.PrivateFontCollection'/>.
/// </summary>
protected override void Dispose(bool disposing)
{
if (_nativeFontCollection != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDeletePrivateFontCollection(ref _nativeFontCollection);
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex))
{
}
finally
{
_nativeFontCollection = IntPtr.Zero;
}
}
base.Dispose(disposing);
}
/// <summary>
/// Adds a font from the specified file to this <see cref='System.Drawing.Text.PrivateFontCollection'/>.
/// </summary>
public void AddFontFile(string filename)
{
Path.GetFullPath(filename);
int status = SafeNativeMethods.Gdip.GdipPrivateAddFontFile(new HandleRef(this, _nativeFontCollection), filename);
SafeNativeMethods.Gdip.CheckStatus(status);
// Register private font with GDI as well so pure GDI-based controls (TextBox, Button for instance) can access it.
SafeNativeMethods.AddFontFile(filename);
}
/// <summary>
/// Adds a font contained in system memory to this <see cref='System.Drawing.Text.PrivateFontCollection'/>.
/// </summary>
public void AddMemoryFont(IntPtr memory, int length)
{
int status = SafeNativeMethods.Gdip.GdipPrivateAddMemoryFont(new HandleRef(this, _nativeFontCollection), new HandleRef(null, memory), length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
| 37.822785 | 154 | 0.618809 | [
"MIT"
] | harunpehlivan/corefx | src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs | 2,988 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
namespace Lib
{
public static class RabbitMQServiceCollectionExtensions
{
public static IServiceCollection AddRabbitMQ(
this IServiceCollection services,
Action<RabbitMQOptions> providerAction
)
{
services.AddOptions();
services.Configure(providerAction);
services.TryAddSingleton<IRabbitMQManager, RabbitMQManager>();
return services;
}
}
}
| 26.304348 | 86 | 0.65124 | [
"MIT"
] | zehrakarahan/rabbitmqdeserizaedilmisornek | Lib/RabbitMQServiceCollectionExtensions.cs | 607 | C# |
//-----------------------------------------------------------------
// AutoSpriteBase
// Copyright 2010 Brady Wright and Above and Beyond Software
// All rights reserved
//-----------------------------------------------------------------
// #define SPRITE_FRAME_DELEGATE // Adds code to call a delegate for each frame of animation (comment out this line to improve performance)
using UnityEngine;
using System.Collections;
/// <remarks>
/// Defines an animation composed of individual
/// textures. This is primarily used for atlas
/// compilation and is not used at run-time except
/// for initialization.
/// </remarks>
[System.Serializable]
public class TextureAnim
{
/// <summary>
/// Name of the animation.
/// </summary>
public string name;
/// <summary>
/// Loop cycles.
/// See loopCycles member of <see cref="UVAnimation"/>.
/// </summary>
public int loopCycles = 0;
/// <summary>
/// See loopReverse member of <see cref="UVAnimation"/>.
/// </summary>
public bool loopReverse = false;
/// <summary>
/// The framerate at which the animation should play in frames per second.
/// </summary>
public float framerate = 15f;// The rate in frames per second at which to play the animation
/// <summary>
/// What the sprite should do when the animation is done playing.
/// The options are to: 1) Do nothing, 2) return to the static image,
/// 3) play the default animation.
/// </summary>
public UVAnimation.ANIM_END_ACTION onAnimEnd = UVAnimation.ANIM_END_ACTION.Do_Nothing;
// Array of paths to textures each of which serve as a frame of animation.
[HideInInspector]
public string[] framePaths;
// Array of GUIDs for textures each of which serve as a frame of animation.
[HideInInspector]
public string[] frameGUIDs;
// Arrays that parallel the Texture2D frames but are populated
// with UV coordinates and other info upon atlas compilation which
// point to the UV locations of where the textures were placed on
// the atlas.
[HideInInspector]
public CSpriteFrame[] spriteFrames; // Array that parallels the Texture2D frameGUIDs array and holds the post-packing atlas UV coords for the given frame
// Allocates enough elements in each of the "frame info" fields
// to hold info for each animation frame specified in "frames":
public void Allocate()
{
bool allocate = false;
if (framePaths == null)
framePaths = new string[0];
if (frameGUIDs == null)
frameGUIDs = new string[0];
if (spriteFrames == null)
allocate = true;
else if (spriteFrames.Length != frameGUIDs.Length)
allocate = true;
if(allocate)
{
spriteFrames = new CSpriteFrame[ Mathf.Max(frameGUIDs.Length, framePaths.Length) ];
for (int i = 0; i < spriteFrames.Length; ++i)
spriteFrames[i] = new CSpriteFrame();
}
}
public TextureAnim()
{
Allocate();
}
public TextureAnim(string n)
{
name = n;
Allocate();
}
// Member-wise copy:
public void Copy(TextureAnim a)
{
name = a.name;
loopCycles = a.loopCycles;
loopReverse = a.loopReverse;
framerate = a.framerate;
onAnimEnd = a.onAnimEnd;
framePaths = new string[a.framePaths.Length];
a.framePaths.CopyTo(framePaths, 0);
frameGUIDs = new string[a.frameGUIDs.Length];
a.frameGUIDs.CopyTo(frameGUIDs, 0);
spriteFrames = new CSpriteFrame[a.spriteFrames.Length];
for(int i=0; i<spriteFrames.Length; ++i)
spriteFrames[i] = new CSpriteFrame(a.spriteFrames[i]);
}
}
/// <remarks>
/// Serves as a base for all "packable" sprite types.
/// That is, all sprites which are defined by one or
/// more source textures, which then get "packed" into
/// an atlas.
/// </remarks>
public abstract class AutoSpriteBase : SpriteBase, ISpriteAggregator, ISpritePackable
{
//---------------------------------------------
// Members related to building atlases:
// (Used for ISpriteAggregator implementation, such
// as Aggregate(), etc)
//---------------------------------------------
protected Texture2D[] sourceTextures;
protected CSpriteFrame[] spriteFrames;
/// <summary>
/// When set to true, even if the "Trim Images" option is
/// enabled in the atlas builder, the images for this object
/// will not be trimmed.
/// </summary>
public bool doNotTrimImages = false;
/// <summary>
/// Holds the actual UV sequences that will be used at run-time.
/// </summary>
[HideInInspector]
public UVAnimation[] animations;
protected UVAnimation curAnim = null; // The current animation
// Used to allow us to write code that accesses
// the sprite's states/animation lists while
// allowing children to declare the actual
// array that will hold them.
/// <summary>
/// Accessor for the sprite's various states as defined in the editor (not used at runtime).
/// </summary>
public abstract TextureAnim[] States
{
get;
set;
}
/// <summary>
/// Gets the default frame of the sprite object.
/// This is the appearance the sprite is to have
/// in the editor.
/// </summary>
public virtual CSpriteFrame DefaultFrame
{
get
{
if (States[0].spriteFrames.Length != 0)
return States[0].spriteFrames[0];
else
return null;
}
}
// Gets the default state (or animation)
// of the sprite object.
public virtual TextureAnim DefaultState
{
get
{
if (States != null)
if(States.Length != 0)
return States[0];
return null;
}
}
public override Vector2 GetDefaultPixelSize(PathFromGUIDDelegate guid2Path, AssetLoaderDelegate loader)
{
TextureAnim a = DefaultState;
CSpriteFrame f = DefaultFrame;
if(a == null)
return Vector2.zero;
if(a.frameGUIDs == null)
return Vector2.zero;
if (a.frameGUIDs.Length == 0)
return Vector2.zero;
if(f == null)
{
Debug.LogWarning("Sprite \"" + name + "\" does not seem to have been built to an atlas yet.");
return Vector2.zero;
}
Vector2 size = Vector2.zero;
Texture2D tex = (Texture2D) loader(guid2Path(a.frameGUIDs[0]), typeof(Texture2D));
if(tex == null)
{
if(spriteMesh != null)
{
tex = (Texture2D)spriteMesh.material.GetTexture("_MainTex");
size = new Vector2(f.uvs.width * tex.width, f.uvs.height * tex.height);
}
}
else
size = new Vector2(tex.width * (1f / (f.scaleFactor.x * 2f)), tex.height * (1f / (f.scaleFactor.y * 2f)));
return size;
}
protected override void Awake()
{
base.Awake();
animations = new UVAnimation[States.Length];
for (int i = 0; i < States.Length; ++i)
{
animations[i] = new UVAnimation();
animations[i].SetAnim(States[i], i);
}
}
// Resets all sprite values to defaults for reuse:
public override void Clear()
{
base.Clear();
if (curAnim != null)
{
PauseAnim();
curAnim = null;
}
}
/// <summary>
/// Sets up the essential elements of a sprite.
/// </summary>
/// <param name="w">The width, in local space, of the sprite.</param>
/// <param name="h">The height, in local space, of the sprite.</param>
public void Setup(float w, float h)
{
this.Setup(w, h, m_spriteMesh.material);
}
/// <summary>
/// Sets up the essential elements of a sprite.
/// </summary>
/// <param name="w">The width, in local space, of the sprite.</param>
/// <param name="h">The height, in local space, of the sprite.</param>
/// <param name="material">The material to use for the sprite.</param>
public void Setup(float w, float h, Material material)
{
width = w;
height = h;
if (!managed)
((SpriteMesh)m_spriteMesh).material = material;
Init();
}
/// <summary>
/// Copies all the attributes of another sprite.
/// </summary>
/// <param name="s">A reference to the sprite to be copied.</param>
public override void Copy(SpriteRoot s)
{
AutoSpriteBase sp;
base.Copy(s);
// Check the type:
if (!(s is AutoSpriteBase))
return;
sp = (AutoSpriteBase)s;
// See if it is an actual sprite instance:
if(sp.spriteMesh != null)
{
if (sp.animations.Length > 0)
{
animations = new UVAnimation[sp.animations.Length];
for (int i = 0; i < animations.Length; ++i)
animations[i] = sp.animations[i].Clone();
}
}
else if(States != null)
{
// Assume this is a prefab, so copy the UV info
//from its TextureAnimations instead:
animations = new UVAnimation[sp.States.Length];
for (int i = 0; i < sp.States.Length; ++i)
{
animations[i] = new UVAnimation();
animations[i].SetAnim(sp.States[i], i);
}
}
}
/// <summary>
/// Copies all the attributes of another sprite,
/// including its edit-time TextureAnimations.
/// </summary>
/// <param name="s">A reference to the sprite to be copied.</param>
public virtual void CopyAll(SpriteRoot s)
{
AutoSpriteBase sp;
base.Copy(s);
// Check the type:
if (!(s is AutoSpriteBase))
return;
sp = (AutoSpriteBase)s;
States = new TextureAnim[sp.States.Length];
for (int i = 0; i < States.Length; ++i)
{
States[i] = new TextureAnim();
States[i].Copy(sp.States[i]);
}
animations = new UVAnimation[States.Length];
for (int i = 0; i < States.Length; ++i)
{
animations[i] = new UVAnimation();
animations[i].SetAnim(States[i], i);
}
doNotTrimImages = sp.doNotTrimImages;
}
// Steps to the next frame of sprite animation
public override bool StepAnim(float time)
{
if (curAnim == null)
return false;
timeSinceLastFrame += Mathf.Max(0, time);
//timeSinceLastFrame += time;
framesToAdvance = (timeSinceLastFrame / timeBetweenAnimFrames);
// If there's nothing to do, return:
if (framesToAdvance < 1)
{
if (crossfadeFrames)
SetColor(new Color(1f, 1f, 1f, (1f - framesToAdvance)));
return true;
}
//timeSinceLastFrame -= timeBetweenAnimFrames * (float)framesToAdvance;
while (framesToAdvance >= 1f)
{
if (curAnim.GetNextFrame(ref frameInfo))
{
framesToAdvance -= 1f;
timeSinceLastFrame -= timeBetweenAnimFrames;
#if SPRITE_FRAME_DELEGATE
// Notify the delegate:
if(framesToAdvance >= 1f)
if (animFrameDelegate != null)
animFrameDelegate(this, curAnim.GetCurPosition());
#endif
}
else
{
// We reached the end of our animation
if (crossfadeFrames)
SetColor(Color.white);
// See if we should revert to a static appearance,
// default anim, or do nothing, etc:
switch(curAnim.onAnimEnd)
{
case UVAnimation.ANIM_END_ACTION.Do_Nothing:
PauseAnim();
// Update mesh UVs:
uvRect = frameInfo.uvs;
SetBleedCompensation();
// Resize if selected:
if (autoResize || pixelPerfect)
CalcSize();
break;
case UVAnimation.ANIM_END_ACTION.Revert_To_Static:
RevertToStatic();
break;
case UVAnimation.ANIM_END_ACTION.Play_Default_Anim:
// Notify the delegates:
#if SPRITE_FRAME_DELEGATE
if (animFrameDelegate != null)
animFrameDelegate(this, curAnim.GetCurPosition());
#endif
if (animCompleteDelegate != null)
animCompleteDelegate(this);
// Play the default animation:
PlayAnim(defaultAnim);
return false;
case UVAnimation.ANIM_END_ACTION.Hide:
Hide(true);
break;
case UVAnimation.ANIM_END_ACTION.Deactivate:
gameObject.active = false;
break;
case UVAnimation.ANIM_END_ACTION.Destroy:
// Notify the delegates:
#if SPRITE_FRAME_DELEGATE
if (animFrameDelegate != null)
animFrameDelegate(this, curAnim.GetCurPosition());
#endif
if (animCompleteDelegate != null)
animCompleteDelegate(this);
Delete();
Destroy(gameObject);
break;
}
// Notify the delegates:
#if SPRITE_FRAME_DELEGATE
if (animFrameDelegate != null)
animFrameDelegate(this, curAnim.GetCurPosition());
#endif
if (animCompleteDelegate != null)
animCompleteDelegate(this);
// Check to see if we are still animating
// before setting the curAnim to null.
// Animating should be turned off if
// PauseAnim() was called above, or if we
// reverted to static. But it could have
// been turned on again by the
// animCompleteDelegate.
if (!animating)
curAnim = null;
return false;
}
}
// Cross-fade to the next frame:
if (crossfadeFrames)
{
int curFrame = curAnim.GetCurPosition();
int stepDir = curAnim.StepDirection;
curAnim.GetNextFrame(ref nextFrameInfo);
Vector2[] uvs2 = m_spriteMesh.uvs2;
Rect nextUV = nextFrameInfo.uvs;
uvs2[0].x = nextUV.xMin; uvs2[0].y = nextUV.yMax;
uvs2[1].x = nextUV.xMin; uvs2[1].y = nextUV.yMin;
uvs2[2].x = nextUV.xMax; uvs2[2].y = nextUV.yMin;
uvs2[3].x = nextUV.xMax; uvs2[3].y = nextUV.yMax;
// Undo our advance:
curAnim.SetCurrentFrame(curFrame);
curAnim.StepDirection = stepDir;
SetColor(new Color(1f,1f,1f,(1f - framesToAdvance)));
}
#if SPRITE_FRAME_DELEGATE
if (animFrameDelegate != null)
animFrameDelegate(this, curAnim.GetCurPosition());
#endif
// Update mesh UVs:
uvRect = frameInfo.uvs;
SetBleedCompensation();
// Resize if selected:
if (autoResize || pixelPerfect)
CalcSize();
else if (anchor == SpriteRoot.ANCHOR_METHOD.TEXTURE_OFFSET)
SetSize(width, height);
//timeSinceLastFrame = 0;
return true;
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="anim">A reference to the animation to play.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnim(UVAnimation anim, int frame)
{
if (deleted || !gameObject.active)
return;
if (!m_started)
Start();
curAnim = anim;
curAnimIndex = curAnim.index;
curAnim.Reset();
curAnim.SetCurrentFrame(frame - 1); // curFrame inside UVAnimation will be incremented before it is used, so anticipate this by decrementing by 1
// Ensure the framerate is not 0 so we don't
// divide by zero:
if(anim.framerate != 0.0f)
{
timeBetweenAnimFrames = 1f / anim.framerate;
}
else
{
timeBetweenAnimFrames = 1f; // Just some dummy value since it won't be used
}
timeSinceLastFrame = timeBetweenAnimFrames;
// Only add to the animated list if
// the animation has more than 1 frame
// or the framerate is non-zero:
if ( (anim.GetFrameCount() > 1 || anim.onAnimEnd != UVAnimation.ANIM_END_ACTION.Do_Nothing) && anim.framerate != 0.0f)
{
StepAnim(0);
// Start coroutine
if (!animating)
{
//animating = true;
AddToAnimatedList();
//StartCoroutine(AnimationPump());
}
}
else
{
// Make sure we are no longer in the animation pump:
PauseAnim();
// Since this is a single-frame anim,
// call our delegate before setting
// the frame so that our behavior is
// consistent with multi-frame anims:
if (animCompleteDelegate != null)
animCompleteDelegate(this);
StepAnim(0);
}
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="anim">A reference to the animation to play.</param>
public void PlayAnim(UVAnimation anim)
{
PlayAnim(anim, 0);
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="index">Index of the animation to play.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnim(int index, int frame)
{
if (index >= animations.Length)
{
Debug.LogError("ERROR: Animation index " + index + " is out of bounds!");
return;
}
PlayAnim(animations[index], frame);
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="index">Index of the animation to play.</param>
public override void PlayAnim(int index)
{
if (index >= animations.Length)
{
Debug.LogError("ERROR: Animation index " + index + " is out of bounds!");
return;
}
PlayAnim(animations[index], 0);
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="name">The name of the animation to play.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnim(string name, int frame)
{
for (int i = 0; i < animations.Length; ++i)
{
if (animations[i].name == name)
{
PlayAnim(animations[i], frame);
return;
}
}
Debug.LogError("ERROR: Animation \"" + name + "\" not found!");
}
/// <summary>
/// Starts playing the specified animation
/// Note: this doesn't resume from a pause,
/// it completely restarts the animation. To
/// unpause, use <see cref="UnpauseAnim"/>.
/// </summary>
/// <param name="name">The name of the animation to play.</param>
public override void PlayAnim(string name)
{
PlayAnim(name, 0);
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="anim">Reference to the animation to play in reverse.</param>
public void PlayAnimInReverse(UVAnimation anim)
{
if (deleted || !gameObject.active)
return;
curAnim = anim;
curAnim.Reset();
curAnim.PlayInReverse();
// Ensure the framerate is not 0 so we don't
// divide by zero:
if (anim.framerate != 0.0f)
{
timeBetweenAnimFrames = 1f / anim.framerate;
}
else
{
timeBetweenAnimFrames = 1f; // Just some dummy value since it won't be used
}
timeSinceLastFrame = timeBetweenAnimFrames;
// Only add to the animated list if
// the animation has more than 1 frame:
if ((anim.GetFrameCount() > 1 || anim.onAnimEnd != UVAnimation.ANIM_END_ACTION.Do_Nothing) && anim.framerate != 0.0f)
{
StepAnim(0);
// Start coroutine
if (!animating)
{
//animating = true;
AddToAnimatedList();
//StartCoroutine(AnimationPump());
}
}
else
{
// Make sure we are no longer in the animation pump:
PauseAnim();
// Since this is a single-frame anim,
// call our delegate before setting
// the frame so that our behavior is
// consistent with multi-frame anims:
if (animCompleteDelegate != null)
animCompleteDelegate(this);
StepAnim(0);
}
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="anim">Reference to the animation to play in reverse.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnimInReverse(UVAnimation anim, int frame)
{
if (deleted || !gameObject.active)
return;
if (!m_started)
Start();
curAnim = anim;
curAnim.Reset();
curAnim.PlayInReverse();
curAnim.SetCurrentFrame(frame + 1); // curFrame inside UVAnimation will be decremented before it is used, so anticipate this by decrementing by 1
// Ensure the framerate is not 0 so we don't
// divide by zero:
anim.framerate = Mathf.Max(0.0001f, anim.framerate);
timeBetweenAnimFrames = 1f / anim.framerate;
timeSinceLastFrame = timeBetweenAnimFrames;
// Only add to the animated list if
// the animation has more than 1 frame:
if (anim.GetFrameCount() > 1)
{
StepAnim(0);
// Start coroutine
if (!animating)
{
//animating = true;
AddToAnimatedList();
//StartCoroutine(AnimationPump());
}
}
else
{
// Since this is a single-frame anim,
// call our delegate before setting
// the frame so that our behavior is
// consistent with multi-frame anims:
if (animCompleteDelegate != null)
animCompleteDelegate(this);
StepAnim(0);
}
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="index">Index of the animation to play in reverse.</param>
public override void PlayAnimInReverse(int index)
{
if (index >= animations.Length)
{
Debug.LogError("ERROR: Animation index " + index + " is out of bounds!");
return;
}
PlayAnimInReverse(animations[index]);
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="index">Index of the animation to play in reverse.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnimInReverse(int index, int frame)
{
if (index >= animations.Length)
{
Debug.LogError("ERROR: Animation index " + index + " is out of bounds!");
return;
}
PlayAnimInReverse(animations[index], frame);
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="name">Name of the animation to play in reverse.</param>
public override void PlayAnimInReverse(string name)
{
for (int i = 0; i < animations.Length; ++i)
{
if (animations[i].name == name)
{
animations[i].PlayInReverse();
PlayAnimInReverse(animations[i]);
return;
}
}
Debug.LogError("ERROR: Animation \"" + name + "\" not found!");
}
/// <summary>
/// Like PlayAnim, but plays the animation in reverse.
/// See <see cref="PlayAnim"/>.
/// </summary>
/// <param name="name">Name of the animation to play in reverse.</param>
/// <param name="frame">The zero-based index of the frame at which to start playing.</param>
public void PlayAnimInReverse(string name, int frame)
{
for (int i = 0; i < animations.Length; ++i)
{
if (animations[i].name == name)
{
animations[i].PlayInReverse();
PlayAnimInReverse(animations[i], frame);
return;
}
}
Debug.LogError("ERROR: Animation \"" + name + "\" not found!");
}
/// <summary>
/// Plays the specified animation only if it
/// is not already playing.
/// </summary>
/// <param name="index">Index of the animation to play.</param>
public void DoAnim(int index)
{
if (curAnim == null)
PlayAnim(index);
else if (curAnim.index != index || !animating)
PlayAnim(index);
}
/// <summary>
/// Plays the specified animation only if it
/// is not already playing.
/// </summary>
/// <param name="name">Name of the animation to play.</param>
public void DoAnim(string name)
{
if (curAnim == null)
PlayAnim(name);
else if (curAnim.name != name || !animating)
PlayAnim(name);
}
/// <summary>
/// Plays the specified animation only if it
/// is not already playing.
/// </summary>
/// <param name="anim">Reference to the animation to play.</param>
public void DoAnim(UVAnimation anim)
{
if (curAnim != anim || !animating)
PlayAnim(anim);
}
/// <summary>
/// Sets the current frame of the current animation immediately.
/// </summary>
/// <param name="index">Zero-based index of the desired frame.</param>
public void SetCurFrame(int index)
{
if (curAnim == null)
return;
if (!m_started)
Start();
curAnim.SetCurrentFrame(index - curAnim.StepDirection);
timeSinceLastFrame = timeBetweenAnimFrames;
StepAnim(0);
}
/// <summary>
/// Stops the current animation from playing
/// and resets it to the beginning for playing
/// again. The sprite then reverts to the static
/// image.
/// </summary>
public override void StopAnim()
{
// Stop coroutine
//animating = false;
RemoveFromAnimatedList();
//StopAllCoroutines();
// Reset the animation:
if (curAnim != null)
curAnim.Reset();
// Revert to our static appearance:
RevertToStatic();
}
/// <summary>
/// Resumes an animation from where it left off previously.
/// </summary>
public void UnpauseAnim()
{
if (curAnim == null) return;
// Resume coroutine
//animating = true;
AddToAnimatedList();
//StartCoroutine(AnimationPump());
}
// Adds the sprite to the list of currently
// animating sprites:
protected override void AddToAnimatedList()
{
// Check to see if the coroutine is running,
// and if not, start it:
// if (!SpriteAnimationPump.pumpIsRunning)
// SpriteAnimationPump.Instance.StartAnimationPump();
// If we're already animating, then we're
// already in the list, no need to add again.
// Also, if we're inactive, also don't add:
if (animating || !Application.isPlaying || !gameObject.active)
return;
animating = true;
SpriteAnimationPump.Add(this);
}
// Removes the sprite from the list of currently
// animating sprites:
protected override void RemoveFromAnimatedList()
{
SpriteAnimationPump.Remove(this);
animating = false;
}
//--------------------------------------------------------------
// Accessors:
//--------------------------------------------------------------
/// <summary>
/// Returns a reference to the currently selected animation.
/// NOTE: This does not mean the animation is currently playing.
/// To determine whether the animation is playing, use <see cref="IsAnimating"/>
/// </summary>
/// <returns>Reference to the currently selected animation.</returns>
public UVAnimation GetCurAnim() { return curAnim; }
/// <summary>
/// Returns a reference to the animation that matches the
/// name specified.
/// </summary>
/// <param name="name">Name of the animation sought.</param>
/// <returns>Reference to the animation, if found, null otherwise.</returns>
public UVAnimation GetAnim(string name)
{
for (int i = 0; i < animations.Length; ++i)
{
if (animations[i].name == name)
{
return animations[i];
}
}
return null;
}
public override int GetStateIndex(string stateName)
{
for (int i = 0; i < animations.Length; ++i)
{
if (string.Equals(animations[i].name, stateName, System.StringComparison.CurrentCultureIgnoreCase))
{
return i;
}
}
return -1;
}
public override void SetState(int index)
{
PlayAnim(index);
}
public virtual bool SupportsArbitraryAnimations
{
get { return false; }
}
public virtual Material GetPackedMaterial(out string errString)
{
errString = "Sprite \"" + name + "\" has not been assigned a material, and can therefore not be included in the atlas build.";
if (spriteMesh == null)
{
// See if it is because the sprite isn't associated
// with a manager:
if (managed)
{
// See if we can get the material
// from an associated manager:
if (manager != null)
{
return manager.renderer.sharedMaterial;
}
else // Else, no manager associated!:
{
errString = "Sprite \"" + name + "\" is not associated with a SpriteManager, and can therefore not be included in the atlas build.";
return null;
}
}
else // Else get the material from the sprite's renderer
{ // as this is probably a prefab and that's why it
// doesn't have a mesh:
return renderer.sharedMaterial;
}
}
else if (managed)
{
if (manager != null)
{
return manager.renderer.sharedMaterial;
}
else // Else, no manager associated!:
{
errString = "Sprite \"" + name + "\" is not associated with a SpriteManager, and can therefore not be included in the atlas build.";
return null;
}
}
else
return spriteMesh.material;
}
/// <summary>
/// When set to true, even if the "Trim Images" option is
/// enabled in the atlas builder, the images for this object
/// will not be trimmed.
/// </summary>
public virtual bool DoNotTrimImages
{
get { return doNotTrimImages; }
set { doNotTrimImages = value; }
}
// Collects all textures intended for packing,
// as well as sprite frames, together into a
// standard form for processing.
public virtual void Aggregate(PathFromGUIDDelegate guid2Path, LoadAssetDelegate load, GUIDFromPathDelegate path2Guid)
{
ArrayList texList = new ArrayList();
ArrayList frameList = new ArrayList();
for (int i = 0; i < States.Length; ++i)
{
States[i].Allocate();
// First try GUIDs:
if(States[i].frameGUIDs.Length >= States[i].framePaths.Length)
{
for (int j = 0; j < States[i].frameGUIDs.Length; ++j)
{
string path = guid2Path(States[i].frameGUIDs[j]);
texList.Add(load(path, typeof(Texture2D)));
frameList.Add(States[i].spriteFrames[j]);
}
// Make sure we always use GUIDs in the future:
States[i].framePaths = new string[0];
}
else
{
States[i].frameGUIDs = new string[States[i].framePaths.Length];
States[i].spriteFrames = new CSpriteFrame[States[i].framePaths.Length];
for (int j = 0; j < States[i].spriteFrames.Length; ++j)
States[i].spriteFrames[j] = new CSpriteFrame();
for (int j = 0; j < States[i].framePaths.Length; ++j)
{
// First get a GUID and save it:
States[i].frameGUIDs[j] = path2Guid(States[i].framePaths[j]);
texList.Add(load(States[i].framePaths[j], typeof(Texture2D)));
frameList.Add(States[i].spriteFrames[j]);
}
}
}
sourceTextures = (Texture2D[])texList.ToArray(typeof(Texture2D));
spriteFrames = (CSpriteFrame[])frameList.ToArray(typeof(CSpriteFrame));
}
// Provides access to the array of source textures.
// NOTE: Should be ordered to parallel the
// SpriteFrames array.
public Texture2D[] SourceTextures
{
get { return sourceTextures; }
}
// Provides access to the array of Sprite Frames.
// NOTE: Should be ordered to parallel the
// SourceTextures array.
public CSpriteFrame[] SpriteFrames
{
get { return spriteFrames; }
}
} | 25.895561 | 155 | 0.659105 | [
"CC0-1.0"
] | sumukhanand/echo | Unity/Assets/Plugins/Sprite Scripts/Support/AutoSpriteBase.cs | 29,754 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace KISSMp3MoverBefore.Contracts
{
public interface IFileRenameStrategyFactory
{
IFileRenameStrategy Get(string type);
}
}
| 19.083333 | 48 | 0.716157 | [
"MIT"
] | Gandjurov/DesignPatterns | 04.KISS/KISS/01. MP3 Mover - Before/Contracts/IFileRenameStrategyFactory.cs | 231 | C# |
using System;
using System.Diagnostics;
namespace Raging.Toolbox
{
/// <summary>
/// A disposable base class.
/// </summary>
/// <seealso cref="T:System.IDisposable"/>
public abstract class DisposableBase : IDisposable
{
private bool disposed;
/// <summary>
/// Finalizes an instance of the DisposableBase class.
/// </summary>
[DebuggerStepThrough]
~DisposableBase()
{
this.Dispose(true);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged
/// resources.
/// </summary>
[DebuggerStepThrough]
public void Dispose()
{
this.Dispose(false);
}
/// <summary>
/// Dispose resources.
/// </summary>
protected virtual void DisposeResources() { }
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged
/// resources.
/// </summary>
/// <param name="isFinalizing">true if this DisposableBase is finalizing.</param>
[DebuggerStepThrough]
private void Dispose(bool isFinalizing)
{
if (this.disposed) return;
this.DisposeResources();
if(!isFinalizing) GC.SuppressFinalize(this);
this.disposed = true;
}
}
} | 26.945455 | 109 | 0.552632 | [
"MIT"
] | RagingKore/Raging.Toolbox | Raging.Toolbox/DisposableBase.cs | 1,484 | C# |
using System;
using Xunit;
using BlogDB.Core;
namespace BlogCore.Tests
{
public class PostTests : IDisposable
{
[Fact]
public void TestAuthor()
{
var post = new BlogDB.Core.Post("", new Author("author", 0), "");
Assert.Equal("author", post.Author.Name);
Assert.Equal(0, post.Author.ID);
}
[Fact]
public void TestTitle()
{
var post = new BlogDB.Core.Post("title", new Author("", 0), "");
Assert.Equal("title", post.Title);
}
[Fact]
public void TestBody()
{
var post = new BlogDB.Core.Post("", new Author("", 0), "body");
Assert.Equal("body", post.Body);
}
[Fact]
public void TestDateTime()
{
var date = DateTime.UtcNow;
var post = new BlogDB.Core.Post("", new Author("", 0), "", date, Guid.NewGuid());
Assert.Equal(date, post.Timestamp);
}
[Fact]
public void TestPostID()
{
var guid = Guid.NewGuid();
var post = new BlogDB.Core.Post("", new Author("", 0), "", DateTime.UtcNow, guid);
Assert.Equal(guid, post.PostID);
}
public void Dispose() { }
}
}
| 23.545455 | 94 | 0.492664 | [
"MIT"
] | CalvinVest/BlogDB | BlogCore.Tests/PostTests.cs | 1,295 | C# |
using System;
using MachineLearning;
public class MNIST_NeuralNetwork : NeuralNetwork
{
public MNIST_NeuralNetwork() : base(numInputs: 784, numHiddenNodes: 90, numOutputs: 10, batches: 1)
{
m_ActivationFunction.ChangeFunction(ActivationFunctions.FunctionTypes.Sigmoid);
m_ActivationFunction.FunctionLearningRate = .5f;
}
public void Train(Func<int, bool, bool> progressFunc, bool continueLastTrainingSet = false)
{
if (TrainingSet == null)
{
return;
}
float epochCompletionPerPropagation = 1.0f / TrainingSetSize;
uint startSet = continueLastTrainingSet == true ? (uint)((TotalEpochs - (uint)TotalEpochs) * TrainingSetSize) : 0;
float deltaSetPercent = 1.0f / (NumEpochs * TrainingSetSize) * 100.0f;
float percent = startSet * deltaSetPercent;
float prevTrainingSensitivity = TrainingSensitivity;
bool earlyExit = false;
for (uint epoch = 0; epoch < NumEpochs; epoch++)
{
ConfusionMatrix.ResetMatrix();
for (uint set = startSet; set < TrainingSetSize; set++, percent += deltaSetPercent)
{
if(progressFunc((int)percent, false) == false)
{
earlyExit = true;
break;
}
Propagate(TrainingSet[set], testing: false);
EvaluateOutput();
TotalEpochs += epochCompletionPerPropagation;
}
startSet = 0;
if (CompletedBatches > 0)
{
BackPropagate();
}
TrainingSensitivity = Sensitivity();
Test();
while(TotalEpochs - CompletedEpochs > 1.0f)
{
CompletedEpochs++;
}
if(earlyExit == true)
{
return;
}
if (TrainingSensitivity - prevTrainingSensitivity < 0.5f)
{
ChangeLayerLearningRate(0, Layers[0].ActivationFunction.FunctionLearningRate / 2.0f);
}
if(progressFunc((int)percent, true) == false)
{
return;
}
}
}
public void Test(Action<int, bool> progressFunc)
{
if (TestSet == null)
{
return;
}
float deltaSetPercent = 1.0f / (TestSetSize) * 100.0f;
float percent = 0.0f;
float prevTestSensitivity = TestingSensitivity;
ConfusionMatrix.ResetMatrix();
for (uint set = 0; set < TestSetSize; set++, percent += deltaSetPercent)
{
progressFunc((int)percent, false);
Propagate(TestSet[set], testing: true);
EvaluateOutput();
}
TestingSensitivity = Sensitivity();
progressFunc((int)percent, false);
}
} | 31 | 122 | 0.545265 | [
"MIT"
] | Janushan-Austin/Mnist_ANN_GUI | Mnist_ANN_GUI/src/MNIST_NeuralNetwork.cs | 2,885 | C# |
using System;
using System.Collections.Generic;
namespace Notification.Domain.Interfaces
{
public interface INotificatorService
{
/// <summary>
/// Handle a notification message
/// </summary>
/// <param name="pMessage">Message of notification</param>
void HandleNotification(string pMessage);
/// <summary>
/// Handle a notification
/// </summary>
/// <param name="pNotification">Notification</param>
void HandleNotification(Domain.Entities.Notification pNotification);
/// <summary>
/// Handle a list of messages
/// </summary>
/// <param name="pMessages">Notification messages</param>
void HandleNotifications(List<string> pMessages);
/// <summary>
/// Handle a list of notifications
/// </summary>
/// <param name="pNotifications">Notifications</param>
void HandleNotifications(List<Domain.Entities.Notification> pNotifications);
/// <summary>
/// Get list of notifications
/// </summary>
/// <returns>List of notifications</returns>
List<Entities.Notification> GetList();
/// <summary>
/// Get list of notifications
/// </summary>
/// <param name="pFunc">Func to filter</param>
/// <returns>List of notifications</returns>
List<Entities.Notification> GetList(Func<Entities.Notification, bool> pFunc);
/// <summary>
/// There is notifications ?
/// </summary>
/// <param name="pFunc">Func to filter</param>
/// <returns>True or false</returns>
bool Any(Func<Entities.Notification, bool> pFunc);
/// <summary>
/// Clear notifications
/// </summary>
void ClearNotifications();
/// <summary>
/// There is notifications ?
/// </summary>
bool HasNotification { get; }
}
}
| 31.126984 | 85 | 0.578786 | [
"MIT"
] | PePires58/Notification_nuget | src/Notification.Domain/Interfaces/INotificatorService.cs | 1,963 | 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 transfer-2018-11-05.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.Transfer.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Transfer.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InvalidRequestException Object
/// </summary>
public class InvalidRequestExceptionUnmarshaller : IErrorResponseUnmarshaller<InvalidRequestException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public InvalidRequestException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public InvalidRequestException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
InvalidRequestException unmarshalledObject = new InvalidRequestException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static InvalidRequestExceptionUnmarshaller _instance = new InvalidRequestExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InvalidRequestExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.258824 | 137 | 0.672673 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Transfer/Generated/Model/Internal/MarshallTransformations/InvalidRequestExceptionUnmarshaller.cs | 2,997 | C# |
using Kayak.Framework;
using System;
using System.Threading;
namespace RvtBcfApiExampleClient
{
public class OAuthModule : KayakService
{
public static ServerLoginUI ServerLoginUIObj { get; set; }
private static SynchronizationContext
m_SyncContext;
static OAuthModule()
{
m_SyncContext = SynchronizationContext.Current;
}
[Verb("GET")]
[Path("/")]
public void Execute()
{
int
iPosStart = this.Request.RequestUri.IndexOf("?code=");
if (iPosStart >= 0)
{
int
iPosEnd = this.Request.RequestUri.IndexOf("&");
ServerLoginUIObj.sAuthCode = this.Request.RequestUri.Substring(iPosStart + 6, iPosEnd - iPosStart - 6);
}
else
throw new Exception("Login failed!");
m_SyncContext.Post((x) => ServerLoginUIObj.Close(), null);
Response.WriteLine("OK");
}
}
}
| 23.897436 | 112 | 0.608369 | [
"MIT"
] | nicmaes/RvtBcf | RvtBcfApiExampleClient/OAuthModule.cs | 934 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Tor.Helpers;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
namespace Tor.Events
{
/// <summary>
/// A class which provides monitoring for events occuring within the tor service.
/// </summary>
public sealed class Events : IDisposable
{
private readonly static Dictionary<Event, Type> dispatchers;
private readonly static string EOL = "\r\n";
private readonly Client client;
private readonly Dictionary<Event, int> events;
private readonly object synchronize;
private StringBuilder backlog;
private Action connectCallback;
private StringBuilder multiLine;
private byte[] buffer;
private volatile bool disposed;
private volatile bool enabled;
private Socket socket;
private event BandwidthEventHandler bandwidthChangedHandlers;
private event CircuitEventHandler circuitChangedHandlers;
private event ConfigurationChangedEventHandler configurationChangedHandlers;
private event LogEventHandler debugReceivedHandlers;
private event LogEventHandler errorReceivedHandlers;
private event LogEventHandler infoReceivedHandlers;
private event LogEventHandler noticeReceivedHandlers;
private event ORConnectionEventHandler orConnectionChangedHandlers;
private event StreamEventHandler streamChangedHandlers;
private event LogEventHandler warnReceivedHandlers;
/// <summary>
/// Initializes the <see cref="Events"/> class.
/// </summary>
static Events()
{
dispatchers = new Dictionary<Event, Type>();
Event[] values = Enum.GetValues(typeof(Event)) as Event[];
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "Tor.Events" && typeof(Dispatcher).IsAssignableFrom(t)))
{
EventAssocAttribute attribute = Attribute.GetCustomAttribute(type, typeof(EventAssocAttribute)) as EventAssocAttribute;
if (attribute == null)
continue;
foreach (Event value in values)
{
if ((attribute.Event & value) == value)
dispatchers[value] = type;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Events"/> class.
/// </summary>
/// <param name="client">The client for which this object instance belongs.</param>
internal Events(Client client)
{
this.backlog = new StringBuilder();
this.buffer = new byte[256];
this.connectCallback = null;
this.client = client;
this.disposed = false;
this.enabled = true;
this.events = new Dictionary<Event, int>();
this.multiLine = null;
this.socket = null;
this.synchronize = new object();
}
#region Events
/// <summary>
/// Occurs when the bandwidth download and upload values change within the tor service.
/// </summary>
public event BandwidthEventHandler BandwidthChanged
{
add { bandwidthChangedHandlers += value; AddEvent(Event.Bandwidth); }
remove { bandwidthChangedHandlers += value; RemoveEvent(Event.Bandwidth); }
}
/// <summary>
/// Occurs when a circuit has changed within the tor service.
/// </summary>
public event CircuitEventHandler CircuitChanged
{
add { circuitChangedHandlers += value; AddEvent(Event.Circuits); }
remove { circuitChangedHandlers -= value; RemoveEvent(Event.Circuits); }
}
/// <summary>
/// Occurs when configurations have changed within the tor service.
/// </summary>
public event ConfigurationChangedEventHandler ConfigurationChanged
{
add { configurationChangedHandlers += value; AddEvent(Event.ConfigChanged); }
remove { configurationChangedHandlers -= value; RemoveEvent(Event.ConfigChanged); }
}
/// <summary>
/// Occurs when a debug log message is received.
/// </summary>
public event LogEventHandler DebugReceived
{
add { debugReceivedHandlers += value; AddEvent(Event.LogDebug); }
remove { debugReceivedHandlers -= value; RemoveEvent(Event.LogDebug); }
}
/// <summary>
/// Occurs when an error log message is received.
/// </summary>
public event LogEventHandler ErrorReceived
{
add { errorReceivedHandlers += value; AddEvent(Event.LogError); }
remove { errorReceivedHandlers -= value; RemoveEvent(Event.LogError); }
}
/// <summary>
/// Occurs when an information log message is received.
/// </summary>
public event LogEventHandler InfoReceived
{
add { infoReceivedHandlers += value; AddEvent(Event.LogInfo); }
remove { infoReceivedHandlers -= value; RemoveEvent(Event.LogInfo); }
}
/// <summary>
/// Occurs when a notice log message is received.
/// </summary>
public event LogEventHandler NoticeReceived
{
add { noticeReceivedHandlers += value; AddEvent(Event.LogNotice); }
remove { noticeReceivedHandlers -= value; RemoveEvent(Event.LogNotice); }
}
/// <summary>
/// Occurs when an OR connection has changed within the tor service.
/// </summary>
public event ORConnectionEventHandler ORConnectionChanged
{
add { orConnectionChangedHandlers += value; AddEvent(Event.ORConnections); }
remove { orConnectionChangedHandlers -= value; RemoveEvent(Event.ORConnections); }
}
/// <summary>
/// Occurs when a stream has changed within the tor service.
/// </summary>
public event StreamEventHandler StreamChanged
{
add { streamChangedHandlers += value; AddEvent(Event.Streams); }
remove { streamChangedHandlers -= value; RemoveEvent(Event.Streams); }
}
/// <summary>
/// Occurs when a warning log message is received.
/// </summary>
public event LogEventHandler WarnReceived
{
add { warnReceivedHandlers += value; AddEvent(Event.LogWarn); }
remove { warnReceivedHandlers -= value; RemoveEvent(Event.LogWarn); }
}
#endregion
#region Events Invoke
/// <summary>
/// Raises the <see cref="E:BandwidthChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="BandwidthEventArgs"/> instance containing the event data.</param>
internal void OnBandwidthChanged(BandwidthEventArgs e)
{
if (bandwidthChangedHandlers != null)
bandwidthChangedHandlers(client, e);
}
/// <summary>
/// Raises the <see cref="E:CircuitChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="CircuitEventArgs"/> instance containing the event data.</param>
internal void OnCircuitChanged(CircuitEventArgs e)
{
if (circuitChangedHandlers != null)
circuitChangedHandlers(client, e);
}
/// <summary>
/// Raises the <see cref="E:ConfigurationChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="ConfigurationChangedEventArgs"/> instance containing the event data.</param>
internal void OnConfigurationChanged(ConfigurationChangedEventArgs e)
{
if (configurationChangedHandlers != null)
configurationChangedHandlers(client, e);
}
/// <summary>
/// Raises the <see cref="E:LogReceived" /> event.
/// </summary>
/// <param name="e">The <see cref="LogEventArgs"/> instance containing the event data.</param>
/// <param name="evt">The event which was processed.</param>
internal void OnLogReceived(LogEventArgs e, Event evt)
{
switch (evt)
{
case Event.LogDebug:
if (debugReceivedHandlers != null)
debugReceivedHandlers(client, e);
break;
case Event.LogError:
if (errorReceivedHandlers != null)
errorReceivedHandlers(client, e);
break;
case Event.LogInfo:
if (infoReceivedHandlers != null)
infoReceivedHandlers(client, e);
break;
case Event.LogNotice:
if (noticeReceivedHandlers != null)
noticeReceivedHandlers(client, e);
break;
case Event.LogWarn:
if (warnReceivedHandlers != null)
warnReceivedHandlers(client, e);
break;
}
}
/// <summary>
/// Raises the <see cref="E:ORConnectionChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="ORConnectionEventArgs"/> instance containing the event data.</param>
internal void OnORConnectionChanged(ORConnectionEventArgs e)
{
if (orConnectionChangedHandlers != null)
orConnectionChangedHandlers(client, e);
}
/// <summary>
/// Raises the <see cref="E:StreamChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="StreamEventArgs"/> instance containing the event data.</param>
internal void OnStreamChanged(StreamEventArgs e)
{
if (streamChangedHandlers != null)
streamChangedHandlers(client, e);
}
#endregion
#region System.IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Shutdown();
disposed = true;
}
}
#endregion
#region System.Net.Sockets.Socket
/// <summary>
/// Called when the socket connects to the control port.
/// </summary>
/// <param name="ar">The asynchronous result object for the asynchronous method.</param>
private void OnSocketConnect(IAsyncResult ar)
{
try
{
socket.EndConnect(ar);
string authenticate = string.Format("authenticate \"{0}\"{1}", client.GetControlPassword(), EOL);
byte[] authenticateBuffer = Encoding.ASCII.GetBytes(authenticate);
socket.BeginSend(authenticateBuffer, 0, authenticateBuffer.Length, SocketFlags.None, OnSocketSendAuthenticate, null);
}
catch { }
}
/// <summary>
/// Called when the socket receives a response to the authentication command.
/// </summary>
/// <param name="ar">The asynchronous result object for the asynchronous method.</param>
private void OnSocketReceiveAuthenticate(IAsyncResult ar)
{
try
{
int received = socket.EndReceive(ar);
if (received <= 0)
return;
string response = Encoding.ASCII.GetString(buffer, 0, received);
if (response.Length < 3 || !response.Substring(0, 3).Equals("250"))
throw new TorException("The events manager failed to authenticate with the control connection");
if (connectCallback != null)
connectCallback();
SetEvents();
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnSocketReceive, null);
}
catch { }
}
/// <summary>
/// Called when the socket receives data from the control port.
/// </summary>
/// <param name="ar">The asynchronous result object for the asynchronous method.</param>
private void OnSocketReceive(IAsyncResult ar)
{
try
{
int received = socket.EndReceive(ar);
if (received <= 0)
return;
string response = Encoding.ASCII.GetString(buffer, 0, received);
SetEventResponse(response);
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnSocketReceive, null);
}
catch { }
}
/// <summary>
/// Called when the socket has completed sending the authentication command.
/// </summary>
/// <param name="ar">The asynchronous result object for the asynchronous method.</param>
private void OnSocketSendAuthenticate(IAsyncResult ar)
{
try
{
socket.EndSend(ar);
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnSocketReceiveAuthenticate, null);
}
catch { }
}
/// <summary>
/// Called when the socket completes sending a list of interested events.
/// </summary>
/// <param name="ar">The asynchronous result object for the asynchronous method.</param>
private void OnSocketSendEvents(IAsyncResult ar)
{
try
{
socket.EndSend(ar);
}
catch { }
}
#endregion
/// <summary>
/// Adds an event to the list of monitored events.
/// </summary>
/// <param name="evt">The event which should be monitored for.</param>
private void AddEvent(Event evt)
{
if (disposed)
throw new ObjectDisposedException("this");
lock (synchronize)
{
int counter = 0;
events.TryGetValue(evt, out counter);
events[evt] = ++counter;
if (enabled && counter == 1)
SetEvents();
}
}
/// <summary>
/// Dispatches an event by parsing the content of the line and raising the relevant event.
/// </summary>
/// <param name="line">The line received from the control connection.</param>
private void Dispatch(string line)
{
if (line == null)
throw new ArgumentNullException("line");
string trimmed = line.Trim();
if (trimmed.Length < 3)
return;
string[] parts = null;
if (trimmed.Length > 3 && trimmed[3] == '-')
{
string[] intermediate = trimmed.Split(new[] { '-' }, 2); // [650, EVENT....]
if (intermediate.Length < 2)
return;
string status = intermediate[0].Trim();
string content = intermediate[1].Trim();
string[] data = content.Split(new string[] { EOL }, 2, StringSplitOptions.None); // [EVENT, ...]
if (data.Length < 2)
return;
parts = new string[] { status, data[0], data[1] };
}
else
parts = trimmed.Split(new[] { ' ' }, 3);
if (parts.Length < 2)
return;
if (parts[0].Equals("650"))
{
Event evt = ReflectionHelper.GetEnumerator<Event, DescriptionAttribute>(attr => parts[1].Equals(attr.Description, StringComparison.CurrentCultureIgnoreCase));
if (evt == Event.Unknown)
return;
Type type;
if (!dispatchers.TryGetValue(evt, out type))
return;
Dispatcher dispatcher = Activator.CreateInstance(type) as Dispatcher;
dispatcher.Client = client;
dispatcher.CurrentEvent = evt;
dispatcher.Events = this;
if (dispatcher == null)
return;
dispatcher.Dispatch(parts[2]);
}
}
/// <summary>
/// Removes an event from the list of monitored events.
/// </summary>
/// <param name="evt">The event which should be removed.</param>
private void RemoveEvent(Event evt)
{
if (disposed)
throw new ObjectDisposedException("this");
lock (synchronize)
{
int counter = 0;
if (!events.ContainsKey(evt))
return;
events.TryGetValue(evt, out counter);
counter--;
if (counter == 0)
{
events.Remove(evt);
SetEvents();
}
else
events[evt] = counter;
}
}
/// <summary>
/// Signals to the control connection to begin monitoring for interested events.
/// </summary>
private void SetEvents()
{
if (disposed)
throw new ObjectDisposedException("this");
lock (synchronize)
{
if (socket == null || !socket.Connected || !enabled)
return;
StringBuilder builder = new StringBuilder("SETEVENTS");
foreach (KeyValuePair<Event, int> interested in events)
{
string name = ReflectionHelper.GetDescription<Event>(interested.Key);
builder.Append(' ');
builder.Append(name);
}
string command = builder.Append("\r\n").ToString();
byte[] buffer = Encoding.ASCII.GetBytes(command);
socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnSocketSendEvents, null);
}
}
/// <summary>
/// Sets the current response data received from the control port, which is event information.
/// </summary>
/// <param name="response">The response received from the control port.</param>
private void SetEventResponse(string response)
{
if (response == null)
throw new ArgumentNullException("response");
if (response.Length == 0)
return;
if (backlog.Length > 0)
response = new StringBuilder(backlog.Length + response.Length).Append(backlog).Append(response).ToString();
int index = 0;
int length = response.Length;
List<string> dispatch = new List<string>();
if (response.Contains(EOL))
{
for (int next = response.IndexOf(EOL); 0 <= next; next = response.IndexOf(EOL, next))
{
string line = response.Substring(index, next - index);
next += EOL.Length;
index = next;
if (line.Length == 0)
{
if (index == length)
break;
continue;
}
if (line.StartsWith("250"))
continue;
if (3 < line.Length && line[3] == '-')
{
if (multiLine == null)
multiLine = new StringBuilder();
multiLine.AppendLine(line);
continue;
}
if (multiLine != null)
{
dispatch.Add(multiLine.ToString());
multiLine = null;
}
else
dispatch.Add(line);
if (index == length)
break;
}
}
if (backlog.Length > 0 && index == length)
backlog = new StringBuilder();
if (index < length)
backlog = new StringBuilder(response.Substring(index));
if (dispatch.Count > 0)
foreach (string line in dispatch)
Dispatch(line);
}
/// <summary>
/// Starts the process of monitoring for events by launching a control connection.
/// </summary>
/// <param name="callback">A method raised when the connection has completed.</param>
internal void Start(Action callback)
{
if (disposed)
throw new ObjectDisposedException("this");
lock (synchronize)
{
if (socket != null || !enabled)
return;
connectCallback = callback;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
socket.BeginConnect(client.GetClientAddress(), client.GetControlPort(), OnSocketConnect, null);
}
}
/// <summary>
/// Shuts down the listener socket and releases all resources associated with it.
/// </summary>
internal void Shutdown()
{
lock (synchronize)
{
if (socket != null)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch { }
socket.Dispose();
socket = null;
}
}
}
}
}
| 34.967841 | 174 | 0.527634 | [
"MIT"
] | kerryjiang/Tor.NET | src/Tor/Events/Events.cs | 22,836 | C# |
using System.Collections.Generic;
namespace TwitterAPI.Models
{
public class TUser
{
public int UserID { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Image { get; set; }
public TUser() {}
public TUser(int userID, string email, string userName, string image)
{
UserID = userID;
Email = email;
UserName = userName;
Image = image;
}
public int InsertUser(TUser user)
{
DBservices dbs = new DBservices();
int numAffected = dbs.insertUser(user);
return numAffected;
}
public List<TUser> GetUsers()
{
DBservices dbs = new DBservices();
return dbs.getUsers();
}
public List<TList> GetUserLists(TUser user)
{
DBservices dbs = new DBservices();
return dbs.getUserLists(user);
}
//@param email - user email
//if user exist return user id else return 0
public int IsExist(string email)
{
DBservices dbs = new DBservices();
return dbs.isExist(email);
}
public int EditUser(TUser user)
{
DBservices dbs = new DBservices();
int numAffected = dbs.editUser(user);
return numAffected;
}
}
} | 24.183333 | 77 | 0.522398 | [
"MIT"
] | igroup29/ProFeed---TwitterFinalProject | TwitterAPI/Models/TUser.cs | 1,453 | C# |
#if !NETSTANDARD13
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model.
*/
using Amazon.SecurityHub;
using Amazon.SecurityHub.Model;
using Moq;
using System;
using System.Linq;
using AWSSDK_DotNet35.UnitTests.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AWSSDK_DotNet35.UnitTests.PaginatorTests
{
[TestClass]
public class SecurityHubPaginatorTests
{
private static Mock<AmazonSecurityHubClient> _mockClient;
[ClassInitialize()]
public static void ClassInitialize(TestContext a)
{
_mockClient = new Mock<AmazonSecurityHubClient>("access key", "secret", Amazon.RegionEndpoint.USEast1);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void DescribeActionTargetsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<DescribeActionTargetsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<DescribeActionTargetsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<DescribeActionTargetsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.DescribeActionTargets(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.DescribeActionTargets(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void DescribeActionTargetsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<DescribeActionTargetsRequest>();
var response = InstantiateClassGenerator.Execute<DescribeActionTargetsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.DescribeActionTargets(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.DescribeActionTargets(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void DescribeProductsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<DescribeProductsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<DescribeProductsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<DescribeProductsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.DescribeProducts(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.DescribeProducts(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void DescribeProductsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<DescribeProductsRequest>();
var response = InstantiateClassGenerator.Execute<DescribeProductsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.DescribeProducts(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.DescribeProducts(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void DescribeStandardsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<DescribeStandardsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<DescribeStandardsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<DescribeStandardsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.DescribeStandards(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.DescribeStandards(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void DescribeStandardsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<DescribeStandardsRequest>();
var response = InstantiateClassGenerator.Execute<DescribeStandardsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.DescribeStandards(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.DescribeStandards(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void DescribeStandardsControlsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<DescribeStandardsControlsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<DescribeStandardsControlsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<DescribeStandardsControlsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.DescribeStandardsControls(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.DescribeStandardsControls(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void DescribeStandardsControlsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<DescribeStandardsControlsRequest>();
var response = InstantiateClassGenerator.Execute<DescribeStandardsControlsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.DescribeStandardsControls(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.DescribeStandardsControls(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void GetEnabledStandardsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<GetEnabledStandardsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<GetEnabledStandardsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<GetEnabledStandardsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.GetEnabledStandards(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.GetEnabledStandards(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void GetEnabledStandardsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<GetEnabledStandardsRequest>();
var response = InstantiateClassGenerator.Execute<GetEnabledStandardsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.GetEnabledStandards(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.GetEnabledStandards(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void GetFindingsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<GetFindingsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<GetFindingsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<GetFindingsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.GetFindings(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.GetFindings(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void GetFindingsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<GetFindingsRequest>();
var response = InstantiateClassGenerator.Execute<GetFindingsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.GetFindings(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.GetFindings(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void GetInsightsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<GetInsightsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<GetInsightsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<GetInsightsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.GetInsights(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.GetInsights(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void GetInsightsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<GetInsightsRequest>();
var response = InstantiateClassGenerator.Execute<GetInsightsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.GetInsights(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.GetInsights(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void ListEnabledProductsForImportTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListEnabledProductsForImportRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListEnabledProductsForImportResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListEnabledProductsForImportResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListEnabledProductsForImport(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListEnabledProductsForImport(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListEnabledProductsForImportTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListEnabledProductsForImportRequest>();
var response = InstantiateClassGenerator.Execute<ListEnabledProductsForImportResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListEnabledProductsForImport(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListEnabledProductsForImport(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void ListInvitationsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListInvitationsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListInvitationsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListInvitationsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListInvitations(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListInvitations(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListInvitationsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListInvitationsRequest>();
var response = InstantiateClassGenerator.Execute<ListInvitationsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListInvitations(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListInvitations(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
public void ListMembersTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListMembersRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListMembersResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListMembersResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListMembers(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListMembers(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SecurityHub")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListMembersTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListMembersRequest>();
var response = InstantiateClassGenerator.Execute<ListMembersResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListMembers(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListMembers(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
}
}
#endif | 42.165899 | 160 | 0.674426 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/test/Services/SecurityHub/UnitTests/Generated/_bcl45+netstandard/Paginators/SecurityHubPaginatorTests.cs | 18,300 | C# |
using System.Collections.Generic;
using System.Linq;
using Akinator.Api.Net.Enumerations;
using Akinator.Api.Net.Model;
namespace Akinator.Api.Net.Utils
{
public static class ServerSelector
{
// todo Add more languages...
private static readonly IReadOnlyDictionary<Language, Server[]> m_languageServerMapping =
new Dictionary<Language, Server[]>()
{
{
Language.German, new[]
{
new Server(ServerType.Person, "srv14.akinator.com:9283/ws"),
new Server(ServerType.Animal, "srv14.akinator.com:9284/ws")
}
},
{
Language.English, new[]
{
new Server(ServerType.Person, "srv13.akinator.com:9196/ws"),
new Server(ServerType.Object, "srv14.akinator.com:9293/ws"),
new Server(ServerType.Animal, "srv13.akinator.com:9287/ws")
}
},
{
Language.Arabic, new[]
{
new Server(ServerType.Person, "srv2.akinator.com:9155/ws")
}
},
{
Language.Italian, new[]
{
new Server(ServerType.Person, "srv9.akinator.com:9214/ws"),
new Server(ServerType.Animal, "srv9.akinator.com:9261/ws")
}
},
{
Language.Spanish, new[]
{
new Server(ServerType.Person, "srv13.akinator.com:9194/ws"),
new Server(ServerType.Animal, "srv13.akinator.com:9257/ws")
}
},
{
Language.French, new[]
{
new Server(ServerType.Person, "srv3.akinator.com:9217/ws"),
new Server(ServerType.Object, "srv3.akinator.com:9218/ws"),
new Server(ServerType.Animal, "srv3.akinator.com:9259/ws")
}
},
{
Language.Russian, new[]
{
new Server(ServerType.Person, "srv12.akinator.com:9190/ws")
}
}
};
public static string GetServerFor(Language language, ServerType type) =>
m_languageServerMapping[language].FirstOrDefault(p => p.Type == type)?.Url;
}
}
| 38.304348 | 97 | 0.444571 | [
"MIT"
] | ahmed605/Akinator.Api.Net | Akinator.Api.Net/Utils/ServerSelector.cs | 2,645 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using CafeinaXml.XReflection.DataStructures;
namespace CafeinaXml.XReflection
{
internal class EntityReflection
{
// Precached reflections
static Dictionary<Type, ReflectedEntity> Precached = new Dictionary<Type, ReflectedEntity>();
/// <summary>
/// Reflection
/// </summary>
/// <param name="type">Data type to reflect</param>
/// <returns>Full Reflected entity</returns>
public static ReflectedEntity Reflect(Type type)
{
// Search in cache
if (Precached.ContainsKey(type))
{
return Precached[type];
}
// Get properties
PropertyInfo[] properties = type.GetProperties();
var reflectedProperties = new List<ReflectedProperty>();
foreach(var property in properties)
{
// Set default info
var reflectedProperty = new ReflectedProperty(
property, StructureClassifier.GetStructure(property.PropertyType));
// Search for key atributtes
Attribute[] attrs = Attribute.GetCustomAttributes(property);
foreach (var attr in attrs)
{
var meta = attr as MetaXmlAttribute;
if (meta != null)
{
reflectedProperty.PropertyType = meta.PropertyType;
}
}
reflectedProperties.Add(reflectedProperty);
}
// Add to cache and return
ReflectedEntity reflectedEntity = new ReflectedEntity(reflectedProperties, ValidateKey(reflectedProperties));
Precached.Add(type, reflectedEntity);
return reflectedEntity;
}
/// <summary>
/// Validates a reflections
/// </summary>
/// <param name="reflectedEntity"></param>
public static PropertyType ValidateKey(List<ReflectedProperty> reflectedProperties)
{
int identityProps = reflectedProperties.Where(p => p.PropertyType == PropertyType.Identity).Count();
int uniqueProps = reflectedProperties.Where(p => p.PropertyType == PropertyType.Unique).Count();
// Errors
if (identityProps > 1)
{
throw new CafeinaXmlException("A entity can't have more than one identity.");
}
if (identityProps > 0 && uniqueProps > 0)
{
throw new CafeinaXmlException("Only can exist one key attribute for identity-entities.");
}
if (identityProps == 1)
{
var id = reflectedProperties.Where(p => p.PropertyType == PropertyType.Identity).FirstOrDefault();
if (id.Structure.StructureType != StructureType.Single)
{
throw new CafeinaXmlException("Only single types allowed to use identity property type.");
}
}
if (uniqueProps > 0)
{
foreach (var p in reflectedProperties.Where(p => p.PropertyType == PropertyType.Unique).ToList())
{
if (p.Structure.StructureType != StructureType.Single)
{
throw new CafeinaXmlException("Only single types allowed to use unique property type.");
}
}
}
// Results
if(identityProps == 1)
{
return PropertyType.Identity;
}
if (uniqueProps > 0)
{
return PropertyType.Unique;
}
return PropertyType.None;
}
private EntityReflection()
{ }
}
}
| 35.356522 | 121 | 0.52361 | [
"MIT"
] | dacanizares/CafeinaXml | CafeinaXml/XReflection/EntityReflection.cs | 4,068 | C# |
using Microsoft.Graph;
using Microsoft.Graph.ExternalConnectors;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
namespace PartsInventoryConnector.Graph
{
// The Graph SDK serializes enumerations in camelCase.
// The Graph service currently requires the PropertyType enum
// to be PascalCase. This will override the Graph serialization
// If the Graphs service changes to accept camelCase this will no
// longer be necessary
class CustomContractResolver : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (typeof(PropertyType).IsAssignableFrom(objectType))
{
// This default converter uses PascalCase
return new StringEnumConverter();
}
return base.ResolveContractConverter(objectType);
}
}
// In order to hook up the custom contract resolver for
// PropertyType, we need to implement a custom serializer to
// pass to the GraphServiceClient.
public class CustomSerializer : ISerializer
{
private Serializer _graphSerializer;
private JsonSerializerSettings _jsonSerializerSettings;
public CustomSerializer()
{
_graphSerializer = new Serializer();
_jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CustomContractResolver()
};
}
// For deserialize, just pass through to the default
// Graph SDK serializer
public T DeserializeObject<T>(Stream stream)
{
return _graphSerializer.DeserializeObject<T>(stream);
}
// For deserialize, just pass through to the default
// Graph SDK serializer
public T DeserializeObject<T>(string inputString)
{
return _graphSerializer.DeserializeObject<T>(inputString);
}
public string SerializeObject(object serializeableObject)
{
// If a Schema object is being serialized, do the conversion
// ourselves
if (serializeableObject is Schema)
{
var foo = JsonConvert.SerializeObject(serializeableObject, _jsonSerializerSettings);
return foo;
}
// Otherwise, just pass through to the default Graph SDK serializer
return _graphSerializer.SerializeObject(serializeableObject);
}
}
} | 33.960526 | 100 | 0.653623 | [
"MIT"
] | microsoftgraph/msgraph-search-connector-sample | PartsInventoryConnector/Graph/CustomSerializer.cs | 2,581 | C# |
using System;
using System.Xml;
namespace OpenSBR.Xades
{
internal static class XadesXmlExtension
{
internal static XmlElement CreateChild(this XmlElement element, string name, string namespaceURI)
{
XmlElement child = element.OwnerDocument.CreateElement(name, namespaceURI);
element.AppendChild(child);
return child;
}
internal static string GetInnerText(this XmlElement element, string xpath, XmlNamespaceManager nsm)
{
XmlElement child = element?.SelectSingleNode(xpath, nsm) as XmlElement;
return child?.InnerText;
}
}
}
| 25.363636 | 101 | 0.767025 | [
"MIT"
] | OpenSBR/SBRAssurance | OpenSBR/Xades/XadesExtension.cs | 560 | C# |
using System;
namespace Magic
{
class DerivedClass : BaseClass
{
public override bool Method(int argument1) => !base.Method(argument1);
}
class BaseClass
{
public virtual bool Method(int argument1) => true;
}
}
| 14.866667 | 72 | 0.713004 | [
"Apache-2.0"
] | WiseTechGlobal/WTG.Analyzers | src/WTG.Analyzers.Test/TestData/PointlessOverrideAnalyzer/ModifyingResult/Source.cs | 223 | C# |
#region License
/*
Copyright © 2014-2018 European Support Limited
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.
*/
#endregion
using System;
using System.Threading;
namespace GingerCoreNET.SolutionRepositoryLib.RepositoryObjectsLib.VariablesLib
{
public class DecimalRandom
{
Random rnd = new Random(Guid.NewGuid().GetHashCode());
public decimal NextDecimal(bool ZeroToOne = false)
{
// Improve fare distribution as rnd is not really random
Thread.Sleep(1);
//The low 32 bits of a 96-bit integer.
int lo = rnd.Next(int.MinValue, int.MaxValue);
Thread.Sleep(1);
//The middle 32 bits of a 96-bit integer.
int mid = rnd.Next(int.MinValue, int.MaxValue);
Thread.Sleep(1);
//The high 32 bits of a 96-bit integer.
int hi = rnd.Next(int.MinValue, int.MaxValue);
//The sign of the number; 1 is negative, 0 is positive.
bool isNegative;
//A power of 10 ranging from 0 to 28.
byte scale;
// Can have fraction up to 28 digits after the .
if (ZeroToOne)
{
isNegative = false;
scale = Convert.ToByte(28);
}
else
{
isNegative = (rnd.Next(2) == 0);
scale = Convert.ToByte(rnd.Next(29));
}
Decimal randomDecimal = new Decimal(lo, mid, hi, isNegative, scale);
if (ZeroToOne)
{
while (randomDecimal > 1) { randomDecimal--; };
}
return randomDecimal;
}
public decimal NextDecimal(decimal Min, decimal Max, bool integer)
{
//Get random decimal
decimal d1 = NextDecimal(true);
//Make sure it is a decimal between 0-1
decimal d0_1 = Math.Abs(d1);
while (d0_1 > 1)
{
d0_1 = d0_1 /10M;
}
decimal d = d0_1 * (decimal)Math.Abs(Max-Min) + Min;
if (integer)
{
d = Math.Round(d,0);
}
return d;
}
}
} | 32.55814 | 80 | 0.542857 | [
"Apache-2.0"
] | DebasmitaGhosh/Ginger | Ginger/GingerCoreNET/SolutionRepositoryLib/RepositoryObjectsLib/VariablesLib/DecimalRandom.cs | 2,801 | C# |
using UnityEngine;
// Script que faz o efeito de paralax no fundo.
[AddComponentMenu("Scripts/Enviroment/Background")]
public class Background : MonoBehaviour {
public static Background currentBackground = null;
[System.Serializable]
public class ParalaxLayer {
public GameObject layerObject;
public float x_multiplier = 1;
public float y_multiplier = 1;
}
public ParalaxLayer[] layers;
void Awake() {
// Garante que só exista um background por vez.
if(currentBackground != null)
Destroy(currentBackground.gameObject);
currentBackground = this;
// Coloca o background dentro da camera para evitar que o background se mova de um jeito estranho.
if(GameController.instance != null)
transform.SetParent(Camera.main.transform);
}
void Update () {
if (GameController.instance == null)
return;
// "Move" cada camada em uma velocidade baseada na camera principal.
for (int i = 0; i < layers.Length; i++) {
Vector2 layer_pos = layers[i].layerObject.transform.position;
layer_pos.x = Camera.main.transform.position.x * layers[i].x_multiplier;
layer_pos.y = Camera.main.transform.position.y * layers[i].y_multiplier;
layers[i].layerObject.transform.position = layer_pos;
}
}
}
| 28.705882 | 107 | 0.618169 | [
"MIT"
] | FellowshipOfTheGame/treinamento-grupo1 | Treinamento-2018-Grupo1/Assets/Scripts/Enviroment/Background.cs | 1,467 | C# |
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
namespace MvvmKit
{
/// <summary>
/// Use this class to combine run time and design time resources.
/// <see cref="DesignTimeResource"/> instances that would be added to the <see cref="ResourceDictionary.MergedDictionaries"/>
/// property, will only be loaded at design time. You can use it for design time resources, such as design time data or resources
/// that are defined in a dynamically loaded assembly
/// </summary>
public class SelectiveResources : ResourceDictionary
{
private readonly DtCollection _noopMergedDictionaries = new DtCollection();
private class DtCollection : ObservableCollection<ResourceDictionary>
{
protected override void InsertItem(int index, ResourceDictionary item)
{
// if the type is DesignTimeResource - we only add it in design time,
// otherwise, we always add it
if ((item is DesignTimeResource) && (Exec.IsRunTime)) return;
// otherwise, add it in any condition
base.InsertItem(index, item);
}
}
public SelectiveResources()
{
var fieldInfo = typeof(ResourceDictionary).GetField("_mergedDictionaries", BindingFlags.Instance | BindingFlags.NonPublic);
if (fieldInfo != null)
{
fieldInfo.SetValue(this, _noopMergedDictionaries);
}
}
}
}
| 37.139535 | 135 | 0.646838 | [
"MIT"
] | kobi2294/MvvmKit | Source/MvvmKit/Ui/Controls/Design Time Support/SelectiveResources.cs | 1,599 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Patchwork.Attributes;
using Patchwork.Utility;
namespace Patchwork {
public partial class AssemblyPatcher {
/// <summary>
/// Fixes a parameter reference
/// </summary>
/// <param name="targetMethod"></param>
/// <param name="yourParamRef"></param>
/// <returns></returns>
///
private ParameterDefinition FixParamReference(MethodDefinition targetMethod,
ParameterReference yourParamRef) {
var targetParam = targetMethod.Parameters[yourParamRef.Index];
return targetParam;
}
/// <summary>
///
/// </summary>
/// <param name="toSimplify"></param>
/// <returns></returns>
private static OpCode SimplifyOpCode(OpCode toSimplify) {
switch (toSimplify.Code) {
case Code.Br_S:
return OpCodes.Br;
case Code.Brfalse_S:
return OpCodes.Brfalse;
case Code.Brtrue_S:
return OpCodes.Brtrue;
case Code.Beq_S:
return OpCodes.Beq;
case Code.Bge_S:
return OpCodes.Bge;
case Code.Bgt_S:
return OpCodes.Bgt;
case Code.Ble_S:
return OpCodes.Ble;
case Code.Blt_S:
return OpCodes.Blt;
case Code.Bne_Un_S:
return OpCodes.Bne_Un;
case Code.Bge_Un_S:
return OpCodes.Bge_Un;
case Code.Bgt_Un_S:
return OpCodes.Bgt_Un;
case Code.Ble_Un_S:
return OpCodes.Ble_Un;
case Code.Blt_Un_S:
return OpCodes.Blt_Un;
case Code.Leave_S:
return OpCodes.Leave;
default:
return toSimplify;
}
}
/*
* As a rule, all the Fix methods will call FixType to fix their types, while there is also one case where FixType
* will call FixMethod, which is when MVars are involved. However, to avoid infinite recursion, FixType⇒FixMethod calls
* only return partially fixed methods (Some of the types may not be fixed).
*
* Also, most Fix methods are recursive, especially FixType.
*/
/// <summary>
/// Fixes a type reference, possibly replacing a reference to a patching type from your assembly with a reference to
/// the type being patched.
/// </summary>
/// <param name="yourTypeRef">The type reference.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException">
/// This method can only fix a reference to a patching type, or a reference to a
/// nested type in a patching type.
/// </exception>
private TypeReference FixTypeReference(TypeReference yourTypeRef) {
//Fixes references to YourAssembly::PatchingType to TargetAssembly::PatchedType
//or YourAssembly::PatchingType::YourType to TargetAssembly::PatchedType::OrigType
//also imports the type to the module.
/*
* A type reference may be to the following "special" forms of a type:
* 0. A regular type.
* 1. A generic instantiation of the type, e.g. List<int> is an instantiation of List<_>
* 2. A reference (basically, 'ref int', which is displayed int&)
* 3. An array of the type (in the IL, an array type T[] is a special form of T, rather than an instantiation of Array<_>)
* x. Pinned, pointer, and a few other uncommon things I don't want to mess with right now
*
* Each is a kind of modified type that modifies a base type, exposed via ElementType. The ElementType could also be one of the above. For example we might have:
* List<int>[], List<List<int>>, List<int>&, etc
*
* We need to go down the "stack" and fix every modification, using recursion and calling ElementType. This is because we might have something like:
* List<UserIntroducedType>[] ⇒ we need to recurse twice to fix it
* UserIntroducedType[][][] ⇒ we need to recurse 3 times to fix it
*
* Note that GetElementType() should NOT be called because it returns the bottom "pure" type, not 1 level below the current type.
*
* Plus, we have references to type parameters ofc.
*/
if (yourTypeRef == null) {
Log_called_to_fix_null("type");
return null;
}
Log_fixing_reference("type", yourTypeRef);
TypeReference targetTypeRef;
var yourTypeDef = yourTypeRef.Resolve();
if (yourTypeDef != null && yourTypeDef.Module.Assembly.IsPatchingAssembly() && yourTypeDef.IsDisablePatching()) {
Log_trying_to_fix_disabled_reference("type", yourTypeRef);
}
TypeReference targetInnerTypeRef;
int index;
switch (yourTypeRef.MetadataType) {
case MetadataType.Array:
//array of the type, e.g. int[]
//kind of amusing arrays aren't generic instantiations of Array<T>, but rather
//a special form of T itself (though this is implified by the syntax T[]).
var yourArrayType = (ArrayType) yourTypeRef;
targetInnerTypeRef = FixTypeReference(yourArrayType.ElementType);
targetTypeRef = targetInnerTypeRef.MakeArrayType(yourArrayType.Rank);
break;
case MetadataType.ByReference:
//ByRef type, e.g. int& or in C# "ref int".
//Note that IL allows for variables and fields to have a reference type (C# does not)
//These sometimes appear in IL, as they are introduced by the compiler.
var yourByRefType = (ByReferenceType) yourTypeRef;
targetInnerTypeRef = FixTypeReference(yourByRefType.ElementType);
targetTypeRef = targetInnerTypeRef.MakeByReferenceType();
break;
case MetadataType.GenericInstance:
//fully instantiated generic type, like List<int>
var asGenericInstanceType = (GenericInstanceType) yourTypeRef;
var targetGenArguments =
asGenericInstanceType.GenericArguments.Select<TypeReference, TypeReference>(FixTypeReference);
targetInnerTypeRef = FixTypeReference(asGenericInstanceType.ElementType);
targetTypeRef = targetInnerTypeRef.MakeGenericInstanceType(targetGenArguments.ToArray());
break;
case MetadataType.MVar:
//method's generic type parameter. We find the DeclaringMethod, and find its version in the target assembly.
var asGenParam = (GenericParameter) yourTypeRef;
index = asGenParam.DeclaringMethod.GenericParameters.IndexOf(x => x.Name == asGenParam.Name);
//the following is dangeorus because it brings about mutual recursion FixMethod ⇔ FixType...
//the 'false' argument makes sure the recursion doesn't become infinite, as it allows for FixMethod
//not to fix all the types in the signature. After all, we just need the generic parameters.
var methodReference = FixMethodReference(asGenParam.DeclaringMethod, false);
//we need to Resolve it in order to get a sort-of more "up to date" reference to the method.
var targetDeclaringMethod = methodReference.Resolve();
var imported = TargetAssembly.MainModule.Import(targetDeclaringMethod);
targetTypeRef = imported.GenericParameters[index];
break;
case MetadataType.Var:
//type's generic type parameter
var declaringType = yourTypeRef.DeclaringType;
index = declaringType.GenericParameters.IndexOf(x => x.Name == yourTypeRef.Name);
var targetDeclaringType = FixTypeReference(declaringType);
targetTypeRef = targetDeclaringType.GenericParameters[index];
break;
case MetadataType.Sentinel: //interop: related to the varargs calling convention, "__arglist" in C#.
case MetadataType.RequiredModifier: //interop: related to marshaling
case MetadataType.OptionalModifier: //interop: related to marshaling
case MetadataType.Pinned: //interop: created using the 'fixed' keyword
case MetadataType.FunctionPointer: //interop: naked function pointer
case MetadataType.TypedByReference: //interop: related to the varargs calling convention, __typeref
case MetadataType.Pointer: //interop: pointer
throw Errors.Feature_not_supported("MetadataType not supported: {0}", yourTypeRef.MetadataType);
default:
//this is the stopping condition for the recursion, which is dealing with a normal type.
if (!yourTypeDef.Module.Assembly.IsPatchingAssembly()) {
//we assume any types that aren't from the patching assembly are safe to import directly.
targetTypeRef = TargetAssembly.MainModule.Import(yourTypeDef);
} else {
//If the type is from a patching assembly.
targetTypeRef = CurrentMemberCache.Types[yourTypeDef].TargetType;
}
if (targetTypeRef == null) {
throw Errors.Could_not_resolve_reference("type", yourTypeRef);
}
break;
}
Log_fixed_reference("type", yourTypeRef, targetTypeRef);
targetTypeRef.Module.Assembly.AssertEqual(TargetAssembly);
return targetTypeRef;
}
/// <summary>
/// This performs a more diligent Import-like operation. The standard Import method can sometimes fail unpredictably when generics are involved.
/// Note that it's possible yourMethodRef will be mutated, so don't use it.
/// </summary>
/// <param name="yourMethodRef">A reference to your method.</param>
/// <returns></returns>
private MethodReference ManualImportMethod(MethodReference yourMethodRef) {
//the following is required due to a workaround.
var newRef = yourMethodRef.IsGenericInstance ? yourMethodRef : yourMethodRef.MakeReference();
foreach (var param in newRef.Parameters) {
param.ParameterType = FixTypeReference(param.ParameterType);
}
if (!newRef.ReturnType.IsVarOrMVar()) {
newRef.ReturnType = FixTypeReference(yourMethodRef.ReturnType);
}
return newRef;
}
/// <summary>
/// Fixes the method reference.
/// </summary>
/// <param name="yourMethodRef">The method reference.</param>
/// <param name="isntFixTypeCall">This parameter is sort of a hack that lets FixType call FixMethod to fix MVars, without infinite recursion. If set to false, it avoids fixing some types.</param>
/// <returns></returns>
/// <exception cref="Exception">Method isn't part of a patching type in this assembly...</exception>
private MethodReference FixMethodReference(MethodReference yourMethodRef, bool isntFixTypeCall = true) {
//Fixes reference like YourAssembly::PatchingClass::Method to TargetAssembly::PatchedClass::Method
if (yourMethodRef == null) {
Log_called_to_fix_null("method");
return null;
}
Log_fixing_reference("method", yourMethodRef);
Asserts.AssertTrue(yourMethodRef.DeclaringType != null);
var yourMethodDef = yourMethodRef.Resolve();
if (yourMethodDef.IsDisablePatching()) {
Log_trying_to_fix_disabled_reference("method", yourMethodDef);
}
/*
* In comparison to types, method references to methods are pretty simple. There are only two kinds:
* 1. A regular method reference
* 2. A reference to an instantiated generic method, e.g. Create<int>
*
* 3. As a special case, any method reference (assume non-generic) that has a generic DeclaringType.
*/
MethodReference targetMethodRef;
if (yourMethodRef.IsGenericInstance) {
var yourGeneric = (GenericInstanceMethod) yourMethodRef;
var targetBaseMethod = FixMethodReference(yourGeneric.ElementMethod);
var targetGenericInstMethod = new GenericInstanceMethod(targetBaseMethod);
foreach (var arg in yourGeneric.GenericArguments) {
var targetGenericArg = FixTypeReference(arg);
targetGenericInstMethod.GenericArguments.Add(targetGenericArg);
}
targetMethodRef = targetGenericInstMethod;
} else {
TypeReference typeToFix = yourMethodRef.DeclaringType;
var action = CurrentMemberCache.Methods.TryGet(yourMethodDef);
var memberAlias = action?.ActionAttribute as MemberAliasAttribute;
if (memberAlias?.AliasedMemberDeclaringType != null) {
typeToFix = (TypeReference) memberAlias.AliasedMemberDeclaringType;
}
var targetType = FixTypeReference(typeToFix);
var targetBaseMethodDef = yourMethodRef;
if (yourMethodDef.Module.Assembly.IsPatchingAssembly()) {
var targetMethodDef = action?.TargetMember;
if (targetMethodDef == null) {
throw Errors.Could_not_resolve_reference("method", yourMethodRef);
}
targetBaseMethodDef = targetMethodDef;
} else {
targetBaseMethodDef = yourMethodRef;
}
var newMethodRef = targetBaseMethodDef.MakeReference();
newMethodRef.DeclaringType = targetType;
targetMethodRef = newMethodRef;
if (isntFixTypeCall) {
targetMethodRef = ManualImportMethod(targetMethodRef);
}
}
targetMethodRef.Module.Assembly.AssertEqual(TargetAssembly);
Log_fixed_reference("method", yourMethodRef, targetMethodRef);
return targetMethodRef;
}
private FieldReference FixFieldReference(FieldReference yourFieldRef) {
if (yourFieldRef == null) {
Log_called_to_fix_null("field");
return null;
}
Log_fixing_reference("field", yourFieldRef);
Asserts.AssertTrue(yourFieldRef.DeclaringType != null);
var yourFieldDef = yourFieldRef.Resolve();
if (yourFieldDef.IsDisablePatching()) {
Log_trying_to_fix_disabled_reference("field", yourFieldRef);
}
var targetType = FixTypeReference(yourFieldRef.DeclaringType);
var targetBaseFieldDef = yourFieldRef;
if (yourFieldDef.Module.Assembly.IsPatchingAssembly()) {
//additional checking
var targetFieldDef = CurrentMemberCache.Fields.TryGet(yourFieldDef)?.TargetMember;
if (targetFieldDef == null) {
throw Errors.Could_not_resolve_reference("field", yourFieldRef);
}
targetBaseFieldDef = targetFieldDef;
} else {
//we assume that types that aren't in a patching assembly will never reference types in a patching assembly
targetBaseFieldDef = yourFieldRef;
}
var newFieldRef = targetBaseFieldDef.MakeReference();
newFieldRef.DeclaringType = targetType;
newFieldRef.FieldType = FixTypeReference(newFieldRef.FieldType);
var targetFieldRef = TargetAssembly.MainModule.Import(newFieldRef);
Log_fixed_reference("field", yourFieldRef, targetFieldRef);
targetFieldRef.Module.Assembly.AssertEqual(TargetAssembly);
return targetFieldRef;
}
private void Log_trying_to_fix_disabled_reference(string kind, MemberReference badMemberRef) {
Log.Warning("Trying to fix {0} reference to {1}, but it has the DisablePatching attribute.", kind,
badMemberRef.UserFriendlyName());
}
private void Log_called_to_fix_null(string kind) {
Log.Warning("Trying to fix {0} reference, but the reference was null. Fixing to null.", kind);
}
private void Log_fixing_reference(string kind, MemberReference badMemberRef) {
Log.Verbose("Trying to fix {0} reference for: {1}", kind, badMemberRef.UserFriendlyName());
}
private void Log_fixed_reference(string kind, MemberReference oldMemberRef, MemberReference fixedMemberRef) {
Log.Verbose("Fixed {0} reference: {1} ⇒ {2}", kind, oldMemberRef.UserFriendlyName(),
fixedMemberRef.UserFriendlyName());
}
}
}
| 42.737752 | 197 | 0.72967 | [
"MIT"
] | DankRank/Patchwork | Patchwork.Engine/AssemblyPatcher/FixReferences.cs | 14,842 | 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetCore.Analyzers.Security.DoNotUseDataSetReadXml,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Security.UnitTests
{
public class DoNotUseDataSetReadXmlTests
{
[Fact]
public async Task ReadXml_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Data;
namespace Blah
{
public class Program
{
public void Unsafe(Stream s)
{
DataSet dataSet = new DataSet();
dataSet.ReadXml(s);
}
}
}",
GetCSharpResultAt(12, 13, "XmlReadMode DataSet.ReadXml(Stream stream)"));
}
[Fact]
public async Task DerivedReadXml_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Data;
namespace Blah
{
public class Program
{
public void Unsafe(string s)
{
MyDataSet dataSet = new MyDataSet();
dataSet.ReadXml(s);
}
}
public class MyDataSet : DataSet
{
}
}",
GetCSharpResultAt(12, 13, "XmlReadMode DataSet.ReadXml(string fileName)"));
}
[Fact]
public async Task DerivedReadXmlEvenWithReadXmlSchema_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Data;
namespace Blah
{
public class Program
{
public void Unsafe(string s)
{
MyDataSet dataSet = new MyDataSet();
dataSet.ReadXmlSchema("""");
dataSet.ReadXml(s);
}
}
public class MyDataSet : DataSet
{
}
}",
GetCSharpResultAt(13, 13, "XmlReadMode DataSet.ReadXml(string fileName)"));
}
[Fact]
public async Task RejectChanges_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Data;
namespace Blah
{
public class Program
{
public void Safe(Stream s)
{
DataSet dataSet = new DataSet();
dataSet.RejectChanges();
}
}
}");
}
[Fact]
public async Task AutogeneratedProbablyForGui1_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace Blah
{
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute(""code"")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute(""GetTypedDataSetSchema"")]
[global::System.Xml.Serialization.XmlRootAttribute(""Package"")]
[global::System.ComponentModel.Design.HelpKeywordAttribute(""vs.data.DataSet"")]
public partial class Something : global::System.Data.DataSet {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""System.Data.Design.TypedDataSetGenerator"", ""4.0.0.0"")]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables[""Something""] != null)) {
//// base.Tables.Add(new SomethingTable(ds.Tables[""Something""]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""System.Data.Design.TypedDataSetGenerator"", ""4.0.0.0"")]
internal void InitVars() {
//this.InitVars(true);
}
}
}",
GetCSharpAutogeneratedResultAt(21, 17, "XmlReadMode DataSet.ReadXml(XmlReader reader)"),
GetCSharpAutogeneratedResultAt(35, 17, "XmlReadMode DataSet.ReadXml(XmlReader reader)"));
}
[Fact]
public async Task AutogeneratedProbablyForGui2_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace Blah
{
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute(""code"")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute(""GetTypedDataSetSchema"")]
[global::System.Xml.Serialization.XmlRootAttribute(""Package"")]
[global::System.ComponentModel.Design.HelpKeywordAttribute(""vs.data.DataSet"")]
public partial class Something : global::System.Data.DataSet {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables[""Something""] != null)) {
//// base.Tables.Add(new SomethingTable(ds.Tables[""Something""]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
internal void InitVars() {
//this.InitVars(true);
}
}
}",
GetCSharpAutogeneratedResultAt(20, 17, "XmlReadMode DataSet.ReadXml(XmlReader reader)"),
GetCSharpAutogeneratedResultAt(34, 17, "XmlReadMode DataSet.ReadXml(XmlReader reader)"));
}
private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseDataSetReadXml.RealMethodUsedDescriptor)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
private static DiagnosticResult GetCSharpAutogeneratedResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseDataSetReadXml.RealMethodUsedInAutogeneratedDescriptor)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
}
}
| 36.124444 | 161 | 0.619218 | [
"Apache-2.0"
] | AndrewZu1337/roslyn-analyzers | src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXmlTests.cs | 8,130 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteNetworkInterfacePermission Request Marshaller
/// </summary>
public class DeleteNetworkInterfacePermissionRequestMarshaller : IMarshaller<IRequest, DeleteNetworkInterfacePermissionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DeleteNetworkInterfacePermissionRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteNetworkInterfacePermissionRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2");
request.Parameters.Add("Action", "DeleteNetworkInterfacePermission");
request.Parameters.Add("Version", "2016-11-15");
if(publicRequest != null)
{
if(publicRequest.IsSetForce())
{
request.Parameters.Add("Force", StringUtils.FromBool(publicRequest.Force));
}
if(publicRequest.IsSetNetworkInterfacePermissionId())
{
request.Parameters.Add("NetworkInterfacePermissionId", StringUtils.FromString(publicRequest.NetworkInterfacePermissionId));
}
}
return request;
}
private static DeleteNetworkInterfacePermissionRequestMarshaller _instance = new DeleteNetworkInterfacePermissionRequestMarshaller();
internal static DeleteNetworkInterfacePermissionRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteNetworkInterfacePermissionRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.32967 | 180 | 0.632323 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/DeleteNetworkInterfacePermissionRequestMarshaller.cs | 3,397 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Bot
{
public partial class AzureBotMsteamsDeleteTask : ExternalProcessTaskBase<AzureBotMsteamsDeleteTask>
{
/// <summary>
/// Delete the Microsoft Teams Channel on a bot.
/// </summary>
public AzureBotMsteamsDeleteTask(string name = null , string resourceGroup = null)
{
WithArguments("az bot msteams delete");
WithArguments("--name");
if (!string.IsNullOrEmpty(name))
{
WithArguments(name);
}
WithArguments("--resource-group");
if (!string.IsNullOrEmpty(resourceGroup))
{
WithArguments(resourceGroup);
}
}
protected override string Description { get; set; }
}
}
| 25.105263 | 104 | 0.604822 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Bot/AzureBotMsteamsDeleteTask.cs | 954 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Twilio.OwlFinance.Domain.Interfaces.Services;
using Twilio.OwlFinance.Domain.Model;
using Twilio.OwlFinance.Domain.Model.Api;
namespace Twilio.OwlFinance.BankingService.Api
{
public class WeatherController : BaseAuthenticatedApiController
{
private readonly IWeatherService weatherService;
public WeatherController(IWeatherService weatherService)
{
this.weatherService = weatherService;
}
/// <summary>
///
/// </summary>
/// <response code="500">Server error, check Error Message property</response>
/// <response code="400">User is not authorized</response>
/// <response code="200">Everything is OK</response>
[ResponseType(typeof(ApiResponse<WeatherModel>))]
[Route("api/weather")]
[HttpGet]
public async Task<HttpResponseMessage> GetWeather(int customerID)
{
var response = await weatherService.GetCustomerWeather(customerID);
return SendHttpResponse(response);
}
}
}
| 32.527778 | 86 | 0.674637 | [
"MIT"
] | jonedavis/OwlFinanceDemo | api/website/TwilioOwlFinanceApi/Api/WeatherController.cs | 1,173 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using GeologicalLandforms.GraphEditor;
using NodeEditorFramework;
using NodeEditorFramework.Utilities;
using UnityEngine;
namespace TerrainGraph;
[Serializable]
[Node(false, "Grid/Map Sides", 250)]
public class NodeGridRotateToMapSides : NodeBase
{
public const string ID = "gridRotateToMapSides";
public override string GetID => ID;
public override Vector2 MinSize => new(100, 10);
public override string Title => "Map Sides";
[NonSerialized]
public List<ValueConnectionKnob> InputKnobs = new();
[NonSerialized]
public List<ValueConnectionKnob> OutputKnobs = new();
public List<MapSide> MapSides = new();
public override void RefreshDynamicKnobs()
{
InputKnobs = dynamicConnectionPorts.Where(k => k.name.StartsWith("Input")).Cast<ValueConnectionKnob>().ToList();
OutputKnobs = dynamicConnectionPorts.Where(k => k.name.StartsWith("Output")).Cast<ValueConnectionKnob>().ToList();
UpdateThresholdArray();
}
private void UpdateThresholdArray()
{
while (MapSides.Count < InputKnobs.Count) MapSides.Add(MapSides.Count == 0 ? MapSide.Front : MapSides[MapSides.Count - 1]);
while (MapSides.Count > 0 && MapSides.Count > InputKnobs.Count) MapSides.RemoveAt(MapSides.Count - 1);
}
public override void NodeGUI()
{
while (InputKnobs.Count < 1) CreateNewKnobPair();
GUILayout.BeginVertical(BoxStyle);
UpdateThresholdArray();
for (int i = 0; i < InputKnobs.Count; i++)
{
GUILayout.BeginHorizontal(BoxStyle);
if (GUILayout.Button(MapSides[i].ToString(), GUI.skin.box, DoubleBoxLayout))
{
var idx = i;
Dropdown<MapSide>(s =>
{
MapSides[idx] = s;
canvas.OnNodeChange(this);
});
}
InputKnobs[i].SetPosition();
OutputKnobs[i].SetPosition();
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
if (GUI.changed)
canvas.OnNodeChange(this);
}
protected void CreateNewKnobPair()
{
CreateValueConnectionKnob(new("Input " + InputKnobs.Count, Direction.In, GridFunctionConnection.Id));
CreateValueConnectionKnob(new("Output " + InputKnobs.Count, Direction.Out, GridFunctionConnection.Id));
RefreshDynamicKnobs();
}
public override void FillNodeActionsMenu(NodeEditorInputInfo inputInfo, GenericMenu menu)
{
base.FillNodeActionsMenu(inputInfo, menu);
menu.AddSeparator("");
if (InputKnobs.Count < 20)
{
menu.AddItem(new GUIContent ("Add branch"), false, CreateNewKnobPair);
canvas.OnNodeChange(this);
}
if (InputKnobs.Count > 1)
{
menu.AddItem(new GUIContent ("Remove branch"), false, () =>
{
DeleteConnectionPort(InputKnobs[InputKnobs.Count - 1]);
DeleteConnectionPort(OutputKnobs[InputKnobs.Count - 1]);
RefreshDynamicKnobs();
canvas.OnNodeChange(this);
});
}
}
public override bool Calculate()
{
for (int i = 0; i < InputKnobs.Count; i++)
{
OutputKnobs[i].SetValue<ISupplier<IGridFunction<double>>>(new NodeGridRotate.Output(
SupplierOrGridFixed(InputKnobs[i], GridFunction.Zero),
Supplier.Of(MapSideToAngle(MapSides[i]) + Landform.GeneratingTile.LandformDirection.AsAngle),
GridSize / 2, GridSize / 2
));
}
return true;
}
public static double MapSideToAngle(MapSide mapSide)
{
return mapSide switch
{
MapSide.Front => 90,
MapSide.Back => -90,
MapSide.Left => 0,
MapSide.Right => 180,
_ => throw new ArgumentOutOfRangeException(nameof(mapSide), mapSide, null)
};
}
public static double MapSideToWorldAngle(MapSide mapSide)
{
return MapSideToAngle(mapSide) - 90f;
}
public enum MapSide
{
Front, Back, Left, Right
}
} | 30.422535 | 131 | 0.598611 | [
"MIT"
] | m00nl1ght-dev/GeologicalLandforms | Sources/GeologicalLandforms/GraphEditor/Nodes/Grid/NodeGridRotateToMapSides.cs | 4,320 | C# |
/* Any copyright is dedicated to the Public Domain.
* https://creativecommons.org/publicdomain/zero/1.0/ */
using CefSharp.WinForms;
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 Wowpaper
{
public partial class RootForm : Form
{
private ChromiumWebBrowser browser;
public RootForm(string startUrl)
{
InitializeComponent();
browser = new ChromiumWebBrowser(startUrl);
browser.Dock = DockStyle.Fill;
Controls.Add(browser);
}
private void Form1_Load(object sender, EventArgs e)
{
this.SetAsWallpaper();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
}
} | 24.675 | 76 | 0.64843 | [
"CC0-1.0"
] | remi6397/Wowpaper_WinFormsWallpaper | Wowpaper/RootForm.cs | 989 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Imported Device Identity.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class ImportedDeviceIdentity : Entity
{
///<summary>
/// The ImportedDeviceIdentity constructor
///</summary>
public ImportedDeviceIdentity()
{
this.ODataType = "microsoft.graph.importedDeviceIdentity";
}
/// <summary>
/// Gets or sets created date time.
/// Created Date Time of the device
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "createdDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? CreatedDateTime { get; set; }
/// <summary>
/// Gets or sets description.
/// The description of the device
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "description", Required = Newtonsoft.Json.Required.Default)]
public string Description { get; set; }
/// <summary>
/// Gets or sets enrollment state.
/// The state of the device in Intune. Possible values are: unknown, enrolled, pendingReset, failed, notContacted, blocked.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "enrollmentState", Required = Newtonsoft.Json.Required.Default)]
public EnrollmentState? EnrollmentState { get; set; }
/// <summary>
/// Gets or sets imported device identifier.
/// Imported Device Identifier
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "importedDeviceIdentifier", Required = Newtonsoft.Json.Required.Default)]
public string ImportedDeviceIdentifier { get; set; }
/// <summary>
/// Gets or sets imported device identity type.
/// Type of Imported Device Identity. Possible values are: unknown, imei, serialNumber.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "importedDeviceIdentityType", Required = Newtonsoft.Json.Required.Default)]
public ImportedDeviceIdentityType? ImportedDeviceIdentityType { get; set; }
/// <summary>
/// Gets or sets last contacted date time.
/// Last Contacted Date Time of the device
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "lastContactedDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? LastContactedDateTime { get; set; }
/// <summary>
/// Gets or sets last modified date time.
/// Last Modified DateTime of the description
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "lastModifiedDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? LastModifiedDateTime { get; set; }
/// <summary>
/// Gets or sets platform.
/// The platform of the Device. Possible values are: unknown, ios, android, windows, windowsMobile, macOS.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "platform", Required = Newtonsoft.Json.Required.Default)]
public Platform? Platform { get; set; }
}
}
| 44.684783 | 158 | 0.638288 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/ImportedDeviceIdentity.cs | 4,111 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.ServiceAuth;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Presence
{
public class PresenceServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IPresenceService m_PresenceService;
public PresenceServerPostHandler(IPresenceService service, IServiceAuth auth) :
base("POST", "/presence", auth)
{
m_PresenceService = service;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
string method = string.Empty;
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
method = request["METHOD"].ToString();
switch (method)
{
case "login":
return LoginAgent(request);
case "logout":
return LogoutAgent(request);
case "logoutregion":
return LogoutRegionAgents(request);
case "report":
return Report(request);
case "getagent":
return GetAgent(request);
case "getagents":
return GetAgents(request);
}
m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[PRESENCE HANDLER]: Exception in method {0}: {1}", method, e);
}
return FailureResult();
}
byte[] LoginAgent(Dictionary<string, object> request)
{
string user = String.Empty;
UUID session = UUID.Zero;
UUID ssession = UUID.Zero;
if (!request.ContainsKey("UserID") || !request.ContainsKey("SessionID"))
return FailureResult();
user = request["UserID"].ToString();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (request.ContainsKey("SecureSessionID"))
// If it's malformed, we go on with a Zero on it
UUID.TryParse(request["SecureSessionID"].ToString(), out ssession);
if (m_PresenceService.LoginAgent(user, session, ssession))
return SuccessResult();
return FailureResult();
}
byte[] LogoutAgent(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
if (!request.ContainsKey("SessionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (m_PresenceService.LogoutAgent(session))
return SuccessResult();
return FailureResult();
}
byte[] LogoutRegionAgents(Dictionary<string, object> request)
{
UUID region = UUID.Zero;
if (!request.ContainsKey("RegionID"))
return FailureResult();
if (!UUID.TryParse(request["RegionID"].ToString(), out region))
return FailureResult();
if (m_PresenceService.LogoutRegionAgents(region))
return SuccessResult();
return FailureResult();
}
byte[] Report(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
UUID region = UUID.Zero;
if (!request.ContainsKey("SessionID") || !request.ContainsKey("RegionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (!UUID.TryParse(request["RegionID"].ToString(), out region))
return FailureResult();
if (m_PresenceService.ReportAgent(session, region))
{
return SuccessResult();
}
return FailureResult();
}
byte[] GetAgent(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
if (!request.ContainsKey("SessionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
PresenceInfo pinfo = m_PresenceService.GetAgent(session);
Dictionary<string, object> result = new Dictionary<string, object>();
if (pinfo == null)
result["result"] = "null";
else
result["result"] = pinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] GetAgents(Dictionary<string, object> request)
{
string[] userIDs;
if (!request.ContainsKey("uuids"))
{
m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents called without required uuids argument");
return FailureResult();
}
if (!(request["uuids"] is List<string>))
{
m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents input argument was of unexpected type {0}", request["uuids"].GetType().ToString());
return FailureResult();
}
userIDs = ((List<string>)request["uuids"]).ToArray();
PresenceInfo[] pinfos = m_PresenceService.GetAgents(userIDs);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((pinfos == null) || ((pinfos != null) && (pinfos.Length == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (PresenceInfo pinfo in pinfos)
{
Dictionary<string, object> rinfoDict = pinfo.ToKeyValuePairs();
result["presence" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
}
}
| 34.833898 | 148 | 0.577851 | [
"BSD-3-Clause"
] | BlueWall/opensim | OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs | 10,276 | C# |
using System;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace WPSystem.Runtime
{
public enum UIPosition
{
Top,
Down
}
[CreateAssetMenu]
#if UNITY_EDITOR
[InitializeOnLoad] //allow to call the static constructor
#endif
/**
* This class is used to keep track of the default settings.
* It is loaded at the start of the Unity editor and on domain reload.
*/
public class WaypointSettings : ScriptableObject
{
private static WaypointSettings _instance;
#pragma warning disable 0649
[Header("Default settings used when spawning a new waypoint system")]
[SerializeField, Tooltip("Used to determine what the waypoints should stick on.")]
private StickMode _defaultStickMode;
[SerializeField, Tooltip("Used to determine at which distance we should consider that we reached a waypoint")]
private float _defaultDistanceToReach = 0.5f;
[SerializeField, Tooltip("Default color for the waypoints")]
private Color _waypointsColor = Color.blue;
[SerializeField, Tooltip("If set to true, the first waypoint will be the nearest, else the first one (the flag)")]
private bool _startAtTheNearest;
[SerializeField, Tooltip("One-way : Go to finish then stop.\n" +
"Loop : Go the end then loop to the start\n" +
"Ping-pong : Go to the end then go back in the opposite direction")]
private LoopType _defaultLoopType;
[Header("Global settings")]
[SerializeField, Tooltip("Position of the UI")] private UIPosition _uiPosition;
[SerializeField]
private bool _showTheDistanceToReachGizmos;
#pragma warning restore 0649
public StickMode DefaultStickMode => _defaultStickMode;
public float DefaultDistanceToReach => _defaultDistanceToReach;
public Color WaypointsColor => _waypointsColor;
public bool StartAtTheNearest => _startAtTheNearest;
public LoopType DefaultLoopType => _defaultLoopType;
public UIPosition UiPosition => _uiPosition;
public bool ShowTheDistanceToReachFGizmos => _showTheDistanceToReachGizmos;
#if UNITY_EDITOR
static WaypointSettings()
{
//we want to call LoadAll AFTER assembly reload or else it will fail with an error
AssemblyReloadEvents.afterAssemblyReload += () => { GetInstance(); };
}
public static WaypointSettings GetInstance()
{
if (!_instance)
{
try
{
//gets the Scriptable object instance asset in the Assets folder.
_instance = Resources.LoadAll<WaypointSettings>("").First();
}
catch (Exception)
{
Debug.LogError("No WaypointSettings !");
}
}
return _instance;
}
#endif
}
}
| 34.477778 | 123 | 0.618434 | [
"MIT"
] | ReyAnthony/waypoint-system | Assets/WPSystem/Runtime/WaypointSettings.cs | 3,105 | C# |
namespace EasyCaching.UnitTests
{
using System;
using EasyCaching.Core.Serialization;
using ProtoBuf;
using Xunit;
public abstract class BaseSerializerTest
{
protected IEasyCachingSerializer _serializer;
[Fact]
public void Serialize_Object_Should_Succeed()
{
var res = _serializer.Serialize(new Model { Prop = "abc" });
Assert.NotEmpty(res);
}
[Fact]
public void Deserialize_Object_Should_Succeed()
{
var bytes = _serializer.Serialize(new Model { Prop = "abc" });
var res = _serializer.Deserialize<Model>(bytes);
Assert.Equal("abc", res.Prop);
}
[Fact]
public void SerializeObject_should_Succeed()
{
object obj = new Model { Prop = "abc" };
var bytes = _serializer.SerializeObject(obj);
Assert.NotEmpty(bytes);
}
[Fact]
public void DeserializeObject_should_Succeed()
{
object obj = new Model { Prop = "abc" };
var bytes = _serializer.SerializeObject(obj);
var desObj = _serializer.DeserializeObject(bytes) as Model;
Assert.Equal("abc", desObj.Prop);
}
[Theory]
[InlineData("N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fFhf8bnNa-yQH3g")]
[InlineData("123abc")]
public void Serialize_String_Should_Succeed(string str)
{
var res = _serializer.Serialize(str);
Assert.NotEmpty(res);
}
[Theory]
[InlineData("N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fFhf8bnNa-yQH3g")]
[InlineData("123abc")]
public void Deserialize_String_Should_Succeed(string str)
{
var bytes = _serializer.Serialize(str);
var res = _serializer.Deserialize<string>(bytes);
Assert.Equal(str, res);
}
}
[Serializable]
[ProtoContract]
public class Model
{
[ProtoMember(1)]
public string Prop { get; set; }
}
} | 27.083333 | 174 | 0.615824 | [
"MIT"
] | 861191244/EasyCaching | test/EasyCaching.UnitTests/SerializerTests/BaseSerializerTest.cs | 2,277 | C# |
using com.idpx.core.oauth.data;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace com.idpx.core.oauth.clients
{
public class OAuth2ClientForPlanningCenter : OAuth2Client<UserData>, IOAuthClient
{
public OAuth2ClientForPlanningCenter(string loginUrl, string tokenUrl, string revokeTokenUrl, string dataUrl, string clientId, string clientSecret, string scope, string redirectUrl, string stateId, string prompt = null, string hint = null)
: base(loginUrl, tokenUrl, revokeTokenUrl, dataUrl, clientId, clientSecret, scope, redirectUrl, stateId, prompt: prompt, hint: hint)
{
}
protected override async Task OnUserDataAsync(dynamic data)
{
#region Sample Response
/*
{
{
"data":{
"type":"Person",
"id":"56586865",
"attributes":{
"accounting_administrator":true,
"anniversary":null,
"avatar":"https://people.planningcenteronline.com/static/no_photo_thumbnail_gray.png",
"birthdate":null,
"child":false,
"created_at":"2019-07-08T21:57:47Z",
"demographic_avatar_url":"https://people.planningcenteronline.com/static/no_photo_thumbnail_gray.png",
"first_name":"Test",
"gender":null,
"given_name":null,
"grade":null,
"graduation_year":null,
"inactivated_at":null,
"last_name":"Person",
"medical_notes":null,
"membership":null,
"middle_name":null,
"name":"Test Person",
"nickname":null,
"passed_background_check":false,
"people_permissions":null,
"remote_id":null,
"school_type":null,
"site_administrator":true,
"status":"active",
"updated_at":"2019-07-08T21:57:47Z"
},
"relationships":{
"primary_campus":{
"data":null
}
},
"links":{
"":"https://api.planningcenteronline.com/people/v2/people/56586865/",
"addresses":"https://api.planningcenteronline.com/people/v2/people/56586865/addresses",
"apps":"https://api.planningcenteronline.com/people/v2/people/56586865/apps",
"connected_people":"https://api.planningcenteronline.com/people/v2/people/56586865/connected_people",
"emails":"https://api.planningcenteronline.com/people/v2/people/56586865/emails",
"field_data":"https://api.planningcenteronline.com/people/v2/people/56586865/field_data",
"household_memberships":"https://api.planningcenteronline.com/people/v2/people/56586865/household_memberships",
"households":"https://api.planningcenteronline.com/people/v2/people/56586865/households",
"inactive_reason":null,
"marital_status":null,
"message_groups":"https://api.planningcenteronline.com/people/v2/people/56586865/message_groups",
"messages":"https://api.planningcenteronline.com/people/v2/people/56586865/messages",
"name_prefix":null,
"name_suffix":null,
"notes":"https://api.planningcenteronline.com/people/v2/people/56586865/notes",
"person_apps":"https://api.planningcenteronline.com/people/v2/people/56586865/person_apps",
"phone_numbers":"https://api.planningcenteronline.com/people/v2/people/56586865/phone_numbers",
"platform_notifications":"https://api.planningcenteronline.com/people/v2/people/56586865/platform_notifications",
"primary_campus":null,
"school":null,
"social_profiles":"https://api.planningcenteronline.com/people/v2/people/56586865/social_profiles",
"workflow_cards":"https://api.planningcenteronline.com/people/v2/people/56586865/workflow_cards",
"self":"https://api.planningcenteronline.com/people/v2/people/56586865"
}
},
"included":[
],
"meta":{
"can_include":[
"addresses",
"emails",
"field_data",
"households",
"inactive_reason",
"marital_status",
"name_prefix",
"name_suffix",
"person_apps",
"phone_numbers",
"platform_notifications",
"primary_campus",
"school",
"social_profiles"
],
"parent":{
"id":"293345",
"type":"Organization"
}
}
}
}
*/
#endregion
var emailData = JsonConvert.DeserializeObject<dynamic>(await GetAsync(data?.data?.links?.emails?.ToString(), DataRequestHeaders));
#region Sample Response
/*
{
{
"links":{
"self":"https://api.planningcenteronline.com/people/v2/people/56586865/emails"
},
"data":[
{
"type":"Email",
"id":"35893217",
"attributes":{
"address":"developer@logonlabs.com",
"created_at":"2019-07-08T21:57:47Z",
"location":"Work",
"primary":true,
"updated_at":"2019-07-08T21:57:47Z"
},
"relationships":{
"person":{
"data":{
"type":"Person",
"id":"56586865"
}
}
},
"links":{
"self":"https://api.planningcenteronline.com/people/v2/emails/35893217"
}
}
],
"included":[
],
"meta":{
"total_count":1,
"count":1,
"can_order_by":[
"address",
"location",
"primary",
"created_at",
"updated_at"
],
"can_query_by":[
"address",
"location",
"primary"
],
"parent":{
"id":"56586865",
"type":"Person"
}
}
}
}
*/
#endregion
var emails = new List<dynamic>(emailData.data);
var email = (string)null;
foreach (var e in emails)
{
if (e?.attributes?.primary?.Value ?? false)
{
email = e?.attributes?.address?.Value;
break;
}
}
_userData.ParseUserData(data?.data?.id?.Value.ToString(), email, data?.data?.attributes?.first_name?.Value, data?.data?.attributes?.last_name?.Value, data?.data?.attributes?.avatar?.Value);
}
}
} | 41.597884 | 248 | 0.466039 | [
"MIT"
] | iguigova/fribs.netcore.idpx | com.idpx.core.oauth.clients/OAuth2ClientForPlanningCenter.cs | 7,864 | C# |
using System.Collections.Generic;
using Contoso.Models;
namespace ContosoWeb.ViewModels
{
public class HomeViewModel
{
public Match NextMatch { get; set; }
public Match CurrentMatch { get; set; }
public List<Match> PreviousMatches { get; set; }
public List<Product> NewProducts { get; set; }
public List<Product> TopSellingProducts { get; set; }
}
} | 26.933333 | 61 | 0.658416 | [
"MIT"
] | Azure-Architecture-Workshop/contososports | src/ContosoWeb/ViewModels/HomeViewModel.cs | 406 | C# |
namespace JccPropertyHub.Domain.Core.Interfaces {
public interface IValidator<in TRequest, out TValidation> {
TValidation Validate(TRequest request);
}
} | 34 | 63 | 0.741176 | [
"Apache-2.0"
] | javiercozar/JccPropertyHub | JccPropertyHub.Domain.Core/Interfaces/IValidator.cs | 172 | C# |
namespace Rosalia.Core.Tasks.Futures
{
/// <summary>
/// A monad used to configure tasks.
/// </summary>
public interface ITaskFuture<out T> where T : class
{
Identity Identity { get; }
T FetchValue(TaskContext context);
}
} | 22.083333 | 55 | 0.607547 | [
"MIT"
] | guryanovev/Rosalia | Src/Rosalia.Core/Tasks/Futures/ITaskFuture.cs | 265 | C# |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Xunit;
namespace Rhino.Mocks.Tests.FieldsProblem
{
public class FieldProblem_Blaz
{
[Fact]
public void SameNameInterface()
{
MockRepository mocks = new MockRepository();
IDemo demo1 = (IDemo)mocks.StrictMock(typeof(IDemo));
Other.IDemo demo2 = (Other.IDemo)mocks.StrictMock(typeof(Other.IDemo));
Assert.NotEqual(demo1.GetType(), demo2.GetType());
}
}
namespace Other
{
public interface IDemo
{
string Name { get; set; }
}
}
}
| 41.436364 | 84 | 0.689337 | [
"BSD-3-Clause"
] | Carolinehan/rhino-mocks | Rhino.Mocks.Tests/FieldsProblem/FieldProblem_Blaz.cs | 2,281 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TypeGen.Cli
{
internal class AppConfig
{
public static string Version => "2.4.3";
}
}
| 16.642857 | 48 | 0.703863 | [
"MIT"
] | fabiomaistro/TypeGen | src/TypeGen/TypeGen.Cli/AppConfig.cs | 233 | C# |
namespace King.Service.Demo.Tasks
{
using System;
using System.Diagnostics;
/// <summary>
/// Simple implementation for regularly used tasks
/// </summary>
public class AttributeBasedTasks
{
/// <summary>
/// Occurs once during start-up
/// </summary>
[Initialize]
public void InitializeDataStore()
{
Trace.TraceInformation("Initialize.");
}
/// <summary>
/// Runs on a set frequency
/// </summary>
[RunsEvery]
public void Recurring()
{
Trace.TraceInformation("Working.");
}
/// <summary>
/// Runs between certain frequency
/// </summary>
[RunsBetween]
public bool Dynamic()
{
var random = new Random();
var workWasDone = (random.Next() % 2) == 0;
Trace.TraceInformation("Work was done: {0}", workWasDone);
return workWasDone;
}
/// <summary>
/// Occurs once during startup
/// Runs on a set frequency
/// </summary>
[RunsEvery]
[Initialize]
public void WhyWouldYouDoThis()
{
Trace.TraceInformation("I don't know.");
}
}
}
| 23.381818 | 70 | 0.504666 | [
"MIT"
] | jefking/King.Service | King.Service.Demo/Tasks/AttributeBasedTasks.cs | 1,288 | C# |
namespace _07.MetricConverter
{
using System;
public class MetricConverter
{
static void Main()
{
var number = double.Parse(Console.ReadLine());
string from = Console.ReadLine();
string to = Console.ReadLine();
double resultInMeters = 0;
switch (from)
{
case "m":
resultInMeters = number;
break;
case "mm":
resultInMeters = number / 1000;
break;
case "cm":
resultInMeters = number / 100;
break;
case "km":
resultInMeters = number / 0.001;
break;
case "mi":
resultInMeters = number / 0.000621371192;
break;
case "in":
resultInMeters = number / 39.3700787;
break;
case "ft":
resultInMeters = number / 3.2808399;
break;
case "yd":
resultInMeters = number / 1.0936133;
break;
default:
break;
}
double result = 0;
switch (to)
{
case "m":
result = resultInMeters;
break;
case "mm":
result = resultInMeters * 1000;
break;
case "cm":
result = resultInMeters * 100;
break;
case "km":
result = resultInMeters * 0.001;
break;
case "mi":
result = resultInMeters * 0.000621371192;
break;
case "in":
result = resultInMeters * 39.3700787;
break;
case "ft":
result = resultInMeters * 3.2808399;
break;
case "yd":
result = resultInMeters * 1.0936133;
break;
default:
break;
}
Console.WriteLine(string.Format("{0:F8}", result));
}
}
}
| 24.418367 | 63 | 0.361889 | [
"MIT"
] | Steffkn/SoftUni | 01.ProgrammingBasicsC#/03.SimpleConditionalStatements/08.MetricConverter/MetricConverter.cs | 2,395 | C# |
namespace JetBrains.RunAs.Tests
{
using System.Collections;
using System.Collections.Generic;
using Moq;
using Shouldly;
using Xunit;
public class RunAsConfigurationFactoryTest
{
[Theory]
[ClassData(typeof(TestData))]
internal void ShouldCreateConfiguration(
string[] args,
bool success,
string userName,
string password,
IEnumerable<string> runAsArguments,
IEnumerable<string> commandArguments)
{
// Given
var environment = new Mock<IEnvironment>();
environment.SetupGet(i => i.Args).Returns(args);
var configurationFactory = new ConfigurationFactory(environment.Object);
Configuration configuration = null;
ToolException exception = null;
// When
try
{
configuration = configurationFactory.Create();
}
catch (ToolException ex)
{
exception = ex;
}
// Then
if (success)
{
configuration.ShouldNotBeNull();
configuration.UserName.ShouldBe(userName);
configuration.Password.ShouldBe(password);
configuration.RunAsArguments.ShouldBe(runAsArguments);
configuration.CommandArguments.ShouldBe(commandArguments);
}
else
{
exception.ShouldNotBeNull();
}
}
private class TestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
// run
yield return new object[] { new [] {"-u:username", "-p:password"}, true, "username", "password", new string[] {}, new string[] {} };
yield return new object[] { new [] {"-il:high", "-u:username", "-p:password", "build"}, true, "username", "password", new[] {"-il:high"}, new[] {"build"} };
yield return new object[] { new [] {"-il:high", "-u:username", "-p:password", "-c:args.txt", "build"}, true, "username", "password", new[] {"-il:high", "-c:args.txt"}, new[] {"build"} };
yield return new object[] { new [] {"-il:high", "-p:password", "build"}, false, null, null, null, null };
yield return new object[] { new [] {"-il:high", "-u:username", "build"}, false, null, null, null, null };
yield return new object[] { new string[] {}, false, null, null, null, null };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}
| 38.371429 | 202 | 0.528295 | [
"Apache-2.0"
] | FDlucifer/runAs | JetBrains.dotnet-runas.Tests/RunAsConfigurationFactoryTest.cs | 2,686 | C# |
// Copyright (c) Yufei Huang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Xna.Framework.Graphics;
public static class Xna4Extensions
{
private static readonly Stack<RenderTarget2D> _renderTargetStack = new();
public static void PushRenderTarget(this GraphicsDevice graphicsDevice, RenderTarget2D renderTarget)
{
var renderTargets = graphicsDevice.GetRenderTargets();
var current = renderTargets.Length > 0 ? (RenderTarget2D)renderTargets[0].RenderTarget : null;
_renderTargetStack.Push(current);
graphicsDevice.SetRenderTarget(renderTarget);
}
public static void PopRenderTarget(this GraphicsDevice graphicsDevice)
{
if (_renderTargetStack.Count > 0)
{
var renderTarget = _renderTargetStack.Pop();
graphicsDevice.SetRenderTarget(renderTarget);
}
}
public static void SetRenderState(
this GraphicsDevice graphicsDevice,
BlendState blendState = null,
DepthStencilState depthStencilState = null,
RasterizerState rasterizerState = null)
{
graphicsDevice.BlendState = blendState ?? BlendState.NonPremultiplied;
graphicsDevice.DepthStencilState = depthStencilState ?? DepthStencilState.Default;
graphicsDevice.RasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise;
}
}
| 38.5 | 104 | 0.726589 | [
"MIT"
] | yufeih/isles | src/isles/Graphics/Xna4Extensions.cs | 1,463 | C# |
using System.Runtime.InteropServices;
using Titan.Windows.D3D11;
using Titan.Windows.DXGI;
namespace Titan.Windows.Win32
{
public static unsafe class GDI32
{
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TextOutW(HDC hdc, int x, int y, char* lpwString, int c);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TextOutA(HDC hdc, int x, int y, byte* lpString, int c);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int SetTextColor(
[In] HDC hdc,
[In] COLORREF color
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int SetBkMode(
[In] HDC hdc,
[In] BackgroundMode mode
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern COLORREF SetBkColor(
[In] HDC hdc,
[In] COLORREF color
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BeginPath(
[In] HDC hdc
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EndPath(
[In] HDC hdc
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern HFONT CreateFontW(
[In] int cHeight,
[In] int cWidth,
[In] int cEscapement,
[In] int cOrientation,
[In] int cWeight,
[In] int bItalic,
[In] int bUnderline,
[In] int bStrikeOut,
[In] int iCharSet,
[In] int iOutPrecision,
[In] int iClipPrecision,
[In] int iQuality,
[In] int iPitchAndFamily,
[In] char* pszFaceName
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern HGDIOBJ SelectObject(
[In] HDC hdc,
[In] HGDIOBJ h
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject(
[In] HGDIOBJ ho
);
[DllImport("user32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int FillRect(
[In] HDC hDC,
[In] RECT* lprc,
[In] HBRUSH hbr
);
[DllImport("gdi32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern HBRUSH CreateSolidBrush(
[In] COLORREF color
);
}
}
| 35.26087 | 97 | 0.607275 | [
"MIT"
] | Golle/Titan | src/Titan.Windows/Win32/GDI32.cs | 3,244 | C# |
namespace Nutanix.Powershell.Models
{
using static Microsoft.Rest.ClientRuntime.Extensions;
/// <summary>Task entity list.</summary>
public partial class TaskListIntentResponse
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Carbon.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Carbon.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Carbon.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Carbon.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Carbon.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Carbon.Json.JsonNode"/> into an instance of Nutanix.Powershell.Models.ITaskListIntentResponse.
/// </summary>
/// <param name="node">a <see cref="Carbon.Json.JsonNode" /> to deserialize from.</param>
/// <returns>an instance of Nutanix.Powershell.Models.ITaskListIntentResponse.</returns>
public static Nutanix.Powershell.Models.ITaskListIntentResponse FromJson(Carbon.Json.JsonNode node)
{
return node is Carbon.Json.JsonObject json ? new TaskListIntentResponse(json) : null;
}
/// <summary>
/// Deserializes a Carbon.Json.JsonObject into a new instance of <see cref="TaskListIntentResponse" />.
/// </summary>
/// <param name="json">A Carbon.Json.JsonObject instance to deserialize from.</param>
internal TaskListIntentResponse(Carbon.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
_apiVersion = If( json?.PropertyT<Carbon.Json.JsonString>("api_version"), out var __jsonApiVersion) ? (string)__jsonApiVersion : (string)ApiVersion;
_entities = If( json?.PropertyT<Carbon.Json.JsonArray>("entities"), out var __jsonEntities) ? If( __jsonEntities, out var __v) ? new System.Func<Nutanix.Powershell.Models.ITask[]>(()=> System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select( __v, (__u)=> Nutanix.Powershell.Models.Task.FromJson(__u) ) ) )() : null : Entities;
_metadata = If( json?.PropertyT<Carbon.Json.JsonObject>("metadata"), out var __jsonMetadata) ? Nutanix.Powershell.Models.TaskListMetadataOutput.FromJson(__jsonMetadata) : Metadata;
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="TaskListIntentResponse" /> into a <see cref="Carbon.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Carbon.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Rest.ClientRuntime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="TaskListIntentResponse" /> as a <see cref="Carbon.Json.JsonNode" />.
/// </returns>
public Carbon.Json.JsonNode ToJson(Carbon.Json.JsonObject container, Microsoft.Rest.ClientRuntime.SerializationMode serializationMode)
{
container = container ?? new Carbon.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != ApiVersion ? (Carbon.Json.JsonNode) new Carbon.Json.JsonString(ApiVersion) : null, "api_version" ,container.Add );
if (null != Entities)
{
var __w = new Carbon.Json.XNodeArray();
foreach( var __x in Entities )
{
AddIf(__x?.ToJson(null) ,__w.Add);
}
container.Add("entities",__w);
}
AddIf( null != Metadata ? (Carbon.Json.JsonNode) Metadata.ToJson(null) : null, "metadata" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 63.4 | 344 | 0.649054 | [
"MIT"
] | gmlp/PowerShell | private/api/Nutanix/Powershell/Models/TaskListIntentResponse.json.cs | 6,340 | C# |
namespace MiCake.DDD.CQS.Tests.Fakes
{
class BCommand : ICommandModel
{
}
}
| 12.714286 | 37 | 0.640449 | [
"MIT"
] | MiCake/MiCake | src/tests/MiCake.DDD.CQS.Tests/Fakes/BCommand.cs | 91 | C# |
namespace StorytellerSpecs.Fixtures.SqlServer.App
{
public class TraceMessage
{
public string Name { get; set; }
}
}
| 17.25 | 50 | 0.652174 | [
"MIT"
] | CodingGorilla/jasper | src/StorytellerSpecs/Fixtures/SqlServer/App/TraceMessage.cs | 140 | C# |
namespace mml2vgmIDE
{
partial class FrmPartCounter
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージド リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle21 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle9 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle10 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle11 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle12 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle13 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle14 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle15 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle16 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle17 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle18 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle19 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle20 = new System.Windows.Forms.DataGridViewCellStyle();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmPartCounter));
this.dgvPartCounter = new System.Windows.Forms.DataGridView();
this.cmsMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.testToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timer = new System.Windows.Forms.Timer(this.components);
this.ClmChipIndex = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmMute = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmSolo = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmPush = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmKBDAssign = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmChipNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmPartNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmPart = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmMIDIch = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmChip = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmCounter = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmLoopCounter = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmInstrument = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmEnvelope = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmVolume = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmExpression = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmVelocity = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmPan = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmNote = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmGateTime = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmLength = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmEnvSw = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmLfoSw = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmLfo = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmDetune = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmKeyShift = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ClmMeter = new System.Windows.Forms.DataGridViewImageColumn();
this.ClmSpacer = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dgvPartCounter)).BeginInit();
this.cmsMenu.SuspendLayout();
this.SuspendLayout();
//
// dgvPartCounter
//
this.dgvPartCounter.AllowUserToAddRows = false;
this.dgvPartCounter.AllowUserToDeleteRows = false;
this.dgvPartCounter.AllowUserToOrderColumns = true;
this.dgvPartCounter.AllowUserToResizeRows = false;
this.dgvPartCounter.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(80)))), ((int)(((byte)(80)))), ((int)(((byte)(160)))));
dataGridViewCellStyle1.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(100)))), ((int)(((byte)(180)))));
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.White;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvPartCounter.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgvPartCounter.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dgvPartCounter.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ClmChipIndex,
this.ClmMute,
this.ClmSolo,
this.ClmPush,
this.ClmKBDAssign,
this.ClmChipNumber,
this.ClmPartNumber,
this.ClmPart,
this.ClmMIDIch,
this.ClmChip,
this.ClmCounter,
this.ClmLoopCounter,
this.ClmInstrument,
this.ClmEnvelope,
this.ClmVolume,
this.ClmExpression,
this.ClmVelocity,
this.ClmPan,
this.ClmNote,
this.ClmGateTime,
this.ClmLength,
this.ClmEnvSw,
this.ClmLfoSw,
this.ClmLfo,
this.ClmDetune,
this.ClmKeyShift,
this.ClmMeter,
this.ClmSpacer});
dataGridViewCellStyle21.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle21.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle21.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
dataGridViewCellStyle21.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle21.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(100)))), ((int)(((byte)(180)))));
dataGridViewCellStyle21.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle21.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvPartCounter.DefaultCellStyle = dataGridViewCellStyle21;
this.dgvPartCounter.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgvPartCounter.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
this.dgvPartCounter.EnableHeadersVisualStyles = false;
this.dgvPartCounter.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(100)))), ((int)(((byte)(180)))));
this.dgvPartCounter.Location = new System.Drawing.Point(0, 0);
this.dgvPartCounter.Name = "dgvPartCounter";
this.dgvPartCounter.ReadOnly = true;
this.dgvPartCounter.RowHeadersVisible = false;
this.dgvPartCounter.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dgvPartCounter.RowTemplate.Height = 21;
this.dgvPartCounter.Size = new System.Drawing.Size(1088, 259);
this.dgvPartCounter.TabIndex = 0;
this.dgvPartCounter.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvPartCounter_CellClick);
this.dgvPartCounter.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.DgvPartCounter_CellMouseClick);
//
// cmsMenu
//
this.cmsMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.testToolStripMenuItem});
this.cmsMenu.Name = "cmsMenu";
this.cmsMenu.Size = new System.Drawing.Size(94, 26);
this.cmsMenu.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.CmsMenu_PreviewKeyDown);
//
// testToolStripMenuItem
//
this.testToolStripMenuItem.Name = "testToolStripMenuItem";
this.testToolStripMenuItem.Size = new System.Drawing.Size(93, 22);
this.testToolStripMenuItem.Text = "test";
//
// timer
//
this.timer.Interval = 10;
this.timer.Tick += new System.EventHandler(this.Timer_Tick);
//
// ClmChipIndex
//
this.ClmChipIndex.HeaderText = "ChipIndex";
this.ClmChipIndex.Name = "ClmChipIndex";
this.ClmChipIndex.ReadOnly = true;
//
// ClmMute
//
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.ClmMute.DefaultCellStyle = dataGridViewCellStyle2;
this.ClmMute.HeaderText = "M";
this.ClmMute.Name = "ClmMute";
this.ClmMute.ReadOnly = true;
this.ClmMute.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ClmSolo
//
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.ClmSolo.DefaultCellStyle = dataGridViewCellStyle3;
this.ClmSolo.HeaderText = "S";
this.ClmSolo.Name = "ClmSolo";
this.ClmSolo.ReadOnly = true;
this.ClmSolo.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ClmPush
//
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.ClmPush.DefaultCellStyle = dataGridViewCellStyle4;
this.ClmPush.HeaderText = "P";
this.ClmPush.Name = "ClmPush";
this.ClmPush.ReadOnly = true;
//
// ClmKBDAssign
//
dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.ClmKBDAssign.DefaultCellStyle = dataGridViewCellStyle5;
this.ClmKBDAssign.HeaderText = "KBD";
this.ClmKBDAssign.Name = "ClmKBDAssign";
this.ClmKBDAssign.ReadOnly = true;
this.ClmKBDAssign.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ClmChipNumber
//
this.ClmChipNumber.HeaderText = "ChipNumber";
this.ClmChipNumber.Name = "ClmChipNumber";
this.ClmChipNumber.ReadOnly = true;
//
// ClmPartNumber
//
this.ClmPartNumber.HeaderText = "PartNumber";
this.ClmPartNumber.Name = "ClmPartNumber";
this.ClmPartNumber.ReadOnly = true;
//
// ClmPart
//
dataGridViewCellStyle6.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmPart.DefaultCellStyle = dataGridViewCellStyle6;
this.ClmPart.HeaderText = "Part";
this.ClmPart.Name = "ClmPart";
this.ClmPart.ReadOnly = true;
this.ClmPart.Width = 50;
//
// ClmMIDIch
//
dataGridViewCellStyle7.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmMIDIch.DefaultCellStyle = dataGridViewCellStyle7;
this.ClmMIDIch.HeaderText = "MIDI Ch";
this.ClmMIDIch.Name = "ClmMIDIch";
this.ClmMIDIch.ReadOnly = true;
this.ClmMIDIch.Width = 80;
//
// ClmChip
//
dataGridViewCellStyle8.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmChip.DefaultCellStyle = dataGridViewCellStyle8;
this.ClmChip.HeaderText = "Chip";
this.ClmChip.Name = "ClmChip";
this.ClmChip.ReadOnly = true;
//
// ClmCounter
//
dataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle9.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmCounter.DefaultCellStyle = dataGridViewCellStyle9;
this.ClmCounter.HeaderText = "Counter";
this.ClmCounter.Name = "ClmCounter";
this.ClmCounter.ReadOnly = true;
//
// ClmLoopCounter
//
dataGridViewCellStyle10.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle10.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmLoopCounter.DefaultCellStyle = dataGridViewCellStyle10;
this.ClmLoopCounter.HeaderText = "LoopCounter";
this.ClmLoopCounter.Name = "ClmLoopCounter";
this.ClmLoopCounter.ReadOnly = true;
//
// ClmInstrument
//
dataGridViewCellStyle11.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle11.Font = new System.Drawing.Font("Consolas", 9F);
this.ClmInstrument.DefaultCellStyle = dataGridViewCellStyle11;
this.ClmInstrument.HeaderText = "Instrument";
this.ClmInstrument.Name = "ClmInstrument";
this.ClmInstrument.ReadOnly = true;
//
// ClmEnvelope
//
dataGridViewCellStyle12.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle12.Font = new System.Drawing.Font("Consolas", 9F);
this.ClmEnvelope.DefaultCellStyle = dataGridViewCellStyle12;
this.ClmEnvelope.HeaderText = "Envelope";
this.ClmEnvelope.Name = "ClmEnvelope";
this.ClmEnvelope.ReadOnly = true;
//
// ClmVolume
//
dataGridViewCellStyle13.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle13.Font = new System.Drawing.Font("Consolas", 9F);
this.ClmVolume.DefaultCellStyle = dataGridViewCellStyle13;
this.ClmVolume.HeaderText = "Volume";
this.ClmVolume.Name = "ClmVolume";
this.ClmVolume.ReadOnly = true;
//
// ClmExpression
//
dataGridViewCellStyle14.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle14.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmExpression.DefaultCellStyle = dataGridViewCellStyle14;
this.ClmExpression.HeaderText = "Expression";
this.ClmExpression.Name = "ClmExpression";
this.ClmExpression.ReadOnly = true;
//
// ClmVelocity
//
dataGridViewCellStyle15.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle15.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmVelocity.DefaultCellStyle = dataGridViewCellStyle15;
this.ClmVelocity.HeaderText = "Velocity";
this.ClmVelocity.Name = "ClmVelocity";
this.ClmVelocity.ReadOnly = true;
//
// ClmPan
//
this.ClmPan.HeaderText = "Pan";
this.ClmPan.Name = "ClmPan";
this.ClmPan.ReadOnly = true;
//
// ClmNote
//
dataGridViewCellStyle16.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle16.Font = new System.Drawing.Font("Consolas", 9F);
this.ClmNote.DefaultCellStyle = dataGridViewCellStyle16;
this.ClmNote.HeaderText = "Note";
this.ClmNote.Name = "ClmNote";
this.ClmNote.ReadOnly = true;
//
// ClmGateTime
//
dataGridViewCellStyle17.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle17.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ClmGateTime.DefaultCellStyle = dataGridViewCellStyle17;
this.ClmGateTime.HeaderText = "GateTime";
this.ClmGateTime.Name = "ClmGateTime";
this.ClmGateTime.ReadOnly = true;
//
// ClmLength
//
dataGridViewCellStyle18.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle18.Font = new System.Drawing.Font("Consolas", 9F);
this.ClmLength.DefaultCellStyle = dataGridViewCellStyle18;
this.ClmLength.HeaderText = "Length(#)";
this.ClmLength.Name = "ClmLength";
this.ClmLength.ReadOnly = true;
//
// ClmEnvSw
//
this.ClmEnvSw.HeaderText = "Env.Sw.";
this.ClmEnvSw.Name = "ClmEnvSw";
this.ClmEnvSw.ReadOnly = true;
//
// ClmLfoSw
//
this.ClmLfoSw.HeaderText = "LFO Sw.";
this.ClmLfoSw.Name = "ClmLfoSw";
this.ClmLfoSw.ReadOnly = true;
//
// ClmLfo
//
this.ClmLfo.HeaderText = "LFO";
this.ClmLfo.Name = "ClmLfo";
this.ClmLfo.ReadOnly = true;
//
// ClmDetune
//
dataGridViewCellStyle19.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
this.ClmDetune.DefaultCellStyle = dataGridViewCellStyle19;
this.ClmDetune.HeaderText = "Detune";
this.ClmDetune.Name = "ClmDetune";
this.ClmDetune.ReadOnly = true;
//
// ClmKeyShift
//
dataGridViewCellStyle20.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
this.ClmKeyShift.DefaultCellStyle = dataGridViewCellStyle20;
this.ClmKeyShift.HeaderText = "Key shift";
this.ClmKeyShift.Name = "ClmKeyShift";
this.ClmKeyShift.ReadOnly = true;
//
// ClmMeter
//
this.ClmMeter.HeaderText = "KeyOn";
this.ClmMeter.Name = "ClmMeter";
this.ClmMeter.ReadOnly = true;
//
// ClmSpacer
//
this.ClmSpacer.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ClmSpacer.HeaderText = "";
this.ClmSpacer.Name = "ClmSpacer";
this.ClmSpacer.ReadOnly = true;
this.ClmSpacer.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// FrmPartCounter
//
this.AllowDrop = true;
this.ClientSize = new System.Drawing.Size(1088, 259);
this.Controls.Add(this.dgvPartCounter);
this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FrmPartCounter";
this.Text = "Part counter";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmPartCounter_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FrmPartCounter_FormClosed);
this.DragOver += new System.Windows.Forms.DragEventHandler(this.FrmPartCounter_DragOver);
((System.ComponentModel.ISupportInitialize)(this.dgvPartCounter)).EndInit();
this.cmsMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dgvPartCounter;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.ContextMenuStrip cmsMenu;
private System.Windows.Forms.ToolStripMenuItem testToolStripMenuItem;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmChipIndex;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmMute;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmSolo;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmPush;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmKBDAssign;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmChipNumber;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmPartNumber;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmPart;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmMIDIch;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmChip;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmCounter;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmLoopCounter;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmInstrument;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmEnvelope;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmVolume;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmExpression;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmVelocity;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmPan;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmNote;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmGateTime;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmLength;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmEnvSw;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmLfoSw;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmLfo;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmDetune;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmKeyShift;
private System.Windows.Forms.DataGridViewImageColumn ClmMeter;
private System.Windows.Forms.DataGridViewTextBoxColumn ClmSpacer;
}
}
| 58.765351 | 190 | 0.659887 | [
"MIT"
] | kuma4649/mml2vgm | mml2vgm/mml2vgmIDE/form/FrmPartCounter.Designer.cs | 27,079 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.PowerFx.Core.Texl.Intellisense{
internal interface ISuggestionHandler
{
/// <summary>
/// Adds suggestions as appropriate to the internal Suggestions and SubstringSuggestions lists of intellisenseData.
/// Returns true if suggestions are found and false otherwise.
/// </summary>
bool Run(IntellisenseData.IntellisenseData intellisenseData);
}
}
| 35.357143 | 123 | 0.711111 | [
"MIT"
] | ivanradicek/Power-Fx | src/libraries/Microsoft.PowerFx.Core/Texl/Intellisense/SuggestionHandlers/ISuggestionHandler.cs | 497 | 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;
struct Pad
{
#pragma warning disable 0414
public double d1;
public double d2;
public double d3;
public double d4;
public double d5;
public double d6;
public double d7;
public double d8;
public double d9;
public double d10;
public double d11;
public double d12;
public double d13;
public double d14;
public double d15;
public double d16;
public double d17;
public double d18;
public double d19;
public double d20;
public double d21;
public double d22;
public double d23;
public double d24;
public double d25;
public double d26;
public double d27;
public double d28;
#pragma warning restore 0414
}
struct S
{
#pragma warning disable 0414
public String str2;
#pragma warning restore 0414
public String str;
public Pad pad;
public S(String s)
{
str = s;
str2 = s + str;
pad.d1 =
pad.d2 =
pad.d3 =
pad.d4 =
pad.d5 =
pad.d6 =
pad.d7 =
pad.d8 =
pad.d9 =
pad.d10 =
pad.d11 =
pad.d12 =
pad.d13 =
pad.d14 =
pad.d15 =
pad.d16 =
pad.d17 =
pad.d18 =
pad.d19 =
pad.d20 =
pad.d21 =
pad.d22 =
pad.d23 =
pad.d24 =
pad.d25 =
pad.d26 =
pad.d27 =
pad.d28 = 3.3;
}
}
class Test
{
public static void c(S s1, S s2, S s3)
{
Console.WriteLine(s1.str + s2.str + s3.str);
}
public static int Main()
{
S sM = new S("test");
S sM2 = new S("test2");
S sM3 = new S("test3");
c(sM, sM2, sM3);
return 100;
}
}
| 18.811881 | 101 | 0.537368 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/JIT/jit64/gc/misc/struct4_4.cs | 1,900 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InchesToCentimeters
{
class Program
{
static void Main(string[] args)
{
Console.Write("The number in inches is: ");
var inches = double.Parse(Console.ReadLine());
var centimeters = inches * 2.54;
Console.Write("The number in centimeters is: ");
Console.WriteLine(centimeters);
}
}
}
| 24.142857 | 60 | 0.613412 | [
"MIT"
] | pkemalov/ProgrammingBasics | SimpleCalculations/InchesToCentimeters/Program.cs | 509 | 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 BroControls.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;
}
}
}
}
| 35.16129 | 151 | 0.568807 | [
"MIT"
] | bombomby/brocompiler | BroControls/Properties/Settings.Designer.cs | 1,092 | C# |
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ExchangeSharp
{
public sealed partial class ExchangeBitstampAPI : ExchangeAPI
{
public override string BaseUrl { get; set; } = "https://www.bitstamp.net/api/v2";
public override string BaseUrlWebSocket { get; set; } = "wss://ws.bitstamp.net";
/// <summary>
/// Bitstamp private API requires a customer id. Internally this is secured in the PassPhrase property.
/// </summary>
public string CustomerId
{
get { return Passphrase.ToUnsecureString(); }
set { Passphrase = value.ToSecureString(); }
}
/// <summary>
/// In order to use private functions of the API, you must set CustomerId by calling constructor with parameter,
/// or setting it later in the ExchangeBitstampAPI object.
/// </summary>
private ExchangeBitstampAPI()
{
RequestContentType = "application/x-www-form-urlencoded";
NonceStyle = NonceStyle.UnixMilliseconds;
MarketSymbolIsUppercase = false;
MarketSymbolSeparator = string.Empty;
}
/// <summary>
/// In order to use private functions of the API, you must set CustomerId by calling this constructor with parameter,
/// or setting it later in the ExchangeBitstampAPI object.
/// </summary>
/// <param name="customerId">Customer Id can be found by the link "https://www.bitstamp.net/account/balance/"</param>
public ExchangeBitstampAPI(string customerId) : this()
{
CustomerId = customerId;
}
protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object> payload)
{
if (CanMakeAuthenticatedRequest(payload))
{
if (string.IsNullOrWhiteSpace(CustomerId))
{
throw new APIException("Customer ID is not set for Bitstamp");
}
// messageToSign = nonce + customer_id + api_key
string apiKey = PublicApiKey.ToUnsecureString();
string messageToSign = payload["nonce"].ToStringInvariant() + CustomerId + apiKey;
string signature = CryptoUtility.SHA256Sign(messageToSign, PrivateApiKey.ToUnsecureString()).ToUpperInvariant();
payload["signature"] = signature;
payload["key"] = apiKey;
await CryptoUtility.WritePayloadFormToRequestAsync(request, payload);
}
}
private async Task<JToken> MakeBitstampRequestAsync(string subUrl)
{
JToken token = await MakeJsonRequestAsync<JToken>(subUrl);
if (!(token is JArray) && token["error"] != null)
{
throw new APIException(token["error"].ToStringInvariant());
}
return token;
}
protected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync()
{
List<string> symbols = new List<string>();
foreach (JToken token in (await MakeBitstampRequestAsync("/trading-pairs-info")))
{
symbols.Add(token["url_symbol"].ToStringInvariant());
}
return symbols;
}
protected internal override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync()
{ // {"base_decimals": 8, "minimum_order": "5.0 USD", "name": "LTC/USD", "counter_decimals": 2, "trading": "Enabled", "url_symbol": "ltcusd", "description": "Litecoin / U.S. dollar"}
List<ExchangeMarket> symbols = new List<ExchangeMarket>();
foreach (JToken token in (await MakeBitstampRequestAsync("/trading-pairs-info")))
{
var split = token["name"].ToStringInvariant().Split('/');
var baseNumDecimals = token["base_decimals"].Value<byte>();
var baseDecimals = (decimal)Math.Pow(0.1, baseNumDecimals);
var counterNumDecimals = token["counter_decimals"].Value<byte>();
var counterDecimals = (decimal)Math.Pow(0.1, counterNumDecimals);
var minOrderString = token["minimum_order"].ToStringInvariant();
symbols.Add(new ExchangeMarket()
{
MarketSymbol = token["url_symbol"].ToStringInvariant(),
BaseCurrency = split[0],
QuoteCurrency = split[1],
MinTradeSize = baseDecimals, // will likely get overriden by MinTradeSizeInQuoteCurrency
QuantityStepSize = baseDecimals,
MinTradeSizeInQuoteCurrency = minOrderString.Split(' ')[0].ConvertInvariant<decimal>(),
MinPrice = counterDecimals,
PriceStepSize = counterDecimals,
IsActive = token["trading"].ToStringLowerInvariant() == "enabled",
});
}
return symbols;
}
protected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol)
{
// {"high": "0.10948945", "last": "0.10121817", "timestamp": "1513387486", "bid": "0.10112165", "vwap": "0.09958913", "volume": "9954.37332614", "low": "0.09100000", "ask": "0.10198408", "open": "0.10250028"}
JToken token = await MakeBitstampRequestAsync("/ticker/" + marketSymbol);
return await this.ParseTickerAsync(token, marketSymbol, "ask", "bid", "last", "volume", null, "timestamp", TimestampType.UnixSeconds);
}
protected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100)
{
JToken token = await MakeBitstampRequestAsync("/order_book/" + marketSymbol);
return ExchangeAPIExtensions.ParseOrderBookFromJTokenArrays(token, maxCount: maxCount);
}
protected override async Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string marketSymbol, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)
{
// [{"date": "1513387997", "tid": "33734815", "price": "0.01724547", "type": "1", "amount": "5.56481714"}]
JToken token = await MakeBitstampRequestAsync("/transactions/" + marketSymbol);
List<ExchangeTrade> trades = new List<ExchangeTrade>();
foreach (JToken trade in token)
{
trades.Add(trade.ParseTrade("amount", "price", "type", "date", TimestampType.UnixSeconds, "tid", "0"));
}
callback(trades);
}
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync()
{
string url = "/balance/";
var payload = await GetNoncePayloadAsync();
var responseObject = await MakeJsonRequestAsync<JObject>(url, null, payload, "POST");
return ExtractDictionary(responseObject, "balance");
}
protected override async Task<Dictionary<string, decimal>> OnGetFeesAsync()
{
string url = "/balance/";
var payload = await GetNoncePayloadAsync();
var responseObject = await MakeJsonRequestAsync<JObject>(url, null, payload, "POST");
return ExtractDictionary(responseObject, "fee");
}
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync()
{
string url = "/balance/";
var payload = await GetNoncePayloadAsync();
var responseObject = await MakeJsonRequestAsync<JObject>(url, null, payload, "POST");
return ExtractDictionary(responseObject, "available");
}
private static Dictionary<string, decimal> ExtractDictionary(JObject responseObject, string key)
{
var result = new Dictionary<string, decimal>();
var suffix = $"_{key}";
foreach (var property in responseObject)
{
if (property.Key.Contains(suffix))
{
decimal value = property.Value.ConvertInvariant<decimal>();
if (value == 0)
{
continue;
}
result.Add(property.Key.Replace(suffix, "").Trim(), value);
}
}
return result;
}
protected override async Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order)
{
string action = order.IsBuy ? "buy" : "sell";
string market = order.OrderType == OrderType.Market ? "/market" : "";
string url = $"/{action}{market}/{order.MarketSymbol}/";
Dictionary<string, object> payload = await GetNoncePayloadAsync();
if (order.OrderType != OrderType.Market)
{
payload["price"] = order.Price.ToStringInvariant();
}
payload["amount"] = order.RoundAmount().ToStringInvariant();
order.ExtraParameters.CopyTo(payload);
JObject responseObject = await MakeJsonRequestAsync<JObject>(url, null, payload, "POST");
return new ExchangeOrderResult
{
OrderDate = CryptoUtility.UtcNow,
OrderId = responseObject["id"].ToStringInvariant(),
IsBuy = order.IsBuy,
MarketSymbol = order.MarketSymbol
};
}
protected override async Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string marketSymbol = null)
{
//{
// "status": "Finished",
// "id": 1022694747,
// "transactions": [
// {
// "fee": "0.000002",
// "bch": "0.00882714",
// "price": "0.12120000",
// "datetime": "2018-02-24 14:15:29.133824",
// "btc": "0.0010698493680000",
// "tid": 56293144,
// "type": 2
// }]
//}
if (string.IsNullOrWhiteSpace(orderId))
{
return null;
}
string url = "/order_status/";
Dictionary<string, object> payload = await GetNoncePayloadAsync();
payload["id"] = orderId;
JObject result = await MakeJsonRequestAsync<JObject>(url, null, payload, "POST");
// status can be 'In Queue', 'Open' or 'Finished'
JArray transactions = result["transactions"] as JArray;
// empty transaction array means that order is InQueue or Open and AmountFilled == 0
// return empty order in this case. no any additional info available at this point
if (!transactions.Any()) { return new ExchangeOrderResult() { OrderId = orderId }; }
JObject first = transactions.First() as JObject;
List<string> excludeStrings = new List<string>() { "tid", "price", "fee", "datetime", "type", "btc", "usd", "eur" };
string quoteCurrency;
string baseCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;
if (string.IsNullOrWhiteSpace(baseCurrency))
{
// the only 2 cases are BTC-USD and BTC-EUR
baseCurrency = "btc";
excludeStrings.RemoveAll(s => s.Equals("usd") || s.Equals("eur"));
quoteCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;
}
else
{
excludeStrings.RemoveAll(s => s.Equals("usd") || s.Equals("eur") || s.Equals("btc"));
excludeStrings.Add(baseCurrency);
quoteCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;
}
string _symbol = $"{baseCurrency}-{quoteCurrency}";
decimal amountFilled = 0, spentQuoteCurrency = 0, price = 0;
foreach (var t in transactions)
{
int type = t["type"].ConvertInvariant<int>();
if (type != 2) { continue; }
spentQuoteCurrency += t[quoteCurrency].ConvertInvariant<decimal>();
amountFilled += t[baseCurrency].ConvertInvariant<decimal>();
//set price only one time
if (price == 0)
{
price = t["price"].ConvertInvariant<decimal>();
}
}
// No way to know if order IsBuy, Amount, OrderDate
return new ExchangeOrderResult()
{
AmountFilled = amountFilled,
MarketSymbol = _symbol,
AveragePrice = spentQuoteCurrency / amountFilled,
Price = price,
};
}
protected override async Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string marketSymbol = null)
{
List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();
// TODO: Bitstamp bug: bad request if url contains symbol, so temporarily using url for all symbols
// string url = string.IsNullOrWhiteSpace(symbol) ? "/open_orders/all/" : "/open_orders/" + symbol;
string url = "/open_orders/all/";
JArray result = await MakeJsonRequestAsync<JArray>(url, null, await GetNoncePayloadAsync(), "POST");
foreach (JToken token in result)
{
//This request doesn't give info about amount filled, use GetOrderDetails(orderId)
string tokenSymbol = token["currency_pair"].ToStringLowerInvariant().Replace("/", "");
if (!string.IsNullOrWhiteSpace(tokenSymbol) && !string.IsNullOrWhiteSpace(marketSymbol) && !tokenSymbol.Equals(marketSymbol, StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
orders.Add(new ExchangeOrderResult()
{
OrderId = token["id"].ToStringInvariant(),
OrderDate = token["datetime"].ToDateTimeInvariant(),
IsBuy = token["type"].ConvertInvariant<int>() == 0,
Price = token["price"].ConvertInvariant<decimal>(),
Amount = token["amount"].ConvertInvariant<decimal>(),
MarketSymbol = tokenSymbol ?? marketSymbol
});
}
return orders;
}
public class BitstampTransaction
{
public BitstampTransaction(string id, DateTime dateTime, int type, string symbol, decimal fees, string orderId, decimal quantity, decimal price, bool isBuy)
{
Id = id;
DateTime = dateTime;
Type = type;
Symbol = symbol;
Fees = fees;
OrderId = orderId;
Quantity = quantity;
Price = price;
IsBuy = isBuy;
}
public string Id { get; }
public DateTime DateTime { get; }
public int Type { get; } // Transaction type: 0 - deposit; 1 - withdrawal; 2 - market trade; 14 - sub account transfer.
public string Symbol { get; }
public decimal Fees { get; }
public string OrderId { get; }
public decimal Quantity { get; }
public decimal Price { get; }
public bool IsBuy { get; }
}
public async Task<IEnumerable<BitstampTransaction>> GetUserTransactionsAsync(string marketSymbol = null, DateTime? afterDate = null)
{
await new SynchronizationContextRemover();
marketSymbol = NormalizeMarketSymbol(marketSymbol);
// TODO: Bitstamp bug: bad request if url contains symbol, so temporarily using url for all symbols
// string url = string.IsNullOrWhiteSpace(symbol) ? "/user_transactions/" : "/user_transactions/" + symbol;
string url = "/user_transactions/";
var payload = await GetNoncePayloadAsync();
payload["limit"] = 1000;
JToken result = await MakeJsonRequestAsync<JToken>(url, null, payload, "POST");
List<BitstampTransaction> transactions = new List<BitstampTransaction>();
foreach (var transaction in result as JArray)
{
int type = transaction["type"].ConvertInvariant<int>();
// only type 2 is order transaction type, so we discard all other transactions
if (type != 2) { continue; }
string tradingPair = ((JObject)transaction).Properties().FirstOrDefault(p =>
!p.Name.Equals("order_id", StringComparison.InvariantCultureIgnoreCase)
&& p.Name.Contains("_"))?.Name.Replace("_", "-");
tradingPair = NormalizeMarketSymbol(tradingPair);
if (!string.IsNullOrWhiteSpace(tradingPair) && !string.IsNullOrWhiteSpace(marketSymbol) && !tradingPair.Equals(marketSymbol))
{
continue;
}
var baseCurrency = tradingPair.Trim().Substring(tradingPair.Length - 3).ToLowerInvariant();
var marketCurrency = tradingPair.Trim().ToLowerInvariant().Replace(baseCurrency, "").Replace("-", "").Replace("_", "");
decimal amount = transaction[baseCurrency].ConvertInvariant<decimal>();
decimal signedQuantity = transaction[marketCurrency].ConvertInvariant<decimal>();
decimal quantity = Math.Abs(signedQuantity);
decimal price = Math.Abs(amount / signedQuantity);
bool isBuy = signedQuantity > 0;
var id = transaction["id"].ToStringInvariant();
var datetime = transaction["datetime"].ToDateTimeInvariant();
var fee = transaction["fee"].ConvertInvariant<decimal>();
var orderId = transaction["order_id"].ToStringInvariant();
var bitstampTransaction = new BitstampTransaction(id, datetime, type, tradingPair, fee, orderId, quantity, price, isBuy);
transactions.Add(bitstampTransaction);
}
return transactions;
}
protected override async Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string marketSymbol = null, DateTime? afterDate = null)
{
// TODO: Bitstamp bug: bad request if url contains symbol, so temporarily using url for all symbols
// string url = string.IsNullOrWhiteSpace(symbol) ? "/user_transactions/" : "/user_transactions/" + symbol;
string url = "/user_transactions/";
var payload = await GetNoncePayloadAsync();
payload["limit"] = 1000;
JToken result = await MakeJsonRequestAsync<JToken>(url, null, payload, "POST");
List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();
foreach (var transaction in result as JArray)
{
int type = transaction["type"].ConvertInvariant<int>();
// only type 2 is order transaction type, so we discard all other transactions
if (type != 2) { continue; }
string tradingPair = ((JObject)transaction).Properties().FirstOrDefault(p =>
!p.Name.Equals("order_id", StringComparison.InvariantCultureIgnoreCase)
&& p.Name.Contains("_"))?.Name.Replace("_", "-");
if (!string.IsNullOrWhiteSpace(tradingPair) && !string.IsNullOrWhiteSpace(marketSymbol) && !NormalizeMarketSymbol(tradingPair).Equals(marketSymbol))
{
continue;
}
var quoteCurrency = tradingPair.Trim().Substring(tradingPair.Length - 3).ToLowerInvariant();
var baseCurrency = tradingPair.Trim().ToLowerInvariant().Replace(quoteCurrency, "").Replace("-", "").Replace("_", "");
decimal resultBaseCurrency = transaction[baseCurrency].ConvertInvariant<decimal>();
ExchangeOrderResult order = new ExchangeOrderResult()
{
OrderId = transaction["order_id"].ToStringInvariant(),
IsBuy = resultBaseCurrency > 0,
Fees = transaction["fee"].ConvertInvariant<decimal>(),
FeesCurrency = quoteCurrency.ToStringUpperInvariant(),
MarketSymbol = NormalizeMarketSymbol(tradingPair),
OrderDate = transaction["datetime"].ToDateTimeInvariant(),
AmountFilled = Math.Abs(resultBaseCurrency),
AveragePrice = transaction[$"{baseCurrency}_{quoteCurrency}"].ConvertInvariant<decimal>()
};
orders.Add(order);
}
// at this point one transaction transformed into one order, we need to consolidate parts into order
// group by order id
var groupings = orders.GroupBy(o => o.OrderId);
List<ExchangeOrderResult> orders2 = new List<ExchangeOrderResult>();
foreach (var group in groupings)
{
decimal spentQuoteCurrency = group.Sum(o => o.AveragePrice * o.AmountFilled);
ExchangeOrderResult order = group.First();
order.AmountFilled = group.Sum(o => o.AmountFilled);
order.AveragePrice = spentQuoteCurrency / order.AmountFilled;
order.Price = order.AveragePrice;
orders2.Add(order);
}
return orders2;
}
protected override async Task OnCancelOrderAsync(string orderId, string marketSymbol = null)
{
if (string.IsNullOrWhiteSpace(orderId))
{
throw new APIException("OrderId is needed for canceling order");
}
Dictionary<string, object> payload = await GetNoncePayloadAsync();
payload["id"] = orderId;
await MakeJsonRequestAsync<JToken>("/cancel_order/", null, payload, "POST");
}
/// <summary>
/// Function to withdraw from Bitsamp exchange. At the moment only XRP is supported.
/// </summary>
/// <param name="withdrawalRequest"></param>
/// <returns></returns>
protected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)
{
string baseurl = null;
string url;
switch (withdrawalRequest.Currency)
{
case "BTC":
// use old API for Bitcoin withdraw
baseurl = "https://www.bitstamp.net/api/";
url = "/bitcoin_withdrawal/";
break;
default:
// this will work for some currencies and fail for others, caller must be aware of the supported currencies
url = "/" + withdrawalRequest.Currency.ToLowerInvariant() + "_withdrawal/";
break;
}
Dictionary<string, object> payload = await GetNoncePayloadAsync();
payload["address"] = withdrawalRequest.Address.ToStringInvariant();
payload["amount"] = withdrawalRequest.Amount.ToStringInvariant();
payload["destination_tag"] = withdrawalRequest.AddressTag.ToStringInvariant();
JObject responseObject = await MakeJsonRequestAsync<JObject>(url, baseurl, payload, "POST");
CheckJsonResponse(responseObject);
return new ExchangeWithdrawalResponse
{
Id = responseObject["id"].ToStringInvariant(),
Message = responseObject["message"].ToStringInvariant(),
Success = responseObject["success"].ConvertInvariant<bool>()
};
}
protected override async Task<IWebSocket> OnGetTradesWebSocketAsync(Func<KeyValuePair<string, ExchangeTrade>, Task> callback, params string[] marketSymbols)
{
if (marketSymbols == null || marketSymbols.Length == 0)
{
marketSymbols = (await GetMarketSymbolsAsync()).ToArray();
}
return await ConnectWebSocketAsync(null, messageCallback: async (_socket, msg) =>
{
JToken token = JToken.Parse(msg.ToStringFromUTF8());
if (token["event"].ToStringInvariant() == "bts:error")
{ // {{"event": "bts:error", "channel": "",
// "data": {"code": null, "message": "Bad subscription string." } }}
token = token["data"];
Logger.Info(token["code"].ToStringInvariant() + " "
+ token["message"].ToStringInvariant());
}
else if (token["event"].ToStringInvariant() == "trade")
{
//{{
// "data": {
// "microtimestamp": "1563418286809203",
// "amount": 0.141247,
// "buy_order_id": 3785916113,
// "sell_order_id": 3785915893,
// "amount_str": "0.14124700",
// "price_str": "9754.23",
// "timestamp": "1563418286",
// "price": 9754.23,
// "type": 0, // Trade type (0 - buy; 1 - sell).
// "id": 94160906
// },
// "event": "trade",
// "channel": "live_trades_btcusd"
//}}
string marketSymbol = token["channel"].ToStringInvariant().Split('_')[2];
var trade = token["data"].ParseTradeBitstamp(amountKey: "amount", priceKey: "price",
typeKey: "type", timestampKey: "microtimestamp",
TimestampType.UnixMicroeconds, idKey: "id",
typeKeyIsBuyValue: "0");
await callback(new KeyValuePair<string, ExchangeTrade>(marketSymbol, trade));
}
else if (token["event"].ToStringInvariant() == "bts:subscription_succeeded")
{ // {{ "event": "bts:subscription_succeeded",
//"channel": "live_trades_btcusd",
//"data": { } }}
}
}, connectCallback: async (_socket) =>
{
//{
// "event": "bts:subscribe",
// "data": {
// "channel": "[channel_name]"
// }
//}
foreach (var marketSymbol in marketSymbols)
{
await _socket.SendMessageAsync(new
{
@event = "bts:subscribe",
data = new { channel = $"live_trades_{marketSymbol}" }
});
}
});
}
}
public partial class ExchangeName { public const string Bitstamp = "Bitstamp"; }
}
| 47.979021 | 460 | 0.598674 | [
"MIT"
] | demironur/ExchangeSharp | src/ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs | 27,444 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Conventions;
using Microsoft.Data.Entity.SqlServer.Metadata;
using Xunit;
namespace Microsoft.Data.Entity.SqlServer.Tests.Metadata
{
public class SqlServerMetadataExtensionsTest
{
[Fact]
public void Can_get_and_set_column_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal("Name", property.SqlServer().Column);
Assert.Equal("Name", ((IProperty)property).SqlServer().Column);
property.Relational().Column = "Eman";
Assert.Equal("Name", property.Name);
Assert.Equal("Name", ((IProperty)property).Name);
Assert.Equal("Eman", property.Relational().Column);
Assert.Equal("Eman", ((IProperty)property).Relational().Column);
Assert.Equal("Eman", property.SqlServer().Column);
Assert.Equal("Eman", ((IProperty)property).SqlServer().Column);
property.SqlServer().Column = "MyNameIs";
Assert.Equal("Name", property.Name);
Assert.Equal("Name", ((IProperty)property).Name);
Assert.Equal("Eman", property.Relational().Column);
Assert.Equal("Eman", ((IProperty)property).Relational().Column);
Assert.Equal("MyNameIs", property.SqlServer().Column);
Assert.Equal("MyNameIs", ((IProperty)property).SqlServer().Column);
property.SqlServer().Column = null;
Assert.Equal("Name", property.Name);
Assert.Equal("Name", ((IProperty)property).Name);
Assert.Equal("Eman", property.Relational().Column);
Assert.Equal("Eman", ((IProperty)property).Relational().Column);
Assert.Equal("Eman", property.SqlServer().Column);
Assert.Equal("Eman", ((IProperty)property).SqlServer().Column);
}
[Fact]
public void Can_get_and_set_table_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var entityType = modelBuilder
.Entity<Customer>()
.Metadata;
Assert.Equal("Customer", entityType.SqlServer().Table);
Assert.Equal("Customer", ((IEntityType)entityType).SqlServer().Table);
entityType.Relational().Table = "Customizer";
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Customer", ((IEntityType)entityType).DisplayName());
Assert.Equal("Customizer", entityType.Relational().Table);
Assert.Equal("Customizer", ((IEntityType)entityType).Relational().Table);
Assert.Equal("Customizer", entityType.SqlServer().Table);
Assert.Equal("Customizer", ((IEntityType)entityType).SqlServer().Table);
entityType.SqlServer().Table = "Custardizer";
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Customer", ((IEntityType)entityType).DisplayName());
Assert.Equal("Customizer", entityType.Relational().Table);
Assert.Equal("Customizer", ((IEntityType)entityType).Relational().Table);
Assert.Equal("Custardizer", entityType.SqlServer().Table);
Assert.Equal("Custardizer", ((IEntityType)entityType).SqlServer().Table);
entityType.SqlServer().Table = null;
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Customer", ((IEntityType)entityType).DisplayName());
Assert.Equal("Customizer", entityType.Relational().Table);
Assert.Equal("Customizer", ((IEntityType)entityType).Relational().Table);
Assert.Equal("Customizer", entityType.SqlServer().Table);
Assert.Equal("Customizer", ((IEntityType)entityType).SqlServer().Table);
}
[Fact]
public void Can_get_and_set_schema_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var entityType = modelBuilder
.Entity<Customer>()
.Metadata;
Assert.Null(entityType.Relational().Schema);
Assert.Null(((IEntityType)entityType).Relational().Schema);
Assert.Null(entityType.SqlServer().Schema);
Assert.Null(((IEntityType)entityType).SqlServer().Schema);
entityType.Relational().Schema = "db0";
Assert.Equal("db0", entityType.Relational().Schema);
Assert.Equal("db0", ((IEntityType)entityType).Relational().Schema);
Assert.Equal("db0", entityType.SqlServer().Schema);
Assert.Equal("db0", ((IEntityType)entityType).SqlServer().Schema);
entityType.SqlServer().Schema = "dbOh";
Assert.Equal("db0", entityType.Relational().Schema);
Assert.Equal("db0", ((IEntityType)entityType).Relational().Schema);
Assert.Equal("dbOh", entityType.SqlServer().Schema);
Assert.Equal("dbOh", ((IEntityType)entityType).SqlServer().Schema);
entityType.SqlServer().Schema = null;
Assert.Equal("db0", entityType.Relational().Schema);
Assert.Equal("db0", ((IEntityType)entityType).Relational().Schema);
Assert.Equal("db0", entityType.SqlServer().Schema);
Assert.Equal("db0", ((IEntityType)entityType).SqlServer().Schema);
}
[Fact]
public void Can_get_and_set_column_type()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().ColumnType);
Assert.Null(((IProperty)property).Relational().ColumnType);
Assert.Null(property.SqlServer().ColumnType);
Assert.Null(((IProperty)property).SqlServer().ColumnType);
property.Relational().ColumnType = "nvarchar(max)";
Assert.Equal("nvarchar(max)", property.Relational().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).Relational().ColumnType);
Assert.Equal("nvarchar(max)", property.SqlServer().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).SqlServer().ColumnType);
property.SqlServer().ColumnType = "nvarchar(verstappen)";
Assert.Equal("nvarchar(max)", property.Relational().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).Relational().ColumnType);
Assert.Equal("nvarchar(verstappen)", property.SqlServer().ColumnType);
Assert.Equal("nvarchar(verstappen)", ((IProperty)property).SqlServer().ColumnType);
property.SqlServer().ColumnType = null;
Assert.Equal("nvarchar(max)", property.Relational().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).Relational().ColumnType);
Assert.Equal("nvarchar(max)", property.SqlServer().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).SqlServer().ColumnType);
}
[Fact]
public void Can_get_and_set_column_default_expression()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().GeneratedValueSql);
Assert.Null(((IProperty)property).Relational().GeneratedValueSql);
Assert.Null(property.SqlServer().GeneratedValueSql);
Assert.Null(((IProperty)property).SqlServer().GeneratedValueSql);
property.Relational().GeneratedValueSql = "newsequentialid()";
Assert.Equal("newsequentialid()", property.Relational().GeneratedValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).Relational().GeneratedValueSql);
Assert.Equal("newsequentialid()", property.SqlServer().GeneratedValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).SqlServer().GeneratedValueSql);
property.SqlServer().GeneratedValueSql = "expressyourself()";
Assert.Equal("newsequentialid()", property.Relational().GeneratedValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).Relational().GeneratedValueSql);
Assert.Equal("expressyourself()", property.SqlServer().GeneratedValueSql);
Assert.Equal("expressyourself()", ((IProperty)property).SqlServer().GeneratedValueSql);
property.SqlServer().GeneratedValueSql = null;
Assert.Equal("newsequentialid()", property.Relational().GeneratedValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).Relational().GeneratedValueSql);
Assert.Equal("newsequentialid()", property.SqlServer().GeneratedValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).SqlServer().GeneratedValueSql);
}
[Fact]
public void Can_get_and_set_column_default_value()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().DefaultValue);
Assert.Null(((IProperty)property).Relational().DefaultValue);
Assert.Null(property.SqlServer().DefaultValue);
Assert.Null(((IProperty)property).SqlServer().DefaultValue);
property.Relational().DefaultValue = new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 };
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.SqlServer().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).SqlServer().DefaultValue);
property.SqlServer().DefaultValue = new Byte[] { 69, 70, 32, 83, 79, 67, 75, 83 };
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 83, 79, 67, 75, 83 }, property.SqlServer().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 83, 79, 67, 75, 83 }, ((IProperty)property).SqlServer().DefaultValue);
property.SqlServer().DefaultValue = null;
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).Relational().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.SqlServer().DefaultValue);
Assert.Equal(new Byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).SqlServer().DefaultValue);
}
[Fact]
public void Can_get_and_set_column_key_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var key = modelBuilder
.Entity<Customer>()
.Key(e => e.Id)
.Metadata;
Assert.Equal("PK_Customer", key.Relational().Name);
Assert.Equal("PK_Customer", ((IKey)key).Relational().Name);
Assert.Equal("PK_Customer", key.SqlServer().Name);
Assert.Equal("PK_Customer", ((IKey)key).SqlServer().Name);
key.Relational().Name = "PrimaryKey";
Assert.Equal("PrimaryKey", key.Relational().Name);
Assert.Equal("PrimaryKey", ((IKey)key).Relational().Name);
Assert.Equal("PrimaryKey", key.SqlServer().Name);
Assert.Equal("PrimaryKey", ((IKey)key).SqlServer().Name);
key.SqlServer().Name = "PrimarySchool";
Assert.Equal("PrimaryKey", key.Relational().Name);
Assert.Equal("PrimaryKey", ((IKey)key).Relational().Name);
Assert.Equal("PrimarySchool", key.SqlServer().Name);
Assert.Equal("PrimarySchool", ((IKey)key).SqlServer().Name);
key.SqlServer().Name = null;
Assert.Equal("PrimaryKey", key.Relational().Name);
Assert.Equal("PrimaryKey", ((IKey)key).Relational().Name);
Assert.Equal("PrimaryKey", key.SqlServer().Name);
Assert.Equal("PrimaryKey", ((IKey)key).SqlServer().Name);
}
[Fact]
public void Can_get_and_set_column_foreign_key_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
modelBuilder
.Entity<Customer>()
.Key(e => e.Id);
var foreignKey = modelBuilder
.Entity<Order>()
.Reference<Customer>()
.InverseReference()
.ForeignKey<Order>(e => e.CustomerId)
.Metadata;
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.Relational().Name);
Assert.Equal("FK_Order_Customer_CustomerId", ((IForeignKey)foreignKey).Relational().Name);
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.SqlServer().Name);
Assert.Equal("FK_Order_Customer_CustomerId", ((IForeignKey)foreignKey).SqlServer().Name);
foreignKey.Relational().Name = "FK";
Assert.Equal("FK", foreignKey.Relational().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).Relational().Name);
Assert.Equal("FK", foreignKey.SqlServer().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).SqlServer().Name);
foreignKey.SqlServer().Name = "KFC";
Assert.Equal("FK", foreignKey.Relational().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).Relational().Name);
Assert.Equal("KFC", foreignKey.SqlServer().Name);
Assert.Equal("KFC", ((IForeignKey)foreignKey).SqlServer().Name);
foreignKey.SqlServer().Name = null;
Assert.Equal("FK", foreignKey.Relational().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).Relational().Name);
Assert.Equal("FK", foreignKey.SqlServer().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).SqlServer().Name);
}
[Fact]
public void Can_get_and_set_index_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var index = modelBuilder
.Entity<Customer>()
.Index(e => e.Id)
.Metadata;
Assert.Equal("IX_Customer_Id", index.Relational().Name);
Assert.Equal("IX_Customer_Id", ((IIndex)index).Relational().Name);
Assert.Equal("IX_Customer_Id", index.SqlServer().Name);
Assert.Equal("IX_Customer_Id", ((IIndex)index).SqlServer().Name);
index.Relational().Name = "MyIndex";
Assert.Equal("MyIndex", index.Relational().Name);
Assert.Equal("MyIndex", ((IIndex)index).Relational().Name);
Assert.Equal("MyIndex", index.SqlServer().Name);
Assert.Equal("MyIndex", ((IIndex)index).SqlServer().Name);
index.SqlServer().Name = "DexKnows";
Assert.Equal("MyIndex", index.Relational().Name);
Assert.Equal("MyIndex", ((IIndex)index).Relational().Name);
Assert.Equal("DexKnows", index.SqlServer().Name);
Assert.Equal("DexKnows", ((IIndex)index).SqlServer().Name);
index.SqlServer().Name = null;
Assert.Equal("MyIndex", index.Relational().Name);
Assert.Equal("MyIndex", ((IIndex)index).Relational().Name);
Assert.Equal("MyIndex", index.SqlServer().Name);
Assert.Equal("MyIndex", ((IIndex)index).SqlServer().Name);
}
[Fact]
public void Can_get_and_set_index_clustering()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var index = modelBuilder
.Entity<Customer>()
.Index(e => e.Id)
.Metadata;
Assert.Null(index.SqlServer().IsClustered);
Assert.Null(((IIndex)index).SqlServer().IsClustered);
index.SqlServer().IsClustered = true;
Assert.True(index.SqlServer().IsClustered.Value);
Assert.True(((IIndex)index).SqlServer().IsClustered.Value);
index.SqlServer().IsClustered = null;
Assert.Null(index.SqlServer().IsClustered);
Assert.Null(((IIndex)index).SqlServer().IsClustered);
}
[Fact]
public void Can_get_and_set_key_clustering()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var key = modelBuilder
.Entity<Customer>()
.Key(e => e.Id)
.Metadata;
Assert.Null(key.SqlServer().IsClustered);
Assert.Null(((IKey)key).SqlServer().IsClustered);
key.SqlServer().IsClustered = true;
Assert.True(key.SqlServer().IsClustered.Value);
Assert.True(((IKey)key).SqlServer().IsClustered.Value);
key.SqlServer().IsClustered = null;
Assert.Null(key.SqlServer().IsClustered);
Assert.Null(((IKey)key).SqlServer().IsClustered);
}
[Fact]
public void Can_get_and_set_sequence()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.Relational().TryGetSequence("Foo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo"));
Assert.Null(model.SqlServer().TryGetSequence("Foo"));
Assert.Null(((IModel)model).SqlServer().TryGetSequence("Foo"));
var sequence = model.SqlServer().GetOrAddSequence("Foo");
Assert.Null(model.Relational().TryGetSequence("Foo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo"));
Assert.Equal("Foo", model.SqlServer().TryGetSequence("Foo").Name);
Assert.Equal("Foo", ((IModel)model).SqlServer().TryGetSequence("Foo").Name);
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.Type);
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo", null, 1729, 11, 2001, 2010, typeof(int)));
Assert.Null(model.Relational().TryGetSequence("Foo"));
sequence = model.SqlServer().GetOrAddSequence("Foo");
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.Type);
}
[Fact]
public void Can_get_and_set_sequence_with_schema_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.Relational().TryGetSequence("Foo", "Smoo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo", "Smoo"));
Assert.Null(model.SqlServer().TryGetSequence("Foo", "Smoo"));
Assert.Null(((IModel)model).SqlServer().TryGetSequence("Foo", "Smoo"));
var sequence = model.SqlServer().GetOrAddSequence("Foo", "Smoo");
Assert.Null(model.Relational().TryGetSequence("Foo", "Smoo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo", "Smoo"));
Assert.Equal("Foo", model.SqlServer().TryGetSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", ((IModel)model).SqlServer().TryGetSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.Type);
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo", "Smoo", 1729, 11, 2001, 2010, typeof(int)));
Assert.Null(model.Relational().TryGetSequence("Foo", "Smoo"));
sequence = model.SqlServer().GetOrAddSequence("Foo", "Smoo");
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.Type);
}
[Fact]
public void Can_add_and_replace_sequence()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo"));
Assert.Null(model.Relational().TryGetSequence("Foo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo"));
Assert.Equal("Foo", model.SqlServer().TryGetSequence("Foo").Name);
Assert.Equal("Foo", ((IModel)model).SqlServer().TryGetSequence("Foo").Name);
var sequence = model.SqlServer().TryGetSequence("Foo");
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.Type);
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo", null, 1729, 11, 2001, 2010, typeof(int)));
Assert.Null(model.Relational().TryGetSequence("Foo"));
sequence = model.SqlServer().TryGetSequence("Foo");
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.Type);
}
[Fact]
public void Can_add_and_replace_sequence_with_schema_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo", "Smoo"));
Assert.Null(model.Relational().TryGetSequence("Foo", "Smoo"));
Assert.Null(((IModel)model).Relational().TryGetSequence("Foo", "Smoo"));
Assert.Equal("Foo", model.SqlServer().TryGetSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", ((IModel)model).SqlServer().TryGetSequence("Foo", "Smoo").Name);
var sequence = model.SqlServer().TryGetSequence("Foo", "Smoo");
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.Type);
model.SqlServer().AddOrReplaceSequence(new Sequence("Foo", "Smoo", 1729, 11, 2001, 2010, typeof(int)));
Assert.Null(model.Relational().TryGetSequence("Foo", "Smoo"));
sequence = model.SqlServer().TryGetSequence("Foo", "Smoo");
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.Type);
}
[Fact]
public void Can_get_multiple_sequences()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
model.Relational().AddOrReplaceSequence(new Sequence("Fibonacci"));
model.SqlServer().AddOrReplaceSequence(new Sequence("Golomb"));
var sequences = model.SqlServer().Sequences;
Assert.Equal(2, sequences.Count);
Assert.Contains(sequences, s => s.Name == "Fibonacci");
Assert.Contains(sequences, s => s.Name == "Golomb");
}
[Fact]
public void Can_get_multiple_sequences_when_overridden()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
model.Relational().AddOrReplaceSequence(new Sequence("Fibonacci", startValue: 1));
model.SqlServer().AddOrReplaceSequence(new Sequence("Fibonacci", startValue: 3));
model.SqlServer().AddOrReplaceSequence(new Sequence("Golomb"));
var sequences = model.SqlServer().Sequences;
Assert.Equal(2, sequences.Count);
Assert.Contains(sequences, s => s.Name == "Golomb");
var sequence = sequences.FirstOrDefault(s => s.Name == "Fibonacci");
Assert.NotNull(sequence);
Assert.Equal(3, sequence.StartValue);
}
[Fact]
public void Can_get_and_set_value_generation_on_model()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.SqlServer().IdentityStrategy);
Assert.Null(((IModel)model).SqlServer().IdentityStrategy);
model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, model.SqlServer().IdentityStrategy);
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, ((IModel)model).SqlServer().IdentityStrategy);
model.SqlServer().IdentityStrategy = null;
Assert.Null(model.SqlServer().IdentityStrategy);
Assert.Null(((IModel)model).SqlServer().IdentityStrategy);
}
[Fact]
public void Can_get_and_set_default_sequence_name_on_model()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.SqlServer().HiLoSequenceName);
Assert.Null(((IModel)model).SqlServer().HiLoSequenceName);
model.SqlServer().HiLoSequenceName = "Tasty.Snook";
Assert.Equal("Tasty.Snook", model.SqlServer().HiLoSequenceName);
Assert.Equal("Tasty.Snook", ((IModel)model).SqlServer().HiLoSequenceName);
model.SqlServer().HiLoSequenceName = null;
Assert.Null(model.SqlServer().HiLoSequenceName);
Assert.Null(((IModel)model).SqlServer().HiLoSequenceName);
}
[Fact]
public void Can_get_and_set_pool_size_on_model()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.SqlServer().HiLoSequencePoolSize);
Assert.Null(((IModel)model).SqlServer().HiLoSequencePoolSize);
model.SqlServer().HiLoSequencePoolSize = 88;
Assert.Equal(88, model.SqlServer().HiLoSequencePoolSize);
Assert.Equal(88, ((IModel)model).SqlServer().HiLoSequencePoolSize);
model.SqlServer().HiLoSequencePoolSize = null;
Assert.Null(model.SqlServer().HiLoSequencePoolSize);
Assert.Null(((IModel)model).SqlServer().HiLoSequencePoolSize);
}
[Fact]
public void Can_get_and_set_default_sequence_schema_on_model()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var model = modelBuilder.Model;
Assert.Null(model.SqlServer().HiLoSequenceSchema);
Assert.Null(((IModel)model).SqlServer().HiLoSequenceSchema);
model.SqlServer().HiLoSequenceSchema = "Tasty.Snook";
Assert.Equal("Tasty.Snook", model.SqlServer().HiLoSequenceSchema);
Assert.Equal("Tasty.Snook", ((IModel)model).SqlServer().HiLoSequenceSchema);
model.SqlServer().HiLoSequenceSchema = null;
Assert.Null(model.SqlServer().HiLoSequenceSchema);
Assert.Null(((IModel)model).SqlServer().HiLoSequenceSchema);
}
[Fact]
public void Can_get_and_set_value_generation_on_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
Assert.Null(property.SqlServer().IdentityStrategy);
Assert.Null(((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
Assert.False(((IProperty)property).RequiresValueGenerator);
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, property.SqlServer().IdentityStrategy);
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, ((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
property.SqlServer().IdentityStrategy = null;
Assert.Null(property.SqlServer().IdentityStrategy);
Assert.Null(((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
}
[Fact]
public void Can_get_and_set_value_generation_on_nullable_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.NullableInt)
.ValueGeneratedOnAdd()
.Metadata;
Assert.Null(property.SqlServer().IdentityStrategy);
Assert.Null(((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
Assert.False(((IProperty)property).RequiresValueGenerator);
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, property.SqlServer().IdentityStrategy);
Assert.Equal(SqlServerIdentityStrategy.SequenceHiLo, ((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
property.SqlServer().IdentityStrategy = null;
Assert.Null(property.SqlServer().IdentityStrategy);
Assert.Null(((IProperty)property).SqlServer().IdentityStrategy);
Assert.Null(property.RequiresValueGenerator);
}
[Fact]
public void Throws_setting_sequence_generation_for_invalid_type()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal(
Strings.SequenceBadType("Name", typeof(Customer).FullName, "String"),
Assert.Throws<ArgumentException>(
() => property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo).Message);
}
[Fact]
public void Throws_setting_identity_generation_for_invalid_type()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal(
Strings.IdentityBadType("Name", typeof(Customer).FullName, "String"),
Assert.Throws<ArgumentException>(
() => property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.IdentityColumn).Message);
}
[Fact]
public void Throws_setting_identity_generation_for_byte_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Byte)
.Metadata;
Assert.Equal(
Strings.IdentityBadType("Byte", typeof(Customer).FullName, "Byte"),
Assert.Throws<ArgumentException>(
() => property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.IdentityColumn).Message);
}
[Fact]
public void Throws_setting_identity_generation_for_nullable_byte_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.NullableByte)
.Metadata;
Assert.Equal(
Strings.IdentityBadType("NullableByte", typeof(Customer).FullName, "Nullable`1"),
Assert.Throws<ArgumentException>(
() => property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.IdentityColumn).Message);
}
[Fact]
public void Can_get_and_set_sequence_name_on_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.SqlServer().HiLoSequenceName);
Assert.Null(((IProperty)property).SqlServer().HiLoSequenceName);
property.SqlServer().HiLoSequenceName = "Snook";
Assert.Equal("Snook", property.SqlServer().HiLoSequenceName);
Assert.Equal("Snook", ((IProperty)property).SqlServer().HiLoSequenceName);
property.SqlServer().HiLoSequenceName = null;
Assert.Null(property.SqlServer().HiLoSequenceName);
Assert.Null(((IProperty)property).SqlServer().HiLoSequenceName);
}
[Fact]
public void Can_get_and_set_pool_size_on_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.SqlServer().HiLoSequencePoolSize);
Assert.Null(((IProperty)property).SqlServer().HiLoSequencePoolSize);
property.SqlServer().HiLoSequencePoolSize = 77;
Assert.Equal(77, property.SqlServer().HiLoSequencePoolSize);
Assert.Equal(77, ((IProperty)property).SqlServer().HiLoSequencePoolSize);
property.SqlServer().HiLoSequencePoolSize = null;
Assert.Null(property.SqlServer().HiLoSequencePoolSize);
Assert.Null(((IProperty)property).SqlServer().HiLoSequencePoolSize);
}
[Fact]
public void Can_get_and_set_sequence_schema_on_property()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.SqlServer().HiLoSequenceSchema);
Assert.Null(((IProperty)property).SqlServer().HiLoSequenceSchema);
property.SqlServer().HiLoSequenceSchema = "Tasty";
Assert.Equal("Tasty", property.SqlServer().HiLoSequenceSchema);
Assert.Equal("Tasty", ((IProperty)property).SqlServer().HiLoSequenceSchema);
property.SqlServer().HiLoSequenceSchema = null;
Assert.Null(property.SqlServer().HiLoSequenceSchema);
Assert.Null(((IProperty)property).SqlServer().HiLoSequenceSchema);
}
[Fact]
public void TryGetSequence_returns_null_if_property_is_not_configured_for_sequence_value_generation()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw"));
Assert.Null(property.SqlServer().TryGetHiLoSequence());
Assert.Null(((IProperty)property).SqlServer().TryGetHiLoSequence());
property.SqlServer().HiLoSequenceName = "DaneelOlivaw";
Assert.Null(property.SqlServer().TryGetHiLoSequence());
Assert.Null(((IProperty)property).SqlServer().TryGetHiLoSequence());
modelBuilder.Model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.IdentityColumn;
Assert.Null(property.SqlServer().TryGetHiLoSequence());
Assert.Null(((IProperty)property).SqlServer().TryGetHiLoSequence());
modelBuilder.Model.SqlServer().IdentityStrategy = null;
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.IdentityColumn;
Assert.Null(property.SqlServer().TryGetHiLoSequence());
Assert.Null(((IProperty)property).SqlServer().TryGetHiLoSequence());
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw"));
property.SqlServer().HiLoSequenceName = "DaneelOlivaw";
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw"));
modelBuilder.Model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
property.SqlServer().HiLoSequenceName = "DaneelOlivaw";
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw"));
modelBuilder.Model.SqlServer().HiLoSequenceName = "DaneelOlivaw";
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw"));
modelBuilder.Model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
modelBuilder.Model.SqlServer().HiLoSequenceName = "DaneelOlivaw";
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw", "R"));
property.SqlServer().HiLoSequenceName = "DaneelOlivaw";
property.SqlServer().HiLoSequenceSchema = "R";
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("R", property.SqlServer().TryGetHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).SqlServer().TryGetHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw", "R"));
modelBuilder.Model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
property.SqlServer().HiLoSequenceName = "DaneelOlivaw";
property.SqlServer().HiLoSequenceSchema = "R";
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("R", property.SqlServer().TryGetHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).SqlServer().TryGetHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw", "R"));
modelBuilder.Model.SqlServer().HiLoSequenceName = "DaneelOlivaw";
modelBuilder.Model.SqlServer().HiLoSequenceSchema = "R";
property.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("R", property.SqlServer().TryGetHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).SqlServer().TryGetHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.SqlServer().AddOrReplaceSequence(new Sequence("DaneelOlivaw", "R"));
modelBuilder.Model.SqlServer().IdentityStrategy = SqlServerIdentityStrategy.SequenceHiLo;
modelBuilder.Model.SqlServer().HiLoSequenceName = "DaneelOlivaw";
modelBuilder.Model.SqlServer().HiLoSequenceSchema = "R";
Assert.Equal("DaneelOlivaw", property.SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).SqlServer().TryGetHiLoSequence().Name);
Assert.Equal("R", property.SqlServer().TryGetHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).SqlServer().TryGetHiLoSequence().Schema);
}
private class Customer
{
public int Id { get; set; }
public int? NullableInt { get; set; }
public string Name { get; set; }
public byte Byte { get; set; }
public byte? NullableByte { get; set; }
}
private class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
}
}
}
| 43.257353 | 158 | 0.613463 | [
"Apache-2.0"
] | suryasnath/csharp | test/EntityFramework.SqlServer.Tests/Metadata/SqlServerMetadataExtensionsTest.cs | 47,064 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Codecs.Http2
{
using System;
using DotNetty.Buffers;
using DotNetty.Codecs.Http;
using DotNetty.Transport.Channels;
/// <summary>
/// This adapter provides just header/data events from the HTTP message flow defined
/// in <a href="https://tools.ietf.org/html/rfc7540#section-8.1">[RFC 7540], Section 8.1</a>.
/// <para>See <see cref="HttpToHttp2ConnectionHandler"/> to get translation from HTTP/1.x objects to HTTP/2 frames for writes.</para>
/// </summary>
public class InboundHttp2ToHttpAdapter : Http2EventAdapter
{
private readonly int _maxContentLength;
private readonly IImmediateSendDetector _sendDetector;
private readonly IHttp2ConnectionPropertyKey _messageKey;
private readonly bool _propagateSettings;
protected readonly IHttp2Connection _connection;
protected readonly bool _validateHttpHeaders;
public InboundHttp2ToHttpAdapter(IHttp2Connection connection, int maxContentLength,
bool validateHttpHeaders, bool propagateSettings)
{
if (connection is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.connection); }
if ((uint)(maxContentLength - 1) > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentException_Positive(maxContentLength, ExceptionArgument.maxContentLength); }
_connection = connection;
_maxContentLength = maxContentLength;
_validateHttpHeaders = validateHttpHeaders;
_propagateSettings = propagateSettings;
_sendDetector = DefaultImmediateSendDetector.Instance;
_messageKey = connection.NewKey();
}
/// <summary>
/// The stream is out of scope for the HTTP message flow and will no longer be tracked
/// </summary>
/// <param name="stream">The stream to remove associated state with</param>
/// <param name="release"><c>true</c> to call release on the value if it is present. <c>false</c> to not call release.</param>
protected void RemoveMessage(IHttp2Stream stream, bool release)
{
IFullHttpMessage msg = stream.RemoveProperty<IFullHttpMessage>(_messageKey);
if (release && msg is object)
{
_ = msg.Release();
}
}
/// <summary>
/// Get the <see cref="IFullHttpMessage"/> associated with <paramref name="stream"/>.
/// </summary>
/// <param name="stream">The stream to get the associated state from</param>
/// <returns>The <see cref="IFullHttpMessage"/> associated with <paramref name="stream"/>.</returns>
protected IFullHttpMessage GetMessage(IHttp2Stream stream)
{
return stream.GetProperty<IFullHttpMessage>(_messageKey);
}
/// <summary>
/// Make <paramref name="message"/> be the state associated with <paramref name="stream"/>.
/// </summary>
/// <param name="stream">The stream which <paramref name="message"/> is associated with.</param>
/// <param name="message">The message which contains the HTTP semantics.</param>
protected void PutMessage(IHttp2Stream stream, IFullHttpMessage message)
{
IFullHttpMessage previous = stream.SetProperty<IFullHttpMessage>(_messageKey, message);
if (previous != message && previous is object)
{
_ = previous.Release();
}
}
public override void OnStreamRemoved(IHttp2Stream stream)
{
RemoveMessage(stream, true);
}
/// <summary>
/// Set final headers and fire a channel read event
/// </summary>
/// <param name="ctx">The context to fire the event on</param>
/// <param name="msg">The message to send</param>
/// <param name="release"><c>true</c> to call release on the value if it is present. <c>false</c> to not call release.</param>
/// <param name="stream">the stream of the message which is being fired</param>
protected virtual void FireChannelRead(IChannelHandlerContext ctx, IFullHttpMessage msg, bool release, IHttp2Stream stream)
{
RemoveMessage(stream, release);
HttpUtil.SetContentLength(msg, msg.Content.ReadableBytes);
_ = ctx.FireChannelRead(msg);
}
/// <summary>
/// Create a new <see cref="IFullHttpMessage"/> based upon the current connection parameters
/// </summary>
/// <param name="stream">The stream to create a message for</param>
/// <param name="headers">The headers associated with <paramref name="stream"/>.</param>
/// <param name="validateHttpHeaders"><c>true</c> to validate HTTP headers in the http-codec
/// <para><c>false</c> not to validate HTTP headers in the http-codec</para></param>
/// <param name="alloc">The <see cref="IByteBufferAllocator"/> to use to generate the content of the message</param>
/// <returns></returns>
protected virtual IFullHttpMessage NewMessage(IHttp2Stream stream, IHttp2Headers headers, bool validateHttpHeaders,
IByteBufferAllocator alloc)
{
if (_connection.IsServer)
{
return HttpConversionUtil.ToFullHttpRequest(stream.Id, headers, alloc, validateHttpHeaders);
}
return HttpConversionUtil.ToFullHttpResponse(stream.Id, headers, alloc, validateHttpHeaders);
}
/// <summary>
/// Provides translation between HTTP/2 and HTTP header objects while ensuring the stream
/// is in a valid state for additional headers.
/// </summary>
/// <param name="ctx">The context for which this message has been received.
/// Used to send informational header if detected.</param>
/// <param name="stream">The stream the <paramref name="headers"/> apply to</param>
/// <param name="headers">The headers to process</param>
/// <param name="endOfStream"><c>true</c> if the <paramref name="stream"/> has received the end of stream flag</param>
/// <param name="allowAppend"><c>true</c> if headers will be appended if the stream already exists.
/// <para>if <c>false</c> and the stream already exists this method returns <c>null</c>.</para></param>
/// <param name="appendToTrailer"><c>true</c> if a message <paramref name="stream"/> already exists then the headers
/// should be added to the trailing headers.
/// <para><c>false</c> then appends will be done to the initial headers.</para></param>
/// <returns>The object used to track the stream corresponding to <paramref name="stream"/>. <c>null</c> if
/// <paramref name="allowAppend"/> is <c>false</c> and the stream already exists.</returns>
/// <exception cref="Http2Exception">If the stream id is not in the correct state to process the headers request</exception>
protected virtual IFullHttpMessage ProcessHeadersBegin(IChannelHandlerContext ctx, IHttp2Stream stream, IHttp2Headers headers,
bool endOfStream, bool allowAppend, bool appendToTrailer)
{
IFullHttpMessage msg = GetMessage(stream);
var release = true;
if (msg is null)
{
msg = NewMessage(stream, headers, _validateHttpHeaders, ctx.Allocator);
}
else if (allowAppend)
{
release = false;
HttpConversionUtil.AddHttp2ToHttpHeaders(stream.Id, headers, msg, appendToTrailer);
}
else
{
release = false;
msg = null;
}
if (_sendDetector.MustSendImmediately(msg))
{
// Copy the message (if necessary) before sending. The content is not expected to be copied (or used) in
// this operation but just in case it is used do the copy before sending and the resource may be released
IFullHttpMessage copy = endOfStream ? null : _sendDetector.CopyIfNeeded(ctx.Allocator, msg);
FireChannelRead(ctx, msg, release, stream);
return copy;
}
return msg;
}
/// <summary>
/// After HTTP/2 headers have been processed by <see cref="ProcessHeadersBegin"/> this method either
/// sends the result up the pipeline or retains the message for future processing.
/// </summary>
/// <param name="ctx">The context for which this message has been received</param>
/// <param name="stream">The stream the <paramref name="msg"/> corresponds to</param>
/// <param name="msg">The object which represents all headers/data for corresponding to <paramref name="stream"/>.</param>
/// <param name="endOfStream"><c>true</c> if this is the last event for the stream</param>
private void ProcessHeadersEnd(IChannelHandlerContext ctx, IHttp2Stream stream, IFullHttpMessage msg, bool endOfStream)
{
if (endOfStream)
{
// Release if the msg from the map is different from the object being forwarded up the pipeline.
FireChannelRead(ctx, msg, GetMessage(stream) != msg, stream);
}
else
{
PutMessage(stream, msg);
}
}
public override int OnDataRead(IChannelHandlerContext ctx, int streamId, IByteBuffer data, int padding, bool endOfStream)
{
IHttp2Stream stream = _connection.Stream(streamId);
IFullHttpMessage msg = GetMessage(stream);
if (msg is null)
{
ThrowHelper.ThrowConnectionError_DataFrameReceivedForUnknownStream(streamId);
}
var content = msg.Content;
int dataReadableBytes = data.ReadableBytes;
if (content.ReadableBytes > _maxContentLength - dataReadableBytes)
{
ThrowHelper.ThrowConnectionError_ContentLengthExceededMax(_maxContentLength, streamId);
}
_ = content.WriteBytes(data, data.ReaderIndex, dataReadableBytes);
if (endOfStream)
{
FireChannelRead(ctx, msg, false, stream);
}
// All bytes have been processed.
return dataReadableBytes + padding;
}
public override void OnHeadersRead(IChannelHandlerContext ctx, int streamId, IHttp2Headers headers, int padding, bool endOfStream)
{
IHttp2Stream stream = _connection.Stream(streamId);
IFullHttpMessage msg = ProcessHeadersBegin(ctx, stream, headers, endOfStream, true, true);
if (msg is object)
{
ProcessHeadersEnd(ctx, stream, msg, endOfStream);
}
}
public override void OnHeadersRead(IChannelHandlerContext ctx, int streamId, IHttp2Headers headers, int streamDependency, short weight, bool exclusive, int padding, bool endOfStream)
{
IHttp2Stream stream = _connection.Stream(streamId);
IFullHttpMessage msg = ProcessHeadersBegin(ctx, stream, headers, endOfStream, true, true);
if (msg is object)
{
// Add headers for dependency and weight.
// See https://github.com/netty/netty/issues/5866
if (streamDependency != Http2CodecUtil.ConnectionStreamId)
{
_ = msg.Headers.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamDependencyId, streamDependency);
}
_ = msg.Headers.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, weight);
ProcessHeadersEnd(ctx, stream, msg, endOfStream);
}
}
public override void OnRstStreamRead(IChannelHandlerContext ctx, int streamId, Http2Error errorCode)
{
IHttp2Stream stream = _connection.Stream(streamId);
IFullHttpMessage msg = GetMessage(stream);
if (msg is object)
{
OnRstStreamRead(stream, msg);
}
_ = ctx.FireExceptionCaught(ThrowHelper.GetStreamError_Http2ToHttpLayerCaughtStreamReset(streamId, errorCode));
}
public override void OnPushPromiseRead(IChannelHandlerContext ctx, int streamId, int promisedStreamId, IHttp2Headers headers, int padding)
{
// A push promise should not be allowed to add headers to an existing stream
IHttp2Stream promisedStream = _connection.Stream(promisedStreamId);
if (headers.Status is null)
{
// A PUSH_PROMISE frame has no Http response status.
// https://tools.ietf.org/html/rfc7540#section-8.2.1
// Server push is semantically equivalent to a server responding to a
// request; however, in this case, that request is also sent by the
// server, as a PUSH_PROMISE frame.
headers.Status = HttpResponseStatus.OK.CodeAsText;
}
IFullHttpMessage msg = ProcessHeadersBegin(ctx, promisedStream, headers, false, false, false);
if (msg is null)
{
ThrowHelper.ThrowConnectionError_PushPromiseFrameReceivedForPreExistingStreamId(promisedStreamId);
}
_ = msg.Headers.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamPromiseId, streamId);
_ = msg.Headers.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, Http2CodecUtil.DefaultPriorityWeight);
ProcessHeadersEnd(ctx, promisedStream, msg, false);
}
public override void OnSettingsRead(IChannelHandlerContext ctx, Http2Settings settings)
{
if (_propagateSettings)
{
// Provide an interface for non-listeners to capture settings
_ = ctx.FireChannelRead(settings);
}
}
/// <summary>
/// Called if a <c>RST_STREAM</c> is received but we have some data for that stream.
/// </summary>
/// <param name="stream"></param>
/// <param name="msg"></param>
protected virtual void OnRstStreamRead(IHttp2Stream stream, IFullHttpMessage msg)
{
RemoveMessage(stream, true);
}
private sealed class DefaultImmediateSendDetector : IImmediateSendDetector
{
public static readonly DefaultImmediateSendDetector Instance = new DefaultImmediateSendDetector();
public IFullHttpMessage CopyIfNeeded(IByteBufferAllocator allocator, IFullHttpMessage msg)
{
if (msg is IFullHttpRequest request)
{
var copy = (IFullHttpRequest)request.Replace(allocator.Buffer(0));
_ = copy.Headers.Remove(HttpHeaderNames.Expect);
return copy;
}
return null;
}
public bool MustSendImmediately(IFullHttpMessage msg)
{
switch (msg)
{
case IFullHttpResponse response:
return response.Status.CodeClass == HttpStatusClass.Informational;
case IFullHttpRequest _:
return msg.Headers.Contains(HttpHeaderNames.Expect);
default:
return false;
}
}
}
/// <summary>
/// Allows messages to be sent up the pipeline before the next phase in the
/// HTTP message flow is detected.
/// </summary>
private interface IImmediateSendDetector
{
/// <summary>
/// Determine if the response should be sent immediately, or wait for the end of the stream
/// </summary>
/// <param name="msg">The response to test</param>
/// <returns><c>true</c> if the message should be sent immediately
/// <para><c>false</c> if we should wait for the end of the stream</para></returns>
bool MustSendImmediately(IFullHttpMessage msg);
/// <summary>
/// Determine if a copy must be made after an immediate send happens.
/// <para>An example of this use case is if a request is received
/// with a 'Expect: 100-continue' header. The message will be sent immediately,
/// and the data will be queued and sent at the end of the stream.</para>
/// </summary>
/// <param name="allocator">The <see cref="IByteBufferAllocator"/> that can be used to allocate</param>
/// <param name="msg">The message which has just been sent due to <see cref="MustSendImmediately(IFullHttpMessage)"/>.</param>
/// <returns>A modified copy of the <paramref name="msg"/> or <c>null</c> if a copy is not needed.</returns>
IFullHttpMessage CopyIfNeeded(IByteBufferAllocator allocator, IFullHttpMessage msg);
}
}
}
| 48.878378 | 190 | 0.624385 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Codecs.Http2/InboundHttp2ToHttpAdapter.cs | 18,087 | C# |
/*
* The MIT License
*
* Copyright 2019 Palmtree Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Palmtree.Math.Core.Uint.Test
{
public class Int32DataItem
: DataItem
{
public Int32DataItem(Int32 value)
{
Value = value;
}
public override string Type => "int32";
public Int32 Value { get; }
public override bool IsInt32 => true;
public override Int32DataItem ToInt32()
{
return (this);
}
public override bool Equals(object o)
{
if (o == null)
return (false);
if (GetType() != o.GetType())
return (false);
return (Value == ((Int32DataItem)o).Value);
}
public override int GetHashCode()
{
return (Value.GetHashCode());
}
public override string ToSummaryString()
{
return (Value.ToString());
}
}
}
/*
* END OF FILE
*/ | 28.424658 | 80 | 0.638072 | [
"MIT"
] | rougemeilland/Palmtree.Math.Core.Uint | Palmtree.Math.Core.Uint.Test/Int32DataItem.cs | 2,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfUI
{
/// <summary>
/// Interaction logic for TraineeWindow.xaml
/// </summary>
public partial class TraineeWindow : Window
{
public TraineeWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
private void Add_Trainee_Button_Click(object sender, RoutedEventArgs e)
{
new AddTraineeWindow().ShowDialog();
}
private void Get_Button_Click(object sender, RoutedEventArgs e)
{
new GetTraineesWindow().ShowDialog();
}
private void Update_Button_Click(object sender, RoutedEventArgs e)
{
new UpdateTraineeWindow().ShowDialog();
}
private void Delete_Button_Click(object sender, RoutedEventArgs e)
{
new deleteTraineeWindow().ShowDialog();
}
}
}
| 25.795918 | 79 | 0.662975 | [
"MIT"
] | RikiZilber/LicensingOffice | WpfUI/TraineeWindow.xaml.cs | 1,266 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AngularBooking.Models
{
public enum AgeRatingType
{
BBFC_UC,
BBFC_U,
BBFC_PG,
BBFC_12A,
BBFC_12,
BBFC_15,
BBFC_18,
BBFC_R18,
BBFC_TBC,
PEGI_Universal,
PEGI_PG,
PEGI_12A,
PEGI_12,
PEGI_15,
PEGI_18,
PEGI_R18
}
}
| 16.392857 | 33 | 0.555556 | [
"MIT"
] | adamlarner/angularbooking | AngularBooking/Models/AgeRatingType.cs | 461 | C# |
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="ALM | DevOps Ranger Contributors">
// © ALM | DevOps Ranger Contributors
// MIT 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.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
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("CuiWordAddinTestProject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("CuiWordAddinTestProject")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("77a7f00e-591c-45de-8865-324c3a98e4e1")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 46.233333 | 84 | 0.704758 | [
"MIT"
] | ALM-Rangers/Sample-Code | src/Coded-UI/samples/DevelopmentDev10/Source Code/CuiWordAddinTestProject/CuiWordAddinTestProject/Properties/AssemblyInfo.cs | 2,778 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Tracing;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Diagnostics.Debug;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Shared named pipe utilities.
/// </summary>
internal static class NamedPipeUtils
{
#region Strings
internal const string NamedPipeNamePrefix = "PSHost.";
#if UNIX
internal const string DefaultAppDomainName = "None";
// This `CoreFxPipe` prefix is defined by CoreFx
internal const string NamedPipeNamePrefixSearch = "CoreFxPipe_PSHost*";
#else
internal const string DefaultAppDomainName = "DefaultAppDomain";
internal const string NamedPipeNamePrefixSearch = "PSHost*";
#endif
// On non-Windows, .NET named pipes are limited to up to 104 characters
internal const int MaxNamedPipeNameSize = 104;
#endregion
#region Static Methods
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId)
{
return CreateProcessPipeName(
System.Diagnostics.Process.GetProcessById(procId));
}
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc)
{
return CreateProcessPipeName(proc, DefaultAppDomainName);
}
/// <summary>
/// Create a pipe name based on process Id and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId,
string appDomainName)
{
return CreateProcessPipeName(System.Diagnostics.Process.GetProcessById(procId), appDomainName);
}
/// <summary>
/// Create a pipe name based on process and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc,
string appDomainName)
{
if (proc == null)
{
throw new PSArgumentNullException(nameof(proc));
}
if (string.IsNullOrEmpty(appDomainName))
{
appDomainName = DefaultAppDomainName;
}
System.Text.StringBuilder pipeNameBuilder = new System.Text.StringBuilder(MaxNamedPipeNameSize);
pipeNameBuilder.Append(NamedPipeNamePrefix)
// The starttime is there to prevent another process easily guessing the pipe name
// and squatting on it.
// There is a limit of 104 characters in total including the temp path to the named pipe file
// on non-Windows systems, so we'll convert the starttime to hex and just take the first 8 characters.
#if UNIX
.Append(proc.StartTime.ToFileTime().ToString("X8").Substring(1,8))
#else
.Append(proc.StartTime.ToFileTime().ToString(CultureInfo.InvariantCulture))
#endif
.Append('.')
.Append(proc.Id.ToString(CultureInfo.InvariantCulture))
.Append('.')
.Append(CleanAppDomainNameForPipeName(appDomainName))
.Append('.')
.Append(proc.ProcessName);
#if UNIX
int charsToTrim = pipeNameBuilder.Length - MaxNamedPipeNameSize;
if (charsToTrim > 0)
{
// TODO: In the case the pipe name is truncated, the user cannot connect to it using the cmdlet
// unless we add a `-Force` type switch as it attempts to validate the current process name
// matches the process name in the pipe name
pipeNameBuilder.Remove(MaxNamedPipeNameSize + 1, charsToTrim);
}
#endif
return pipeNameBuilder.ToString();
}
private static string CleanAppDomainNameForPipeName(string appDomainName)
{
// Pipe names cannot contain the ':' character. Remove unwanted characters.
return appDomainName.Replace(":", string.Empty).Replace(" ", string.Empty);
}
/// <summary>
/// Returns the current process AppDomain name.
/// </summary>
/// <returns>AppDomain Name string.</returns>
internal static string GetCurrentAppDomainName()
{
#if CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
return DefaultAppDomainName;
#else // Use the AppDomain in which current powershell is running
return AppDomain.CurrentDomain.IsDefaultAppDomain() ? DefaultAppDomainName : AppDomain.CurrentDomain.FriendlyName;
#endif
}
#endregion
}
/// <summary>
/// Native API for Named Pipes.
/// </summary>
internal static class NamedPipeNative
{
#region Pipe constants
// Pipe open modes
internal const uint PIPE_ACCESS_DUPLEX = 0x00000003;
internal const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
internal const uint PIPE_ACCESS_INBOUND = 0x00000001;
// Pipe modes
internal const uint PIPE_TYPE_BYTE = 0x00000000;
internal const uint PIPE_TYPE_MESSAGE = 0x00000004;
internal const uint FILE_FLAG_OVERLAPPED = 0x40000000;
internal const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const uint PIPE_WAIT = 0x00000000;
internal const uint PIPE_NOWAIT = 0x00000001;
internal const uint PIPE_READMODE_BYTE = 0x00000000;
internal const uint PIPE_READMODE_MESSAGE = 0x00000002;
internal const uint PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
internal const uint PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
// Pipe errors
internal const uint ERROR_FILE_NOT_FOUND = 2;
internal const uint ERROR_BROKEN_PIPE = 109;
internal const uint ERROR_PIPE_BUSY = 231;
internal const uint ERROR_NO_DATA = 232;
internal const uint ERROR_MORE_DATA = 234;
internal const uint ERROR_PIPE_CONNECTED = 535;
internal const uint ERROR_IO_INCOMPLETE = 996;
internal const uint ERROR_IO_PENDING = 997;
// File function constants
internal const uint GENERIC_READ = 0x80000000;
internal const uint GENERIC_WRITE = 0x40000000;
internal const uint GENERIC_EXECUTE = 0x20000000;
internal const uint GENERIC_ALL = 0x10000000;
internal const uint CREATE_NEW = 1;
internal const uint CREATE_ALWAYS = 2;
internal const uint OPEN_EXISTING = 3;
internal const uint OPEN_ALWAYS = 4;
internal const uint TRUNCATE_EXISTING = 5;
internal const uint SECURITY_IMPERSONATIONLEVEL_ANONYMOUS = 0;
internal const uint SECURITY_IMPERSONATIONLEVEL_IDENTIFICATION = 1;
internal const uint SECURITY_IMPERSONATIONLEVEL_IMPERSONATION = 2;
internal const uint SECURITY_IMPERSONATIONLEVEL_DELEGATION = 3;
// Infinite timeout
internal const uint INFINITE = 0xFFFFFFFF;
#endregion
#region Data structures
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
/// <summary>
/// The size, in bytes, of this structure. Set this value to the size of the SECURITY_ATTRIBUTES structure.
/// </summary>
public int NLength;
/// <summary>
/// A pointer to a security descriptor for the object that controls the sharing of it.
/// </summary>
public IntPtr LPSecurityDescriptor = IntPtr.Zero;
/// <summary>
/// A Boolean value that specifies whether the returned handle is inherited when a new process is created.
/// </summary>
public bool InheritHandle;
/// <summary>
/// Initializes a new instance of the SECURITY_ATTRIBUTES class.
/// </summary>
public SECURITY_ATTRIBUTES()
{
this.NLength = 12;
}
}
#endregion
#region Pipe methods
[DllImport(PinvokeDllNames.CreateNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafePipeHandle CreateNamedPipe(
string lpName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
SECURITY_ATTRIBUTES securityAttributes);
internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescriptorPinnedHandle, bool inheritHandle = false)
{
SECURITY_ATTRIBUTES securityAttributes = new NamedPipeNative.SECURITY_ATTRIBUTES();
securityAttributes.InheritHandle = inheritHandle;
securityAttributes.NLength = (int)Marshal.SizeOf(securityAttributes);
securityAttributes.LPSecurityDescriptor = securityDescriptorPinnedHandle.AddrOfPinnedObject();
return securityAttributes;
}
[DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern SafePipeHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport(PinvokeDllNames.WaitNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WaitNamedPipe(string lpNamedPipeName, uint nTimeOut);
[DllImport(PinvokeDllNames.ImpersonateNamedPipeClientDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
[DllImport(PinvokeDllNames.RevertToSelfDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RevertToSelf();
#endregion
}
/// <summary>
/// Event arguments for listener thread end event.
/// </summary>
internal sealed class ListenerEndedEventArgs : EventArgs
{
#region Properties
/// <summary>
/// Exception reason for listener end event. Can be null
/// which indicates listener thread end is not due to an error.
/// </summary>
public Exception Reason { get; }
/// <summary>
/// True if listener should be restarted after ending.
/// </summary>
public bool RestartListener { get; }
#endregion
#region Constructors
private ListenerEndedEventArgs() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="reason">Listener end reason.</param>
/// <param name="restartListener">Restart listener.</param>
public ListenerEndedEventArgs(
Exception reason,
bool restartListener)
{
Reason = reason;
RestartListener = restartListener;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeServerStream class, that
/// creates the named pipe server with process named pipe name,
/// having correct access restrictions, and provides a listener
/// thread loop.
/// </summary>
public sealed class RemoteSessionNamedPipeServer : IDisposable
{
#region Members
private readonly object _syncObject;
private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
private const string _threadName = "IPC Listener Thread";
private const int _namedPipeBufferSizeForRemoting = 32768;
private const int _maxPipePathLengthLinux = 108;
private const int _maxPipePathLengthMacOS = 104;
// Singleton server.
private static object s_syncObject;
internal static RemoteSessionNamedPipeServer IPCNamedPipeServer;
internal static bool IPCNamedPipeServerEnabled;
// Optional custom server.
private static RemoteSessionNamedPipeServer _customNamedPipeServer;
// Access mask constant taken from PipeSecurity access rights and is equivalent to
// PipeAccessRights.FullControl.
// See: https://msdn.microsoft.com/library/vstudio/bb348408(v=vs.100).aspx
//
private const int _pipeAccessMaskFullControl = 0x1f019f;
#endregion
#region Properties
/// <summary>
/// Returns the Named Pipe stream object.
/// </summary>
internal NamedPipeServerStream Stream { get; }
/// <summary>
/// Returns the Named Pipe name.
/// </summary>
internal string PipeName { get; }
/// <summary>
/// Returns true if listener is currently running.
/// </summary>
internal bool IsListenerRunning { get; private set; }
/// <summary>
/// Name of session configuration.
/// </summary>
internal string ConfigurationName { get; set; }
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
internal StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
internal StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
internal bool IsDisposed { get; private set; }
/// <summary>
/// Buffer size for PSRP fragmentor.
/// </summary>
internal static int NamedPipeBufferSizeForRemoting
{
get { return _namedPipeBufferSizeForRemoting; }
}
#endregion
#region Events
/// <summary>
/// Event raised when the named pipe server listening thread
/// ends.
/// </summary>
internal event EventHandler<ListenerEndedEventArgs> ListenerEnded;
#endregion
#region Constructors
/// <summary>
/// Creates a RemoteSessionNamedPipeServer with the current process and AppDomain information.
/// </summary>
/// <returns>RemoteSessionNamedPipeServer.</returns>
internal static RemoteSessionNamedPipeServer CreateRemoteSessionNamedPipeServer()
{
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
return new RemoteSessionNamedPipeServer(NamedPipeUtils.CreateProcessPipeName(
System.Diagnostics.Process.GetCurrentProcess(), appDomainName));
}
/// <summary>
/// Constructor. Creates named pipe server with provided pipe name.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeServer(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
_syncObject = new object();
PipeName = pipeName;
Stream = CreateNamedPipe(
serverName: ".",
namespaceName: "pipe",
coreName: pipeName,
securityDesc: GetServerPipeSecurity());
}
/// <summary>
/// Helper method to create a PowerShell transport named pipe via native API, along
/// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
/// </summary>
/// <param name="serverName">Named pipe server name.</param>
/// <param name="namespaceName">Named pipe namespace name.</param>
/// <param name="coreName">Named pipe core name.</param>
/// <param name="securityDesc"></param>
/// <returns>NamedPipeServerStream.</returns>
private NamedPipeServerStream CreateNamedPipe(
string serverName,
string namespaceName,
string coreName,
CommonSecurityDescriptor securityDesc)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
#if !UNIX
string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Create optional security attributes based on provided PipeSecurity.
NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
GCHandle? securityDescHandle = null;
if (securityDesc != null)
{
byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
securityDesc.GetBinaryForm(securityDescBuffer, 0);
securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
}
// Create named pipe.
SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
fullPipeName,
NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
1,
_namedPipeBufferSizeForRemoting,
_namedPipeBufferSizeForRemoting,
0,
securityAttributes);
int lastError = Marshal.GetLastWin32Error();
if (securityDescHandle != null)
{
securityDescHandle.Value.Free();
}
if (pipeHandle.IsInvalid)
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
}
// Create the .Net NamedPipeServerStream wrapper.
try
{
return new NamedPipeServerStream(
PipeDirection.InOut,
true, // IsAsync
false, // IsConnected
pipeHandle);
}
catch (Exception)
{
pipeHandle.Dispose();
throw;
}
#else
return new NamedPipeServerStream(
pipeName: coreName,
direction: PipeDirection.InOut,
maxNumberOfServerInstances: 1,
transmissionMode: PipeTransmissionMode.Byte,
options: PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly,
inBufferSize: _namedPipeBufferSizeForRemoting,
outBufferSize: _namedPipeBufferSizeForRemoting);
#endif
}
static RemoteSessionNamedPipeServer()
{
s_syncObject = new object();
// All PowerShell instances will start with the named pipe
// and listener created and running.
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
CreateProcessExitHandler();
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates the custom named pipe server with the given pipename.
/// </summary>
/// <param name="pipeName">The name of the pipe to create.</param>
public static void CreateCustomNamedPipeServer(string pipeName)
{
lock (s_syncObject)
{
if (_customNamedPipeServer != null && !_customNamedPipeServer.IsDisposed)
{
if (pipeName == _customNamedPipeServer.PipeName)
{
// we shouldn't recreate the server object if we're using the same pipeName
return;
}
// Dispose of the current pipe server so we can create a new one with the new pipeName
_customNamedPipeServer.Dispose();
}
if (!Platform.IsWindows)
{
int maxNameLength = (Platform.IsLinux ? _maxPipePathLengthLinux : _maxPipePathLengthMacOS) - Path.GetTempPath().Length;
if (pipeName.Length > maxNameLength)
{
throw new InvalidOperationException(
string.Format(
RemotingErrorIdStrings.CustomPipeNameTooLong,
maxNameLength,
pipeName,
pipeName.Length));
}
}
try
{
try
{
_customNamedPipeServer = new RemoteSessionNamedPipeServer(pipeName);
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
_customNamedPipeServer.ListenerEnded += OnCustomNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
_customNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
_customNamedPipeServer = null;
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Starts named pipe server listening thread. When a client connects this thread
/// makes a callback to implement the client communication. When the thread ends
/// this object is disposed and a new RemoteSessionNamedPipeServer must be created
/// and a new listening thread started to handle subsequent client connections.
/// </summary>
/// <param name="clientConnectCallback">Connection callback.</param>
internal void StartListening(
Action<RemoteSessionNamedPipeServer> clientConnectCallback)
{
if (clientConnectCallback == null)
{
throw new PSArgumentNullException(nameof(clientConnectCallback));
}
lock (_syncObject)
{
if (IsListenerRunning)
{
throw new InvalidOperationException(RemotingErrorIdStrings.NamedPipeAlreadyListening);
}
IsListenerRunning = true;
// Create listener thread.
Thread listenerThread = new Thread(ProcessListeningThread);
listenerThread.Name = _threadName;
listenerThread.IsBackground = true;
listenerThread.Start(clientConnectCallback);
}
}
internal static CommonSecurityDescriptor GetServerPipeSecurity()
{
#if UNIX
return null;
#else
// Built-in Admin SID
SecurityIdentifier adminSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1);
dacl.AddAccess(
AccessControlType.Allow,
adminSID,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
CommonSecurityDescriptor securityDesc = new CommonSecurityDescriptor(
false, false,
ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted,
null, null, null, dacl);
// Conditionally add User SID
bool isAdminElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
if (!isAdminElevated)
{
securityDesc.DiscretionaryAcl.AddAccess(
AccessControlType.Allow,
WindowsIdentity.GetCurrent().User,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
}
return securityDesc;
#endif
}
/// <summary>
/// Wait for client connection.
/// </summary>
private void WaitForConnection()
{
Stream.WaitForConnection();
}
/// <summary>
/// Process listening thread.
/// </summary>
/// <param name="state">Client callback delegate.</param>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
private void ProcessListeningThread(object state)
{
string processId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
Exception ex = null;
string userName = string.Empty;
bool restartListenerThread = true;
// Wait for connection.
try
{
// Begin listening for a client connect.
this.WaitForConnection();
try
{
#if UNIX
userName = System.Environment.UserName;
#else
userName = WindowsIdentity.GetCurrent().Name;
#endif
}
catch (System.Security.SecurityException) { }
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
// Create reader/writer streams.
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
}
catch (Exception e)
{
ex = e;
}
if (ex != null)
{
// Error during connection handling. Don't try to restart listening thread.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
Dispose();
return;
}
// Start server session on new connection.
ex = null;
try
{
Action<RemoteSessionNamedPipeServer> clientConnectCallback = state as Action<RemoteSessionNamedPipeServer>;
Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");
// Handle a new client connect by making the callback.
// The callback must handle all exceptions except
// for a named pipe disposed or disconnected exception
// which propagates up to the thread listener loop.
clientConnectCallback(this);
}
catch (IOException)
{
// Expected connection terminated.
}
catch (ObjectDisposedException)
{
// Expected from PS transport close/dispose.
}
catch (Exception e)
{
ex = e;
restartListenerThread = false;
}
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
if (ex == null)
{
// Normal listener exit.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
}
else
{
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
}
lock (_syncObject)
{
IsListenerRunning = false;
}
// Ensure this named pipe server object is disposed.
Dispose();
ListenerEnded.SafeInvoke(
this,
new ListenerEndedEventArgs(ex, restartListenerThread));
}
#endregion
#region Static Methods
/// <summary>
/// Ensures the namedpipe singleton server is running and waits for a client connection.
/// This is a blocking call that returns after the client connection ends.
/// This method supports PowerShell running in "NamedPipeServerMode", which is used for
/// PowerShell Direct Windows Server Container connection and management.
/// </summary>
/// <param name="configurationName">Name of the configuration to use.</param>
internal static void RunServerMode(string configurationName)
{
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
if (IPCNamedPipeServer == null)
{
throw new RuntimeException(RemotingErrorIdStrings.NamedPipeServerCannotStart);
}
IPCNamedPipeServer.ConfigurationName = configurationName;
ManualResetEventSlim clientConnectionEnded = new ManualResetEventSlim(false);
IPCNamedPipeServer.ListenerEnded -= OnIPCNamedPipeServerEnded;
IPCNamedPipeServer.ListenerEnded += (sender, e) =>
{
clientConnectionEnded.Set();
};
// Wait for server to service a single client connection.
clientConnectionEnded.Wait();
clientConnectionEnded.Dispose();
IPCNamedPipeServerEnabled = false;
}
/// <summary>
/// Creates the process named pipe server object singleton and
/// starts the client listening thread.
/// </summary>
internal static void CreateIPCNamedPipeServerSingleton()
{
lock (s_syncObject)
{
if (!IPCNamedPipeServerEnabled) { return; }
if (IPCNamedPipeServer == null || IPCNamedPipeServer.IsDisposed)
{
try
{
try
{
IPCNamedPipeServer = CreateRemoteSessionNamedPipeServer();
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
IPCNamedPipeServer.ListenerEnded += OnIPCNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
IPCNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
IPCNamedPipeServer = null;
}
}
}
}
private static void CreateProcessExitHandler()
{
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
IPCNamedPipeServerEnabled = false;
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
if (namedPipeServer != null)
{
try
{
// Terminate the IPC thread.
namedPipeServer.Dispose();
}
catch (ObjectDisposedException)
{
// Ignore if object already disposed.
}
catch (Exception)
{
// Don't throw an exception on the app domain unload event thread.
}
}
};
}
private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener)
{
CreateIPCNamedPipeServerSingleton();
}
}
private static void OnCustomNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener && sender is RemoteSessionNamedPipeServer server)
{
CreateCustomNamedPipeServer(server.PipeName);
}
}
private static void ClientConnectionCallback(RemoteSessionNamedPipeServer pipeServer)
{
// Create server mediator object and begin remote session with client.
NamedPipeProcessMediator.Run(
string.Empty,
pipeServer);
}
#endregion
}
/// <summary>
/// Base class for RemoteSessionNamedPipeClient and ContainerSessionNamedPipeClient.
/// </summary>
internal class NamedPipeClientBase : IDisposable
{
#region Members
private NamedPipeClientStream _clientPipeStream;
private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected string _pipeName;
#endregion
#region Properties
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Name of pipe.
/// </summary>
public string PipeName
{
get { return _pipeName; }
}
#endregion
#region Constructor
public NamedPipeClientBase()
{ }
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (_clientPipeStream != null)
{
try { _clientPipeStream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Methods
/// <summary>
/// Connect to named pipe server. This is a blocking call until a
/// connection occurs or the timeout time has elapsed.
/// </summary>
/// <param name="timeout">Connection attempt timeout in milliseconds.</param>
public void Connect(
int timeout)
{
// Uses Native API to connect to pipe and return NamedPipeClientStream object.
_clientPipeStream = DoConnect(timeout);
// Create reader/writer streams.
TextReader = new StreamReader(_clientPipeStream);
TextWriter = new StreamWriter(_clientPipeStream);
TextWriter.AutoFlush = true;
_tracer.WriteMessage("NamedPipeClientBase", "Connect", Guid.Empty,
"Connection started on pipe: {0}", _pipeName);
}
/// <summary>
/// Closes the named pipe.
/// </summary>
public void Close()
{
if (_clientPipeStream != null)
{
_clientPipeStream.Dispose();
}
}
public virtual void AbortConnect()
{ }
protected virtual NamedPipeClientStream DoConnect(int timeout)
{
return null;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server.
/// </summary>
internal sealed class RemoteSessionNamedPipeClient : NamedPipeClientBase
{
#region Members
private volatile bool _connecting;
#endregion
#region Constructors
private RemoteSessionNamedPipeClient()
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process object.
/// </summary>
/// <param name="process">Target process object for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(
System.Diagnostics.Process process, string appDomainName) :
this(NamedPipeUtils.CreateProcessPipeName(process, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process Id.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(
int procId, string appDomainName) :
this(NamedPipeUtils.CreateProcessPipeName(procId, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on name argument.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeClient(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
_pipeName = pipeName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="serverName"></param>
/// <param name="namespaceName"></param>
/// <param name="coreName"></param>
internal RemoteSessionNamedPipeClient(
string serverName,
string namespaceName,
string coreName)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
_pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
#endregion
#region Public Methods
/// <summary>
/// Abort connection attempt.
/// </summary>
public override void AbortConnect()
{
_connecting = false;
}
#endregion
#region Protected Methods
protected override NamedPipeClientStream DoConnect(int timeout)
{
// Repeatedly attempt connection to pipe until timeout expires.
int startTime = Environment.TickCount;
int elapsedTime = 0;
_connecting = true;
NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName,
direction: PipeDirection.InOut,
options: PipeOptions.Asynchronous);
namedPipeClientStream.Connect();
do
{
if (!namedPipeClientStream.IsConnected)
{
Thread.Sleep(100);
elapsedTime = unchecked(Environment.TickCount - startTime);
continue;
}
_connecting = false;
return namedPipeClientStream;
} while (_connecting && (elapsedTime < timeout));
_connecting = false;
throw new TimeoutException(RemotingErrorIdStrings.ConnectNamedPipeTimeout);
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server inside Windows Server container.
/// </summary>
internal sealed class ContainerSessionNamedPipeClient : NamedPipeClientBase
{
#region Constructors
/// <summary>
/// Constructor. Creates Named Pipe based on process Id, app domain name and container object root path.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
/// <param name="containerObRoot">Container OB root.</param>
public ContainerSessionNamedPipeClient(
int procId,
string appDomainName,
string containerObRoot)
{
if (string.IsNullOrEmpty(containerObRoot))
{
throw new PSArgumentNullException(nameof(containerObRoot));
}
//
// Named pipe inside Windows Server container is under different name space.
//
_pipeName = containerObRoot + @"\Device\NamedPipe\" +
NamedPipeUtils.CreateProcessPipeName(procId, appDomainName);
}
#endregion
#region Protected Methods
/// <summary>
/// Helper method to open a named pipe via native APIs and return in
/// .Net NamedPipeClientStream wrapper object.
/// </summary>
protected override NamedPipeClientStream DoConnect(int timeout)
{
// Create pipe flags.
uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED;
//
// WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly
// attempt connection to pipe server until timeout expires.
//
int startTime = Environment.TickCount;
int elapsedTime = 0;
SafePipeHandle pipeHandle = null;
do
{
// Get handle to pipe.
pipeHandle = NamedPipeNative.CreateFile(
_pipeName,
NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE,
0,
IntPtr.Zero,
NamedPipeNative.OPEN_EXISTING,
pipeFlags,
IntPtr.Zero);
int lastError = Marshal.GetLastWin32Error();
if (pipeHandle.IsInvalid)
{
if (lastError == NamedPipeNative.ERROR_FILE_NOT_FOUND)
{
elapsedTime = unchecked(Environment.TickCount - startTime);
Thread.Sleep(100);
continue;
}
else
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotConnectContainerNamedPipe, lastError));
}
}
else
{
break;
}
} while (elapsedTime < timeout);
try
{
return new NamedPipeClientStream(
PipeDirection.InOut,
true,
true,
pipeHandle);
}
catch (Exception)
{
pipeHandle.Dispose();
throw;
}
}
#endregion
}
}
| 36.631347 | 167 | 0.577498 | [
"MIT"
] | Global19/PowerShell | src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs | 49,782 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.