content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using WPILib.Commands;
namespace WPILib.Buttons
{
/// <summary>
/// An internal class of <see cref="Trigger"/>. The user should ignore this, it is
/// only public to interface between packages
/// </summary>
public abstract class ButtonScheduler
{
/// <summary>
/// True if the button was pressed last.
/// </summary>
protected bool m_pressedLast;
/// <summary>
/// The button trigger.
/// </summary>
protected readonly Trigger m_button;
/// <summary>
/// The button command.
/// </summary>
protected readonly Command m_command;
/// <summary>
/// Creates a new <see cref="ButtonScheduler"/>.
/// </summary>
/// <param name="last">True if the button was last pressed.</param>
/// <param name="button">The button trigger.</param>
/// <param name="orders">The button command.</param>
protected ButtonScheduler(bool last, Trigger button, Command orders)
{
m_pressedLast = last;
m_button = button;
m_command = orders;
}
/// <summary>
/// Executes the trigger.
/// </summary>
public abstract void Execute();
/// <summary>
/// Starts the button scheduler.
/// </summary>
public void Start()
{
Scheduler.Instance.AddButton(this);
}
}
/// <summary>
/// A derivation of <see cref="ButtonScheduler"/>. The user should ignore this.
/// It shouldn't be viewable from user code anyway.
/// </summary>
internal class PressedButtonScheduler : ButtonScheduler
{
public PressedButtonScheduler(bool last, Trigger button, Command orders)
: base(last, button, orders)
{
}
public override void Execute()
{
if (m_button.Grab())
{
if (!m_pressedLast)
{
m_pressedLast = true;
m_command.Start();
}
}
else
{
m_pressedLast = false;
}
}
}
/// <summary>
/// A derivation of <see cref="ButtonScheduler"/>. The user should ignore this.
/// It shouldn't be viewable from user code anyway.
/// </summary>
internal class ReleasedButtonScheduler : ButtonScheduler
{
public ReleasedButtonScheduler(bool last, Trigger button, Command orders)
: base(last, button, orders)
{
}
public override void Execute()
{
if (m_button.Grab())
{
m_pressedLast = true;
}
else
{
if (m_pressedLast)
{
m_pressedLast = false;
m_command.Start();
}
}
}
}
/// <summary>
/// A derivation of <see cref="ButtonScheduler"/>. The user should ignore this.
/// It shouldn't be viewable from user code anyway.
/// </summary>
internal class HeldButtonScheduler : ButtonScheduler
{
public HeldButtonScheduler(bool last, Trigger button, Command orders)
: base(last, button, orders)
{
}
public override void Execute()
{
if (m_button.Grab())
{
m_pressedLast = true;
m_command.Start();
}
else
{
if (m_pressedLast)
{
m_pressedLast = false;
m_command.Cancel();
}
}
}
}
/// <summary>
/// A derivation of <see cref="ButtonScheduler"/>. The user should ignore this.
/// It shouldn't be viewable from user code anyway.
/// </summary>
internal class CancelButtonScheduler : ButtonScheduler
{
public CancelButtonScheduler(bool last, Trigger button, Command orders)
: base(last, button, orders)
{
}
public override void Execute()
{
if (m_button.Grab())
{
if (!m_pressedLast)
{
m_pressedLast = true;
m_command.Cancel();
}
else
{
m_pressedLast = false;
}
}
}
}
/// <summary>
/// A derivation of <see cref="ButtonScheduler"/>. The user should ignore this.
/// It shouldn't be viewable from user code anyway.
/// </summary>
internal class ToggleButtonScheduler : ButtonScheduler
{
public ToggleButtonScheduler(bool last, Trigger button, Command orders)
: base(last, button, orders)
{
}
public override void Execute()
{
if (m_button.Grab())
{
if (!m_pressedLast)
{
m_pressedLast = true;
if (m_command.IsRunning())
{
m_command.Cancel();
}
else
{
m_command.Start();
}
}
}
else
{
m_pressedLast = false;
}
}
}
}
| 26.653659 | 86 | 0.471999 | [
"MIT"
] | Team-1922/OzWPILib.NET | WPILib/Buttons/ButtonSchedulers.cs | 5,466 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.9
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace RakNet {
using System;
using System.Runtime.InteropServices;
public class AddressOrGUID : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn;
internal AddressOrGUID(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(AddressOrGUID obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
~AddressOrGUID() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
RakNetPINVOKE.delete_AddressOrGUID(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
}
public static implicit operator AddressOrGUID(SystemAddress systemAddress)
{
return new AddressOrGUID(systemAddress);
}
public static implicit operator AddressOrGUID(RakNetGUID guid)
{
return new AddressOrGUID(guid);
}
public RakNetGUID rakNetGuid {
set {
RakNetPINVOKE.AddressOrGUID_rakNetGuid_set(swigCPtr, RakNetGUID.getCPtr(value));
}
get {
IntPtr cPtr = RakNetPINVOKE.AddressOrGUID_rakNetGuid_get(swigCPtr);
RakNetGUID ret = (cPtr == IntPtr.Zero) ? null : new RakNetGUID(cPtr, false);
return ret;
}
}
public SystemAddress systemAddress {
set {
RakNetPINVOKE.AddressOrGUID_systemAddress_set(swigCPtr, SystemAddress.getCPtr(value));
}
get {
IntPtr cPtr = RakNetPINVOKE.AddressOrGUID_systemAddress_get(swigCPtr);
SystemAddress ret = (cPtr == IntPtr.Zero) ? null : new SystemAddress(cPtr, false);
return ret;
}
}
public ushort GetSystemIndex() {
ushort ret = RakNetPINVOKE.AddressOrGUID_GetSystemIndex(swigCPtr);
return ret;
}
public bool IsUndefined() {
bool ret = RakNetPINVOKE.AddressOrGUID_IsUndefined(swigCPtr);
return ret;
}
public void SetUndefined() {
RakNetPINVOKE.AddressOrGUID_SetUndefined(swigCPtr);
}
public static uint ToInteger(AddressOrGUID aog) {
uint ret = RakNetPINVOKE.AddressOrGUID_ToInteger(AddressOrGUID.getCPtr(aog));
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public string ToString(bool writePort) {
string ret = RakNetPINVOKE.AddressOrGUID_ToString(swigCPtr, writePort);
return ret;
}
public AddressOrGUID() : this(RakNetPINVOKE.new_AddressOrGUID__SWIG_0(), true) {
}
public AddressOrGUID(AddressOrGUID input) : this(RakNetPINVOKE.new_AddressOrGUID__SWIG_1(AddressOrGUID.getCPtr(input)), true) {
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public AddressOrGUID(SystemAddress input) : this(RakNetPINVOKE.new_AddressOrGUID__SWIG_2(SystemAddress.getCPtr(input)), true) {
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public AddressOrGUID(Packet packet) : this(RakNetPINVOKE.new_AddressOrGUID__SWIG_3(Packet.getCPtr(packet)), true) {
}
public AddressOrGUID(RakNetGUID input) : this(RakNetPINVOKE.new_AddressOrGUID__SWIG_4(RakNetGUID.getCPtr(input)), true) {
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
}
public AddressOrGUID CopyData(AddressOrGUID input) {
AddressOrGUID ret = new AddressOrGUID(RakNetPINVOKE.AddressOrGUID_CopyData__SWIG_0(swigCPtr, AddressOrGUID.getCPtr(input)), false);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public AddressOrGUID CopyData(SystemAddress input) {
AddressOrGUID ret = new AddressOrGUID(RakNetPINVOKE.AddressOrGUID_CopyData__SWIG_1(swigCPtr, SystemAddress.getCPtr(input)), false);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public AddressOrGUID CopyData(RakNetGUID input) {
AddressOrGUID ret = new AddressOrGUID(RakNetPINVOKE.AddressOrGUID_CopyData__SWIG_2(swigCPtr, RakNetGUID.getCPtr(input)), false);
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public bool Equals(AddressOrGUID right) {
bool ret = RakNetPINVOKE.AddressOrGUID_Equals(swigCPtr, AddressOrGUID.getCPtr(right));
if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
}
| 33.662162 | 135 | 0.721798 | [
"BSD-2-Clause"
] | noblewhale/RakNetZebStyle | DependentExtensions/Swig/SwigWindowsCSharpSample/SwigTestApp/SwigFiles/AddressOrGUID.cs | 4,982 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Equinor.ProCoSys.Preservation.Command.TagFunctionCommands.UpdateRequirements;
using Equinor.ProCoSys.Preservation.Domain;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.TagFunctionAggregate;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.RequirementTypeAggregate;
using Equinor.ProCoSys.Preservation.MainApi.TagFunction;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Equinor.ProCoSys.Preservation.Command.Tests.TagFunctionCommands.UpdateRequirements
{
[TestClass]
public class UpdateRequirementsCommandHandlerTests : CommandHandlerTestsBase
{
private readonly string TagFunctionCode = "TFC";
private readonly string RegisterCode = "RC";
private readonly string PCSDescription = "PCSDescription";
private RequirementDefinition _reqDef1;
private RequirementDefinition _reqDef2;
private const int ReqDefId1 = 99;
private const int ReqDefId2 = 199;
private const int Interval1 = 2;
private const int Interval2 = 3;
private const int Interval3 = 4;
private TagFunction _tfAddedToRepository;
private Mock<ITagFunctionRepository> _tfRepositoryMock;
private Mock<IRequirementTypeRepository> _rtRepositoryMock;
private Mock<ITagFunctionApiService> _tagFunctionApiServiceMock;
private UpdateRequirementsCommand _commandWithTwoRequirements;
private UpdateRequirementsCommand _commandWithoutRequirements;
private UpdateRequirementsCommandHandler _dut;
[TestInitialize]
public void Setup()
{
// Arrange
_rtRepositoryMock = new Mock<IRequirementTypeRepository>();
var rdMock1 = new Mock<RequirementDefinition>();
rdMock1.SetupGet(x => x.Id).Returns(ReqDefId1);
rdMock1.SetupGet(x => x.Plant).Returns(TestPlant);
_reqDef1 = rdMock1.Object;
var rdMock2 = new Mock<RequirementDefinition>();
rdMock2.SetupGet(x => x.Id).Returns(ReqDefId2);
rdMock2.SetupGet(x => x.Plant).Returns(TestPlant);
_reqDef2 = rdMock2.Object;
_rtRepositoryMock
.Setup(r => r.GetRequirementDefinitionsByIdsAsync(new List<int> {ReqDefId1, ReqDefId2}))
.Returns(Task.FromResult(new List<RequirementDefinition> {rdMock1.Object, rdMock2.Object}));
_tagFunctionApiServiceMock = new Mock<ITagFunctionApiService>();
_tagFunctionApiServiceMock.Setup(t => t.TryGetTagFunctionAsync(TestPlant, TagFunctionCode, RegisterCode))
.Returns(Task.FromResult(new PCSTagFunction
{
Code = TagFunctionCode,
Description = PCSDescription,
RegisterCode = RegisterCode
}));
_commandWithTwoRequirements = new UpdateRequirementsCommand(TagFunctionCode, RegisterCode,
new List<RequirementForCommand>
{
new RequirementForCommand(ReqDefId1, Interval1),
new RequirementForCommand(ReqDefId2, Interval2),
});
_commandWithoutRequirements = new UpdateRequirementsCommand(TagFunctionCode, RegisterCode, null);
_tfRepositoryMock = new Mock<ITagFunctionRepository>();
_tfRepositoryMock
.Setup(x => x.Add(It.IsAny<TagFunction>()))
.Callback<TagFunction>(tf =>
{
_tfAddedToRepository = tf;
});
_dut = new UpdateRequirementsCommandHandler(
_tfRepositoryMock.Object,
_rtRepositoryMock.Object,
UnitOfWorkMock.Object,
PlantProviderMock.Object,
_tagFunctionApiServiceMock.Object);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldAddTagFunctionWithRequirementsToRepository_WhenTagFunctionNotExists()
{
// Arrange
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult((TagFunction)null));
// Act
await _dut.Handle(_commandWithTwoRequirements, default);
// Assert
Assert.AreEqual(TagFunctionCode, _tfAddedToRepository.Code);
Assert.AreEqual(PCSDescription, _tfAddedToRepository.Description);
Assert.AreEqual(RegisterCode, _tfAddedToRepository.RegisterCode);
Assert.AreEqual(2, _tfAddedToRepository.Requirements.Count);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldAddTagFunctionWithoutRequirementsToRepository_WhenTagFunctionNotExists()
{
// Arrange
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult((TagFunction)null));
// Act
await _dut.Handle(_commandWithoutRequirements, default);
// Assert
Assert.AreEqual(TagFunctionCode, _tfAddedToRepository.Code);
Assert.AreEqual(RegisterCode, _tfAddedToRepository.RegisterCode);
Assert.AreEqual(0, _tfAddedToRepository.Requirements.Count);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldNotAddAnyTagFunctionToRepository_WhenTagFunctionAlreadyExists()
{
// Arrange
var tagFunction = new TagFunction(TestPlant, TagFunctionCode, "", RegisterCode);
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult(tagFunction));
// Act
var result = await _dut.Handle(_commandWithTwoRequirements, default);
// Assert
Assert.AreEqual(0, result.Errors.Count);
Assert.IsNull(_tfAddedToRepository);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldAddNewRequirementsToExistingTagFunction()
{
// Arrange
var tagFunction = new TagFunction(TestPlant, TagFunctionCode, "", RegisterCode);
Assert.AreEqual(0, tagFunction.Requirements.Count);
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult(tagFunction));
// Act
await _dut.Handle(_commandWithTwoRequirements, default);
// Assert
Assert.AreEqual(2, tagFunction.Requirements.Count);
AssertRequirement(tagFunction.Requirements, ReqDefId1, Interval1);
AssertRequirement(tagFunction.Requirements, ReqDefId2, Interval2);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldUpdateRequirementsInExistingTagFunction_WhenNewIntervals()
{
// Arrange
var tagFunction = new TagFunction(TestPlant, TagFunctionCode, "", RegisterCode);
tagFunction.AddRequirement(new TagFunctionRequirement(TestPlant, Interval3, _reqDef1));
tagFunction.AddRequirement(new TagFunctionRequirement(TestPlant, Interval3, _reqDef2));
Assert.AreEqual(2, tagFunction.Requirements.Count);
AssertRequirement(tagFunction.Requirements, ReqDefId1, Interval3);
AssertRequirement(tagFunction.Requirements, ReqDefId2, Interval3);
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult(tagFunction));
// Act
await _dut.Handle(_commandWithTwoRequirements, default);
// Assert
Assert.AreEqual(2, tagFunction.Requirements.Count);
AssertRequirement(tagFunction.Requirements, ReqDefId1, Interval1);
AssertRequirement(tagFunction.Requirements, ReqDefId2, Interval2);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldRemoveRequirementsFromExistingTagFunction()
{
// Arrange
var tagFunction = new TagFunction(TestPlant, TagFunctionCode, "", RegisterCode);
tagFunction.AddRequirement(new TagFunctionRequirement(TestPlant, Interval3, _reqDef1));
tagFunction.AddRequirement(new TagFunctionRequirement(TestPlant, Interval3, _reqDef2));
Assert.AreEqual(2, tagFunction.Requirements.Count);
AssertRequirement(tagFunction.Requirements, ReqDefId1, Interval3);
AssertRequirement(tagFunction.Requirements, ReqDefId2, Interval3);
_tfRepositoryMock
.Setup(r => r.GetByCodesAsync(TagFunctionCode, RegisterCode)).Returns(Task.FromResult(tagFunction));
// Act
await _dut.Handle(_commandWithoutRequirements, default);
// Assert
Assert.AreEqual(0, tagFunction.Requirements.Count);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldSave()
{
// Act
await _dut.Handle(_commandWithTwoRequirements, default);
// Assert
UnitOfWorkMock.Verify(u => u.SaveChangesAsync(default), Times.Once);
}
private void AssertRequirement(IReadOnlyCollection<TagFunctionRequirement> requirements, int reqDefId, int interval)
{
var req = requirements.SingleOrDefault(r => r.RequirementDefinitionId == reqDefId);
Assert.IsNotNull(req);
Assert.AreEqual(interval, req.IntervalWeeks);
}
[TestMethod]
public async Task HandlingUpdateRequirementsCommand_ShouldNotSetRowVersion_WhenTagFunctionAdded()
{
// Act
var result = await _dut.Handle(_commandWithoutRequirements, default);
// Assert
Assert.AreEqual(0, result.Errors.Count);
// In real life EF Core will create a new RowVersion when save.
// Since UnitOfWorkMock is a Mock this will not happen here, so we assert that RowVersion is set from command
var defaultRowVersion = "AAAAAAAAAAA=";
Assert.AreEqual(defaultRowVersion, result.Data);
Assert.AreEqual(defaultRowVersion, _tfAddedToRepository.RowVersion.ConvertToString());
}
}
}
| 45.4329 | 138 | 0.663649 | [
"MIT"
] | equinor/pcs-preservation-api | src/tests/Equinor.ProCoSys.Preservation.Command.Tests/TagFunctionCommands/UpdateRequirements/UpdateRequirementsCommandHandlerTests.cs | 10,497 | C# |
using Serveur.Controllers.Server;
using Serveur.Packets;
using ZeroFormatter;
namespace MosaiqueServeur.Packets.ServerPackets
{
[ZeroFormattable]
public class DoLoadRegistryKey : IPackets
{
public override TypePackets Type
{
get
{
return TypePackets.DoLoadRegistryKey;
}
}
[Index(0)]
public virtual string rootKeyName { get; set; }
public DoLoadRegistryKey()
{
}
public DoLoadRegistryKey(string rootKeyName)
{
this.rootKeyName = rootKeyName;
}
public void Execute(ClientMosaique client)
{
client.send(this);
}
}
}
| 20.111111 | 55 | 0.564917 | [
"MIT"
] | LegionXKP/MosaiqueRAT | MosaiqueServer/Packets/ServerPackets/DoLoadRegistryKey.cs | 726 | C# |
using System.Resources;
using System.Security.Principal;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
using YIF.Core.Domain.ApiModels.RequestApiModels;
using YIF.Core.Domain.ApiModels.ResponseApiModels;
using YIF.Core.Domain.ServiceInterfaces;
using YIF_Backend.Controllers;
namespace YIF_XUnitTests.Unit.YIF_Backend.Controllers
{
public class InstitutionOfEducationModeratorControllerTests
{
private readonly Mock<ResourceManager> _resourceManager;
private readonly Mock<IIoEModeratorService> _ioEModeratorService;
private readonly Mock<HttpContext> _httpContext;
private readonly InstitutionOfEducationModeratorController _testControl;
private readonly GenericIdentity _fakeIdentity;
private readonly string[] _roles;
private readonly GenericPrincipal _principal;
public InstitutionOfEducationModeratorControllerTests()
{
_ioEModeratorService = new Mock<IIoEModeratorService>();
_resourceManager = new Mock<ResourceManager>();
_testControl = new InstitutionOfEducationModeratorController(_ioEModeratorService.Object, _resourceManager.Object);
_httpContext = new Mock<HttpContext>();
_fakeIdentity = new GenericIdentity("User");
_roles = new string[] { "InstitutionOfEducationModerator" };
_principal = new GenericPrincipal(_fakeIdentity, _roles);
_testControl.ControllerContext = new ControllerContext()
{
HttpContext = _httpContext.Object
};
}
[Fact]
public async Task AddSpecialty_EndpointReturnsOk()
{
//Arrange
_httpContext.SetupGet(x => x.User).Returns(_principal);
_ioEModeratorService.Setup(x => x.AddSpecialtyToIoe(It.IsAny<SpecialtyToInstitutionOfEducationPostApiModel>()));
//Act
var result = await _testControl.AddSpecialtyToIoE(new SpecialtyToInstitutionOfEducationPostApiModel());
//Assert
Assert.IsType<OkResult>(result);
}
[Fact]
public async Task UpdateSpecialtyDescription_EndpointReturnsOk()
{
//Arrange
var response = new ResponseApiModel<DescriptionResponseApiModel>(new DescriptionResponseApiModel(), true);
_ioEModeratorService.Setup(x => x.UpdateSpecialtyDescription(It.IsAny<SpecialtyDescriptionUpdateApiModel>())).ReturnsAsync(response);
//Act
var result = await _testControl.UpdateSpecialtyDescription(It.IsAny<SpecialtyDescriptionUpdateApiModel>());
//Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async void DeleteSpecialtyFromInstitutionOfEducation_ShouldReturnNoContent_IfEverythingIsOk()
{
// Arrange
_ioEModeratorService.Setup(x => x.DeleteSpecialtyToIoe(It.IsAny<SpecialtyToInstitutionOfEducationPostApiModel>()));
// Act
var result = await _testControl.DeleteSpecialtyFromIoE(new SpecialtyToInstitutionOfEducationPostApiModel());
// Assert
Assert.IsType<NoContentResult>(result);
}
[Fact]
public async Task GetSpecialtyDescription_ShouldReturnOk_IfEverythingIsOk()
{
//Arrange
var claims = new List<Claim>()
{
new Claim("id", "id"),
};
var identity = new ClaimsIdentity(claims, "Test");
var claimsPrincipal = new ClaimsPrincipal(identity);
_httpContext.SetupGet(hc => hc.User).Returns(claimsPrincipal);
var response = new ResponseApiModel<SpecialtyToInstitutionOfEducationResponseApiModel>(new SpecialtyToInstitutionOfEducationResponseApiModel(), true);
_ioEModeratorService.Setup(x => x.GetSpecialtyToIoEDescription(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(response);
//Act
var result = await _testControl.GetSpecialtyDescription(It.IsAny<string>());
//Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetAdminByUserId_EndpointReturnsOk()
{
//Arrange
var claims = new List<Claim>()
{
new Claim("id", "id"),
};
var identity = new ClaimsIdentity(claims, "Test");
var claimsPrincipal = new ClaimsPrincipal(identity);
_httpContext.SetupGet(hc => hc.User).Returns(claimsPrincipal);
var response = new ResponseApiModel<IoEAdminForIoEModeratorResponseApiModel>(new IoEAdminForIoEModeratorResponseApiModel(), true);
_ioEModeratorService.Setup(x => x.GetIoEAdminByUserId(It.IsAny<string>())).ReturnsAsync(response);
var result = await _testControl.GetAdminByUserId();
//Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async void GetIoEInfoByUserId_ShouldReturnSuccess()
{
// Arrange
var claims = new List<Claim>()
{
new Claim("id", "id"),
};
var identity = new ClaimsIdentity(claims, "Test");
var claimsPrincipal = new ClaimsPrincipal(identity);
_httpContext.SetupGet(hc => hc.User).Returns(claimsPrincipal);
_ioEModeratorService.Setup(x => x.GetIoEInfoByUserId(It.IsAny<string>()))
.ReturnsAsync(new ResponseApiModel<IoEInformationResponseApiModel>());
// Act
var result = await _testControl.GetIoEInfoByUserId();
// Assert
Assert.IsType<OkObjectResult>(result);
}
}
}
| 40.129252 | 162 | 0.653162 | [
"MIT"
] | ita-social-projects/YIF_Backend | YIF_XUnitTests/Unit/YIF_Backend/Controllers/InstitutionOfEducationModeratorControllerTests.cs | 5,901 | 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.Text;
namespace Org.BouncyCastle.Crypto.Xml
{
internal interface ICanonicalXmlCDataSection
{
bool IsInNodeSet { get; set; }
void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc);
void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc);
}
} | 35.3125 | 103 | 0.752212 | [
"MIT"
] | EdoardoLenzi9/bc-xml-security | interfaces/CanonicalXml/ICanonicalXmlCDataSection.cs | 567 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
namespace WebDynamic
{
/**
* Le classe Mymethods permet de récupérer les documents depuis un éxécutable.
* Elle contient une méthode <mymethod>(string <parm1_value>, string <param2_value>) qui sera appelée sur une invocation de type
* http://localhost:8080/<ceque_vousvoulez>/<ceque_vousvoulez>/<MyMethod>?param1=<ceque_vousvoulez>& param2=<ceque_vousvoulez>
* @author Kevin Ushaka Kubwawe
*
*/
public class Mymethods
{
public Mymethods()
{
}
public string Exec(string param1, string param2)
{
//
// Set up the process with the ProcessStartInfo class.
// https://www.dotnetperls.com/process
//
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"C:\Users\keush\Projects\soc-ws-20-21\eiin839\TD2\Exec\bin\Debug\Exec.exe"; // Specify exe name.
start.Arguments = param1 + " " + param2; // Specify arguments.
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
//
// Start the process.
//
using (Process process = Process.Start(start))
{
//
// Read in all the text from the process with the StreamReader.
//
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.WriteLine(result);
return result;
}
}
}
public string Method(string param1, string param2)
{
return "<HTML><BODY> Hello " + param1 + " et " + param2 + "</BODY></HTML>";
}
public string Incr(string param)
{
int val = int.Parse(param);
val++;
return "{ \"status\":200, \"val\":" + val + "}";
}
}
}
| 32.738462 | 135 | 0.547932 | [
"MIT"
] | kevinushaka/eiin839 | TD2/WebDynamic/Mymethods.cs | 2,136 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MTCAssistant.Tests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("MTCAssistant.Tests")]
[assembly: System.Reflection.AssemblyTitleAttribute("MTCAssistant.Tests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.833333 | 80 | 0.65239 | [
"MIT"
] | richross/MYVirtualAssist | src/MTCAssistant/MTCAssistant.Tests/obj/Debug/netcoreapp3.1/MTCAssistant.Tests.AssemblyInfo.cs | 1,004 | C# |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace NFCRing.UI.ViewModel.Services
{
public interface ITokenService
{
bool Ping();
/// <summary>
/// Get tokens, key - hash, value - name.
/// </summary>
Task<Dictionary<string, string>> GetTokensAsync(string userName);
Task RemoveTokenAsync(string token);
Task AddTokenAsync(string userName, string password, string token);
Task<string> GetNewTokenAsync(CancellationToken cancellationToken);
Task SendCancelAsync();
void UpdateTokenImage(string token, ImageData imageData);
ImageData GetTokenImage(string token);
Task UpdateNameAsync(string token, string name);
}
} | 25.9 | 75 | 0.676963 | [
"Apache-2.0"
] | LaudateCorpus1/Sesame | UI/NFCRing.UI.ViewModel/Services/ITokenService.cs | 779 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Workflow.Domains
{
/// <summary>
/// 处理者
/// </summary>
public interface IDealer
{
public Guid Id { get; }
public string Name { get; }
}
}
| 16.125 | 35 | 0.589147 | [
"MIT"
] | yitek/Workflow | dotnet/0.03/Workflow.Domains/IDealer.cs | 264 | C# |
namespace Sepes.Common.Interface
{
public interface IRequestIdService
{
string GetRequestId();
}
}
| 15.75 | 38 | 0.626984 | [
"MIT"
] | equinor/sepes | src/Sepes.Common/Interface/Service/IRequestIdService.cs | 128 | C# |
namespace PinvokeGen.Cli
{
public static class Program
{
public static void Main(string[] args)
{
}
}
}
| 14.1 | 46 | 0.539007 | [
"MIT"
] | mjcheetham/pinvokegen | src/pinvokegen/Program.cs | 143 | C# |
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EasyAbp.AbpHelper.Models;
using Elsa.Expressions;
using Elsa.Results;
using Elsa.Scripting.JavaScript;
using Elsa.Services.Models;
namespace EasyAbp.AbpHelper.Steps.Abp
{
public class ProjectInfoProviderStep : Step
{
public WorkflowExpression<string> BaseDirectory
{
get => GetState(() => new JavaScriptExpression<string>("BaseDirectory"));
set => SetState(value);
}
protected override async Task<ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
{
var baseDirectory = await context.EvaluateAsync(BaseDirectory, cancellationToken);
LogInput(() => baseDirectory);
TemplateType templateType;
if (Directory.EnumerateFiles(baseDirectory, "*.DbMigrator.csproj", SearchOption.AllDirectories).Any())
templateType = TemplateType.Application;
else if (Directory.EnumerateFiles(baseDirectory, "*.Host.Shared.csproj", SearchOption.AllDirectories).Any())
templateType = TemplateType.Module;
else
throw new NotSupportedException($"Unknown ABP project structure. Directory: {baseDirectory}");
// Assume the domain project must be existed for an ABP project
var domainCsprojFile = Directory.EnumerateFiles(baseDirectory, "*.Domain.csproj", SearchOption.AllDirectories).FirstOrDefault();
if (domainCsprojFile == null) throw new NotSupportedException($"Cannot find the domain project file. Make sure it is a valid ABP project. Directory: {baseDirectory}");
var fileName = Path.GetFileName(domainCsprojFile);
var fullName = fileName.RemovePostFix(".Domain.csproj");
UiFramework uiFramework;
if (Directory.EnumerateFiles(baseDirectory, "*.cshtml", SearchOption.AllDirectories).Any())
{
uiFramework = UiFramework.RazorPages;
if (templateType == TemplateType.Application)
{
context.SetVariable("AspNetCoreDir", Path.Combine(baseDirectory, "aspnet-core"));
}
else
{
context.SetVariable("AspNetCoreDir", baseDirectory);
}
}
else if (Directory.EnumerateFiles(baseDirectory, "app.module.ts", SearchOption.AllDirectories).Any())
{
uiFramework = UiFramework.Angular;
context.SetVariable("AspNetCoreDir", Path.Combine(baseDirectory, "aspnet-core"));
}
else
{
uiFramework = UiFramework.None;
context.SetVariable("AspNetCoreDir", baseDirectory);
}
var tiered = false;
if (templateType == TemplateType.Application) tiered = Directory.EnumerateFiles(baseDirectory, "*.IdentityServer.csproj").Any();
var projectInfo = new ProjectInfo(baseDirectory, fullName, templateType, uiFramework, tiered);
context.SetLastResult(projectInfo);
context.SetVariable("ProjectInfo", projectInfo);
LogOutput(() => projectInfo);
return Done();
}
}
} | 43.662338 | 179 | 0.635634 | [
"MIT"
] | SanchoWalden/AbpHelper.CLI | src/AbpHelper/Steps/Abp/ProjectInfoProviderStep.cs | 3,364 | C# |
using System;
using System.Web.Mvc;
using Microsoft.ApplicationInsights;
namespace MyFixIt.Infrastructure
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AiHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
{
//If customError is Off, then AI HTTPModule will report the exception
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
var ai = new TelemetryClient();
ai.TrackException(filterContext.Exception);
}
}
base.OnException(filterContext);
}
}
} | 36.666667 | 110 | 0.628409 | [
"Apache-2.0"
] | dzimchuk/azure-app-insights | C#/MyFixIt/Infrastructure/AiHandleErrorAttribute.cs | 882 | C# |
using System;
namespace uri2754
{
internal static class Saida8
{
private static void Main()
{
const double x = 234.345, y = 45.698;
Console.WriteLine($"{x:F6} - {y:F6}");
Console.WriteLine($"{x:F0} - {y:F0}");
Console.WriteLine($"{x:F1} - {y:F1}");
Console.WriteLine($"{x:F2} - {y:F2}");
Console.WriteLine($"{x:F3} - {y:F3}");
Console.WriteLine($"{x:e} - {y:e}");
Console.WriteLine($"{x:E} - {y:E}");
Console.WriteLine($"{x:G} - {y:G}");
Console.WriteLine($"{x:G} - {y:G}");
}
}
}
//using System;
//namespace uri2754
//{
// internal static class Saida8
// {
// private static void Main()
// {
// Console.WriteLine($"234.345000 - 45.698000");
// Console.WriteLine($"234 - 46");
// Console.WriteLine($"234.3 - 45.7");
// Console.WriteLine($"234.34 - 45.70");
// Console.WriteLine($"234.345 - 45.698");
// Console.WriteLine($"2.343450e+02 - 4.569800e+01");
// Console.WriteLine($"2.343450E+02 - 4.569800E+01");
// Console.WriteLine($"234.345 - 45.698");
// Console.WriteLine($"234.345 - 45.698");
// }
// }
//} | 30.857143 | 64 | 0.474537 | [
"MIT"
] | filimor/uri-online-judge-c-sharp | UriOnlineJudge/Iniciante/uri2754/Saida8.cs | 1,298 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TicTacToE1
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.521739 | 65 | 0.61583 | [
"MIT"
] | Ash200042123/SWE-4202---OOC-I | TicTacToE1/Program.cs | 520 | C# |
using SharpDX;
namespace Engine.PathFinding.RecastNavigation.Detour.Crowds
{
public class ObstacleCircle
{
/// <summary>
/// Position of the obstacle
/// </summary>
public Vector3 P { get; set; }
/// <summary>
/// Velocity of the obstacle
/// </summary>
public Vector3 Vel { get; set; }
/// <summary>
/// Desired velocity of the obstacle
/// </summary>
public Vector3 DVel { get; set; }
/// <summary>
/// Radius of the obstacle
/// </summary>
public float Rad { get; set; }
/// <summary>
/// Use for side selection during sampling.
/// </summary>
public Vector3 Dp { get; set; }
/// <summary>
/// Use for side selection during sampling.
/// </summary>
public Vector3 Np { get; set; }
};
}
| 27.121212 | 59 | 0.510615 | [
"MIT"
] | Selinux24/SharpDX-Tests | Engine.PathFinding.RecastNavigation/Detour/Crowds/ObstacleCircle.cs | 897 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using NBehave.Hooks;
using Mono.Reflection;
namespace NBehave.Fluent.Framework
{
public enum ScenarioFragment
{
Given,
When,
Then
}
public class ScenarioBuilder
{
private object _stepHelper;
private ScenarioDrivenSpecStepRunner _stepRunner;
private Scenario _scenario;
private readonly string _scenarioTitle;
private ScenarioFragment previousStage = ScenarioFragment.Given;
private readonly HooksCatalog hooksCatalog;
int stepsCalled;
private int stepsToRunBeforeAfterScenario;
protected Feature Feature { get; private set; }
protected Scenario Scenario
{
get
{
if (_scenario == null)
{
_scenario = new Scenario(_scenarioTitle, "");
Feature.AddScenario(Scenario);
}
return _scenario;
}
}
private ScenarioDrivenSpecStepRunner StepRunner
{
get { return _stepRunner ?? (_stepRunner = new ScenarioDrivenSpecStepRunner(_stepHelper)); }
}
public ScenarioBuilder(Feature feature, string scenarioTitle)
{
Feature = feature;
_scenarioTitle = scenarioTitle;
hooksCatalog = new HooksCatalog();
SetupHooks();
}
private void SetupHooks()
{
var h = new HooksParser(hooksCatalog);
h.FindHooks(GetTypeByCallStack());
}
private void SetHelperObject(object helper)
{
_stepHelper = helper;
}
private void AddStepAndExecute(ScenarioFragment currentStage, string step, Action inlineImplementation)
{
if (inlineImplementation != null)
StepRunner.RegisterImplementation(currentStage, step, inlineImplementation);
if (!Scenario.Steps.Any())
{
RunHooks<BeforeScenarioAttribute>();
CountStepsToRunBeforeCallingAfterScenario();
}
stepsCalled++;
var stringStep = AddStepToScenario(currentStage, step);
RunStep(currentStage, step, stringStep);
RunAfterScenario();
previousStage = currentStage;
var failure = stringStep.StepResult.Result as Failed;
if (failure != null)
{
throw new ApplicationException("Failed on step " + step, failure.Exception);
}
}
private readonly Type[] virtualCallsTo = new[] { typeof(IGivenFragment), typeof(IWhenFragment), typeof(IGivenFragment) };
private bool CallsNBehave(Instruction i)
{
var callvirt = i.OpCode.Name == "callvirt";
if (callvirt)
{
var m = (MethodInfo)i.Operand;
var returnType = m.ReturnParameter;
if (returnType != null)
return virtualCallsTo.Contains(returnType.ParameterType);
}
return false;
}
private StringStep AddStepToScenario(ScenarioFragment currentStage, string step)
{
var stringStep = CreateStringStep(currentStage, step);
Scenario.AddStep(stringStep);
return stringStep;
}
private void RunStep(ScenarioFragment currentStage, string step, StringStep stringStep)
{
var stepToRun = new StringStep(currentStage.ToString(), step, Scenario.Source);
try
{
RunHooks<BeforeStepAttribute>();
}
catch (Exception e)
{
stringStep.StepResult = new StepResult(stringStep, new Failed(e));
}
try
{
StepRunner.Run(stepToRun);
stringStep.StepResult = new StepResult(stringStep, stepToRun.StepResult.Result);
}
finally
{
RunHooks<AfterStepAttribute>();
}
}
private void RunAfterScenario()
{
if (stepsCalled == stepsToRunBeforeAfterScenario)
{
stepsCalled = 0;
stepsToRunBeforeAfterScenario = -1;
RunHooks<AfterScenarioAttribute>();
}
}
private void RunHooks<T>()
{
hooksCatalog.OfType<T>().ToList().ForEach(_ => _.Invoke());
}
private StringStep CreateStringStep(ScenarioFragment currentStage, string step)
{
string stepType = currentStage.ToString();
if (Scenario.Steps.Any() && previousStage == currentStage)
stepType = "And";
var stringStep = new StringStep(stepType, step, Scenario.Source);
return stringStep;
}
private Assembly GetTypeByCallStack()
{
int i = -1;
Type declaringType;
do
{
i++;
var stackFrame = new StackFrame(i);
declaringType = stackFrame.GetMethod().DeclaringType;
} while (declaringType.Assembly == typeof(ScenarioBuilder).Assembly);
return declaringType.Assembly;
}
private void CountStepsToRunBeforeCallingAfterScenario()
{
int i = -1;
StackFrame stackFrame;
do
{
i++;
stackFrame = new StackFrame(i);
} while (stackFrame.GetMethod().DeclaringType.Assembly == typeof(ScenarioBuilder).Assembly);
var instructions = Disassembler.GetInstructions(stackFrame.GetMethod())
.Where(CallsNBehave)
.ToList();
stepsToRunBeforeAfterScenario = instructions.Count;
}
internal class StartFragment : IScenarioBuilderStartWithHelperObject
{
private readonly ScenarioBuilder _builder;
public StartFragment(Feature feature)
: this(feature, null)
{
}
public StartFragment(Feature feature, string scenarioTitle)
{
_builder = new ScenarioBuilder(feature, scenarioTitle);
}
public IGivenFragment Given(string step)
{
return Given(step, null);
}
public IGivenFragment Given(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.Given, step, implementation);
return new GivenFragment(_builder);
}
public IScenarioBuilderStart WithHelperObject(object stepHelper)
{
_builder.SetHelperObject(stepHelper);
return this;
}
public IScenarioBuilderStart WithHelperObject<T>() where T : new()
{
_builder.SetHelperObject(new T());
return this;
}
}
internal class GivenFragment : IGivenFragment
{
private readonly ScenarioBuilder _builder;
public GivenFragment(ScenarioBuilder builder)
{
_builder = builder;
}
public IGivenFragment And(string step)
{
return And(step, null);
}
public IGivenFragment And(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.Given, step, implementation);
return this;
}
public IWhenFragment When(string step)
{
return When(step, null);
}
public IWhenFragment When(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.When, step, implementation);
return new WhenFragment(_builder);
}
}
internal class WhenFragment : IWhenFragment
{
private readonly ScenarioBuilder _builder;
public WhenFragment(ScenarioBuilder builder)
{
_builder = builder;
}
public IWhenFragment And(string step)
{
return And(step, null);
}
public IWhenFragment And(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.When, step, implementation);
return this;
}
public IThenFragment Then(string step)
{
return Then(step, null);
}
public IThenFragment Then(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.Then, step, implementation);
return new ThenFragment(_builder);
}
}
internal class ThenFragment : IThenFragment
{
private readonly ScenarioBuilder _builder;
public ThenFragment(ScenarioBuilder builder)
{
_builder = builder;
}
public IThenFragment And(string step)
{
return And(step, null);
}
public IThenFragment And(string step, Action implementation)
{
_builder.AddStepAndExecute(ScenarioFragment.Then, step, implementation);
return this;
}
}
}
}
| 31.987138 | 130 | 0.529152 | [
"BSD-3-Clause"
] | MorganPersson/NBehave | src/NBehave.Fluent.Framework/ScenarioBuilder.cs | 9,948 | 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 clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.CloudDirectory.Model
{
/// <summary>
/// Base class for ListObjectAttributes paginators.
/// </summary>
internal sealed partial class ListObjectAttributesPaginator : IPaginator<ListObjectAttributesResponse>, IListObjectAttributesPaginator
{
private readonly IAmazonCloudDirectory _client;
private readonly ListObjectAttributesRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListObjectAttributesResponse> Responses => new PaginatedResponse<ListObjectAttributesResponse>(this);
internal ListObjectAttributesPaginator(IAmazonCloudDirectory client, ListObjectAttributesRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListObjectAttributesResponse> IPaginator<ListObjectAttributesResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListObjectAttributesResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListObjectAttributes(_request);
nextToken = response.NextToken;
yield return response;
}
while (nextToken != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListObjectAttributesResponse> IPaginator<ListObjectAttributesResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListObjectAttributesResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListObjectAttributesAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (nextToken != null);
}
#endif
}
}
#endif | 39.645161 | 162 | 0.67399 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/_bcl45+netstandard/ListObjectAttributesPaginator.cs | 3,687 | C# |
using System;
namespace _08.Refactor_Volume_of_Pyramid
{
class Program
{
static void Main()
{
double Lenght, Width, Height = 0;
Console.Write("Length: ");
Lenght = double.Parse(Console.ReadLine());
Console.Write("Width: ");
Width = double.Parse(Console.ReadLine());
Console.Write("Height: ");
Height = double.Parse(Console.ReadLine());
double volume = ((Lenght * Width * Height) / 3);
Console.WriteLine("Pyramid Volume: {0:F2}", volume);
}
}
}
| 26.863636 | 64 | 0.532995 | [
"MIT"
] | vankatalp360/Programming-Fundamentals-2017 | Data Types and Variables-Lab/08.Refactor Volume of Pyramid/08.Refactor Volume of Pyramid.cs | 593 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Test.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.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>
/// Returns the cached ResourceManager instance used by this class.
/// </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("Test.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.28125 | 170 | 0.611191 | [
"MIT"
] | rahodges/Amns | Amns.GreyFox.Test/Properties/Resources.Designer.cs | 2,772 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Reflection_PropertyInfo_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Reflection.PropertyInfo);
args = new Type[]{};
method = type.GetMethod("GetGetMethod", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetGetMethod_0);
}
static StackObject* GetGetMethod_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo)typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.GetGetMethod();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| 36.307692 | 217 | 0.697564 | [
"MIT"
] | naivetang/2019MiniGame22 | Unity/Assets/Model/ILBinding/System_Reflection_PropertyInfo_Binding.cs | 1,888 | C# |
using System;
using System.Diagnostics;
namespace RockLib.Interop
{
partial class EmbeddedNativeLibrary
{
private class MaybeIntPtr
{
public MaybeIntPtr(IntPtr value)
{
Debug.Assert(value != IntPtr.Zero, "MaybeIntPtr.ctor(IntPtr value): value must be non-zero.");
Value = value;
}
public MaybeIntPtr(Exception[] exceptions)
{
Debug.Assert(exceptions != null, "MaybeIntPtr.ctor(Exception[] exceptions): exceptions parameter must not be null.");
Debug.Assert(exceptions.Length >= 1, "MaybeIntPtr.ctor(Exception[] exceptions): exceptions must contain at least one element.");
Exceptions = exceptions;
}
public IntPtr Value { get; private set; }
public Exception[] Exceptions { get; private set; }
public bool HasValue { get { return Value != IntPtr.Zero; } }
}
}
}
| 34.137931 | 144 | 0.582828 | [
"MIT"
] | RockLib/RockLib.EmbeddedNativeLibrary | RockLib.EmbeddedNativeLibrary.Shared/MaybeIntPtr.cs | 992 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GraphQL.Dummy;
using GraphQL.Language.AST;
using GraphQL.StarWars.Types;
using GraphQL.Types;
using GraphQL.Utilities;
using Shouldly;
using Xunit;
namespace GraphQL.Tests.Extensions
{
public class GraphQLExtensionsTests
{
public class IsValidDefaultTestData : IEnumerable<object[]>
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { new BooleanGraphType(), true, true };
yield return new object[] { new BooleanGraphType(), false, true };
yield return new object[] { new BooleanGraphType(), null, true };
yield return new object[] { new NonNullGraphType(new BooleanGraphType()), false, true };
yield return new object[] { new NonNullGraphType(new BooleanGraphType()), null, false };
yield return new object[] { new ListGraphType(new BooleanGraphType()), null, true };
yield return new object[] { new ListGraphType(new BooleanGraphType()), new object[] { true, false, null }, true };
yield return new object[] { new NonNullGraphType(new ListGraphType(new BooleanGraphType())), null, false };
yield return new object[] { new ListGraphType(new NonNullGraphType(new BooleanGraphType())), new object[] { true, false, null }, false };
yield return new object[] { new ListGraphType(new NonNullGraphType(new BooleanGraphType())), new object[] { true, false, true }, true };
yield return new object[] { new InputObjectGraphType<Person>(), null, true };
yield return new object[] { new NonNullGraphType(new InputObjectGraphType<Person>()), null, false };
yield return new object[] { new InputObjectGraphType<Person>(), new Person(), true };
yield return new object[] { new InputObjectGraphType<Person>(), "aaa", false };
// https://github.com/graphql-dotnet/graphql-dotnet/issues/2334
yield return new object[] { new ListGraphType(new BooleanGraphType()), true, true };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class IsValidDefaultExceptionTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { null, 0, new ArgumentNullException("type") };
yield return new object[] { new ObjectGraphType(), 0, new ArgumentOutOfRangeException("type", "Must provide Input Type, cannot use ObjectGraphType 'Object'") };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class ToASTTestData : IEnumerable<object[]>
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
public class PersonInputType : InputObjectGraphType<Person>
{
public override IValue ToAST(object value)
{
var person = (Person)value;
return new ObjectValue(new[]
{
new ObjectField("Name", new StringValue(person.Name)),
new ObjectField("Age", new IntValue(person.Age))
});
}
}
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { new BooleanGraphType(), true, new BooleanValue(true) };
yield return new object[] { new BooleanGraphType(), false, new BooleanValue(false) };
yield return new object[] { new BooleanGraphType(), null, new NullValue() };
yield return new object[] { new NonNullGraphType(new BooleanGraphType()), false, new BooleanValue(false) };
yield return new object[] { new ListGraphType(new BooleanGraphType()), null, new NullValue() };
yield return new object[] { new ListGraphType(new BooleanGraphType()), new object[] { true, false, null }, new ListValue(new IValue[] { new BooleanValue(true), new BooleanValue(false), new NullValue() }) };
yield return new object[] { new ListGraphType(new NonNullGraphType(new BooleanGraphType())), new object[] { true, false, true }, new ListValue(new IValue[] { new BooleanValue(true), new BooleanValue(false), new BooleanValue(true) }) };
yield return new object[] { new InputObjectGraphType<Person>(), null, new NullValue() };
yield return new object[] { new PersonInputType(), new Person { Name = "Tom", Age = 42 }, new ObjectValue(new[]
{
new ObjectField("Name", new StringValue("Tom")),
new ObjectField("Age", new IntValue(42))
}) };
yield return new object[] { new ListGraphType(new BooleanGraphType()), true, new BooleanValue(true) };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class ToASTExceptionTestData : IEnumerable<object[]>
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
public class BadPersonInputType : InputObjectGraphType<Person>
{
public override IValue ToAST(object value) => null;
}
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { new ObjectGraphType(), 0, new ArgumentOutOfRangeException("type", "Must provide Input Type, cannot use ObjectGraphType 'Object'") };
yield return new object[] { new InputObjectGraphType<Person>(), new Person(), new NotImplementedException("Please override the 'ToAST' method of the 'InputObjectGraphType`1' Input Object to support this operation.") };
yield return new object[] { new BadPersonInputType(), new Person(), new InvalidOperationException("Unable to get an AST representation of the input object type 'BadPersonInputType' for 'GraphQL.Tests.Extensions.GraphQLExtensionsTests+ToASTExceptionTestData+Person'.") };
yield return new object[] { new NonNullGraphType(new BooleanGraphType()), null, new InvalidOperationException($"Unable to get an AST representation of null value for type 'Boolean!'.") };
yield return new object[] { new NonNullGraphType(new ListGraphType(new BooleanGraphType())), null, new InvalidOperationException($"Unable to get an AST representation of null value for type '[Boolean]!'.") };
yield return new object[] { new ListGraphType(new NonNullGraphType(new BooleanGraphType())), new object[] { true, false, null }, new InvalidOperationException($"Unable to get an AST representation of null value for type 'Boolean!'.") };
yield return new object[] { new NonNullGraphType(new InputObjectGraphType<Person>()), null, new InvalidOperationException($"Unable to get an AST representation of null value for type 'InputObjectGraphType_1!'.") };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Theory]
[ClassData(typeof(IsValidDefaultTestData))]
public void IsValidDefault_Test(IGraphType type, object value, bool expected) => type.IsValidDefault(value).ShouldBe(expected);
[Theory]
[ClassData(typeof(IsValidDefaultExceptionTestData))]
public void IsValidDefault_Exception_Test(IGraphType type, object value, Exception expected)
{
Should.Throw(() => type.IsValidDefault(value), expected.GetType()).Message.ShouldBe(expected.Message);
}
[Theory]
[ClassData(typeof(ToASTTestData))]
public void ToAST_Test(IGraphType type, object value, IValue expected)
{
var actual = AstPrinter.Print(type.ToAST(value));
var result = AstPrinter.Print(expected);
actual.ShouldBe(result);
}
[Theory]
[ClassData(typeof(ToASTExceptionTestData))]
public void ToAST_Exception_Test(IGraphType type, object value, Exception expected)
{
Should.Throw(() => type.ToAST(value), expected.GetType()).Message.ShouldBe(expected.Message);
}
[Fact]
public void BuildNamedType_ResolveReturnNull_Throws()
{
Should.Throw<InvalidOperationException>(() => typeof(ListGraphType<ListGraphType<EpisodeEnum>>).BuildNamedType(_ => null));
}
[Fact]
public void GetResult_Extension_Should_Work()
{
var task1 = Task.FromResult(42);
task1.GetResult().ShouldBe(42);
var obj = new object();
var task2 = Task.FromResult(obj);
task2.GetResult().ShouldBe(obj);
IEnumerable collection = new List<string>();
var task3 = Task.FromResult(collection);
task3.GetResult().ShouldBe(collection);
ILookup<string, EqualityComparer<DateTime>> lookup = new List<EqualityComparer<DateTime>>().ToLookup(i => i.GetHashCode().ToString());
var task4 = Task.FromResult(lookup);
task4.GetResult().ShouldBe(lookup);
var task5 = DataSource.GetSomething();
task5.GetResult().ShouldNotBeNull();
}
}
}
| 49.746193 | 286 | 0.613878 | [
"MIT"
] | Askar938/graphql-dotnet | src/GraphQL.Tests/Extensions/GraphQLExtensionsTests.cs | 9,800 | C# |
#pragma checksum "D:\Project\C#\Chameleon\WowStuff\View\FlashlightPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "CAE74C3AC11EAD5EDCA3E6725615A702"
//------------------------------------------------------------------------------
// <auto-generated>
// 이 코드는 도구를 사용하여 생성되었습니다.
// 런타임 버전:4.0.30319.34011
//
// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
// 이러한 변경 내용이 손실됩니다.
// </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace ChameleonLib.View {
public partial class FlashlightPage : Microsoft.Phone.Controls.PhoneApplicationPage {
internal Microsoft.Phone.Controls.PhoneApplicationPage flashlightPage;
internal System.Windows.Controls.Grid LayoutRoot;
internal System.Windows.Controls.Grid ContentPanel;
internal System.Windows.Controls.Button PowerButton;
internal System.Windows.Controls.TextBlock BatteryRemainPercent;
internal System.Windows.Controls.Image PowerButtonImage;
internal System.Windows.Controls.TextBlock FlickeringFrequencyHeader;
internal System.Windows.Controls.Slider FlickeringFrequency;
internal System.Windows.Controls.CheckBox UseToggleButton;
internal System.Windows.Controls.Grid FlashlightPanel;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/Chameleon;component/View/FlashlightPage.xaml", System.UriKind.Relative));
this.flashlightPage = ((Microsoft.Phone.Controls.PhoneApplicationPage)(this.FindName("flashlightPage")));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
this.PowerButton = ((System.Windows.Controls.Button)(this.FindName("PowerButton")));
this.BatteryRemainPercent = ((System.Windows.Controls.TextBlock)(this.FindName("BatteryRemainPercent")));
this.PowerButtonImage = ((System.Windows.Controls.Image)(this.FindName("PowerButtonImage")));
this.FlickeringFrequencyHeader = ((System.Windows.Controls.TextBlock)(this.FindName("FlickeringFrequencyHeader")));
this.FlickeringFrequency = ((System.Windows.Controls.Slider)(this.FindName("FlickeringFrequency")));
this.UseToggleButton = ((System.Windows.Controls.CheckBox)(this.FindName("UseToggleButton")));
this.FlashlightPanel = ((System.Windows.Controls.Grid)(this.FindName("FlashlightPanel")));
}
}
}
| 42.423529 | 153 | 0.670826 | [
"MIT"
] | yookjy/Chameleon | WowStuff/obj/Release/View/FlashlightPage.g.i.cs | 3,742 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UniRx;
using UnityEngine;
namespace Skaillz.Ubernet.NetworkEntities
{
/// <summary>
/// Handles sending and executing RPCs on <see cref="INetworkComponent"/>s.
/// </summary>
public class RpcHandler : IDisposable
{
private readonly INetworkComponent _context;
private Dictionary<short, MethodInfo> _rpcCodeLookup;
private Dictionary<string, short> _rpcMethodLookup;
private IDisposable _rpcSubscription;
/// <summary>
/// Creates a new instance for the given component, with the given serializer.
/// All methods with the <see cref="NetworkRpcAttribute"/> are registered.
/// </summary>
/// <param name="context"></param>
/// <param name="serializer"></param>
public RpcHandler(INetworkComponent context, ISerializer serializer)
{
_context = context;
if (!serializer.IsTypeRegistered(typeof(RpcCall)))
{
serializer.RegisterCustomType(DefaultTypes.Rpc, new RpcCallSerializer(serializer));
}
InitializeRpcs();
}
public void Dispose()
{
if (_rpcSubscription == null)
{
throw new InvalidOperationException($"The {nameof(SyncedValueSerializer)} instance has not been " +
$"initialized or had errors during initialization.");
}
_rpcSubscription.Dispose();
}
/// <summary>
/// Sends an RPC. Called methods must be decorated with the <see cref="NetworkRpcAttribute"/>.
/// </summary>
/// <param name="name">The name of the method to call.</param>
/// <param name="target">The message target.</param>
/// <param name="parameters">The parameters to call the RPC method with.</param>
public void SendRpc(string name, IMessageTarget target, params object[] parameters)
{
SendRpc(name, target, true, parameters);
}
/// <summary>
/// Sends an RPC unreliably (meaning that delivery and order of execution are not guaranteed).
/// Called methods must be decorated with the <see cref="NetworkRpcAttribute"/>.
/// </summary>
/// <param name="name">The name of the method to call.</param>
/// <param name="target">The message target.</param>
/// <param name="parameters">The parameters to call the RPC method with.</param>
public void SendRpcUnreliable(string name, IMessageTarget target, params object[] parameters)
{
SendRpc(name, target, false, parameters);
}
private void InitializeRpcs()
{
_rpcCodeLookup = new Dictionary<short, MethodInfo>();
_rpcMethodLookup = new Dictionary<string, short>();
var type = _context.GetType();
var methods = ReflectionCache.GetRpcMethods(type);
for (short i = 0; i < methods.Length; i++)
{
var method = methods[i];
if (_rpcMethodLookup.ContainsKey(method.Name))
{
throw new NotImplementedException($"Detected overloaded RPC method '{method.Name}' " +
$"on component type '{type.FullName}'. Overloads are not supported yet, so please make sure " +
"that there aren't multiple RPC methods with the same name on the same component.");
}
_rpcCodeLookup[i] = method;
_rpcMethodLookup[method.Name] = i;
}
_rpcSubscription = _context.Entity.Manager.OnEvent(DefaultEvents.Rpc)
.Select(evt => (RpcCall) evt.Data)
.Where(rpc => rpc.EntityId == _context.Entity.Id && rpc.ComponentId == _context.Id)
.Subscribe(rpc =>
{
if (_rpcCodeLookup.ContainsKey(rpc.RpcCode))
{
var method = _rpcCodeLookup[rpc.RpcCode];
method.Invoke(_context, rpc.Params);
}
else
{
Debug.LogWarning($"No RPC method found with code {rpc.RpcCode} " +
$"on component {_context} on entity {_context.Entity}");
}
});
}
private void SendRpc(string name, IMessageTarget target, bool reliable, object[] parameters)
{
if (!_rpcMethodLookup.ContainsKey(name))
{
throw new InvalidOperationException($"No RPC method with the name {name} is registered on the component." +
$"Check if you misspelled it or forgot to add the {nameof(NetworkRpcAttribute)} to your method.");
}
var call = new RpcCall
{
EntityId = _context.Entity.Id,
ComponentId = _context.Id,
RpcCode = _rpcMethodLookup[name],
Params = parameters
};
_context.Entity.Manager.SendEvent(DefaultEvents.Rpc, call, target, reliable);
}
internal struct RpcCall
{
public int EntityId { get; set; }
public short ComponentId { get; set; }
public short RpcCode { get; set; }
public object[] Params { get; set; }
}
internal class RpcCallSerializer : CustomTypeSerializer<RpcCall>
{
private readonly ISerializer _baseSerializer;
public RpcCallSerializer(ISerializer baseSerializer)
{
_baseSerializer = baseSerializer;
}
public override void Serialize(RpcCall rpcCall, Stream stream)
{
SerializationHelper.SerializeInt(rpcCall.EntityId, stream);
SerializationHelper.SerializeShort(rpcCall.ComponentId, stream);
SerializationHelper.SerializeShort(rpcCall.RpcCode, stream);
_baseSerializer.Serialize(rpcCall.Params, stream);
}
public override RpcCall Deserialize(Stream stream)
{
return new RpcCall
{
EntityId = SerializationHelper.DeserializeInt(stream),
ComponentId = SerializationHelper.DeserializeShort(stream),
RpcCode = SerializationHelper.DeserializeShort(stream),
Params = (object[]) _baseSerializer.Deserialize(stream)
};
}
}
}
} | 40.170588 | 123 | 0.555865 | [
"MIT"
] | SkaillZ/ubernet | Assets/Plugins/Ubernet/Scripts/Core/NetworkEntities/RpcHandler.cs | 6,829 | C# |
using System;
namespace OpenVIII
{
internal sealed class LSCROLLA : JsmInstruction
{
private IJsmExpression _arg0;
private IJsmExpression _arg1;
public LSCROLLA(IJsmExpression arg0, IJsmExpression arg1)
{
_arg0 = arg0;
_arg1 = arg1;
}
public LSCROLLA(Int32 parameter, IStack<IJsmExpression> stack)
: this(
arg1: stack.Pop(),
arg0: stack.Pop())
{
}
public override String ToString()
{
return $"{nameof(LSCROLLA)}({nameof(_arg0)}: {_arg0}, {nameof(_arg1)}: {_arg1})";
}
}
} | 22.655172 | 93 | 0.532725 | [
"MIT"
] | A-n-d-y/OpenVIII | Core/Field/JSM/Instructions/LSCROLLA.cs | 659 | C# |
//Copyright(c) Microsoft Corporation.All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using CommandLine;
using System.Reflection;
using NLog;
using NLog.Targets;
using NLog.Config;
using System.IO;
namespace Microsoft.AppInspector
{
#region CommandLineArgOptions
/// <summary>
/// Command option classes for each command verb
/// </summary>
[Verb("analyze", HelpText = "Inspect source directory/file/compressed file (.tgz|zip) against defined characteristics")]
public class AnalyzeCommandOptions
{
[Option('s', "source-path", Required = true, HelpText = "Path to source code to inspect (required)")]
public string SourcePath { get; set; }
[Option('o', "output-file-path", Required = false, HelpText = "Path to output file")]
public string OutputFilePath { get; set; }
[Option('f', "output-file-format", Required = false, HelpText = "Output format [html|json|text]", Default = "html")]
public string OutputFileFormat { get; set; }
[Option('e', "text-format", Required = false, HelpText = "Match text format specifiers", Default = "Tag:%T,Rule:%N,Ruleid:%R,Confidence:%X,File:%F,Sourcetype:%t,Line:%L,Sample:%m")]
public string TextOutputFormat { get; set; }
[Option('r', "custom-rules-path", Required = false, HelpText = "Custom rules path")]
public string CustomRulesPath { get; set; }
[Option('t', "tag-output-only", Required = false, HelpText = "Output only identified tags", Default = false)]
public bool SimpleTagsOnly { get; set; }
[Option('i', "ignore-default-rules", Required = false, HelpText = "Exclude default rules bundled with application", Default = false)]
public bool IgnoreDefaultRules { get; set; }
[Option('d', "allow-dup-tags", Required = false, HelpText = "Output contains unique and non-unique tag matches", Default = false)]
public bool AllowDupTags { get; set; }
[Option('b', "supress-browser-open", Required = false, HelpText = "HTML formatted output is automatically opened to default browser", Default = false)]
public bool AutoBrowserOpen { get; set; }
[Option('c', "confidence-filters", Required = false, HelpText = "Output only matches with specified confidence <value>,<value> [high|medium|low]", Default = "high,medium")]
public string ConfidenceFilters { get; set; }
[Option('k', "file-path-exclusions", Required = false, HelpText = "Exclude source files (none|default: sample,example,test,docs,.vs,.git)", Default = "sample,example,test,docs,.vs,.git")]
public string FilePathExclusions { get; set; }
[Option('x', "console-verbosity", Required = false, HelpText = "Console verbosity [high|medium|low|none]", Default = "medium")]
public string ConsoleVerbosityLevel { get; set; }
#region logoptions
[Option('l', "log-file-path", Required = false, HelpText = "Log file path")]
public string LogFilePath { get; set; }
[Option('v', "log-file-level", Required = false, HelpText = "Log file level [Debug|Info|Warn|Error|Fatal|Off]", Default = "Error")]
public string LogFileLevel { get; set; }
#endregion
}
[Verb("tagdiff", HelpText = "Compares unique tag values between two source paths")]
public class TagDiffCommandOptions
{
[Option("src1", Required = true, HelpText = "Source 1 to compare (required)")]
public string SourcePath1 { get; set; }
[Option("src2", Required = true, HelpText = "Source 2 to compare (required")]
public string SourcePath2 { get; set; }
[Option('t', "test-type", Required = false, HelpText = "Type of test to run [equality|inequality]", Default = "equality")]
public string TestType { get; set; }
[Option('r', "custom-rules-path", Required = false, HelpText = "Custom rules path")]
public string CustomRulesPath { get; set; }
[Option('i', "ignore-default-rules", Required = false, HelpText = "Exclude default rules bundled with application", Default = false)]
public bool IgnoreDefaultRules { get; set; }
[Option('o', "output-file-path", Required = false, HelpText = "Path to output file")]
public string OutputFilePath { get; set; }
[Option('x', "console-verbosity", Required = false, HelpText = "Console verbosity [high|medium|low|none]", Default = "medium")]
public string ConsoleVerbosityLevel { get; set; }
#region logoptions
[Option('l', "log-file-path", Required = false, HelpText = "Log file path")]
public string LogFilePath { get; set; }
[Option('v', "log-file-level", Required = false, HelpText = "Log file level [Debug|Info|Warn|Error|Fatal|Off]", Default = "Error")]
public string LogFileLevel { get; set; }
#endregion
}
[Verb("tagtest", HelpText = "Test presence of smaller set or custom tags in source (compare or verify modes)")]
public class TagTestCommandOptions
{
[Option('s', "source-path", Required = true, HelpText = "Source to test (required)")]
public string SourcePath { get; set; }
[Option('t', "test-type", Required = false, HelpText = "Test to perform [rulespresent|rulesnotpresent] ", Default = "rulespresent")]
public string TestType { get; set; }
[Option('r', "custom-rules-path", Required = false, HelpText = "Custom rules path")]
public string CustomRulesPath { get; set; }
[Option('i', "ignore-default-rules", Required = false, HelpText = "Exclude default rules bundled with application", Default = true)]
public bool IgnoreDefaultRules { get; set; }
[Option('o', "output-file-path", Required = false, HelpText = "Path to output file")]
public string OutputFilePath { get; set; }
[Option('x', "console-verbosity", Required = false, HelpText = "Console verbosity [high|medium|low|none]", Default = "medium")]
public string ConsoleVerbosityLevel { get; set; }
#region logoptions
[Option('l', "log-file-path", Required = false, HelpText = "Log file path")]
public string LogFilePath { get; set; }
[Option('v', "log-file-level", Required = false, HelpText = "Log file level [Debug|Info|Warn|Error|Fatal|Off]", Default = "Error")]
public string LogFileLevel { get; set; }
#endregion
}
[Verb("exporttags", HelpText = "Export default unique rule tags to view what features may be detected")]
public class ExportTagsCommandOptions
{
[Option('r', "custom-rules-path", Required = false, HelpText = "Custom rules path")]
public string CustomRulesPath { get; set; }
[Option('i', "ignore-default-rules", Required = false, HelpText = "Exclude default rules bundled with application", Default = false)]
public bool IgnoreDefaultRules { get; set; }
[Option('o', "output-file-path", Required = false, HelpText = "Path to output file")]
public string OutputFilePath { get; set; }
[Option('x', "console-verbosity", Required = false, HelpText = "Console verbosity [high|medium|low|none]", Default = "medium")]
public string ConsoleVerbosityLevel { get; set; }
#region logoptions
[Option('l', "log-file-path", Required = false, HelpText = "Log file path")]
public string LogFilePath { get; set; }
[Option('v', "log-file-level", Required = false, HelpText = "Log file level [Debug|Info|Warn|Error|Fatal|Off]", Default = "Error")]
public string LogFileLevel { get; set; }
#endregion
}
[Verb("verifyrules", HelpText = "Verify rules syntax is valid")]
public class VerifyRulesCommandOptions
{
[Option('r', "custom-rules-path", Required = false, HelpText = "Custom rules path")]
public string CustomRulesPath { get; set; }
[Option('i', "ignore-default-rules", Required = false, HelpText = "Exclude default rules bundled with application", Default = false)]
public bool IgnoreDefaultRules { get; set; }
[Option('o', "output-file-path", Required = false, HelpText = "Path to output file")]
public string OutputFilePath { get; set; }
[Option('x', "console-verbosity", Required = false, HelpText = "Console verbosity [high|medium|low|none]", Default = "medium")]
public string ConsoleVerbosityLevel { get; set; }
#region logoptions
[Option('l', "log-file-path", Required = false, HelpText = "Log file path")]
public string LogFilePath { get; set; }
[Option('v', "log-file-level", Required = false, HelpText = "Log file level [Debug|Info|Warn|Error|Fatal|Off]", Default = "Error")]
public string LogFileLevel { get; set; }
#endregion
}
#endregion
class Program
{
public static string GetVersionString()
{
return String.Format("Microsoft Application Inspector {0}", GetVersion());
}
public static string GetVersion()
{
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
return fileVersionInfo.ProductVersion;
}
static public Logger Logger { get; set; }
/// <summary>
/// Program entry point which defines command verbs and options to running
/// </summary>
/// <param name="args"></param>
static int Main(string[] args)
{
int finalResult = -1;
WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.Medium;
try
{
WriteOnce.Info(GetVersionString());
var argsResult = Parser.Default.ParseArguments<AnalyzeCommandOptions,
TagDiffCommandOptions,
TagTestCommandOptions,
ExportTagsCommandOptions,
VerifyRulesCommandOptions>(args)
.MapResult(
(AnalyzeCommandOptions opts) => RunAnalyzeCommand(opts),
(TagDiffCommandOptions opts) => RunTagDiffCommand(opts),
(TagTestCommandOptions opts) => RunTagTestCommand(opts),
(ExportTagsCommandOptions opts) => RunExportTagsCommand(opts),
(VerifyRulesCommandOptions opts) => RunVerifyRulesCommand(opts),
errs => 1
);
finalResult = argsResult;
}
catch (OpException e)
{
if (Logger != null)
{
WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_NAMED, e.Message));
Logger.Error($"Runtime error: {e.StackTrace}");
}
else
WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_PRELOG, e.Message));
}
catch (Exception e)
{
if (Logger != null)
{
WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_UNNAMED));
Logger.Error($"Runtime error: {e.Message} {e.StackTrace}");
}
else
WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_PRELOG, e.Message));
}
return finalResult;
}
private static int RunAnalyzeCommand(AnalyzeCommandOptions opts)
{
SetupLogging(opts.LogFilePath, opts.LogFileLevel);
return new AnalyzeCommand(opts).Run();
}
private static int RunTagDiffCommand(TagDiffCommandOptions opts)
{
SetupLogging(opts.LogFilePath, opts.LogFileLevel);
return new TagDiffCommand(opts).Run();
}
private static int RunTagTestCommand(TagTestCommandOptions opts)
{
SetupLogging(opts.LogFilePath, opts.LogFileLevel);
return new TagTestCommand(opts).Run();
}
private static int RunExportTagsCommand(ExportTagsCommandOptions opts)
{
SetupLogging(opts.LogFilePath, opts.LogFileLevel);
return new ExportTagsCommand(opts).Run();
}
private static int RunVerifyRulesCommand(VerifyRulesCommandOptions opts)
{
SetupLogging(opts.LogFilePath, opts.LogFileLevel);
return new VerifyRulesCommand(opts).Run();
}
static void SetupLogging(string logFilePath, string logFileLevel)
{
var config = new NLog.Config.LoggingConfiguration();
if (String.IsNullOrEmpty(logFilePath))
{
logFilePath = Utils.GetPath(Utils.AppPath.defaultLog);
//if using default app log path clean up previous for convenience in reading
if (File.Exists(logFilePath))
File.Delete(logFilePath);
}
LogLevel log_level = LogLevel.Error;//default
try
{
log_level = LogLevel.FromString(logFileLevel);
}
catch (Exception)
{
throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-v")));
}
using (var fileTarget = new FileTarget()
{
Name = "LogFile",
FileName = logFilePath,
Layout = @"${date:universalTime=true:format=s} ${threadid} ${level:uppercase=true} - ${message}",
ForceMutexConcurrentWrites = true
})
{
config.AddTarget(fileTarget);
config.LoggingRules.Add(new LoggingRule("*", log_level, fileTarget));
}
LogManager.Configuration = config;
Logger = LogManager.GetCurrentClassLogger();
Logger.Info("["+ DateTime.Now.ToLocalTime() + "] //////////////////////////////////////////////////////////");
WriteOnce.Log = Logger;//allows log to be written to as well as console or output file
}
}
}
| 41.315942 | 195 | 0.607058 | [
"MIT"
] | PabloClon/ApplicationInspector | AppInspector/Program.cs | 14,256 | 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;
public
// Do a simple 5 dimensional Jagged array.
class Simple_Array_Test
{
public static int Main( String[] args )
{
Console.WriteLine("Starting...");
int SIZE = 10;
//Create an array that is jagged.
// in last 2d, the array looks like:
// Int32
// Int32 Int32
// Int32 Int32 Int32
// Int32 Int32 Int32 Int32
// Int32 Int32 Int32 Int32 Int32
//
Int32 [][][][][] foo = new Int32[SIZE][][][][];
int i,j,k,l,m;
Int64 sum=0;
for(i=0;i<SIZE;i++)
{
foo[i] = new Int32[i][][][];
for(j=0;j<i;j++)
{
foo[i][j] = new Int32[j][][];
for(k=0;k<j;k++)
{
foo[i][j][k] = new Int32[k][];
for(l=0;l<k;l++)
{
foo[i][j][k][l] = new Int32[l];
for(m=0;m<l;m++)
{
foo[i][j][k][l][m] = i*j*k*l*m;
}
}
}
}
}
for(i=0;i<SIZE;i++)
for(j=0;j<i;j++)
for(k=0;k<j;k++)
for(l=0;l<k;l++)
for(m=0;m<l;m++)
{
//Console.Write(" "+foo[i][j][k][l][m].ToString());
sum+=foo[i][j][k][l][m];
}
if(sum==269325)
{
Console.WriteLine("Everything Worked!");
return 100;
}
else
{
Console.WriteLine("Something is broken!");
return 1;
}
}
}
| 21.465753 | 71 | 0.474154 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/Directed/Arrays/simple1.cs | 1,567 | C# |
using DotnetSpider.Extension.Model;
using DotnetSpider.Extraction;
using DotnetSpider.Extraction.Model.Attribute;
namespace DotnetSpider.Extension.Downloader
{
/// <summary>
/// 下载内容缓存对象
/// </summary>
[Schema("crawl_cache", "cache", TableNamePostfix.Today)]
public class DownloadCache : BaseEntity
{
/// <summary>
/// 所属爬虫的唯一标识
/// </summary>
[Field(Expression = "", Type = SelectorType.Enviroment)]
[Column]
[Index("URL_IDENTITY_TASK_ID_NAME")]
public string Identity { get; set; }
/// <summary>
/// 所属爬虫的任务编号
/// </summary>
[Field(Expression = "", Type = SelectorType.Enviroment)]
[Column]
[Index("URL_IDENTITY_TASK_ID_NAME")]
public string TaskId { get; set; }
/// <summary>
/// 所属爬虫的名称
/// </summary>
[Field(Expression = "", Type = SelectorType.Enviroment)]
[Column]
[Index("URL_IDENTITY_TASK_ID_NAME")]
public string Name { get; set; }
/// <summary>
/// 采集的链接
/// </summary>
[Field(Expression = "", Type = SelectorType.Enviroment)]
[Column]
[Index("URL_IDENTITY_TASK_ID_NAME")]
public string Url { get; set; }
/// <summary>
/// 下载的内容
/// </summary>
[Field(Expression = "", Type = SelectorType.Enviroment)]
[Column]
public string Content { get; set; }
}
}
| 23.433962 | 58 | 0.657005 | [
"MIT"
] | DavidAlphaFox/DotnetSpider | src/DotnetSpider.Extension/Downloader/DownloadCache.cs | 1,330 | C# |
using NextGenSpice.Core.Devices;
using NextGenSpice.Parser.Statements.Deferring;
namespace NextGenSpice.Parser.Statements.Devices
{
/// <summary>Class for processing current controlled voltage source SPICE statements.</summary>
public class CurrentControlledVoltageSourceStatementProcessor : DeviceStatementProcessor
{
public CurrentControlledVoltageSourceStatementProcessor()
{
MinArgs = MaxArgs = 4;
}
/// <summary>Discriminator of the device type this processor can parse.</summary>
public override char Discriminator => 'H';
/// <summary>Processes given set of statements.</summary>
protected override void DoProcess()
{
var name = DeviceName;
var nodes = GetNodeIds(1, 2);
var vsource = RawStatement[3];
var gain = GetValue(4);
if (Errors == 0)
Context.DeferredStatements.Add(new VoltageSourceDependentDeferredStatement(Context.CurrentScope, vsource,
(builder, vs) =>
builder.AddDevice(
nodes,
new Ccvs(
vs,
gain,
name
)
)
));
}
}
} | 26.974359 | 109 | 0.702471 | [
"MIT"
] | rzikm/NextGenSpice | src/NextGenSpice.Parser/Statements/Devices/CurrentControlledVoltageSourceStatementProcessor.cs | 1,054 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
namespace Tests.TestFramework
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class TempDir : IDisposable
{
private static List<TempDir> s_Dirs = new List<TempDir>();
public TempDir() => System.IO.Directory.CreateDirectory(Directory);
public string Directory { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
public void Dispose() => System.IO.Directory.Delete(Directory, true);
public static string Get()
{
var dir = new TempDir();
s_Dirs.Add(dir);
return dir.Directory;
}
public static void CleanUp()
{
var dirs = s_Dirs;
s_Dirs = new List<TempDir>();
foreach (var tempDir in dirs)
{
tempDir.Dispose();
}
}
}
} | 27.852941 | 102 | 0.587117 | [
"MIT"
] | samblackburn/NetDoc | Tests/TestFramework/TempDir.cs | 949 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExchangeVariableValues")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExchangeVariableValues")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("370a1471-6945-4a03-a805-650c42635736")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.297297 | 84 | 0.748765 | [
"MIT"
] | terzievair/Data-Types-and-Variables---Exercises | DataTypes/ExchangeVariableValues/Properties/AssemblyInfo.cs | 1,420 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.OutlookApi
{
#region Delegates
#pragma warning disable
public delegate void OutlookBarGroups_GroupAddEventHandler(NetOffice.OutlookApi.OutlookBarGroup newGroup);
public delegate void OutlookBarGroups_BeforeGroupAddEventHandler(ref bool cancel);
public delegate void OutlookBarGroups_BeforeGroupRemoveEventHandler(NetOffice.OutlookApi.OutlookBarGroup group, ref bool cancel);
#pragma warning restore
#endregion
/// <summary>
/// CoClass OutlookBarGroups
/// SupportByVersion Outlook, 9,10,11,12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff868789.aspx </remarks>
[SupportByVersion("Outlook", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsCoClass)]
[EventSink(typeof(Events.OutlookBarGroupsEvents_SinkHelper))]
[ComEventInterface(typeof(Events.OutlookBarGroupsEvents))]
public class OutlookBarGroups : _OutlookBarGroups, IEventBinding
{
#pragma warning disable
#region Fields
private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint;
private string _activeSinkId;
private static Type _type;
private Events.OutlookBarGroupsEvents_SinkHelper _outlookBarGroupsEvents_SinkHelper;
#endregion
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
/// <summary>
/// Type Cache
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(OutlookBarGroups);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public OutlookBarGroups(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public OutlookBarGroups(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public OutlookBarGroups(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public OutlookBarGroups(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public OutlookBarGroups(ICOMObject replacedObject) : base(replacedObject)
{
}
/// <summary>
/// Creates a new instance of OutlookBarGroups
/// </summary>
public OutlookBarGroups():base("Outlook.OutlookBarGroups")
{
}
/// <summary>
/// Creates a new instance of OutlookBarGroups
/// </summary>
///<param name="progId">registered ProgID</param>
public OutlookBarGroups(string progId):base(progId)
{
}
#endregion
#region Static CoClass Methods
#endregion
#region Events
/// <summary>
/// SupportByVersion Outlook, 9,10,11,12,14,15,16
/// </summary>
private event OutlookBarGroups_GroupAddEventHandler _GroupAddEvent;
/// <summary>
/// SupportByVersion Outlook 9 10 11 12 14 15,16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff865659.aspx </remarks>
[SupportByVersion("Outlook", 9,10,11,12,14,15,16)]
public event OutlookBarGroups_GroupAddEventHandler GroupAddEvent
{
add
{
CreateEventBridge();
_GroupAddEvent += value;
}
remove
{
_GroupAddEvent -= value;
}
}
/// <summary>
/// SupportByVersion Outlook, 9,10,11,12,14,15,16
/// </summary>
private event OutlookBarGroups_BeforeGroupAddEventHandler _BeforeGroupAddEvent;
/// <summary>
/// SupportByVersion Outlook 9 10 11 12 14 15,16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff866940.aspx </remarks>
[SupportByVersion("Outlook", 9,10,11,12,14,15,16)]
public event OutlookBarGroups_BeforeGroupAddEventHandler BeforeGroupAddEvent
{
add
{
CreateEventBridge();
_BeforeGroupAddEvent += value;
}
remove
{
_BeforeGroupAddEvent -= value;
}
}
/// <summary>
/// SupportByVersion Outlook, 9,10,11,12,14,15,16
/// </summary>
private event OutlookBarGroups_BeforeGroupRemoveEventHandler _BeforeGroupRemoveEvent;
/// <summary>
/// SupportByVersion Outlook 9 10 11 12 14 15,16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff868646.aspx </remarks>
[SupportByVersion("Outlook", 9,10,11,12,14,15,16)]
public event OutlookBarGroups_BeforeGroupRemoveEventHandler BeforeGroupRemoveEvent
{
add
{
CreateEventBridge();
_BeforeGroupRemoveEvent += value;
}
remove
{
_BeforeGroupRemoveEvent -= value;
}
}
#endregion
#region IEventBinding
/// <summary>
/// Creates active sink helper
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void CreateEventBridge()
{
if(false == Factory.Settings.EnableEvents)
return;
if (null != _connectPoint)
return;
if (null == _activeSinkId)
_activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, Events.OutlookBarGroupsEvents_SinkHelper.Id);
if(Events.OutlookBarGroupsEvents_SinkHelper.Id.Equals(_activeSinkId, StringComparison.InvariantCultureIgnoreCase))
{
_outlookBarGroupsEvents_SinkHelper = new Events.OutlookBarGroupsEvents_SinkHelper(this, _connectPoint);
return;
}
}
/// <summary>
/// The instance use currently an event listener
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool EventBridgeInitialized
{
get
{
return (null != _connectPoint);
}
}
/// <summary>
/// Instance has one or more event recipients
/// </summary>
/// <returns>true if one or more event is active, otherwise false</returns>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool HasEventRecipients()
{
return NetOffice.Events.CoClassEventReflector.HasEventRecipients(this, LateBindingApiWrapperType);
}
/// <summary>
/// Instance has one or more event recipients
/// </summary>
/// <param name="eventName">name of the event</param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool HasEventRecipients(string eventName)
{
return NetOffice.Events.CoClassEventReflector.HasEventRecipients(this, LateBindingApiWrapperType, eventName);
}
/// <summary>
/// Target methods from its actual event recipients
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Delegate[] GetEventRecipients(string eventName)
{
return NetOffice.Events.CoClassEventReflector.GetEventRecipients(this, LateBindingApiWrapperType, eventName);
}
/// <summary>
/// Returns the current count of event recipients
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int GetCountOfEventRecipients(string eventName)
{
return NetOffice.Events.CoClassEventReflector.GetCountOfEventRecipients(this, LateBindingApiWrapperType, eventName);
}
/// <summary>
/// Raise an instance event
/// </summary>
/// <param name="eventName">name of the event without 'Event' at the end</param>
/// <param name="paramsArray">custom arguments for the event</param>
/// <returns>count of called event recipients</returns>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int RaiseCustomEvent(string eventName, ref object[] paramsArray)
{
return NetOffice.Events.CoClassEventReflector.RaiseCustomEvent(this, LateBindingApiWrapperType, eventName, ref paramsArray);
}
/// <summary>
/// Stop listening events for the instance
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void DisposeEventBridge()
{
if( null != _outlookBarGroupsEvents_SinkHelper)
{
_outlookBarGroupsEvents_SinkHelper.Dispose();
_outlookBarGroupsEvents_SinkHelper = null;
}
_connectPoint = null;
}
#endregion
#pragma warning restore
}
}
| 32.603175 | 171 | 0.675463 | [
"MIT"
] | DominikPalo/NetOffice | Source/Outlook/Classes/OutlookBarGroups.cs | 10,272 | C# |
using CefNet;
using CefNet.Windows.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WinFormsCoreApp
{
public partial class DeviceEmulatorForm : Form
{
private WebView view;
public DeviceEmulatorForm()
{
InitializeComponent();
view = new CustomWebView()
{
RequestContext = new CefRequestContext(new CefRequestContextSettings()),
WindowlessRenderingEnabled = true,
InitialUrl = "https://www.mydevice.io/"
};
view.SimulateDevice(IPhoneDevice.Create(IPhone.Model7));
view.Top = txtAddress.Bottom + 2;
view.Left = 0;
view.Width = ClientSize.Width;
view.Height = ClientSize.Height - view.Top;
view.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
view.Navigated += View_Navigated;
view.CreateWindow += View_CreateWindow;
view.BrowserCreated += View_BrowserCreated;
this.Controls.Add(view);
}
protected override void OnResizeBegin(EventArgs e)
{
this.SuspendLayout();
base.OnResizeBegin(e);
}
protected override void OnResizeEnd(EventArgs e)
{
this.ResumeLayout(true);
base.OnResizeEnd(e);
}
private async void View_BrowserCreated(object sender, EventArgs e)
{
await view.SetUserAgentOverrideAsync("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Safari/604.1", null, "iPhone", CancellationToken.None);
await view.SetTouchEmulationEnabledAsync(true, null, CancellationToken.None);
await view.SetEmulatedMediaAsync(null, new Dictionary<string, string> { ["any-pointer"] = "coarse" }, CancellationToken.None);
}
private void View_CreateWindow(object sender, CefNet.CreateWindowEventArgs e)
{
e.Cancel = true;
}
private void View_Navigated(object sender, CefNet.NavigatedEventArgs e)
{
txtAddress.Text = e.Url;
txtAddress.Select(txtAddress.Text.Length, 0);
}
private void txtAddress_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (Uri.TryCreate(txtAddress.Text, UriKind.Absolute, out Uri url))
{
view.Navigate(url.AbsoluteUri);
}
}
}
protected override void OnClosing(CancelEventArgs e)
{
view.Dispose();
base.OnClosing(e);
}
}
}
| 26.842697 | 206 | 0.727501 | [
"MIT"
] | AigioL/CefNet | WinFormsCoreApp/DeviceEmulatorForm.cs | 2,391 | C# |
namespace Yarp.Messages
{
public class GetCurrentElectionTimeOutRange
{
}
} | 16 | 47 | 0.645833 | [
"MIT"
] | philiplaureano/Yarp | Yarp/Yarp/Messages/GetCurrentElectionTimeOutRange.cs | 98 | C# |
namespace HomeKitAccessory.Net
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HomeKitAccessory.Data;
using HomeKitAccessory.Pairing.PairSetupStates;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
class HttpConnection
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private TcpClient client;
private Stream stream;
byte[] readBuffer = new byte[102400];
int readPos = 0;
private object sendLock = new object();
private PairSetupState pairState;
private Server server;
private CharacteristicHandler characteristicHandler;
public HttpConnection(Server server, TcpClient client)
{
this.server = server;
this.client = client;
stream = client.GetStream();
pairState = new Initial(server);
characteristicHandler = new CharacteristicHandler(server, SendEvent);
}
public void SendEvent(JObject data)
{
var bodyms = new MemoryStream();
var sw = new StreamWriter(bodyms);
var jw = new JsonTextWriter(sw);
data.WriteTo(jw);
jw.Flush();
bodyms.Position = 0;
var ms = new MemoryStream();
sw = new StreamWriter(ms);
sw.NewLine = "\r\n";
sw.WriteLine("EVENT/1.0 200 OK");
sw.WriteLine("Date: {0:r}", DateTime.UtcNow);
sw.WriteLine("Content-Type: application/hap+json");
sw.WriteLine("Content-Length: {0}", bodyms.Length);
sw.WriteLine();
sw.Flush();
bodyms.CopyTo(ms);
ms.Position = 0;
lock (sendLock)
{
ms.CopyTo(stream);
}
}
public static NameValueCollection ParseQueryString(string queryString)
{
var qs = new NameValueCollection();
foreach (var item in queryString.Split('&'))
{
var kv = item.Split('=');
qs.Add(
Uri.UnescapeDataString(kv[0]),
kv.Length > 1 ?
Uri.UnescapeDataString(kv[1]) :
"");
}
return qs;
}
public void Start()
{
for(;;)
{
var readlen = stream.Read(readBuffer, readPos, readBuffer.Length - readPos);
if (readlen == 0) break;
logger.Debug("Read {0} bytes from client", readlen);
readPos += readlen;
logger.Debug("Total bytes in buffer {0}", readPos);
for (var i = 0; i < readPos - 3; i++) {
if (readBuffer[i] == 0x0d && readBuffer[i + 1] == 0x0a && readBuffer[i + 2] == 0x0d && readBuffer[i + 3] == 0x0a)
{
// Complete header block available
var headerEnd = i + 4;
logger.Debug("Headers {0} bytes", headerEnd);
var reader = new StreamReader(new MemoryStream(readBuffer, 0, headerEnd));
var requestLineRaw = reader.ReadLine();
logger.Debug("requestLine: " + requestLineRaw);
var req = new HttpRequest();
var requestLine = requestLineRaw.Split(' ');
req.Method = requestLine[0];
var pathAndQuery = requestLine[1].Split('?');
req.Path = pathAndQuery[0];
req.QueryString = pathAndQuery.Length > 1 ? ParseQueryString(pathAndQuery[1]) : null;
var requestProtocol = requestLine[2];
if (requestProtocol != "HTTP/1.1")
{
client.Dispose();
throw new InvalidOperationException("Unsupported protocol " + requestProtocol);
}
logger.Debug("Method: {0}", req.Method);
logger.Debug("Path: {0}", req.Path);
logger.Debug("Path and Query: {0}", requestLine[1]);
var headerLine = reader.ReadLine();
int contentLength = 0;
while (!string.IsNullOrEmpty(headerLine)) {
logger.Debug("headerLine: {0}", headerLine);
var header = headerLine.Split(':');
var headerName = header[0].Trim();
var headerValue = header[1].Trim();
if (StringComparer.OrdinalIgnoreCase.Equals(headerName, "Content-Length"))
{
contentLength = int.Parse(headerValue);
}
else
{
req.RequestHeaders.Add(headerName, headerValue);
}
headerLine = reader.ReadLine();
}
byte[] body;
if (contentLength > 0) {
logger.Debug("Reading {0} bytes of body", contentLength);
logger.Debug("{0} bytes already read", readPos - headerEnd);
body = new byte[contentLength];
Array.Copy(readBuffer, headerEnd, body, 0, readPos - headerEnd);
contentLength -= (readPos - headerEnd);
while (contentLength > 0) {
readlen = stream.Read(body, body.Length - contentLength, contentLength);
logger.Debug("Read {0} bytes of body", readlen);
if (readlen == 0) throw new EndOfStreamException();
contentLength -= readlen;
}
} else {
logger.Debug("No body content");
body = new byte[0];
}
req.Body = body;
var res = new HttpResponse();
try
{
logger.Debug("Dispatching request");
DispatchRequest(req, res);
logger.Debug("Request complete");
}
catch (HttpException ex)
{
logger.Warn(ex);
res.StatusCode = ex.StatusCode;
res.StatusPhrase = ex.Message;
res.Body = Encoding.UTF8.GetBytes(ex.ToString());
res.ResponseHeaders.Clear();
res.ResponseHeaders["Content-Type"] = "text/plain";
}
catch (Exception ex)
{
logger.Error(ex);
res.StatusCode = 500;
res.StatusPhrase = "Internal server error";
res.Body = Encoding.UTF8.GetBytes(ex.ToString());
res.ResponseHeaders.Clear();
res.ResponseHeaders["Content-Type"] = "text/plain";
}
if (res.StatusPhrase == null)
res.StatusPhrase = StatusPhrase(res.StatusCode);
res.ResponseHeaders["Server"] = "EventedHttpServer";
res.ResponseHeaders["Date"] = DateTime.UtcNow.ToString("r");
var ms = new MemoryStream();
var rw = new StreamWriter(ms);
rw.NewLine = "\r\n";
rw.Write("HTTP/1.1 ");
rw.Write(res.StatusCode);
if (!string.IsNullOrWhiteSpace(res.StatusPhrase)) {
rw.Write(" ");
rw.Write(res.StatusPhrase);
}
rw.WriteLine();
foreach (string header in res.ResponseHeaders)
{
foreach (var headerValue in res.ResponseHeaders.GetValues(header)) {
rw.Write(header);
rw.Write(": ");
rw.WriteLine(headerValue);
}
}
rw.WriteLine("Content-Length: " + (res.Body?.Length ?? 0));
rw.WriteLine();
rw.Flush();
ms.Position = 0;
lock (sendLock)
{
ms.CopyTo(stream);
if (res.Body != null)
{
stream.Write(res.Body);
}
}
logger.Debug("Request complete");
if (res.Context.TryGetValue("hap.ReadKey", out object readKey) &&
res.Context.TryGetValue("hap.WriteKey", out object writeKey))
{
logger.Debug("Setting encryption keys");
stream = new HapEncryptedStream(stream, (Sodium.Key)readKey, (Sodium.Key)writeKey);
}
readPos = 0;
continue;
}
}
}
client.Dispose();
logger.Debug("Client disconnect normally");
characteristicHandler.Dispose();
}
private static string StatusPhrase(int statusCode)
{
switch (statusCode)
{
case 200: return "Ok";
case 204: return "No Content";
case 207: return "Multi-Status";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 403: return "Forbidden";
case 500: return "Internal Server Error";
default: return "Unknown";
}
}
private void DispatchRequest(HttpRequest req, HttpResponse res)
{
if (req.Path == "/pair-setup")
{
HandlePairSetup(req, res);
}
else if (req.Path == "/pair-verify")
{
HandlePairVerify(req, res);
}
else if (req.Path == "/pairings")
{
HandlePairings(req, res);
}
else if (req.Path == "/accessories")
{
HandleAccessoryDatabase(req, res);
}
else if (req.Path == "/characteristics")
{
HandleCharacteristics(req, res);
}
else if (req.Path == "/identify")
{
HandleIdentify(req, res);
}
else
{
throw new HttpException(404, "Not found");
}
}
private TLVCollection GetRequestTLV(HttpRequest request)
{
if (request.Method != "POST")
throw new HttpException(405, "Method not allowed");
if (request.RequestHeaders["Content-Type"] != "application/pairing+tlv8")
throw new HttpException(415, "Unsupported media type");
return TLVCollection.Deserialize(request.Body);
}
private void SetResponseTLV(HttpResponse response, TLVCollection tLVs)
{
response.StatusCode = 200;
response.StatusPhrase = "Ok";
response.ResponseHeaders["Content-Type"] = "application/pairing+tlv8";
response.Body = tLVs.Serialize();
}
private void HandlePairSetup(HttpRequest request, HttpResponse response)
{
var tlvRequest = GetRequestTLV(request);
var tlvResponse = pairState.HandlePairSetupRequest(tlvRequest, out PairSetupState newState);
if (newState != null)
{
pairState = newState;
}
SetResponseTLV(response, tlvResponse);
}
private void HandlePairVerify(HttpRequest request, HttpResponse response)
{
var tlvRequest = GetRequestTLV(request);
var tlvResponse = pairState.HandlePairVerifyRequest(tlvRequest, out PairSetupState newState);
if (newState != null)
{
pairState = newState;
newState.UpdateEnvironment(response.Context);
}
SetResponseTLV(response, tlvResponse);
}
private void HandlePairings(HttpRequest request, HttpResponse response)
{
var tlvRequest = GetRequestTLV(request);
var method = tlvRequest.Find(TLVType.Method).IntegerValue;
logger.Debug("Pairings method is {0}", method);
switch (method)
{
case 3:
HandlePairingsAdd(tlvRequest, response);
break;
case 4:
HandlePairingsRemove(tlvRequest, response);
break;
case 5:
HandlePairingsList(tlvRequest, response);
break;
default:
throw new NotImplementedException();
}
}
private void HandlePairingsAdd(TLVCollection req, HttpResponse response)
{
var deviceId = req.Find(TLVType.Identifier).StringValue;
var ltpk = req.Find(TLVType.PublicKey).DataValue;
var perms = req.Find(TLVType.Permissions);
logger.Debug("Added device permissions is {0}", perms.IntegerValue);
server.PairingDatabase.AddPairing(deviceId, new Sodium.Ed25519PublicKey(ltpk));
SetResponseTLV(response, new TLVCollection()
{
new TLV(TLVType.State, 2)
});
}
private void HandlePairingsRemove(TLVCollection req, HttpResponse response)
{
var deviceId = req.Find(TLVType.Identifier).StringValue;
server.RemovePairing(deviceId);
SetResponseTLV(response, new TLVCollection
{
new TLV(TLVType.State, 2)
});
}
private void HandlePairingsList(TLVCollection req, HttpResponse response)
{
var list = new TLVCollection();
list.Add(new TLV(TLVType.State, 2));
var i = 0;
foreach (var pairing in server.PairingDatabase.Pairings)
{
if (i > 0) {
list.Add(new TLV(TLVType.Separator, new byte[0]));
}
list.Add(new TLV(TLVType.Identifier, pairing.DeviceId));
list.Add(new TLV(TLVType.PublicKey, pairing.PublicKey.Data));
list.Add(new TLV(TLVType.Permissions, 1));
i++;
}
SetResponseTLV(response, list);
}
private const string HapContentType = "application/hap+json";
private void SetHapResponse(HttpResponse response, HapResponse data)
{
response.StatusCode = data.Status;
if (data.Body != null)
{
if (logger.IsDebugEnabled)
logger.Debug(data.Body.ToString());
response.ResponseHeaders["Content-Type"] = HapContentType;
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var jw = new JsonTextWriter(sw);
data.Body.WriteTo(jw);
jw.Flush();
response.Body = ms.ToArray();
}
}
private void HandleIdentify(HttpRequest request, HttpResponse response)
{
if (server.IsPaired)
{
SetHapResponse(response, new HapResponse {
Status = 400,
Body = new JObject() { "status", -70401 }
});
}
else
{
server.Identify();
response.StatusCode = 204;
}
}
private void HandleAccessoryDatabase(HttpRequest request, HttpResponse response)
{
if (pairState is Verified)
{
if (request.Method != "GET")
throw new HttpException(405, "Not implemented");
var data = characteristicHandler.GetAccessoryDatabase();
SetHapResponse(response, data);
}
else
{
SetHapResponse(response, new HapResponse {
Status = 400,
Body = new JObject() {
{ "status", -70401 }
}
});
}
}
private void HandleCharacteristics(HttpRequest request, HttpResponse response)
{
if (pairState is Verified)
{
if (request.Method == "GET")
{
var ids = new List<AccessoryCharacteristicId>();
foreach (var id in request.QueryString["id"].Split(','))
{
var idpair = id.Split('.');
ulong aid = ulong.Parse(idpair[0]);
ulong iid = ulong.Parse(idpair[1]);
ids.Add(new AccessoryCharacteristicId(aid, iid));
}
var readRequest = new CharacteristicReadRequest();
readRequest.Ids = ids.ToArray();
readRequest.IncludeEvent = request.QueryString["ev"] == "1";
readRequest.IncludeMeta = request.QueryString["meta"] == "1";
readRequest.IncludePerms = request.QueryString["perms"] == "1";
readRequest.IncludeType = request.QueryString["type"] == "1";
var hapResponse = characteristicHandler.HandleCharacteristicReadRequest(readRequest);
SetHapResponse(response, hapResponse);
}
else if (request.Method == "PUT")
{
var writeRequest = new JsonSerializer().Deserialize<CharacteristicWriteRequest>(
new JsonTextReader(
new StreamReader(
new MemoryStream(request.Body))));
var hapResponse = characteristicHandler.HandleCharacteristicWriteRequest(writeRequest);
SetHapResponse(response, hapResponse);
}
else
{
throw new HttpException(405, "Not implemented");
}
}
else
{
throw new HttpException(401, "Not authenticated");
}
}
}
} | 39.171657 | 133 | 0.462981 | [
"MIT"
] | agaskill/homekitaccessory | HomeKitAccessory/Net/HttpConnection.cs | 19,625 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Games;
using Charlotte.Games.Scenarios;
namespace Charlotte.Games
{
public class World : IDisposable
{
public IScenario[] Scenarios;
// <---- prm
public static World I = null;
public World()
{
I = this;
}
public void Dispose()
{
I = null;
}
public void Perform()
{
// ルートが分岐したりすんじゃね?
foreach (IScenario scenario in this.Scenarios)
{
using (Game game = new Game())
{
game.Scenario = scenario;
game.Status = new Status();
game.Perform();
}
}
}
}
}
| 14.272727 | 49 | 0.627389 | [
"MIT"
] | stackprobe/G4YokoShoot | G4YokoShoot/G4YokoShoot/Games/World.cs | 660 | C# |
using Leelite.Commons.Host;
using Leelite.Core.Module;
using Leelite.Modules.MessageCenter.UniPush;
using Microsoft.Extensions.DependencyInjection;
namespace Leelite.Modules.MessageCenter.UserClientId
{
public class MessageCenterUserClientIdModule : ModuleBase
{
public override void ConfigureServices(HostContext context)
{
var services = context.ServiceDescriptors;
services.AddSingleton<IUserClientIdFactory, DefaultUserClientIdFactory>();
}
}
}
| 27 | 86 | 0.744639 | [
"MIT"
] | liduopie/LeeliteCore | src/Modules/Message/Leelite.Modules.MessageCenter.UserClientId/MessageCenterUserClientIdModule.cs | 515 | C# |
using UnityEngine;
using System.Collections;
public class SwipeParticlesEmitter : MonoBehaviour
{
public ParticleEmitter emitter;
public float baseSpeed = 4.0f;
public float swipeVelocityScale = 0.001f;
void Start()
{
if( !emitter )
emitter = GetComponent<ParticleEmitter>();
emitter.emit = false;
}
public void Emit( FingerGestures.SwipeDirection direction, float swipeVelocity )
{
Vector3 heading;
// convert the swipe direction to a 3D vector we can use as our new forward direction for the particle emitter
if( direction == FingerGestures.SwipeDirection.Up )
heading = Vector3.up;
else if( direction == FingerGestures.SwipeDirection.Down )
heading = Vector3.down;
else if( direction == FingerGestures.SwipeDirection.Right )
heading = Vector3.right;
else
heading = Vector3.left;
// orient our emitter towards the swipe direction
emitter.transform.rotation = Quaternion.LookRotation( heading );
Vector3 localEmitVelocity = emitter.localVelocity;
localEmitVelocity.z = baseSpeed * swipeVelocityScale * swipeVelocity;
emitter.localVelocity = localEmitVelocity;
// fire away!
emitter.Emit();
}
}
| 30.697674 | 118 | 0.658333 | [
"MIT"
] | caedmom/MMORPG | Assets/FingerGestures/Samples/Scripts/Internal/SwipeParticlesEmitter.cs | 1,320 | C# |
namespace Gu.Wpf.PropertyGrid.Demo
{
using System.Windows.Controls;
/// <summary>
/// Interaction logic for SettingsView.xaml
/// </summary>
public partial class PlainSettingsView : UserControl
{
public PlainSettingsView()
{
this.InitializeComponent();
}
}
}
| 20.3125 | 56 | 0.606154 | [
"MIT"
] | GuOrg/Gu.Wpf.PropertyGrid | Gu.Wpf.PropertyGrid.Demo/PlainSettingsView.xaml.cs | 327 | 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.Navigation;
using System.Windows.Shapes;
namespace O4ZI.AdminApplication
{
/// <summary>
/// Interaction logic for ManageUsers.xaml
/// </summary>
public partial class ManageUsers : Page
{
public ManageUsers()
{
InitializeComponent();
DataContext = new ManageUsersViewModel();
}
}
}
| 23.266667 | 53 | 0.710602 | [
"Apache-2.0"
] | gerinka/O4ZI | O4ZI.AdminApplication/ManageUsers.xaml.cs | 700 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Wollo.Entities.ViewModels;
using Wollo.Base.Entity;
using System.ComponentModel.DataAnnotations;
using Wollo.Base.LocalResource;
namespace Wollo.Web.Models
{
public class IssuePointTransferDetailViewModel :BaseAuditableViewModel
{
public List<Issue_Point_Transfer_Detail> IssueCashTransferDetails { get; set; }
[Display(Name = "IssuePointsIssuedintoSystem", ResourceType = typeof(Resource))]
public string issuepointsissuedintosystem { get; set; }
[Display(Name = "IssuePointsIssuedToMembers", ResourceType = typeof(Resource))]
public string issuepointsissuedtomembers { get; set; }
[Display(Name = "Dashboard", ResourceType = typeof(Resource))]
public string dashboard { get; set; }
}
} | 30.068966 | 88 | 0.72133 | [
"MIT"
] | umangsunarc/OTH | Wollo.Web/Models/IssuePointTransferDetailViewModel.cs | 874 | 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.
// Template Source: Templates\CSharp\Model\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 Person.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class Person : Entity
{
/// <summary>
/// Gets or sets display name.
/// The person's display name.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "displayName", Required = Newtonsoft.Json.Required.Default)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets given name.
/// The person's given name.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "givenName", Required = Newtonsoft.Json.Required.Default)]
public string GivenName { get; set; }
/// <summary>
/// Gets or sets surname.
/// The person's surname.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "surname", Required = Newtonsoft.Json.Required.Default)]
public string Surname { get; set; }
/// <summary>
/// Gets or sets birthday.
/// The person's birthday.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "birthday", Required = Newtonsoft.Json.Required.Default)]
public string Birthday { get; set; }
/// <summary>
/// Gets or sets person notes.
/// Free-form notes that the the user has taken about this person.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "personNotes", Required = Newtonsoft.Json.Required.Default)]
public string PersonNotes { get; set; }
/// <summary>
/// Gets or sets is favorite.
/// true if the user has flagged this person as a favorite.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isFavorite", Required = Newtonsoft.Json.Required.Default)]
public bool? IsFavorite { get; set; }
/// <summary>
/// Gets or sets scored email addresses.
/// The person's email addresses.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "scoredEmailAddresses", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<ScoredEmailAddress> ScoredEmailAddresses { get; set; }
/// <summary>
/// Gets or sets phones.
/// The person's phone numbers.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "phones", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<Phone> Phones { get; set; }
/// <summary>
/// Gets or sets postal addresses.
/// The person's addresses.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "postalAddresses", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<Location> PostalAddresses { get; set; }
/// <summary>
/// Gets or sets websites.
/// The person's websites.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "websites", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<Website> Websites { get; set; }
/// <summary>
/// Gets or sets job title.
/// The person's job title.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "jobTitle", Required = Newtonsoft.Json.Required.Default)]
public string JobTitle { get; set; }
/// <summary>
/// Gets or sets company name.
/// The name of the person's company.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "companyName", Required = Newtonsoft.Json.Required.Default)]
public string CompanyName { get; set; }
/// <summary>
/// Gets or sets yomi company.
/// The phonetic Japanese name of the person's company.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "yomiCompany", Required = Newtonsoft.Json.Required.Default)]
public string YomiCompany { get; set; }
/// <summary>
/// Gets or sets department.
/// The person's department.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "department", Required = Newtonsoft.Json.Required.Default)]
public string Department { get; set; }
/// <summary>
/// Gets or sets office location.
/// The location of the person's office.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "officeLocation", Required = Newtonsoft.Json.Required.Default)]
public string OfficeLocation { get; set; }
/// <summary>
/// Gets or sets profession.
/// The person's profession.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "profession", Required = Newtonsoft.Json.Required.Default)]
public string Profession { get; set; }
/// <summary>
/// Gets or sets person type.
/// The type of person.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "personType", Required = Newtonsoft.Json.Required.Default)]
public PersonType PersonType { get; set; }
/// <summary>
/// Gets or sets user principal name.
/// The user principal name (UPN) of the person. The UPN is an Internet-style login name for the person based on the Internet standard RFC 822. By convention, this should map to the person's email name. The general format is alias@domain.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "userPrincipalName", Required = Newtonsoft.Json.Required.Default)]
public string UserPrincipalName { get; set; }
/// <summary>
/// Gets or sets im address.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "imAddress", Required = Newtonsoft.Json.Required.Default)]
public string ImAddress { get; set; }
}
}
| 45.327044 | 246 | 0.619398 | [
"MIT"
] | PaoloPia/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/Person.cs | 7,207 | C# |
using System;
using System.Dynamic;
using static Ramda.NET.Currying;
namespace Ramda.NET
{
internal class CurryParams : AbstractLambda
{
internal CurryParams(DynamicDelegate fn) : base(fn, 2) {
}
internal CurryParams(Delegate fn) : this(new DelegateDecorator(fn)) {
}
protected override object TryInvoke(InvokeBinder binder, object[] arguments) {
var arg1IsPlaceHolder = false;
var arg2IsPlaceHolder = false;
var length = arguments.Length;
if (length == 0) {
return new Curry2(fn);
}
else {
var arg1 = arguments[0];
switch (arguments.Length) {
case 1:
return IsPlaceholder(arg1) ? (AbstractLambda)new Curry2(fn) : new Curry1(new Func<object, object>(_arg2 => fn(arg1, _arg2)));
default:
var arg2 = arguments[1];
arg1IsPlaceHolder = IsPlaceholder(arg1);
arg2IsPlaceHolder = IsPlaceholder(arg2);
return arg1IsPlaceHolder && arg2IsPlaceHolder ? (AbstractLambda)new Curry2(fn) : arg1IsPlaceHolder ? new Curry1(new Func<object, object>(_arg1 => {
return fn(_arg1, arg2);
})) : arg2IsPlaceHolder ? new Curry1(new Func<object, object>(_arg2 => {
return fn(arg1, _arg2);
})) : fn(arg1, arg2);
}
}
}
}
} | 35 | 171 | 0.516825 | [
"MIT"
] | sagifogel/Ramda.NET | CurryParams.cs | 1,577 | C# |
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace MelonLoader.Support
{
public class Module : ISupportModule
{
public int GetActiveSceneIndex() => SceneManager.GetActiveScene().buildIndex;
public object StartCoroutine(IEnumerator coroutine) => MelonCoroutines.Start(coroutine);
public void StopCoroutine(object coroutineToken) => MelonCoroutines.Stop((IEnumerator)coroutineToken);
public void UnityDebugLog(string msg) => Debug.Log(msg);
public void Destroy() => MelonLoaderComponent.Destroy();
}
} | 40.333333 | 111 | 0.727273 | [
"Apache-2.0",
"MIT"
] | kagurazakasanae/MelonLoader-YuanShen | MelonLoader.Support.Il2Cpp/SupportModule.cs | 605 | C# |
using Dazinator.AspNet.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Physical;
using NUnit.Framework;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
namespace Sia.Skynet.Tests.Integration
{
public class SkynetWebPortalTests
{
private SkynetWebPortal _skynetWebPortal;
[OneTimeSetUp]
public void OneTimeSetUp()
{
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://skynet.developmomentum.com")
};
_skynetWebPortal = new SkynetWebPortal(httpClient);
}
[Test]
public async Task DownloadFile_FromFileProvider_ExpectedMetadata()
{
// Arrange
var skylink = Skylink.Parse("AAAox419FTqN04JIo3urNNtyxwY9i61cZVnbwNlhGluwOQ");
// Act
var content = await _skynetWebPortal.DownloadFile(skylink);
var result = await content.ReadAsStringAsync();
// Assert
Assert.That(result == "This file is embedded into the assembly");
}
[Test]
public async Task UploadFile_FromFileProvider_ExpectedSkylink()
{
// Arrange
var fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly());
// Act
var skylink = await _skynetWebPortal.UploadFile(fileProvider, "assets/test-file.txt");
// Assert
Assert.That(skylink.ToString() == "AAAox419FTqN04JIo3urNNtyxwY9i61cZVnbwNlhGluwOQ");
}
[Test]
public async Task UploadFile_FromFileInfo_ExpectedSkylink()
{
// Arrange
var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
// Act
var skylink = await _skynetWebPortal.UploadFile(file);
// Assert
Assert.That(skylink.ToString() == "AACcDsB0hiRosExg1JlERWIJP5MVYiAS2F5EkU8VLtlPrA");
}
[Test]
public async Task UploadFile_FromUploadItemDifferentSkynetPath_ExpectedSkylink()
{
// Arrange
var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
var item = new UploadItem(file, skynetPath: "custom/directory/test-file.json");
// Act
var skylink = await _skynetWebPortal.UploadFile(item);
// Assert
Assert.That(skylink.ToString() == "AADoxsbpEVLgFTMco_fS3eiTAvtKx5WCfll5wqHEfyksrQ");
}
[Test]
public async Task UploadFile_FromUploadItemDifferentContentType_ExpectedSkylink()
{
// Arrange
var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
var item = new UploadItem(file, contentType: new MediaTypeHeaderValue("text/xml"));
// Act
var skylink = await _skynetWebPortal.UploadFile(item);
// Assert
Assert.That(skylink.ToString() == "AABDI5UpS0B8tuxKBOiwwKEULV7V4Ln_aBdPPFLWpTlFhA");
}
[Test]
public async Task UploadFiles_FromFileInfo_ExpectedSkylink()
{
// Arrange
var files = new PhysicalFileInfo[]
{
new PhysicalFileInfo(new FileInfo("assets/test-file.json")),
new PhysicalFileInfo(new FileInfo("assets/test-file.txt"))
};
var options = new MultiFileUploadOptions { FileName = "integration-tests" };
// Act
var skylink = await _skynetWebPortal.UploadFiles(files, options);
// Assert
Assert.That(skylink.ToString() == "AACVmVl_KyZTaaS2cdGANxedYtOGJu13urqfc_yQl5jL8w");
}
[Test]
public async Task UploadFiles_FromUploadItemsDifferentSkynetPath_ExpectedSkylink()
{
// Arrange
var fileOne = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
var fileTwo = new PhysicalFileInfo(new FileInfo("assets/test-file.txt"));
var items = new UploadItem[]
{
new UploadItem(fileOne, skynetPath: "custom/directory/test-file.json"),
new UploadItem(fileTwo, skynetPath: "custom/directory/foo/test-file.txt")
};
var options = new MultiFileUploadOptions { FileName = "integration-tests" };
// Act
var skylink = await _skynetWebPortal.UploadFiles(items, options);
// Assert
Assert.That(skylink.ToString() == "AADPKdb7S7E_Uvdy8kjeA4OoPG5HgTZgismv0Ys_BBLgrQ");
}
[Test]
public async Task UploadFiles_FromUploadItemsDifferentContentType_ExpectedSkylink()
{
// Arrange
var fileOne = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
var fileTwo = new PhysicalFileInfo(new FileInfo("assets/test-file.txt"));
var items = new UploadItem[]
{
new UploadItem(fileOne, contentType: new MediaTypeHeaderValue("application/octet-stream")),
new UploadItem(fileTwo, contentType: new MediaTypeHeaderValue("text/xml"))
};
var options = new MultiFileUploadOptions { FileName = "integration-tests" };
// Act
var skylink = await _skynetWebPortal.UploadFiles(items, options);
// Assert
Assert.That(skylink.ToString() == "AADOj5s9MWkkim6Py9suD0DDZWzddCB3ep8C0Vr9W8w9DQ");
}
[Test]
public async Task UploadDirectory_NonRecursive_ExpectedSkylink()
{
// Arrange
var fileProvider = new InMemoryFileProvider();
fileProvider.Directory.AddFile("", new StringFileInfo("this file exists", "exists.txt"));
fileProvider.Directory.AddFile("", new StringFileInfo("file contents", "foo.txt"));
fileProvider.Directory.AddFile("foo", new StringFileInfo("{ \"another\":\"file\" }", "bar.json"));
var options = new MultiFileUploadOptions { FileName = "integration-tests" };
// Act
var skylink = await _skynetWebPortal.UploadDirectory(fileProvider, "", false, options);
// Assert
Assert.That(skylink.ToString() == "AABU1QK8EVh5O47wX2qYyXQrzgRu7sl_ty5lWluhVzEFCw");
}
[Test]
public async Task UploadDirectory_Recursive_ExpectedSkylink()
{
// Arrange
var fileProvider = new InMemoryFileProvider();
fileProvider.Directory.Root.AddFile(new StringFileInfo("this file exists", "exists.txt"));
fileProvider.Directory.Root.AddFile(new StringFileInfo("file contents", "foo.txt"));
fileProvider.Directory.GetOrAddFolder("foo").AddFile(new StringFileInfo("{ \"another\":\"file\" }", "bar.json"));
var options = new MultiFileUploadOptions { FileName = "integration-tests" };
// Act
var skylink = await _skynetWebPortal.UploadDirectory(fileProvider, "", true, options);
// Assert
Assert.That(skylink.ToString() == "AACggsc6nihGIi-1rOhJbx2TJi3W30OgdQKPNr_9Kgfeog");
}
}
} | 37.348718 | 125 | 0.61774 | [
"MIT"
] | drmathias/csharp-skynet | test/Sia.Skynet.Tests.Integration/SkynetWebPortalTests.cs | 7,285 | C# |
using System;
namespace evitoriav2.Net.MimeTypes
{
/* Copied from:
* http://stackoverflow.com/questions/10362140/asp-mvc-are-there-any-constants-for-the-default-content-types */
/// <summary>
/// Common mime types.
/// </summary>
public static class MimeTypeNames
{
///<summary>Used to denote the encoding necessary for files containing JavaScript source code. The alternative MIME type for this file type is text/javascript.</summary>
public const string ApplicationXJavascript = "application/x-javascript";
///<summary>24bit Linear PCM audio at 8-48kHz, 1-N channels; Defined in RFC 3190</summary>
public const string AudioL24 = "audio/L24";
///<summary>Adobe Flash files for example with the extension .swf</summary>
public const string ApplicationXShockwaveFlash = "application/x-shockwave-flash";
///<summary>Arbitrary binary data.[5] Generally speaking this type identifies files that are not associated with a specific application. Contrary to past assumptions by software packages such as Apache this is not a type that should be applied to unknown files. In such a case, a server or application should not indicate a content type, as it may be incorrect, but rather, should omit the type in order to allow the recipient to guess the type.[6]</summary>
public const string ApplicationOctetStream = "application/octet-stream";
///<summary>Atom feeds</summary>
public const string ApplicationAtomXml = "application/atom+xml";
///<summary>Cascading Style Sheets; Defined in RFC 2318</summary>
public const string TextCss = "text/css";
///<summary>commands; subtype resident in Gecko browsers like Firefox 3.5</summary>
public const string TextCmd = "text/cmd";
///<summary>Comma-separated values; Defined in RFC 4180</summary>
public const string TextCsv = "text/csv";
///<summary>deb (file format), a software package format used by the Debian project</summary>
public const string ApplicationXDeb = "application/x-deb";
///<summary>Defined in RFC 1847</summary>
public const string MultipartEncrypted = "multipart/encrypted";
///<summary>Defined in RFC 1847</summary>
public const string MultipartSigned = "multipart/signed";
///<summary>Defined in RFC 2616</summary>
public const string MessageHttp = "message/http";
///<summary>Defined in RFC 4735</summary>
public const string ModelExample = "model/example";
///<summary>device-independent document in DVI format</summary>
public const string ApplicationXDvi = "application/x-dvi";
///<summary>DTD files; Defined by RFC 3023</summary>
public const string ApplicationXmlDtd = "application/xml-dtd";
///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/ecmascript but with looser processing rules) It is not accepted in IE 8 or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329. The "type" attribute of the <script> tag in HTML5 is optional and in practice omitting the media type of JavaScript programs is the most interoperable solution since all browsers have always assumed the correct default even before HTML5.</summary>
public const string ApplicationJavascript = "application/javascript";
///<summary>ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/javascript but with stricter processing rules)</summary>
public const string ApplicationEcmascript = "application/ecmascript";
///<summary>EDI EDIFACT data; Defined in RFC 1767</summary>
public const string ApplicationEdifact = "application/EDIFACT";
///<summary>EDI X12 data; Defined in RFC 1767</summary>
public const string ApplicationEdiX12 = "application/EDI-X12";
///<summary>Email; Defined in RFC 2045 and RFC 2046</summary>
public const string MessagePartial = "message/partial";
///<summary>Email; EML files, MIME files, MHT files, MHTML files; Defined in RFC 2045 and RFC 2046</summary>
public const string MessageRfc822 = "message/rfc822";
///<summary>Extensible Markup Language; Defined in RFC 3023</summary>
public const string TextXml = "text/xml";
///<summary>Flash video (FLV files)</summary>
public const string VideoXFlv = "video/x-flv";
///<summary>GIF image; Defined in RFC 2045 and RFC 2046</summary>
public const string ImageGif = "image/gif";
///<summary>GoogleWebToolkit data</summary>
public const string TextXGwtRpc = "text/x-gwt-rpc";
///<summary>Gzip</summary>
public const string ApplicationXGzip = "application/x-gzip";
///<summary>HTML; Defined in RFC 2854</summary>
public const string TextHtml = "text/html";
///<summary>ICO image; Registered[9]</summary>
public const string ImageVndMicrosoftIcon = "image/vnd.microsoft.icon";
///<summary>IGS files, IGES files; Defined in RFC 2077</summary>
public const string ModelIges = "model/iges";
///<summary>IMDN Instant Message Disposition Notification; Defined in RFC 5438</summary>
public const string MessageImdnXml = "message/imdn+xml";
///<summary>JavaScript Object Notation JSON; Defined in RFC 4627</summary>
public const string ApplicationJson = "application/json";
///<summary>JavaScript Object Notation (JSON) Patch; Defined in RFC 6902</summary>
public const string ApplicationJsonPatch = "application/json-patch+json";
///<summary>JavaScript - Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript. However,text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support. The "type" attribute of the <script> tag in HTML5 is optional and there is no need to use it at all since all browsers have always assumed the correct default (even in HTML 4 where it was required by the specification).</summary>
[Obsolete]
public const string TextJavascript = "text/javascript";
///<summary>JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) - Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).</summary>
public const string ImagePjpeg = "image/pjpeg";
///<summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046</summary>
public const string ImageJpeg = "image/jpeg";
///<summary>jQuery template data</summary>
public const string TextXJqueryTmpl = "text/x-jquery-tmpl";
///<summary>KML files (e.g. for Google Earth)</summary>
public const string ApplicationVndGoogleEarthKmlXml = "application/vnd.google-earth.kml+xml";
///<summary>LaTeX files</summary>
public const string ApplicationXLatex = "application/x-latex";
///<summary>Matroska open media format</summary>
public const string VideoXMatroska = "video/x-matroska";
///<summary>Microsoft Excel 2007 files</summary>
public const string ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
///<summary>Microsoft Excel files</summary>
public const string ApplicationVndMsExcel = "application/vnd.ms-excel";
///<summary>Microsoft Powerpoint 2007 files</summary>
public const string ApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
///<summary>Microsoft Powerpoint files</summary>
public const string ApplicationVndMsPowerpoint = "application/vnd.ms-powerpoint";
///<summary>Microsoft Word 2007 files</summary>
public const string ApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
///<summary>Microsoft Word files[15]</summary>
public const string ApplicationMsword = "application/msword";
///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary>
public const string MultipartAlternative = "multipart/alternative";
///<summary>MIME Email; Defined in RFC 2045 and RFC 2046</summary>
public const string MultipartMixed = "multipart/mixed";
///<summary>MIME Email; Defined in RFC 2387 and used by MHTML (HTML mail)</summary>
public const string MultipartRelated = "multipart/related";
///<summary>MIME Webform; Defined in RFC 2388</summary>
public const string MultipartFormData = "multipart/form-data";
///<summary>Mozilla XUL files</summary>
public const string ApplicationVndMozillaXulXml = "application/vnd.mozilla.xul+xml";
///<summary>MP3 or other MPEG audio; Defined in RFC 3003</summary>
public const string AudioMpeg = "audio/mpeg";
///<summary>MP4 audio</summary>
public const string AudioMp4 = "audio/mp4";
///<summary>MP4 video; Defined in RFC 4337</summary>
public const string VideoMp4 = "video/mp4";
///<summary>MPEG-1 video with multiplexed audio; Defined in RFC 2045 and RFC 2046</summary>
public const string VideoMpeg = "video/mpeg";
///<summary>MSH files, MESH files; Defined in RFC 2077, SILO files</summary>
public const string ModelMesh = "model/mesh";
///<summary>mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046</summary>
public const string AudioBasic = "audio/basic";
///<summary>Ogg Theora or other video (with audio); Defined in RFC 5334</summary>
public const string VideoOgg = "video/ogg";
///<summary>Ogg Vorbis, Speex, Flac and other audio; Defined in RFC 5334</summary>
public const string AudioOgg = "audio/ogg";
///<summary>Ogg, a multimedia bitstream container format; Defined in RFC 5334</summary>
public const string ApplicationOgg = "application/ogg";
///<summary>OP</summary>
public const string ApplicationXopXml = "application/xop+xml";
///<summary>OpenDocument Graphics; Registered[14]</summary>
public const string ApplicationVndOasisOpendocumentGraphics = "application/vnd.oasis.opendocument.graphics";
///<summary>OpenDocument Presentation; Registered[13]</summary>
public const string ApplicationVndOasisOpendocumentPresentation = "application/vnd.oasis.opendocument.presentation";
///<summary>OpenDocument Spreadsheet; Registered[12]</summary>
public const string ApplicationVndOasisOpendocumentSpreadsheet = "application/vnd.oasis.opendocument.spreadsheet";
///<summary>OpenDocument Text; Registered[11]</summary>
public const string ApplicationVndOasisOpendocumentText = "application/vnd.oasis.opendocument.text";
///<summary>p12 files</summary>
public const string ApplicationXPkcs12 = "application/x-pkcs12";
///<summary>p7b and spc files</summary>
public const string ApplicationXPkcs7Certificates = "application/x-pkcs7-certificates";
///<summary>p7c files</summary>
public const string ApplicationXPkcs7Mime = "application/x-pkcs7-mime";
///<summary>p7r files</summary>
public const string ApplicationXPkcs7Certreqresp = "application/x-pkcs7-certreqresp";
///<summary>p7s files</summary>
public const string ApplicationXPkcs7Signature = "application/x-pkcs7-signature";
///<summary>Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778</summary>
public const string ApplicationPdf = "application/pdf";
///<summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083</summary>
public const string ImagePng = "image/png";
///<summary>PostScript; Defined in RFC 2046</summary>
public const string ApplicationPostscript = "application/postscript";
///<summary>QuickTime video; Registered[10]</summary>
public const string VideoQuicktime = "video/quicktime";
///<summary>RAR archive files</summary>
public const string ApplicationXRarCompressed = "application/x-rar-compressed";
///<summary>RealAudio; Documented in RealPlayer Customer Support Answer 2559</summary>
public const string AudioVndRnRealaudio = "audio/vnd.rn-realaudio";
///<summary>Resource Description Framework; Defined by RFC 3870</summary>
public const string ApplicationRdfXml = "application/rdf+xml";
///<summary>RSS feeds</summary>
public const string ApplicationRssXml = "application/rss+xml";
///<summary>SOAP; Defined by RFC 3902</summary>
public const string ApplicationSoapXml = "application/soap+xml";
///<summary>StuffIt archive files</summary>
public const string ApplicationXStuffit = "application/x-stuffit";
///<summary>SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M</summary>
public const string ImageSvgXml = "image/svg+xml";
///<summary>Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302</summary>
public const string ImageTiff = "image/tiff";
///<summary>Tarball files</summary>
public const string ApplicationXTar = "application/x-tar";
///<summary>Textual data; Defined in RFC 2046 and RFC 3676</summary>
public const string TextPlain = "text/plain";
///<summary>TrueType Font No registered MIME type, but this is the most commonly used</summary>
public const string ApplicationXFontTtf = "application/x-font-ttf";
///<summary>vCard (contact information); Defined in RFC 6350</summary>
public const string TextVcard = "text/vcard";
///<summary>Vorbis encoded audio; Defined in RFC 5215</summary>
public const string AudioVorbis = "audio/vorbis";
///<summary>WAV audio; Defined in RFC 2361</summary>
public const string AudioVndWave = "audio/vnd.wave";
///<summary>Web Open Font Format; (candidate recommendation; use application/x-font-woff until standard is official)</summary>
public const string ApplicationFontWoff = "application/font-woff";
///<summary>WebM Matroska-based open media format</summary>
public const string VideoWebm = "video/webm";
///<summary>WebM open media format</summary>
public const string AudioWebm = "audio/webm";
///<summary>Windows Media Audio Redirector; Documented in Microsoft help page</summary>
public const string AudioXMsWax = "audio/x-ms-wax";
///<summary>Windows Media Audio; Documented in Microsoft KB 288102</summary>
public const string AudioXMsWma = "audio/x-ms-wma";
///<summary>Windows Media Video; Documented in Microsoft KB 288102</summary>
public const string VideoXMsWmv = "video/x-ms-wmv";
///<summary>WRL files, VRML files; Defined in RFC 2077</summary>
public const string ModelVrml = "model/vrml";
///<summary>X3D ISO standard for representing 3D computer graphics, X3D XML files</summary>
public const string ModelX3DXml = "model/x3d+xml";
///<summary>X3D ISO standard for representing 3D computer graphics, X3DB binary files</summary>
public const string ModelX3DBinary = "model/x3d+binary";
///<summary>X3D ISO standard for representing 3D computer graphics, X3DV VRML files</summary>
public const string ModelX3DVrml = "model/x3d+vrml";
///<summary>XHTML; Defined by RFC 3236</summary>
public const string ApplicationXhtmlXml = "application/xhtml+xml";
///<summary>ZIP archive files; Registered[7]</summary>
public const string ApplicationZip = "application/zip";
}
}
| 51.570513 | 493 | 0.698819 | [
"MIT"
] | ntgentil/evitoria | aspnet-core/src/evitoriav2.Application/Net/MimeTypes/MimeTypeNames.cs | 16,092 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VideoOnDemand.Entities;
namespace VideoOnDemand.Web.Models
{
public class GeneroViewModel
{
public int? GeneroId { get; set; }
public string Nombre { get; set; }
public string Descripcion { get; set; }
public bool? Activo { get; set; }
public ICollection<Media> Medias { get; set; }
}
} | 24 | 54 | 0.657407 | [
"Apache-2.0"
] | NestorGuemez123/BlockbusterWeb | Aplicacion/Codigo y Pruebas/VideoOnDemand/VideoOnDemand.Web/Models/GeneroViewModel.cs | 434 | C# |
using Turbo.Events.Reports;
namespace Turbo.UnitTests.Events.Reports
{
internal class SampleReport : SimpleReport<SampleConsumer>
{
protected override SampleConsumer CreateConsumerInstance(string source)
{
return new SampleConsumer();
}
public override void Reset()
{
}
public override void Render(IReportView view)
{
}
}
} | 22.1 | 80 | 0.588235 | [
"Unlicense"
] | mikalai-kardash/Turbo | src/Turbo.UnitTests/Events/Reports/SampleReport.cs | 444 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Emulation
{
/// <summary>
/// Switches script execution in the page.
/// </summary>
[CommandResponse(ProtocolName.Emulation.SetScriptExecutionDisabled)]
[SupportedBy("Chrome")]
public class SetScriptExecutionDisabledCommandResponse
{
}
}
| 23.705882 | 69 | 0.796526 | [
"MIT"
] | Digitalbil/ChromeDevTools | source/ChromeDevTools/Protocol/Chrome/Emulation/SetScriptExecutionDisabledCommandResponse.cs | 403 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 09.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableDecimal.NullableInt64{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Decimal>;
using T_DATA2 =System.Nullable<System.Int64>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__02__VN
public static class TestSet_504__param__02__VN
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ == /*}OP*/ vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
};//class TestSet_504__param__02__VN
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableDecimal.NullableInt64
| 26.262774 | 142 | 0.530573 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete/NullableDecimal/NullableInt64/TestSet_504__param__02__VN.cs | 3,600 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Yale.Tests.Theory
{
[TestClass]
public class Emit
{
private const string Key = "Hei";
private const string Value = "Hello";
internal delegate object MyMethod();
[TestMethod]
public void CreateBasicDynamicMethod()
{
var value = "Hello world!";
var dynamicMethod = new DynamicMethod("my_method", typeof(string), null);
var ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldstr, value);
ilGenerator.Emit(OpCodes.Ret);
var result = dynamicMethod.Invoke(null, null);
Assert.AreEqual(value, result);
}
[TestMethod]
public void CreateDynamicMethodThatCallsAStaticMethodNoArguments()
{
var dynamicMethod = new DynamicMethod("my_method", typeof(int), null);
var ilGenerator = dynamicMethod.GetILGenerator();
var staticMethodInfo = typeof(Emit).GetMethod("StaticMethodNoParamsThatReturnInt", BindingFlags.Public | BindingFlags.Static);
ilGenerator.Emit(OpCodes.Call, staticMethodInfo);
ilGenerator.Emit(OpCodes.Ret);
var result = dynamicMethod.Invoke(null, null);
Assert.AreEqual(5, result);
}
public static int StaticMethodNoParamsThatReturnInt()
{
return 5;
}
[TestMethod]
public void CreateDynamicMethodThatCallsAStaticMethod()
{
const int value = 2;
var dynamicMethod = new DynamicMethod("my_method", typeof(int), null);
var ilGenerator = dynamicMethod.GetILGenerator();
var staticMethodInfo = typeof(Emit).GetMethod("StaticMethodThatReturnInt", BindingFlags.Public | BindingFlags.Static);
ilGenerator.Emit(OpCodes.Ldc_I4, value);
ilGenerator.Emit(OpCodes.Call, staticMethodInfo ?? throw new InvalidOperationException());
ilGenerator.Emit(OpCodes.Ret);
var result = dynamicMethod.Invoke(null, null);
Assert.AreEqual(value * 2, result);
}
public static int StaticMethodThatReturnInt(int value)
{
return value * value;
}
[TestMethod]
public void CreateDynamicMethodThatCallsAnInstanceMethod()
{
var dynamicMethod = new DynamicMethod("my_method", typeof(object),
new Type[] { typeof(InternalClassForTest) });
var ilGenerator = dynamicMethod.GetILGenerator();
var methodInfo = typeof(InternalClassForTest).GetMethod("GetValue", BindingFlags.Public | BindingFlags.Instance);
Assert.AreEqual(false, methodInfo != null && methodInfo.IsStatic);
ilGenerator.Emit(OpCodes.Ldarg_0); //Load instance (InternalClassForTest) that has the method
ilGenerator.Emit(OpCodes.Ldstr, Key); //Load method arguments
ilGenerator.Emit(OpCodes.Callvirt, methodInfo); //Call method
ilGenerator.Emit(OpCodes.Ret); //Return value
var result = dynamicMethod.Invoke(null, new object[] { new InternalClassForTest() });
Assert.AreEqual(Value, result);
}
public class InternalClassForTest
{
public InternalClassForTest()
{
_values.Add(Key, Value);
}
private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
public object GetValue(string key)
{
return _values[key];
}
public T DynamicGetVariableValueInternal<T>(string key)
{
return (T)_values[key];
}
}
private DynamicMethod CreateDynamicMethod(Type ownerType)
{
Type[] parameterTypes = { };
return new DynamicMethod("MethodName", typeof(object), parameterTypes, ownerType);
}
}
} | 34.966102 | 138 | 0.61779 | [
"MIT"
] | eskaufel/Yale | test/Yale.Tests/Theory/EmitDelegate.cs | 4,128 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using CsvHelper;
using Resgrid.Framework;
using Resgrid.Model;
using Resgrid.Model.Providers;
using Resgrid.Providers.NumberProvider.Models;
using RestSharp;
using RestSharp.Authenticators;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace Resgrid.Providers.NumberProvider
{
public class TextMessageProvider : ITextMessageProvider
{
private static int _minZone = 1;
private static int _maxZone = 4;
private static IEnumerable<AreaCodeCity> _areaCodes;
public async Task<bool> SendTextMessage(string number, string message, string departmentNumber, MobileCarriers carrier, int departmentId, bool forceGateway = false, bool isCall = false)
{
if (carrier == MobileCarriers.Telstra)
{
return await SendTextMessageViaNexmo(number, message, departmentNumber);
}
else if (Carriers.OnPremSmsGatewayCarriers.Contains(carrier) || forceGateway)
{
if (!Config.SystemBehaviorConfig.DepartmentsToForceBackupSmsProvider.Contains(departmentId))
{
if (!await SendTextMessageViaDiafaan(number, message))
{
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
}
else
{
return true;
}
}
else
{
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
}
}
else if (Config.SystemBehaviorConfig.SmsProviderType == Config.SmsProviderTypes.SignalWire)
{
if (!Config.SystemBehaviorConfig.DepartmentsToForceBackupSmsProvider.Contains(departmentId))
{
if (!await SendTextMessageViaSignalWire(number, message, departmentNumber))
{
return await SendTextMessageViaTwillio(number, message, departmentNumber);
}
else
{
return true;
}
}
else
{
if (isCall)
{
await SendTextMessageViaTwillio(number, message, departmentNumber);
if (Config.SystemBehaviorConfig.AlsoSendToPrimarySmsProvider)
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
else
return true;
}
else
{
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
//SendTextMessageViaTwillio(number, message, departmentNumber);
}
}
}
else
{
if (!Config.SystemBehaviorConfig.DepartmentsToForceBackupSmsProvider.Contains(departmentId))
{
if (!await SendTextMessageViaTwillio(number, message, departmentNumber))
{
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
}
else
{
return true;
}
}
else
{
return await SendTextMessageViaSignalWire(number, message, departmentNumber);
}
}
}
private async Task<bool> SendTextMessageViaNexmo(string number, string message, string departmentNumber)
{
var client = new RestClient(Config.NumberProviderConfig.BaseNexmoUrl);
var request = new RestRequest(GenerateSendTextMessageUrl(number, message, departmentNumber), Method.Get);
var response = await client.ExecuteAsync(request);
if (response.ResponseStatus == ResponseStatus.Completed)
{
if (response.Content.Contains("rejected"))
{
// Error
return false;
}
}
return true;
}
public async Task<bool> SendTextMessageViaTwillio(string number, string message, string departmentNumber)
{
TwilioClient.Init(Config.NumberProviderConfig.TwilioAccountSid, Config.NumberProviderConfig.TwilioAuthToken);
MessageResource messageResource;
try
{
if (String.IsNullOrWhiteSpace(departmentNumber) || NumberHelper.IsNexmoNumber(departmentNumber))
{
//textMessage = twilio.SendMessage(Settings.Default.TwilioResgridNumber, number, message);
messageResource = await MessageResource.CreateAsync(
from: new PhoneNumber(Config.NumberProviderConfig.TwilioResgridNumber),
to: new PhoneNumber(number),
body: message);
if (messageResource != null)
return true;
else
return false;
}
else
{
//textMessage = twilio.SendMessage(departmentNumber, number, message);
//messageResource = MessageResource.Create(
// from: new PhoneNumber(departmentNumber),
// to: new PhoneNumber(number),
// body: message);
messageResource = await MessageResource.CreateAsync(
from: new PhoneNumber(Config.NumberProviderConfig.TwilioResgridNumber),
to: new PhoneNumber(number),
body: message);
if (messageResource != null)
return true;
else
return false;
}
}
catch (Exception ex)
{
return false;
}
}
public async Task<bool> SendTextMessageViaSignalWire(string number, string message, string departmentNumber)
{
try
{
var client = new RestClient(Config.NumberProviderConfig.SignalWireApiUrl);
client.Authenticator = new HttpBasicAuthenticator(Config.NumberProviderConfig.SignalWireAccountSid, Config.NumberProviderConfig.SignalWireApiKey);
var request = new RestRequest(GenerateSendTextMessageUrlForSignalWire(), Method.Post);
if (!number.StartsWith("+"))
{
if (number.Length >= 11)
number = $"+{number}";
else
{
if (number.Length == 10)
{
number = $"+1{number}";
}
}
}
var sendingPhoneNumber = GetSendingPhoneNumber(number);
request.AddJsonBody(new
{
From = sendingPhoneNumber,
To = number,
Body = message
});
var response = await client.ExecuteAsync<SignalWireMessageResponse>(request);
if (response.ResponseStatus == ResponseStatus.Completed)
{
if (response.StatusCode == HttpStatusCode.Created && response.Data.error_code == null)
return true;
else
return false;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
public async Task<bool> SendTextMessageViaDiafaan(string number, string message)
{
var client = new RestClient(Config.NumberProviderConfig.DiafaanSmsGatewayUrl);
var request = new RestRequest(GenerateSendTextMessageUrlForDiafaan(number, message), Method.Get);
var response = await client.ExecuteAsync(request);
if (response.ResponseStatus == ResponseStatus.Completed)
{
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
}
else
{
return false;
}
}
public string GetSendingPhoneNumber(string number)
{
var sendingPhoneNumber = Config.NumberProviderConfig.SignalWireResgridNumber;
try
{
var zone = GetZoneForAreaCode(number);
var possibleNumbers = Config.NumberProviderConfig.SignalWireZones[zone];
var sendingNumber = possibleNumbers.Random();
if (!String.IsNullOrWhiteSpace(sendingNumber))
sendingPhoneNumber = sendingNumber;
}
catch (Exception ex)
{
Logging.LogException(ex);
}
return sendingPhoneNumber;
}
public int GetZoneForAreaCode(string number)
{
try
{
LoadAreaCodeData();
if (_areaCodes != null && _areaCodes.Any())
{
string areaCode = NumberHelper.TryGetAreaCode(number);
if (!String.IsNullOrWhiteSpace(areaCode))
{
var record = _areaCodes.Where(x => x.AreaCode == int.Parse(areaCode)).FirstOrDefault();
if (record != null && !String.IsNullOrWhiteSpace(record.State))
{
switch (record.State.ToUpper())
{
case "ALABAMA":
return 4;
case "ALASKA":
return 1;
case "AMERICAN SAMOA":
return 1;
case "ARIZONA":
return 2;
case "ARKANSAS":
return 4;
case "CALIFORNIA":
return 1;
case "COLORADO":
return 2;
case "CONNECTICUT":
return 5;
case "DELAWARE":
return 5;
case "DISTRICT OF COLUMBIA":
return 6;
case "FEDERATED STATES OF MICRONESIA":
return 1;
case "FLORIDA":
return 4;
case "GEORGIA":
return 4;
case "GUAM":
return 1;
case "HAWAII":
return 1;
case "IDAHO":
return 1;
case "ILLINOIS":
return 3;
case "INDIANA":
return 6;
case "IOWA":
return 3;
case "KANSAS":
return 3;
case "KENTUCKY":
return 4;
case "LOUISIANA":
return 4;
case "MAINE":
return 5;
case "MARSHALL ISLANDS":
return 1;
case "MARYLAND":
return 5;
case "MASSACHUSETTS":
return 5;
case "MICHIGAN":
return 6;
case "MINNESOTA":
return 3;
case "MISSISSIPPI":
return 4;
case "MISSOURI":
return 3;
case "MONTANA":
return 2;
case "NEBRASKA":
return 3;
case "NEVADA":
return 1;
case "NEW HAMPSHIRE":
return 5;
case "NEW JERSEY":
return 5;
case "NEW MEXICO":
return 2;
case "NEW YORK":
return 5;
case "NORTH CAROLINA":
return 6;
case "NORTH DAKOTA":
return 3;
case "NORTHERN MARIANA ISLANDS":
return 1;
case "OHIO":
return 6;
case "OKLAHOMA":
return 4;
case "OREGON":
return 1;
case "PALAU":
return 1;
case "PENNSYLVANIA":
return 5;
case "PUERTO RICO":
return 1;
case "RHODE ISLAND":
return 5;
case "SOUTH CAROLINA":
return 6;
case "SOUTH DAKOTA":
return 3;
case "TENNESSEE":
return 4;
case "TEXAS":
return 4;
case "UTAH":
return 2;
case "VERMONT":
return 5;
case "VIRGIN ISLANDS":
return 1;
case "VIRGINIA":
return 6;
case "WASHINGTON":
return 1;
case "WEST VIRGINIA":
return 6;
case "WISCONSIN":
return 3;
case "WYOMING":
return 2;
}
}
}
}
}
catch (Exception ex)
{
}
var rnd = new Random(DateTime.Now.Millisecond);
int zone = rnd.Next(_minZone, _maxZone);
return zone;
}
private void LoadAreaCodeData()
{
if (_areaCodes == null || !_areaCodes.Any())
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Resgrid.Providers.Number.Data.area-code-cities.csv"))
{
using (var reader = new StreamReader(stream))
{
var config = new CsvHelper.Configuration.CsvConfiguration(new CultureInfo("en-US"));
config.HasHeaderRecord = false;
var csvReader = new CsvReader(reader, config);
_areaCodes = csvReader.GetRecords<AreaCodeCity>().ToList();
}
}
var minKey = Config.NumberProviderConfig.SignalWireZones.First();
var maxKey = Config.NumberProviderConfig.SignalWireZones.Last();
_minZone = minKey.Key;
_maxZone = maxKey.Key;
}
}
private static string GenerateSendTextMessageUrl(string number, string message, string departmentNumber)
{
if (!string.IsNullOrWhiteSpace(departmentNumber))
return string.Format("sms/json?api_key={0}&api_secret={1}&from={2}&to={3}&text={4}", Config.NumberProviderConfig.NexmoApiKey, Config.NumberProviderConfig.NexmoApiSecret, departmentNumber, number, HttpUtility.UrlEncode(message));
else
return string.Format("sms/json?api_key={0}&api_secret={1}&from={2}&to={3}&text={4}", Config.NumberProviderConfig.NexmoApiKey, Config.NumberProviderConfig.NexmoApiSecret, "12132633666", number, HttpUtility.UrlEncode(message));
}
private static string GenerateSendTextMessageUrlForDiafaan(string number, string message)
{
return $"http/send-message/?username={HttpUtility.UrlEncode(Config.NumberProviderConfig.DiafaanSmsGatewayUserName)}&password={HttpUtility.UrlEncode(Config.NumberProviderConfig.DiafaanSmsGatewayPassword)}&to={HttpUtility.UrlEncode(number)}&message={HttpUtility.UrlEncode(message)}";
}
private static string GenerateSendTextMessageUrlForSignalWire()
{
return $"/api/laml/2010-04-01/Accounts/{Resgrid.Config.NumberProviderConfig.SignalWireAccountSid}/Messages.json";
}
}
}
| 27.317181 | 284 | 0.651347 | [
"Apache-2.0"
] | Resgrid/core | Providers/Resgrid.Providers.Number/TextMessageProvider.cs | 12,404 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// koubei.catering.dish.material.modify
/// </summary>
public class KoubeiCateringDishMaterialModifyRequest : IAlipayRequest<KoubeiCateringDishMaterialModifyResponse>
{
/// <summary>
/// 口碑菜品库加料修改接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.catering.dish.material.modify";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if (udfParams == null)
{
udfParams = new Dictionary<string, string>();
}
udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
if (udfParams != null)
{
parameters.AddAll(udfParams);
}
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.608696 | 115 | 0.540823 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Request/KoubeiCateringDishMaterialModifyRequest.cs | 3,282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Wing.Configuration;
using Wing.ServiceProvider;
namespace Wing.Consul
{
public class IntervalConsulProvider : IDiscoveryServiceProvider, IDisposable
{
private List<Service> _services;
private bool _wait = false;
private Timer _timer;
public IntervalConsulProvider(int interval, IDiscoveryServiceProvider discoveryServiceProvider)
{
_services = new List<Service>();
_timer = new Timer(async x =>
{
if (_wait)
{
return;
}
_wait = true;
_services = await discoveryServiceProvider.Get();
_wait = false;
}, interval, 0, interval);
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
Dispose();
};
}
public void Dispose()
{
_timer?.Dispose();
}
public Task<List<Service>> Get()
{
return Task.FromResult(_services);
}
public Task<List<Service>> Get(string serviceName)
{
return Task.FromResult(_services.Where(s => s.Name.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToList());
}
public Task<List<Service>> GetGrpcServices(string serviceName)
{
return Task.FromResult(_services.Where(s => s.Name.Equals(serviceName, StringComparison.OrdinalIgnoreCase) && s.Tags.Contains(ServiceTag.GRPC)).ToList());
}
public Task<List<Service>> GetHttpServices(string serviceName)
{
return Task.FromResult(_services.Where(s => s.Name.Equals(serviceName, StringComparison.OrdinalIgnoreCase) && !s.Tags.Contains(ServiceTag.GRPC)).ToList());
}
}
}
| 30.777778 | 167 | 0.587932 | [
"MIT"
] | PingPongBoy/Wing | src/Wing.Consul/IntervalConsulProvider.cs | 1,941 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IElasticsearchDomainCognitoOptions), fullyQualifiedName: "aws.ElasticsearchDomainCognitoOptions")]
public interface IElasticsearchDomainCognitoOptions
{
[JsiiProperty(name: "identityPoolId", typeJson: "{\"primitive\":\"string\"}")]
string IdentityPoolId
{
get;
}
[JsiiProperty(name: "roleArn", typeJson: "{\"primitive\":\"string\"}")]
string RoleArn
{
get;
}
[JsiiProperty(name: "userPoolId", typeJson: "{\"primitive\":\"string\"}")]
string UserPoolId
{
get;
}
[JsiiProperty(name: "enabled", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
bool? Enabled
{
get
{
return null;
}
}
[JsiiTypeProxy(nativeType: typeof(IElasticsearchDomainCognitoOptions), fullyQualifiedName: "aws.ElasticsearchDomainCognitoOptions")]
internal sealed class _Proxy : DeputyBase, aws.IElasticsearchDomainCognitoOptions
{
private _Proxy(ByRefValue reference): base(reference)
{
}
[JsiiProperty(name: "identityPoolId", typeJson: "{\"primitive\":\"string\"}")]
public string IdentityPoolId
{
get => GetInstanceProperty<string>()!;
}
[JsiiProperty(name: "roleArn", typeJson: "{\"primitive\":\"string\"}")]
public string RoleArn
{
get => GetInstanceProperty<string>()!;
}
[JsiiProperty(name: "userPoolId", typeJson: "{\"primitive\":\"string\"}")]
public string UserPoolId
{
get => GetInstanceProperty<string>()!;
}
[JsiiOptional]
[JsiiProperty(name: "enabled", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true)]
public bool? Enabled
{
get => GetInstanceProperty<bool?>();
}
}
}
}
| 30.944444 | 140 | 0.547127 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IElasticsearchDomainCognitoOptions.cs | 2,228 | 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: MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsErfCRequest.
/// </summary>
public partial class WorkbookFunctionsErfCRequest : BaseRequest, IWorkbookFunctionsErfCRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsErfCRequest.
/// </summary>
public WorkbookFunctionsErfCRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsErfCRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsErfCRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsErfCRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsErfCRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.609195 | 153 | 0.577881 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/WorkbookFunctionsErfCRequest.cs | 3,011 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class RayCastVisualizer : MonoBehaviour
{
public GameObject CursorPrefab;
public Pose? Pose => _pose;
private GameObject _cursor;
private LayerMask _mask;
private Pose? _pose;
private ARRaycastManager _raycastManager;
private ARPlaneManager _planeManager;
void Start()
{
_mask = LayerMask.GetMask("DebugPlane");
_raycastManager = FindObjectOfType<ARRaycastManager>();
_planeManager = FindObjectOfType<ARPlaneManager>();
_cursor = Instantiate(CursorPrefab);
HideCursor();
}
void Update()
{
var ray = new Ray(CameraCache.Transform.position, CameraCache.Transform.forward);
if (Application.isEditor)
{
if (Physics.Raycast(ray, out var hitInfo, 100, _mask))
{
ShowCursorAt(hitInfo.point);
return;
}
}
else
{
// Exercise: Perform a Raycast and find the nearest, "valid" AR plane using the ARRaycastManager.
// Hints:
// - Use _raycastManager.Raycast with TrackableType PlaneWithinPolygon
// - Use the ARPlaneManager to get the plane from the hit
// - ARPlane.IsValid() is an extension method to check the validity
// Your code here:
}
HideCursor();
}
private void ShowCursorAt(Vector3 cursorPos)
{
if (!_cursor.activeSelf)
{
_cursor.SetActive(true);
}
var cameraPos = CameraCache.Transform.position;
_cursor.transform.position = cursorPos;
_cursor.transform.LookAt(new Vector3(cameraPos.x, cursorPos.y, cameraPos.z));
_pose = _cursor.transform.ToPose();
}
private void HideCursor()
{
_cursor.SetActive(false);
_pose = null;
}
} | 27.930556 | 109 | 0.612133 | [
"Apache-2.0"
] | brookman/mobile-ar-public | projects/2-Heli-Rescue-Exercises/Assets/Scripts/Setup/RayCastVisualizer.cs | 2,013 | 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 TP.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;
}
}
}
}
| 36.166667 | 152 | 0.563134 | [
"Apache-2.0"
] | ismailelghazi/ado.net | TP/TP/Properties/Settings.Designer.cs | 1,087 | C# |
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.Applets;
using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Kernel.Common;
using Ryujinx.HLE.HOS.Services.SurfaceFlinger;
using Ryujinx.HLE.HOS.Services.Vi.RootService.ApplicationDisplayService;
using Ryujinx.HLE.Ui;
using Ryujinx.HLE.HOS.Services.Vi.RootService.ApplicationDisplayService.Types;
using Ryujinx.HLE.HOS.Services.Vi.Types;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace Ryujinx.HLE.HOS.Services.Vi.RootService
{
class IApplicationDisplayService : IpcService
{
private readonly ViServiceType _serviceType;
private readonly List<DisplayInfo> _displayInfo;
private readonly Dictionary<ulong, DisplayInfo> _openDisplayInfo;
private int _vsyncEventHandle;
public IApplicationDisplayService(ViServiceType serviceType)
{
_serviceType = serviceType;
_displayInfo = new List<DisplayInfo>();
_openDisplayInfo = new Dictionary<ulong, DisplayInfo>();
void AddDisplayInfo(string name, bool layerLimitEnabled, ulong layerLimitMax, ulong width, ulong height)
{
DisplayInfo displayInfo = new DisplayInfo()
{
Name = new Array64<byte>(),
LayerLimitEnabled = layerLimitEnabled,
Padding = new Array7<byte>(),
LayerLimitMax = layerLimitMax,
Width = width,
Height = height
};
Encoding.ASCII.GetBytes(name).AsSpan().CopyTo(displayInfo.Name.ToSpan());
_displayInfo.Add(displayInfo);
}
AddDisplayInfo("Default", true, 1, 1920, 1080);
AddDisplayInfo("External", true, 1, 1920, 1080);
AddDisplayInfo("Edid", true, 1, 0, 0);
AddDisplayInfo("Internal", true, 1, 1920, 1080);
AddDisplayInfo("Null", false, 0, 1920, 1080);
}
[CommandHipc(100)]
// GetRelayService() -> object<nns::hosbinder::IHOSBinderDriver>
public ResultCode GetRelayService(ServiceCtx context)
{
// FIXME: Should be _serviceType != ViServiceType.Application but guests crashes if we do this check.
if (_serviceType > ViServiceType.System)
{
return ResultCode.InvalidRange;
}
MakeObject(context, new HOSBinderDriverServer());
return ResultCode.Success;
}
[CommandHipc(101)]
// GetSystemDisplayService() -> object<nn::visrv::sf::ISystemDisplayService>
public ResultCode GetSystemDisplayService(ServiceCtx context)
{
// FIXME: Should be _serviceType == ViServiceType.System but guests crashes if we do this check.
if (_serviceType > ViServiceType.System)
{
return ResultCode.InvalidRange;
}
MakeObject(context, new ISystemDisplayService(this));
return ResultCode.Success;
}
[CommandHipc(102)]
// GetManagerDisplayService() -> object<nn::visrv::sf::IManagerDisplayService>
public ResultCode GetManagerDisplayService(ServiceCtx context)
{
if (_serviceType > ViServiceType.System)
{
return ResultCode.InvalidRange;
}
MakeObject(context, new IManagerDisplayService(this));
return ResultCode.Success;
}
[CommandHipc(103)] // 2.0.0+
// GetIndirectDisplayTransactionService() -> object<nns::hosbinder::IHOSBinderDriver>
public ResultCode GetIndirectDisplayTransactionService(ServiceCtx context)
{
if (_serviceType > ViServiceType.System)
{
return ResultCode.InvalidRange;
}
MakeObject(context, new HOSBinderDriverServer());
return ResultCode.Success;
}
[CommandHipc(1000)]
// ListDisplays() -> (u64 count, buffer<nn::vi::DisplayInfo, 6>)
public ResultCode ListDisplays(ServiceCtx context)
{
ulong displayInfoBuffer = context.Request.ReceiveBuff[0].Position;
// TODO: Determine when more than one display is needed.
ulong displayCount = 1;
for (int i = 0; i < (int)displayCount; i++)
{
context.Memory.Write(displayInfoBuffer + (ulong)(i * Unsafe.SizeOf<DisplayInfo>()), _displayInfo[i]);
}
context.ResponseData.Write(displayCount);
return ResultCode.Success;
}
[CommandHipc(1010)]
// OpenDisplay(nn::vi::DisplayName) -> u64 display_id
public ResultCode OpenDisplay(ServiceCtx context)
{
string name = "";
for (int index = 0; index < 8 && context.RequestData.BaseStream.Position < context.RequestData.BaseStream.Length; index++)
{
byte chr = context.RequestData.ReadByte();
if (chr >= 0x20 && chr < 0x7f)
{
name += (char)chr;
}
}
return OpenDisplayImpl(context, name);
}
[CommandHipc(1011)]
// OpenDefaultDisplay() -> u64 display_id
public ResultCode OpenDefaultDisplay(ServiceCtx context)
{
return OpenDisplayImpl(context, "Default");
}
private ResultCode OpenDisplayImpl(ServiceCtx context, string name)
{
if (name == "")
{
return ResultCode.InvalidValue;
}
int displayId = _displayInfo.FindIndex(display => Encoding.ASCII.GetString(display.Name.ToSpan()).Trim('\0') == name);
if (displayId == -1)
{
return ResultCode.InvalidValue;
}
if (!_openDisplayInfo.TryAdd((ulong)displayId, _displayInfo[displayId]))
{
return ResultCode.AlreadyOpened;
}
context.ResponseData.Write((ulong)displayId);
return ResultCode.Success;
}
[CommandHipc(1020)]
// CloseDisplay(u64 display_id)
public ResultCode CloseDisplay(ServiceCtx context)
{
ulong displayId = context.RequestData.ReadUInt64();
if (!_openDisplayInfo.Remove(displayId))
{
return ResultCode.InvalidValue;
}
return ResultCode.Success;
}
[CommandHipc(1101)]
// SetDisplayEnabled(u32 enabled_bool, u64 display_id)
public ResultCode SetDisplayEnabled(ServiceCtx context)
{
// NOTE: Stubbed in original service.
return ResultCode.Success;
}
[CommandHipc(1102)]
// GetDisplayResolution(u64 display_id) -> (u64 width, u64 height)
public ResultCode GetDisplayResolution(ServiceCtx context)
{
// NOTE: Not used in original service.
// ulong displayId = context.RequestData.ReadUInt64();
// NOTE: Returns ResultCode.InvalidArguments if width and height pointer are null, doesn't occur in our case.
// NOTE: Values are hardcoded in original service.
context.ResponseData.Write(1280UL); // Width
context.ResponseData.Write(720UL); // Height
return ResultCode.Success;
}
[CommandHipc(2020)]
// OpenLayer(nn::vi::DisplayName, u64, nn::applet::AppletResourceUserId, pid) -> (u64, buffer<bytes, 6>)
public ResultCode OpenLayer(ServiceCtx context)
{
// TODO: support multi display.
byte[] displayName = context.RequestData.ReadBytes(0x40);
long layerId = context.RequestData.ReadInt64();
long userId = context.RequestData.ReadInt64();
ulong parcelPtr = context.Request.ReceiveBuff[0].Position;
IBinder producer = context.Device.System.SurfaceFlinger.OpenLayer(context.Request.HandleDesc.PId, layerId);
context.Device.System.SurfaceFlinger.SetRenderLayer(layerId);
Parcel parcel = new Parcel(0x28, 0x4);
parcel.WriteObject(producer, "dispdrv\0");
ReadOnlySpan<byte> parcelData = parcel.Finish();
context.Memory.Write(parcelPtr, parcelData);
context.ResponseData.Write((long)parcelData.Length);
return ResultCode.Success;
}
[CommandHipc(2021)]
// CloseLayer(u64)
public ResultCode CloseLayer(ServiceCtx context)
{
long layerId = context.RequestData.ReadInt64();
context.Device.System.SurfaceFlinger.CloseLayer(layerId);
return ResultCode.Success;
}
[CommandHipc(2030)]
// CreateStrayLayer(u32, u64) -> (u64, u64, buffer<bytes, 6>)
public ResultCode CreateStrayLayer(ServiceCtx context)
{
long layerFlags = context.RequestData.ReadInt64();
long displayId = context.RequestData.ReadInt64();
ulong parcelPtr = context.Request.ReceiveBuff[0].Position;
// TODO: support multi display.
IBinder producer = context.Device.System.SurfaceFlinger.CreateLayer(0, out long layerId);
context.Device.System.SurfaceFlinger.SetRenderLayer(layerId);
Parcel parcel = new Parcel(0x28, 0x4);
parcel.WriteObject(producer, "dispdrv\0");
ReadOnlySpan<byte> parcelData = parcel.Finish();
context.Memory.Write(parcelPtr, parcelData);
context.ResponseData.Write(layerId);
context.ResponseData.Write((long)parcelData.Length);
return ResultCode.Success;
}
[CommandHipc(2031)]
// DestroyStrayLayer(u64)
public ResultCode DestroyStrayLayer(ServiceCtx context)
{
long layerId = context.RequestData.ReadInt64();
context.Device.System.SurfaceFlinger.CloseLayer(layerId);
return ResultCode.Success;
}
[CommandHipc(2101)]
// SetLayerScalingMode(u32, u64)
public ResultCode SetLayerScalingMode(ServiceCtx context)
{
/*
uint sourceScalingMode = context.RequestData.ReadUInt32();
ulong layerId = context.RequestData.ReadUInt64();
*/
// NOTE: Original service converts SourceScalingMode to DestinationScalingMode but does nothing with the converted value.
return ResultCode.Success;
}
[CommandHipc(2102)] // 5.0.0+
// ConvertScalingMode(u32 source_scaling_mode) -> u64 destination_scaling_mode
public ResultCode ConvertScalingMode(ServiceCtx context)
{
SourceScalingMode scalingMode = (SourceScalingMode)context.RequestData.ReadInt32();
DestinationScalingMode? convertedScalingMode = scalingMode switch
{
SourceScalingMode.None => DestinationScalingMode.None,
SourceScalingMode.Freeze => DestinationScalingMode.Freeze,
SourceScalingMode.ScaleAndCrop => DestinationScalingMode.ScaleAndCrop,
SourceScalingMode.ScaleToWindow => DestinationScalingMode.ScaleToWindow,
SourceScalingMode.PreserveAspectRatio => DestinationScalingMode.PreserveAspectRatio,
_ => null,
};
if (!convertedScalingMode.HasValue)
{
// Scaling mode out of the range of valid values.
return ResultCode.InvalidArguments;
}
if (scalingMode != SourceScalingMode.ScaleToWindow && scalingMode != SourceScalingMode.PreserveAspectRatio)
{
// Invalid scaling mode specified.
return ResultCode.InvalidScalingMode;
}
context.ResponseData.Write((ulong)convertedScalingMode);
return ResultCode.Success;
}
private ulong GetA8B8G8R8LayerSize(int width, int height, out int pitch, out int alignment)
{
const int defaultAlignment = 0x1000;
const ulong defaultSize = 0x20000;
alignment = defaultAlignment;
pitch = BitUtils.AlignUp(BitUtils.DivRoundUp(width * 32, 8), 64);
int memorySize = pitch * BitUtils.AlignUp(height, 64);
ulong requiredMemorySize = (ulong)BitUtils.AlignUp(memorySize, alignment);
return (requiredMemorySize + defaultSize - 1) / defaultSize * defaultSize;
}
[CommandHipc(2450)]
// GetIndirectLayerImageMap(s64 width, s64 height, u64 handle, nn::applet::AppletResourceUserId, pid) -> (s64, s64, buffer<bytes, 0x46>)
public ResultCode GetIndirectLayerImageMap(ServiceCtx context)
{
// The size of the layer buffer should be an aligned multiple of width * height
// because it was created using GetIndirectLayerImageRequiredMemoryInfo as a guide.
long layerWidth = context.RequestData.ReadInt64();
long layerHeight = context.RequestData.ReadInt64();
long layerHandle = context.RequestData.ReadInt64();
ulong layerBuffPosition = context.Request.ReceiveBuff[0].Position;
ulong layerBuffSize = context.Request.ReceiveBuff[0].Size;
// Get the pitch of the layer that is necessary to render correctly.
ulong size = GetA8B8G8R8LayerSize((int)layerWidth, (int)layerHeight, out int pitch, out _);
Debug.Assert(layerBuffSize == size);
RenderingSurfaceInfo surfaceInfo = new RenderingSurfaceInfo(ColorFormat.A8B8G8R8, (uint)layerWidth, (uint)layerHeight, (uint)pitch, (uint)layerBuffSize);
// Get the applet associated with the handle.
object appletObject = context.Device.System.AppletState.IndirectLayerHandles.GetData((int)layerHandle);
if (appletObject == null)
{
Logger.Error?.Print(LogClass.ServiceVi, $"Indirect layer handle {layerHandle} does not match any applet");
return ResultCode.Success;
}
Debug.Assert(appletObject is IApplet);
IApplet applet = appletObject as IApplet;
if (!applet.DrawTo(surfaceInfo, context.Memory, layerBuffPosition))
{
Logger.Warning?.Print(LogClass.ServiceVi, $"Applet did not draw on indirect layer handle {layerHandle}");
return ResultCode.Success;
}
context.ResponseData.Write(layerWidth);
context.ResponseData.Write(layerHeight);
return ResultCode.Success;
}
[CommandHipc(2460)]
// GetIndirectLayerImageRequiredMemoryInfo(u64 width, u64 height) -> (u64 size, u64 alignment)
public ResultCode GetIndirectLayerImageRequiredMemoryInfo(ServiceCtx context)
{
/*
// Doesn't occur in our case.
if (sizePtr == null || address_alignmentPtr == null)
{
return ResultCode.InvalidArguments;
}
*/
int width = (int)context.RequestData.ReadUInt64();
int height = (int)context.RequestData.ReadUInt64();
if (height < 0 || width < 0)
{
return ResultCode.InvalidLayerSize;
}
else
{
/*
// Doesn't occur in our case.
if (!service_initialized)
{
return ResultCode.InvalidArguments;
}
*/
// NOTE: The official service setup a A8B8G8R8 texture with a linear layout and then query its size.
// As we don't need this texture on the emulator, we can just simplify this logic and directly
// do a linear layout size calculation. (stride * height * bytePerPixel)
ulong size = GetA8B8G8R8LayerSize(width, height, out int pitch, out int alignment);
context.ResponseData.Write(size);
context.ResponseData.Write(alignment);
}
return ResultCode.Success;
}
[CommandHipc(5202)]
// GetDisplayVsyncEvent(u64) -> handle<copy>
public ResultCode GetDisplayVSyncEvent(ServiceCtx context)
{
ulong displayId = context.RequestData.ReadUInt64();
if (!_openDisplayInfo.ContainsKey(displayId))
{
return ResultCode.InvalidValue;
}
if (_vsyncEventHandle == 0)
{
if (context.Process.HandleTable.GenerateHandle(context.Device.System.VsyncEvent.ReadableEvent, out _vsyncEventHandle) != KernelResult.Success)
{
throw new InvalidOperationException("Out of handles!");
}
}
context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_vsyncEventHandle);
return ResultCode.Success;
}
}
} | 36.778947 | 165 | 0.597768 | [
"MIT"
] | 2579768776/Ryujinx | Ryujinx.HLE/HOS/Services/Vi/RootService/IApplicationDisplayService.cs | 17,470 | C# |
using System;
using System.Collections.Generic;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AlgoTest.LeetCode.Minimum_Operations_to_Make_Array_Equal
{
[TestClass]
public class Minimum_Operations_to_Make_Array_Equal
{
/*
* 7 5 3 1
* 1,3,5,7, 9,11,13,15 //8
* x * 2 -1
*
* 8 6 4 2
* 1,3,5,7, 9, 11,13,15,17
*
*/
[TestMethod]
public void Test()
{
Assert.AreEqual(4, MinOperations(4));
Assert.AreEqual(2, MinOperations(3));
Assert.AreEqual(6, MinOperations(5));
Assert.AreEqual(9, MinOperations(6));
Assert.AreEqual(16, MinOperations(8));
Assert.AreEqual(20, MinOperations(9));
Assert.AreEqual(0, MinOperations(1));
Assert.AreEqual(1, MinOperations(2));
}
public int MinOperations(int n)
{
var count = 0;
var factor = n / 2;
if (n % 2 == 0)
for (var i = 1; i <= factor; i++) count += i * 2 - 1;
else
for (var i = 1; i <= factor; i++) count += i * 2;
return count;
}
}
}
| 27.270833 | 69 | 0.510313 | [
"MIT"
] | sagasu/Algo-DataStructures | AlgoTest/LeetCode/Minimum Operations to Make Array Equal/Minimum Operations to Make Array Equal.cs | 1,311 | C# |
using UIKit;
namespace PhotoPicker
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 24.5625 | 91 | 0.592875 | [
"MIT"
] | program12017/DesarrolloiOS611 | Segundo Parcial/Practicas/PhotoPicker/PhotoPicker/Main.cs | 395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace CharacterMultiplier
{
class CharacterMultiplier
{
static BigInteger CharSum(string[] input)
{
int[] firstArraySum = input[0].Select(c => (int)c).ToArray();
int[] secondArraySum = input[1].Select(c => (int)c).ToArray();
int minArrayLength = Math.Min(firstArraySum.Length, secondArraySum.Length);
int maxArrayLength = Math.Max(firstArraySum.Length, secondArraySum.Length);
BigInteger sum = new BigInteger(0);
for(int i = 0; i < minArrayLength; i++)
{
sum += firstArraySum[i] * secondArraySum[i];
}
if(firstArraySum.Length > secondArraySum.Length)
{
int s = firstArraySum.Skip(minArrayLength).Take(maxArrayLength - minArrayLength).Sum();
sum += s;
}
else if (secondArraySum.Length > firstArraySum.Length)
{
int s = secondArraySum.Skip(minArrayLength).Take(maxArrayLength - minArrayLength).Sum();
sum += s;
}
return sum;
}
static void Main(string[] args)
{
string[] input = Console.ReadLine()
.Split(' ')
.Where(p => !string.IsNullOrWhiteSpace(p))
.ToArray();
Console.WriteLine(CharSum(input));
}
}
}
| 31.75 | 104 | 0.517868 | [
"MIT"
] | MustafaAmish/All-Curses-in-SoftUni | 02. Tech Module/Programming Fundamentals/24. Strings and Text Processing - Exercises/Strings and Text Processing - Exercises/CharacterMultiplier/CharacterMultiplier.cs | 1,653 | C# |
namespace PivotalTrackerDotNet.Domain
{
public enum ProjectRole
{
Owner,
Member,
Viewer,
Inactive
}
} | 14.6 | 38 | 0.554795 | [
"MIT"
] | Charcoals/PivotalTracker.NET | PivotalTrackerDotNet/Domain/ProjectRole.cs | 148 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using RomanticWeb.Converters;
using RomanticWeb.Dynamic;
using RomanticWeb.Entities;
using RomanticWeb.Entities.ResultAggregations;
using RomanticWeb.LightInject;
using RomanticWeb.Mapping;
using RomanticWeb.Mapping.Conventions;
using RomanticWeb.Mapping.Model;
using RomanticWeb.Mapping.Sources;
using RomanticWeb.Mapping.Visitors;
using RomanticWeb.NamedGraphs;
using RomanticWeb.Ontologies;
using RomanticWeb.Updates;
namespace RomanticWeb.ComponentModel
{
internal delegate INodeConverter GetConverterDelegate(Type converterType);
internal delegate IEnumerable<INodeConverter> GetAllConvertersDelegate();
internal class InternalComponentsCompositionRoot : ICompositionRoot
{
public void Compose(IServiceRegistry registry)
{
registry.Register<IConverterCatalog, ConverterCatalog>(new PerContainerLifetime());
registry.Register<IResultTransformerCatalog, ResultTransformerCatalog>(new PerContainerLifetime());
registry.RegisterAssembly(GetType().Assembly, () => new PerContainerLifetime(), (service, impl) => service == typeof(IResultAggregator));
registry.Register(factory => CreateEntitySource(factory), new PerContainerLifetime());
registry.Register<EmitHelper>(new PerContainerLifetime());
registry.Register<MappingModelBuilder>();
registry.Register(factory => CreateMappingContext(factory), new PerContainerLifetime());
registry.Register(factory => CreateMappingsRepository(factory), new PerContainerLifetime());
registry.Register<IEntityCaster, ImpromptuInterfaceCaster>(new PerScopeLifetime());
registry.Register(factory => CreateEntityProxy(factory));
registry.Register<IDatasetChangesTracker, DatasetChanges>(new PerScopeLifetime());
var container = (IServiceContainer)registry;
container.RegisterInstance<GetConverterDelegate>(type =>
{
if (!container.CanGetInstance(type, string.Empty))
{
container.Register(typeof(INodeConverter), type, type.FullName, new PerContainerLifetime());
container.Register(type, new PerContainerLifetime());
}
return (INodeConverter)container.GetInstance(type);
});
container.RegisterInstance<GetAllConvertersDelegate>(container.GetAllInstances<INodeConverter>);
}
private static Func<Entity, IEntityMapping, IEntityProxy> CreateEntityProxy(IServiceFactory factory)
{
return (entity, mapping) =>
{
var transformerCatalog = factory.GetInstance<IResultTransformerCatalog>();
var namedGraphSeletor = factory.GetInstance<INamedGraphSelector>();
return new EntityProxy(entity, mapping, transformerCatalog, namedGraphSeletor);
};
}
private static IEntitySource CreateEntitySource(IServiceFactory factory)
{
var entitySource = factory.GetInstance<IEntitySource>("EntitySource");
entitySource.MetaGraphUri = factory.GetInstance<Uri>("MetaGraphUri");
return entitySource;
}
private static MappingContext CreateMappingContext(IServiceFactory factory)
{
var actualOntologyProvider = new CompoundOntologyProvider(factory.GetAllInstances<IOntologyProvider>());
return new MappingContext(actualOntologyProvider, factory.GetAllInstances<IConvention>());
}
private static IMappingsRepository CreateMappingsRepository(IServiceFactory factory)
{
var visitors = from chain in factory.GetAllInstances<MappingProviderVisitorChain>()
from type in chain.Visitors
select (IMappingProviderVisitor)factory.GetInstance(type);
return new MappingsRepository(
factory.GetInstance<MappingModelBuilder>(),
factory.GetAllInstances<IMappingProviderSource>(),
visitors,
factory.GetAllInstances<IMappingModelVisitor>());
}
}
} | 43.907216 | 149 | 0.689598 | [
"BSD-3-Clause"
] | MakoLab/RomanticWeb | RomanticWeb/ComponentModel/InternalComponentsCompositionRoot.cs | 4,261 | C# |
/*
* OpenDoc_API-文档访问
*
* API to access AnyShare 如有任何疑问,可到开发者社区提问:https://developers.aishu.cn # Authentication - 调用需要鉴权的API,必须将token放在HTTP header中:\"Authorization: Bearer ACCESS_TOKEN\" - 对于GET请求,除了将token放在HTTP header中,也可以将token放在URL query string中:\"tokenid=ACCESS_TOKEN\"
*
* The version of the OpenAPI document: 6.0.10
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = AnyShareSDK.Client.OpenAPIDateConverter;
namespace AnyShareSDK.Model
{
/// <summary>
/// MessageGetResMsgType5
/// </summary>
[DataContract]
public partial class MessageGetResMsgType5 : IEquatable<MessageGetResMsgType5>, IValidatableObject
{
/// <summary>
/// 表示访问者类型
/// </summary>
/// <value>表示访问者类型</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum AccessortypeEnum
{
/// <summary>
/// Enum User for value: user
/// </summary>
[EnumMember(Value = "user")]
User = 1,
/// <summary>
/// Enum Department for value: department
/// </summary>
[EnumMember(Value = "department")]
Department = 2,
/// <summary>
/// Enum Contactor for value: contactor
/// </summary>
[EnumMember(Value = "contactor")]
Contactor = 3
}
/// <summary>
/// 表示访问者类型
/// </summary>
/// <value>表示访问者类型</value>
[DataMember(Name="accessortype", EmitDefaultValue=false)]
public AccessortypeEnum Accessortype { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MessageGetResMsgType5" /> class.
/// </summary>
[JsonConstructorAttribute]
protected MessageGetResMsgType5() { }
/// <summary>
/// Initializes a new instance of the <see cref="MessageGetResMsgType5" /> class.
/// </summary>
/// <param name="accessorname">接收者名字,如果是外链,为空字符串 (required).</param>
/// <param name="accessortype">表示访问者类型 (required).</param>
/// <param name="csf">文件密级,5~15,文件夹为0 (required).</param>
/// <param name="id">此条消息的唯一标识 (required).</param>
/// <param name="isdir">是否为文件夹 (required).</param>
/// <param name="isread">消息是否已读 (required).</param>
/// <param name="sender">发送者名字 (required).</param>
/// <param name="time">共享操作的时间(unix utc ns) (required).</param>
/// <param name="type">此条消息的类型 1. 开启共享 2. 关闭共享 3. 设置所有者 4. 取消所有者 5. 开启共享申请 6. 关闭共享申请 7. 设置所有者申请 8. 取消所有者申请 9. 开启外链申请 10. 开启共享审核结果 11. 关闭共享审核结果 12. 开启所有者审核结果 13. 关闭所有者审核结果 14. 开启外链审核结果 15. 待审流程消息 16. 流程进度消息 17. 流程结果消息 18. 简单消息 19. 提交密级申请消息 20. 密级申请审核结果 21. 隔离消息 22. 隔离被还原消息 23. 杀毒消息 24. 创建文档收集任务消息 25. 文档收发变更消息 26. 文档收发提醒消息 27. 取消文档收发任务消息 28. 文件到期通知消息 29. 短信验证码发送 30. 继承变更申请消息 31. 继承变更审核结果 (required).</param>
/// <param name="url">内链,相对地址 (required).</param>
/// <param name="allowvalue">允许的权限值,按bit为存储,参考权限获取 (required).</param>
/// <param name="denyvalue">拒绝的权限值,按bit为存储,参考权限获取 (required).</param>
/// <param name="end">有效到期时间 (unix utc 精确到微秒) -1 无限期 (required).</param>
public MessageGetResMsgType5(string accessorname = default(string), AccessortypeEnum accessortype = default(AccessortypeEnum), long? csf = default(long?), string id = default(string), bool? isdir = default(bool?), bool? isread = default(bool?), string sender = default(string), long? time = default(long?), long? type = default(long?), string url = default(string), long? allowvalue = default(long?), long? denyvalue = default(long?), long? end = default(long?))
{
this.Accessorname = accessorname;
this.Accessortype = accessortype;
this.Csf = csf;
this.Id = id;
this.Isdir = isdir;
this.Isread = isread;
this.Sender = sender;
this.Time = time;
this.Type = type;
this.Url = url;
this.Allowvalue = allowvalue;
this.Denyvalue = denyvalue;
this.End = end;
}
/// <summary>
/// 接收者名字,如果是外链,为空字符串
/// </summary>
/// <value>接收者名字,如果是外链,为空字符串</value>
[DataMember(Name="accessorname", EmitDefaultValue=false)]
public string Accessorname { get; set; }
/// <summary>
/// 文件密级,5~15,文件夹为0
/// </summary>
/// <value>文件密级,5~15,文件夹为0</value>
[DataMember(Name="csf", EmitDefaultValue=false)]
public long? Csf { get; set; }
/// <summary>
/// 此条消息的唯一标识
/// </summary>
/// <value>此条消息的唯一标识</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// 是否为文件夹
/// </summary>
/// <value>是否为文件夹</value>
[DataMember(Name="isdir", EmitDefaultValue=false)]
public bool? Isdir { get; set; }
/// <summary>
/// 消息是否已读
/// </summary>
/// <value>消息是否已读</value>
[DataMember(Name="isread", EmitDefaultValue=false)]
public bool? Isread { get; set; }
/// <summary>
/// 发送者名字
/// </summary>
/// <value>发送者名字</value>
[DataMember(Name="sender", EmitDefaultValue=false)]
public string Sender { get; set; }
/// <summary>
/// 共享操作的时间(unix utc ns)
/// </summary>
/// <value>共享操作的时间(unix utc ns)</value>
[DataMember(Name="time", EmitDefaultValue=false)]
public long? Time { get; set; }
/// <summary>
/// 此条消息的类型 1. 开启共享 2. 关闭共享 3. 设置所有者 4. 取消所有者 5. 开启共享申请 6. 关闭共享申请 7. 设置所有者申请 8. 取消所有者申请 9. 开启外链申请 10. 开启共享审核结果 11. 关闭共享审核结果 12. 开启所有者审核结果 13. 关闭所有者审核结果 14. 开启外链审核结果 15. 待审流程消息 16. 流程进度消息 17. 流程结果消息 18. 简单消息 19. 提交密级申请消息 20. 密级申请审核结果 21. 隔离消息 22. 隔离被还原消息 23. 杀毒消息 24. 创建文档收集任务消息 25. 文档收发变更消息 26. 文档收发提醒消息 27. 取消文档收发任务消息 28. 文件到期通知消息 29. 短信验证码发送 30. 继承变更申请消息 31. 继承变更审核结果
/// </summary>
/// <value>此条消息的类型 1. 开启共享 2. 关闭共享 3. 设置所有者 4. 取消所有者 5. 开启共享申请 6. 关闭共享申请 7. 设置所有者申请 8. 取消所有者申请 9. 开启外链申请 10. 开启共享审核结果 11. 关闭共享审核结果 12. 开启所有者审核结果 13. 关闭所有者审核结果 14. 开启外链审核结果 15. 待审流程消息 16. 流程进度消息 17. 流程结果消息 18. 简单消息 19. 提交密级申请消息 20. 密级申请审核结果 21. 隔离消息 22. 隔离被还原消息 23. 杀毒消息 24. 创建文档收集任务消息 25. 文档收发变更消息 26. 文档收发提醒消息 27. 取消文档收发任务消息 28. 文件到期通知消息 29. 短信验证码发送 30. 继承变更申请消息 31. 继承变更审核结果</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public long? Type { get; set; }
/// <summary>
/// 内链,相对地址
/// </summary>
/// <value>内链,相对地址</value>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { get; set; }
/// <summary>
/// 允许的权限值,按bit为存储,参考权限获取
/// </summary>
/// <value>允许的权限值,按bit为存储,参考权限获取</value>
[DataMember(Name="allowvalue", EmitDefaultValue=false)]
public long? Allowvalue { get; set; }
/// <summary>
/// 拒绝的权限值,按bit为存储,参考权限获取
/// </summary>
/// <value>拒绝的权限值,按bit为存储,参考权限获取</value>
[DataMember(Name="denyvalue", EmitDefaultValue=false)]
public long? Denyvalue { get; set; }
/// <summary>
/// 有效到期时间 (unix utc 精确到微秒) -1 无限期
/// </summary>
/// <value>有效到期时间 (unix utc 精确到微秒) -1 无限期</value>
[DataMember(Name="end", EmitDefaultValue=false)]
public long? End { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class MessageGetResMsgType5 {\n");
sb.Append(" Accessorname: ").Append(Accessorname).Append("\n");
sb.Append(" Accessortype: ").Append(Accessortype).Append("\n");
sb.Append(" Csf: ").Append(Csf).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Isdir: ").Append(Isdir).Append("\n");
sb.Append(" Isread: ").Append(Isread).Append("\n");
sb.Append(" Sender: ").Append(Sender).Append("\n");
sb.Append(" Time: ").Append(Time).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" Allowvalue: ").Append(Allowvalue).Append("\n");
sb.Append(" Denyvalue: ").Append(Denyvalue).Append("\n");
sb.Append(" End: ").Append(End).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as MessageGetResMsgType5);
}
/// <summary>
/// Returns true if MessageGetResMsgType5 instances are equal
/// </summary>
/// <param name="input">Instance of MessageGetResMsgType5 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(MessageGetResMsgType5 input)
{
if (input == null)
return false;
return
(
this.Accessorname == input.Accessorname ||
(this.Accessorname != null &&
this.Accessorname.Equals(input.Accessorname))
) &&
(
this.Accessortype == input.Accessortype ||
(this.Accessortype != null &&
this.Accessortype.Equals(input.Accessortype))
) &&
(
this.Csf == input.Csf ||
(this.Csf != null &&
this.Csf.Equals(input.Csf))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Isdir == input.Isdir ||
(this.Isdir != null &&
this.Isdir.Equals(input.Isdir))
) &&
(
this.Isread == input.Isread ||
(this.Isread != null &&
this.Isread.Equals(input.Isread))
) &&
(
this.Sender == input.Sender ||
(this.Sender != null &&
this.Sender.Equals(input.Sender))
) &&
(
this.Time == input.Time ||
(this.Time != null &&
this.Time.Equals(input.Time))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
) &&
(
this.Allowvalue == input.Allowvalue ||
(this.Allowvalue != null &&
this.Allowvalue.Equals(input.Allowvalue))
) &&
(
this.Denyvalue == input.Denyvalue ||
(this.Denyvalue != null &&
this.Denyvalue.Equals(input.Denyvalue))
) &&
(
this.End == input.End ||
(this.End != null &&
this.End.Equals(input.End))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Accessorname != null)
hashCode = hashCode * 59 + this.Accessorname.GetHashCode();
if (this.Accessortype != null)
hashCode = hashCode * 59 + this.Accessortype.GetHashCode();
if (this.Csf != null)
hashCode = hashCode * 59 + this.Csf.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Isdir != null)
hashCode = hashCode * 59 + this.Isdir.GetHashCode();
if (this.Isread != null)
hashCode = hashCode * 59 + this.Isread.GetHashCode();
if (this.Sender != null)
hashCode = hashCode * 59 + this.Sender.GetHashCode();
if (this.Time != null)
hashCode = hashCode * 59 + this.Time.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.Url != null)
hashCode = hashCode * 59 + this.Url.GetHashCode();
if (this.Allowvalue != null)
hashCode = hashCode * 59 + this.Allowvalue.GetHashCode();
if (this.Denyvalue != null)
hashCode = hashCode * 59 + this.Denyvalue.GetHashCode();
if (this.End != null)
hashCode = hashCode * 59 + this.End.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 41.243094 | 470 | 0.522304 | [
"MIT"
] | ArtyDinosaur404/AnyShareSDK | AnyShareSDK/Model/MessageGetResMsgType5.cs | 17,128 | C# |
//
// AsyncTests.Framework.NotWorkingAttribute
//
// Authors:
// Martin Baulig (martin.baulig@gmail.com)
//
// Copyright 2012 Xamarin Inc. (http://www.xamarin.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.Reflection;
using Mono.Addins;
namespace AsyncTests.Framework {
[Extension]
public class NotWorkingAttribute : TestCategoryAttribute {
public override string Name {
get { return "Not Working"; }
}
}
}
| 35.595238 | 73 | 0.749833 | [
"Apache-2.0"
] | DavidAlphaFox/mac-samples | CFNetwork/AsyncTests.Framework/AsyncTests.Framework/NotWorkingAttribute.cs | 1,495 | 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.
*/
using System.Collections.Generic;
namespace DotNetty.Transport.Channels
{
public sealed class ChannelComparer : IEqualityComparer<IChannel>
{
public static readonly IEqualityComparer<IChannel> Default = new ChannelComparer();
private ChannelComparer() { }
public bool Equals(IChannel x, IChannel y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(IChannel obj)
{
//if (obj is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); }
return obj.Id.GetHashCode();
}
}
}
| 33.422222 | 101 | 0.700798 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Transport/Channels/IChannelComparer.cs | 1,506 | C# |
using System;
namespace funktio_task4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Syötä kymmenen positiivista kokonaislukua. Ohjelma palauttaa suurimman: ");
Console.WriteLine($"{highNumber()}");
Console.ReadKey();
}
static string highNumber()
{
string result = "";
int i = 0;
int max = 0;
int line = 0;
bool b;
for (int y = 1; y <= 10; y++)
{
Console.Write($"{y}. ");
// syötä luku
if (b = int.TryParse(Console.ReadLine(), out i) && i > 0)
{
if (max < i)
{
max = i;
line = y;
}
}
else
{
Console.WriteLine("Syöttämäsi luku oli negatiivinen. Syötä uusi luku!");
y--;
}
result = ($"Suurin luku {max} oli rivillä {line}");
}
//mikä on suurin
return result;
}
}
}
| 24.530612 | 106 | 0.375208 | [
"MIT"
] | amanndajosefiina/programming-basics | Functions/function tasks/funktio task4/Program.cs | 1,215 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Processor", menuName = "ScriptableObjects/New Processor", order = 1)]
public class Processor : Item
{
public Material material;
public float clockSpeedBoost;
public float detectionRangeBoost;
private void OnEnable()
{
//se ajustan las estadisticas para que no sobrepasen el maximo
clockSpeedBoost = clockSpeedBoost > clockSpeedCap ? clockSpeedCap : clockSpeedBoost;
detectionRangeBoost = detectionRangeBoost > detectionRangeCap ? detectionRangeCap : detectionRangeBoost;
itemType = ItemType.Processor;
utility = (clockSpeedBoost / clockSpeedCap) * .4f + (detectionRangeBoost / detectionRangeCap) * .6f;
}
}
| 31.6 | 112 | 0.729114 | [
"MIT"
] | Joymg/CP2122_Grupo4 | Assets/Scripts/Processor.cs | 790 | C# |
using System.Collections.Generic;
using System.Security.Claims;
namespace CustomerContact
{
public class GraphQLUserContext : Dictionary<string, object>
{
public ClaimsPrincipal User { get; set; }
}
} | 21.1 | 62 | 0.758294 | [
"Apache-2.0"
] | lasse1979/customer-contact-service | src/GraphQLUserContext.cs | 211 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the opsworkscm-2016-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.OpsWorksCM.Model;
using Amazon.OpsWorksCM.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.OpsWorksCM
{
/// <summary>
/// Implementation for accessing OpsWorksCM
///
/// AWS OpsWorks for Chef Automate
/// <para>
/// AWS OpsWorks for Chef Automate is a service that runs and manages configuration management
/// servers.
/// </para>
///
/// <para>
/// <b>Glossary of terms</b>
/// </para>
/// <ul> <li>
/// <para>
/// <b>Server</b>: A configuration management server that can be highly-available. The
/// configuration manager runs on your instances by using various AWS services, such as
/// Amazon Elastic Compute Cloud (EC2), and potentially Amazon Relational Database Service
/// (RDS). A server is a generic abstraction over the configuration manager that you want
/// to use, much like Amazon RDS. In AWS OpsWorks for Chef Automate, you do not start
/// or stop servers. After you create servers, they continue to run until they are deleted.
/// </para>
/// </li> <li>
/// <para>
/// <b>Engine</b>: The specific configuration manager that you want to use (such as <code>Chef</code>)
/// is the engine.
/// </para>
/// </li> <li>
/// <para>
/// <b>Backup</b>: This is an application-level backup of the data that the configuration
/// manager stores. A backup creates a .tar.gz file that is stored in an Amazon Simple
/// Storage Service (S3) bucket in your account. AWS OpsWorks for Chef Automate creates
/// the S3 bucket when you launch the first instance. A backup maintains a snapshot of
/// all of a server's important attributes at the time of the backup.
/// </para>
/// </li> <li>
/// <para>
/// <b>Events</b>: Events are always related to a server. Events are written during server
/// creation, when health checks run, when backups are created, etc. When you delete a
/// server, the server's events are also deleted.
/// </para>
/// </li> <li>
/// <para>
/// <b>AccountAttributes</b>: Every account has attributes that are assigned in the AWS
/// OpsWorks for Chef Automate database. These attributes store information about configuration
/// limits (servers, backups, etc.) and your customer account.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Endpoints</b>
/// </para>
///
/// <para>
/// AWS OpsWorks for Chef Automate supports the following endpoints, all HTTPS. You must
/// connect to one of the following endpoints. Chef servers can only be accessed or managed
/// within the endpoint in which they are created.
/// </para>
/// <ul> <li>
/// <para>
/// opsworks-cm.us-east-1.amazonaws.com
/// </para>
/// </li> <li>
/// <para>
/// opsworks-cm.us-west-2.amazonaws.com
/// </para>
/// </li> <li>
/// <para>
/// opsworks-cm.eu-west-1.amazonaws.com
/// </para>
/// </li> </ul>
/// <para>
/// <b>Throttling limits</b>
/// </para>
///
/// <para>
/// All API operations allow for five requests per second with a burst of 10 requests
/// per second.
/// </para>
/// </summary>
public partial class AmazonOpsWorksCMClient : AmazonServiceClient, IAmazonOpsWorksCM
{
#region Constructors
/// <summary>
/// Constructs AmazonOpsWorksCMClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonOpsWorksCMClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonOpsWorksCMConfig()) { }
/// <summary>
/// Constructs AmazonOpsWorksCMClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonOpsWorksCMClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonOpsWorksCMConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonOpsWorksCMClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonOpsWorksCMClient Configuration Object</param>
public AmazonOpsWorksCMClient(AmazonOpsWorksCMConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonOpsWorksCMClient(AWSCredentials credentials)
: this(credentials, new AmazonOpsWorksCMConfig())
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonOpsWorksCMClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonOpsWorksCMConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Credentials and an
/// AmazonOpsWorksCMClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonOpsWorksCMClient Configuration Object</param>
public AmazonOpsWorksCMClient(AWSCredentials credentials, AmazonOpsWorksCMConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonOpsWorksCMConfig())
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonOpsWorksCMConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonOpsWorksCMClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonOpsWorksCMClient Configuration Object</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonOpsWorksCMConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonOpsWorksCMConfig())
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonOpsWorksCMConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonOpsWorksCMClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonOpsWorksCMClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonOpsWorksCMClient Configuration Object</param>
public AmazonOpsWorksCMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonOpsWorksCMConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AssociateNode
/// <summary>
/// Associates a new node with the Chef server. This command is an alternative to <code>knife
/// bootstrap</code>. For more information about how to disassociate a node, see <a>DisassociateNode</a>.
///
///
/// <para>
/// A node can can only be associated with servers that are in a <code>HEALTHY</code>
/// state. Otherwise, an <code>InvalidStateException</code> is thrown. A <code>ResourceNotFoundException</code>
/// is thrown when the server does not exist. A <code>ValidationException</code> is raised
/// when parameters of the request are not valid. The AssociateNode API call can be integrated
/// into Auto Scaling configurations, AWS Cloudformation templates, or the user data of
/// a server's instance.
/// </para>
///
/// <para>
/// Example: <code>aws opsworks-cm associate-node --server-name <i>MyServer</i> --node-name
/// <i>MyManagedNode</i> --engine-attributes "Name=<i>MyOrganization</i>,Value=default"
/// "Name=<i>Chef_node_public_key</i>,Value=<i>Public_key_contents</i>"</code>
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateNode service method.</param>
///
/// <returns>The response from the AssociateNode service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/AssociateNode">REST API Reference for AssociateNode Operation</seealso>
public AssociateNodeResponse AssociateNode(AssociateNodeRequest request)
{
var marshaller = new AssociateNodeRequestMarshaller();
var unmarshaller = AssociateNodeResponseUnmarshaller.Instance;
return Invoke<AssociateNodeRequest,AssociateNodeResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the AssociateNode operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AssociateNode operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAssociateNode
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/AssociateNode">REST API Reference for AssociateNode Operation</seealso>
public IAsyncResult BeginAssociateNode(AssociateNodeRequest request, AsyncCallback callback, object state)
{
var marshaller = new AssociateNodeRequestMarshaller();
var unmarshaller = AssociateNodeResponseUnmarshaller.Instance;
return BeginInvoke<AssociateNodeRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the AssociateNode operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAssociateNode.</param>
///
/// <returns>Returns a AssociateNodeResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/AssociateNode">REST API Reference for AssociateNode Operation</seealso>
public AssociateNodeResponse EndAssociateNode(IAsyncResult asyncResult)
{
return EndInvoke<AssociateNodeResponse>(asyncResult);
}
#endregion
#region CreateBackup
/// <summary>
/// Creates an application-level backup of a server. While the server is in the <code>BACKING_UP</code>
/// state, the server cannot be changed, and no additional backup can be created.
///
///
/// <para>
/// Backups can be created for servers in <code>RUNNING</code>, <code>HEALTHY</code>,
/// and <code>UNHEALTHY</code> states. By default, you can create a maximum of 50 manual
/// backups.
/// </para>
///
/// <para>
/// This operation is asynchronous.
/// </para>
///
/// <para>
/// A <code>LimitExceededException</code> is thrown when the maximum number of manual
/// backups is reached. An <code>InvalidStateException</code> is thrown when the server
/// is not in any of the following states: RUNNING, HEALTHY, or UNHEALTHY. A <code>ResourceNotFoundException</code>
/// is thrown when the server is not found. A <code>ValidationException</code> is thrown
/// when parameters of the request are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateBackup service method.</param>
///
/// <returns>The response from the CreateBackup service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.LimitExceededException">
/// The limit of servers or backups has been reached.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateBackup">REST API Reference for CreateBackup Operation</seealso>
public CreateBackupResponse CreateBackup(CreateBackupRequest request)
{
var marshaller = new CreateBackupRequestMarshaller();
var unmarshaller = CreateBackupResponseUnmarshaller.Instance;
return Invoke<CreateBackupRequest,CreateBackupResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateBackup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateBackup operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateBackup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateBackup">REST API Reference for CreateBackup Operation</seealso>
public IAsyncResult BeginCreateBackup(CreateBackupRequest request, AsyncCallback callback, object state)
{
var marshaller = new CreateBackupRequestMarshaller();
var unmarshaller = CreateBackupResponseUnmarshaller.Instance;
return BeginInvoke<CreateBackupRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateBackup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateBackup.</param>
///
/// <returns>Returns a CreateBackupResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateBackup">REST API Reference for CreateBackup Operation</seealso>
public CreateBackupResponse EndCreateBackup(IAsyncResult asyncResult)
{
return EndInvoke<CreateBackupResponse>(asyncResult);
}
#endregion
#region CreateServer
/// <summary>
/// Creates and immedately starts a new server. The server is ready to use when it is
/// in the <code>HEALTHY</code> state. By default, you can create a maximum of 10 servers.
///
///
///
/// <para>
/// This operation is asynchronous.
/// </para>
///
/// <para>
/// A <code>LimitExceededException</code> is thrown when you have created the maximum
/// number of servers (10). A <code>ResourceAlreadyExistsException</code> is thrown when
/// a server with the same name already exists in the account. A <code>ResourceNotFoundException</code>
/// is thrown when you specify a backup ID that is not valid or is for a backup that does
/// not exist. A <code>ValidationException</code> is thrown when parameters of the request
/// are not valid.
/// </para>
///
/// <para>
/// If you do not specify a security group by adding the <code>SecurityGroupIds</code>
/// parameter, AWS OpsWorks creates a new security group. The default security group opens
/// the Chef server to the world on TCP port 443. If a KeyName is present, AWS OpsWorks
/// enables SSH access. SSH is also open to the world on TCP port 22.
/// </para>
///
/// <para>
/// By default, the Chef Server is accessible from any IP address. We recommend that you
/// update your security group rules to allow access from known IP addresses and address
/// ranges only. To edit security group rules, open Security Groups in the navigation
/// pane of the EC2 management console.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateServer service method.</param>
///
/// <returns>The response from the CreateServer service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.LimitExceededException">
/// The limit of servers or backups has been reached.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceAlreadyExistsException">
/// The requested resource cannot be created because it already exists.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateServer">REST API Reference for CreateServer Operation</seealso>
public CreateServerResponse CreateServer(CreateServerRequest request)
{
var marshaller = new CreateServerRequestMarshaller();
var unmarshaller = CreateServerResponseUnmarshaller.Instance;
return Invoke<CreateServerRequest,CreateServerResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateServer operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateServer">REST API Reference for CreateServer Operation</seealso>
public IAsyncResult BeginCreateServer(CreateServerRequest request, AsyncCallback callback, object state)
{
var marshaller = new CreateServerRequestMarshaller();
var unmarshaller = CreateServerResponseUnmarshaller.Instance;
return BeginInvoke<CreateServerRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateServer.</param>
///
/// <returns>Returns a CreateServerResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/CreateServer">REST API Reference for CreateServer Operation</seealso>
public CreateServerResponse EndCreateServer(IAsyncResult asyncResult)
{
return EndInvoke<CreateServerResponse>(asyncResult);
}
#endregion
#region DeleteBackup
/// <summary>
/// Deletes a backup. You can delete both manual and automated backups. This operation
/// is asynchronous.
///
///
/// <para>
/// An <code>InvalidStateException</code> is thrown when a backup deletion is already
/// in progress. A <code>ResourceNotFoundException</code> is thrown when the backup does
/// not exist. A <code>ValidationException</code> is thrown when parameters of the request
/// are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBackup service method.</param>
///
/// <returns>The response from the DeleteBackup service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteBackup">REST API Reference for DeleteBackup Operation</seealso>
public DeleteBackupResponse DeleteBackup(DeleteBackupRequest request)
{
var marshaller = new DeleteBackupRequestMarshaller();
var unmarshaller = DeleteBackupResponseUnmarshaller.Instance;
return Invoke<DeleteBackupRequest,DeleteBackupResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteBackup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteBackup operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteBackup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteBackup">REST API Reference for DeleteBackup Operation</seealso>
public IAsyncResult BeginDeleteBackup(DeleteBackupRequest request, AsyncCallback callback, object state)
{
var marshaller = new DeleteBackupRequestMarshaller();
var unmarshaller = DeleteBackupResponseUnmarshaller.Instance;
return BeginInvoke<DeleteBackupRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteBackup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteBackup.</param>
///
/// <returns>Returns a DeleteBackupResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteBackup">REST API Reference for DeleteBackup Operation</seealso>
public DeleteBackupResponse EndDeleteBackup(IAsyncResult asyncResult)
{
return EndInvoke<DeleteBackupResponse>(asyncResult);
}
#endregion
#region DeleteServer
/// <summary>
/// Deletes the server and the underlying AWS CloudFormation stack (including the server's
/// EC2 instance). When you run this command, the server state is updated to <code>DELETING</code>.
/// After the server is deleted, it is no longer returned by <code>DescribeServer</code>
/// requests. If the AWS CloudFormation stack cannot be deleted, the server cannot be
/// deleted.
///
///
/// <para>
/// This operation is asynchronous.
/// </para>
///
/// <para>
/// An <code>InvalidStateException</code> is thrown when a server deletion is already
/// in progress. A <code>ResourceNotFoundException</code> is thrown when the server does
/// not exist. A <code>ValidationException</code> is raised when parameters of the request
/// are not valid.
/// </para>
///
/// <para>
///
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteServer service method.</param>
///
/// <returns>The response from the DeleteServer service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
public DeleteServerResponse DeleteServer(DeleteServerRequest request)
{
var marshaller = new DeleteServerRequestMarshaller();
var unmarshaller = DeleteServerResponseUnmarshaller.Instance;
return Invoke<DeleteServerRequest,DeleteServerResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteServer operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
public IAsyncResult BeginDeleteServer(DeleteServerRequest request, AsyncCallback callback, object state)
{
var marshaller = new DeleteServerRequestMarshaller();
var unmarshaller = DeleteServerResponseUnmarshaller.Instance;
return BeginInvoke<DeleteServerRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteServer.</param>
///
/// <returns>Returns a DeleteServerResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
public DeleteServerResponse EndDeleteServer(IAsyncResult asyncResult)
{
return EndInvoke<DeleteServerResponse>(asyncResult);
}
#endregion
#region DescribeAccountAttributes
/// <summary>
/// Describes your account attributes, and creates requests to increase limits before
/// they are reached or exceeded.
///
///
/// <para>
/// This operation is synchronous.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountAttributes service method.</param>
///
/// <returns>The response from the DescribeAccountAttributes service method, as returned by OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso>
public DescribeAccountAttributesResponse DescribeAccountAttributes(DescribeAccountAttributesRequest request)
{
var marshaller = new DescribeAccountAttributesRequestMarshaller();
var unmarshaller = DescribeAccountAttributesResponseUnmarshaller.Instance;
return Invoke<DescribeAccountAttributesRequest,DescribeAccountAttributesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeAccountAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountAttributes operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAccountAttributes
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso>
public IAsyncResult BeginDescribeAccountAttributes(DescribeAccountAttributesRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeAccountAttributesRequestMarshaller();
var unmarshaller = DescribeAccountAttributesResponseUnmarshaller.Instance;
return BeginInvoke<DescribeAccountAttributesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeAccountAttributes operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAccountAttributes.</param>
///
/// <returns>Returns a DescribeAccountAttributesResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso>
public DescribeAccountAttributesResponse EndDescribeAccountAttributes(IAsyncResult asyncResult)
{
return EndInvoke<DescribeAccountAttributesResponse>(asyncResult);
}
#endregion
#region DescribeBackups
/// <summary>
/// Describes backups. The results are ordered by time, with newest backups first. If
/// you do not specify a BackupId or ServerName, the command returns all backups.
///
///
/// <para>
/// This operation is synchronous.
/// </para>
///
/// <para>
/// A <code>ResourceNotFoundException</code> is thrown when the backup does not exist.
/// A <code>ValidationException</code> is raised when parameters of the request are not
/// valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBackups service method.</param>
///
/// <returns>The response from the DescribeBackups service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidNextTokenException">
/// This occurs when the provided nextToken is not valid.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeBackups">REST API Reference for DescribeBackups Operation</seealso>
public DescribeBackupsResponse DescribeBackups(DescribeBackupsRequest request)
{
var marshaller = new DescribeBackupsRequestMarshaller();
var unmarshaller = DescribeBackupsResponseUnmarshaller.Instance;
return Invoke<DescribeBackupsRequest,DescribeBackupsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeBackups operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeBackups operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeBackups
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeBackups">REST API Reference for DescribeBackups Operation</seealso>
public IAsyncResult BeginDescribeBackups(DescribeBackupsRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeBackupsRequestMarshaller();
var unmarshaller = DescribeBackupsResponseUnmarshaller.Instance;
return BeginInvoke<DescribeBackupsRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeBackups operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeBackups.</param>
///
/// <returns>Returns a DescribeBackupsResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeBackups">REST API Reference for DescribeBackups Operation</seealso>
public DescribeBackupsResponse EndDescribeBackups(IAsyncResult asyncResult)
{
return EndInvoke<DescribeBackupsResponse>(asyncResult);
}
#endregion
#region DescribeEvents
/// <summary>
/// Describes events for a specified server. Results are ordered by time, with newest
/// events first.
///
///
/// <para>
/// This operation is synchronous.
/// </para>
///
/// <para>
/// A <code>ResourceNotFoundException</code> is thrown when the server does not exist.
/// A <code>ValidationException</code> is raised when parameters of the request are not
/// valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeEvents service method.</param>
///
/// <returns>The response from the DescribeEvents service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidNextTokenException">
/// This occurs when the provided nextToken is not valid.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso>
public DescribeEventsResponse DescribeEvents(DescribeEventsRequest request)
{
var marshaller = new DescribeEventsRequestMarshaller();
var unmarshaller = DescribeEventsResponseUnmarshaller.Instance;
return Invoke<DescribeEventsRequest,DescribeEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeEvents operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeEvents
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso>
public IAsyncResult BeginDescribeEvents(DescribeEventsRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeEventsRequestMarshaller();
var unmarshaller = DescribeEventsResponseUnmarshaller.Instance;
return BeginInvoke<DescribeEventsRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeEvents operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEvents.</param>
///
/// <returns>Returns a DescribeEventsResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso>
public DescribeEventsResponse EndDescribeEvents(IAsyncResult asyncResult)
{
return EndInvoke<DescribeEventsResponse>(asyncResult);
}
#endregion
#region DescribeNodeAssociationStatus
/// <summary>
/// Returns the current status of an existing association or disassociation request.
///
///
///
/// <para>
/// A <code>ResourceNotFoundException</code> is thrown when no recent association or
/// disassociation request with the specified token is found, or when the server does
/// not exist. A <code>ValidationException</code> is raised when parameters of the request
/// are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeNodeAssociationStatus service method.</param>
///
/// <returns>The response from the DescribeNodeAssociationStatus service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeNodeAssociationStatus">REST API Reference for DescribeNodeAssociationStatus Operation</seealso>
public DescribeNodeAssociationStatusResponse DescribeNodeAssociationStatus(DescribeNodeAssociationStatusRequest request)
{
var marshaller = new DescribeNodeAssociationStatusRequestMarshaller();
var unmarshaller = DescribeNodeAssociationStatusResponseUnmarshaller.Instance;
return Invoke<DescribeNodeAssociationStatusRequest,DescribeNodeAssociationStatusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeNodeAssociationStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeNodeAssociationStatus operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeNodeAssociationStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeNodeAssociationStatus">REST API Reference for DescribeNodeAssociationStatus Operation</seealso>
public IAsyncResult BeginDescribeNodeAssociationStatus(DescribeNodeAssociationStatusRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeNodeAssociationStatusRequestMarshaller();
var unmarshaller = DescribeNodeAssociationStatusResponseUnmarshaller.Instance;
return BeginInvoke<DescribeNodeAssociationStatusRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeNodeAssociationStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeNodeAssociationStatus.</param>
///
/// <returns>Returns a DescribeNodeAssociationStatusResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeNodeAssociationStatus">REST API Reference for DescribeNodeAssociationStatus Operation</seealso>
public DescribeNodeAssociationStatusResponse EndDescribeNodeAssociationStatus(IAsyncResult asyncResult)
{
return EndInvoke<DescribeNodeAssociationStatusResponse>(asyncResult);
}
#endregion
#region DescribeServers
/// <summary>
/// Lists all configuration management servers that are identified with your account.
/// Only the stored results from Amazon DynamoDB are returned. AWS OpsWorks for Chef Automate
/// does not query other services.
///
///
/// <para>
/// This operation is synchronous.
/// </para>
///
/// <para>
/// A <code>ResourceNotFoundException</code> is thrown when the server does not exist.
/// A <code>ValidationException</code> is raised when parameters of the request are not
/// valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeServers service method.</param>
///
/// <returns>The response from the DescribeServers service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidNextTokenException">
/// This occurs when the provided nextToken is not valid.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeServers">REST API Reference for DescribeServers Operation</seealso>
public DescribeServersResponse DescribeServers(DescribeServersRequest request)
{
var marshaller = new DescribeServersRequestMarshaller();
var unmarshaller = DescribeServersResponseUnmarshaller.Instance;
return Invoke<DescribeServersRequest,DescribeServersResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeServers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeServers operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeServers
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeServers">REST API Reference for DescribeServers Operation</seealso>
public IAsyncResult BeginDescribeServers(DescribeServersRequest request, AsyncCallback callback, object state)
{
var marshaller = new DescribeServersRequestMarshaller();
var unmarshaller = DescribeServersResponseUnmarshaller.Instance;
return BeginInvoke<DescribeServersRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeServers operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeServers.</param>
///
/// <returns>Returns a DescribeServersResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DescribeServers">REST API Reference for DescribeServers Operation</seealso>
public DescribeServersResponse EndDescribeServers(IAsyncResult asyncResult)
{
return EndInvoke<DescribeServersResponse>(asyncResult);
}
#endregion
#region DisassociateNode
/// <summary>
/// Disassociates a node from a Chef server, and removes the node from the Chef server's
/// managed nodes. After a node is disassociated, the node key pair is no longer valid
/// for accessing the Chef API. For more information about how to associate a node, see
/// <a>AssociateNode</a>.
///
///
/// <para>
/// A node can can only be disassociated from a server that is in a <code>HEALTHY</code>
/// state. Otherwise, an <code>InvalidStateException</code> is thrown. A <code>ResourceNotFoundException</code>
/// is thrown when the server does not exist. A <code>ValidationException</code> is raised
/// when parameters of the request are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisassociateNode service method.</param>
///
/// <returns>The response from the DisassociateNode service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DisassociateNode">REST API Reference for DisassociateNode Operation</seealso>
public DisassociateNodeResponse DisassociateNode(DisassociateNodeRequest request)
{
var marshaller = new DisassociateNodeRequestMarshaller();
var unmarshaller = DisassociateNodeResponseUnmarshaller.Instance;
return Invoke<DisassociateNodeRequest,DisassociateNodeResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DisassociateNode operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisassociateNode operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisassociateNode
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DisassociateNode">REST API Reference for DisassociateNode Operation</seealso>
public IAsyncResult BeginDisassociateNode(DisassociateNodeRequest request, AsyncCallback callback, object state)
{
var marshaller = new DisassociateNodeRequestMarshaller();
var unmarshaller = DisassociateNodeResponseUnmarshaller.Instance;
return BeginInvoke<DisassociateNodeRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DisassociateNode operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisassociateNode.</param>
///
/// <returns>Returns a DisassociateNodeResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/DisassociateNode">REST API Reference for DisassociateNode Operation</seealso>
public DisassociateNodeResponse EndDisassociateNode(IAsyncResult asyncResult)
{
return EndInvoke<DisassociateNodeResponse>(asyncResult);
}
#endregion
#region RestoreServer
/// <summary>
/// Restores a backup to a server that is in a <code>CONNECTION_LOST</code>, <code>HEALTHY</code>,
/// <code>RUNNING</code>, <code>UNHEALTHY</code>, or <code>TERMINATED</code> state. When
/// you run RestoreServer, the server's EC2 instance is deleted, and a new EC2 instance
/// is configured. RestoreServer maintains the existing server endpoint, so configuration
/// management of the server's client devices (nodes) should continue to work.
///
///
/// <para>
/// This operation is asynchronous.
/// </para>
///
/// <para>
/// An <code>InvalidStateException</code> is thrown when the server is not in a valid
/// state. A <code>ResourceNotFoundException</code> is thrown when the server does not
/// exist. A <code>ValidationException</code> is raised when parameters of the request
/// are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RestoreServer service method.</param>
///
/// <returns>The response from the RestoreServer service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/RestoreServer">REST API Reference for RestoreServer Operation</seealso>
public RestoreServerResponse RestoreServer(RestoreServerRequest request)
{
var marshaller = new RestoreServerRequestMarshaller();
var unmarshaller = RestoreServerResponseUnmarshaller.Instance;
return Invoke<RestoreServerRequest,RestoreServerResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the RestoreServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RestoreServer operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRestoreServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/RestoreServer">REST API Reference for RestoreServer Operation</seealso>
public IAsyncResult BeginRestoreServer(RestoreServerRequest request, AsyncCallback callback, object state)
{
var marshaller = new RestoreServerRequestMarshaller();
var unmarshaller = RestoreServerResponseUnmarshaller.Instance;
return BeginInvoke<RestoreServerRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RestoreServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRestoreServer.</param>
///
/// <returns>Returns a RestoreServerResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/RestoreServer">REST API Reference for RestoreServer Operation</seealso>
public RestoreServerResponse EndRestoreServer(IAsyncResult asyncResult)
{
return EndInvoke<RestoreServerResponse>(asyncResult);
}
#endregion
#region StartMaintenance
/// <summary>
/// Manually starts server maintenance. This command can be useful if an earlier maintenance
/// attempt failed, and the underlying cause of maintenance failure has been resolved.
/// The server is in an <code>UNDER_MAINTENANCE</code> state while maintenance is in progress.
///
///
///
/// <para>
/// Maintenance can only be started on servers in <code>HEALTHY</code> and <code>UNHEALTHY</code>
/// states. Otherwise, an <code>InvalidStateException</code> is thrown. A <code>ResourceNotFoundException</code>
/// is thrown when the server does not exist. A <code>ValidationException</code> is raised
/// when parameters of the request are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartMaintenance service method.</param>
///
/// <returns>The response from the StartMaintenance service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/StartMaintenance">REST API Reference for StartMaintenance Operation</seealso>
public StartMaintenanceResponse StartMaintenance(StartMaintenanceRequest request)
{
var marshaller = new StartMaintenanceRequestMarshaller();
var unmarshaller = StartMaintenanceResponseUnmarshaller.Instance;
return Invoke<StartMaintenanceRequest,StartMaintenanceResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StartMaintenance operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartMaintenance operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartMaintenance
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/StartMaintenance">REST API Reference for StartMaintenance Operation</seealso>
public IAsyncResult BeginStartMaintenance(StartMaintenanceRequest request, AsyncCallback callback, object state)
{
var marshaller = new StartMaintenanceRequestMarshaller();
var unmarshaller = StartMaintenanceResponseUnmarshaller.Instance;
return BeginInvoke<StartMaintenanceRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartMaintenance operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartMaintenance.</param>
///
/// <returns>Returns a StartMaintenanceResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/StartMaintenance">REST API Reference for StartMaintenance Operation</seealso>
public StartMaintenanceResponse EndStartMaintenance(IAsyncResult asyncResult)
{
return EndInvoke<StartMaintenanceResponse>(asyncResult);
}
#endregion
#region UpdateServer
/// <summary>
/// Updates settings for a server.
///
///
/// <para>
/// This operation is synchronous.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServer service method.</param>
///
/// <returns>The response from the UpdateServer service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
public UpdateServerResponse UpdateServer(UpdateServerRequest request)
{
var marshaller = new UpdateServerRequestMarshaller();
var unmarshaller = UpdateServerResponseUnmarshaller.Instance;
return Invoke<UpdateServerRequest,UpdateServerResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateServer operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
public IAsyncResult BeginUpdateServer(UpdateServerRequest request, AsyncCallback callback, object state)
{
var marshaller = new UpdateServerRequestMarshaller();
var unmarshaller = UpdateServerResponseUnmarshaller.Instance;
return BeginInvoke<UpdateServerRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateServer.</param>
///
/// <returns>Returns a UpdateServerResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
public UpdateServerResponse EndUpdateServer(IAsyncResult asyncResult)
{
return EndInvoke<UpdateServerResponse>(asyncResult);
}
#endregion
#region UpdateServerEngineAttributes
/// <summary>
/// Updates engine-specific attributes on a specified server. The server enters the <code>MODIFYING</code>
/// state when this operation is in progress. Only one update can occur at a time. You
/// can use this command to reset the Chef server's private key (<code>CHEF_PIVOTAL_KEY</code>).
///
///
///
/// <para>
/// This operation is asynchronous.
/// </para>
///
/// <para>
/// This operation can only be called for servers in <code>HEALTHY</code> or <code>UNHEALTHY</code>
/// states. Otherwise, an <code>InvalidStateException</code> is raised. A <code>ResourceNotFoundException</code>
/// is thrown when the server does not exist. A <code>ValidationException</code> is raised
/// when parameters of the request are not valid.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServerEngineAttributes service method.</param>
///
/// <returns>The response from the UpdateServerEngineAttributes service method, as returned by OpsWorksCM.</returns>
/// <exception cref="Amazon.OpsWorksCM.Model.InvalidStateException">
/// The resource is in a state that does not allow you to perform a specified action.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ResourceNotFoundException">
/// The requested resource does not exist, or access was denied.
/// </exception>
/// <exception cref="Amazon.OpsWorksCM.Model.ValidationException">
/// One or more of the provided request parameters are not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServerEngineAttributes">REST API Reference for UpdateServerEngineAttributes Operation</seealso>
public UpdateServerEngineAttributesResponse UpdateServerEngineAttributes(UpdateServerEngineAttributesRequest request)
{
var marshaller = new UpdateServerEngineAttributesRequestMarshaller();
var unmarshaller = UpdateServerEngineAttributesResponseUnmarshaller.Instance;
return Invoke<UpdateServerEngineAttributesRequest,UpdateServerEngineAttributesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateServerEngineAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateServerEngineAttributes operation on AmazonOpsWorksCMClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateServerEngineAttributes
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServerEngineAttributes">REST API Reference for UpdateServerEngineAttributes Operation</seealso>
public IAsyncResult BeginUpdateServerEngineAttributes(UpdateServerEngineAttributesRequest request, AsyncCallback callback, object state)
{
var marshaller = new UpdateServerEngineAttributesRequestMarshaller();
var unmarshaller = UpdateServerEngineAttributesResponseUnmarshaller.Instance;
return BeginInvoke<UpdateServerEngineAttributesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateServerEngineAttributes operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateServerEngineAttributes.</param>
///
/// <returns>Returns a UpdateServerEngineAttributesResult from OpsWorksCM.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/opsworkscm-2016-11-01/UpdateServerEngineAttributes">REST API Reference for UpdateServerEngineAttributes Operation</seealso>
public UpdateServerEngineAttributesResponse EndUpdateServerEngineAttributes(IAsyncResult asyncResult)
{
return EndInvoke<UpdateServerEngineAttributesResponse>(asyncResult);
}
#endregion
}
} | 53.624476 | 191 | 0.659377 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/OpsWorksCM/Generated/_bcl35/AmazonOpsWorksCMClient.cs | 76,683 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
using Alipay.AopSdk.Core.Domain;
namespace Alipay.AopSdk.Core.Response
{
/// <summary>
/// AlipayMarketingCardBenefitQueryResponse.
/// </summary>
public class AlipayMarketingCardBenefitQueryResponse : AopResponse
{
/// <summary>
/// 会员卡模板外部权益列表
/// </summary>
[JsonProperty("mcard_template_benefit_query")]
public List<McardTemplateBenefitQuery> McardTemplateBenefitQuery { get; set; }
}
} | 25 | 80 | 0.743158 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk.Core/Response/AlipayMarketingCardBenefitQueryResponse.cs | 497 | C# |
using Assets.Scripts;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class eOrcWarrior : Enemy
{
public float timeBtwCharge;
public float startTimeBtwCharge;
public float attackRange;
[SerializeField] public const float ChargeForce = 3;
private int layerMaskWall;
public LayerMask whatIsSolid;
public bool isCharging = false;
[SerializeField] private Vector3 directionCharge;
// Start is called before the first frame update
protected override void Awake()
{
animator = GetComponent<Animator>();
target = FindObjectOfType<Player>().transform;
enemyCurrentHealth = enemyMaxHealth;
healthBar.SetMaxHealth(enemyMaxHealth);
layerMaskWall = LayerMask.NameToLayer("Wall");
TypeEnemy = EnumTypeEnemies.strong;
collider = this.GetComponent<BoxCollider2D>();
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
protected override void EnemyBehaviour()
{
if (Vector3.Distance(target.position, transform.position) <= maxRange && Vector3.Distance(target.position, transform.position) >= minRange && !isCharging)
{
FollowPlayer();
isMoving = true;
animator.SetBool("isMoving", isMoving);
}
else
{
isMoving = false;
animator.SetBool("isMoving", isMoving);
//goRespawn();
}
//if (passingTime < inmuneTime)
//{
// passingTime += Time.deltaTime;
// enemyInmune = true;
//}
//else
//{
// enemyInmune = false;
//}
//cd de la carga
if (timeBtwCharge <= 0 && !isCharging)
{
//raycast si hay vision del jugador
Vector3 directionRay = (GameManager.instance.player.transform.position - transform.position).normalized;
RaycastHit2D hitVision = Physics2D.Raycast(transform.position + (directionRay * 1), directionRay, attackRange, whatIsSolid);
//debug
Debug.DrawRay(transform.position + (directionRay * 1), directionRay * attackRange, Color.green, 0.1f);
if (hitVision.collider != null)
{
if (hitVision.collider.CompareTag("Player"))
{
timeBtwCharge = startTimeBtwCharge;
directionCharge = directionRay;
isCharging = true;
}
}
}
else
{
timeBtwCharge -= Time.deltaTime;
}
if (isCharging)
{
this.GetComponent<Rigidbody2D>().AddRelativeForce(directionCharge * ChargeForce);
}
}
private void OnCollisionEnter2D(Collision2D other)
{
//Check if the tag of the trigger collided with is Exit.
if (other.gameObject.layer == layerMaskWall && isCharging)
{
isCharging = false;
this.GetComponent<Rigidbody2D>().AddRelativeForce(directionCharge * ChargeForce * -1);
}
if (other.gameObject.tag == "Player" && isCharging)
{
isCharging = false;
this.GetComponent<Rigidbody2D>().AddRelativeForce(directionCharge * ChargeForce * -1);
}
}
}
| 31.971154 | 162 | 0.591579 | [
"MIT"
] | Clovisindo/Unity2dRogueLike | Assets/Scripts/Entities/Enemies/eOrcWarrior.cs | 3,327 | C# |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace WorldMapStrategyKit {
public class DemoLoadSave : MonoBehaviour {
/// <summary>
/// Here we'll store the data - you can save these strings to file or database (ie. System.IO.File.WriteAllText(path, countryGeoData)
/// </summary>
string countryGeoData, countryAttributes, provinceGeoData, provinceAttributes, cityGeoData, cityAttributes, mountPointGeoData, mountPointAttributes;
int state;
GUIStyle buttonStyle;
WMSK map;
void Start () {
map = WMSK.instance;
// setup GUI resizer - only for the demo
GUIResizer.Init (800, 500);
// setup GUI styles - only for the demo
buttonStyle = new GUIStyle ();
buttonStyle.alignment = TextAnchor.MiddleCenter;
buttonStyle.normal.background = Texture2D.whiteTexture;
buttonStyle.normal.textColor = Color.black;
#if UNITY_EDITOR
EditorUtility.DisplayDialog ("Load/Save Demo", "In this demo scene, a map change is simulated (North America is collapsed into one single country), then saved and loaded.", "Ok");
#endif
}
void OnGUI () {
// Do autoresizing of GUI layer
GUIResizer.AutoResize ();
switch (state) {
case 0:
if (GUI.Button (new Rect (10, 10, 160, 30), "Merge North America", buttonStyle)) {
int countryUSA = map.GetCountryIndex ("United States of America");
int countryCanada = map.GetCountryIndex ("Canada");
map.CountryTransferCountry (countryUSA, countryCanada, true);
countryUSA = map.GetCountryIndex ("United States of America");
int countryMexico = map.GetCountryIndex ("Mexico");
map.CountryTransferCountry (countryUSA, countryMexico, true);
state++;
}
break;
case 1:
if (GUI.Button (new Rect (10, 10, 160, 30), "Save Current Frontiers", buttonStyle)) {
SaveAllData ();
state++;
#if UNITY_EDITOR
EditorUtility.DisplayDialog ("Saved Data", "Data stored in temporary variables. You can now click reset frontiers to simulate a game restart and then Load Saved Data to restore the saved data.", "Ok");
#endif
}
break;
case 2:
if (GUI.Button (new Rect (10, 10, 160, 30), "Reset Frontiers", buttonStyle)) {
map.ReloadData ();
map.Redraw ();
state++;
}
break;
case 3:
if (GUI.Button (new Rect (10, 10, 160, 30), "Load Saved Data", buttonStyle)) {
LoadAllData ();
state++;
#if UNITY_EDITOR
EditorUtility.DisplayDialog ("Data Loaded!", "Data has been loaded from the temporary variables.", "Ok");
#endif
}
break;
case 4:
if (GUI.Button (new Rect (10, 50, 160, 30), "Reset Frontiers", buttonStyle)) {
map.ReloadData ();
map.Redraw ();
state = 0;
}
break;
}
}
void SaveAllData () {
// Store current countries information and frontiers data in string variables
countryGeoData = map.GetCountryGeoData ();
countryAttributes = map.GetCountriesAttributes ();
// Same for provinces. This wouldn't be neccesary if you are not using provinces in your app.
provinceGeoData = map.GetProvinceGeoData ();
provinceAttributes = map.GetProvincesAttributes ();
// Same for cities. This wouldn't be neccesary if you are not using cities in your app.
cityGeoData = map.GetCityGeoData ();
cityAttributes = map.GetCitiesAttributes ();
// Same for mount points. This wouldn't be neccesary if you are not using mount points in your app.
mountPointGeoData = map.GetMountPointsGeoData ();
mountPointAttributes = map.GetMountPointsAttributes ();
}
void LoadAllData () {
// Load country information from a string.
map.SetCountryGeoData (countryGeoData);
map.SetCountriesAttributes (countryAttributes);
// Same for provinces. This wouldn't be neccesary if you are not using provinces in your app.
map.SetProvincesGeoData (provinceGeoData);
map.SetProvincesAttributes (provinceAttributes);
// Same for cities. This wouldn't be neccesary if you are not using cities in your app.
map.SetCityGeoData (cityGeoData);
map.SetCitiesAttributes (cityAttributes);
// Same for mount points. This wouldn't be neccesary if you are not using mount points in your app.
map.SetMountPointsGeoData (mountPointGeoData);
map.SetMountPointsAttributes (mountPointAttributes);
// Redraw everything
map.Redraw ();
}
}
}
| 32.81203 | 206 | 0.695005 | [
"CC0-1.0"
] | lelehappy666/Refugees | Refugees/Assets/PlugInPackage/WorldMapStrategyKit/Demos/General Examples/104 Loading and Saving/DemoLoadSave.cs | 4,364 | C# |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Adv
{
public enum AlmanacStatus
{
Uncertain = 0,
Good = 1,
Certain = 2
}
public enum FixStatus
{
NoFix = 0,
InternalTimeKeeping = 1,
GFix = 2,
PFix = 3
}
public enum AdvImageData
{
PixelDepth16Bit,
PixelData12Bit,
PixelDepth8Bit,
PixelData24BitColor
}
/// <summary>
/// Represents the ADV system time which is the number of milliseconds elapsed since: 1 Jan 2010, 00:00:00 GMT
/// </summary>
public struct AdvTimeStamp
{
public const ulong ADV_EPOCH_ZERO_TICKS = 633979008000000000;
public ulong NanosecondsAfterAdvZeroEpoch;
public ulong MillisecondsAfterAdvZeroEpoch;
public static AdvTimeStamp FromWindowsTicks(ulong windowsTicks)
{
return new AdvTimeStamp()
{
NanosecondsAfterAdvZeroEpoch = (windowsTicks - ADV_EPOCH_ZERO_TICKS) * 100,
MillisecondsAfterAdvZeroEpoch = (windowsTicks - ADV_EPOCH_ZERO_TICKS) / 10000
};
}
public AdvTimeStamp AddNanoseconds(uint nanoseconds)
{
var rv = new AdvTimeStamp();
rv.NanosecondsAfterAdvZeroEpoch = NanosecondsAfterAdvZeroEpoch + nanoseconds;
rv.MillisecondsAfterAdvZeroEpoch = (ulong)(NanosecondsAfterAdvZeroEpoch + (nanoseconds / 1000000.0));
return rv;
}
public static AdvTimeStamp FromDateTime(DateTime dateTime)
{
return AdvTimeStamp.FromWindowsTicks((ulong)dateTime.Ticks);
}
public static AdvTimeStamp FromDateTime(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds)
{
return AdvTimeStamp.FromWindowsTicks((ulong)new DateTime(year, month, day, hours, minutes, seconds, milliseconds).Ticks);
}
}
} | 30.123288 | 133 | 0.638472 | [
"MIT"
] | aschweiz/ADVLib | Helpers.cs | 2,201 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing;
using System.Threading;
using NET.Tools.Forms.Frames;
namespace NET.Tools.Forms
{
/// <summary>
/// Represent a open picture dialog
///
/// <remarks>
/// Support languages:
/// - English (Default)
/// - German
/// </remarks>
/// </summary>
[ToolboxItemFilter("NET Tools")]
public sealed class OpenPictureDialog : CommonDialog, IPictureDialog
{
private PictureFilterIndex filterIndex;
#region Properties
[Browsable(true)]
[Category("Behavior")]
[Description("Use the filter for JPEGs")]
[DefaultValue(true)]
public bool UseJPEGFilter { get; set; }
[Browsable(true)]
[Category("Behavior")]
[Description("Use the filter for BMPs")]
[DefaultValue(true)]
public bool UseBMPFilter { get; set; }
[Browsable(true)]
[Category("Behavior")]
[Description("Use the filter for PNGs")]
[DefaultValue(true)]
public bool UsePNGFilter { get; set; }
[Browsable(true)]
[Category("Behavior")]
[Description("Sets the multi selecting")]
[DefaultValue(false)]
public bool MultiSelect { get; set; }
[Browsable(true)]
[Category("Behavior")]
[Description("Sets the first time directory")]
[Editor(typeof(UIDirectoryInfoEditor), typeof(UITypeEditor))]
public DirectoryInfo InitialDirectory { get; set; }
[Browsable(true)]
[Category("Behavior")]
[Description("Sets the filter index")]
[DefaultValue(PictureFilterIndex.JPEG)]
public PictureFilterIndex FilterIndex {
get { return filterIndex; }
set
{
switch (value)
{
case PictureFilterIndex.BMP:
if (!UseBMPFilter) throw new ArgumentException("The BMP Filter is deactivated!");
break;
case PictureFilterIndex.JPEG:
if (!UseJPEGFilter) throw new ArgumentException("The JPEG Filter is deactivated!");
break;
case PictureFilterIndex.PNG:
if (!UsePNGFilter) throw new ArgumentException("The PNG Filter is deactivated!");
break;
default:
throw new NotImplementedException();
}
filterIndex = value;
}
}
[Browsable(true)]
[Category("Behavior")]
[Description("Sets the initial file name")]
[DefaultValue("")]
public String FileName { get; set; }
[Browsable(false)]
public List<String> FileNames { get; private set; }
#endregion
public OpenPictureDialog()
{
UseBMPFilter = true;
UseJPEGFilter = true;
UsePNGFilter = true;
MultiSelect = false;
InitialDirectory = new DirectoryInfo("C:\\");
filterIndex = PictureFilterIndex.JPEG;
FileName = "";
FileNames = new List<String>();
}
public override void Reset()
{
}
protected override bool RunDialog(IntPtr hwndOwner)
{
PictureDialog dlg = new PictureDialog(PictureDialog.DialogType.Open, UseBMPFilter, UseJPEGFilter,
UsePNGFilter, filterIndex, MultiSelect, false, InitialDirectory, FileName);
if (dlg.ShowDialog() == DialogResult.OK)
{
FileName = dlg.FileNames[0];
FileNames = dlg.FileNames;
return true;
}
return false;
}
}
}
| 31.55814 | 110 | 0.538443 | [
"Apache-2.0"
] | CHiiLD/net-toolkit | NET.Tools.Forms.Controls/OpenPictureDialog.cs | 4,073 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace TrackMyStuff.ApiGateway.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DeviceStatus",
columns: table => new
{
DeviceId = table.Column<string>(nullable: false),
LastSeenAt = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceStatus", x => x.DeviceId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DeviceStatus");
}
}
}
| 29.333333 | 73 | 0.540909 | [
"MIT"
] | stonemonkey/TrackMyStuff | src/TrackMyStuff.ApiGateway/Migrations/20191225134754_Initial.cs | 882 | C# |
using UnityEngine;
public class DemoVikingMover : MonoBehaviour
{
Vector3 from = new Vector3(-2.5f, 0, 0);
Vector3 to = new Vector3(2.5f, 0, 0);
Vector3 previous;
Quaternion rotation;
void Start()
{
previous = transform.position;
}
void Update()
{
previous = transform.position;
transform.position = Vector3.Lerp(from, to, Mathf.PingPong(Time.time, 6) / 6f);
rotation = Quaternion.LookRotation((transform.position - previous).normalized);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * 10f);
}
} | 27.954545 | 97 | 0.653659 | [
"Unlicense",
"MIT"
] | Amitkapadi/unityassets | CombatText/Assets/BattleText/Demo/Scripts/DemoVikingMover.cs | 615 | C# |
namespace MakingDotNETApplicationsFaster.Runners.Models
{
public struct StructWithRefTypeAndOverridenEquals
{
public int Age { get; set; }
public int Height { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (!(obj is StructWithRefTypeAndOverridenEquals))
{
return false;
}
var other = (StructWithRefTypeAndOverridenEquals)obj;
return Age == other.Age && Height == other.Height && Name == other.Name;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
//== != operators can be ommited for this example
}
} | 26.678571 | 84 | 0.566265 | [
"MIT"
] | Ky7m/DemoCode | MakingDotNETApplicationsFaster/MakingDotNETApplicationsFaster/Runners/Models/StructWithRefTypeAndOverridenEquals.cs | 747 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Silk.NET.Core.Native;
using Ultz.SuperInvoke;
#pragma warning disable 1591
namespace Silk.NET.Vulkan
{
public unsafe struct PipelineViewportCoarseSampleOrderStateCreateInfoNV
{
public PipelineViewportCoarseSampleOrderStateCreateInfoNV
(
StructureType sType = StructureType.PipelineViewportCoarseSampleOrderStateCreateInfoNV,
void* pNext = default,
CoarseSampleOrderTypeNV sampleOrderType = default,
uint customSampleOrderCount = default,
CoarseSampleOrderCustomNV* pCustomSampleOrders = default
)
{
SType = sType;
PNext = pNext;
SampleOrderType = sampleOrderType;
CustomSampleOrderCount = customSampleOrderCount;
PCustomSampleOrders = pCustomSampleOrders;
}
/// <summary></summary>
public StructureType SType;
/// <summary></summary>
public void* PNext;
/// <summary></summary>
public CoarseSampleOrderTypeNV SampleOrderType;
/// <summary></summary>
public uint CustomSampleOrderCount;
/// <summary></summary>
public CoarseSampleOrderCustomNV* PCustomSampleOrders;
}
}
| 30.021277 | 99 | 0.690291 | [
"MIT"
] | AzyIsCool/Silk.NET | src/Vulkan/Silk.NET.Vulkan/Structs/PipelineViewportCoarseSampleOrderStateCreateInfoNV.gen.cs | 1,411 | C# |
#if __IOS__ || __ANDROID__
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Windows.UI.Xaml.Controls
{
partial class ItemsPresenter : ILayoutOptOut
{
public bool ShouldUseMinSize => !(_itemsPanel is NativeListViewBase);
}
}
#endif
| 19 | 71 | 0.775439 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/Controls/ItemsControl/ItemsPresenter.iOSAndroid.cs | 287 | C# |
using System;
using System.Security;
using System.Runtime.InteropServices;
namespace OpenNISharp2.Native
{
#pragma warning disable 169
internal unsafe struct ushort_array10
{
internal static readonly int Size = 10;
fixed ushort _[10];
public ushort this[uint i]
{
get { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (ushort_array10* p = &this) { return p->_[i]; } }
set { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (ushort_array10* p = &this) { p->_[i] = value; } }
}
public ushort[] ToArray()
{
fixed (ushort_array10* p = &this) { var a = new ushort[Size]; for (uint i = 0; i < Size; i++) a[i] = p->_[i]; return a; }
}
public void UpdateFrom(ushort[] array)
{
fixed (ushort_array10* p = &this) { uint i = 0; foreach(var value in array) { p->_[i++] = value; if (i >= Size) return; } }
}
public static implicit operator ushort[](ushort_array10 @struct) => @struct.ToArray();
}
internal unsafe struct byte_array16
{
internal static readonly int Size = 16;
fixed byte _[16];
public byte this[uint i]
{
get { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array16* p = &this) { return p->_[i]; } }
set { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array16* p = &this) { p->_[i] = value; } }
}
public byte[] ToArray()
{
fixed (byte_array16* p = &this) { var a = new byte[Size]; for (uint i = 0; i < Size; i++) a[i] = p->_[i]; return a; }
}
public void UpdateFrom(byte[] array)
{
fixed (byte_array16* p = &this) { uint i = 0; foreach(var value in array) { p->_[i++] = value; if (i >= Size) return; } }
}
public static implicit operator byte[](byte_array16 @struct) => @struct.ToArray();
}
internal unsafe struct byte_array32
{
internal static readonly int Size = 32;
fixed byte _[32];
public byte this[uint i]
{
get { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array32* p = &this) { return p->_[i]; } }
set { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array32* p = &this) { p->_[i] = value; } }
}
public byte[] ToArray()
{
fixed (byte_array32* p = &this) { var a = new byte[Size]; for (uint i = 0; i < Size; i++) a[i] = p->_[i]; return a; }
}
public void UpdateFrom(byte[] array)
{
fixed (byte_array32* p = &this) { uint i = 0; foreach(var value in array) { p->_[i++] = value; if (i >= Size) return; } }
}
public static implicit operator byte[](byte_array32 @struct) => @struct.ToArray();
}
internal unsafe struct byte_array80
{
internal static readonly int Size = 80;
fixed byte _[80];
public byte this[uint i]
{
get { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array80* p = &this) { return p->_[i]; } }
set { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array80* p = &this) { p->_[i] = value; } }
}
public byte[] ToArray()
{
fixed (byte_array80* p = &this) { var a = new byte[Size]; for (uint i = 0; i < Size; i++) a[i] = p->_[i]; return a; }
}
public void UpdateFrom(byte[] array)
{
fixed (byte_array80* p = &this) { uint i = 0; foreach(var value in array) { p->_[i++] = value; if (i >= Size) return; } }
}
public static implicit operator byte[](byte_array80 @struct) => @struct.ToArray();
}
internal unsafe struct byte_array256
{
internal static readonly int Size = 256;
fixed byte _[256];
public byte this[uint i]
{
get { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array256* p = &this) { return p->_[i]; } }
set { if (i >= Size) throw new ArgumentOutOfRangeException(); fixed (byte_array256* p = &this) { p->_[i] = value; } }
}
public byte[] ToArray()
{
fixed (byte_array256* p = &this) { var a = new byte[Size]; for (uint i = 0; i < Size; i++) a[i] = p->_[i]; return a; }
}
public void UpdateFrom(byte[] array)
{
fixed (byte_array256* p = &this) { uint i = 0; foreach(var value in array) { p->_[i++] = value; if (i >= Size) return; } }
}
public static implicit operator byte[](byte_array256 @struct) => @struct.ToArray();
}
}
| 41.643478 | 135 | 0.540823 | [
"MIT"
] | rational-core/OpenNISharp2 | OpenNISharp2/Native/OniCAPI.arrays.g.cs | 4,789 | C# |
using UnityEngine;
using UnityEditor;
using System.Collections;
public class PlayerPrefsMenu : MonoBehaviour
{
[MenuItem( "Playerprefs/Delete All" )]
public static void DeleteAll()
{
PlayerPrefs.DeleteAll();
}
}
| 16.923077 | 44 | 0.754545 | [
"MIT"
] | thatgamesguy/bounce | bounce/Assets/Bouce/Editor/PlayerPrefsMenu.cs | 222 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MilitaryElite.Models
{
public interface ISpy
{
int CodeNumberOfSpy { get; }
}
}
| 14.833333 | 36 | 0.691011 | [
"MIT"
] | tonkatawe/SoftUni-Advanced | OOP/Interfaces and Abstraction - Exercise/MilitaryElite/Interfaces/ISpy.cs | 180 | C# |
// ReSharper disable All
namespace OpenTl.Schema.Photos
{
using System;
using System.Collections;
using OpenTl.Schema;
public interface IPhotos : IObject
{
OpenTl.Schema.TVector<OpenTl.Schema.IPhoto> Photos {get; set;}
OpenTl.Schema.TVector<OpenTl.Schema.IUser> Users {get; set;}
}
}
| 17.888889 | 69 | 0.686335 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/Photos/Photos/IPhotos.cs | 324 | C# |
#region License
/*
Copyright © 2014-2022 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.Windows.Controls;
using GingerCore.Actions;
namespace Ginger.Actions
{
/// <summary>
/// Interaction logic for ActTextBoxEditPage.xaml
/// </summary>
public partial class ActUIALabelEditPage : Page
{
public static Act currentAct;
public ActUIALabelEditPage(GingerCore.Actions.ActUIALabel Act)
{
InitializeComponent();
currentAct = Act;
GingerCore.General.FillComboFromEnumObj(ActionNameComboBox, Act.LabelAction);
GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(ActionNameComboBox, ComboBox.TextProperty, Act, "LabelAction");
}
private void ActionNameComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
| 31.5 | 129 | 0.728716 | [
"Apache-2.0"
] | FOSSAware/Ginger | Ginger/Ginger/Actions/ActionEditPages/ActUIALabelEditPage.xaml.cs | 1,387 | C# |
/****************************************************************
Copyright 2021 Infosys Ltd.
Use of this source code is governed by Apache License Version 2.0 that can be found in the LICENSE file or at
http://www.apache.org/licenses/
***************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Infosys.WEM.Infrastructure.Common;
using System.Runtime.InteropServices;
using System.Windows.Automation;
using System.Reflection;
namespace Infosys.ATR.WinUIAutomationRuntimeWrapper
{
//Add the additional Application object properties
public class Application
{
[DllImport("user32.dll", CharSet=CharSet.Auto,ExactSpelling=true)]
public static extern IntPtr SetFocus(HandleRef hWnd);
private IntPtr _winHandle;
private int _processId;
private string _appName;
private string _automationControlName;
private string _automationClassName;
private string _appType;
private string _appLocationPath;
private string _uiFwk;
private Dictionary<string, Screen> _screens;
Dictionary<string, Control> _controls;
private bool appLaunched = true;
private string _webBrowser;
private string _webBrowserVersion;
private int _getWindowsHandleTimeOut = 3; //in seconds, the duration for which it would be tried to get the windows handlle based on the process id or application control name
private string className = "Application";
//events for client developers
#region Event- PropertyHasChanged
public class PropertyHasChangedArgs : EventArgs
{
public Control Control { get; set; }
public string ChangedProperty{ get; set; }
public object OldValue { get; set; }
public object NewValue { get; set; }
}
public delegate void PropertyHasChangedEventHandler(PropertyHasChangedArgs e);
public event PropertyHasChangedEventHandler PropertyHasChanged;
#endregion
#region Event- StructureHasChanged
public class StructureHasChangedArgs : EventArgs
{
public Control Control { get; set; }
public string StructureChangeType { get; set; }
}
public delegate void StructureHasChangedEventHandler(StructureHasChangedArgs e);
public event StructureHasChangedEventHandler StructureHasChanged;
#endregion
/// <summary>
/// Application Constructor
/// </summary>
/// <param name="applicationName">Name of Application</param>
/// <param name="launchedApp">Boolean value stating if the application should be launched or not</param>
/// <param name="applicationClassName">Optional, to set the application class name. e.g. to be used in case of IE context menu</param>
public Application(string applicationName, bool launchedApp= false, string applicationClassName="")
{
Core.Utilities.SetDLLsPath();
appLaunched = launchedApp;
using (LogHandler.TraceOperations(Logging.InformationMessages.RUNTIMEWRAPPER_ENTER, LogHandler.Layer.Business, Guid.Empty, className, Logging.Constants.APPLICATION))
{
//in param
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_PARAMETERS, LogHandler.Layer.Business, "applicationName", Logging.Constants.PARAMDIRECTION_IN, applicationName);
_automationControlName = applicationName;
_automationClassName = applicationClassName;
_winHandle = GetWindowsHandle();
}
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_EXIT, LogHandler.Layer.Business, className, Logging.Constants.APPLICATION);
}
/// <summary>
/// Application Constructor
/// </summary>
/// <param name="pid">Process Id of the application</param>
public Application(int pid)
{
Core.Utilities.WriteLog("instantiating application with process id");
appLaunched = true;
using (LogHandler.TraceOperations(Logging.InformationMessages.RUNTIMEWRAPPER_ENTER, LogHandler.Layer.Business, Guid.Empty, className, Logging.Constants.APPLICATION))
{
//in param
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_PARAMETERS, LogHandler.Layer.Business, "pid", Logging.Constants.PARAMDIRECTION_IN, pid.ToString());
_processId = pid;
_winHandle = GetWindowsHandle();
}
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_EXIT, LogHandler.Layer.Business, className, Logging.Constants.APPLICATION);
}
public string Name
{
get { return _appName; }
set { _appName = value; }
}
public string AutomationName
{
get { return _automationControlName; }
set { _automationControlName = value; }
}
public string AutomationClassName
{
get { return _automationClassName; }
set { _automationClassName = value; }
}
public int ProcessId
{
get { return _processId; }
}
public IntPtr WindowsHandle
{
get { return _winHandle; }
}
public string AppType
{
get { return _appType; }
set { _appType = value; }
}
public string AppLocationPath
{
get { return _appLocationPath; }
set { _appLocationPath = value; }
}
public string UIFwk
{
get { return _uiFwk; }
set { _uiFwk = value; }
}
public Dictionary<string, Control> Controls
{
get { return _controls; }
set { _controls = value; }
}
public Dictionary<string, Screen> Screens
{
get { return _screens; }
set { _screens = value; }
}
public string WebBrowser
{
get { return _webBrowser; }
set { _webBrowser = value; }
}
public string WebBrowserVersion
{
get { return _webBrowserVersion; }
set { _webBrowserVersion = value; }
}
public bool ShowAppStartWaitBox { get; set; }
/// <summary>
/// This method is used to set the reference of the parent automation element.
/// </summary>
public void RefreshAppHandle()
{
using (LogHandler.TraceOperations(Logging.InformationMessages.RUNTIMEWRAPPER_ENTER, LogHandler.Layer.Business, Guid.Empty, className, Logging.Constants.REFRESHAPPHANDLE))
{
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_ENTER, LogHandler.Layer.Business, className, Logging.Constants.REFRESHAPPHANDLE);
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_ENTER, LogHandler.Layer.Business, className, Logging.Constants.GETWINDOWSHANDLE);
GetWindowsHandle();
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_EXIT, LogHandler.Layer.Business, className, Logging.Constants.GETWINDOWSHANDLE);
if (_screens.Count > 0)
{
foreach (KeyValuePair<string, Screen> scrn in _screens)
{
//Set the reference of the parent automation element
_screens[scrn.Key].RefreshScreenHandle(_winHandle);
}
}
}
LogHandler.LogInfo(Logging.InformationMessages.RUNTIMEWRAPPER_EXIT, LogHandler.Layer.Business, className, Logging.Constants.REFRESHAPPHANDLE);
}
/// <summary>
/// This method is ised to return Window handle for the current active application.
/// </summary>
/// <returns></returns>
public IntPtr GetWindowsHandle()
{
Core.Utilities.WriteLog("getting application handle");
if (string.IsNullOrEmpty(_automationControlName) && _processId == 0)
{
Core.Utilities.WriteLog("application control name is blank and also the process id is zero hence returning zero windows handle");
return IntPtr.Zero; //error
}
//in the below while loop also include the _getWindowsHandleTimeOut
DateTime startTime = DateTime.Now;
while (_winHandle == IntPtr.Zero && (System.DateTime.Now - startTime).TotalMilliseconds <= _getWindowsHandleTimeOut * 1000)
{
if (!string.IsNullOrEmpty(_automationControlName) && !string.IsNullOrEmpty(_automationClassName))
{
_winHandle = Core.Utilities.GetWindowHandle(_automationClassName, _automationControlName);
if(_winHandle!= IntPtr.Zero)
_processId = Core.Utilities.GetProcessId(_winHandle);
}
else if (!string.IsNullOrEmpty(_automationControlName))
{
_winHandle = Core.Utilities.GetWindowHandle(null, _automationControlName);
if (_winHandle != IntPtr.Zero)
_processId = Core.Utilities.GetProcessId(_winHandle);
}
else if (!string.IsNullOrEmpty(_automationClassName))
{
_winHandle = Core.Utilities.GetWindowHandle(_automationClassName, null);
if (_winHandle != IntPtr.Zero)
_processId = Core.Utilities.GetProcessId(_winHandle);
}
else
{
Process process = Process.GetProcessById(ProcessId);
if(process != null)
{
_winHandle = process.MainWindowHandle;
_automationControlName = process.MainWindowTitle;
}
}
}
if(_winHandle!= IntPtr.Zero)
Core.Utilities.WriteLog("application handle is valid");
else
Core.Utilities.WriteLog("application handle is invalid");
return _winHandle;
}
public void SubscribeToPropertyChangeEvent(PropertyHasChangedEventHandler propertyChangedCallBack)
{
if (_winHandle != IntPtr.Zero && _winHandle != null)
{
//get the automation element from the _winHandle and then register for property and structure changed handler
AutomationElement appAutoElement = AutomationElement.FromHandle(_winHandle);
if (appAutoElement != null)
{
PropertyHasChanged += propertyChangedCallBack;
AutomationPropertyChangedEventHandler propertyHandler = new AutomationPropertyChangedEventHandler(PropertyChanged_EventHandler);
Automation.AddAutomationPropertyChangedEventHandler(appAutoElement, TreeScope.Children, propertyHandler, AutomationElement.AutomationIdProperty, AutomationElement.NameProperty);
}
}
}
public void DesubscribeToPropertyChangeEvent(PropertyHasChangedEventHandler propertyChangedCallBack)
{
if (_winHandle != IntPtr.Zero && _winHandle != null)
{
//get the automation element from the _winHandle and then register for property and structure changed handler
AutomationElement appAutoElement = AutomationElement.FromHandle(_winHandle);
if (appAutoElement != null)
{
PropertyHasChanged -= propertyChangedCallBack;
AutomationPropertyChangedEventHandler propertyHandler = new AutomationPropertyChangedEventHandler(PropertyChanged_EventHandler);
Automation.RemoveAutomationPropertyChangedEventHandler(appAutoElement, propertyHandler);
}
}
}
public void SubscribeToStructureChangeEvent(StructureHasChangedEventHandler structureChangedCallBack)
{
if (_winHandle != IntPtr.Zero && _winHandle != null)
{
//get the automation element from the _winHandle and then register for property and structure changed handler
AutomationElement appAutoElement = AutomationElement.FromHandle(_winHandle);
if (appAutoElement != null)
{
StructureHasChanged += structureChangedCallBack;
StructureChangedEventHandler structureHandler = new StructureChangedEventHandler(StructureChanged_EventHandler);
Automation.AddStructureChangedEventHandler(appAutoElement, TreeScope.Children, structureHandler);
}
}
}
public void DesubscribeToStructureChangeEvent(StructureHasChangedEventHandler structureChangedCallBack)
{
if (_winHandle != IntPtr.Zero && _winHandle != null)
{
//get the automation element from the _winHandle and then register for property and structure changed handler
AutomationElement appAutoElement = AutomationElement.FromHandle(_winHandle);
if (appAutoElement != null)
{
StructureHasChanged -= structureChangedCallBack;
StructureChangedEventHandler structureHandler = new StructureChangedEventHandler(StructureChanged_EventHandler);
Automation.RemoveStructureChangedEventHandler(appAutoElement, structureHandler);
}
}
}
private void PropertyChanged_EventHandler(object sender, AutomationPropertyChangedEventArgs e)
{
//from here raise the event to be used by the client code
if (PropertyHasChanged != null)
{
Control ctl = new Control(IntPtr.Zero, IntPtr.Zero);
ctl.ControlElementFound = sender as AutomationElement;
if (ctl.ControlElementFound != null)
{
ctl.AutomationId = ctl.ControlElementFound.Current.AutomationId;
ctl.AutomationName = ctl.ControlElementFound.Current.Name;
//ctl.ControlTypeName = ctl.ControlElementFound.Current.ControlType.ProgrammaticName; /// not needed at the property ControlTypeName looks into the under lining automation element
}
PropertyHasChanged(new PropertyHasChangedArgs() { Control = ctl, ChangedProperty = e.Property.ProgrammaticName, OldValue= e.OldValue, NewValue = e.NewValue });
}
}
private void StructureChanged_EventHandler(object sender, StructureChangedEventArgs e)
{
//from here raise the event to be used by the client code
if (StructureHasChanged != null)
{
Control ctl = new Control(IntPtr.Zero, IntPtr.Zero);
ctl.ControlElementFound = sender as AutomationElement;
if (ctl.ControlElementFound != null)
{
ctl.AutomationId = ctl.ControlElementFound.Current.AutomationId;
ctl.AutomationName = ctl.ControlElementFound.Current.Name;
//ctl.ControlTypeName = ctl.ControlElementFound.Current.ControlType.ProgrammaticName; /// not needed at the property ControlTypeName looks into the under lining automation element
}
StructureHasChanged(new StructureHasChangedArgs() { Control = ctl, StructureChangeType = e.StructureChangeType.ToString() });
}
}
/// <summary>
/// Imitate the key board button press for the provided text and modifier (e.g. ctrl, shift, etc)
/// </summary>
/// <param name="text">The alpha nuemeric keys to be pressed</param>
/// <param name="modifiers">modifier: 0 for shift, 1 for ctrl, 2 for windows, 3 for alt, 4 for caps, 5 for enter, 6 for tab, 7 for back space, 8 for del, 9 for space. NB- in case of CAPS/ENTER, etc first call with text= blank or null and modifiers= 4 or 5, then again call with the required text as neeeded and modifier = -1.
/// Alternatively use enums- KeyModifier.SHIFT/CTRL/WINDOWS/ALT/CAPITAL/TAB/BACKSPACE/DEL/SPACE</param>
//public void KeyPress(string text, int modifiers)
//{
// Core.Utilities.KeyPress(modifiers: modifiers, text: text);
//}
/// <summary>
/// Imitate the key board button press for the provided text and modifier (e.g. ctrl, shift, etc)
/// </summary>
/// <param name="text">The alpha nuemeric keys to be pressed</param>
/// <param name="modifiers">Refer to the API user guide for the list of valid key codes</param>
public void KeyPress(string text, params int[] modifiers)
{
if (modifiers != null)
Core.Utilities.KeyPress(modifiers: modifiers, text: text);
else
Core.Utilities.KeyPress(text);
}
public void SendText(string text)
{
Core.Utilities.SendText(text: text);
}
public void KeyDown(int modifier)
{
Core.Utilities.KeyDown(modifier);
}
public void KeyUp(int modifier)
{
Core.Utilities.KeyUp(modifier);
}
/// <summary>
/// This method is used to start the application.
/// </summary>
/// <returns>true- if has access to the windows handle of the application started, else false</returns>
public bool StartApp()
{
bool startedSuccwessfully = true;
_processId = Core.Utilities.LaunchApplication(this.AppLocationPath,AppType, this.WebBrowser, this.ShowAppStartWaitBox);
appLaunched = true;
_winHandle = GetWindowsHandle();
if (!IsAvailable)
startedSuccwessfully = false;
return startedSuccwessfully;
}
/// <summary>
/// This method is used to start the application based on appArguement.
/// </summary>
/// <param name="appArguement">Argument to be passed</param>
/// /// <returns>true- if has access to the windows handle of the application started, else false</returns>
public bool StartApp(string appArguement)
{
bool startedSuccwessfully = true;
_processId = Core.Utilities.LaunchApplication(this.AppLocationPath,this.AppType, this.WebBrowser, this.ShowAppStartWaitBox, appArguement);
appLaunched = true;
_winHandle = GetWindowsHandle();
if (!IsAvailable)
startedSuccwessfully = false;
return startedSuccwessfully;
}
/// <summary>
/// This method is used to close the application based on _processId value.
/// </summary>
public void CloseApp()
{
if (_processId > 0)
{
Process process = Process.GetProcessById(_processId);
process.Kill();
}
}
/// <summary>
/// This method is used to set focus to the application based on _processId value.
/// </summary>
public void SetFocus()
{
if (_processId > 0)
{
Process process = Process.GetProcessById(_processId);
SetFocus(new HandleRef(null, process.MainWindowHandle));
}
}
public bool AppLaunched
{
set
{
appLaunched = value;
}
}
public bool IsAvailable
{
get
{
if (WindowsHandle == IntPtr.Zero || WindowsHandle == null)
return false;
else
return true;
}
}
/// <summary>
/// In seconds, the duration for which it would be tried to get the windows handlle based on the process id or application control name
/// </summary>
public int TimeOut
{
set
{
if (value > 0)
_getWindowsHandleTimeOut = value;
}
}
}
}
| 43.572632 | 333 | 0.602551 | [
"Apache-2.0"
] | Infosys/Script-Control-Center | ScriptDevelopmentTool/Infosys.ATR.WinUIAutomationRuntimeWrapper/Application.cs | 20,699 | C# |
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System;
using System.ComponentModel;
using ES3Types;
using ES3Internal;
public abstract class ES3Reader : System.IDisposable
{
/// <summary>The settings used to create this reader.</summary>
public ES3Settings settings;
protected int serializationDepth = 0;
#region ES3Reader Abstract Methods
internal abstract int Read_int();
internal abstract float Read_float();
internal abstract bool Read_bool();
internal abstract char Read_char();
internal abstract decimal Read_decimal();
internal abstract double Read_double();
internal abstract long Read_long();
internal abstract ulong Read_ulong();
internal abstract byte Read_byte();
internal abstract sbyte Read_sbyte();
internal abstract short Read_short();
internal abstract ushort Read_ushort();
internal abstract uint Read_uint();
internal abstract string Read_string();
internal abstract byte[] Read_byteArray();
internal abstract long Read_ref();
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public abstract string ReadPropertyName();
protected abstract Type ReadKeyPrefix(bool ignore = false);
protected abstract void ReadKeySuffix();
internal abstract byte[] ReadElement(bool skip=false);
/// <summary>Disposes of the reader and it's underlying stream.</summary>
public abstract void Dispose();
// Seeks to the given key. Note that the stream position will not be reset.
internal virtual bool Goto(string key)
{
if (key == null)
throw new ArgumentNullException("Key cannot be NULL when loading data.");
string currentKey;
while ((currentKey = ReadPropertyName()) != key)
{
if (currentKey == null)
return false;
Skip();
}
return true;
}
internal virtual bool StartReadObject()
{
serializationDepth++;
return false;
}
internal virtual void EndReadObject()
{
serializationDepth--;
}
internal abstract bool StartReadDictionary();
internal abstract void EndReadDictionary();
internal abstract bool StartReadDictionaryKey();
internal abstract void EndReadDictionaryKey();
internal abstract void StartReadDictionaryValue();
internal abstract bool EndReadDictionaryValue();
internal abstract bool StartReadCollection();
internal abstract void EndReadCollection();
internal abstract bool StartReadCollectionItem();
internal abstract bool EndReadCollectionItem();
#endregion
internal ES3Reader(ES3Settings settings, bool readHeaderAndFooter = true)
{
this.settings = settings;
}
// If this is not null, the next call to the Properties will return this name.
internal string overridePropertiesName = null;
/// <summary>Allows you to enumerate over each field name. This should only be used within an ES3Type file.</summary>
public virtual ES3ReaderPropertyEnumerator Properties
{
get
{
return new ES3ReaderPropertyEnumerator (this);
}
}
internal virtual ES3ReaderRawEnumerator RawEnumerator
{
get
{
return new ES3ReaderRawEnumerator (this);
}
}
/*
* Skips the current object in the stream.
* Stream position should be somewhere before the opening brace for the object.
* When this method successfully exits, it will be on the closing brace for the object.
*/
/// <summary>Skips the current object in the stream.</summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual void Skip()
{
ReadElement(true);
}
/// <summary>Reads a value of type T from the reader.</summary>
public virtual T Read<T>()
{
return Read<T>(ES3TypeMgr.GetOrCreateES3Type(typeof(T)));
}
/// <summary>Reads a value of type T from the reader into an existing object.</summary>
/// <param name="obj">The object we want to read our value into.</param>
public virtual void ReadInto<T>(object obj)
{
ReadInto<T>(obj, ES3TypeMgr.GetOrCreateES3Type(typeof(T)));
}
/// <summary>Reads a property (i.e. a property name and value) from the reader, ignoring the property name and only returning the value.</summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public T ReadProperty<T>()
{
return ReadProperty<T>(ES3TypeMgr.GetOrCreateES3Type(typeof(T)));
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public T ReadProperty<T>(ES3Type type)
{
ReadPropertyName();
return Read<T>(type);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public long ReadRefProperty()
{
ReadPropertyName();
return Read_ref();
}
internal Type ReadType()
{
return Type.GetType(Read<string>(ES3Type_string.Instance));
}
/// <summary>Sets the value of a private property on an object.</summary>
/// <param name="name">The name of the property we want to set.</param>
/// <param name="value">The value we want to set the property to.</param>
/// <param name="objectContainingProperty">The object containing the property we want to set.</param>
public void SetPrivateProperty(string name, object value, object objectContainingProperty)
{
var property = ES3Reflection.GetES3ReflectedProperty(objectContainingProperty.GetType(), name);
if(property.IsNull)
throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType());
property.SetValue(objectContainingProperty, value);
}
/// <summary>Sets the value of a private field on an object.</summary>
/// <param name="name">The name of the field we want to set.</param>
/// <param name="value">The value we want to set the field to.</param>
/// <param name="objectContainingProperty">The object containing the field we want to set.</param>
public void SetPrivateField(string name, object value, object objectContainingField)
{
var field = ES3Reflection.GetES3ReflectedMember(objectContainingField.GetType(), name);
if(field.IsNull)
throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType());
field.SetValue(objectContainingField, value);
}
#region Read(key) & Read(key, obj) methods
/// <summary>Reads a value from the reader with the given key.</summary>
/// <param name="key">The key which uniquely identifies our value.</param>
public virtual T Read<T>(string key)
{
if(!Goto(key))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\". Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist.");
Type type = ReadTypeFromHeader<T>();
T obj = Read<T>(ES3TypeMgr.GetOrCreateES3Type(type));
//ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders.
return obj;
}
/// <summary>Reads a value from the reader with the given key, returning the default value if the key does not exist.</summary>
/// <param name="key">The key which uniquely identifies our value.</param>
/// <param name="defaultValue">The value we want to return if this key does not exist in the reader.</param>
public virtual T Read<T>(string key, T defaultValue)
{
if(!Goto(key))
return defaultValue;
Type type = ReadTypeFromHeader<T>();
T obj = Read<T>(ES3TypeMgr.GetOrCreateES3Type(type));
//ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders.
return obj;
}
/// <summary>Reads a value from the reader with the given key into the provided object.</summary>
/// <param name="key">The key which uniquely identifies our value.</param>
/// <param name="obj">The object we want to load the value into.</param>
public virtual void ReadInto<T>(string key, T obj) where T : class
{
if(!Goto(key))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\"");
Type type = ReadTypeFromHeader<T>();
ReadInto<T>(obj, ES3TypeMgr.GetOrCreateES3Type(type));
//ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders.
}
protected virtual void ReadObject<T>(object obj, ES3Type type)
{
// Check for null.
if(StartReadObject())
return;
type.ReadInto<T>(this, obj);
EndReadObject();
}
protected virtual T ReadObject<T>(ES3Type type)
{
if(StartReadObject())
return default(T);
object obj = type.Read<T>(this);
EndReadObject();
return (T)obj;
}
#endregion
#region Read(ES3Type) & Read(obj,ES3Type) methods
/*
* Parses the next JSON Object in the stream (i.e. must be between '{' and '}' chars).
* If the first character in the Stream is not a '{', it will throw an error.
* Will also read the terminating '}'.
* If we have reached the end of stream, it will return null.
*/
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual T Read<T>(ES3Type type)
{
if(type == null || type.isUnsupported)
throw new NotSupportedException("Type of "+type+" is not currently supported, and could not be loaded using reflection.");
else if(type.isPrimitive)
return (T)type.Read<T>(this);
else if(type.isCollection)
return (T)((ES3CollectionType)type).Read(this);
else if(type.isDictionary)
return (T)((ES3DictionaryType)type).Read(this);
else
return ReadObject<T>(type);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual void ReadInto<T>(object obj, ES3Type type)
{
if(type == null || type.isUnsupported)
throw new NotSupportedException("Type of "+obj.GetType()+" is not currently supported, and could not be loaded using reflection.");
else if(type.isCollection)
((ES3CollectionType)type).ReadInto(this, obj);
else if(type.isDictionary)
((ES3DictionaryType)type).ReadInto(this, obj);
else
ReadObject<T>(obj, type);
}
#endregion
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal Type ReadTypeFromHeader<T>()
{
// Check whether we need to determine the type by reading the header.
if(typeof(T) == typeof(object))
return ReadKeyPrefix();
else if(settings.typeChecking)
{
Type type = ReadKeyPrefix();
if(type != typeof(T))
throw new InvalidOperationException("Trying to load data of type "+typeof(T)+", but data contained in file is type of "+type+".");
return type;
}
else
{
ReadKeyPrefix(true);
return typeof(T);
}
}
/// <summary>Creates a new ES3Reader and loads the default file into it.</summary>
public static ES3Reader Create()
{
return Create(new ES3Settings());
}
/// <summary>Creates a new ES3Reader and loads a file in storage into it.</summary>
/// <param name="filePath">The relative or absolute path of the file we want to load into the reader.</param>
public static ES3Reader Create(string filePath)
{
return Create(new ES3Settings(filePath));
}
/// <summary>Creates a new ES3Reader and loads a file in storage into it.</summary>
/// <param name="filePath">The relative or absolute path of the file we want to load into the reader.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public static ES3Reader Create(string filePath, ES3Settings settings)
{
return Create(new ES3Settings(filePath, settings));
}
/// <summary>Creates a new ES3Reader and loads a file in storage into it.</summary>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public static ES3Reader Create(ES3Settings settings)
{
Stream stream = ES3Stream.CreateStream(settings, ES3FileMode.Read);
if(stream == null)
return null;
// Get the baseWriter using the given Stream.
if (settings.format == ES3.Format.JSON)
return new ES3JSONReader(stream, settings);
else if (settings.format == ES3.Format.Binary_Alpha)
return new ES3BinaryReader(stream, settings);
return null;
}
/// <summary>Creates a new ES3Reader and loads the bytes provided into it.</summary>
public static ES3Reader Create(byte[] bytes)
{
return Create(bytes, new ES3Settings());
}
/// <summary>Creates a new ES3Reader and loads the bytes provided into it.</summary>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public static ES3Reader Create(byte[] bytes, ES3Settings settings)
{
Stream stream = ES3Stream.CreateStream(new MemoryStream(bytes), settings, ES3FileMode.Read);
if(stream == null)
return null;
// Get the baseWriter using the given Stream.
if(settings.format == ES3.Format.JSON)
return new ES3JSONReader(stream, settings);
else if(settings.format == ES3.Format.Binary_Alpha)
return new ES3BinaryReader(stream, settings);
return null;
}
internal static ES3Reader Create(Stream stream, ES3Settings settings)
{
stream = ES3Stream.CreateStream(stream, settings, ES3FileMode.Read);
// Get the baseWriter using the given Stream.
if(settings.format == ES3.Format.JSON)
return new ES3JSONReader(stream, settings);
else if (settings.format == ES3.Format.Binary_Alpha)
return new ES3BinaryReader(stream, settings);
return null;
}
internal static ES3Reader Create(Stream stream, ES3Settings settings, bool readHeaderAndFooter)
{
// Get the baseWriter using the given Stream.
if(settings.format == ES3.Format.JSON)
return new ES3JSONReader(stream, settings, readHeaderAndFooter);
else if (settings.format == ES3.Format.Binary_Alpha)
return new ES3BinaryReader(stream, settings, readHeaderAndFooter);
return null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public class ES3ReaderPropertyEnumerator
{
public ES3Reader reader;
public ES3ReaderPropertyEnumerator(ES3Reader reader)
{
this.reader = reader;
}
public IEnumerator GetEnumerator()
{
string propertyName;
while(true)
{
// Allows us to repeat a property name or insert one of our own.
if(reader.overridePropertiesName != null)
{
string tempName = reader.overridePropertiesName;
reader.overridePropertiesName = null;
yield return tempName;
}
else
{
if((propertyName = reader.ReadPropertyName()) == null)
yield break;
yield return propertyName;
}
}
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public class ES3ReaderRawEnumerator
{
public ES3Reader reader;
public ES3ReaderRawEnumerator(ES3Reader reader)
{
this.reader = reader;
}
public IEnumerator GetEnumerator()
{
while(true)
{
string key = reader.ReadPropertyName();
if(key == null)
yield break;
Type type = reader.ReadTypeFromHeader<object>();
byte[] bytes = reader.ReadElement();
reader.ReadKeySuffix();
yield return new KeyValuePair<string,ES3Data>(key, new ES3Data(type, bytes));
}
}
}
} | 34.454148 | 203 | 0.696958 | [
"MIT"
] | TrutzX/9Nations | Assets/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs | 15,782 | C# |
//Skapad av Emil Hallin för en C# kurs år 2018. Created by Emil Hallin for a C# course in 2018.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Personnrgranskare
{
public class MinKlass
{
public bool testFail;
public bool Algoritm21(long personnummer)
{
int summa = 0;
long sifferHållare = personnummer;
bool jämnt = true;
for (long i = 1000000000; i > 0; i /= 10)
{
long tempSumma, tiotal, ental;
tempSumma = ((sifferHållare - (personnummer % i)) / i);
sifferHållare = personnummer % i;
if (jämnt)
{
tempSumma *= 2;
if (tempSumma >= 10)
{
tiotal = tempSumma / 10;
ental = tempSumma - 10;
summa += (int)tiotal + (int)ental;
}
else
{
summa += (int)tempSumma;
}
jämnt = false;
}
else
{
summa += (int)tempSumma * 1;
jämnt = true;
}
}
if (summa % 10 == 0)
{
testFail = false;
return true;
}
else
{
testFail = true;
return false;
}
}
public bool Kön(int fyraSista)
{
int tempSiffra1 = 0;
int tempSiffra2 = 0;
int resultat = 0;
tempSiffra1 = fyraSista - fyraSista % 1000;
tempSiffra2 = fyraSista - tempSiffra1;
tempSiffra1 = tempSiffra2 - fyraSista % 100;
tempSiffra2 = tempSiffra2 - tempSiffra1;
resultat = (tempSiffra2 - fyraSista % 10) / 10;
if (resultat % 2 == 0)
{
return true;
}
else
{
return false;
}
}
}
public class personnummergranskare : System.Windows.Forms.Form
{
public System.Windows.Forms.Label förnamn;
public System.Windows.Forms.Label efternamn;
public System.Windows.Forms.Label personnummer;
public System.Windows.Forms.Label välkommen;
public System.Windows.Forms.Label instruktioner;
public System.Windows.Forms.Label resultatPerson;
public System.Windows.Forms.Label resultatKön;
public System.Windows.Forms.TextBox förnamnText;
public System.Windows.Forms.TextBox efternamnText;
public System.Windows.Forms.TextBox personnummerText;
public System.Windows.Forms.Button kalkylera;
public System.Windows.Forms.Button avsluta;
public personnummergranskare()
{
InitializeComponent();
}
private System.ComponentModel.Container components = null;
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
//Design layout
private void InitializeComponent()
{
this.förnamn = new System.Windows.Forms.Label();
this.efternamn = new System.Windows.Forms.Label();
this.personnummer = new System.Windows.Forms.Label();
this.välkommen = new System.Windows.Forms.Label();
this.instruktioner = new System.Windows.Forms.Label();
this.resultatPerson = new System.Windows.Forms.Label();
this.resultatKön = new System.Windows.Forms.Label();
this.förnamnText = new System.Windows.Forms.TextBox();
this.efternamnText = new System.Windows.Forms.TextBox();
this.personnummerText = new System.Windows.Forms.TextBox();
this.kalkylera = new System.Windows.Forms.Button();
this.avsluta = new System.Windows.Forms.Button();
this.SuspendLayout();
//Välkommen
this.välkommen.Location = new System.Drawing.Point(200, 10);
this.välkommen.Name = "välkommen";
this.välkommen.Size = new System.Drawing.Size(350, 50);
this.välkommen.TabIndex = 4;
this.välkommen.Text = "Välkommen!";
this.välkommen.Font = new Font("Georgia", 35, FontStyle.Bold);
this.välkommen.ForeColor = Color.Black;
//this.välkommen.BackColor = Color.Gray;
//Förnamn
this.förnamn.Location = new System.Drawing.Point(8, 100);
this.förnamn.Name = "förnamn";
this.förnamn.Size = new System.Drawing.Size(100, 20);
this.förnamn.TabIndex = 4;
this.förnamn.Text = "Förnamn:";
this.förnamn.Font = new Font("Georgia", 12, FontStyle.Bold);
this.förnamn.ForeColor = Color.Black;
//this.förnamn.BackColor = Color.Gray;
//Efternamn
this.efternamn.Location = new System.Drawing.Point(8, 125);
this.efternamn.Name = "efternamn";
this.efternamn.Size = new System.Drawing.Size(130, 20);
this.efternamn.TabIndex = 4;
this.efternamn.Text = "Efternamn:";
this.efternamn.Font = new Font("Georgia", 12, FontStyle.Bold);
this.efternamn.ForeColor = Color.Black;
//this.efternamn.BackColor = Color.Gray;
//Personnummer
this.personnummer.Location = new System.Drawing.Point(8, 150);
this.personnummer.Name = "personnummer";
this.personnummer.Size = new System.Drawing.Size(150, 20);
this.personnummer.TabIndex = 4;
this.personnummer.Text = "Personnummer:";
this.personnummer.Font = new Font("Georgia", 12, FontStyle.Bold);
this.personnummer.ForeColor = Color.Black;
//this.personnummer.BackColor = Color.Gray;
//Instruktioner
this.instruktioner.Location = new System.Drawing.Point(450, 100);
this.instruktioner.Name = "instruktioner";
this.instruktioner.Size = new System.Drawing.Size(250, 400);
this.instruktioner.TabIndex = 4;
this.instruktioner.Text = "I detta program är din uppgift att skriva in personuppgifter. Programmet kollar sedan ifall det angivna personnummret är ett godkänt personnummer eller ej. Samt ifall det är en man eller kvinna.";
this.instruktioner.Font = new Font("Georgia", 17, FontStyle.Bold);
this.instruktioner.ForeColor = Color.Black;
this.instruktioner.BackColor = Color.FromArgb(100, 201, 198, 197);
//Resultat Person
this.resultatPerson.Location = new System.Drawing.Point(10, 400);
this.resultatPerson.Name = "resultatPerson";
this.resultatPerson.Size = new System.Drawing.Size(400, 35);
this.resultatPerson.TabIndex = 4;
this.resultatPerson.Text = "";
this.resultatPerson.Font = new Font("Georgia", 10, FontStyle.Bold);
this.resultatPerson.ForeColor = Color.Black;
this.resultatPerson.BackColor = Color.FromArgb(100, 201, 198, 197);
//Resultat Kön
this.resultatKön.Location = new System.Drawing.Point(10, 435);
this.resultatKön.Name = "resultatKön";
this.resultatKön.Size = new System.Drawing.Size(400, 35);
this.resultatKön.TabIndex = 4;
this.resultatKön.Text = "";
this.resultatKön.Font = new Font("Georgia", 10, FontStyle.Bold);
this.resultatKön.ForeColor = Color.Black;
this.resultatKön.BackColor = Color.FromArgb(100, 201, 198, 197);
//FörnamnText
this.förnamnText.Location = new System.Drawing.Point(180, 100);
this.förnamnText.Name = "förnamnText";
this.förnamnText.Size = new System.Drawing.Size(130, 20);
this.förnamnText.TabIndex = 2;
this.förnamnText.Text = "";
//EfternamnText
this.efternamnText.Location = new System.Drawing.Point(180, 125);
this.efternamnText.Name = "efternamnText";
this.efternamnText.Size = new System.Drawing.Size(130, 20);
this.efternamnText.TabIndex = 2;
this.efternamnText.Text = "";
//PersonnummerText
this.personnummerText.Location = new System.Drawing.Point(180, 150);
this.personnummerText.Name = "personnummerText";
this.personnummerText.Size = new System.Drawing.Size(130, 20);
this.personnummerText.TabIndex = 2;
this.personnummerText.Text = "";
//Kalkylera
this.kalkylera.Location = new System.Drawing.Point(8, 190);
this.kalkylera.Name = "kalkylera";
this.kalkylera.Size = new System.Drawing.Size(125, 30);
this.kalkylera.Text = "Granska";
this.kalkylera.BackColor = Color.FromArgb(1, 201, 198, 197);
this.kalkylera.Click += new System.EventHandler(granskaClick);
//Avsluta
this.avsluta.Location = new System.Drawing.Point(185, 190);
this.avsluta.Name = "avsluta";
this.avsluta.Size = new System.Drawing.Size(125, 30);
this.avsluta.Text = "Avsluta";
this.avsluta.BackColor = Color.FromArgb(1, 201, 198, 197);
this.avsluta.Click += new System.EventHandler(avslutaProgrammet);
this.AutoScaleDimensions = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(800, 600);
this.Controls.AddRange(
new System.Windows.Forms.Control[]
{
this.förnamn,
this.efternamn ,
this.personnummer,
this.välkommen,
this.instruktioner,
this.resultatPerson,
this.resultatKön,
this.förnamnText,
this.efternamnText,
this.personnummerText ,
this.kalkylera,
this.avsluta
}
);
this.Name = "Personnummerkontroll";
this.Text = "Personnummerkontroll";
this.ResumeLayout(false);
this.BackColor = Color.White;
}
#endregion
//Initierare av programmet
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new personnummergranskare());
}
//Algoritmer och funktioner
private void granskaClick(object sender, System.EventArgs e)
{
MinKlass funktioner = new MinKlass();
long test, tempSistaFyra = 0, nyttPersonnummer = 0;
bool godkänt;
godkänt = Int64.TryParse(this.personnummerText.Text, out test);
if (godkänt)
{
//Variabler för Algoritm21
nyttPersonnummer = Int64.Parse(this.personnummerText.Text);
if (funktioner.Algoritm21(nyttPersonnummer))
{
this.resultatPerson.Text = "Personnummret för " + this.förnamnText.Text + " " + this.efternamnText.Text + " är Godkänt";
}
else
{
this.resultatPerson.Text = "Personnummret för " + this.förnamnText.Text + " " + this.efternamnText.Text + " är icke godkänt";
}
//Variabler för Köncheck
tempSistaFyra = Int64.Parse(this.personnummerText.Text);
while (tempSistaFyra > 9999)
{
if (tempSistaFyra > 1000000000)
{
tempSistaFyra -= 1000000000;
}
else if (tempSistaFyra > 100000000)
{
tempSistaFyra -= 100000000;
}
else if (tempSistaFyra > 10000000)
{
tempSistaFyra -= 10000000;
}
else if (tempSistaFyra > 1000000)
{
tempSistaFyra -= 1000000;
}
else if (tempSistaFyra > 100000)
{
tempSistaFyra -= 100000;
}
else
{
tempSistaFyra -= 10000;
}
}
int fyraSista = (int)tempSistaFyra;
if (!funktioner.testFail)
{
if (funktioner.Kön(fyraSista))
{
this.resultatKön.Text = "Personen är en kvinna";
}
else
{
this.resultatKön.Text = "Personen är en man";
}
}
else
{
this.resultatKön.Text = "";
}
}
else
{
this.resultatPerson.Text = "Personnumret får endast innehålla siffror, försök igen";
}
}
private void avslutaProgrammet(object sender, System.EventArgs e)
{
this.Close();
}
}
}
| 37.600536 | 235 | 0.528414 | [
"MIT"
] | Frauxo/Personnummergranskare | L0002B Inl 3/personnummergranskare.cs | 14,116 | C# |
using PHP.Core.Lang.Lexic.Token;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PHP.Core.Lang.Syntax.AST.Basic
{
public class ASTUnaryNode : ASTContainerNode
{
public ASTNode operand;
public ASTUnaryNode(TokenItem token, ASTNode operand = null) : base(token) => this.operand = operand;
public override string ToString() =>
" (" + operand.ToString() + token.data + ") ";
}
}
| 27.473684 | 110 | 0.657088 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | LoveNek0/PHPSharp | php-core/src/Core/Lang/Syntax/AST/Basic/ASTUnaryNode.cs | 524 | C# |
using LiteDB;
using Moq;
using NUnit.Framework;
using Playnite;
using Playnite.Database;
using Playnite.Models;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlayniteTests.Database
{
[TestFixture]
public class GameDatabaseFileTests
{
[Test]
public void CheckSumCreationTest()
{
var image = Path.Combine(PlaynitePaths.ProgramPath, "Resources", "Images", "applogo.png");
var db = new GameDatabase(null);
using (db.OpenDatabase(new MemoryStream()))
{
db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
var dbImage = db.GetFile("test.png");
Assert.IsFalse(string.IsNullOrEmpty(dbImage.Metadata["checksum"].AsString));
}
}
[Test]
public void MultiAddtionTest()
{
var image = Path.Combine(PlaynitePaths.ProgramPath, "Resources", "Images", "applogo.png");
var db = new GameDatabase(null);
using (db.OpenDatabase(new MemoryStream()))
{
db.AddFile("test.png", "test.png", File.ReadAllBytes(image));
var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
Assert.AreEqual("test.png", id);
Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
}
db = new GameDatabase(null);
using (db.OpenDatabase(new MemoryStream()))
{
db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
var id = db.AddFileNoDuplicate("test2.png", "test2.png", File.ReadAllBytes(image));
Assert.AreEqual("test.png", id);
Assert.AreEqual(1, db.Database.FileStorage.FindAll().Count());
}
db = new GameDatabase(null);
using (db.OpenDatabase(new MemoryStream()))
{
db.AddFileNoDuplicate("test.png", "test.png", File.ReadAllBytes(image));
db.AddFile("test2.png", "test2.png", File.ReadAllBytes(image));
Assert.AreEqual(2, db.Database.FileStorage.FindAll().Count());
}
}
}
}
| 37.030769 | 103 | 0.567511 | [
"MIT"
] | kingkong1946/Playnite | source/PlayniteTests/Database/GameDatabaseFileTests.cs | 2,409 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ToyingFile.Properties {
using System;
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをビルドし直します。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.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("ToyingFile.Properties.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;
}
}
/// <summary>
/// (アイコン) に類似した型 System.Drawing.Icon のローカライズされたリソースを検索します。
/// </summary>
internal static System.Drawing.Icon ToyingFile {
get {
object obj = ResourceManager.GetObject("ToyingFile", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
}
| 40.932432 | 177 | 0.585342 | [
"MIT"
] | koichi210/CS_Form | ToyingFile/ToyingFile/Properties/Resources.Designer.cs | 3,735 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
#if CAP_TypeOfPointer
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// member access
// </Description>
// <RelatedBug>564384</RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority0)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
int* ptr = stackalloc int[10];
for (int i = 0; i < 10; i++)
{
*(ptr + i) = i;
}
dynamic d = 5;
int x = ptr[d];
if (x != 5) return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02;
// <Area> dynamic with pointer indexer </Area>
// <Title>pointer operator</Title>
// <Description>
// member access
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority0)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
int* ptr = stackalloc int[10];
for (int i = 0; i < 10; i++)
{
*(ptr + i) = i;
}
int test = 0, success = 0;
dynamic d;
int x;
test++;
d = (uint)5;
x = ptr[d];
if (x == 5) success++;
test++;
d = (ulong)5;
x = ptr[d];
if (x == 5) success++;
test++;
d = (long)5;
x = ptr[d];
if (x == 5) success++;
return test == success ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// sizeof operator
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority1)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
dynamic d = sizeof(int);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// stackalloc
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority1)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
dynamic d = 10;
int* ptr = stackalloc int[d];
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01;
// <Area> dynamic in unsafe code </Area>
// <Title>Regression</Title>
// <Description>
// VerificationException thrown when dynamically dispatching a method call with out/ref arguments which are pointer types
// </Description>
// <RelatedBug></RelatedBug>
// <Expects Status=success></Expects>
// <Code>
using System;
using System.Security;
[TestClass]
public class TestClass
{
public unsafe void Method(out int* arg)
{
arg = (int*)5;
}
}
struct Driver
{
[Test]
[Priority(Priority.Priority2)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); }
public static unsafe int MainMethod()
{
int* ptr = null;
dynamic tc = new TestClass();
try
{
tc.Method(out ptr);
}
catch (VerificationException e)
{
return 0; //this was won't fix
}
return 1;
}
}
// </Code>
}
#endif
| 25.799107 | 131 | 0.589894 | [
"MIT"
] | 690486439/corefx | src/System.Dynamic.Runtime/tests/Dynamic.Unsafe/Conformance.dynamic.unsafe.PointerOperator.cs | 5,779 | C# |
using System.Collections.Generic;
using Ascentis.Infrastructure.DataPipeline.SourceAdapter.Utils;
namespace Ascentis.Infrastructure.DataPipeline
{
public interface ISourceAdapter<TRow> : IAdapter
{
public event DataPipeline<TRow>.RowErrorDelegate OnSourceAdapterRowReadError;
public bool AbortOnReadException { get; set; }
void Prepare();
void UnPrepare();
void ReleaseRow(TRow row);
IEnumerable<TRow> RowsEnumerable { get; }
int FieldCount { get; }
ColumnMetadataList ColumnMetadatas { get; }
string DownConvertToText(object obj);
int ParallelLevel { get; set; }
Dictionary<string, int> MetadatasColumnToIndexMap { get; }
int RowsPoolSize { get; }
public IEnumerable<string> ColumnNames();
}
}
| 35.347826 | 85 | 0.686347 | [
"MIT"
] | Ascentis/Infrastructure | Ascentis.Infrastructure/DataPipeline/ISourceAdapter.cs | 815 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels;
public class DefaultPageApplicationModelProviderTest
{
[Fact]
public void OnProvidersExecuting_ThrowsIfPageDoesNotDeriveFromValidBaseType()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(InvalidPageWithWrongBaseClass).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => provider.OnProvidersExecuting(context));
// Assert
Assert.Equal(
$"The type '{typeInfo.FullName}' is not a valid page. A page must inherit from '{typeof(PageBase).FullName}'.",
ex.Message);
}
private class InvalidPageWithWrongBaseClass : RazorPageBase
{
public override void BeginContext(int position, int length, bool isLiteral)
{
throw new NotImplementedException();
}
public override void EndContext()
{
throw new NotImplementedException();
}
public override void EnsureRenderedBodyOrSections()
{
throw new NotImplementedException();
}
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
[Fact]
public void OnProvidersExecuting_ThrowsIfModelPropertyDoesNotExistOnPage()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithoutModelProperty).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => provider.OnProvidersExecuting(context));
// Assert
Assert.Equal(
$"The type '{typeInfo.FullName}' is not a valid page. A page must define a public, non-static 'Model' property.",
ex.Message);
}
private class PageWithoutModelProperty : PageBase
{
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[Fact]
public void OnProvidersExecuting_ThrowsIfModelPropertyIsNotPublic()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithNonVisibleModel).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => provider.OnProvidersExecuting(context));
// Assert
Assert.Equal(
$"The type '{typeInfo.FullName}' is not a valid page. A page must define a public, non-static 'Model' property.",
ex.Message);
}
private class PageWithNonVisibleModel : PageBase
{
private object Model => null;
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[Fact]
public void OnProvidersExecuting_ThrowsIfModelPropertyIsStatic()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithStaticModel).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => provider.OnProvidersExecuting(context));
// Assert
Assert.Equal(
$"The type '{typeInfo.FullName}' is not a valid page. A page must define a public, non-static 'Model' property.",
ex.Message);
}
private class PageWithStaticModel : PageBase
{
public static object Model => null;
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[Fact]
public void OnProvidersExecuting_DiscoversPropertiesFromPage_IfModelTypeDoesNotHaveAttribute()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithModelWithoutPageModelAttribute).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
var propertiesOnPage = context.PageApplicationModel.HandlerProperties
.Where(p => p.PropertyInfo.DeclaringType.GetTypeInfo() == typeInfo);
Assert.Collection(
propertiesOnPage.OrderBy(p => p.PropertyName),
property =>
{
Assert.Equal(typeInfo.GetProperty(nameof(PageWithModelWithoutPageModelAttribute.Model)), property.PropertyInfo);
Assert.Equal(nameof(PageWithModelWithoutPageModelAttribute.Model), property.PropertyName);
},
property =>
{
Assert.Equal(typeInfo.GetProperty(nameof(PageWithModelWithoutPageModelAttribute.Property1)), property.PropertyInfo);
Assert.Null(property.BindingInfo);
Assert.Equal(nameof(PageWithModelWithoutPageModelAttribute.Property1), property.PropertyName);
},
property =>
{
Assert.Equal(typeInfo.GetProperty(nameof(PageWithModelWithoutPageModelAttribute.Property2)), property.PropertyInfo);
Assert.Equal(nameof(PageWithModelWithoutPageModelAttribute.Property2), property.PropertyName);
Assert.NotNull(property.BindingInfo);
Assert.Equal(BindingSource.Path, property.BindingInfo.BindingSource);
});
}
private class PageWithModelWithoutPageModelAttribute : Page
{
public string Property1 { get; set; }
[FromRoute]
public object Property2 { get; set; }
public ModelWithoutPageModelAttribute Model => null;
public override Task ExecuteAsync() => throw new NotImplementedException();
}
private class ModelWithoutPageModelAttribute
{
}
[Fact]
public void OnProvidersExecuting_DiscoversPropertiesFromPageModel_IfModelHasAttribute()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithModelWithPageModelAttribute).GetTypeInfo();
var modelType = typeof(ModelWithPageModelAttribute);
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerProperties.OrderBy(p => p.PropertyName),
property =>
{
Assert.Equal(modelType.GetProperty(nameof(ModelWithPageModelAttribute.Property)), property.PropertyInfo);
Assert.Equal(nameof(ModelWithPageModelAttribute.Property), property.PropertyName);
Assert.NotNull(property.BindingInfo);
Assert.Equal(BindingSource.Path, property.BindingInfo.BindingSource);
});
}
private class PageWithModelWithPageModelAttribute : Page
{
public string Property1 { get; set; }
[FromRoute]
public object Property2 { get; set; }
public ModelWithPageModelAttribute Model => null;
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[PageModel]
private class ModelWithPageModelAttribute
{
[FromRoute]
public string Property { get; set; }
}
[Fact]
public void OnProvidersExecuting_DiscoversProperties_FromAllSubTypesThatDeclaresBindProperty()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(BindPropertyAttributeOnBaseModelPage).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerProperties.OrderBy(p => p.PropertyName).Where(p => p.BindingInfo != null),
property =>
{
var name = nameof(ModelLevel3.Property2);
Assert.Equal(typeof(ModelLevel3).GetProperty(name), property.PropertyInfo);
Assert.Equal(name, property.PropertyName);
Assert.NotNull(property.BindingInfo);
},
property =>
{
var name = nameof(ModelLevel3.Property3);
Assert.Equal(typeof(ModelLevel3).GetProperty(name), property.PropertyInfo);
Assert.Equal(name, property.PropertyName);
Assert.NotNull(property.BindingInfo);
});
}
private class BindPropertyAttributeOnBaseModelPage : Page
{
public ModelLevel3 Model => null;
public override Task ExecuteAsync() => throw new NotImplementedException();
}
private class ModelLevel1 : PageModel
{
public string Property1 { get; set; }
}
[BindProperties]
private class ModelLevel2 : ModelLevel1
{
public string Property2 { get; set; }
}
private class ModelLevel3 : ModelLevel2
{
public string Property3 { get; set; }
}
[Fact]
public void OnProvidersExecuting_DiscoversHandlersFromPage()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithModelWithoutHandlers).GetTypeInfo();
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerMethods.OrderBy(p => p.Name),
handler =>
{
var name = nameof(PageWithModelWithoutHandlers.OnGet);
Assert.Equal(typeInfo.GetMethod(name), handler.MethodInfo);
Assert.Equal(name, handler.Name);
Assert.Equal("Get", handler.HttpMethod);
Assert.Null(handler.HandlerName);
},
handler =>
{
var name = nameof(PageWithModelWithoutHandlers.OnPostAsync);
Assert.Equal(typeInfo.GetMethod(name), handler.MethodInfo);
Assert.Equal(name, handler.Name);
Assert.Equal("Post", handler.HttpMethod);
Assert.Null(handler.HandlerName);
},
handler =>
{
var name = nameof(PageWithModelWithoutHandlers.OnPostDeleteCustomerAsync);
Assert.Equal(typeInfo.GetMethod(name), handler.MethodInfo);
Assert.Equal(name, handler.Name);
Assert.Equal("Post", handler.HttpMethod);
Assert.Equal("DeleteCustomer", handler.HandlerName);
});
}
[Fact]
public void OnProvidersExecuting_DiscoversPropertiesFromModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithModel).GetTypeInfo();
var modelType = typeof(TestPageModel);
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerProperties.OrderBy(p => p.PropertyName),
property =>
{
var name = nameof(TestPageModel.Property1);
Assert.Equal(modelType.GetProperty(name), property.PropertyInfo);
Assert.Null(property.BindingInfo);
Assert.Equal(name, property.PropertyName);
},
property =>
{
var name = nameof(TestPageModel.Property2);
Assert.Equal(modelType.GetProperty(name), property.PropertyInfo);
Assert.Equal(name, property.PropertyName);
Assert.NotNull(property.BindingInfo);
Assert.Equal(BindingSource.Query, property.BindingInfo.BindingSource);
});
}
[Fact]
public void OnProvidersExecuting_DiscoversBindingInfoFromHandler()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithBindPropertyModel).GetTypeInfo();
var modelType = typeof(ModelWithBindProperty);
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerProperties.OrderBy(p => p.PropertyName),
property =>
{
Assert.Equal(nameof(ModelWithBindProperty.Property1), property.PropertyName);
Assert.NotNull(property.BindingInfo);
},
property =>
{
Assert.Equal(nameof(ModelWithBindProperty.Property2), property.PropertyName);
Assert.NotNull(property.BindingInfo);
Assert.Equal(BindingSource.Path, property.BindingInfo.BindingSource);
});
}
private class PageWithBindPropertyModel : PageBase
{
public ModelWithBindProperty Model => null;
public override Task ExecuteAsync() => null;
}
[BindProperties]
[PageModel]
private class ModelWithBindProperty
{
public string Property1 { get; set; }
[FromRoute]
public string Property2 { get; set; }
}
[Fact]
public void OnProvidersExecuting_DiscoversHandlersFromModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithModel).GetTypeInfo();
var modelType = typeof(TestPageModel);
var descriptor = new PageActionDescriptor();
var context = new PageApplicationModelProviderContext(descriptor, typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.NotNull(context.PageApplicationModel);
Assert.Collection(
context.PageApplicationModel.HandlerMethods.OrderBy(p => p.Name),
handler =>
{
var name = nameof(TestPageModel.OnGetUser);
Assert.Equal(modelType.GetMethod(name), handler.MethodInfo);
Assert.Equal(name, handler.Name);
Assert.Equal("Get", handler.HttpMethod);
Assert.Equal("User", handler.HandlerName);
});
}
// We want to test the 'empty' page has no bound properties, and no handler methods.
[Fact]
public void OnProvidersExecuting_EmptyPage()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(EmptyPage).GetTypeInfo();
var context = new PageApplicationModelProviderContext(new PageActionDescriptor(), typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
var pageModel = context.PageApplicationModel;
Assert.Empty(pageModel.HandlerProperties.Where(p => p.BindingInfo != null));
Assert.Empty(pageModel.HandlerMethods);
Assert.Same(typeof(EmptyPage).GetTypeInfo(), pageModel.HandlerType);
Assert.Same(typeof(EmptyPage).GetTypeInfo(), pageModel.ModelType);
Assert.Same(typeof(EmptyPage).GetTypeInfo(), pageModel.PageType);
}
// We want to test the 'empty' page and PageModel has no bound properties, and no handler methods.
[Fact]
public void OnProvidersExecuting_EmptyPageModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(EmptyPageWithPageModel).GetTypeInfo();
var context = new PageApplicationModelProviderContext(new PageActionDescriptor(), typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
var pageModel = context.PageApplicationModel;
Assert.Empty(pageModel.HandlerProperties.Where(p => p.BindingInfo != null));
Assert.Empty(pageModel.HandlerMethods);
Assert.Same(typeof(EmptyPageModel).GetTypeInfo(), pageModel.DeclaredModelType);
Assert.Same(typeof(EmptyPageModel).GetTypeInfo(), pageModel.ModelType);
Assert.Same(typeof(EmptyPageModel).GetTypeInfo(), pageModel.HandlerType);
Assert.Same(typeof(EmptyPageWithPageModel).GetTypeInfo(), pageModel.PageType);
}
private class EmptyPage : Page
{
// Copied from generated code
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<EmptyPage> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<EmptyPage> ViewData => null;
public EmptyPage Model => ViewData.Model;
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class EmptyPageWithPageModel : Page
{
// Copied from generated code
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<EmptyPageModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<EmptyPageModel> ViewData => null;
public EmptyPageModel Model => ViewData.Model;
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class EmptyPageModel : PageModel
{
}
[Fact]
public void OnProvidersExecuting_CombinesFilters_OnPageAndPageModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithFilters).GetTypeInfo();
var context = new PageApplicationModelProviderContext(new PageActionDescriptor(), typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
var pageModel = context.PageApplicationModel;
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<TypeFilterAttribute>(filter),
filter => Assert.IsType<ServiceFilterAttribute>(filter),
filter => Assert.IsType<PageHandlerPageFilter>(filter),
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
[ServiceFilter(typeof(Guid))]
private class PageWithFilters : Page
{
public PageWithFilterModel Model { get; }
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[TypeFilter(typeof(string))]
private class PageWithFilterModel : PageModel
{
}
[ServiceFilter(typeof(IServiceProvider))]
private class FiltersOnPageAndPageModel : PageModel { }
[Fact] // If the model has handler methods, we prefer those.
public void CreateDescriptor_FindsHandlerMethod_OnModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithHandlerThatGetsIgnored).GetTypeInfo();
var modelType = typeof(ModelWithHandler);
var context = new PageApplicationModelProviderContext(new PageActionDescriptor(), typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
var pageModel = context.PageApplicationModel;
Assert.Contains(
pageModel.HandlerProperties,
p => p.PropertyInfo == modelType.GetProperty(nameof(ModelWithHandler.BindMe)));
Assert.Collection(
pageModel.HandlerMethods,
p => Assert.Equal(modelType.GetMethod(nameof(ModelWithHandler.OnGet)), p.MethodInfo));
Assert.Same(typeof(ModelWithHandler).GetTypeInfo(), pageModel.HandlerType);
Assert.Same(typeof(ModelWithHandler).GetTypeInfo(), pageModel.ModelType);
Assert.Same(typeof(PageWithHandlerThatGetsIgnored).GetTypeInfo(), pageModel.PageType);
}
private class ModelWithHandler : PageModel
{
[ModelBinder]
public int BindMe { get; set; }
public void OnGet() { }
}
private class PageWithHandlerThatGetsIgnored : Page
{
public ModelWithHandler Model => null;
[ModelBinder]
public int IgnoreMe { get; set; }
public void OnPost() { }
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[Fact] // If the model does not have the PageModelAttribute, we look at the page instead.
public void OnProvidersExecuting_FindsHandlerMethodOnPage_WhenModelIsNotAnnotatedWithPageModelAttribute()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithHandler).GetTypeInfo();
var context = new PageApplicationModelProviderContext(new PageActionDescriptor(), typeInfo);
// Act
provider.OnProvidersExecuting(context);
// Assert
var pageModel = context.PageApplicationModel;
var propertiesOnPage = pageModel.HandlerProperties
.Where(p => p.PropertyInfo.DeclaringType.GetTypeInfo() == typeInfo);
Assert.Collection(
propertiesOnPage.OrderBy(p => p.PropertyName),
p => Assert.Equal(typeInfo.GetProperty(nameof(PageWithHandler.BindMe)), p.PropertyInfo),
p => Assert.Equal(typeInfo.GetProperty(nameof(PageWithHandler.Model)), p.PropertyInfo));
Assert.Collection(
pageModel.HandlerMethods,
p => Assert.Equal(typeInfo.GetMethod(nameof(PageWithHandler.OnGet)), p.MethodInfo));
Assert.Same(typeof(PageWithHandler).GetTypeInfo(), pageModel.HandlerType);
Assert.Same(typeof(PocoModel).GetTypeInfo(), pageModel.ModelType);
Assert.Same(typeof(PageWithHandler).GetTypeInfo(), pageModel.PageType);
}
private class PageWithHandler : Page
{
public PocoModel Model => null;
[ModelBinder]
public int BindMe { get; set; }
public void OnGet() { }
public override Task ExecuteAsync() => throw new NotImplementedException();
}
private class PocoModel
{
// Just a plain ol' model, nothing to see here.
[ModelBinder]
public int IgnoreMe { get; set; }
public void OnGet() { }
}
[Fact]
public void PopulateHandlerMethods_DiscoversHandlersFromBaseType()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(InheritsMethods).GetTypeInfo();
var baseType = typeof(TestSetPageModel);
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Collection(
handlerMethods.OrderBy(h => h.MethodInfo.DeclaringType.Name).ThenBy(h => h.MethodInfo.Name),
handler =>
{
Assert.Equal(nameof(InheritsMethods.OnGet), handler.MethodInfo.Name);
Assert.Equal(typeInfo, handler.MethodInfo.DeclaringType.GetTypeInfo());
},
handler =>
{
Assert.Equal(nameof(TestSetPageModel.OnGet), handler.MethodInfo.Name);
Assert.Equal(baseType, handler.MethodInfo.DeclaringType);
},
handler =>
{
Assert.Equal(nameof(TestSetPageModel.OnPost), handler.MethodInfo.Name);
Assert.Equal(baseType, handler.MethodInfo.DeclaringType);
});
}
private class TestSetPageModel
{
public void OnGet()
{
}
public void OnPost()
{
}
}
private class InheritsMethods : TestSetPageModel
{
public new void OnGet()
{
}
}
[Fact]
public void PopulateHandlerMethods_IgnoresNonPublicMethods()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(ProtectedModel).GetTypeInfo();
var baseType = typeof(TestSetPageModel);
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Empty(handlerMethods);
}
private class ProtectedModel
{
protected void OnGet()
{
}
private void OnPost()
{
}
}
[Fact]
public void PopulateHandlerMethods_IgnoreGenericTypeParameters()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(GenericClassModel).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Empty(handlerMethods);
}
private class GenericClassModel
{
public void OnGet<T>()
{
}
}
[Fact]
public void PopulateHandlerMethods_IgnoresStaticMethods()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageModelWithStaticHandler).GetTypeInfo();
var expected = typeInfo.GetMethod(nameof(PageModelWithStaticHandler.OnGet), BindingFlags.Public | BindingFlags.Instance);
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Collection(
handlerMethods,
handler => Assert.Same(expected, handler.MethodInfo));
}
private class PageModelWithStaticHandler
{
public static void OnGet(string name)
{
}
public void OnGet()
{
}
}
[Fact]
public void PopulateHandlerMethods_IgnoresAbstractMethods()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageModelWithAbstractMethod).GetTypeInfo();
var expected = typeInfo.GetMethod(nameof(PageModelWithAbstractMethod.OnGet), BindingFlags.Public | BindingFlags.Instance);
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Collection(
handlerMethods,
handler => Assert.Same(expected, handler.MethodInfo));
}
private abstract class PageModelWithAbstractMethod
{
public abstract void OnPost(string name);
public void OnGet()
{
}
}
[Fact]
public void PopulateHandlerMethods_IgnoresMethodWithNonHandlerAttribute()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithNonHandlerMethod).GetTypeInfo();
var expected = typeInfo.GetMethod(nameof(PageWithNonHandlerMethod.OnGet), BindingFlags.Public | BindingFlags.Instance);
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Collection(
handlerMethods,
handler => Assert.Same(expected, handler.MethodInfo));
}
private class PageWithNonHandlerMethod
{
[NonHandler]
public void OnPost(string name) { }
public void OnGet()
{
}
}
// There are more tests for the parsing elsewhere, this is just testing that it's wired
// up to the model.
[Fact]
public void CreateHandlerModel_ParsesMethod()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageModelWithHandlerNames).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
Assert.Collection(
handlerMethods.OrderBy(h => h.MethodInfo.Name),
handler =>
{
Assert.Same(typeInfo.GetMethod(nameof(PageModelWithHandlerNames.OnPutDeleteAsync)), handler.MethodInfo);
Assert.Equal("Put", handler.HttpMethod);
Assert.Equal("Delete", handler.HandlerName);
});
}
private class PageModelWithHandlerNames
{
public void OnPutDeleteAsync()
{
}
public void Foo() // This isn't a valid handler name.
{
}
}
[Fact]
public void CreateHandlerMethods_AddsParameterDescriptors()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(PageWithHandlerParameters).GetTypeInfo();
var expected = typeInfo.GetMethod(nameof(PageWithHandlerParameters.OnPost));
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerMethods(pageModel);
// Assert
var handlerMethods = pageModel.HandlerMethods;
var handler = Assert.Single(handlerMethods);
Assert.Collection(
handler.Parameters,
p =>
{
Assert.NotNull(p.ParameterInfo);
Assert.Equal(typeof(string), p.ParameterInfo.ParameterType);
Assert.Equal("name", p.ParameterName);
},
p =>
{
Assert.NotNull(p.ParameterInfo);
Assert.Equal(typeof(int), p.ParameterInfo.ParameterType);
Assert.Equal("id", p.ParameterName);
Assert.Equal("personId", p.BindingInfo.BinderModelName);
});
}
private class PageWithHandlerParameters
{
public void OnPost(string name, [ModelBinder(Name = "personId")] int id) { }
}
// We're using PropertyHelper from Common to find the properties here, which implements
// out standard set of semantics for properties that the framework interacts with.
//
// One of the desirable consequences of that is we only find 'visible' properties. We're not
// retesting all of the details of PropertyHelper here, just the visibility part as a quick check
// that we're using PropertyHelper as expected.
[Fact]
public void PopulateHandlerProperties_UsesPropertyHelpers_ToFindProperties()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(HidesAProperty).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerProperties(pageModel);
// Assert
var properties = pageModel.HandlerProperties;
Assert.Collection(
properties,
p =>
{
Assert.Equal(typeof(HidesAProperty).GetTypeInfo(), p.PropertyInfo.DeclaringType.GetTypeInfo());
});
}
private class HasAHiddenProperty
{
[BindProperty]
public int Property { get; set; }
}
private class HidesAProperty : HasAHiddenProperty
{
[BindProperty]
public new int Property { get; set; }
}
[Fact]
public void PopulateHandlerProperties_SupportsGet_OnProperty()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(ModelSupportsGetOnProperty).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, new object[0]);
// Act
provider.PopulateHandlerProperties(pageModel);
// Assert
var properties = pageModel.HandlerProperties;
Assert.Collection(
properties.OrderBy(p => p.PropertyName),
p =>
{
Assert.Equal(typeInfo.GetProperty(nameof(ModelSupportsGetOnProperty.Property)), p.PropertyInfo);
Assert.NotNull(p.BindingInfo.RequestPredicate);
Assert.True(p.BindingInfo.RequestPredicate(new ActionContext
{
HttpContext = new DefaultHttpContext
{
Request =
{
Method ="GET",
}
}
}));
});
}
private class ModelSupportsGetOnProperty
{
[BindProperty(SupportsGet = true)]
public int Property { get; set; }
}
[Theory]
[InlineData("Foo")]
[InlineData("On")]
[InlineData("OnAsync")]
[InlineData("Async")]
public void TryParseHandler_ParsesHandlerNames_InvalidData(string methodName)
{
// Act
var result = DefaultPageApplicationModelPartsProvider.TryParseHandlerMethod(methodName, out var httpMethod, out var handler);
// Assert
Assert.False(result);
Assert.Null(httpMethod);
Assert.Null(handler);
}
[Theory]
[InlineData("OnG", "G", null)]
[InlineData("OnGAsync", "G", null)]
[InlineData("OnPOST", "P", "OST")]
[InlineData("OnPOSTAsync", "P", "OST")]
[InlineData("OnDeleteFoo", "Delete", "Foo")]
[InlineData("OnDeleteFooAsync", "Delete", "Foo")]
[InlineData("OnMadeupLongHandlerName", "Madeup", "LongHandlerName")]
[InlineData("OnMadeupLongHandlerNameAsync", "Madeup", "LongHandlerName")]
public void TryParseHandler_ParsesHandlerNames_ValidData(string methodName, string expectedHttpMethod, string expectedHandler)
{
// Arrange
// Act
var result = DefaultPageApplicationModelPartsProvider.TryParseHandlerMethod(methodName, out var httpMethod, out var handler);
// Assert
Assert.True(result);
Assert.Equal(expectedHttpMethod, httpMethod);
Assert.Equal(expectedHandler, handler);
}
private class PageWithModelWithoutHandlers : Page
{
public ModelWithoutHandler Model { get; }
public override Task ExecuteAsync() => throw new NotImplementedException();
public void OnGet() { }
public void OnPostAsync() { }
public void OnPostDeleteCustomerAsync() { }
public class ModelWithoutHandler
{
}
}
private class PageWithModel : Page
{
public TestPageModel Model { get; }
public override Task ExecuteAsync() => throw new NotImplementedException();
}
[PageModel]
private class TestPageModel
{
public string Property1 { get; set; }
[FromQuery]
public string Property2 { get; set; }
public void OnGetUser() { }
}
[Fact]
public void PopulateFilters_AddsDisallowOptionsRequestsPageFilter()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(object).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, typeInfo.GetCustomAttributes(inherit: true));
// Act
provider.PopulateFilters(pageModel);
// Assert
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
[Fact]
public void PopulateFilters_AddsIFilterMetadataAttributesToModel()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(FilterModel).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, typeInfo.GetCustomAttributes(inherit: true));
// Act
provider.PopulateFilters(pageModel);
// Assert
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<TypeFilterAttribute>(filter),
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
[PageModel]
[Serializable]
[TypeFilter(typeof(object))]
private class FilterModel
{
}
[Fact]
public void PopulateFilters_AddsPageHandlerPageFilter_IfPageImplementsIAsyncPageFilter()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(ModelImplementingAsyncPageFilter).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, typeInfo.GetCustomAttributes(inherit: true));
// Act
provider.PopulateFilters(pageModel);
// Assert
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<PageHandlerPageFilter>(filter),
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
private class ModelImplementingAsyncPageFilter : IAsyncPageFilter
{
public Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
throw new NotImplementedException();
}
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
{
throw new NotImplementedException();
}
}
[Fact]
public void PopulateFilters_AddsPageHandlerPageFilter_IfPageImplementsIPageFilter()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(ModelImplementingPageFilter).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, typeInfo.GetCustomAttributes(inherit: true));
// Act
provider.PopulateFilters(pageModel);
// Assert
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<PageHandlerPageFilter>(filter),
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
private class ModelImplementingPageFilter : IPageFilter
{
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
throw new NotImplementedException();
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
throw new NotImplementedException();
}
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
throw new NotImplementedException();
}
}
[Fact]
public void PopulateFilters_AddsPageHandlerPageFilter_ForModelDerivingFromTypeImplementingPageFilter()
{
// Arrange
var provider = CreateProvider();
var typeInfo = typeof(DerivedFromPageModel).GetTypeInfo();
var pageModel = new PageApplicationModel(new PageActionDescriptor(), typeInfo, typeInfo.GetCustomAttributes(inherit: true));
// Act
provider.PopulateFilters(pageModel);
// Assert
Assert.Collection(
pageModel.Filters,
filter => Assert.IsType<ServiceFilterAttribute>(filter),
filter => Assert.IsType<PageHandlerPageFilter>(filter),
filter => Assert.IsType<HandleOptionsRequestsPageFilter>(filter));
}
[ServiceFilter(typeof(IServiceProvider))]
private class DerivedFromPageModel : PageModel { }
private static DefaultPageApplicationModelProvider CreateProvider()
{
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
return new DefaultPageApplicationModelProvider(
modelMetadataProvider,
Options.Create(new RazorPagesOptions()),
new DefaultPageApplicationModelPartsProvider(modelMetadataProvider));
}
}
| 35.0682 | 133 | 0.646797 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Mvc/Mvc.RazorPages/test/ApplicationModels/DefaultPageApplicationModelProviderTest.cs | 42,680 | C# |
using DancingGoat.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
namespace DancingGoat.ViewComponents
{
public class TweetViewComponent : ViewComponent
{
private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(30) };
public TweetViewComponent()
{
}
public IViewComponentResult Invoke(Tweet item)
{
var selectedTheme = item.Theme.FirstOrDefault()?.Name?.ToLower() ?? "light";
var displayOptions = item.DisplayOptions.ToList();
var hideThread = displayOptions.Any(o => o.Codename.Equals("hide_thread"));
var hideMedia = displayOptions.Any(o => o.Codename.Equals("hide_media"));
var options = $"&hide_thread={hideThread}&hide_media={hideMedia}";
var tweetLink = item.TweetLink;
var tweetResponse = Client.GetAsync(
$"https://publish.twitter.com/oembed?url={tweetLink}&theme={selectedTheme}" + options).Result;
var jsonResponse = JObject.Parse(tweetResponse.Content.ReadAsStringAsync().Result);
return View((object)jsonResponse?.Property("html")?.Value.ToObject<string>());
}
}
}
| 36.514286 | 110 | 0.655712 | [
"MIT"
] | ArunWadhwagit/test1 | DancingGoat/ViewComponents/TweetViewComponent.cs | 1,280 | C# |
/*
Copyright 2011 Michael Edwards
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 System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Sitecore.Mapper.Configuration;
using Glass.Sitecore.Mapper.Data;
using Glass.Sitecore.Mapper.Configuration.Attributes;
using System.Reflection.Emit;
namespace Glass.Sitecore.Mapper
{
public class Context
{
public ClassManager ClassManager
{
get
{
return StaticContext.ClassManager;
}
set
{
StaticContext.ClassManager = value;
}
}
#region STATICS
/// <summary>
/// The context created with the classes loaded. If you want a copy of this use GetContext.
/// </summary>
internal static InstanceContext StaticContext { get; set; }
static readonly object _lock = new object();
/// <summary>
/// Indicates that the context has been loaded
/// </summary>
static bool _contextLoaded = false;
#endregion
/// <summary>
/// The context constructor should only be called once. After the context has been created call GetContext for specific copies
/// </summary>
/// <param name="loader">The loader used to load classes.</param>
public Context(params AbstractConfigurationLoader [] loaders)
{
//the setup must only run if the context has not been setup
//second attempts to setup a context should throw an error
if (!_contextLoaded)
{
lock (_lock)
{
if (!_contextLoaded)
{
//load all classes
List<SitecoreClassConfig> configs = new List<SitecoreClassConfig>();
List<AbstractSitecoreDataHandler> dataHandlers = new List<AbstractSitecoreDataHandler>();
foreach(var loader in loaders){
configs.AddRange(loader.Load());
if(loader.DataHandlers != null)
dataHandlers.AddRange(loader.DataHandlers);
}
var classes = configs.ToDictionary();
InstanceContext instance = new InstanceContext(classes, dataHandlers, loaders);
StaticContext = instance;
//now assign a data handler to each property
foreach (var cls in classes)
{
IList<AbstractSitecoreDataHandler> handlers = new List<AbstractSitecoreDataHandler>();
//create constructors
CreateConstructorDelegates(cls.Value);
foreach (var prop in cls.Value.Properties)
{
var handler = instance.GetDataHandler(prop);
//set the ID property of the class
//the ID property is needed later for writing and page editing,
//saves time having to look it
if (prop.Attribute is SitecoreIdAttribute)
cls.Value.IdProperty = prop;
else if (prop.Attribute is SitecoreInfoAttribute
&& prop.Attribute.CastTo<SitecoreInfoAttribute>().Type == SitecoreInfoType.Language)
cls.Value.LanguageProperty = prop;
else if (prop.Attribute is SitecoreInfoAttribute
&& prop.Attribute.CastTo<SitecoreInfoAttribute>().Type == SitecoreInfoType.Version)
cls.Value.VersionProperty = prop;
handlers.Add(handler);
}
cls.Value.DataHandlers = handlers;
}
}
}
}
else
throw new MapperException("Context already loaded");
}
/// <summary>
/// The context constructor should only be called once. After the context has been created call GetContext for specific copies
/// </summary>
/// <param name="loader">The loader used to load classes.</param>
/// <param name="datas">Custom data handlers.</param>
[Obsolete("Assign AbstractDataHandlers to the IConfigurationLoader.DataHandlers property instead of using this contructor")]
public Context(AbstractConfigurationLoader loader, IEnumerable<AbstractSitecoreDataHandler> datas) :this(new TemporaryConfigurationLoader(loader, datas))
{
}
/// <summary>
/// A temporary class to bridge the gap between the original method of loading classes and the new solution
/// </summary>
private class TemporaryConfigurationLoader:AbstractConfigurationLoader{
AbstractConfigurationLoader _loader;
private static readonly Guid _id = new Guid("{60782D9C-C145-4C12-AC68-9C328B085F64}");
public TemporaryConfigurationLoader(AbstractConfigurationLoader loader, IEnumerable<AbstractSitecoreDataHandler> datas)
{
_loader = loader;
//must push custom handlers to the top of the pile.
datas.ForEach(x => _loader.AddDataHandler(x));
this._dataHandlers = _loader.DataHandlers.ToList();
}
public override IEnumerable<SitecoreClassConfig> Load()
{
return _loader.Load();
}
public override Guid Id
{
get { return _id; }
}
}
/// <summary>
/// Returns a delegate method that will load a class based on its constuctor
/// </summary>
/// <param name="classConfig">The SitecoreClassConfig to store the delegate method in</param>
/// <param name="constructorParameters">The list of contructor parameters</param>
/// <param name="delegateType">The type of the delegate function to create</param>
/// <returns></returns>
internal static void CreateConstructorDelegates(SitecoreClassConfig classConfig)
{
Type type = classConfig.Type;
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
var parameters = constructor.GetParameters();
var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + type.Name, type, parameters.Select(x => x.ParameterType).ToArray(), type);
ILGenerator ilGen = dynMethod.GetILGenerator();
for (int i = 0; i < parameters.Count(); i++)
{
ilGen.Emit(OpCodes.Ldarg, i);
}
ilGen.Emit(OpCodes.Newobj, constructor);
ilGen.Emit(OpCodes.Ret);
Type genericType = null;
switch (parameters.Count())
{
case 0:
genericType = typeof(Func<>);
break;
case 1:
genericType = typeof(Func<,>);
break;
case 2:
genericType = typeof(Func<,,>);
break;
case 3:
genericType = typeof(Func<,,,>);
break;
case 4:
genericType = typeof(Func<,,,,>);
break;
default:
throw new MapperException("Only supports constructors with a maximum of 4 parameters");
}
var delegateType = genericType.MakeGenericType(parameters.Select(x=>x.ParameterType).Concat(new []{ type}).ToArray());
classConfig.CreateObjectMethods[constructor] = dynMethod.CreateDelegate(delegateType);
}
}
/// <summary>
/// Creates an instance of the context that can be used by the calling class
/// </summary>
/// <returns></returns>
internal static InstanceContext GetContext()
{
if (StaticContext == null) throw new MapperException("Context has not been loaded");
//due to changes in the way that handlers are created we should no longer need to clone the instance context
return StaticContext; //.Clone() as InstanceContext;
}
}
}
| 37.880478 | 169 | 0.535759 | [
"Apache-2.0"
] | akatakritos/Glass.Sitecore.Mapper | Source/Glass.Sitecore.Mapper/Context.cs | 9,510 | C# |
namespace OpenVIII.Fields.Scripts.Instructions
{
/// <summary>
/// Set Card? Card ID and NPC?
/// </summary>
/// <see cref="http://wiki.ffrtt.ru/index.php?title=FF8/Field/Script/Opcodes/15E_SETCARD&action=edit&redlink=1"/>
public sealed class SetCard : JsmInstruction
{
#region Fields
/// <summary>
/// I think this is the card ID.
/// </summary>
private readonly IJsmExpression _cardID;
/// <summary>
/// Unsure Maybe NPC who has the card?
/// </summary>
private readonly IJsmExpression _maybeNPC;
#endregion Fields
#region Constructors
public SetCard(IJsmExpression maybeNPC, IJsmExpression cardID)
{
_maybeNPC = maybeNPC;
_cardID = cardID;
}
public SetCard(int parameter, IStack<IJsmExpression> stack)
: this(
cardID: stack.Pop(), //can't cast to card ID with out doing something first
maybeNPC: stack.Pop())
{
}
#endregion Constructors
#region Methods
public override string ToString() => $"{nameof(SetCard)}({nameof(_maybeNPC)}: {_maybeNPC}, {nameof(_cardID)}: {_cardID})";
#endregion Methods
}
} | 27.73913 | 130 | 0.579154 | [
"MIT"
] | Sebanisu/OpenVIII | Core/Field/JSM/Instructions/SetCard.cs | 1,278 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.