content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Xml;
namespace DocumentFormat.OpenXml
{
/// <summary>
/// Represents the <see cref="sbyte"/> value for attributes.
/// </summary>
[CLSCompliant(false)]
[DebuggerDisplay("{InnerText}")]
public class SByteValue : OpenXmlComparableSimpleValue<sbyte>
{
/// <summary>
/// Initializes a new instance of the <see cref="SByteValue"/> class.
/// </summary>
public SByteValue()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SByteValue"/> class using the supplied <see cref="sbyte"/> value.
/// </summary>
/// <param name="value">The <see cref="sbyte"/> value.</param>
public SByteValue(sbyte value)
: base(value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SByteValue"/> by deep copying the supplied <see cref="SByteValue"/> class.
/// </summary>
/// <param name="source">The source <see cref="SByteValue"/> class.</param>
public SByteValue(SByteValue source)
: base(source)
{
}
private protected override string GetText(sbyte input) => XmlConvert.ToString(input);
private protected override sbyte Parse(string input) => XmlConvert.ToSByte(input);
/// <summary>
/// Implicitly converts the specified <see cref="SByteValue"/> to an <see cref="sbyte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByteValue"/> to convert.</param>
/// <returns>The converted <see cref="sbyte"/> value.</returns>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="value"/> is <c>null</c>.</exception>
public static implicit operator sbyte(SByteValue value)
{
if (value is null)
{
throw new InvalidOperationException(ExceptionMessages.ImplicitConversionExceptionOnNull);
}
return ToSByte(value);
}
/// <summary>
/// Implicitly converts the specified <see cref="sbyte"/> value to an <see cref="SByteValue"/> instance.
/// </summary>
/// <param name="value">The specified <see cref="sbyte"/> value.</param>
/// <returns>A new <see cref="SByteValue"/> instance with the value.</returns>
public static implicit operator SByteValue(sbyte value) => FromSByte(value);
/// <summary>
/// Returns a new <see cref="SByteValue"/> object created from a Byte value.
/// </summary>
/// <param name="value">An <see cref="sbyte"/> value to use to create a new <see cref="SByteValue"/> object.</param>
/// <returns>An <see cref="SByteValue"/> that corresponds to the value parameter.</returns>
public static SByteValue FromSByte(sbyte value) => new SByteValue(value);
/// <summary>
/// Returns the <see cref="sbyte"/> representation of an <see cref="SByteValue"/> object.
/// </summary>
/// <param name="value">
/// An <see cref="SByteValue"/> object to retrieve an <see cref="sbyte"/> representation.
/// </param>
/// <returns>An <see cref="sbyte"/> value that represents an <see cref="SByteValue"/> object.</returns>
public static sbyte ToSByte(SByteValue value)
{
if (value is null)
{
throw new InvalidOperationException(ExceptionMessages.ImplicitConversionExceptionOnNull);
}
return value.Value;
}
private protected override OpenXmlSimpleType CloneImpl() => new SByteValue(this);
}
}
| 40.197917 | 131 | 0.602747 | [
"MIT"
] | 929496959/Open-XML-SDK | src/DocumentFormat.OpenXml/SimpleTypes/SByteValue.cs | 3,861 | C# |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalRis
{
/// <summary>
/// Controller class for TAM_PAPM
/// </summary>
[System.ComponentModel.DataObject]
public partial class TamPapmController
{
// Preload our schema..
TamPapm thisSchemaLoad = new TamPapm();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public TamPapmCollection FetchAll()
{
TamPapmCollection coll = new TamPapmCollection();
Query qry = new Query(TamPapm.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public TamPapmCollection FetchByID(object IdPaps)
{
TamPapmCollection coll = new TamPapmCollection().Where("idPaps", IdPaps).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public TamPapmCollection FetchByQuery(Query qry)
{
TamPapmCollection coll = new TamPapmCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdPaps)
{
return (TamPapm.Delete(IdPaps) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdPaps)
{
return (TamPapm.Destroy(IdPaps) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int? IdTipoPapPrevio,int? IdResultadoPapPrevio,int? IdCitologo,int? IdMedicoSol,int? IdTipoMuestra,string FechaMuestra,int? IdCentroMuestra,string FechaInforme,int? IdCalidadMuestra,int? IdMicroorganismo,int? IdOtrosHallazgos,int? IdCelulasEscamosas,int? IdCelulasGlandulares,int? IdObservacion,string FechaRecepcion,string Observaciones,int? IdCentro,int? IdMujerExporta,string NumeroLaboratorio,string FechaEntrega,string CervixSatisfactorio,string TratHormonal,string TratRadiante,string Quimioterapia,string TratDestructivo,string Embarazada,string FechaFum,int? Paridad,int? IdAnticonceptivo,int? IdCirugia,string Menopausia,string Lactancia,string FechaPrevio,int? IdPaps)
{
TamPapm item = new TamPapm();
item.IdTipoPapPrevio = IdTipoPapPrevio;
item.IdResultadoPapPrevio = IdResultadoPapPrevio;
item.IdCitologo = IdCitologo;
item.IdMedicoSol = IdMedicoSol;
item.IdTipoMuestra = IdTipoMuestra;
item.FechaMuestra = FechaMuestra;
item.IdCentroMuestra = IdCentroMuestra;
item.FechaInforme = FechaInforme;
item.IdCalidadMuestra = IdCalidadMuestra;
item.IdMicroorganismo = IdMicroorganismo;
item.IdOtrosHallazgos = IdOtrosHallazgos;
item.IdCelulasEscamosas = IdCelulasEscamosas;
item.IdCelulasGlandulares = IdCelulasGlandulares;
item.IdObservacion = IdObservacion;
item.FechaRecepcion = FechaRecepcion;
item.Observaciones = Observaciones;
item.IdCentro = IdCentro;
item.IdMujerExporta = IdMujerExporta;
item.NumeroLaboratorio = NumeroLaboratorio;
item.FechaEntrega = FechaEntrega;
item.CervixSatisfactorio = CervixSatisfactorio;
item.TratHormonal = TratHormonal;
item.TratRadiante = TratRadiante;
item.Quimioterapia = Quimioterapia;
item.TratDestructivo = TratDestructivo;
item.Embarazada = Embarazada;
item.FechaFum = FechaFum;
item.Paridad = Paridad;
item.IdAnticonceptivo = IdAnticonceptivo;
item.IdCirugia = IdCirugia;
item.Menopausia = Menopausia;
item.Lactancia = Lactancia;
item.FechaPrevio = FechaPrevio;
item.IdPaps = IdPaps;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdPaps,int? IdTipoPapPrevio,int? IdResultadoPapPrevio,int? IdCitologo,int? IdMedicoSol,int? IdTipoMuestra,string FechaMuestra,int? IdCentroMuestra,string FechaInforme,int? IdCalidadMuestra,int? IdMicroorganismo,int? IdOtrosHallazgos,int? IdCelulasEscamosas,int? IdCelulasGlandulares,int? IdObservacion,string FechaRecepcion,string Observaciones,int? IdCentro,int? IdMujerExporta,string NumeroLaboratorio,string FechaEntrega,string CervixSatisfactorio,string TratHormonal,string TratRadiante,string Quimioterapia,string TratDestructivo,string Embarazada,string FechaFum,int? Paridad,int? IdAnticonceptivo,int? IdCirugia,string Menopausia,string Lactancia,string FechaPrevio,int? IdPaps)
{
TamPapm item = new TamPapm();
item.MarkOld();
item.IsLoaded = true;
item.IdPaps = IdPaps;
item.IdTipoPapPrevio = IdTipoPapPrevio;
item.IdResultadoPapPrevio = IdResultadoPapPrevio;
item.IdCitologo = IdCitologo;
item.IdMedicoSol = IdMedicoSol;
item.IdTipoMuestra = IdTipoMuestra;
item.FechaMuestra = FechaMuestra;
item.IdCentroMuestra = IdCentroMuestra;
item.FechaInforme = FechaInforme;
item.IdCalidadMuestra = IdCalidadMuestra;
item.IdMicroorganismo = IdMicroorganismo;
item.IdOtrosHallazgos = IdOtrosHallazgos;
item.IdCelulasEscamosas = IdCelulasEscamosas;
item.IdCelulasGlandulares = IdCelulasGlandulares;
item.IdObservacion = IdObservacion;
item.FechaRecepcion = FechaRecepcion;
item.Observaciones = Observaciones;
item.IdCentro = IdCentro;
item.IdMujerExporta = IdMujerExporta;
item.NumeroLaboratorio = NumeroLaboratorio;
item.FechaEntrega = FechaEntrega;
item.CervixSatisfactorio = CervixSatisfactorio;
item.TratHormonal = TratHormonal;
item.TratRadiante = TratRadiante;
item.Quimioterapia = Quimioterapia;
item.TratDestructivo = TratDestructivo;
item.Embarazada = Embarazada;
item.FechaFum = FechaFum;
item.Paridad = Paridad;
item.IdAnticonceptivo = IdAnticonceptivo;
item.IdCirugia = IdCirugia;
item.Menopausia = Menopausia;
item.Lactancia = Lactancia;
item.FechaPrevio = FechaPrevio;
item.IdPaps = IdPaps;
item.Save(UserName);
}
}
}
| 32.487603 | 713 | 0.635589 | [
"MIT"
] | saludnqn/prosane | RIS_Publico/RIS_Publico/generated/TamPapmController.cs | 7,862 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vestris.ResourceLib
{
/// <summary>
/// This structure depicts the organization of data in an icon resource.
/// </summary>
public class IconResource : IconImageResource
{
/// <summary>
/// An existing icon resource.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="hResource">Resource ID.</param>
/// <param name="type">Resource type.</param>
/// <param name="name">Resource name.</param>
/// <param name="language">Language ID.</param>
/// <param name="size">Resource size.</param>
internal IconResource(IntPtr hModule, IntPtr hResource, ResourceId type, ResourceId name, UInt16 language, int size)
: base(hModule, hResource, type, name, language, size)
{
}
/// <summary>
/// A new icon resource.
/// </summary>
public IconResource()
: base(new ResourceId(Kernel32.ResourceTypes.RT_ICON))
{
}
/// <summary>
/// Convert into an icon resource that can be written into an executable.
/// </summary>
/// <param name="icon">Icon image.</param>
/// <param name="id">Icon Id.</param>
/// <param name="language">Resource language.</param>
/// <returns>An icon resource.</returns>
public IconResource(IconFileIcon icon, ResourceId id, UInt16 language)
: base(icon, new ResourceId(Kernel32.ResourceTypes.RT_ICON), id, language)
{
}
}
}
| 33.54 | 125 | 0.56768 | [
"MIT"
] | SunburstApps/ResourceLib | Source/ResourceLib/IconResource.cs | 1,679 | C# |
using NUnit.Framework;
namespace Disruptor.Tests
{
[TestFixture]
public class MultiProducerSequencerTest
{
private readonly MultiProducerSequencer _publisher = new MultiProducerSequencer(1024);
[Test]
public void ShouldOnlyAllowMessagesToBeAvailableIfSpecificallyPublished()
{
_publisher.Publish(3);
_publisher.Publish(5);
Assert.That(_publisher.IsAvailable(0), Is.EqualTo(false));
Assert.That(_publisher.IsAvailable(1), Is.EqualTo(false));
Assert.That(_publisher.IsAvailable(2), Is.EqualTo(false));
Assert.That(_publisher.IsAvailable(3), Is.EqualTo(true));
Assert.That(_publisher.IsAvailable(4), Is.EqualTo(false));
Assert.That(_publisher.IsAvailable(5), Is.EqualTo(true));
Assert.That(_publisher.IsAvailable(6), Is.EqualTo(false));
}
}
}
| 34.923077 | 94 | 0.655286 | [
"Apache-2.0"
] | JTOne123/Disruptor-net | src/Disruptor.Tests/MultiProducerSequencerTest.cs | 910 | C# |
namespace DesignPatterns.Other.Behavioral.Specification
{
using DesignPatterns.Other.Behavioral.Specification.Base;
public class InCollectionSpecification : CompositeSpecification<Invoice>
{
public override bool IsSatisfiedBy(Invoice invoice)
{
return invoice.SentToCollectionAgency;
}
}
} | 28.583333 | 76 | 0.720117 | [
"MIT"
] | jimtsikos/DesignPatternsCSharp | DesignPatternsStandard/Other/Behavioral/Specification/NoticeSentSpecification.cs | 345 | C# |
/*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 6.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
namespace AdobeSign.Rest.Test.Model.Agreements
{
/// <summary>
/// Class for testing ParticipantSecurityOption
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class ParticipantSecurityOptionTests
{
// TODO uncomment below to declare an instance variable for ParticipantSecurityOption
//private ParticipantSecurityOption instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of ParticipantSecurityOption
//instance = new ParticipantSecurityOption();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of ParticipantSecurityOption
/// </summary>
[Test]
public void ParticipantSecurityOptionInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" ParticipantSecurityOption
//Assert.IsInstanceOfType<ParticipantSecurityOption> (instance, "variable 'instance' is a ParticipantSecurityOption");
}
/// <summary>
/// Test the property 'AuthenticationMethod'
/// </summary>
[Test]
public void AuthenticationMethodTest()
{
// TODO unit test for the property 'AuthenticationMethod'
}
/// <summary>
/// Test the property 'Password'
/// </summary>
[Test]
public void PasswordTest()
{
// TODO unit test for the property 'Password'
}
/// <summary>
/// Test the property 'PhoneInfo'
/// </summary>
[Test]
public void PhoneInfoTest()
{
// TODO unit test for the property 'PhoneInfo'
}
}
}
| 27.305882 | 130 | 0.581646 | [
"Apache-2.0"
] | gabon/AdobeSignCSharpSDK | src/AdobeSign.Rest.Tests/Model.Agreements/ParticipantSecurityOptionTests.cs | 2,321 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Arcus.Templates.Tests.Integration.AzureFunctions.Admin;
using Arcus.Templates.Tests.Integration.AzureFunctions.Configuration;
using Arcus.Templates.Tests.Integration.AzureFunctions.Databricks.JobMetrics.Configuration;
using Arcus.Templates.Tests.Integration.AzureFunctions.Databricks.JobMetrics.MetricReporting;
using Arcus.Templates.Tests.Integration.AzureFunctions.Http.Configuration;
using Arcus.Templates.Tests.Integration.Fixture;
using Xunit;
using Xunit.Abstractions;
namespace Arcus.Templates.Tests.Integration.AzureFunctions.Http.Health
{
[Collection(TestCollections.Docker)]
[Trait("Category", TestTraits.Docker)]
public class HttpHealthDockerTests
{
private readonly ITestOutputHelper _outputWriter;
/// <summary>
/// Initializes a new instance of the <see cref="HttpHealthDockerTests"/> class.
/// </summary>
public HttpHealthDockerTests(ITestOutputHelper outputWriter)
{
_outputWriter = outputWriter;
}
[Fact]
public async Task AzureFunctionsHttpProject_WithoutOptions_ShouldAnswerToAdministratorEndpoint()
{
// Arrange
var configuration = TestConfig.Create();
AzureFunctionHttpConfig httpConfig = configuration.GetAzureFunctionHttpConfig();
var service = new AdminEndpointService(httpConfig.HttpPort, AzureFunctionsHttpProject.OrderFunctionName, _outputWriter);
// Act / Assert
await service.TriggerFunctionAsync();
}
}
}
| 38.232558 | 132 | 0.736618 | [
"MIT"
] | Mcalewaert/arcus.templates | src/Arcus.Templates.Tests.Integration/AzureFunctions/Http/Health/HttpHealthDockerTests.cs | 1,646 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.Common;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
namespace SuperWebSocket.Protocol
{
/// <summary>
/// WebSocketFragment request info
/// </summary>
public interface IWebSocketFragment : IRequestInfo
{
}
}
| 20.578947 | 55 | 0.70844 | [
"BSD-3-Clause"
] | 3rdandUrban-dev/Nuxleus | src/external/superwebsocket/future/SuperWebSocket/Protocol/IWebSocketFragment.cs | 393 | C# |
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Web.Server.Events;
using Microsoft.AspNetCore.Hosting;
namespace AppBrix.Web.Server.Impl
{
internal sealed class ConfigureWebHost : IConfigureWebHost
{
#region Construction
public ConfigureWebHost(IWebHostBuilder builder)
{
this.Builder = builder;
}
#endregion
#region Properties
public IWebHostBuilder Builder { get; }
#endregion
}
}
| 26 | 101 | 0.673913 | [
"MIT"
] | MarinAtanasov/AppBrix.NetCore | Modules/AppBrix.Web.Server/Impl/ConfigureWebHost.cs | 600 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Yolol.Execution;
namespace YololEmulator.Tests.Ladder
{
[TestClass]
public class TheBells
{
private static string RandomString(Random rng, int minLength, int maxLength)
{
const string chars = "ABCDEFGH";
var length = rng.Next(minLength, maxLength);
var order = Enumerable.Repeat(chars, length)
.Select(s => chars[rng.Next(chars.Length)])
.SelectMany(c => rng.NextDouble() > 0.93f ? new string(c, rng.Next(1, 10)) : c.ToString())
.ToArray();
return string.Join("", order);
}
[TestMethod]
public void GenerateTheBells()
{
var input = new List<Dictionary<string, Value>>();
var output = new List<Dictionary<string, Value>>();
void SingleCase(string pattern)
{
input.Add(new Dictionary<string, Value> {
{ "i", pattern },
});
var result = ApplyRules(pattern);
output.Add(new Dictionary<string, Value> {
{ "o", result },
});
}
SingleCase("ABAB");
SingleCase("AAA");
SingleCase("BACA");
SingleCase("BACAD");
var r = new Random();
while (input.Count < 100000)
SingleCase(RandomString(r, 1, 7));
Console.WriteLine($"Most swaps: {_most}");
Generator.YololLadderGenerator(input, output);
}
private static int _most;
private static string ApplyRules(string pattern)
{
// - If an A comes directly before a B, swap them
// - If an A comes directly after a C, swap them
// - If an C comes directly after a D, swap them
// - If an C comes directly after a B, swap them
// - If an D comes directly after a A, swap them
// - If there are an odd number of items, add the first character to the end of the string
static string ApplyRule(string input, Func<string, string> func)
{
var count = 0;
string p;
do
{
p = input;
input = func(input);
count++;
} while (input != p);
_most = Math.Max(_most, count);
return input;
}
// - If an A comes directly before a B, swap them
if (pattern.Contains("AB", StringComparison.OrdinalIgnoreCase))
return ApplyRule(pattern, a => a.Replace("AB", "BA"));
// - If an A comes directly after a C, swap them
if (pattern.Contains("CA", StringComparison.OrdinalIgnoreCase))
return ApplyRule(pattern, a => a.Replace("CA", "AC"));
// - If an C comes directly after a D, swap them
if (pattern.Contains("DC", StringComparison.OrdinalIgnoreCase))
return ApplyRule(pattern, a => a.Replace("DC", "CD"));
// - If an C comes directly after a B, swap them
if (pattern.Contains("BC", StringComparison.OrdinalIgnoreCase))
return ApplyRule(pattern, a => a.Replace("BC", "CB"));
// - If an D comes directly after a A, swap them
if (pattern.Contains("AD", StringComparison.OrdinalIgnoreCase))
return ApplyRule(pattern, a => a.Replace("AD", "DA"));
// - If there are an odd number of items, add the first character to the end of the string
if (pattern.Length % 2 == 1)
return pattern + pattern[0];
return pattern;
}
}
} | 35.477477 | 124 | 0.516506 | [
"MIT"
] | Resultlabz/Yolol | YololEmulator.Tests/Ladder/TheBells.cs | 3,940 | C# |
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014.Resources
{
using System.Runtime.Serialization;
/// <summary>
/// A virtual network resource.
/// </summary>
[DataContract(Namespace = Constants.HdInsightManagementNamespace)]
internal class VirtualNetworkResource : AbstractResource<VirtualNetworkResource>
{
public static VirtualNetworkResource ProvisionNew
{
get { return new VirtualNetworkResource { ShouldProvisionNew = true }; }
}
internal VirtualNetworkResource()
{
}
}
} | 37.617647 | 84 | 0.721658 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/HDInsight/Microsoft.WindowsAzure.Management.HDInsight.Contracts/May2014/Resources/VirtualNetworkResource.cs | 1,281 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
private Player player;
private LifeManager lifeManager;
[SerializeField] private int currentLife;
[SerializeField] private int score;
public int TotalLife = 3;
void Start()
{
player = FindObjectOfType<Player>();
lifeManager = FindObjectOfType<LifeManager>();
currentLife = TotalLife;
}
//체력 감소
public void decreaseLife(int _life = 1)
{
currentLife -= _life;
if (currentLife <= 0)
currentLife = 0;
lifeManager.updateHeartImage();
if (isDead()) player._state = Player.playerState.Die;
}
//체력이 0인지 확인
public bool isDead()
{
return (currentLife <= 0) ? true : false;
}
//체력 증가
public void increaseLife(int _life = 1)
{
currentLife += _life;
if (currentLife > TotalLife)
currentLife = TotalLife;
lifeManager.updateHeartImage();
}
//private인 currentLife를 외부에서 체크하는 함수
public int checkLife()
{
return currentLife;
}
public void addScore(int _score)
{
score += _score;
}
public int checkScore()
{
return score;
}
}
| 19.38806 | 61 | 0.597383 | [
"MIT"
] | DaeguDev/MeowRun | unity/Assets/Scripts/manager/GameManager.cs | 1,353 | 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.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Reflection;
using System.Globalization;
using System.Security.Permissions;
using System.Collections;
using System.Drawing;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Security;
namespace System.Windows.Forms {
internal class WebBrowserContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMethods.IOleInPlaceFrame {
//
// Private fields:
//
private WebBrowserBase parent;
private IContainer assocContainer; // associated IContainer...
// the assocContainer may be null, in which case all this container does is
// forward [de]activation messages to the requisite container...
private WebBrowserBase siteUIActive;
private WebBrowserBase siteActive;
private Hashtable containerCache = new Hashtable(); // name -> Control
private Hashtable components = null; // Control -> any
private WebBrowserBase ctlInEditMode = null;
internal WebBrowserContainer(WebBrowserBase parent) {
this.parent = parent;
}
//
// IOleContainer methods:
//
int UnsafeNativeMethods.IOleContainer.ParseDisplayName(Object pbc, string pszDisplayName, int[] pchEaten, Object[] ppmkOut) {
if (ppmkOut != null)
ppmkOut[0] = null;
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) {
ppenum = null;
if ((grfFlags & 1) != 0) { // 1 == OLECONTF_EMBEDDINGS
Debug.Assert(parent != null, "gotta have it...");
ArrayList list = new ArrayList();
ListAXControls(list, true);
if (list.Count > 0) {
Object[] temp = new Object[list.Count];
list.CopyTo(temp, 0);
ppenum = new AxHost.EnumUnknown(temp);
return NativeMethods.S_OK;
}
}
ppenum = new AxHost.EnumUnknown(null);
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) {
return NativeMethods.E_NOTIMPL;
}
//
// IOleInPlaceFrame methods:
//
IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() {
return parent.Handle;
}
int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) {
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) {
if (pActiveObject == null) {
if (ctlInEditMode != null) {
ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None);
ctlInEditMode = null;
}
return NativeMethods.S_OK;
}
WebBrowserBase ctl = null;
UnsafeNativeMethods.IOleObject oleObject = pActiveObject as UnsafeNativeMethods.IOleObject;
if (oleObject != null) {
UnsafeNativeMethods.IOleClientSite clientSite = null;
try {
clientSite = oleObject.GetClientSite();
WebBrowserSiteBase webBrowserSiteBase = clientSite as WebBrowserSiteBase;
if (webBrowserSiteBase != null)
{
ctl = webBrowserSiteBase.GetAXHost();
}
}
catch (COMException t) {
Debug.Fail(t.ToString());
}
if (ctlInEditMode != null) {
Debug.Fail("control " + ctlInEditMode.ToString() + " did not reset its edit mode to null");
ctlInEditMode.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected);
ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None);
}
if (ctl == null) {
ctlInEditMode = null;
}
else {
if (!ctl.IsUserMode) {
ctlInEditMode = ctl;
ctl.SetEditMode(WebBrowserHelper.AXEditMode.Object);
ctl.AddSelectionHandler();
ctl.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Active);
}
}
}
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) {
return NativeMethods.S_OK;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) {
return NativeMethods.E_NOTIMPL;
}
int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) {
return NativeMethods.S_FALSE;
}
//
// Private helper methods:
//
private void ListAXControls(ArrayList list, bool fuseOcx) {
Hashtable components = GetComponents();
if (components == null)
{
return;
}
Control[] ctls = new Control[components.Keys.Count];
components.Keys.CopyTo(ctls, 0);
if (ctls != null) {
for (int i = 0; i < ctls.Length; i++) {
Control ctl = ctls[i];
WebBrowserBase webBrowserBase = ctl as WebBrowserBase;
if (webBrowserBase != null) {
if (fuseOcx) {
object ax = webBrowserBase.activeXInstance;
if (ax != null) {
list.Add(ax);
}
}
else {
list.Add(ctl);
}
}
}
}
}
private Hashtable GetComponents() {
return GetComponents(GetParentsContainer());
}
private IContainer GetParentsContainer() {
//
IContainer rval = GetParentIContainer();
Debug.Assert(rval == null || assocContainer == null || rval == assocContainer,
"mismatch between getIPD & aContainer");
return rval == null ? assocContainer : rval;
}
private IContainer GetParentIContainer() {
ISite site = parent.Site;
if (site != null && site.DesignMode) return site.Container;
return null;
}
private Hashtable GetComponents(IContainer cont) {
FillComponentsTable(cont);
return components;
}
private void FillComponentsTable(IContainer container) {
if (container != null) {
ComponentCollection comps = container.Components;
if (comps != null) {
components = new Hashtable();
foreach (IComponent comp in comps) {
if (comp is Control && comp != parent && comp.Site != null) {
components.Add(comp, comp);
}
}
return;
}
}
Debug.Assert(parent.Site == null, "Parent is sited but we could not find IContainer!!!");
bool checkHashTable = true;
Control[] ctls = new Control[containerCache.Values.Count];
containerCache.Values.CopyTo(ctls, 0);
if (ctls != null) {
if (ctls.Length > 0 && components == null) {
components = new Hashtable();
checkHashTable = false;
}
for (int i = 0; i < ctls.Length; i ++) {
if (checkHashTable && !components.Contains(ctls[i])) {
components.Add(ctls[i], ctls[i]);
}
}
}
GetAllChildren(this.parent);
}
private void GetAllChildren(Control ctl) {
if (ctl == null)
return;
if (components == null) {
components = new Hashtable();
}
if (ctl != this.parent && !components.Contains(ctl))
components.Add(ctl, ctl);
foreach(Control c in ctl.Controls) {
GetAllChildren(c);
}
}
private bool RegisterControl(WebBrowserBase ctl) {
ISite site = ctl.Site;
if (site != null) {
IContainer cont = site.Container;
if (cont != null) {
if (assocContainer != null) {
return cont == assocContainer;
}
else {
assocContainer = cont;
IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (ccs != null) {
ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved);
}
return true;
}
}
}
return false;
}
private void OnComponentRemoved(object sender, ComponentEventArgs e) {
Control c = e.Component as Control;
if (sender == assocContainer && c != null) {
RemoveControl(c);
}
}
//
// Internal helper methods:
//
internal void AddControl(Control ctl) {
if (containerCache.Contains(ctl))
throw new ArgumentException(string.Format(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl");
containerCache.Add(ctl, ctl);
if (assocContainer == null) {
ISite site = ctl.Site;
if (site != null) {
assocContainer = site.Container;
IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (ccs != null) {
ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved);
}
}
}
}
internal void RemoveControl(Control ctl) {
//ctl may not be in containerCache: Remove is a no-op if it's not there.
containerCache.Remove(ctl);
}
internal static WebBrowserContainer FindContainerForControl(WebBrowserBase ctl) {
if (ctl != null) {
if (ctl.container != null)
{
return ctl.container;
}
ScrollableControl f = ctl.ContainingControl;
if (f != null) {
WebBrowserContainer container = ctl.CreateWebBrowserContainer();
if (container.RegisterControl(ctl)) {
container.AddControl(ctl);
return container;
}
}
}
return null;
}
internal string GetNameForControl(Control ctl) {
string name = (ctl.Site != null) ? ctl.Site.Name : ctl.Name;
return name ?? "";
}
internal void OnUIActivate(WebBrowserBase site) {
// The ShDocVw control repeatedly calls OnUIActivate() with the same
// site. This causes the assert below to fire.
//
if (siteUIActive == site)
return;
if (siteUIActive != null && siteUIActive != site) {
WebBrowserBase tempSite = siteUIActive;
tempSite.AXInPlaceObject.UIDeactivate();
}
site.AddSelectionHandler();
Debug.Assert(siteUIActive == null, "Object did not call OnUIDeactivate");
siteUIActive = site;
ContainerControl f = site.ContainingControl;
if (f != null && f.Contains(site)) {
f.SetActiveControlInternal(site);
}
}
internal void OnUIDeactivate(WebBrowserBase site) {
#if DEBUG
if (siteUIActive != null) {
Debug.Assert(siteUIActive == site, "deactivating when not active...");
}
#endif // DEBUG
siteUIActive = null;
site.RemoveSelectionHandler();
site.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected);
site.SetEditMode(WebBrowserHelper.AXEditMode.None);
}
internal void OnInPlaceDeactivate(WebBrowserBase site) {
if (siteActive == site) {
siteActive = null;
ContainerControl parentContainer = parent.FindContainerControlInternal();
if (parentContainer != null) {
parentContainer.SetActiveControlInternal(null);
}
}
}
internal void OnExitEditMode(WebBrowserBase ctl) {
Debug.Assert(ctlInEditMode == null || ctlInEditMode == ctl, "who is exiting edit mode?");
if (ctlInEditMode == ctl) {
ctlInEditMode = null;
}
}
}
}
| 37.954082 | 144 | 0.533271 | [
"MIT"
] | OliaG/winforms | src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs | 14,878 | C# |
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.OS;
namespace XFAgeAnalysis.Droid
{
[Activity(Label = "XFAgeAnalysis", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
Window.SetStatusBarColor(Android.Graphics.Color.ParseColor("#CC0000"));
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Xamarin.Forms.FormsMaterial.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | 41.117647 | 188 | 0.711731 | [
"MIT"
] | tsjdev-apps/xf-cognitiveservices-ageanalysis | XFAgeAnalysis/XFAgeAnalysis/XFAgeAnalysis.Android/MainActivity.cs | 1,400 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
namespace Microsoft.AspNet.Builder.Internal
{
public class ApplicationBuilder : IApplicationBuilder
{
private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();
public ApplicationBuilder(IServiceProvider serviceProvider)
{
Properties = new Dictionary<string, object>();
ApplicationServices = serviceProvider;
}
public ApplicationBuilder(IServiceProvider serviceProvider, object server)
: this(serviceProvider)
{
SetProperty(Constants.BuilderProperties.ServerFeatures, server);
}
private ApplicationBuilder(ApplicationBuilder builder)
{
Properties = builder.Properties;
}
public IServiceProvider ApplicationServices
{
get
{
return GetProperty<IServiceProvider>(Constants.BuilderProperties.ApplicationServices);
}
set
{
SetProperty<IServiceProvider>(Constants.BuilderProperties.ApplicationServices, value);
}
}
public IFeatureCollection ServerFeatures
{
get
{
return GetProperty<IFeatureCollection>(Constants.BuilderProperties.ServerFeatures);
}
}
public IDictionary<string, object> Properties { get; }
private T GetProperty<T>(string key)
{
object value;
return Properties.TryGetValue(key, out value) ? (T)value : default(T);
}
private void SetProperty<T>(string key, T value)
{
Properties[key] = value;
}
public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
{
_components.Add(middleware);
return this;
}
public IApplicationBuilder New()
{
return new ApplicationBuilder(this);
}
public RequestDelegate Build()
{
RequestDelegate app = context =>
{
context.Response.StatusCode = 404;
return Task.FromResult(0);
};
foreach (var component in _components.Reverse())
{
app = component(app);
}
return app;
}
}
}
| 28.905263 | 136 | 0.599053 | [
"Apache-2.0"
] | sebnema/HttpAbstractions-1.0.0-rc1-NoAuthHandler | src/Microsoft.AspNet.Http/ApplicationBuilder.cs | 2,746 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Typewriter.Test
{
// supported test languages
public enum TestLanguage
{
CSharp,
Java,
TypeScript,
PHP,
ObjC
}
public static class MultipleNamespacesTestRunner
{
private const string OutputDirectoryPrefix = "OutputDirectory";
private const string TestDataDirectoryPrefix = "TestData";
private const string MetadataDirectoryName = "Metadata";
// contains microsoft.graph and microsoft.graph2.callRecords namespaces
private const string MetadataMultipleNamespacesFile = "MetadataMultipleNamespaces.xml";
// contains microsoft.graph and microsoft.graph.callRecords
// TypeScript, ObjC and PHP rely on the assumption that all namespaces will be a subnamespace to microsoft.graph
// and generation process creates a single file with nested namespaces
private const string MetadataWithSubNamespacesFile = "MetadataWithSubNamespaces.xml";
public static void Run(TestLanguage language, bool isBeta = false)
{
string getMetadataFile(TestLanguage testLanguage)
{
switch (testLanguage)
{
case TestLanguage.CSharp:
case TestLanguage.Java:
return MetadataMultipleNamespacesFile;
case TestLanguage.TypeScript:
case TestLanguage.PHP:
case TestLanguage.ObjC:
return MetadataWithSubNamespacesFile;
default:
throw new ArgumentException("unexpected test language", nameof(testLanguage));
}
}
// Arrange
var languageStr = language.ToString();
var directoryPostfix = languageStr + (isBeta ? "Beta" : string.Empty);
var outputDirectoryName = OutputDirectoryPrefix + directoryPostfix;
var testDataDirectoryName = TestDataDirectoryPrefix + directoryPostfix;
var currentDirectory = Path.GetDirectoryName(typeof(MultipleNamespacesTestRunner).Assembly.Location); //Directory.GetCurrentDirectory();
var outputDirectory = Path.Combine(currentDirectory, outputDirectoryName);
var dataDirectory = Path.Combine(currentDirectory, testDataDirectoryName);
var metadataFile = Path.Combine(currentDirectory, MetadataDirectoryName, getMetadataFile(language));
var csdlContents = MetadataResolver.GetMetadata(metadataFile);
var options = new Options
{
Verbosity = VerbosityLevel.Info,
Output = outputDirectory,
GenerationMode = GenerationMode.Files,
Language = languageStr
};
options.EndpointVersion = isBeta ? "beta" : "v1.0"; // fixes java generation test as the endpoint contains the version and the default options are not applied in this testing mode
if (isBeta)
{
if (TestLanguage.PHP == language)
{
options.Properties = new List<string> { "php.namespacePrefix:Beta" };
}
if (TestLanguage.TypeScript == language)
{
options.Properties = new List<string> { "typescript.namespacePostfix:beta" };
}
}
// Act
if (Directory.Exists(outputDirectory))
{
Directory.Delete(outputDirectory, recursive: true); // clean up any previous runs
}
Generator.GenerateFiles(csdlContents, options);
var outputDirectoryInfo = new DirectoryInfo(outputDirectory);
var dataDirectoryInfo = new DirectoryInfo(dataDirectory);
Assert.AreEqual(dataDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories).Length,
outputDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories).Length,
$@"Number of generated files don't match with number of expected files! Compare these two folders:
{dataDirectory}
{outputDirectory}");
// Assert
var testOutputBuilder = new StringBuilder();
var errorCounter = 0;
foreach (var (expectedFilePath, actualOutputFilePath) in GetFilePaths(language, dataDirectory, testDataDirectoryName, outputDirectoryName))
{
if (File.Exists(actualOutputFilePath))
{
CompareFiles(testOutputBuilder, expectedFilePath, actualOutputFilePath, ref errorCounter);
}
else
{
testOutputBuilder.AppendLine();
testOutputBuilder.AppendLine($"{++errorCounter}. Output file is not generated: {actualOutputFilePath}");
}
}
if (errorCounter > 0)
{
string message = string.Join(Environment.NewLine,
"A diff between following folders are strongly encouraged to see if the changes are intended:",
dataDirectory,
outputDirectory,
string.Empty,
$"If the changes are expected, please replace the contents of {testDataDirectoryName} with the contents of {outputDirectoryName}.",
string.Empty,
"Details of failures:");
Assert.Fail(message + testOutputBuilder.ToString());
}
}
/// <summary>
/// Compares the contents of expected file to actual output from Typewriter.
/// </summary>
/// <param name="testOutputBuilder">String builder to append into the test output</param>
/// <param name="expectedFilePath">Path to the expected file</param>
/// <param name="actualOutputFilePath">Path to the actual output file from Typewriter</param>
/// <param name="errorCounter">Error counter for the test run</param>
private static void CompareFiles(StringBuilder testOutputBuilder, string expectedFilePath, string actualOutputFilePath, ref int errorCounter)
{
var expectedFileContents = File.ReadAllText(expectedFilePath).Replace("\r", "");
var actualFileContents = File.ReadAllText(actualOutputFilePath).Replace("\r", "");
if (expectedFileContents != actualFileContents)
{
testOutputBuilder.AppendLine();
testOutputBuilder.AppendLine($"{++errorCounter}. File contents do not match.");
testOutputBuilder.AppendLine($"\tExpected file: {expectedFilePath}");
testOutputBuilder.AppendLine($"\tActual file: {actualOutputFilePath}");
}
}
/// <summary>
/// Takes a data directory, traverses the entire subdirectory structure,
/// extracts full file paths as expected file paths,
/// converts expected file paths into actual output file paths as well for a later diff.
/// </summary>
/// <param name="dataDirectory">Data directory full path</param>
/// <param name="testDataDirectoryName">test data directory name, e.g. TestDataCSharp</param>
/// <param name="outputDirectoryName">output directory name, e.g. OutputDirectoryCSharp</param>
/// <returns></returns>
private static IEnumerable<(string, string)> GetFilePaths(TestLanguage language, string dataDirectory, string testDataDirectoryName, string outputDirectoryName)
{
HashSet<string> extensions = new HashSet<string>();
switch (language)
{
case TestLanguage.CSharp:
extensions.Add(".cs");
break;
case TestLanguage.Java:
extensions.Add(".java");
break;
case TestLanguage.TypeScript:
extensions.Add(".ts");
break;
case TestLanguage.PHP:
extensions.Add(".php");
break;
case TestLanguage.ObjC:
extensions.Add(".m");
extensions.Add(".h");
break;
default:
throw new ArgumentException("unexpected test language", nameof(language));
}
return from file in new DirectoryInfo(dataDirectory)
.EnumerateFiles("*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(f.Extension))
let actualOutputFilePath = file.FullName.Replace(testDataDirectoryName, outputDirectoryName)
let expectedFilePath = file.FullName
select (expectedFilePath, actualOutputFilePath);
}
}
}
| 45.730964 | 191 | 0.598513 | [
"MIT"
] | Dakoni4400/MSGraph-SDK-Code-Generator | test/Typewriter.Test/MultipleNamespacesTestRunner.cs | 9,011 | C# |
using InfraApp.Models;
using InfraApp.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
namespace InfraApp.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{
public IDataStore<Item> DataStore => DependencyService.Get<IDataStore<Item>>();
bool isBusy = false;
public bool IsBusy
{
get { return isBusy; }
set { SetProperty(ref isBusy, value); }
}
string title = string.Empty;
public string Title
{
get { return title; }
set { SetProperty(ref title, value); }
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
| 28.090909 | 87 | 0.602589 | [
"MIT"
] | MilenkoMarkovic/SimpleUWP | InfraApp/ViewModels/BaseViewModel.cs | 1,547 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TechnicalRadiation.WebApi.Migrations
{
public partial class newsItems : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 19.166667 | 71 | 0.678261 | [
"MIT"
] | eggertmar1/Large_assignment1 | TechnicalRadiation.WebApi/Migrations/20210919224657_newsItems.cs | 347 | C# |
// ReSharper disable IdentifierTypo
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedMember.Global
namespace Jinkong.TencentFaceId
{
public class DetectInfo
{
/// <summary>
/// 原始内容
/// </summary>
public string DetectInfoContent { get; set; }
public _Text Text { get; set; }
public _IdCardData IdCardData { get; set; }
public _BestFrame BestFrame { get; set; }
public _VideoData VideoData { get; set; }
public class _Text
{
public string ErrCode { get; set; }
public string ErrMsg { get; set; }
public string IdCard { get; set; }
public string Name { get; set; }
public string OcrNation { get; set; }
public string OcrAddress { get; set; }
public string OcrBirth { get; set; }
public string OcrAuthority { get; set; }
public string OcrValidDate { get; set; }
public string OcrName { get; set; }
public string OcrIdCard { get; set; }
public string OcrGender { get; set; }
public string LiveStatus { get; set; }
public string LiveMsg { get; set; }
public string Comparestatus { get; set; }
public string Comparemsg { get; set; }
public string Extra { get; set; }
public object Detail { get; set; }
}
public class _IdCardData
{
public string OcrFront { get; set; }
public string OcrBack { get; set; }
}
public class _BestFrame
{
public string BestFrame { get; set; }
}
public class _VideoData
{
public string LivenessVideo { get; set; }
}
}
} | 30.639344 | 54 | 0.555377 | [
"MIT"
] | cqjinkong/component | src/Jinkong.TencentFaceId/DetectInfo.cs | 1,879 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Domain.Entities.WebThingsGateway.Things;
using Domain.Exceptions;
using Domain.Updaters;
namespace Domain.Entities.WebThingsGateway.Properties
{
public record EnumProperty : StringProperty
{
public EnumProperty(
string name,
bool visible,
string title,
string propertyType,
IReadOnlyCollection<Link> links,
bool readOnly,
IPropertyValueUpdater propertyValueUpdater,
string defaultValue,
IReadOnlyCollection<string> allowedValues,
Thing thing)
: base(name, visible, title, propertyType, links, readOnly, propertyValueUpdater, defaultValue, thing)
{
AllowedValues = allowedValues;
}
public override GatewayValueType ValueType => GatewayValueType.Enum;
public IReadOnlyCollection<string> AllowedValues { get; }
public override bool IsValidValue(string? value)
{
return AllowedValues.Contains(value);
}
public override async Task UpdateValueAsync(string? value)
{
if (!IsValidValue(value))
{
throw new ValidationException($"Value \"{value}\" is not allowed for the property. Allowed values are: [${string.Join(", ", AllowedValues)}]");
}
await PropertyValueUpdater.UpdateAsync(this, value);
}
}
} | 33.06383 | 160 | 0.614543 | [
"MIT"
] | ArtemK123/PolytechWebThings | src/Domain/Entities/WebThingsGateway/Properties/EnumProperty.cs | 1,556 | C# |
#region Copyright notice and license
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Reflection;
using Grpc.Core;
using Grpc.Core.Logging;
using NUnit.Common;
using NUnitLite;
namespace Grpc.Reflection.Tests
{
/// <summary>
/// Provides entry point for NUnitLite
/// </summary>
public class NUnitMain
{
public static int Main(string[] args)
{
// Make logger immune to NUnit capturing stdout and stderr to workaround https://github.com/nunit/nunit/issues/1406.
GrpcEnvironment.SetLogger(new ConsoleLogger());
#if NETCOREAPP1_0
return new AutoRun(typeof(NUnitMain).GetTypeInfo().Assembly).Execute(args, new ExtendedTextWrapper(Console.Out), Console.In);
#else
return new AutoRun().Execute(args);
#endif
}
}
}
| 30.822222 | 137 | 0.708003 | [
"Apache-2.0"
] | 0mok/grpc | src/csharp/Grpc.Reflection.Tests/NUnitMain.cs | 1,387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class TestLayer : CCNode
{
public TestLayer()
{}
public override void OnEnter()
{
base.OnEnter();
var label = new CCLabel("CocosSharp", "arial", 64, CCLabelFormat.SpriteFont);
label.Position = VisibleBoundsWorldspace.Center;
AddChild(label);
}
}
}
| 18.076923 | 89 | 0.614894 | [
"MIT"
] | YersonSolano/CocosSharp | tests/tests/classes/tests/RotateWorldTest/TestLayer.cs | 470 | 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("Todo.WebAPI")]
[assembly: AssemblyDescription("Web API server for the Todo sample")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Todo.WebAPI")]
[assembly: AssemblyCopyright("Copyright IdeaBlade © 2014")]
[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("a604d4b1-0ef9-4f1f-ba2b-2844ce629ad8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.861111 | 84 | 0.749821 | [
"MIT"
] | 100goals/ng-demos-master | todo-zumo/todo.WebAPI/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using Android.Util;
namespace OmniGui.Android
{
public static class Assemblies
{
public static IEnumerable<Assembly> ReferencedAssemblies => Assembly.GetCallingAssembly().GetReferencedAssemblies().Select(Assembly.Load);
public static IEnumerable<Assembly> AppDomainAssemblies => AppDomain.CurrentDomain.GetAssemblies();
public static IEnumerable<Assembly> AssembliesInAppFolder
{
get
{
Log.WriteLine(LogPriority.Error, "SuperJMN", "entrando!");
var entryAssembly = Assembly.GetExecutingAssembly();
var path = entryAssembly.Location;
Log.WriteLine(LogPriority.Debug, "SuperJMN", "path=" + entryAssembly.Location);
var folder = Path.GetDirectoryName(path);
var assemblies = new Collection<Assembly>();
var fileNames = FilterFiles(folder, ".dll", ".exe");
foreach (var fileName in fileNames)
{
try
{
assemblies.Add(Assembly.LoadFile(fileName));
}
catch (FileNotFoundException)
{
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
}
return assemblies;
}
}
public static IEnumerable<string> FilterFiles(string path, params string[] extensionsWithNoWildcard)
{
Log.WriteLine(LogPriority.Debug, "SuperJMN", "FilterFiles.Path=" + path);
var enumerateFiles = Directory.EnumerateFiles(path, "*.*");
Log.WriteLine(LogPriority.Debug, "SuperJMN", "Archiovs enumerados: " + string.Concat(",", enumerateFiles));
return
enumerateFiles
.Where(file => extensionsWithNoWildcard.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}
}
} | 36.403226 | 146 | 0.555605 | [
"MIT"
] | OmniGUI/OmniGUI | OmniGui.Android/Assemblies.cs | 2,257 | C# |
// <auto-generated />
namespace ULFGService.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class bytes : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(bytes));
string IMigrationMetadata.Id
{
get { return "201804171725276_bytes"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.6 | 88 | 0.611529 | [
"MIT"
] | DanielAlba96/ULFG | ULFGService/Migrations/201804171725276_bytes.Designer.cs | 798 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client202010.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class ODataValueOfIEnumerableOfTaskActivityDto
{
/// <summary>
/// Initializes a new instance of the
/// ODataValueOfIEnumerableOfTaskActivityDto class.
/// </summary>
public ODataValueOfIEnumerableOfTaskActivityDto()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// ODataValueOfIEnumerableOfTaskActivityDto class.
/// </summary>
public ODataValueOfIEnumerableOfTaskActivityDto(IList<TaskActivityDto> value = default(IList<TaskActivityDto>))
{
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<TaskActivityDto> Value { get; set; }
}
}
| 28.851064 | 119 | 0.626844 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated202010/Models/ODataValueOfIEnumerableOfTaskActivityDto.cs | 1,356 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using AnimalCentre.Models.Contracts;
namespace AnimalCentre.Models.Procedures
{
public class DentalCare : Procedure
{
public override void DoService(IAnimal animal, int procedureTime)
{
base.DoService(animal, procedureTime);
animal.Happiness += 12;
animal.Energy += 10;
}
}
}
| 22.947368 | 74 | 0.626147 | [
"MIT"
] | Gandjurov/OOP-Basic-CSharp | 11.ExamPrepOOP-TechModule4.0/AnimalCentre/AnimalCentre/Models/Procedures/DentalCare.cs | 438 | C# |
using System;
class Recursion
{
static void Main()
{
long number = long.Parse(Console.ReadLine());
int p = int.Parse(Console.ReadLine());
int q = int.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
for (int i = 0; i < k; i++)
{
long mask = 1 << p + i;
long nAndMask = number & mask;
long bit = nAndMask >> p + i;
long mask1 = 1 << q + i;
long nAndMask1 = number & mask1;
long bit1 = nAndMask1 >> q + i;
if (bit != bit1)
{
if (bit == 0)
{
// set small bit
long mask2 = 1 << p + i;
number = number | mask2;
// set big bit
long mask4 = ~(1 << q + i );
number = number & mask4;
}
if (bit == 1)
{
// set small bit
long mask3 = ~(1 << p + i);
number = number & mask3;
// set big bit
long mask5 = 1 << q + i ;
number = number | mask5;
}
}
}
Console.WriteLine(number);
}
}
| 26.22 | 53 | 0.357742 | [
"MIT"
] | iliyaST/TelericAcademy | C#2/1-Arrays/RecursionDemo/Program.cs | 1,313 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
using Microsoft.TemplateEngine.Edge.Settings;
using Microsoft.TemplateEngine.Cli.TemplateResolution;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Cli.CommandParsing;
using Microsoft.TemplateEngine.Cli.UnitTests.CliMocks;
using System.Linq;
using Microsoft.TemplateEngine.Orchestrator.RunnableProjects;
using Microsoft.TemplateEngine.Cli.HelpAndUsage;
using Microsoft.TemplateEngine.Mocks;
namespace Microsoft.TemplateEngine.Cli.UnitTests.TemplateResolutionTests
{
public class HelpTemplateListResolverTests
{
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UniqueNameMatchesCorrectly))]
public void TestGetTemplateResolutionResult_UniqueNameMatchesCorrectly()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console1", name: "Long name for Console App", identity: "Console.App"));
templatesToSearch.Add(new MockTemplateInfo("console2", name: "Long name for Console App #2", identity: "Console.App2"));
INewCommandInput userInputs = new MockNewCommandInput("console2").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal("console2", matchResult.UnambiguousTemplateGroup.Single().Info.ShortName);
Assert.Equal("Console.App2", matchResult.UnambiguousTemplateGroup.Single().Info.Identity);
Assert.Equal(1, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_ExactMatchOnShortNameMatchesCorrectly))]
public void TestGetTemplateResolutionResult_ExactMatchOnShortNameMatchesCorrectly()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App"));
templatesToSearch.Add(new MockTemplateInfo("console2", name: "Long name for Console App #2", identity: "Console.App2"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal("console", matchResult.UnambiguousTemplateGroup.Single().Info.ShortName);
Assert.Equal("Console.App", matchResult.UnambiguousTemplateGroup.Single().Info.Identity);
Assert.Equal(1, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UnambiguousGroupIsFound))]
public void TestGetTemplateResolutionResult_UnambiguousGroupIsFound()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L3", groupIdentity: "Console.App.Test").WithTag("language", "L3"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(1, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(3, matchResult.ExactMatchedTemplates.Count);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(3, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MultipleGroupsAreFound))]
public void TestGetTemplateResolutionResult_MultipleGroupsAreFound()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L3", groupIdentity: "Console.App.Test").WithTag("language", "L3"));
templatesToSearch.Add(new MockTemplateInfo("classlib", name: "Long name for Class Library App", identity: "Class.Library.L1", groupIdentity: "Class.Library.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("classlib", name: "Long name for Class Library App", identity: "Class.Library.L2", groupIdentity: "Class.Library.Test").WithTag("language", "L2"));
INewCommandInput userInputs = new MockNewCommandInput("c").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(2, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(5, matchResult.ExactMatchedTemplates.Count);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_DefaultLanguageDisambiguates))]
public void TestGetTemplateResolutionResult_DefaultLanguageDisambiguates()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, "L1");
Assert.True(matchResult.HasExactMatches);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.True(matchResult.HasUnambiguousTemplateGroupForDefaultLanguage);
Assert.Equal("console", matchResult.UnambiguousTemplatesForDefaultLanguage.Single().Info.ShortName);
Assert.Equal("Console.App.L1", matchResult.UnambiguousTemplatesForDefaultLanguage.Single().Info.Identity);
Assert.Equal("L1", matchResult.UnambiguousTemplatesForDefaultLanguage.Single().Info.Tags["language"].Choices.Keys.FirstOrDefault());
Assert.Equal(2, matchResult.UnambiguousTemplateGroup.Count);
Assert.Equal(1, matchResult.UnambiguousTemplatesForDefaultLanguage.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_InputLanguageIsPreferredOverDefault))]
public void TestGetTemplateResolutionResult_InputLanguageIsPreferredOverDefault()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));
INewCommandInput userInputs = new MockNewCommandInput("console", "L2").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, "L1");
Assert.True(matchResult.HasExactMatches);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal("console", matchResult.UnambiguousTemplateGroup.Single().Info.ShortName);
Assert.Equal("Console.App.L2", matchResult.UnambiguousTemplateGroup.Single().Info.Identity);
Assert.Equal("L2", matchResult.UnambiguousTemplateGroup.Single().Info.Tags["language"].Choices.Keys.FirstOrDefault());
Assert.Equal(1, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UnambiguousGroup_TemplatesAreNotSameLanguage))]
public void TestGetTemplateResolutionResult_UnambiguousGroup_TemplatesAreNotSameLanguage()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L3", groupIdentity: "Console.App.Test").WithTag("language", "L3"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(1, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(3, matchResult.ExactMatchedTemplates.Count);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(3, matchResult.UnambiguousTemplateGroup.Count);
Assert.False(matchResult.AllTemplatesInUnambiguousTemplateGroupAreSameLanguage);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_UnambiguousGroup_TemplatesAreSameLanguage))]
public void TestGetTemplateResolutionResult_UnambiguousGroup_TemplatesAreSameLanguage()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T3", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(1, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(3, matchResult.ExactMatchedTemplates.Count);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(3, matchResult.UnambiguousTemplateGroup.Count);
Assert.True(matchResult.AllTemplatesInUnambiguousTemplateGroupAreSameLanguage);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasLanguageMismatch))]
public void TestGetTemplateResolutionResult_PartialMatch_HasLanguageMismatch()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("console", "L2").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.True(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasContextMismatch))]
public void TestGetTemplateResolutionResult_PartialMatch_HasContextMismatch()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("console", type: "item").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.True (matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasBaselineMismatch))]
public void TestGetTemplateResolutionResult_PartialMatch_HasBaselineMismatch()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("console").WithHelpOption().WithCommandOption("--baseline", "core");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.True(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatch_HasMultipleMismatches))]
public void TestGetTemplateResolutionResult_PartialMatch_HasMultipleMismatches()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("console", "L2", "item").WithHelpOption().WithCommandOption("--baseline", "core");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.True(matchResult.HasLanguageMismatch);
Assert.True(matchResult.HasContextMismatch);
Assert.True(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_PartialMatchGroup_HasTypeMismatch_HasGroupLanguageMatch))]
public void TestGetTemplateResolutionResult_PartialMatchGroup_HasTypeMismatch_HasGroupLanguageMatch()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test")
.WithTag("language", "L2")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("console", "L2", "item").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(2, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(1, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.True(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_NoMatch))]
public void TestGetTemplateResolutionResult_NoMatch()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("zzzzz", "L1", "item").WithHelpOption().WithCommandOption("--baseline", "app");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.False(matchResult.HasPartialMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.Equal(0, matchResult.PartiallyMatchedTemplates.Count);
Assert.Equal(0, matchResult.PartiallyMatchedTemplateGroups.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(0, matchResult.UnambiguousTemplateGroup.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_OtherParameterMatch_Text))]
public void TestGetTemplateResolutionResult_OtherParameterMatch_Text()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test1")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithParameters("langVersion")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test2")
.WithTag("language", "L2")
.WithTag("type", "project")
.WithParameters("test")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T3", groupIdentity: "Console.App.Test3")
.WithTag("language", "L3")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("c").WithHelpOption().WithTemplateOption("langVersion");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(1, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(1, matchResult.ExactMatchedTemplates.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.True(matchResult.HasUnambiguousTemplateGroup);
Assert.Equal(1, matchResult.UnambiguousTemplateGroup.Count);
HelpForTemplateResolution.GetParametersInvalidForTemplatesInList(matchResult.ExactMatchedTemplates, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates);
Assert.Equal(0, invalidForSomeTemplates.Count);
Assert.Equal(0, invalidForAllTemplates.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_OtherParameterMatch_Choice))]
public void TestGetTemplateResolutionResult_OtherParameterMatch_Choice()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test1")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithTag("framework", "netcoreapp1.0", "netcoreapp1.1")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test2")
.WithTag("language", "L2")
.WithTag("type", "project")
.WithParameters("test")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T3", groupIdentity: "Console.App.Test3")
.WithTag("language", "L3")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("c").WithHelpOption().WithTemplateOption("framework");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(3, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(3, matchResult.ExactMatchedTemplates.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
HelpForTemplateResolution.GetParametersInvalidForTemplatesInList(matchResult.ExactMatchedTemplates, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates);
Assert.Equal(1, invalidForSomeTemplates.Count);
Assert.Equal(0, invalidForAllTemplates.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_OtherParameterDoesNotExist))]
public void TestGetTemplateResolutionResult_OtherParameterDoesNotExist()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test1")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithTag("framework", "netcoreapp1.0", "netcoreapp1.1")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test2")
.WithTag("language", "L2")
.WithTag("type", "project")
.WithParameters("test")
.WithBaselineInfo("app", "standard"));
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T3", groupIdentity: "Console.App.Test3")
.WithTag("language", "L3")
.WithTag("type", "project")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("c").WithHelpOption().WithTemplateOption("do-not-exist");
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.True(matchResult.HasExactMatches);
Assert.Equal(3, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(3, matchResult.ExactMatchedTemplates.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
Assert.False(matchResult.HasUnambiguousTemplateGroup);
HelpForTemplateResolution.GetParametersInvalidForTemplatesInList(matchResult.ExactMatchedTemplates, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates);
Assert.Equal(0, invalidForSomeTemplates.Count);
Assert.Equal(1, invalidForAllTemplates.Count);
}
[Fact(DisplayName = nameof(TestGetTemplateResolutionResult_MatchByTagsIgnoredForHelp))]
public void TestGetTemplateResolutionResult_MatchByTagsIgnoredForHelp()
{
List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>();
templatesToSearch.Add(
new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test1")
.WithTag("language", "L1")
.WithTag("type", "project")
.WithClassifications("Common", "Test")
.WithBaselineInfo("app", "standard"));
INewCommandInput userInputs = new MockNewCommandInput("Common").WithHelpOption();
TemplateListResolutionResult matchResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null);
Assert.False(matchResult.HasExactMatches);
Assert.False(matchResult.HasPartialMatches);
Assert.Equal(0, matchResult.ExactMatchedTemplateGroups.Count);
Assert.Equal(0, matchResult.ExactMatchedTemplates.Count);
Assert.False(matchResult.HasLanguageMismatch);
Assert.False(matchResult.HasContextMismatch);
Assert.False(matchResult.HasBaselineMismatch);
}
}
}
| 66.859244 | 213 | 0.697942 | [
"MIT"
] | ajeckmans/templating | test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/HelpTemplateListResolverTests.cs | 31,825 | C# |
using System.Collections.Generic;
using TypingRealm.Messaging;
using TypingRealm.Messaging.Updating;
namespace TypingRealm.Combat
{
[Message]
public sealed class Update
{
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public List<Player> Players { get; set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
}
public sealed class UpdateFactory : IUpdateFactory
{
private readonly ICombatRoomStore _combatRooms;
public UpdateFactory(ICombatRoomStore combatRooms)
{
_combatRooms = combatRooms;
}
public object GetUpdateFor(string clientId)
{
return new Update
{
Players = _combatRooms.FindInBattle(clientId).Players
};
}
}
}
| 26.352941 | 102 | 0.664063 | [
"MIT"
] | ewancoder/typingrealm | TypingRealm.Combat/UpdateFactory.cs | 898 | C# |
using System;
using System.Collections.Generic;
using Cosmos.Common;
using Cosmos.Core;
using Cosmos.Core.IOGroup.Network;
using Cosmos.HAL.Network;
namespace Cosmos.HAL.Drivers.PCI.Network
{
public class AMDPCNetII : NetworkDevice
{
protected PCIDevice pciCard;
protected AMDPCNetIIIOGroup io;
protected MACAddress mac;
protected bool mInitDone;
protected ManagedMemoryBlock mInitBlock;
protected ManagedMemoryBlock mRxDescriptor;
protected ManagedMemoryBlock mTxDescriptor;
protected List<ManagedMemoryBlock> mRxBuffers;
protected List<ManagedMemoryBlock> mTxBuffers;
protected Queue<byte[]> mRecvBuffer;
protected Queue<byte[]> mTransmitBuffer;
private int mNextTXDesc;
public AMDPCNetII(PCIDevice device)
: base()
{
if (device == null)
{
throw new ArgumentException("PCI Device is null. Unable to get AMD PCNet card");
}
this.pciCard = device;
this.pciCard.Claimed = true;
this.pciCard.EnableDevice();
this.io = new AMDPCNetIIIOGroup((ushort)this.pciCard.BaseAddressBar[0].BaseAddress);
this.io.RegisterData.DWord = 0;
// Get the EEPROM MAC Address and set it as the devices MAC
byte[] eeprom_mac = new byte[6];
UInt32 result = io.MAC1.DWord;
eeprom_mac[0] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[1] = BinaryHelper.GetByteFrom32bit(result, 8);
eeprom_mac[2] = BinaryHelper.GetByteFrom32bit(result, 16);
eeprom_mac[3] = BinaryHelper.GetByteFrom32bit(result, 24);
result = io.MAC2.DWord;
eeprom_mac[4] = BinaryHelper.GetByteFrom32bit(result, 0);
eeprom_mac[5] = BinaryHelper.GetByteFrom32bit(result, 8);
mac = new MACAddress(eeprom_mac);
mInitBlock = new ManagedMemoryBlock(28, 4);
mRxDescriptor = new ManagedMemoryBlock(256, 16);
mTxDescriptor = new ManagedMemoryBlock(256, 16);
mInitBlock.Write32(0x00, (0x4 << 28) | (0x4 << 20));
mInitBlock.Write32(0x04,
(UInt32)(eeprom_mac[0] | (eeprom_mac[1] << 8) | (eeprom_mac[2] << 16) | (eeprom_mac[3] << 24)));
mInitBlock.Write32(0x08, (UInt32)(eeprom_mac[4] | (eeprom_mac[5] << 8)));
mInitBlock.Write32(0x0C, 0x0);
mInitBlock.Write32(0x10, 0x0);
mInitBlock.Write32(0x14, mRxDescriptor.Offset);
mInitBlock.Write32(0x18, mTxDescriptor.Offset);
InitializationBlockAddress = mInitBlock.Offset;
SoftwareStyleRegister = 0x03;
mRxBuffers = new List<ManagedMemoryBlock>();
mTxBuffers = new List<ManagedMemoryBlock>();
for (uint rxd = 0; rxd < 16; rxd++)
{
uint xOffset = rxd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mRxDescriptor.Write32(xOffset + 8, buffer.Offset);
UInt16 buffer_len = (UInt16)(~buffer.Size);
buffer_len++;
UInt32 flags = (UInt32)(buffer_len & 0x0FFF) | 0xF000 | 0x80000000;
mRxDescriptor.Write32(xOffset + 4, flags);
mRxBuffers.Add(buffer);
}
for (uint txd = 0; txd < 16; txd++)
{
uint xOffset = txd * 16;
ManagedMemoryBlock buffer = new ManagedMemoryBlock(2048);
mTxDescriptor.Write32(xOffset + 8, buffer.Offset);
mTxBuffers.Add(buffer);
}
mNextTXDesc = 0;
// Setup our Receive and Transmit Queues
mTransmitBuffer = new Queue<byte[]>();
mRecvBuffer = new Queue<byte[]>();
INTs.SetIrqHandler(device.InterruptLine, HandleNetworkInterrupt);
}
protected void HandleNetworkInterrupt(ref INTs.IRQContext aContext)
{
UInt32 cur_status = StatusRegister;
//Console.WriteLine("AMD PCNet IRQ raised!");
if ((cur_status & 0x100) != 0)
{
mInitDone = true;
}
if ((cur_status & 0x200) != 0)
{
if (mTransmitBuffer.Count > 0)
{
byte[] data = mTransmitBuffer.Peek();
if (SendBytes(ref data) == true)
{
mTransmitBuffer.Dequeue();
}
}
}
if ((cur_status & 0x400) != 0)
{
ReadRawData();
}
StatusRegister = cur_status;
Cosmos.Core.Global.PIC.EoiSlave();
}
/// <summary>
/// Retrieve all AMD PCNetII network cards found on computer.
/// </summary>
public static void FindAll()
{
Console.WriteLine("Scanning for AMD PCNetII cards...");
PCIDevice device = Cosmos.HAL.PCI.GetDevice(VendorID.AMD, DeviceID.PCNETII);
if (device != null)
{
AMDPCNetII nic = new AMDPCNetII((PCIDevice)device);
Console.WriteLine("Found AMD PCNetII NIC on PCI " + device.bus + ":" + device.slot + ":" +
device.function);
Console.WriteLine("NIC IRQ: " + device.InterruptLine);
Console.WriteLine("NIC MAC Address: " + nic.MACAddress.ToString());
}
}
#region Register Access Properties
protected UInt32 StatusRegister
{
get
{
io.RegisterAddress.DWord = 0x00;
return io.RegisterData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x00;
io.RegisterData.DWord = value;
}
}
protected UInt32 InitializationBlockAddress
{
get
{
UInt32 result;
io.RegisterAddress.DWord = 0x01;
result = io.RegisterData.DWord;
io.RegisterAddress.DWord = 0x02;
result |= (io.RegisterData.DWord << 16);
return result;
}
set
{
io.RegisterAddress.DWord = 0x01;
io.RegisterData.DWord = (value & 0xFFFF);
io.RegisterAddress.DWord = 0x02;
io.RegisterData.DWord = (value >> 16);
}
}
protected UInt32 SoftwareStyleRegister
{
get
{
io.RegisterAddress.DWord = 0x14;
return io.BusData.DWord;
}
set
{
io.RegisterAddress.DWord = 0x14;
io.BusData.DWord = value;
}
}
#endregion
#region Network Device Implementation
public override MACAddress MACAddress
{
get { return mac; }
}
public override bool Ready
{
get { return mInitDone; }
}
public override bool Enable()
{
StatusRegister = 0x43;
return true;
}
public override bool QueueBytes(byte[] buffer, int offset, int length)
{
byte[] data = new byte[length];
for (int b = 0; b < length; b++)
{
data[b] = buffer[b + offset];
}
if (SendBytes(ref data) == false)
{
mTransmitBuffer.Enqueue(data);
}
return true;
}
public override bool ReceiveBytes(byte[] buffer, int offset, int max)
{
throw new NotImplementedException();
}
public override byte[] ReceivePacket()
{
if (mRecvBuffer.Count < 1)
{
return null;
}
byte[] data = mRecvBuffer.Dequeue();
return data;
}
public override int BytesAvailable()
{
if (mRecvBuffer.Count < 1)
{
return 0;
}
return mRecvBuffer.Peek().Length;
}
public override bool IsSendBufferFull()
{
return false;
}
public override bool IsReceiveBufferFull()
{
return false;
}
#endregion
#region Helper Functions
protected bool SendBytes(ref byte[] aData)
{
int txd = mNextTXDesc++;
if (mNextTXDesc >= 16)
{
mNextTXDesc = 0;
}
uint xOffset = (uint)(txd * 16);
UInt32 status = mTxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
for (uint b = 0; b < aData.Length; b++)
{
mTxBuffers[txd][b] = aData[b];
}
//UInt16 buffer_len = (UInt16)(aData.Length < 64 ? 64 : aData.Length);
UInt16 buffer_len = (UInt16)aData.Length;
buffer_len = (UInt16)(~buffer_len);
buffer_len++;
UInt32 flags = (UInt32)((buffer_len) & 0x0FFF) | 0x0300F000 | 0x80000000;
mTxDescriptor.Write32(xOffset + 4, flags);
return true;
}
return false;
}
private void ReadRawData()
{
uint status;
UInt16 recv_size;
byte[] recv_data;
for (int rxd = 0; rxd < 16; rxd++)
{
uint xOffset = (uint)(rxd * 16);
status = mRxDescriptor.Read32(xOffset + 4);
if ((status & 0x80000000) == 0)
{
recv_size = (UInt16)(mRxDescriptor.Read32(xOffset + 0) & 0xFFF);
recv_data = new byte[recv_size];
for (uint b = 0; b < recv_size; b++)
{
recv_data[b] = mRxBuffers[rxd][b];
}
if (DataReceived != null)
{
DataReceived(recv_data);
}
else
{
mRecvBuffer.Enqueue(recv_data);
}
mRxDescriptor.Write32(xOffset + 4, status | 0x80000000);
}
}
}
#endregion
}
}
| 30.75942 | 112 | 0.492461 | [
"BSD-3-Clause"
] | Geramy/Cosmos | source/Cosmos.HAL2/Drivers/PCI/Network/AMDPCNetII.cs | 10,612 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Drawing;
using ListenScanner;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization;
namespace ListenScanner
{
[ServiceContract]
[ServiceKnownType(typeof(Document))]
public interface IScannerService
{
[OperationContract]
Document ScanDocuments();
}
public class ScannerService : IScannerService
{
public Document ScanDocuments()
{
//List<string> devices = WIAScanner.GetDevices();
try
{
// if (devices.Count > 0)
//{
List<Image> images = WIAScanner.Scan(Main.DeviceID);
if (images.Count > 0)
return new Document() { Image = ImageToByteArray(images.FirstOrDefault()) };
//foreach (Image image in images)
//{
// image.Save(sharedFolder + name + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".jpeg", ImageFormat.Jpeg);
//}
//}
}
catch (Exception exc)
{
// MessageBox.Show(exc.Message);
}
//scan and save on shared folder
return null;
}
private byte[] ImageToByteArray(System.Drawing.Image m_imageIn)
{
MemoryStream oMemoryStream = new MemoryStream();
// ImageFormat could be other formats like bmp,gif,icon,png etc.
m_imageIn.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return oMemoryStream.ToArray();
}
private Image ByteArrayToImage(byte[] m_byteArrayIn)
{
MemoryStream oMemoryStream = new MemoryStream(m_byteArrayIn);
Image oImage = Image.FromStream(oMemoryStream);
return oImage;
}
}
public class Document
{
public byte[] Image { get; set; }
}
}
| 28.575342 | 131 | 0.558965 | [
"Apache-2.0"
] | becker-portilla/ListenScanner | ListenScanner/IScannerService.cs | 2,088 | C# |
namespace DW.ELA.UnitTests
{
using System;
using System.Collections.Generic;
using DW.ELA.Utility.Extensions;
using NUnit.Framework;
public class DictionaryExtensionsTests
{
[Test]
public void GetOrDefaultShouldReturnValue()
{
string result = GetTestDictionary().GetValueOrDefault("A");
Assert.AreEqual("1", result);
}
[Test]
public void GetOrDefaultShouldReturnNull()
{
string result = GetTestDictionary().GetValueOrDefault("D");
Assert.IsNull(result);
}
[Test]
public void AddIfNotNullShouldAdd()
{
var dictionary = GetTestDictionary();
dictionary.AddIfNotNull("D", "4");
Assert.AreEqual("4", dictionary["D"]);
}
[Test]
public void AddIfNotNullShouldNotAdd()
{
var dictionary = GetTestDictionary();
dictionary.AddIfNotNull("D", null);
Assert.IsFalse(dictionary.ContainsKey("D"));
}
[Test]
public void AddIfNotNullShouldThrow()
{
var dictionary = GetTestDictionary();
Assert.Throws<ArgumentException>(() => dictionary.AddIfNotNull("C", "4"));
}
private IDictionary<string, string> GetTestDictionary() => new Dictionary<string, string> { { "A", "1" }, { "B", null }, { "C", "3" } };
}
}
| 28.68 | 144 | 0.564156 | [
"MIT"
] | Rfvgyhn/Elite-Log-Agent | DW.ELA.UnitTests/DictionaryExtensionsTests.cs | 1,436 | C# |
using System;
using System.Collections.Generic;
using NSubstitute;
using Xunit;
using System.Threading.Tasks;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class SearchClientTests
{
public class TheConstructor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new SearchClient(null));
}
}
public class TheSearchUsersMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchUsers(new SearchUsersRequest("something"));
connection.Received().Get<SearchUsersResult>(Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchUsers(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github"));
}
[Fact]
public void TestingTheAccountTypeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.User;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:User"));
}
[Fact]
public void TestingTheAccountTypeQualifier_Org()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.Org;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:Org"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users where the fullname contains 'github'
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Fullname };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Fullname"));
}
[Fact]
public void TestingTheInQualifier_Email()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Email"));
}
[Fact]
public void TestingTheInQualifier_Username()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username, UserInQualifier.Fullname, UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username,Fullname,Email"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>5"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<5"));
}
[Fact]
public void TestingTheLocationQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Location = "San Francisco";
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+location:San Francisco"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users who have mostly repos where language is Ruby
var request = new SearchUsersRequest("github");
request.Language = Language.Ruby;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2014-01-01"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>1"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>=1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<=1"));
}
[Fact]
public void TestingTheFollowersQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = new Range(1, 1000);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:1..1000"));
}
}
public class TheSearchRepoMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchRepo(new SearchRepositoriesRequest("something"));
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchRepo(null));
}
[Fact]
public void TestingTheSizeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Size = Range.GreaterThan(1);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+size:>1"));
}
[Fact]
public void TestingTheStarsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are greater than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.GreaterThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:>500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500 or equal to
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThanOrEquals(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<=500"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos which has forks that are greater than 50
var request = new SearchRepositoriesRequest("github");
request.Forks = Range.GreaterThan(50);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+forks:>50"));
}
[Fact]
public void TestingTheForkQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//search repos that contains rails and forks are included in the search
var request = new SearchRepositoriesRequest("github");
request.Fork = ForkQualifier.IncludeForks;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+fork:IncludeForks"));
}
[Fact]
public void TestingTheLangaugeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos language is Ruby
var request = new SearchRepositoriesRequest("github");
request.Language = Language.Ruby;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the Description contains the test 'github'
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Description };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Description"));
}
[Fact]
public void TestingTheInQualifier_Name()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Name"));
}
[Fact]
public void TestingTheInQualifier_Readme()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme, InQualifier.Description, InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme,Description,Name"));
}
[Fact]
public void TestingTheCreatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2011-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>=2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<=2013-01-01"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where search contains 'github' and user/org is 'github'
var request = new SearchRepositoriesRequest("github");
request.User = "rails";
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+user:rails"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.SortField = RepoSearchSort.Stars;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "github" &&
d["sort"] == "stars"));
}
}
public class TheSearchIssuesMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchIssues(new SearchIssuesRequest("something"));
connection.Received().Get<SearchIssuesResult>(Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchIssues(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("pub");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "pub"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Comments;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "comments"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Updated;
request.Order = SortDirection.Ascending;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "updated" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Comment };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:comment"));
}
[Fact]
public void TestingTheInQualifiers_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Body, IssueInQualifier.Title };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:body,title"));
}
[Fact]
public void TestingTheTypeQualifier_Issue()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.Issue;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:issue"));
}
[Fact]
public void TestingTheTypeQualifier_PR()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.PR;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:pr"));
}
[Fact]
public void TestingTheAuthorQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Author = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+author:alfhenrik"));
}
[Fact]
public void TestingTheAssigneeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Assignee = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+assignee:alfhenrik"));
}
[Fact]
public void TestingTheMentionsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Mentions = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+mentions:alfhenrik"));
}
[Fact]
public void TestingTheCommenterQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Commenter = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+commenter:alfhenrik"));
}
[Fact]
public void TestingTheInvolvesQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Involves = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+involves:alfhenrik"));
}
[Fact]
public void TestingTheStateQualifier_Open()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Open;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:open"));
}
[Fact]
public void TestingTheStateQualifier_Closed()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Closed;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:closed"));
}
[Fact]
public void TestingTheLabelsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug"));
}
[Fact]
public void TestingTheLabelsQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug", "feature" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug+label:feature"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Language = Language.CSharp;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:CSharp"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<=2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>=2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<=2014-01-01"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>10"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>=10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<=10"));
}
[Fact]
public void TestingTheCommentsQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = new Range(10, 20);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:10..20"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.User = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repo = "octokit.net";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit.net"));
}
[Fact]
public void TestingTheRepoAndUserAndLabelQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repo = "octokit.net";
request.User = "alfhenrik";
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] ==
"something+label:bug+user:alfhenrik+repo:octokit.net"));
}
}
public class TheSearchCodeMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchCode(new SearchCodeRequest("something"));
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchCode(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["sort"] == "indexed"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
request.Order = SortDirection.Ascending;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "indexed" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File, CodeInQualifier.Path };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file,path"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Language = Language.CSharp;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:C#"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Forks = true;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+fork:true"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>10"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>=10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<=10"));
}
[Fact]
public void TestingTheSizeQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = new Range(10, 100);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:10..100"));
}
[Fact]
public void TestingThePathQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Path = "app/public";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+path:app/public"));
}
[Fact]
public void TestingTheExtensionQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Extension = "cs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+extension:cs"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.User = "alfhenrik";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Repo = "octokit.net";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit.net"));
}
[Fact]
public void TestingTheRepoQualifier_InConstructor()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public void TestingTheRepoAndPathAndExtensionQualifiers()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Repo = "octokit.net";
request.Path = "tools/FAKE.core";
request.Extension = "fs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+path:tools/FAKE.core+extension:fs+repo:octokit.net"));
}
}
}
}
| 45.450304 | 152 | 0.531679 | [
"MIT"
] | darrelmiller/octokit.net | Octokit.Tests/Clients/SearchClientTests.cs | 67,223 | C# |
using Axiverse.Injection;
using Axiverse.Modules;
using Axiverse.Services;
using Axiverse.Services.ChatService;
using Axiverse.Services.EntityService;
using Axiverse.Services.IdentityService;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Services
{
[Dependency(typeof(ChatServiceModule))]
[Dependency(typeof(IdentityServiceModule))]
[Dependency(typeof(EntityServiceModule))]
//[Dependency(typeof(ServerModule))]
public class Program : ProgramModule
{
private ManualResetEvent shutdownEvent = new ManualResetEvent(false);
[Bind]
Server server;
public override void Execute(string[] args)
{
// Setup
Console.WriteLine("Starting services server.");
foreach (var item in server.Services)
{
Console.WriteLine("\t- {0}", item);
}
Console.WriteLine("Press Ctrl-C to stop the server...");
// Start
server.Start();
// Shutdown
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Shutting request recieved.");
shutdownEvent.Set();
};
shutdownEvent.WaitOne();
// Cleanup
Console.WriteLine("Shutting down services server.");
var shutdown = server.ShutdownAsync();
if (!shutdown.Wait(1000))
{
Console.WriteLine("Graceful shutdown timeout, killing server.");
server.KillAsync().Wait();
}
Console.WriteLine("Shutdown complete.");
}
static void Main(string[] args)
{
Run<Program>(args);
}
}
}
| 27.597015 | 80 | 0.587345 | [
"MIT"
] | AxiverseCode/Axiverse | Source/Deployment/Services/Program.cs | 1,851 | C# |
//
// System.Diagnostics.LocalFileEventLog.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
// Gert Driesen <drieseng@users.sourceforge.net>
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.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.
//
#if !MOBILE
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal class LocalFileEventLog : EventLogImpl
{
const string DateFormat = "yyyyMMddHHmmssfff";
static readonly object lockObject = new object ();
FileSystemWatcher file_watcher;
int last_notification_index;
bool _notifying;
public LocalFileEventLog (EventLog coreEventLog) : base (coreEventLog)
{
}
public override void BeginInit () {
}
public override void Clear ()
{
string logDir = FindLogStore (CoreEventLog.Log);
if (!Directory.Exists (logDir))
return;
foreach (string file in Directory.GetFiles (logDir, "*.log"))
File.Delete (file);
}
public override void Close ()
{
if (file_watcher != null) {
file_watcher.EnableRaisingEvents = false;
file_watcher = null; // force creation of new FileSystemWatcher
}
}
public override void CreateEventSource (EventSourceCreationData sourceData)
{
// construct path for storing log entries
string logDir = FindLogStore (sourceData.LogName);
// create event log store (if necessary), and modify access
// permissions (unix only)
if (!Directory.Exists (logDir)) {
// ensure the log name is valid for customer logs
ValidateCustomerLogName (sourceData.LogName, sourceData.MachineName);
Directory.CreateDirectory (logDir);
// MS does not allow an event source to be named after an already
// existing event log. To speed up checking whether a given event
// source already exists (either as a event source or event log)
// we create an event source directory named after the event log.
// This matches what MS does with the registry-based registration.
Directory.CreateDirectory (Path.Combine (logDir, sourceData.LogName));
if (RunningOnUnix) {
ModifyAccessPermissions (logDir, "777");
ModifyAccessPermissions (logDir, "+t");
}
}
// create directory for event source, so we can check if the event
// source already exists
string sourceDir = Path.Combine (logDir, sourceData.Source);
Directory.CreateDirectory (sourceDir);
}
public override void Delete (string logName, string machineName)
{
string logDir = FindLogStore (logName);
if (!Directory.Exists (logDir))
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Event Log '{0}'"
+ " does not exist on computer '{1}'.", logName,
machineName));
Directory.Delete (logDir, true);
}
public override void DeleteEventSource (string source, string machineName)
{
if (!Directory.Exists (EventLogStore))
throw new ArgumentException (string.Format (
CultureInfo.InvariantCulture, "The source '{0}' is not"
+ " registered on computer '{1}'.", source, machineName));
string sourceDir = FindSourceDirectory (source);
if (sourceDir == null)
throw new ArgumentException (string.Format (
CultureInfo.InvariantCulture, "The source '{0}' is not"
+ " registered on computer '{1}'.", source, machineName));
Directory.Delete (sourceDir);
}
public override void Dispose (bool disposing)
{
Close ();
}
public override void DisableNotification ()
{
if (file_watcher == null)
return;
file_watcher.EnableRaisingEvents = false;
}
public override void EnableNotification ()
{
if (file_watcher == null) {
string logDir = FindLogStore (CoreEventLog.Log);
if (!Directory.Exists (logDir))
Directory.CreateDirectory (logDir);
file_watcher = new FileSystemWatcher ();
file_watcher.Path = logDir;
file_watcher.Created += delegate (object o, FileSystemEventArgs e) {
lock (this) {
if (_notifying)
return;
_notifying = true;
}
// allow for file to be finished writing
Thread.Sleep (100);
// Process every new entry in one notification event.
try {
while (GetLatestIndex () > last_notification_index) {
try {
CoreEventLog.OnEntryWritten (GetEntry (last_notification_index++));
} catch (Exception ex) {
// FIXME: find some proper way to output this error
Debug.WriteLine (ex);
}
}
} finally {
lock (this)
_notifying = false;
}
};
}
last_notification_index = GetLatestIndex ();
file_watcher.EnableRaisingEvents = true;
}
public override void EndInit () { }
public override bool Exists (string logName, string machineName)
{
string logDir = FindLogStore (logName);
return Directory.Exists (logDir);
}
[MonoTODO ("Use MessageTable from PE for lookup")]
protected override string FormatMessage (string source, uint eventID, string [] replacementStrings)
{
return string.Join (", ", replacementStrings);
}
protected override int GetEntryCount ()
{
string logDir = FindLogStore (CoreEventLog.Log);
if (!Directory.Exists (logDir))
return 0;
string[] logFiles = Directory.GetFiles (logDir, "*.log");
return logFiles.Length;
}
protected override EventLogEntry GetEntry (int index)
{
string logDir = FindLogStore (CoreEventLog.Log);
// our file names are one-based
string file = Path.Combine (logDir, (index + 1).ToString (
CultureInfo.InvariantCulture) + ".log");
using (TextReader tr = File.OpenText (file)) {
int eventIndex = int.Parse (Path.GetFileNameWithoutExtension (file),
CultureInfo.InvariantCulture);
uint instanceID = uint.Parse (tr.ReadLine ().Substring (12),
CultureInfo.InvariantCulture);
EventLogEntryType type = (EventLogEntryType)
Enum.Parse (typeof (EventLogEntryType), tr.ReadLine ().Substring (11));
string source = tr.ReadLine ().Substring (8);
string category = tr.ReadLine ().Substring (10);
short categoryNumber = short.Parse(category, CultureInfo.InvariantCulture);
string categoryName = "(" + category + ")";
DateTime timeGenerated = DateTime.ParseExact (tr.ReadLine ().Substring (15),
DateFormat, CultureInfo.InvariantCulture);
DateTime timeWritten = File.GetLastWriteTime (file);
int stringNums = int.Parse (tr.ReadLine ().Substring (20));
ArrayList replacementTemp = new ArrayList ();
StringBuilder sb = new StringBuilder ();
while (replacementTemp.Count < stringNums) {
char c = (char) tr.Read ();
if (c == '\0') {
replacementTemp.Add (sb.ToString ());
sb.Length = 0;
} else {
sb.Append (c);
}
}
string [] replacementStrings = new string [replacementTemp.Count];
replacementTemp.CopyTo (replacementStrings, 0);
string message = FormatMessage (source, instanceID, replacementStrings);
int eventID = EventLog.GetEventID (instanceID);
byte [] bin = Convert.FromBase64String (tr.ReadToEnd ());
return new EventLogEntry (categoryName, categoryNumber, eventIndex,
eventID, source, message, null, Environment.MachineName,
type, timeGenerated, timeWritten, bin, replacementStrings,
instanceID);
}
}
[MonoTODO]
protected override string GetLogDisplayName ()
{
return CoreEventLog.Log;
}
protected override string [] GetLogNames (string machineName)
{
if (!Directory.Exists (EventLogStore))
return new string [0];
string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
string [] logNames = new string [logDirs.Length];
for (int i = 0; i < logDirs.Length; i++)
logNames [i] = Path.GetFileName (logDirs [i]);
return logNames;
}
public override string LogNameFromSourceName (string source, string machineName)
{
if (!Directory.Exists (EventLogStore))
return string.Empty;
string sourceDir = FindSourceDirectory (source);
if (sourceDir == null)
return string.Empty;
DirectoryInfo info = new DirectoryInfo (sourceDir);
return info.Parent.Name;
}
public override bool SourceExists (string source, string machineName)
{
if (!Directory.Exists (EventLogStore))
return false;
string sourceDir = FindSourceDirectory (source);
return (sourceDir != null);
}
public override void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte [] rawData)
{
lock (lockObject) {
string logDir = FindLogStore (CoreEventLog.Log);
int index = GetLatestIndex () + 1;
string logPath = Path.Combine (logDir, index.ToString (CultureInfo.InvariantCulture) + ".log");
try {
using (TextWriter w = File.CreateText (logPath)) {
#if NET_2_0
w.WriteLine ("InstanceID: {0}", instanceID.ToString (CultureInfo.InvariantCulture));
#else
w.WriteLine ("InstanceID: {0}", instanceID.ToString (CultureInfo.InvariantCulture));
#endif
w.WriteLine ("EntryType: {0}", (int) type);
w.WriteLine ("Source: {0}", CoreEventLog.Source);
w.WriteLine ("Category: {0}", category.ToString (CultureInfo.InvariantCulture));
w.WriteLine ("TimeGenerated: {0}", DateTime.Now.ToString (
DateFormat, CultureInfo.InvariantCulture));
w.WriteLine ("ReplacementStrings: {0}", replacementStrings.
Length.ToString (CultureInfo.InvariantCulture));
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < replacementStrings.Length; i++) {
string replacement = replacementStrings [i];
sb.Append (replacement);
sb.Append ('\0');
}
w.Write (sb.ToString ());
w.Write (Convert.ToBase64String (rawData));
}
} catch (IOException) {
File.Delete (logPath);
}
}
}
private string FindSourceDirectory (string source)
{
string sourceDir = null;
string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
for (int i = 0; i < logDirs.Length; i++) {
string [] sourceDirs = Directory.GetDirectories (logDirs [i], "*");
for (int j = 0; j < sourceDirs.Length; j++) {
string relativeDir = Path.GetFileName (sourceDirs [j]);
// use a case-insensitive comparison
if (string.Compare (relativeDir, source, true, CultureInfo.InvariantCulture) == 0) {
sourceDir = sourceDirs [j];
break;
}
}
}
return sourceDir;
}
private bool RunningOnUnix {
get {
int p = (int) Environment.OSVersion.Platform;
return ((p == 4) || (p == 128) || (p == 6));
}
}
private string FindLogStore (string logName) {
// when the event log store does not yet exist, there's no need
// to perform a case-insensitive lookup
if (!Directory.Exists (EventLogStore))
return Path.Combine (EventLogStore, logName);
// we'll use a case-insensitive lookup to match the MS behaviour
// while still allowing the original casing of the log name to be
// retained
string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
for (int i = 0; i < logDirs.Length; i++) {
string relativeDir = Path.GetFileName (logDirs [i]);
// use a case-insensitive comparison
if (string.Compare (relativeDir, logName, true, CultureInfo.InvariantCulture) == 0) {
return logDirs [i];
}
}
return Path.Combine (EventLogStore, logName);
}
private string EventLogStore {
get {
// for the local file implementation, the MONO_EVENTLOG_TYPE
// environment variable can contain the path of the event log
// store by using the following syntax: local:<path>
string eventLogType = Environment.GetEnvironmentVariable (EventLog.EVENTLOG_TYPE_VAR);
if (eventLogType != null && eventLogType.Length > EventLog.LOCAL_FILE_IMPL.Length + 1)
return eventLogType.Substring (EventLog.LOCAL_FILE_IMPL.Length + 1);
if (RunningOnUnix) {
return "/var/lib/mono/eventlog";
} else {
return Path.Combine (Environment.GetFolderPath (
Environment.SpecialFolder.CommonApplicationData),
"mono\\eventlog");
}
}
}
private int GetLatestIndex () {
// our file names are one-based
int maxIndex = 0;
string[] logFiles = Directory.GetFiles (FindLogStore (CoreEventLog.Log), "*.log");
for (int i = 0; i < logFiles.Length; i++) {
try {
string file = logFiles[i];
int index = int.Parse (Path.GetFileNameWithoutExtension (
file), CultureInfo.InvariantCulture);
if (index > maxIndex)
maxIndex = index;
} catch {
}
}
return maxIndex;
}
private static void ModifyAccessPermissions (string path, string permissions)
{
ProcessStartInfo pi = new ProcessStartInfo ();
pi.FileName = "chmod";
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.Arguments = string.Format ("{0} \"{1}\"", permissions, path);
Process p = null;
try {
p = Process.Start (pi);
} catch (Exception ex) {
throw new SecurityException ("Access permissions could not be modified.", ex);
}
p.WaitForExit ();
if (p.ExitCode != 0) {
p.Close ();
throw new SecurityException ("Access permissions could not be modified.");
}
p.Close ();
}
#if NET_2_0
public override OverflowAction OverflowAction {
get { return OverflowAction.DoNotOverwrite; }
}
public override int MinimumRetentionDays {
get { return int.MaxValue; }
}
public override long MaximumKilobytes {
get { return long.MaxValue; }
set { throw new NotSupportedException ("This EventLog implementation does not support setting max kilobytes policy"); }
}
public override void ModifyOverflowPolicy (OverflowAction action, int retentionDays)
{
throw new NotSupportedException ("This EventLog implementation does not support modifying overflow policy");
}
public override void RegisterDisplayName (string resourceFile, long resourceId)
{
throw new NotSupportedException ("This EventLog implementation does not support registering display name");
}
#endif
}
}
#endif
| 32.803879 | 138 | 0.690099 | [
"Apache-2.0"
] | OpenPSS/psm-mono | mcs/class/System/System.Diagnostics/LocalFileEventLog.cs | 15,221 | C# |
using Castle.Core.Logging;
using Covid19Radar.Api;
using Covid19Radar.Api.Common;
using Covid19Radar.Api.DataStore;
using Covid19Radar.Api.Tests.Mock;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Scripts;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace Covid19Radar.Api.Tests.Common.DataStore
{
[TestClass]
[TestCategory("Common")]
public class CosmosTest
{
[TestMethod]
public void CreateMethod()
{
// preparation
var config = new Mock<IConfiguration>();
config.Setup(_ => _["COSMOS_AUTO_GENERATE"]).Returns("true");
var containerScripts = new Mock<Scripts>();
var container = new Mock<Container>();
container.Setup(_ => _.Scripts).Returns(containerScripts.Object);
var containerResponse = new Mock<ContainerResponse>();
containerResponse.Setup(_ => _.Container).Returns(container.Object);
var database = new Mock<Database>();
database.Setup(_ => _.CreateContainerIfNotExistsAsync
(It.IsAny<ContainerProperties>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(containerResponse.Object);
database.Setup(_ => _.GetContainer(It.IsAny<string>()))
.Returns(container.Object);
var databaseResponse = new Mock<DatabaseResponse>();
databaseResponse.Setup(_ => _.Database).Returns(database.Object);
databaseResponse.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
var client = new Mock<CosmosClient>();
client.Setup(_ => _.CreateDatabaseIfNotExistsAsync
(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseResponse.Object);
var logger = new LoggerMock<ICosmos>();
// action
var instance = new Cosmos(config.Object, client.Object, logger);
}
[TestMethod]
public void CreateMethodThrowException()
{
// preparation
var config = new Mock<IConfiguration>();
config.Setup(_ => _["COSMOS_AUTO_GENERATE"]).Returns("true");
var containerScripts = new Mock<Scripts>();
var container = new Mock<Container>();
container.Setup(_ => _.Scripts).Returns(containerScripts.Object);
var containerResponse = new Mock<ContainerResponse>();
containerResponse.Setup(_ => _.Container).Returns(container.Object);
var database = new Mock<Database>();
database.Setup(_ => _.CreateContainerIfNotExistsAsync
(It.IsAny<ContainerProperties>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(containerResponse.Object);
database.Setup(_ => _.GetContainer(It.IsAny<string>()))
.Returns(container.Object);
var databaseResponse = new Mock<DatabaseResponse>();
databaseResponse.Setup(_ => _.Database).Returns(database.Object);
databaseResponse.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.BadRequest);
var client = new Mock<CosmosClient>();
client.Setup(_ => _.CreateDatabaseIfNotExistsAsync
(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseResponse.Object);
client.Setup(_ => _.GetDatabase(It.IsAny<string>())).Throws(new Exception());
var logger = new LoggerMock<ICosmos>();
// action
#if DEBUG
Assert.ThrowsException<AggregateException>(() => {
var instance = new Cosmos(config.Object, client.Object, logger);
});
#else
Assert.ThrowsException<Exception>(() => {
var instance = new Cosmos(config.Object, client.Object, logger);
});
#endif
}
[TestMethod]
public void GetContainerProperties()
{
// preparation
var config = new Mock<IConfiguration>();
config.Setup(_ => _["COSMOS_AUTO_GENERATE"]).Returns("true");
var containerScripts = new Mock<Scripts>();
var container = new Mock<Container>();
container.Setup(_ => _.Scripts).Returns(containerScripts.Object);
var containerResponse = new Mock<ContainerResponse>();
containerResponse.Setup(_ => _.Container).Returns(container.Object);
var database = new Mock<Database>();
database.Setup(_ => _.CreateContainerIfNotExistsAsync
(It.IsAny<ContainerProperties>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(containerResponse.Object);
database.Setup(_ => _.GetContainer(It.IsAny<string>()))
.Returns(container.Object);
var databaseResponse = new Mock<DatabaseResponse>();
databaseResponse.Setup(_ => _.Database).Returns(database.Object);
databaseResponse.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
var client = new Mock<CosmosClient>();
client.Setup(_ => _.CreateDatabaseIfNotExistsAsync
(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<Microsoft.Azure.Cosmos.RequestOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseResponse.Object);
client.Setup(_ => _.GetDatabase(It.IsAny<string>()))
.Returns(database.Object);
var logger = new LoggerMock<ICosmos>();
var instance = new Cosmos(config.Object, client.Object, logger);
// action
Assert.IsNotNull(instance.Diagnosis);
Assert.IsNotNull(instance.Notification);
Assert.IsNotNull(instance.Sequence);
Assert.IsNotNull(instance.TemporaryExposureKey);
Assert.IsNotNull(instance.TemporaryExposureKeyExport);
Assert.IsNotNull(instance.User);
}
}
}
| 49.871212 | 150 | 0.629652 | [
"MPL-2.0-no-copyleft-exception",
"MPL-2.0",
"Apache-2.0"
] | 178inaba/Covid19Radar | src/Covid19Radar.Api.Tests/Common/DataStore/CosmosTest.cs | 6,585 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace ChildSupport.Domain
{
public partial class SalesTerritoryHistory
{
#region Primitive Properties
public virtual int BusinessEntityID
{
get { return _businessEntityID; }
set
{
if (_businessEntityID != value)
{
if (SalesPerson != null && SalesPerson.BusinessEntityID != value)
{
SalesPerson = null;
}
_businessEntityID = value;
}
}
}
private int _businessEntityID;
public virtual int TerritoryID
{
get { return _territoryID; }
set
{
if (_territoryID != value)
{
if (SalesTerritory != null && SalesTerritory.TerritoryID != value)
{
SalesTerritory = null;
}
_territoryID = value;
}
}
}
private int _territoryID;
public virtual System.DateTime StartDate
{
get;
set;
}
public virtual Nullable<System.DateTime> EndDate
{
get;
set;
}
public virtual System.Guid rowguid
{
get;
set;
}
public virtual System.DateTime ModifiedDate
{
get;
set;
}
#endregion
#region Navigation Properties
public virtual SalesPerson SalesPerson
{
get { return _salesPerson; }
set
{
if (!ReferenceEquals(_salesPerson, value))
{
var previousValue = _salesPerson;
_salesPerson = value;
FixupSalesPerson(previousValue);
}
}
}
private SalesPerson _salesPerson;
public virtual SalesTerritory SalesTerritory
{
get { return _salesTerritory; }
set
{
if (!ReferenceEquals(_salesTerritory, value))
{
var previousValue = _salesTerritory;
_salesTerritory = value;
FixupSalesTerritory(previousValue);
}
}
}
private SalesTerritory _salesTerritory;
#endregion
#region Association Fixup
private void FixupSalesPerson(SalesPerson previousValue)
{
if (previousValue != null && previousValue.SalesTerritoryHistories.Contains(this))
{
previousValue.SalesTerritoryHistories.Remove(this);
}
if (SalesPerson != null)
{
if (!SalesPerson.SalesTerritoryHistories.Contains(this))
{
SalesPerson.SalesTerritoryHistories.Add(this);
}
if (BusinessEntityID != SalesPerson.BusinessEntityID)
{
BusinessEntityID = SalesPerson.BusinessEntityID;
}
}
}
private void FixupSalesTerritory(SalesTerritory previousValue)
{
if (previousValue != null && previousValue.SalesTerritoryHistories.Contains(this))
{
previousValue.SalesTerritoryHistories.Remove(this);
}
if (SalesTerritory != null)
{
if (!SalesTerritory.SalesTerritoryHistories.Contains(this))
{
SalesTerritory.SalesTerritoryHistories.Add(this);
}
if (TerritoryID != SalesTerritory.TerritoryID)
{
TerritoryID = SalesTerritory.TerritoryID;
}
}
}
#endregion
}
}
| 29.402516 | 95 | 0.452193 | [
"MIT"
] | propellingbits/RepositoryPattern-EF | ChildSupport.Domain/SalesTerritoryHistory.cs | 4,675 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace XenAPI
{
public enum vif_ipv6_configuration_mode
{
None, Static, unknown
}
public static class vif_ipv6_configuration_mode_helper
{
public static string ToString(vif_ipv6_configuration_mode x)
{
switch (x)
{
case vif_ipv6_configuration_mode.None:
return "None";
case vif_ipv6_configuration_mode.Static:
return "Static";
default:
return "unknown";
}
}
}
}
| 35.20339 | 71 | 0.669234 | [
"BSD-2-Clause"
] | jijiang/xenadmin | XenModel/XenAPI/vif_ipv6_configuration_mode.cs | 2,077 | C# |
namespace MSGraph.Exchange.Attachment {
/// <summary>
/// names of reference attachment provider types in Microsoft Graph API
/// </summary>
public enum ReferenceAttachmentProvider {
/// <summary>
/// oneDriveBusiness
/// </summary>
oneDriveBusiness,
/// <summary>
/// oneDriveConsumer
/// </summary>
oneDriveConsumer,
/// <summary>
/// dropbox
/// </summary>
dropbox,
/// <summary>
/// other
/// </summary>
other
}
/// <summary>
/// names of possible permissions in referenceAttachments in Microsoft Graph API
/// </summary>
public enum referenceAttachmentPermission {
/// <summary>
/// view
/// </summary>
view,
/// <summary>
/// edit
/// </summary>
edit,
/// <summary>
/// anonymousView
/// </summary>
anonymousView,
/// <summary>
/// anonymousEdit
/// </summary>
anonymousEdit,
/// <summary>
/// organizationView
/// </summary>
organizationView,
/// <summary>
/// organizationEdit
/// </summary>
organizationEdit,
/// <summary>
/// other
/// </summary>
other,
}
}
| 20.462687 | 84 | 0.471918 | [
"MIT"
] | AndiBellstedt/MSGraph | library/MSGraph/MSGraph/Exchange/Attachment/referenceAttachmentEnums.cs | 1,373 | 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 ivs-2020-07-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IVS.Model
{
/// <summary>
///
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class StreamUnavailableException : AmazonIVSException
{
private string _exceptionMessage;
/// <summary>
/// Constructs a new StreamUnavailableException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public StreamUnavailableException(string message)
: base(message) {}
/// <summary>
/// Construct instance of StreamUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public StreamUnavailableException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of StreamUnavailableException
/// </summary>
/// <param name="innerException"></param>
public StreamUnavailableException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of StreamUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public StreamUnavailableException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of StreamUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public StreamUnavailableException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the StreamUnavailableException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected StreamUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.ExceptionMessage = (string)info.GetValue("ExceptionMessage", typeof(string));
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("ExceptionMessage", this.ExceptionMessage);
}
#endif
/// <summary>
/// Gets and sets the property ExceptionMessage.
/// <para>
/// The stream is temporarily unavailable.
/// </para>
/// </summary>
public string ExceptionMessage
{
get { return this._exceptionMessage; }
set { this._exceptionMessage = value; }
}
// Check to see if ExceptionMessage property is set
internal bool IsSetExceptionMessage()
{
return this._exceptionMessage != null;
}
}
} | 45.096552 | 178 | 0.667839 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/IVS/Generated/Model/StreamUnavailableException.cs | 6,539 | C# |
using System.Collections.Generic;
using System.Linq;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using AutoStep.Elements.Interaction;
using AutoStep.Elements.Parts;
using AutoStep.Language.Position;
namespace AutoStep.Language.Interaction.Visitors
{
using static AutoStep.Language.Interaction.Parser.AutoStepInteractionsParser;
/// <summary>
/// Provides the visitor for component definitions.
/// </summary>
internal class ComponentDefinitionVisitor : InteractionDefinitionVisitor<ComponentDefinitionElement>
{
/// <summary>
/// Initializes a new instance of the <see cref="ComponentDefinitionVisitor"/> class.
/// </summary>
/// <param name="sourceName">The name of the source.</param>
/// <param name="tokenStream">The token stream.</param>
/// <param name="rewriter">The token rewriter.</param>
/// <param name="compilerOptions">The compiler options.</param>
/// <param name="positionIndex">The position index (or null if not in use).</param>
public ComponentDefinitionVisitor(string? sourceName, ITokenStream tokenStream, TokenStreamRewriter rewriter, InteractionsCompilerOptions compilerOptions, PositionIndex? positionIndex)
: base(sourceName, tokenStream, rewriter, compilerOptions, positionIndex)
{
}
/// <inheritdoc/>
public override ComponentDefinitionElement VisitComponentDefinition([NotNull] ComponentDefinitionContext context)
{
var declaration = context.componentDefinitionDeclaration();
var componentName = declaration.NAME_REF();
Result = new ComponentDefinitionElement(componentName.GetText());
Result.AddLineInfo(declaration);
PositionIndex?.PushScope(Result, context);
PositionIndex?.AddLineToken(declaration.COMPONENT_DEFINITION(), LineTokenCategory.EntryMarker, LineTokenSubCategory.InteractionComponent);
PositionIndex?.AddLineToken(componentName, LineTokenCategory.InteractionName, LineTokenSubCategory.InteractionComponent);
VisitChildren(context);
PositionIndex?.PopScope(context);
// Apply the known name to each step.
foreach (var step in Result.Steps)
{
step.FixedComponentName = Result.Name;
}
return Result;
}
/// <inheritdoc/>
protected override bool ValidateAddedStepDefinition(InteractionStepDefinitionElement stepDef, StepDefinitionBodyContext bodyContext)
{
if (stepDef.Parts.OfType<PlaceholderMatchPart>().Any())
{
// Component step definitions cannot have a component marker.
MessageSet.Add(bodyContext.stepDefinition(), CompilerMessageLevel.Error, CompilerMessageCode.InteractionComponentStepDefinitionCannotHaveComponentMarker);
return false;
}
return base.ValidateAddedStepDefinition(stepDef, bodyContext);
}
/// <inheritdoc/>
public override ComponentDefinitionElement VisitComponentName([NotNull] ComponentNameContext context)
{
var str = context.STRING();
PositionIndex?.AddLineToken(context.NAME_KEYWORD(), LineTokenCategory.InteractionPropertyName, LineTokenSubCategory.InteractionName);
PositionIndex?.AddLineToken(context.STRING(), LineTokenCategory.InteractionString, LineTokenSubCategory.InteractionName);
if (str is object)
{
ProvideName(GetTextFromStringToken(str), context);
}
return Result!;
}
/// <inheritdoc/>
public override ComponentDefinitionElement VisitComponentInherits([NotNull] ComponentInheritsContext context)
{
var inherits = context.NAME_REF();
if (inherits is object)
{
var inheritsElement = new NameRefElement(inherits.GetText()).AddPositionalLineInfo(inherits);
PositionIndex?.AddLineToken(context.INHERITS_KEYWORD(), LineTokenCategory.InteractionPropertyName, LineTokenSubCategory.InteractionInherits);
PositionIndex?.AddLineToken(inheritsElement, LineTokenCategory.InteractionString, LineTokenSubCategory.InteractionName);
Result!.Inherits = inheritsElement;
}
return Result!;
}
/// <inheritdoc/>
public override ComponentDefinitionElement VisitComponentTraits(ComponentTraitsContext context)
{
var actualRefs = new HashSet<string>();
PositionIndex?.AddLineToken(context.TRAITS_KEYWORD(), LineTokenCategory.InteractionPropertyName, LineTokenSubCategory.InteractionTrait);
foreach (var traitRef in context.NAME_REF())
{
var traitText = traitRef.GetText();
if (actualRefs.Contains(traitText))
{
// Warning, duplicate not allowed.
MessageSet.Add(traitRef, CompilerMessageLevel.Warning, CompilerMessageCode.InteractionDuplicateTrait);
}
else
{
var traitNamePart = new NameRefElement(traitText);
traitNamePart.AddPositionalLineInfo(traitRef);
PositionIndex?.AddLineToken(traitNamePart, LineTokenCategory.InteractionName, LineTokenSubCategory.InteractionTrait);
actualRefs.Add(traitNamePart.Name);
Result!.Traits.Add(traitNamePart);
}
}
return Result!;
}
}
}
| 41.144928 | 192 | 0.659387 | [
"MIT"
] | SivaGudivada/AutoStep | src/AutoStep/Language/Interaction/Visitors/ComponentDefinitionVisitor.cs | 5,680 | C# |
namespace EventStore.Projections.Core.Services.Management.ManagedProjectionStates
{
class FaultedState : ManagedProjection.ManagedProjectionStateBase
{
public FaultedState(ManagedProjection managedProjection)
: base(managedProjection)
{
}
}
} | 26.454545 | 81 | 0.714777 | [
"Apache-2.0"
] | bartelink/EventStore | src/EventStore.Projections.Core/Services/Management/ManagedProjectionStates/FaultedState.cs | 291 | C# |
// Generated by the MSBuild WriteCodeFragment class.
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("TravelBlog")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("TravelBlog")]
[assembly: System.Reflection.AssemblyTitleAttribute("TravelBlog")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
| 47.428571 | 81 | 0.825301 | [
"MIT"
] | ReconScout77/potential-couscous | TravelBlog/obj/Debug/netcoreapp1.1/TravelBlog.AssemblyInfo.cs | 664 | C# |
using JetBrains.ReSharper.Plugins.Unity.JsonNew.Psi.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDefNew.Psi.Resolve
{
public class AsmDefNameReferenceFactory : IReferenceFactory
{
public ReferenceCollection GetReferences(ITreeNode element, ReferenceCollection oldReferences)
{
if (ResolveUtil.CheckThatAllReferencesBelongToElement<AsmDefNameReference>(oldReferences, element))
return oldReferences;
if (element.IsReferenceLiteral())
{
return new ReferenceCollection(new AsmDefNameReference((IJsonNewLiteralExpression) element));
}
return ReferenceCollection.Empty;
}
public bool HasReference(ITreeNode element, IReferenceNameContainer names)
{
if (element is IJsonNewLiteralExpression literal && literal.ConstantValueType == ConstantValueTypes.String)
return names.Contains(literal.GetStringValue() ?? string.Empty);
return false;
}
}
} | 38.966667 | 119 | 0.703165 | [
"Apache-2.0"
] | 20chan/resharper-unity | resharper/resharper-unity/src/AsmDefNew/Psi/Resolve/AsmDefNameReferenceFactory.cs | 1,171 | C# |
using System;
using NuGetPe;
namespace NuGetPackageExplorer.Types
{
public enum PackageType
{
LocalPackage,
DataServicePackage
}
public sealed class MruItem : IEquatable<MruItem>
{
public string Id { get; set; }
public TemplatebleSemanticVersion Version { get; set; }
public string Path { get; set; }
public PackageType PackageType { get; set; }
#region IEquatable<MruItem> Members
public bool Equals(MruItem other)
{
if (other == null)
{
return false;
}
return Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase);
}
#endregion
public override bool Equals(object obj)
{
return Equals(obj as MruItem);
}
public override int GetHashCode()
{
return Path.GetHashCode();
}
}
} | 22.261905 | 79 | 0.559358 | [
"MIT"
] | ItsMrQ/NugetPE-Mod-v3.23 | PackageViewModel/Types/MruItem.cs | 937 | C# |
//-----------------------------------------------------------------------
// <copyright file="ReplicatedDataSerializerSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Immutable;
using Akka.Actor;
using Akka.Cluster;
using Akka.Configuration;
using Akka.DistributedData.Internal;
using Akka.DistributedData.Serialization;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.DistributedData.Tests.Serialization
{
[Collection("DistributedDataSpec")]
public class ReplicatedDataSerializerSpec : TestKit.Xunit2.TestKit
{
private static readonly Config BaseConfig = ConfigurationFactory.ParseString(@"
akka.actor {
provider=""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
}
akka.remote.dot-netty.tcp.port = 0").WithFallback(DistributedData.DefaultConfig());
private readonly UniqueAddress _address1;
private readonly UniqueAddress _address2;
private readonly UniqueAddress _address3;
public ReplicatedDataSerializerSpec(ITestOutputHelper output) : base(BaseConfig, "ReplicatedDataSerializerSpec", output: output)
{
_address1 = new UniqueAddress(new Address("akka.tcp", Sys.Name, "some.host.org", 4711), 1);
_address2 = new UniqueAddress(new Address("akka.tcp", Sys.Name, "other.host.org", 4711), 2);
_address3 = new UniqueAddress(new Address("akka.tcp", Sys.Name, "some.host.org", 4711), 3);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_GSet()
{
CheckSerialization(GSet<string>.Empty);
CheckSerialization(GSet.Create("a"));
CheckSerialization(GSet.Create("a", "b"));
CheckSerialization(GSet.Create(1, 2, 3));
CheckSerialization(GSet.Create(_address1, _address2));
CheckSerialization(GSet.Create<object>(1L, "2", 3, _address1));
CheckSameContent(GSet.Create("a", "b"), GSet.Create("a", "b"));
CheckSameContent(GSet.Create("a", "b"), GSet.Create("b", "a"));
CheckSameContent(GSet.Create(_address1, _address2, _address3), GSet.Create(_address2, _address1, _address3));
CheckSameContent(GSet.Create(_address1, _address2, _address3), GSet.Create(_address3, _address2, _address1));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_ORSet()
{
CheckSerialization(ORSet<string>.Empty);
CheckSerialization(ORSet.Create(_address1, "a"));
CheckSerialization(ORSet.Create(_address1, "a").Add(_address2, "a"));
CheckSerialization(ORSet.Create(_address1, "a").Remove(_address2, "a"));
CheckSerialization(ORSet.Create(_address1, "a").Add(_address2, "b").Remove(_address1, "a"));
CheckSerialization(ORSet.Create(_address1, 1).Add(_address2, 2));
CheckSerialization(ORSet.Create(_address1, 1L).Add(_address2, 2L));
CheckSerialization(ORSet.Create<object>(_address1, "a").Add(_address2, 2).Add(_address3, 3L).Add(_address3, _address3));
var s1 = ORSet.Create(_address1, "a").Add(_address2, "b");
var s2 = ORSet.Create(_address2, "b").Add(_address1, "a");
CheckSameContent(s1.Merge(s2), s2.Merge(s1));
var s3 = ORSet.Create<object>(_address1, "a").Add(_address2, 17).Remove(_address3, 17);
var s4 = ORSet.Create<object>(_address2, 17).Remove(_address3, 17).Add(_address1, "a");
CheckSameContent(s3.Merge(s4), s4.Merge(s3));
CheckSerialization(ORSet<object>.Empty);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_ORSet_delta()
{
CheckSerialization(ORSet<string>.Empty.Add(_address1, "a").Delta);
CheckSerialization(ORSet<string>.Empty.Add(_address1, "a").ResetDelta().Remove(_address2, "a").Delta);
CheckSerialization(ORSet<string>.Empty.Add(_address1, "a").Remove(_address2, "a").Delta);
CheckSerialization(ORSet<string>.Empty.Add(_address1, "a").ResetDelta().Clear(_address2).Delta);
CheckSerialization(ORSet<string>.Empty.Add(_address1, "a").Clear(_address2).Delta);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_Flag()
{
CheckSerialization(Flag.False);
CheckSerialization(Flag.False.SwitchOn());
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_LWWRegister()
{
CheckSerialization(new LWWRegister<string>(_address1, "value1"));
CheckSerialization(new LWWRegister<string>(_address2, "value2").WithValue(_address2, "value3"));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_GCounter()
{
CheckSerialization(GCounter.Empty);
CheckSerialization(GCounter.Empty.Increment(_address1, 3));
CheckSerialization(GCounter.Empty.Increment(_address1, 2).Increment(_address2, 5));
CheckSameContent(
GCounter.Empty.Increment(_address1, 2).Increment(_address2, 5),
GCounter.Empty.Increment(_address2, 5).Increment(_address1, 1).Increment(_address1, 1));
CheckSameContent(
GCounter.Empty.Increment(_address1, 2).Increment(_address3, 5),
GCounter.Empty.Increment(_address3, 5).Increment(_address1, 2));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_PNCounter()
{
CheckSerialization(PNCounter.Empty);
CheckSerialization(PNCounter.Empty.Increment(_address1, 3));
CheckSerialization(PNCounter.Empty.Increment(_address1, 3).Decrement(_address1, 1));
CheckSerialization(PNCounter.Empty.Increment(_address1, 2).Increment(_address2, 5));
CheckSerialization(PNCounter.Empty.Increment(_address1, 2).Increment(_address2, 5).Decrement(_address1, 1));
CheckSameContent(
PNCounter.Empty.Increment(_address1, 2).Increment(_address2, 5),
PNCounter.Empty.Increment(_address2, 5).Increment(_address1, 1).Increment(_address1, 1));
CheckSameContent(
PNCounter.Empty.Increment(_address1, 2).Increment(_address3, 5),
PNCounter.Empty.Increment(_address3, 5).Increment(_address1, 2));
CheckSameContent(
PNCounter.Empty.Increment(_address1, 2).Decrement(_address1, 1).Increment(_address3, 5),
PNCounter.Empty.Increment(_address3, 5).Increment(_address1, 2).Decrement(_address1, 1));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_ORDictionary()
{
CheckSerialization(ORDictionary<string, GSet<string>>.Empty);
CheckSerialization(ORDictionary<string, GSet<string>>.Empty.SetItem(_address1, "a", GSet.Create("A")));
CheckSerialization(ORDictionary<IActorRef, GSet<string>>.Empty.SetItem(_address1, TestActor, GSet.Create("A")));
CheckSerialization(ORDictionary<string, GSet<string>>.Empty.SetItem(_address1, "a", GSet.Create("A")).SetItem(_address2, "b", GSet.Create("B")));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_ORDictionary_delta()
{
CheckSerialization(ORDictionary<string, GSet<string>>.Empty
.SetItem(_address1, "a", GSet.Create("A"))
.SetItem(_address2, "b", GSet.Create("B"))
.Delta);
CheckSerialization(ORDictionary<string, GSet<string>>.Empty
.SetItem(_address1, "a", GSet.Create("A"))
.ResetDelta()
.Remove(_address2, "a")
.Delta);
CheckSerialization(ORDictionary<string, GSet<string>>.Empty
.SetItem(_address1, "a", GSet.Create("A"))
.Remove(_address2, "a")
.Delta);
CheckSerialization(ORDictionary<string, ORSet<string>>.Empty
.SetItem(_address1, "a", ORSet.Create(_address1, "A"))
.SetItem(_address2, "b", ORSet.Create(_address2, "B"))
.AddOrUpdate(_address1, "a", ORSet<string>.Empty, old => old.Add(_address1, "C"))
.Delta);
CheckSerialization(ORDictionary<string, ORSet<string>>.Empty
.ResetDelta()
.AddOrUpdate(_address1, "a", ORSet<string>.Empty, old => old.Add(_address1, "C"))
.Delta);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_LWWDictionary()
{
CheckSerialization(LWWDictionary<string, string>.Empty);
CheckSerialization(LWWDictionary<string, string>.Empty.SetItem(_address1, "a", "value1"));
CheckSerialization(LWWDictionary<string, object>.Empty.SetItem(_address1, "a", "value1").SetItem(_address2, "b", 17));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_PNCounterDictionary()
{
CheckSerialization(PNCounterDictionary<string>.Empty);
CheckSerialization(PNCounterDictionary<int>.Empty);
CheckSerialization(PNCounterDictionary<long>.Empty);
CheckSerialization(PNCounterDictionary<IActorRef>.Empty.Increment(_address1, TestActor));
CheckSerialization(PNCounterDictionary<string>.Empty.Increment(_address1, "a", 3));
CheckSerialization(PNCounterDictionary<string>.Empty
.Increment(_address1, "a", 3)
.Decrement(_address2, "a", 2)
.Increment(_address2, "b", 5));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_PNCounterDictionary_delta()
{
CheckSerialization(PNCounterDictionary<string>.Empty.Increment(_address1, "a", 3).Delta);
CheckSerialization(PNCounterDictionary<string>.Empty
.Increment(_address1, "a", 3)
.Decrement(_address2, "a", 2)
.Increment(_address2, "b", 5).Delta);
CheckSerialization(PNCounterDictionary<string>.Empty
.Increment(_address1, "a", 3)
.Decrement(_address2, "a", 2)
.Increment(_address2, "b", 5)
.Remove(_address1, "b").Delta);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_ORMultiDictionary()
{
CheckSerialization(ORMultiValueDictionary<string, string>.Empty);
CheckSerialization(ORMultiValueDictionary<string, string>.Empty.AddItem(_address1, "a", "A"));
CheckSerialization(ORMultiValueDictionary<string, string>.Empty
.AddItem(_address1, "a", "A1")
.SetItems(_address2, "b", ImmutableHashSet.CreateRange(new[] { "B1", "B2", "B3" }))
.AddItem(_address2, "a", "A2"));
var m1 = ORMultiValueDictionary<string, string>.Empty.AddItem(_address1, "a", "A1").AddItem(_address2, "a", "A2");
var m2 = ORMultiValueDictionary<string, string>.Empty.SetItems(_address2, "b", ImmutableHashSet.CreateRange(new[] { "B1", "B2", "B3" }));
CheckSameContent(m1.Merge(m2), m2.Merge(m1));
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_DeletedData()
{
CheckSerialization(DeletedData.Instance);
}
[Fact()]
public void ReplicatedDataSerializer_should_serialize_VersionVector()
{
CheckSerialization(VersionVector.Empty);
CheckSerialization(VersionVector.Create(_address1, 1));
CheckSerialization(VersionVector.Empty.Increment(_address1).Increment(_address2));
var v1 = VersionVector.Empty.Increment(_address1).Increment(_address1);
var v2 = VersionVector.Empty.Increment(_address2);
CheckSameContent(v1.Merge(v2), v2.Merge(v1));
}
[Fact]
public void ReplicatedDataSerializer_should_serialize_Keys()
{
CheckSerialization(new GSetKey<IActorRef>("foo"));
CheckSerialization(new ORSetKey<int>("foo"));
CheckSerialization(new FlagKey("foo"));
CheckSerialization(new PNCounterKey("id"));
CheckSerialization(new GCounterKey("id"));
CheckSerialization(new ORDictionaryKey<IActorRef, LWWRegister<string>>("bar"));
CheckSerialization(new LWWDictionaryKey<IActorRef, string>("bar"));
CheckSerialization(new ORMultiValueDictionaryKey<IActorRef, string>("bar"));
}
private void CheckSerialization<T>(T expected)
{
var serializer = Sys.Serialization.FindSerializerFor(expected);
serializer.Should().BeOfType<ReplicatedDataSerializer>();
var manifest = Akka.Serialization.Serialization.ManifestFor(serializer, expected);
var blob = serializer.ToBinary(expected);
var actual = Sys.Serialization.Deserialize(blob, serializer.Identifier, manifest);
// we cannot use Assert.Equal here since ORMultiDictionary will be resolved as
// IEnumerable<KeyValuePair<string, ImmutableHashSet<string>> and immutable sets
// fails on structural equality
expected.Equals(actual).Should().BeTrue($"Expected actual [{actual}] to be [{expected}]");
}
private void CheckSameContent(object a, object b)
{
// we cannot use Assert.Equal here since ORMultiDictionary will be resolved as
// IEnumerable<KeyValuePair<string, ImmutableHashSet<string>> and immutable sets
// fails on structural equality
Assert.True(a.Equals(b));
var serializer = Sys.Serialization.FindSerializerFor(a);
var blobA = serializer.ToBinary(a);
var blobB = serializer.ToBinary(b);
Assert.Equal(blobA.Length, blobB.Length);
for (int i = 0; i < blobA.Length; i++)
Assert.Equal(blobA[i], blobB[i]);
}
}
}
| 49.649485 | 157 | 0.629499 | [
"Apache-2.0"
] | Walle-Li/akka.net | src/contrib/cluster/Akka.DistributedData.Tests/Serialization/ReplicatedDataSerializerSpec.cs | 14,450 | 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 MO.Scout.Face.Logic
{
/// <summary>
/// WInvoker.xaml 的交互逻辑
/// </summary>
public partial class WInvoker : UserControl
{
public WInvoker() {
InitializeComponent();
}
}
}
| 21.535714 | 46 | 0.733002 | [
"Apache-2.0"
] | favedit/MoCross | Utiliy/Profiler/MoScout/Face/Logic/WInvoker.xaml.cs | 615 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SNSPED
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
public static bool skipTextChange = false;
private void Form3_Load(object sender, EventArgs e)
{
skipTextChange = true;
textBox1.Text = Form1.dither_factor.ToString();
if (Form1.f3_cb1 == false)
{
checkBox1.Checked = false;
}
else
{
checkBox1.Checked = true;
}
skipTextChange = false;
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
Form1.close_it3();
}
private void checkBox1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == false)
{
Form1.f3_cb1 = false;
}
else
{
Form1.f3_cb1 = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (skipTextChange == true) return;
string str = textBox1.Text;
if (str == "") return;
skipTextChange = true;
int value = 0;
int.TryParse(str, out value);
if (value > 12) value = 12; // max value
if (value < 0) value = 0; // min value
str = value.ToString();
textBox1.Text = str;
Form1.dither_factor = value;
skipTextChange = false;
}
}
}
| 24.053333 | 75 | 0.511086 | [
"MIT"
] | nesdoug/SPEZ | SNSPED/Form3.cs | 1,806 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace MaestroApp.Migrations
{
public partial class cambioTablas4 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.555556 | 71 | 0.670659 | [
"MIT"
] | dviltres18/MaestroApp | aspnet-core/src/MaestroApp.EntityFrameworkCore/Migrations/20190710050652_cambioTablas4.cs | 336 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PrismaWEB.Models
{
using System;
using System.Collections.Generic;
public partial class database_firewall_rules
{
public int id { get; set; }
public string name { get; set; }
public string start_ip_address { get; set; }
public string end_ip_address { get; set; }
public System.DateTime create_date { get; set; }
public System.DateTime modify_date { get; set; }
}
}
| 34.88 | 85 | 0.540138 | [
"MIT"
] | LeonardoVanelli/PrismaWeb | PrismaWEB/Models/database_firewall_rules.cs | 872 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BeyondThemes.BeyondAdmin
{
using System;
using System.Collections.Generic;
public partial class Glo_Estados
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Glo_Estados()
{
this.Dir_Empresas = new HashSet<Dir_Empresas>();
this.Dir_Establecimientos = new HashSet<Dir_Establecimientos>();
this.Dir_EstablecimientosTemporales = new HashSet<Dir_EstablecimientosTemporales>();
}
public int IdEstado { get; set; }
public string GlosaEstado { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Dir_Empresas> Dir_Empresas { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Dir_Establecimientos> Dir_Establecimientos { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Dir_EstablecimientosTemporales> Dir_EstablecimientosTemporales { get; set; }
}
}
| 48.277778 | 128 | 0.657077 | [
"Apache-2.0"
] | simadine/simad | BeyondThemes.BeyondAdmin/Glo_Estados.cs | 1,738 | C# |
using System;
namespace PluggablePersistenceLayer.Core {
public class Dataset {
public Type Type { get; }
public string Name { get; }
public Dataset(Type type) {
Type = type;
Name = type.Name;
}
public Dataset(Type type, string name) {
Type = type;
Name = name;
}
}
} | 21.277778 | 48 | 0.498695 | [
"MIT"
] | joseantmazonsb/ppl | Core/Dataset.cs | 385 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_Firewalls_Patch_sync_flattened]
using Google.Cloud.Compute.V1;
using lro = Google.LongRunning;
public sealed partial class GeneratedFirewallsClientSnippets
{
/// <summary>Snippet for Patch</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void Patch()
{
// Create client
FirewallsClient firewallsClient = FirewallsClient.Create();
// Initialize request argument(s)
string project = "";
string firewall = "";
Firewall firewallResource = new Firewall();
// Make the request
lro::Operation<Operation, Operation> response = firewallsClient.Patch(project, firewall, firewallResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
}
}
// [END compute_v1_generated_Firewalls_Patch_sync_flattened]
}
| 42.4 | 119 | 0.669025 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/FirewallsClient.PatchSnippet.g.cs | 2,544 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Trackable.Common;
namespace Trackable.Models
{
[Serializable]
public class Trip : ModelBase<int>
{
/// <summary>
/// The date time at which this trip was created
/// </summary>
public DateTime CreatedAtUtc { get; set; }
/// <summary>
/// The trip's starting Location ID.
/// </summary>
[Mutable]
public string StartLocationId { get; set; }
/// <summary>
/// The trip's ending Location ID.
/// </summary>
[Mutable]
public string EndLocationId { get; set; }
public Location StartLocation { get; set; }
public Location EndLocation { get; set; }
/// <summary>
/// The id of the asset that made this trip.
/// </summary>
[Mutable]
public string AssetId { get; set; }
/// <summary>
/// The id of the tracking device that recorded this trip.
/// </summary>
[Mutable]
public string TrackingDeviceId { get; set; }
/// <summary>
/// The starting time of the trip in UTC.
/// </summary>
[Mutable]
public DateTime StartTimeUtc { get; set; }
/// <summary>
/// The ending time of the trip in UTC.
/// </summary>
[Mutable]
public DateTime EndTimeUtc { get; set; }
/// <summary>
/// The trip legs that constitute this trip.
/// </summary>
public IEnumerable<TripLeg> TripLegs { get; set; }
/// <summary>
/// Gets the duration of the trip in minutes
/// </summary>
public double DurationInMinutes => this.EndTimeUtc.Subtract(this.StartTimeUtc).TotalMinutes;
/// <summary>
/// Gets the start UTC time-stamp.
/// </summary>
public long StartTimeStampUtc => DateTimeUtils.ToUnixTime(StartTimeUtc);
}
}
| 27.635135 | 100 | 0.559902 | [
"MIT"
] | Microsoft/Bing-Maps-Fleet-Tracker | Backend/src/Trackable.Models/Trip.cs | 2,045 | C# |
using HttpClientMock.Test.Utility;
using NUnit.Framework;
using System.Net.Http;
namespace Tests
{
public class ValueCodeResponseTest
{
private HttpClientDependentClass _httpClientDependentClass;
private HttpClient _mockedHttpClient;
[SetUp]
public void Setup()
{
_mockedHttpClient = HttpClientMock.HttpClientMock.GetMockedHttpClient("Hello Mr. Walrus", System.Net.HttpStatusCode.OK);
_httpClientDependentClass = new HttpClientDependentClass(_mockedHttpClient);
}
[Test]
public void GetStringAsyncReturns()
{
var returnValue = _httpClientDependentClass.GetStringAsync();
Assert.AreEqual("Hello Mr. Walrus", returnValue);
}
[Test]
public void GetAsyncReturns()
{
var returnValue = _httpClientDependentClass.GetAsync();
Assert.AreEqual("Hello Mr. Walrus", returnValue);
}
[Test]
public void GetReponseReturnsOk()
{
var returnValue = _httpClientDependentClass.GetResponseMessage();
Assert.IsTrue(returnValue.IsSuccessStatusCode);
Assert.AreEqual(System.Net.HttpStatusCode.OK, returnValue.StatusCode);
Assert.AreEqual("Hello Mr. Walrus", returnValue.Content.ReadAsStringAsync().Result);
}
[TestCase(System.Net.HttpStatusCode.Ambiguous)]
[TestCase(System.Net.HttpStatusCode.BadGateway)]
[TestCase(System.Net.HttpStatusCode.BadRequest)]
[TestCase(System.Net.HttpStatusCode.Conflict)]
[TestCase(System.Net.HttpStatusCode.ExpectationFailed)]
[TestCase(System.Net.HttpStatusCode.Forbidden)]
[TestCase(System.Net.HttpStatusCode.GatewayTimeout)]
[TestCase(System.Net.HttpStatusCode.Gone)]
[TestCase(System.Net.HttpStatusCode.HttpVersionNotSupported)]
[TestCase(System.Net.HttpStatusCode.InternalServerError)]
[TestCase(System.Net.HttpStatusCode.MethodNotAllowed)]
[TestCase(System.Net.HttpStatusCode.MovedPermanently)]
[TestCase(System.Net.HttpStatusCode.NotFound)]
[TestCase(System.Net.HttpStatusCode.Unauthorized)]
public void GetReponseReturnsBadStatus(System.Net.HttpStatusCode statusCodeIn)
{
_mockedHttpClient = HttpClientMock.HttpClientMock.GetMockedHttpClient("Bad Requst", statusCodeIn);
_httpClientDependentClass = new HttpClientDependentClass(_mockedHttpClient);
var returnValue = _httpClientDependentClass.GetResponseMessage();
Assert.IsTrue(!returnValue.IsSuccessStatusCode);
Assert.AreEqual(statusCodeIn, returnValue.StatusCode);
Assert.AreEqual("Bad Requst", returnValue.Content.ReadAsStringAsync().Result);
}
}
} | 41.910448 | 132 | 0.690171 | [
"MIT"
] | marthurIntersys/HttpClientMock | src/HttpClientMock/HttpClientMock.Test/ValueCodeResponseTest.cs | 2,808 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerShoot : MonoBehaviour {
[SerializeField] float fireRate = 1f;
[SerializeField] GameObject projectilePrefab = null;
[SerializeField] AudioClip shootSound = null;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] int scoreDecreasePerShoot = 10;
private GameObject projectileParent;
private bool shootCoroutineRunning;
private AudioSource audioSource;
private PlayerStatController playerStatController;
void Start() {
playerStatController = GetComponent<PlayerStatController>();
audioSource = GetComponent<AudioSource>();
projectileParent = GameObject.Find(PredefinedStrings.PARENT_OBJECT_PROJECTILE);
if (!projectileParent) {
projectileParent = new GameObject(PredefinedStrings.PARENT_OBJECT_PROJECTILE);
}
}
void Update() {
Shoot();
}
private void Shoot() {
if (CrossPlatformInputManager.GetButtonDown("Fire1") && !shootCoroutineRunning) {
StartCoroutine(ShootContinuously());
}
}
private IEnumerator ShootContinuously() {
shootCoroutineRunning = true;
do {
var projectile = Instantiate(projectilePrefab, transform.position, Quaternion.identity, projectileParent.transform);
projectile.GetComponent<Rigidbody2D>().velocity = Vector2.up * projectileSpeed;
audioSource.PlayOneShot(shootSound);
playerStatController.DecreaseScore(scoreDecreasePerShoot);
yield return new WaitForSeconds(fireRate);
} while (CrossPlatformInputManager.GetButton("Fire1"));
shootCoroutineRunning = false;
}
}
| 35.254902 | 128 | 0.708009 | [
"Apache-2.0"
] | vadym-vasilyev/star-rage | Assets/Scripts/Player/PlayerShoot.cs | 1,800 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Protocols.TestSuites.ActiveDirectory.Lsat
{
/// <summary>
/// The LSA_UNICODE_STRING structure specifies the unicode string of LSA names.
/// </summary>
public partial struct _LSA_UNICODE_STRING
{
/// <summary>
/// The length of LSA unicode string.
/// </summary>
public ushort Length;
/// <summary>
/// The max length of LSA unicode string.
/// </summary>
public ushort MaximumLength;
/// <summary>
/// The value of LSA unicode string.
/// </summary>
public ushort[] Buffer;
}
}
| 28.666667 | 101 | 0.614987 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | TestSuites/ADFamily/src/Adapter/MS-LSAT/Struct/LsatStruct.cs | 774 | C# |
using System;
using System.Threading.Tasks;
using Android.Views;
using Android.Widget;
using Microsoft.Maui.Handlers;
namespace Microsoft.Maui.DeviceTests
{
public partial class ActivityIndicatorHandlerTests
{
ProgressBar GetNativeActivityIndicator(ActivityIndicatorHandler activityIndicatorHandler) =>
(ProgressBar)activityIndicatorHandler.View;
bool GetNativeIsRunning(ActivityIndicatorHandler activityIndicatorHandler) =>
GetNativeActivityIndicator(activityIndicatorHandler).Visibility == ViewStates.Visible;
Task ValidateColor(IActivityIndicator activityIndicator, Color color, Action action = null) =>
ValidateHasColor(activityIndicator, color, action);
Task ValidateHasColor(IActivityIndicator activityIndicator, Color color, Action action = null)
{
return InvokeOnMainThreadAsync(() =>
{
var nativeActivityIndicator = GetNativeActivityIndicator(CreateHandler(activityIndicator));
action?.Invoke();
nativeActivityIndicator.AssertContainsColor(color);
});
}
}
} | 33.866667 | 96 | 0.808071 | [
"MIT"
] | Eilon/maui | src/Core/tests/DeviceTests/Handlers/ActivityIndicator/ActivityIndicatorHandlerTests.Android.cs | 1,018 | 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("07_NumbersCountsInArray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07_NumbersCountsInArray")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("fe4ce182-9ff6-4a80-aa6c-4868d491a39d")]
// 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.351351 | 84 | 0.749119 | [
"MIT"
] | razsilev/TelerikAcademy_Homework | Algorithms data structures/02_Linear-Data-Structures/Linear_Data_Structures/07_NumbersCountsInArray/Properties/AssemblyInfo.cs | 1,422 | C# |
// ReSharper disable InconsistentNaming
using System.Net;
using Solitons.Net;
using Xunit;
namespace Solitons
{
public sealed class IpAddressComparer_Compare_Should
{
[Fact]
public void Work()
{
var target = IpAddressComparer.Instance;
Assert.Equal(0, target.Compare(IPAddress.Parse("204.120.0.10"), IPAddress.Parse("204.120.0.10")));
Assert.True(target.Compare(IPAddress.Parse("204.120.0.15"), IPAddress.Parse("204.120.0.10")) > 0);
Assert.True(target.Compare(IPAddress.Parse("204.120.0.10"), IPAddress.Parse("204.120.0.15")) < 0);
}
}
}
| 30.190476 | 110 | 0.635647 | [
"MIT"
] | AlexeyEvlampiev/Solitons.Core | test/Solitons.Core.XUnitTest/IpAddressComparer_Compare_Should.cs | 636 | C# |
using System;
using System.Globalization;
using System.Threading.Tasks;
using SpeedTestLogger.Models;
namespace SpeedTestLogger
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello SpeedTestLogger!");
var config = new LoggerConfiguration();
var runner = new SpeedTestRunner(config.LoggerLocation);
var testData = runner.RunSpeedTest();
var results = new TestResult
{
SessionId = new Guid(),
User = config.UserId,
Device = config.LoggerId,
Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
Data = testData
};
var success = false;
using (var client = new SpeedTestApiClient(config.ApiUrl))
{
success = await client.PublishTestResult(results);
}
if (success)
{
Console.WriteLine("Speedtest complete!");
}
else
{
Console.WriteLine("Speedtest failed!");
}
}
}
}
| 27.795455 | 73 | 0.498774 | [
"MIT"
] | cloud-101-testuser/az-speedtest-logger | SpeedTestLogger/Program.cs | 1,225 | C# |
using GalvanizedSoftware.Beethoven.Core.Methods.MethodMatchers;
using System;
using System.Linq;
using System.Reflection;
namespace GalvanizedSoftware.Beethoven.Extensions
{
internal static class MethodMatcherExtensions
{
public static bool IsMatchToFlowControlled(this IMethodMatcher methodMatcher, (Type, string)[] parameterTypeAndNames,
Type[] genericArguments, Type returnType) =>
methodMatcher.IsMatchCheck(parameterTypeAndNames?.AppendReturnValue(returnType)?.ToArray(),
genericArguments,
typeof(bool).MakeByRefType());
public static bool IsNonGenericMatch(this IMethodMatcher methodMatcher, MethodInfo methodInfo) =>
methodMatcher.IsMatchCheck(methodInfo.GetParameterTypeAndNames(),
Array.Empty<Type>(),
methodInfo?.ReturnType);
public static bool IsMatchIgnoreGeneric(this IMethodMatcher methodMatcher, MethodInfo methodInfo) =>
methodMatcher.IsMatchEitherType(methodInfo.GetParameterTypeAndNames(),
null, methodInfo?.ReturnType.RemoveGeneric());
public static bool IsMatchIgnoreGeneric(this IMethodMatcher methodMatcher, MethodInfo methodInfo, string name) =>
name == methodInfo?.Name && methodMatcher.IsMatchIgnoreGeneric(methodInfo);
public static bool IsMatchEitherType(this IMethodMatcher methodMatcher,
(Type, string)[] parameters, Type[] genericArguments, Type returnType) =>
!returnType.IsByRefence() &&
methodMatcher != null &&
(methodMatcher.IsMatchCheck(parameters, genericArguments, returnType) ||
methodMatcher.IsMatchToFlowControlled(parameters, genericArguments, returnType));
public static bool IsMatchCheck(this IMethodMatcher methodMatcher, (Type, string)[] parameterTypeAndNames,
Type[] genericArguments, Type returnType) =>
methodMatcher?.IsMatch(parameterTypeAndNames, genericArguments, returnType) == true;
}
}
| 47.275 | 121 | 0.768377 | [
"Apache-2.0"
] | GalvanizedSoftware/Beethoven | GalvanizedBeethoven/Extensions/MethodMatcherExtensions.cs | 1,893 | C# |
using Core.Repository.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Core.Data.Entitys.Security;
namespace Core.Repository.Data
{
public class AuthContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
public AuthContext(DbContextOptions<AuthContext> options) : base(options)
{
}
public DbSet<Token> Tokens { set; get; }
}
}
| 27.235294 | 88 | 0.734341 | [
"MIT"
] | zolgera/Onion.Core.Repository | Data/AuthContext.cs | 465 | C# |
using System.IO;
namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{
public class CtorDtorNameType : ParentNode
{
private bool IsDestructor;
public CtorDtorNameType(BaseNode Name, bool IsDestructor) : base(NodeType.CtorDtorNameType, Name)
{
this.IsDestructor = IsDestructor;
}
public override void PrintLeft(TextWriter Writer)
{
if (IsDestructor)
{
Writer.Write("~");
}
Writer.Write(Child.GetName());
}
}
} | 23.166667 | 105 | 0.573741 | [
"Unlicense"
] | simonmkwii-dev/Ryujinx | Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs | 556 | C# |
using System;
using Xunit;
namespace ERPForServiceActivity.Tests {
public class UnitTest1 {
[Fact]
public void Test1() {
}
}
}
| 11.416667 | 39 | 0.693431 | [
"MIT"
] | ALMLAMBO/ERP-for-service-activity | Second-version/ERPForServiceActivity/ERPForServiceActivity.Tests/UnitTest1.cs | 137 | C# |
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Microsoft.FamilyShow.Services;
public interface IAppConfiguration : INotifyPropertyChanged
{
ReadOnlyCollection<string> RecentFiles { get; }
ReadOnlyDictionary<string, string> Skins { get; }
string ExportPath { get; }
void LoadRecentFiles();
void PushRecentFile(string filename);
void SaveRecentFiles();
void SaveSkinSetting(string skin);
}
| 28.0625 | 59 | 0.761693 | [
"MIT"
] | VincentH-Net/FamilyShow2022 | src/Microsoft.FamilyShow/Services/IAppConfiguration.cs | 451 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using LeaguePackets.Game.Common;
namespace LeaguePackets.Game
{
public class WaypointListHeroWithSpeed : GamePacket // 0x83
{
public override GamePacketID ID => GamePacketID.WaypointListHeroWithSpeed;
public int SyncID { get; set; }
public SpeedParams WaypointSpeedParams { get; set; } = new SpeedParams();
public List<Vector2> Waypoints { get; set; } = new List<Vector2>();
protected override void ReadBody(ByteReader reader)
{
this.SyncID = reader.ReadInt32();
this.WaypointSpeedParams = reader.ReadWaypointSpeedParams();
while(reader.BytesLeft >= 8)
{
Vector2 waypoint = reader.ReadVector2();
this.Waypoints.Add(waypoint);
}
}
protected override void WriteBody(ByteWriter writer)
{
writer.WriteInt32(SyncID);
writer.WriteWaypointSpeedParams(WaypointSpeedParams);
foreach(var waypoint in Waypoints)
{
writer.WriteVector2(waypoint);
}
}
}
}
| 30.071429 | 82 | 0.625495 | [
"Apache-2.0"
] | JanDevDE/LeaguePackets | LeaguePackets/Game/131_WaypointListHeroWithSpeed.cs | 1,265 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.Azure;
namespace Microsoft.Azure.Management.SiteRecovery.Models
{
/// <summary>
/// A standard service response for long running operations.
/// </summary>
public partial class LongRunningOperationResponse : AzureOperationResponse
{
private string _asyncOperation;
/// <summary>
/// Optional. The async operation url.
/// </summary>
public string AsyncOperation
{
get { return this._asyncOperation; }
set { this._asyncOperation = value; }
}
private string _location;
/// <summary>
/// Optional. The location url for the get request.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private int? _retryAfter;
/// <summary>
/// Optional. The retry after time in seconds.
/// </summary>
public int? RetryAfter
{
get { return this._retryAfter; }
set { this._retryAfter = value; }
}
private OperationStatus _status;
/// <summary>
/// Optional. Status of the operation.
/// </summary>
public OperationStatus Status
{
get { return this._status; }
set { this._status = value; }
}
/// <summary>
/// Initializes a new instance of the LongRunningOperationResponse
/// class.
/// </summary>
public LongRunningOperationResponse()
{
}
}
}
| 28.965116 | 78 | 0.591329 | [
"Apache-2.0"
] | ailn/azure-sdk-for-net | src/ResourceManagement/SiteRecovery/SiteRecoveryManagement/Generated/Models/LongRunningOperationResponse.cs | 2,491 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Win32;
using Au.Types;
namespace Au.Compiler
{
static partial class Compiler
{
/// <summary>
/// Resolves whether need to [re]compile or can run previously compiled assembly.
/// </summary>
unsafe class XCompiled
{
FilesModel _coll;
string _file;
Dictionary<uint, string> _data;
public string CacheDirectory { get; }
public static XCompiled OfCollection(FilesModel coll)
{
var cc = coll.CompilerContext;
if(cc == null) coll.CompilerContext = cc = new XCompiled(coll);
return cc as XCompiled;
}
public XCompiled(FilesModel coll)
{
_coll = coll;
CacheDirectory = _coll.WorkspaceDirectory + @"\.compiled";
_file = CacheDirectory + @"\compiled.log";
}
/// <summary>
/// Called before executing script f. If returns true, don't need to compile.
/// </summary>
/// <param name="f"></param>
/// <param name="r">Receives file path and execution options.</param>
/// <param name="projFolder">Project folder or null. If not null, f must be its main file.</param>
public bool IsCompiled(FileNode f, out CompResults r, FileNode projFolder)
{
r = new CompResults();
if(_data == null && !_Open()) return false;
if(!_data.TryGetValue(f.Id, out string value)) return false;
//ADebug.Print(value);
int iPipe = 0;
bool isScript = f.IsScript;
r.role = MetaComments.DefaultRole(isScript);
string asmFile;
if(r.notInCache = (value != null && value.Starts("|="))) {
iPipe = value.IndexOf('|', 2); if(iPipe < 0) iPipe = value.Length;
asmFile = value.Substring(2, iPipe - 2);
} else asmFile = CacheDirectory + "\\" + f.IdString;
//AOutput.Write(asmFile);
if(!AFile.GetProperties(asmFile, out var asmProp, FAFlags.UseRawPath)) return false;
DateTime asmDate = asmProp.LastWriteTimeUtc;
if(_IsFileModified(f)) return false;
bool isMultiFileProject = false;
if(value != null && iPipe < value.Length) {
iPipe++;
foreach(var v in value.Segments("|", SegFlags.NoEmpty, iPipe..)) {
int offs = v.start + 1;
char ch = value[v.start];
switch(ch) {
case 't':
r.role = (ERole)value.ToInt(offs);
break;
case 'a':
r.runMode = (ERunMode)value.ToInt(offs);
break;
case 'n':
r.ifRunning = (EIfRunning)value.ToInt(offs);
break;
case 'N':
r.ifRunning2 = (EIfRunning2)value.ToInt(offs);
break;
case 'u':
r.uac = (EUac)value.ToInt(offs);
break;
case 'b':
r.prefer32bit = true;
break;
case 'q':
r.console = true;
break;
case 'z':
r.mtaThread = true;
break;
case 'd':
r.pdbOffset = value.ToInt(offs);
break;
case 'p':
isMultiFileProject = true;
if(projFolder != null) {
if(!Util.AHash.MD5Result.FromString(value.AsSpan(offs, v.end - offs), out var md5)) return false;
Util.AHash.MD5 md = default;
foreach(var f1 in projFolder.EnumProjectClassFiles(f)) {
if(_IsFileModified(f1)) return false;
md.Add(f1.Id);
}
if(md.IsEmpty || md.Hash != md5) return false;
}
break;
case '*':
var dll = value[offs..v.end];
if(!APath.IsFullPath(dll)) dll = AFolders.ThisApp + dll;
if(_IsFileModified2(dll)) return false;
r.AddToFullPathRefsIfNeed(dll);
break;
case 'l':
case 'c':
case 'x':
case 'k':
case 'm':
case 'y':
case 's':
//case 'o':
value.ToInt(out uint u1, offs);
var f2 = _coll.FindById(u1);
if(f2 == null) return false;
if(ch == 'l') {
if(f2.FindProject(out var projFolder2, out var projMain2)) f2 = projMain2;
if(f2 == f) return false; //will be compiler error "circular reference"
//AOutput.Write(f2, projFolder2);
if(!IsCompiled(f2, out _, projFolder2)) return false;
//AOutput.Write("library is compiled");
} else {
if(_IsFileModified(f2)) return false;
//switch(ch) {
//case 'o': //f2 is the source config file
// r.hasConfig = true;
// break;
//}
}
break;
default: return false;
}
}
}
if(isMultiFileProject != (projFolder != null)) {
if(projFolder == null) return false;
foreach(var f1 in projFolder.EnumProjectClassFiles(f)) return false; //project with single file?
}
//ADebug.Print("compiled");
r.file = asmFile;
r.name = APath.GetFileName(f.Name, true);
return true;
bool _IsFileModified(FileNode f_) => _IsFileModified2(f_.FilePath);
bool _IsFileModified2(string path_)
{
if(!AFile.GetProperties(path_, out var prop_, FAFlags.UseRawPath)) return true;
//AOutput.Write(prop_.LastWriteTimeUtc, asmDate);
if(prop_.LastWriteTimeUtc > asmDate) return true;
return false;
}
}
/// <summary>
/// Called when successfully compiled script f. Saves data that next time will be used by <see cref="IsCompiled"/>.
/// </summary>
/// <param name="f"></param>
/// <param name="outFile">The output assembly.</param>
/// <param name="m"></param>
/// <param name="pdbOffset"></param>
/// <param name="mtaThread">No [STAThread].</param>
public void AddCompiled(FileNode f, string outFile, MetaComments m, int pdbOffset, bool mtaThread)
{
if(_data == null) {
_data = new Dictionary<uint, string>();
}
/*
IDmain|=path.exe|tN|aN|nN|NN|uN|b|q|z|dN|pMD5project|cIDcode|lIDlibrary|xIDresource|kIDicon|mIDmanifest|yIDres|sIDsign|oIDconfig|*ref
= - outFile
t - role
a - runMode
n - ifRunning
N - ifRunning2
u - uac
b - prefer32bit
q - console
z - mtaThread
d - pdbOffset
p - MD5 of Id of all project files except main
c - c
l - pr
x - resource
k - icon
m - manifest
y - res
s - sign
o - config (now removed)
* - r
*/
string value = null;
using(new Util.StringBuilder_(out var b)) {
if(m.OutputPath != null) b.Append("|=").Append(outFile); //else f.Id in cache
if(m.Role != MetaComments.DefaultRole(m.IsScript)) b.Append("|t").Append((int)m.Role);
if(m.RunMode != default) b.Append("|a").Append((int)m.RunMode);
if(m.IfRunning != default) b.Append("|n").Append((int)m.IfRunning);
if(m.IfRunning2 != default) b.Append("|N").Append((int)m.IfRunning2);
if(m.Uac != default) b.Append("|u").Append((int)m.Uac);
if(m.Prefer32Bit) b.Append("|b");
if(m.Console) b.Append("|q");
if(mtaThread) b.Append("|z");
if(pdbOffset != 0) b.Append("|d").Append(pdbOffset);
int nAll = m.CodeFiles.Count, nNoC = nAll - m.CountC;
if(nNoC > 1) { //add MD5 hash of project files, except main
Util.AHash.MD5 md = default;
for(int i = 1; i < nNoC; i++) md.Add(m.CodeFiles[i].f.Id);
b.Append("|p").Append(md.Hash.ToString());
}
for(int i = nNoC; i < nAll; i++) _AppendFile("|c", m.CodeFiles[i].f); //ids of C# files added through meta 'c'
if(m.ProjectReferences != null) foreach(var v in m.ProjectReferences) _AppendFile("|l", v); //ids of meta 'pr' files
if(m.Resources != null) foreach(var v in m.Resources) _AppendFile("|x", v.f); //ids of meta 'resource' files
_AppendFile("|k", m.IconFile);
_AppendFile("|m", m.ManifestFile);
_AppendFile("|y", m.ResFile);
_AppendFile("|s", m.SignFile);
//_AppendFile("|o", m.ConfigFile);
//references
var refs = m.References.Refs;
int j = MetaReferences.DefaultReferences.Count;
if(refs.Count > j) {
string appDir = AFolders.ThisAppBS;
for(; j < refs.Count; j++) {
var s1 = refs[j].FilePath;
if(s1.Starts(appDir, true)) s1 = s1.Substring(appDir.Length);
b.Append("|*").Append(s1);
}
}
if(b.Length != 0) value = b.ToString();
void _AppendFile(string opt, FileNode f_)
{
if(f_ != null) b.Append(opt).Append(f_.IdString);
}
}
uint id = f.Id;
if(_data.TryGetValue(id, out var oldValue) && value == oldValue) { /*ADebug.Print("same");*/ return; }
//ADebug.Print("different");
_data[id] = value;
_Save();
}
/// <summary>
/// Removes saved f data, so that next time <see cref="IsCompiled"/> will return false.
/// </summary>
public void Remove(FileNode f, bool deleteAsmFile)
{
if(_data == null && !_Open()) return;
if(_data.Remove(f.Id)) {
_Save();
if(deleteAsmFile) {
try { AFile.Delete(CacheDirectory + "\\" + f.IdString); }
catch(Exception ex) { ADebug.Print(ex); }
}
}
}
bool _Open()
{
if(_data != null) return true;
if(!AFile.ExistsAsFile(_file)) return false;
string sData = AFile.LoadText(_file);
foreach(var v in sData.Segments(SegSep.Line, SegFlags.NoEmpty)) {
if(_data == null) {
//first line contains .NET Core version and Au.dll version, like 3.1.0|1.2.3.4
if(sData[v.start..v.end] != s_coreAuVersions) goto g1;
_data = new Dictionary<uint, string>(sData.LineCount());
continue;
}
sData.ToInt(out uint id, v.start, out int idEnd);
Debug.Assert(null != _coll.FindById(id));
_data[id] = v.end > idEnd ? sData[idEnd..v.end] : null;
}
if(_data == null) return false; //empty file
return true;
g1:
_ClearCache();
return false;
}
static string s_coreAuVersions = Environment.Version.ToString() + "|" + typeof(AWnd).Assembly.GetName().Version.ToString();
void _Save()
{
AFile.CreateDirectory(CacheDirectory);
using(var b = AFile.WaitIfLocked(() => File.CreateText(_file))) {
b.WriteLine(s_coreAuVersions);
foreach(var v in _data) {
if(v.Value == null) b.WriteLine(v.Key); else { b.Write(v.Key); b.WriteLine(v.Value); }
}
//tested: fast, same speed as StringBuilder+WriteAllText. With b.WriteLine(v.Key+v.Value) same speed or slower.
}
}
void _ClearCache()
{
_data = null;
try { AFile.Delete(CacheDirectory); }
catch(AuException e) { AWarning.Write(e.ToString(), -1); }
}
}
public static void OnFileDeleted(FilesModel coll, FileNode f)
{
XCompiled.OfCollection(coll).Remove(f, true);
}
}
}
| 31.121302 | 134 | 0.610419 | [
"MIT"
] | alexfordc/Au | _Au.Editor/Compiler/XCompiled.cs | 10,519 | C# |
using DGP.Genshin.Data.Weapon;
using System;
using System.Globalization;
using System.Windows.Data;
namespace DGP.Genshin.Controls.Converters
{
public class WeaponTypeToNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((WeaponType)value) switch
{
WeaponType.Sword => "单手剑",
WeaponType.Claymore => "双手剑",
WeaponType.Polearm => "长柄武器",
WeaponType.Bow => "弓",
WeaponType.Catalyst => "法器",
_ => "???",
};
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 28.862069 | 103 | 0.574671 | [
"MIT"
] | Klee233/Snap.Genshin | DGP.Genshin/Controls/Converters/ElementToNameConverter.cs | 865 | C# |
namespace Miki.Framework
{
using System;
public class Mathm
{
public static float Clamp(float value, float min, float max)
{
return Math.Min(Math.Max(value, min), max);
}
public static int Clamp(int value, int min, int max)
{
return Math.Min(Math.Max(value, min), max);
}
public static bool IsEven(int value)
{
return (value & 1) == 0;
}
}
} | 17.545455 | 62 | 0.626943 | [
"MIT"
] | GerardSmit/Miki.Framework | src/Miki.Framework/Extension/Mathm.cs | 388 | C# |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.ObjectModel;
namespace Contoso.Patterns.UI.Forms.SmartFormElements
{
/// <summary>
/// ElementCollection
/// </summary>
public class ElementCollection : KeyedCollection<string, ElementBase>
{
protected override string GetKeyForItem(ElementBase item) { return item.Name; }
}
}
| 39.783784 | 88 | 0.76087 | [
"MIT"
] | Grimace1975/bclcontrib-extend | src/Contoso.CoreEx/Patterns/UI/Forms/SmartFormElements/ElementCollection.cs | 1,472 | 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.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.Xsl.XPath
{
using XPathNodeType = System.Xml.XPath.XPathNodeType;
internal sealed class XPathParser<Node>
{
private XPathScanner? _scanner;
private IXPathBuilder<Node>? _builder;
private readonly Stack<int> _posInfo = new Stack<int>();
// Six possible causes of exceptions in the builder:
// 1. Undefined prefix in a node test.
// 2. Undefined prefix in a variable reference, or unknown variable.
// 3. Undefined prefix in a function call, or unknown function, or wrong number/types of arguments.
// 4. Argument of Union operator is not a node-set.
// 5. First argument of Predicate is not a node-set.
// 6. Argument of Axis is not a node-set.
public Node Parse(XPathScanner scanner, IXPathBuilder<Node> builder, LexKind endLex)
{
Debug.Assert(_scanner == null && _builder == null);
Debug.Assert(scanner != null && builder != null);
Node? result = default(Node);
_scanner = scanner;
_builder = builder;
_posInfo.Clear();
try
{
builder.StartBuild();
result = ParseExpr();
scanner.CheckToken(endLex);
}
catch (XPathCompileException e)
{
if (e.queryString == null)
{
e.queryString = scanner.Source;
PopPosInfo(out e.startChar, out e.endChar);
}
throw;
}
finally
{
result = builder.EndBuild(result);
#if DEBUG
_builder = null;
_scanner = null;
#endif
}
Debug.Assert(_posInfo.Count == 0, "PushPosInfo() and PopPosInfo() calls have been unbalanced");
return result!;
}
#region Location paths and node tests
/**************************************************************************************************/
/* Location paths and node tests */
/**************************************************************************************************/
internal static bool IsStep(LexKind lexKind)
{
return (
lexKind == LexKind.Dot ||
lexKind == LexKind.DotDot ||
lexKind == LexKind.At ||
lexKind == LexKind.Axis ||
lexKind == LexKind.Star ||
lexKind == LexKind.Name // NodeTest is also Name
);
}
/*
* LocationPath ::= RelativeLocationPath | '/' RelativeLocationPath? | '//' RelativeLocationPath
*/
private Node ParseLocationPath()
{
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
Node opnd = _builder!.Axis(XPathAxis.Root, XPathNodeType.All, null, null);
if (IsStep(_scanner.Kind))
{
opnd = _builder.JoinStep(opnd, ParseRelativeLocationPath());
}
return opnd;
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
return _builder!.JoinStep(
_builder.Axis(XPathAxis.Root, XPathNodeType.All, null, null),
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
else
{
return ParseRelativeLocationPath();
}
}
/*
* RelativeLocationPath ::= Step (('/' | '//') Step)*
*/
//Max depth to avoid StackOverflow
private const int MaxParseRelativePathDepth = 1024;
private int _parseRelativePath;
private Node ParseRelativeLocationPath()
{
if (++_parseRelativePath > MaxParseRelativePathDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
Node opnd = ParseStep();
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
--_parseRelativePath;
return opnd;
}
/*
* Step ::= '.' | '..' | (AxisName '::' | '@')? NodeTest Predicate*
*/
private Node ParseStep()
{
Node opnd;
if (LexKind.Dot == _scanner!.Kind)
{ // '.'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Self, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDot);
}
}
else if (LexKind.DotDot == _scanner.Kind)
{ // '..'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Parent, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDotDot);
}
}
else
{ // (AxisName '::' | '@')? NodeTest Predicate*
XPathAxis axis;
switch (_scanner.Kind)
{
case LexKind.Axis: // AxisName '::'
axis = _scanner.Axis;
_scanner.NextLex();
_scanner.NextLex();
break;
case LexKind.At: // '@'
axis = XPathAxis.Attribute;
_scanner.NextLex();
break;
case LexKind.Name:
case LexKind.Star:
// NodeTest must start with Name or '*'
axis = XPathAxis.Child;
break;
default:
throw _scanner.CreateException(SR.XPath_UnexpectedToken, _scanner.RawValue);
}
opnd = ParseNodeTest(axis);
while (LexKind.LBracket == _scanner.Kind)
{
opnd = _builder!.Predicate(opnd, ParsePredicate(), IsReverseAxis(axis));
}
}
return opnd;
}
private static bool IsReverseAxis(XPathAxis axis)
{
return (
axis == XPathAxis.Ancestor || axis == XPathAxis.Preceding ||
axis == XPathAxis.AncestorOrSelf || axis == XPathAxis.PrecedingSibling
);
}
/*
* NodeTest ::= NameTest | ('comment' | 'text' | 'node') '(' ')' | 'processing-instruction' '(' Literal? ')'
* NameTest ::= '*' | NCName ':' '*' | QName
*/
private Node ParseNodeTest(XPathAxis axis)
{
XPathNodeType nodeType;
string? nodePrefix, nodeName;
int startChar = _scanner!.LexStart;
InternalParseNodeTest(_scanner, axis, out nodeType, out nodePrefix, out nodeName);
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Axis(axis, nodeType, nodePrefix, nodeName);
PopPosInfo();
return result;
}
private static bool IsNodeType(XPathScanner scanner)
{
return scanner.Prefix.Length == 0 && (
scanner.Name == "node" ||
scanner.Name == "text" ||
scanner.Name == "processing-instruction" ||
scanner.Name == "comment"
);
}
private static XPathNodeType PrincipalNodeType(XPathAxis axis)
{
return (
axis == XPathAxis.Attribute ? XPathNodeType.Attribute :
axis == XPathAxis.Namespace ? XPathNodeType.Namespace :
/*else*/ XPathNodeType.Element
);
}
internal static void InternalParseNodeTest(XPathScanner scanner, XPathAxis axis, out XPathNodeType nodeType, out string? nodePrefix, out string? nodeName)
{
switch (scanner.Kind)
{
case LexKind.Name:
if (scanner.CanBeFunction && IsNodeType(scanner))
{
nodePrefix = null;
nodeName = null;
switch (scanner.Name)
{
case "comment": nodeType = XPathNodeType.Comment; break;
case "text": nodeType = XPathNodeType.Text; break;
case "node": nodeType = XPathNodeType.All; break;
default:
Debug.Assert(scanner.Name == "processing-instruction");
nodeType = XPathNodeType.ProcessingInstruction;
break;
}
scanner.NextLex();
scanner.PassToken(LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (scanner.Kind != LexKind.RParens)
{ // 'processing-instruction' '(' Literal ')'
scanner.CheckToken(LexKind.String);
// It is not needed to set nodePrefix here, but for our current implementation
// comparing whole QNames is faster than comparing just local names
nodePrefix = string.Empty;
nodeName = scanner.StringValue;
scanner.NextLex();
}
}
scanner.PassToken(LexKind.RParens);
}
else
{
nodePrefix = scanner.Prefix;
nodeName = scanner.Name;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
if (nodeName == "*")
{
nodeName = null;
}
}
break;
case LexKind.Star:
nodePrefix = null;
nodeName = null;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
break;
default:
throw scanner.CreateException(SR.XPath_NodeTestExpected, scanner.RawValue);
}
}
/*
* Predicate ::= '[' Expr ']'
*/
private Node ParsePredicate()
{
_scanner!.PassToken(LexKind.LBracket);
Node opnd = ParseExpr();
_scanner.PassToken(LexKind.RBracket);
return opnd;
}
#endregion
#region Expressions
/**************************************************************************************************/
/* Expressions */
/**************************************************************************************************/
/*
* Expr ::= OrExpr
* OrExpr ::= AndExpr ('or' AndExpr)*
* AndExpr ::= EqualityExpr ('and' EqualityExpr)*
* EqualityExpr ::= RelationalExpr (('=' | '!=') RelationalExpr)*
* RelationalExpr ::= AdditiveExpr (('<' | '>' | '<=' | '>=') AdditiveExpr)*
* AdditiveExpr ::= MultiplicativeExpr (('+' | '-') MultiplicativeExpr)*
* MultiplicativeExpr ::= UnaryExpr (('*' | 'div' | 'mod') UnaryExpr)*
* UnaryExpr ::= ('-')* UnionExpr
*/
private Node ParseExpr()
{
return ParseSubExpr(/*callerPrec:*/0);
}
//Max depth to avoid StackOverflow
//limit the recursive call from ParseSubExpr -> ParseSubExpr
//and also ParseSubExpr->ParseUnionExpr->ParsePathExpr->...->ParseExpr->ParseSubExpr
private const int MaxParseSubExprDepth = 1024;
private int _parseSubExprDepth;
private Node ParseSubExpr(int callerPrec)
{
if (++_parseSubExprDepth > MaxParseSubExprDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
XPathOperator op;
Node opnd;
ReadOnlySpan<byte> xpathOperatorPrecedence = new byte[]
{
/*Unknown */ 0,
/*Or */ 1,
/*And */ 2,
/*Eq */ 3,
/*Ne */ 3,
/*Lt */ 4,
/*Le */ 4,
/*Gt */ 4,
/*Ge */ 4,
/*Plus */ 5,
/*Minus */ 5,
/*Multiply */ 6,
/*Divide */ 6,
/*Modulo */ 6,
/*UnaryMinus */ 7,
/*Union */ 8, // Not used
};
// Check for unary operators
if (_scanner!.Kind == LexKind.Minus)
{
op = XPathOperator.UnaryMinus;
byte opPrec = xpathOperatorPrecedence[(int)op];
_scanner.NextLex();
opnd = _builder!.Operator(op, ParseSubExpr(opPrec), default(Node));
}
else
{
opnd = ParseUnionExpr();
}
// Process binary operators
while (true)
{
op = (_scanner.Kind <= LexKind.LastOperator) ? (XPathOperator)_scanner.Kind : XPathOperator.Unknown;
byte opPrec = xpathOperatorPrecedence[(int)op];
if (opPrec <= callerPrec)
{
break;
}
// Operator's precedence is greater than the one of our caller, so process it here
_scanner.NextLex();
opnd = _builder!.Operator(op, opnd, ParseSubExpr(/*callerPrec:*/opPrec));
}
--_parseSubExprDepth;
return opnd;
}
/*
* UnionExpr ::= PathExpr ('|' PathExpr)*
*/
private Node ParseUnionExpr()
{
int startChar = _scanner!.LexStart;
Node opnd1 = ParsePathExpr();
if (_scanner.Kind == LexKind.Union)
{
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder!.Operator(XPathOperator.Union, default(Node), opnd1);
PopPosInfo();
while (_scanner.Kind == LexKind.Union)
{
_scanner.NextLex();
startChar = _scanner.LexStart;
Node opnd2 = ParsePathExpr();
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder.Operator(XPathOperator.Union, opnd1, opnd2);
PopPosInfo();
}
}
return opnd1;
}
/*
* PathExpr ::= LocationPath | FilterExpr (('/' | '//') RelativeLocationPath )?
*/
private Node ParsePathExpr()
{
// Here we distinguish FilterExpr from LocationPath - the former starts with PrimaryExpr
if (IsPrimaryExpr())
{
int startChar = _scanner!.LexStart;
Node opnd = ParseFilterExpr();
int endChar = _scanner.PrevLexEnd;
if (_scanner.Kind == LexKind.Slash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
PopPosInfo();
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
PopPosInfo();
}
return opnd;
}
else
{
return ParseLocationPath();
}
}
/*
* FilterExpr ::= PrimaryExpr Predicate*
*/
private Node ParseFilterExpr()
{
int startChar = _scanner!.LexStart;
Node opnd = ParsePrimaryExpr();
int endChar = _scanner.PrevLexEnd;
while (_scanner.Kind == LexKind.LBracket)
{
PushPosInfo(startChar, endChar);
opnd = _builder!.Predicate(opnd, ParsePredicate(), /*reverseStep:*/false);
PopPosInfo();
}
return opnd;
}
private bool IsPrimaryExpr()
{
return (
_scanner!.Kind == LexKind.String ||
_scanner.Kind == LexKind.Number ||
_scanner.Kind == LexKind.Dollar ||
_scanner.Kind == LexKind.LParens ||
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner)
);
}
/*
* PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
*/
private Node ParsePrimaryExpr()
{
Debug.Assert(IsPrimaryExpr());
Node opnd;
switch (_scanner!.Kind)
{
case LexKind.String:
opnd = _builder!.String(_scanner.StringValue);
_scanner.NextLex();
break;
case LexKind.Number:
opnd = _builder!.Number(XPathConvert.StringToDouble(_scanner.RawValue));
_scanner.NextLex();
break;
case LexKind.Dollar:
int startChar = _scanner.LexStart;
_scanner.NextLex();
_scanner.CheckToken(LexKind.Name);
PushPosInfo(startChar, _scanner.LexStart + _scanner.LexSize);
opnd = _builder!.Variable(_scanner.Prefix, _scanner.Name);
PopPosInfo();
_scanner.NextLex();
break;
case LexKind.LParens:
_scanner.NextLex();
opnd = ParseExpr();
_scanner.PassToken(LexKind.RParens);
break;
default:
Debug.Assert(
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner),
"IsPrimaryExpr() returned true, but the lexeme is not recognized"
);
opnd = ParseFunctionCall();
break;
}
return opnd;
}
/*
* FunctionCall ::= FunctionName '(' (Expr (',' Expr)* )? ')'
*/
private Node ParseFunctionCall()
{
List<Node> argList = new List<Node>();
string name = _scanner!.Name;
string prefix = _scanner.Prefix;
int startChar = _scanner.LexStart;
_scanner.PassToken(LexKind.Name);
_scanner.PassToken(LexKind.LParens);
if (_scanner.Kind != LexKind.RParens)
{
while (true)
{
argList.Add(ParseExpr());
if (_scanner.Kind != LexKind.Comma)
{
_scanner.CheckToken(LexKind.RParens);
break;
}
_scanner.NextLex(); // move off the ','
}
}
_scanner.NextLex(); // move off the ')'
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Function(prefix, name, argList);
PopPosInfo();
return result;
}
#endregion
/**************************************************************************************************/
/* Helper methods */
/**************************************************************************************************/
private void PushPosInfo(int startChar, int endChar)
{
_posInfo.Push(startChar);
_posInfo.Push(endChar);
}
private void PopPosInfo()
{
_posInfo.Pop();
_posInfo.Pop();
}
private void PopPosInfo(out int startChar, out int endChar)
{
endChar = _posInfo.Pop();
startChar = _posInfo.Pop();
}
}
}
| 37.38843 | 162 | 0.43992 | [
"MIT"
] | ilonatommy/runtime | src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs | 22,620 | C# |
#if ((UNITY_SWITCH || UNITY_XBOXONE || (WINDOWS_UWP && ENABLE_IL2CPP)) && !UNITY_EDITOR) || GS_FORCE_NATIVE_PLATFORM
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace GameSparksNative.detail {
class GameSparksNativePINVOKE {
protected class SWIGExceptionHelper {
public delegate void ExceptionDelegate(string message);
public delegate void ExceptionArgumentDelegate(string message, string paramName);
static ExceptionDelegate applicationDelegate = new ExceptionDelegate(SetPendingApplicationException);
static ExceptionDelegate arithmeticDelegate = new ExceptionDelegate(SetPendingArithmeticException);
static ExceptionDelegate divideByZeroDelegate = new ExceptionDelegate(SetPendingDivideByZeroException);
static ExceptionDelegate indexOutOfRangeDelegate = new ExceptionDelegate(SetPendingIndexOutOfRangeException);
static ExceptionDelegate invalidCastDelegate = new ExceptionDelegate(SetPendingInvalidCastException);
static ExceptionDelegate invalidOperationDelegate = new ExceptionDelegate(SetPendingInvalidOperationException);
static ExceptionDelegate ioDelegate = new ExceptionDelegate(SetPendingIOException);
static ExceptionDelegate nullReferenceDelegate = new ExceptionDelegate(SetPendingNullReferenceException);
static ExceptionDelegate outOfMemoryDelegate = new ExceptionDelegate(SetPendingOutOfMemoryException);
static ExceptionDelegate overflowDelegate = new ExceptionDelegate(SetPendingOverflowException);
static ExceptionDelegate systemDelegate = new ExceptionDelegate(SetPendingSystemException);
static ExceptionArgumentDelegate argumentDelegate = new ExceptionArgumentDelegate(SetPendingArgumentException);
static ExceptionArgumentDelegate argumentNullDelegate = new ExceptionArgumentDelegate(SetPendingArgumentNullException);
static ExceptionArgumentDelegate argumentOutOfRangeDelegate = new ExceptionArgumentDelegate(SetPendingArgumentOutOfRangeException);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="SWIGRegisterExceptionCallbacks_GameSparksNative")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="SWIGRegisterExceptionCallbacks_GameSparksNative")]
#endif
public static extern void SWIGRegisterExceptionCallbacks_GameSparksNative(
ExceptionDelegate applicationDelegate,
ExceptionDelegate arithmeticDelegate,
ExceptionDelegate divideByZeroDelegate,
ExceptionDelegate indexOutOfRangeDelegate,
ExceptionDelegate invalidCastDelegate,
ExceptionDelegate invalidOperationDelegate,
ExceptionDelegate ioDelegate,
ExceptionDelegate nullReferenceDelegate,
ExceptionDelegate outOfMemoryDelegate,
ExceptionDelegate overflowDelegate,
ExceptionDelegate systemExceptionDelegate);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_GameSparksNative")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_GameSparksNative")]
#endif
public static extern void SWIGRegisterExceptionCallbacksArgument_GameSparksNative(
ExceptionArgumentDelegate argumentDelegate,
ExceptionArgumentDelegate argumentNullDelegate,
ExceptionArgumentDelegate argumentOutOfRangeDelegate);
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingApplicationException(string message) {
SWIGPendingException.Set(new global::System.ApplicationException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingArithmeticException(string message) {
SWIGPendingException.Set(new global::System.ArithmeticException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingDivideByZeroException(string message) {
SWIGPendingException.Set(new global::System.DivideByZeroException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingIndexOutOfRangeException(string message) {
SWIGPendingException.Set(new global::System.IndexOutOfRangeException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingInvalidCastException(string message) {
SWIGPendingException.Set(new global::System.InvalidCastException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingInvalidOperationException(string message) {
SWIGPendingException.Set(new global::System.InvalidOperationException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingIOException(string message) {
SWIGPendingException.Set(new global::System.IO.IOException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingNullReferenceException(string message) {
SWIGPendingException.Set(new global::System.NullReferenceException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingOutOfMemoryException(string message) {
SWIGPendingException.Set(new global::System.OutOfMemoryException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingOverflowException(string message) {
SWIGPendingException.Set(new global::System.OverflowException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionDelegate))]
static void SetPendingSystemException(string message) {
SWIGPendingException.Set(new global::System.SystemException(message, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionArgumentDelegate))]
static void SetPendingArgumentException(string message, string paramName) {
SWIGPendingException.Set(new global::System.ArgumentException(message, paramName, SWIGPendingException.Retrieve()));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionArgumentDelegate))]
static void SetPendingArgumentNullException(string message, string paramName) {
global::System.Exception e = SWIGPendingException.Retrieve();
if (e != null) message = message + " Inner Exception: " + e.Message;
SWIGPendingException.Set(new global::System.ArgumentNullException(paramName, message));
}
[AOT.MonoPInvokeCallback (typeof (ExceptionArgumentDelegate))]
static void SetPendingArgumentOutOfRangeException(string message, string paramName) {
global::System.Exception e = SWIGPendingException.Retrieve();
if (e != null) message = message + " Inner Exception: " + e.Message;
SWIGPendingException.Set(new global::System.ArgumentOutOfRangeException(paramName, message));
}
static SWIGExceptionHelper() {
SWIGRegisterExceptionCallbacks_GameSparksNative(
applicationDelegate,
arithmeticDelegate,
divideByZeroDelegate,
indexOutOfRangeDelegate,
invalidCastDelegate,
invalidOperationDelegate,
ioDelegate,
nullReferenceDelegate,
outOfMemoryDelegate,
overflowDelegate,
systemDelegate);
SWIGRegisterExceptionCallbacksArgument_GameSparksNative(
argumentDelegate,
argumentNullDelegate,
argumentOutOfRangeDelegate);
}
}
protected static SWIGExceptionHelper swigExceptionHelper = new SWIGExceptionHelper();
public class SWIGPendingException {
[global::System.ThreadStatic]
private static global::System.Exception pendingException = null;
private static int numExceptionsPending = 0;
public static bool Pending {
get {
bool pending = false;
if (numExceptionsPending > 0)
if (pendingException != null)
pending = true;
return pending;
}
}
public static void Set(global::System.Exception e) {
if (pendingException != null)
throw new global::System.ApplicationException("FATAL: An earlier pending exception from unmanaged code was missed and thus not thrown (" + pendingException.ToString() + ")", e);
pendingException = e;
lock(typeof(GameSparksNativePINVOKE)) {
numExceptionsPending++;
}
}
public static global::System.Exception Retrieve() {
global::System.Exception e = null;
if (numExceptionsPending > 0) {
if (pendingException != null) {
e = pendingException;
pendingException = null;
lock(typeof(GameSparksNativePINVOKE)) {
numExceptionsPending--;
}
}
}
return e;
}
}
protected class SWIGStringHelper {
public delegate string SWIGStringDelegate(string message);
static SWIGStringDelegate stringDelegate = new SWIGStringDelegate(CreateString);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="SWIGRegisterStringCallback_GameSparksNative")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="SWIGRegisterStringCallback_GameSparksNative")]
#endif
public static extern void SWIGRegisterStringCallback_GameSparksNative(SWIGStringDelegate stringDelegate);
[AOT.MonoPInvokeCallback (typeof (SWIGStringDelegate))]
static string CreateString(string cString) {
return cString;
}
static SWIGStringHelper() {
SWIGRegisterStringCallback_GameSparksNative(stringDelegate);
}
}
static protected SWIGStringHelper swigStringHelper = new SWIGStringHelper();
static GameSparksNativePINVOKE() {
}
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Result_getType___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Result_getType___")]
#endif
public static extern int NativeWebSocket_Result_getType(global::System.Runtime.InteropServices.HandleRef jarg1);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Result_getMessage___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Result_getMessage___")]
#endif
public static extern string NativeWebSocket_Result_getMessage(global::System.Runtime.InteropServices.HandleRef jarg1);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_delete_NativeWebSocket_Result___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_delete_NativeWebSocket_Result___")]
#endif
public static extern void delete_NativeWebSocket_Result(global::System.Runtime.InteropServices.HandleRef jarg1);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_new_NativeWebSocket___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_new_NativeWebSocket___")]
#endif
public static extern global::System.IntPtr new_NativeWebSocket();
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_delete_NativeWebSocket___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_delete_NativeWebSocket___")]
#endif
public static extern void delete_NativeWebSocket(global::System.Runtime.InteropServices.HandleRef jarg1);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalOpen___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalOpen___")]
#endif
public static extern void NativeWebSocket_GSExternalOpen(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2, string jarg3, string jarg4);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalClose___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalClose___")]
#endif
public static extern void NativeWebSocket_GSExternalClose(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalSend___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GSExternalSend___")]
#endif
public static extern void NativeWebSocket_GSExternalSend(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2, string jarg3);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Update___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_Update___")]
#endif
public static extern bool NativeWebSocket_Update(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
#if (UNITY_IPHONE || UNITY_SWITCH || UNITY_XBOX360) && !UNITY_EDITOR
[global::System.Runtime.InteropServices.DllImport("__Internal", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GetNextResult___")]
#else
[global::System.Runtime.InteropServices.DllImport("GameSparksNative", EntryPoint="CSharp_GameSparksNativefdetail_NativeWebSocket_GetNextResult___")]
#endif
public static extern global::System.IntPtr NativeWebSocket_GetNextResult(global::System.Runtime.InteropServices.HandleRef jarg1);
}
}
#endif | 55.513605 | 185 | 0.744072 | [
"Apache-2.0"
] | UnityEQ/ARMessages | Assets/GameSparks/Platforms/Native/detail/GameSparksNativePINVOKE.cs | 16,321 | C# |
using CsvGnome.Components;
using CsvGnome.Fields;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvGnome;
namespace CsvGnomeTests
{
[TestClass]
public class InterpreterTest
{
[TestMethod]
public void InterpretEmpty()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(String.Empty), CsvGnome.Action.Continue);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretExit()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("exit"), CsvGnome.Action.Exit);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretRun()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("run"), CsvGnome.Action.Run);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretWrite()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("write"), CsvGnome.Action.Write);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretHelp()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("help"), CsvGnome.Action.Help);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretHelpSpecial()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("help special"), CsvGnome.Action.HelpSpecial);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretShowGnomeFiles()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret("gnomefiles"), CsvGnome.Action.ShowGnomeFiles);
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretSave()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(CsvGnome.Action.Continue, x.Interpret("save test"));
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretLoad()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(CsvGnome.Action.Continue, x.Interpret("load test"));
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void Interpret_Delete()
{
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
// Create a field to delete
IComponent[] c = new IComponent[] { new TextComponent("moo") };
fieldBrain.AddOrUpdateComponentField("test", c);
Assert.IsTrue(fieldBrain.Fields.Any());
Assert.AreEqual(CsvGnome.Action.Continue, x.Interpret("delete test"));
Assert.IsTrue(!fieldBrain.Fields.Any());
}
[TestMethod]
public void InterpretComponents_Text()
{
const string ins = "test:meowmeowmeow";
IComponent[] expected = new IComponent[] { new TextComponent("meowmeowmeow") };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_EmptyText()
{
const string ins = "test:";
IComponent[] expected = new IComponent[] { new TextComponent(String.Empty) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_Incrementing()
{
const string ins = "test:[++]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(0) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingWithStart()
{
const string ins = "test:[39++]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(39, 1) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingWithIncrement()
{
const string ins = "test:[++254]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(0, 254) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingBoth()
{
const string ins = "test:[718++218]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(718, 218) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingEvery()
{
const string ins = "test:[3++2 every 7]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(3, 2, 7) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingNegative()
{
const string ins = "test:[++][++-11][-110++-2]";
IComponent[] expected = new IComponent[]
{
Utilties.NewIncrementingComponent(0),
Utilties.NewIncrementingComponent(0, -11),
Utilties.NewIncrementingComponent(-110, -2)
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_IncrementingSpaces()
{
const string ins = "test:[-110++-2][ -110 ++ -2 ]";
IComponent[] expected = new IComponent[]
{
Utilties.NewIncrementingComponent(-110, -2),
Utilties.NewIncrementingComponent(-110, -2)
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_Incrementingi()
{
const string ins = "test:[i]";
IComponent[] expected = new IComponent[] { Utilties.NewIncrementingComponent(0) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_Date()
{
const string ins = "test:[date]";
IComponent[] expected = new IComponent[] { new DateComponent(new CsvGnome.Date.Provider()) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_DateWithFormat()
{
const string format = "HH:mm";
string ins = $"test:[date \"{format}\"]";
IComponent[] expected = new IComponent[] { new DateComponent(new CsvGnome.Date.Provider(), format) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_MinMax()
{
const string ins = "test:[0=>10]";
IComponent[] expected = new IComponent[] { new MinMaxComponent(0,10) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_MinMaxIncrement()
{
const string ins = "test:[1=>11,2]";
IComponent[] expected = new IComponent[] { new MinMaxComponent(1, 11, 2) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_SpreadComponent()
{
const string ins = "test:[spread]{one,two , three}";
IComponent[] expected = new IComponent[]
{
new ArraySpreadComponent(new string[] {"one", "two ", " three"}, new TestContext(), new TestConfigurationProvider())
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_CycleComponent()
{
const string ins = "test:[cycle]{one,two , three}";
IComponent[] expected = new IComponent[]
{
new ArrayCycleComponent(new string[] {"one", "two ", " three"}, new TestConfigurationProvider())
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_AlphabetComponent()
{
const string ins = "test:[a=>z]";
IComponent[] expected = new IComponent[]
{
new AlphabetComponent('a','z')
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_Compound1()
{
const string ins = "test:1[date]meow[++]xxx";
IComponent[] expected = new IComponent[]
{
new TextComponent("1"),
new DateComponent(new CsvGnome.Date.Provider()),
new TextComponent("meow"),
Utilties.NewIncrementingComponent(0),
new TextComponent("xxx")
};
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
[TestMethod]
public void InterpretComponents_NComponent()
{
const string ins = "test:[N]";
IComponent[] expected = new IComponent[] { new NComponent(new TestContext()) };
FieldBrain fieldBrain;
Interpreter x;
Utilties.InterpreterTestInit(out fieldBrain, out x);
Assert.AreEqual(x.Interpret(ins), CsvGnome.Action.Continue);
AssertSingleComponentField(fieldBrain, expected);
}
public static void AssertSingleComponentField(FieldBrain fb, IComponent[] expected)
{
Assert.IsTrue(fb.Fields.Count == 1);
Assert.IsTrue(fb.Fields.First() is ComponentField);
Assert.IsTrue(fb.Fields.First().Name == "test");
Assert.AreEqual(expected.Length, (fb.Fields.First() as ComponentField).Components.Length);
Assert.IsTrue((fb.Fields.First() as ComponentField).Components.Zip(expected, (a, e) => a.EqualsComponent(e)).All(r => r == true));
}
}
}
| 35.325472 | 142 | 0.591668 | [
"MIT"
] | benmosheron/CsvGnome | CsvGnomeTests/InterpreterTest.cs | 14,980 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using NAudio.Wave;
using System.Net;
using NAudioDemo.Utils;
namespace NAudioDemo.NetworkChatDemo
{
public partial class NetworkChatPanel : UserControl
{
private INetworkChatCodec selectedCodec;
private volatile bool connected;
private NetworkAudioPlayer player;
private NetworkAudioSender audioSender;
private AES256 aes;
public NetworkChatPanel()
{
// use reflection to find all the codecs
var codecs = ReflectionHelper.CreateAllInstancesOf<INetworkChatCodec>();
InitializeComponent();
PopulateInputDevicesCombo();
PopulateCodecsCombo(codecs);
comboBoxProtocol.Items.Add("UDP");
comboBoxProtocol.Items.Add("TCP");
comboBoxProtocol.SelectedIndex = 0;
Disposed += OnPanelDisposed;
}
void OnPanelDisposed(object sender, EventArgs e)
{
Disconnect();
}
private void PopulateCodecsCombo(IEnumerable<INetworkChatCodec> codecs)
{
var sorted = from codec in codecs
where codec.IsAvailable
orderby codec.BitsPerSecond ascending
select codec;
foreach(var codec in sorted)
{
var bitRate = codec.BitsPerSecond == -1 ? "VBR" : $"{codec.BitsPerSecond / 1000.0:0.#}kbps";
var text = $"{codec.Name} ({bitRate})";
comboBoxCodecs.Items.Add(new CodecComboItem { Text=text, Codec=codec });
}
comboBoxCodecs.SelectedIndex = 0;
}
class CodecComboItem
{
public string Text { get; set; }
public INetworkChatCodec Codec { get; set; }
public override string ToString()
{
return Text;
}
}
private void PopulateInputDevicesCombo()
{
for (int n = 0; n < WaveIn.DeviceCount; n++)
{
var capabilities = WaveIn.GetCapabilities(n);
comboBoxInputDevices.Items.Add(capabilities.ProductName);
}
if (comboBoxInputDevices.Items.Count > 0)
{
comboBoxInputDevices.SelectedIndex = 0;
}
}
private void buttonStartStreaming_Click(object sender, EventArgs e)
{
if (!connected)
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(textBoxIPAddress.Text), int.Parse(textBoxPort.Text));
int inputDeviceNumber = comboBoxInputDevices.SelectedIndex;
selectedCodec = ((CodecComboItem)comboBoxCodecs.SelectedItem).Codec;
Connect(endPoint, inputDeviceNumber,selectedCodec);
buttonStartStreaming.Text = "Disconnect";
}
else
{
Disconnect();
buttonStartStreaming.Text = "Connect";
}
}
private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec)
{
var receiver = (comboBoxProtocol.SelectedIndex == 0)
? (IAudioReceiver) new UdpAudioReceiver(endPoint.Port)
: new TcpAudioReceiver(endPoint.Port);
var sender = (comboBoxProtocol.SelectedIndex == 0)
? (IAudioSender)new UdpAudioSender(endPoint)
: new TcpAudioSender(endPoint);
aes = new AES256();
player = new NetworkAudioPlayer(codec, receiver, aes);
audioSender = new NetworkAudioSender(codec, inputDeviceNumber, sender, aes);
connected = true;
}
private void Disconnect()
{
if (connected)
{
connected = false;
player.Dispose();
audioSender.Dispose();
// a bit naughty but we have designed the codecs to support multiple calls to Dispose,
// recreating their resources if Encode/Decode called again
selectedCodec.Dispose();
}
}
}
public class NetworkChatPanelPlugin : INAudioDemoPlugin
{
public string Name => "Network Chat";
public Control CreatePanel()
{
return new NetworkChatPanel();
}
}
}
| 34.058824 | 123 | 0.547064 | [
"MIT"
] | sanea010/NAudio | NAudioDemo/NetworkChatDemo/NetworkChatPanel.cs | 4,634 | C# |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace ShootR
{
public class UserHandler
{
private readonly ConcurrentDictionary<string, User> _userList = new ConcurrentDictionary<string, User>();
private readonly GameHandler _gameHandler;
public int TotalActiveUsers { get; set; }
public UserHandler(GameHandler gameHandler)
{
_gameHandler = gameHandler;
}
public void AddUser(User user)
{
_userList.TryAdd(user.ConnectionID, user);
user.IdleManager.OnIdle += _gameHandler.RemoveShipFromGame;
//user.IdleManager.OnIdleTimeout += DisconnectUser;
user.IdleManager.OnComeBack += _gameHandler.AddShipToGame;
if (!user.Controller)
{
user.MyShip.OnFire += _gameHandler.AddBulletToGame;
}
}
public void RemoveUser(string connectionId)
{
if (_userList.TryRemove(connectionId, out var u) && !u.Controller && u.MyShip != null)
{
u.MyShip.Dispose();
u.MyShip.Host = null; // Remove linking from the ship
}
}
public Ship GetUserShip(string connectionId)
{
return _userList[connectionId].MyShip;
}
// public User FindUserByIdentity(string identity)
// {
// return (from user in _userList.Values
// where user.RegistrationTicket.Identity == identity && !user.Controller
// select user).FirstOrDefault();
// }
public bool UserExistsAndReady(string connectionId)
{
return _userList.ContainsKey(connectionId) && _userList[connectionId].MyShip != null;
}
public User GetUser(string connectionId)
{
return _userList[connectionId];
}
public List<User> GetUsers()
{
return _userList.Values.ToList();
}
public List<User> GetActiveUsers()
{
List<User> activeUsers = (from user in _userList.Values
where !user.Controller && user.Connected && !user.IdleManager.Idle
select user).ToList();
TotalActiveUsers = activeUsers.Count;
return activeUsers;
}
public void Update()
{
foreach (User user in _userList.Values)
{
user.Update();
}
}
}
} | 29.931034 | 113 | 0.554147 | [
"MIT"
] | BrennanConroy/ShootR | ShootR/ShootR/Server/User/UserHandler.cs | 2,604 | C# |
using System.Numerics;
namespace AsciiFuntimeLand
{
public class RenderableWall : RenderablePlane, ICollidable
{
private Hitbox hb;
public Hitbox[] getHitboxes()
{
return new[] { hb };
}
public RenderableWall(World world, char renderChar, SquarePlane plane, int r, int g, int b) : base(world, new ColorableSquareFace(renderChar, plane, r, g, b))
{
hb = new Hitbox(plane);
world.Hitcubes.Add(this);
}
}
} | 21.6 | 160 | 0.696759 | [
"MIT"
] | jojo2357/AsciiFuntimeLand | Objects/RenderableWall.cs | 432 | C# |
/* see LICENSE notice in solution root */
using System;
using Microsoft.VisualStudio.Project.Automation;
using Microsoft.VisualStudio.Project;
using VisualSquirrel;
using System.Drawing;
namespace Squirrel.Project
{
/// <summary>
/// This class extends the FileNode in order to represent a file
/// within the hierarchy.
/// </summary>
public class SquirrelProjectFileNode2 : FileNode
{
#region Fields
private SQAutomationProjectFileItem automationObject;
internal int imageIndex;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SquirrelProjectFileNode"/> class.
/// </summary>
/// <param name="root">The project node.</param>
/// <param name="e">The project element node.</param>
internal SquirrelProjectFileNode2(ProjectNode root, ProjectElement e)
: base(root, e)
{
SquirrelProjectNode project = (SquirrelProjectNode)root;
imageIndex = project.NutIconIndex;
}
#endregion
#region Overriden implementation
/// <summary>
/// Gets the automation object for the file node.
/// </summary>
/// <returns></returns>
public override object GetAutomationObject()
{
if(automationObject == null)
{
automationObject = new SQAutomationProjectFileItem(this.ProjectMgr.GetAutomationObject() as OAProject, this);
}
return automationObject;
}
public override int ImageIndex
{
get
{
return imageIndex;
}
}
#endregion
NodeProperties _nodeproperties;
protected override NodeProperties CreatePropertiesObject()
{
return _nodeproperties = new SQFileNodeProperties(this);
}
public override NodeProperties NodeProperties
{
get
{
return _nodeproperties;
}
}
#region Private implementation
internal OleServiceProvider.ServiceCreatorCallback ServiceCreator
{
get { return new OleServiceProvider.ServiceCreatorCallback(this.CreateServices); }
}
private object CreateServices(Type serviceType)
{
object service = null;
if(typeof(EnvDTE.ProjectItem) == serviceType)
{
service = GetAutomationObject();
}
return service;
}
#endregion
}
} | 26.488889 | 113 | 0.645973 | [
"MIT"
] | albertodemichelis/visualsquirrel | VisualSquirrel/VSSQ8/Project/SquirrelProjectFileNode.cs | 2,386 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Com.StudioTBD.CoronaIO.Agent;
using Com.StudioTBD.CoronaIO.FMS;
using UnityEngine;
public class HouseDoor : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
// Make sure it is an agent
if (!other.CompareTag("Human")) return;
other.GetComponent<Agent>().Consume(new HumanEvent(this.gameObject, HumanEvent.HumanEventType.EnteredShelter));
}
} | 29.4375 | 119 | 0.738854 | [
"MIT"
] | StudioTBA/CoronaIO | Assets/Scripts/Map/Objects/HouseDoor.cs | 473 | C# |
using System.Collections.Generic;
namespace NinjaTools.IPC.Console
{
public static class Run
{
// TODO: make this on other systems (linux, android)
public static int System(string cmdlineFormat, params object[] args)
{
string cmdline = string.Format(cmdlineFormat, args);
return Command("cmd.exe", "/c " + cmdline);
}
public static int System(IList<string> stdout, IList<string> stderr, string cmdlineFormat, params object[] args)
{
string cmdline = string.Format(cmdlineFormat, args);
return Command("cmd.exe", "/c " + cmdline, stdout, stderr);
}
public static int System(IList<string> stdoutAndErr, string cmdlineFormat, params object[] args)
{
string cmdline = string.Format(cmdlineFormat, args);
return Command("cmd.exe", "/c " + cmdline, stdoutAndErr);
}
public static int Command(string command, string arguments)
{
ConsoleProcess proc = new ConsoleProcess();
proc.Arguments = arguments;
proc.AppFileName = command;
proc.Start();
proc.Wait();
return proc.ExitCode;
}
public static int Command(string command, string arguments, IList<string> stdout, IList<string> stderr)
{
ConsoleProcess proc = new ConsoleProcess();
proc.Arguments = arguments;
proc.AppFileName = command;
proc.StderrLineRead += l => { if (stderr == null) return; lock (stderr) stderr.Add(l); };
proc.StdoutLineRead += l => { if (stdout == null) return; lock (stdout) stdout.Add(l); };
proc.Start();
proc.Wait();
return proc.ExitCode;
}
public static int Command(string command, string arguments, IList<string> stdoutAndErr)
{
ConsoleProcess proc = new ConsoleProcess();
proc.Arguments = arguments;
proc.AppFileName = command;
proc.StderrLineRead += l => { lock (stdoutAndErr) stdoutAndErr.Add(l); };
proc.StdoutLineRead += l => { lock (stdoutAndErr) stdoutAndErr.Add(l); };
proc.Start();
proc.Wait();
return proc.ExitCode;
}
}
}
| 36.265625 | 120 | 0.576045 | [
"MIT"
] | ninjasync/NinjaTasks | NinjaTools/NinjaTools.IPC.Console/Run.cs | 2,323 | C# |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mario Carrion <mcarrion@novell.com>
//
using System;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using SWF = System.Windows.Forms;
using Mono.UIAutomation.Winforms;
using Mono.UIAutomation.Winforms.Events;
namespace Mono.UIAutomation.Winforms.Events.ListBox
{
internal class ScrollPatternHorizontallyScrollableEvent
: BaseAutomationPropertyEvent
{
#region Constructors
public ScrollPatternHorizontallyScrollableEvent (ListBoxProvider provider)
: base (provider,
ScrollPatternIdentifiers.HorizontallyScrollableProperty)
{
}
#endregion
#region ProviderEvent Methods
public override void Connect ()
{
SWF.ScrollBar hscrollbar
= ((ListBoxProvider) Provider).GetInternalScrollBar (SWF.Orientation.Horizontal);
hscrollbar.VisibleChanged += new EventHandler (OnScrollableChanged);
hscrollbar.EnabledChanged += new EventHandler (OnScrollableChanged);
}
public override void Disconnect ()
{
SWF.ScrollBar hscrollbar
= ((ListBoxProvider) Provider).GetInternalScrollBar (SWF.Orientation.Horizontal);
hscrollbar.VisibleChanged -= new EventHandler (OnScrollableChanged);
hscrollbar.EnabledChanged -= new EventHandler (OnScrollableChanged);
}
#endregion
#region Protected methods
private void OnScrollableChanged (object sender, EventArgs e)
{
RaiseAutomationPropertyChangedEvent ();
}
#endregion
}
}
| 32.345679 | 85 | 0.751908 | [
"MIT"
] | ABEMBARKA/monoUI | UIAutomationWinforms/UIAutomationWinforms/Mono.UIAutomation.Winforms.Events/ListBox/ScrollPatternHorizontallyScrollableEvent.cs | 2,620 | C# |
/*
* LUSID API
*
* # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages and frameworks: * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) * [Angular](https://github.com/finbourne/lusid-sdk-angular) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#operation/UpsertInstrumentsProperties) endpoint. | Field|Type|Description | | - --|- --|- -- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | | EffectiveUntil|datetimeoffset|The effective datetime until which the property is valid. If not supplied this will be valid indefinitely, or until the next 'effectiveFrom' datetime of the property. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | - --|- --|- -- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency (settlement currency being represented by the TotalConsideration.Currency). For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for £54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | - -- -- | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate* | 0.7673 | 0.7673 | 0.7673 | [* This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | - -- -- | - -- -- | - -- - | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | | Currency|currency|The holding currency. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | - --|- --|- -- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | - --|- --|- -- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | - -- -- | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | - --|- --|- -- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | - -- | - -- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | | <a name=\"693\">693</a>|Entity type is not supported for Relationship| | | <a name=\"694\">694</a>|Relationship Validation Failure| | | <a name=\"695\">695</a>|Relationship Not Found| | | <a name=\"697\">697</a>|Derived Property Formula No Longer Valid| | | <a name=\"698\">698</a>|Story is not available| | | <a name=\"703\">703</a>|Corporate Action Does Not Exist| |
*
* The version of the OpenAPI document: 0.11.2810
* Contact: info@finbourne.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter;
namespace Lusid.Sdk.Model
{
/// <summary>
/// FxOptionAllOf
/// </summary>
[DataContract]
public partial class FxOptionAllOf : IEquatable<FxOptionAllOf>
{
/// <summary>
/// The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashflowLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CashSettled, CdsIndex, Basket
/// </summary>
/// <value>The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashflowLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CashSettled, CdsIndex, Basket</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum InstrumentTypeEnum
{
/// <summary>
/// Enum QuotedSecurity for value: QuotedSecurity
/// </summary>
[EnumMember(Value = "QuotedSecurity")]
QuotedSecurity = 1,
/// <summary>
/// Enum InterestRateSwap for value: InterestRateSwap
/// </summary>
[EnumMember(Value = "InterestRateSwap")]
InterestRateSwap = 2,
/// <summary>
/// Enum FxForward for value: FxForward
/// </summary>
[EnumMember(Value = "FxForward")]
FxForward = 3,
/// <summary>
/// Enum Future for value: Future
/// </summary>
[EnumMember(Value = "Future")]
Future = 4,
/// <summary>
/// Enum ExoticInstrument for value: ExoticInstrument
/// </summary>
[EnumMember(Value = "ExoticInstrument")]
ExoticInstrument = 5,
/// <summary>
/// Enum FxOption for value: FxOption
/// </summary>
[EnumMember(Value = "FxOption")]
FxOption = 6,
/// <summary>
/// Enum CreditDefaultSwap for value: CreditDefaultSwap
/// </summary>
[EnumMember(Value = "CreditDefaultSwap")]
CreditDefaultSwap = 7,
/// <summary>
/// Enum InterestRateSwaption for value: InterestRateSwaption
/// </summary>
[EnumMember(Value = "InterestRateSwaption")]
InterestRateSwaption = 8,
/// <summary>
/// Enum Bond for value: Bond
/// </summary>
[EnumMember(Value = "Bond")]
Bond = 9,
/// <summary>
/// Enum EquityOption for value: EquityOption
/// </summary>
[EnumMember(Value = "EquityOption")]
EquityOption = 10,
/// <summary>
/// Enum FixedLeg for value: FixedLeg
/// </summary>
[EnumMember(Value = "FixedLeg")]
FixedLeg = 11,
/// <summary>
/// Enum FloatingLeg for value: FloatingLeg
/// </summary>
[EnumMember(Value = "FloatingLeg")]
FloatingLeg = 12,
/// <summary>
/// Enum BespokeCashflowLeg for value: BespokeCashflowLeg
/// </summary>
[EnumMember(Value = "BespokeCashflowLeg")]
BespokeCashflowLeg = 13,
/// <summary>
/// Enum Unknown for value: Unknown
/// </summary>
[EnumMember(Value = "Unknown")]
Unknown = 14,
/// <summary>
/// Enum TermDeposit for value: TermDeposit
/// </summary>
[EnumMember(Value = "TermDeposit")]
TermDeposit = 15,
/// <summary>
/// Enum ContractForDifference for value: ContractForDifference
/// </summary>
[EnumMember(Value = "ContractForDifference")]
ContractForDifference = 16,
/// <summary>
/// Enum EquitySwap for value: EquitySwap
/// </summary>
[EnumMember(Value = "EquitySwap")]
EquitySwap = 17,
/// <summary>
/// Enum CashPerpetual for value: CashPerpetual
/// </summary>
[EnumMember(Value = "CashPerpetual")]
CashPerpetual = 18,
/// <summary>
/// Enum CashSettled for value: CashSettled
/// </summary>
[EnumMember(Value = "CashSettled")]
CashSettled = 19,
/// <summary>
/// Enum CdsIndex for value: CdsIndex
/// </summary>
[EnumMember(Value = "CdsIndex")]
CdsIndex = 20,
/// <summary>
/// Enum Basket for value: Basket
/// </summary>
[EnumMember(Value = "Basket")]
Basket = 21
}
/// <summary>
/// The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashflowLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CashSettled, CdsIndex, Basket
/// </summary>
/// <value>The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashflowLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CashSettled, CdsIndex, Basket</value>
[DataMember(Name="instrumentType", EmitDefaultValue=false)]
public InstrumentTypeEnum InstrumentType { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="FxOptionAllOf" /> class.
/// </summary>
[JsonConstructorAttribute]
protected FxOptionAllOf() { }
/// <summary>
/// Initializes a new instance of the <see cref="FxOptionAllOf" /> class.
/// </summary>
/// <param name="startDate">The start date of the instrument. This is normally synonymous with the trade-date. (required).</param>
/// <param name="optionMaturityDate">The maturity date of the option. (required).</param>
/// <param name="optionSettlementDate">The settlement date of the option. (required).</param>
/// <param name="isDeliveryNotCash">True of the option is settled in cash false if delivery. (required).</param>
/// <param name="isCallNotPut">True if the option is a call, false if the option is a put. (required).</param>
/// <param name="strike">The strike of the option. (required).</param>
/// <param name="domCcy">The domestic currency of the instrument. (required).</param>
/// <param name="fgnCcy">The foreign currency of the FX. (required).</param>
/// <param name="instrumentType">The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashflowLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CashSettled, CdsIndex, Basket (required).</param>
public FxOptionAllOf(DateTimeOffset? startDate = default(DateTimeOffset?), DateTimeOffset? optionMaturityDate = default(DateTimeOffset?), DateTimeOffset? optionSettlementDate = default(DateTimeOffset?), bool? isDeliveryNotCash = default(bool?), bool? isCallNotPut = default(bool?), decimal? strike = default(decimal?), string domCcy = default(string), string fgnCcy = default(string), InstrumentTypeEnum instrumentType = default(InstrumentTypeEnum))
{
// to ensure "startDate" is required (not null)
if (startDate == null)
{
throw new InvalidDataException("startDate is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.StartDate = startDate;
}
// to ensure "optionMaturityDate" is required (not null)
if (optionMaturityDate == null)
{
throw new InvalidDataException("optionMaturityDate is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.OptionMaturityDate = optionMaturityDate;
}
// to ensure "optionSettlementDate" is required (not null)
if (optionSettlementDate == null)
{
throw new InvalidDataException("optionSettlementDate is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.OptionSettlementDate = optionSettlementDate;
}
// to ensure "isDeliveryNotCash" is required (not null)
if (isDeliveryNotCash == null)
{
throw new InvalidDataException("isDeliveryNotCash is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.IsDeliveryNotCash = isDeliveryNotCash;
}
// to ensure "isCallNotPut" is required (not null)
if (isCallNotPut == null)
{
throw new InvalidDataException("isCallNotPut is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.IsCallNotPut = isCallNotPut;
}
// to ensure "strike" is required (not null)
if (strike == null)
{
throw new InvalidDataException("strike is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.Strike = strike;
}
// to ensure "domCcy" is required (not null)
if (domCcy == null)
{
throw new InvalidDataException("domCcy is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.DomCcy = domCcy;
}
// to ensure "fgnCcy" is required (not null)
if (fgnCcy == null)
{
throw new InvalidDataException("fgnCcy is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.FgnCcy = fgnCcy;
}
// to ensure "instrumentType" is required (not null)
if (instrumentType == null)
{
throw new InvalidDataException("instrumentType is a required property for FxOptionAllOf and cannot be null");
}
else
{
this.InstrumentType = instrumentType;
}
}
/// <summary>
/// The start date of the instrument. This is normally synonymous with the trade-date.
/// </summary>
/// <value>The start date of the instrument. This is normally synonymous with the trade-date.</value>
[DataMember(Name="startDate", EmitDefaultValue=false)]
public DateTimeOffset? StartDate { get; set; }
/// <summary>
/// The maturity date of the option.
/// </summary>
/// <value>The maturity date of the option.</value>
[DataMember(Name="optionMaturityDate", EmitDefaultValue=false)]
public DateTimeOffset? OptionMaturityDate { get; set; }
/// <summary>
/// The settlement date of the option.
/// </summary>
/// <value>The settlement date of the option.</value>
[DataMember(Name="optionSettlementDate", EmitDefaultValue=false)]
public DateTimeOffset? OptionSettlementDate { get; set; }
/// <summary>
/// True of the option is settled in cash false if delivery.
/// </summary>
/// <value>True of the option is settled in cash false if delivery.</value>
[DataMember(Name="isDeliveryNotCash", EmitDefaultValue=false)]
public bool? IsDeliveryNotCash { get; set; }
/// <summary>
/// True if the option is a call, false if the option is a put.
/// </summary>
/// <value>True if the option is a call, false if the option is a put.</value>
[DataMember(Name="isCallNotPut", EmitDefaultValue=false)]
public bool? IsCallNotPut { get; set; }
/// <summary>
/// The strike of the option.
/// </summary>
/// <value>The strike of the option.</value>
[DataMember(Name="strike", EmitDefaultValue=false)]
public decimal? Strike { get; set; }
/// <summary>
/// The domestic currency of the instrument.
/// </summary>
/// <value>The domestic currency of the instrument.</value>
[DataMember(Name="domCcy", EmitDefaultValue=false)]
public string DomCcy { get; set; }
/// <summary>
/// The foreign currency of the FX.
/// </summary>
/// <value>The foreign currency of the FX.</value>
[DataMember(Name="fgnCcy", EmitDefaultValue=false)]
public string FgnCcy { 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 FxOptionAllOf {\n");
sb.Append(" StartDate: ").Append(StartDate).Append("\n");
sb.Append(" OptionMaturityDate: ").Append(OptionMaturityDate).Append("\n");
sb.Append(" OptionSettlementDate: ").Append(OptionSettlementDate).Append("\n");
sb.Append(" IsDeliveryNotCash: ").Append(IsDeliveryNotCash).Append("\n");
sb.Append(" IsCallNotPut: ").Append(IsCallNotPut).Append("\n");
sb.Append(" Strike: ").Append(Strike).Append("\n");
sb.Append(" DomCcy: ").Append(DomCcy).Append("\n");
sb.Append(" FgnCcy: ").Append(FgnCcy).Append("\n");
sb.Append(" InstrumentType: ").Append(InstrumentType).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 FxOptionAllOf);
}
/// <summary>
/// Returns true if FxOptionAllOf instances are equal
/// </summary>
/// <param name="input">Instance of FxOptionAllOf to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FxOptionAllOf input)
{
if (input == null)
return false;
return
(
this.StartDate == input.StartDate ||
(this.StartDate != null &&
this.StartDate.Equals(input.StartDate))
) &&
(
this.OptionMaturityDate == input.OptionMaturityDate ||
(this.OptionMaturityDate != null &&
this.OptionMaturityDate.Equals(input.OptionMaturityDate))
) &&
(
this.OptionSettlementDate == input.OptionSettlementDate ||
(this.OptionSettlementDate != null &&
this.OptionSettlementDate.Equals(input.OptionSettlementDate))
) &&
(
this.IsDeliveryNotCash == input.IsDeliveryNotCash ||
(this.IsDeliveryNotCash != null &&
this.IsDeliveryNotCash.Equals(input.IsDeliveryNotCash))
) &&
(
this.IsCallNotPut == input.IsCallNotPut ||
(this.IsCallNotPut != null &&
this.IsCallNotPut.Equals(input.IsCallNotPut))
) &&
(
this.Strike == input.Strike ||
(this.Strike != null &&
this.Strike.Equals(input.Strike))
) &&
(
this.DomCcy == input.DomCcy ||
(this.DomCcy != null &&
this.DomCcy.Equals(input.DomCcy))
) &&
(
this.FgnCcy == input.FgnCcy ||
(this.FgnCcy != null &&
this.FgnCcy.Equals(input.FgnCcy))
) &&
(
this.InstrumentType == input.InstrumentType ||
(this.InstrumentType != null &&
this.InstrumentType.Equals(input.InstrumentType))
);
}
/// <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.StartDate != null)
hashCode = hashCode * 59 + this.StartDate.GetHashCode();
if (this.OptionMaturityDate != null)
hashCode = hashCode * 59 + this.OptionMaturityDate.GetHashCode();
if (this.OptionSettlementDate != null)
hashCode = hashCode * 59 + this.OptionSettlementDate.GetHashCode();
if (this.IsDeliveryNotCash != null)
hashCode = hashCode * 59 + this.IsDeliveryNotCash.GetHashCode();
if (this.IsCallNotPut != null)
hashCode = hashCode * 59 + this.IsCallNotPut.GetHashCode();
if (this.Strike != null)
hashCode = hashCode * 59 + this.Strike.GetHashCode();
if (this.DomCcy != null)
hashCode = hashCode * 59 + this.DomCcy.GetHashCode();
if (this.FgnCcy != null)
hashCode = hashCode * 59 + this.FgnCcy.GetHashCode();
if (this.InstrumentType != null)
hashCode = hashCode * 59 + this.InstrumentType.GetHashCode();
return hashCode;
}
}
}
}
| 103.745223 | 29,340 | 0.642927 | [
"MIT"
] | SamuelColvinFinbourne/lusid-sdk-csharp-preview | sdk/Lusid.Sdk/Model/FxOptionAllOf.cs | 48,864 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.System.Profile
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum PlatformDataCollectionLevel
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Security,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Basic,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Enhanced,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Full,
#endif
}
#endif
}
| 34.923077 | 99 | 0.713656 | [
"Apache-2.0"
] | Abhishek-Sharma-Msft/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System.Profile/PlatformDataCollectionLevel.cs | 908 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
#region Singleton
public static Inventory instance;
private void Awake()
{
if (instance != null)
{
Debug.LogWarning("More than one instance of Inventory found");
}
instance = this;
}
#endregion
public delegate void OnItemChanged();
public OnItemChanged GetOnItemChangedCallback;
public int space = 20;
public List<Item> items = new List<Item>();
public bool Add(Item item)
{
if (!item.isDefaultItem)
{
if (items.Count >= space)
{
Debug.Log("Inventory full!");
return false;
}
items.Add(item);
if(GetOnItemChangedCallback != null)
GetOnItemChangedCallback.Invoke();
}
return true;
}
public void Remove(Item item)
{
items.Remove(item);
if (GetOnItemChangedCallback != null)
GetOnItemChangedCallback.Invoke();
}
}
| 20.178571 | 74 | 0.561947 | [
"MIT"
] | TheSaviour1/RPG-Project | Assets/Scripts/Inventory/Inventory.cs | 1,132 | C# |
using System.ComponentModel.DataAnnotations;
namespace IdentityExample.ViewModels;
public class LoginViewModel
{
[Display(Name = "User Name")]
[Required(ErrorMessage = "Please enter your user name.")]
public string UserName { get; set; } = null!;
[Display(Name = "Password")]
[Required(ErrorMessage = "Please enter your password.")]
public string Password { get; set; } = null!;
[Display(Name = "Remember Me")]
public bool RememberMe { get; set; } = false;
}
| 26.157895 | 61 | 0.674044 | [
"MIT"
] | EricCote/20486D-New | Allfiles/Mod11/Democode/01_IdentityExample_begin/IdentityExample/ViewModels/LoginViewModel.cs | 499 | C# |
namespace Part_2_Avatar
{
//Child class to the class monument. Holds one additional property.
public class EarthMonument : Monument
{
private int earthAffinity;
public int EarthAffinity
{
get
{
return this.earthAffinity;
}
set
{
this.earthAffinity = value;
}
}
public EarthMonument(string name, int earthAffinity)
: base(name)
{
this.EarthAffinity = earthAffinity;
}
}
} | 22.038462 | 71 | 0.500873 | [
"MIT"
] | Brankovanov/SoftUniCourses | 4.OOPBasic/5.ExamPreparation/Part_2_Avatar/EarthMonument.cs | 575 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Vetrina.Server.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Promotions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PromotionStartingFrom = table.Column<DateTime>(type: "datetime2", nullable: false),
PromotionEndingAt = table.Column<DateTime>(type: "datetime2", nullable: false),
Price = table.Column<double>(type: "float", nullable: false),
PriceRaw = table.Column<string>(type: "nvarchar(max)", nullable: true),
OfficialPrice = table.Column<double>(type: "float", nullable: false),
DiscountPercentage = table.Column<string>(type: "nvarchar(max)", nullable: true),
DescriptionRaw = table.Column<string>(type: "nvarchar(max)", nullable: true),
DescriptionSearch = table.Column<string>(type: "nvarchar(max)", nullable: true),
ImageUrl = table.Column<string>(type: "nvarchar(max)", nullable: true),
Store = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Promotions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SearchRecords",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Keyword = table.Column<string>(type: "nvarchar(max)", nullable: true),
IpAddress = table.Column<string>(type: "nvarchar(max)", nullable: true),
EventDate = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SearchRecords", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(type: "nvarchar(max)", nullable: true),
FirstName = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastName = table.Column<string>(type: "nvarchar(max)", nullable: true),
Email = table.Column<string>(type: "nvarchar(max)", nullable: true),
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true),
AcceptTerms = table.Column<bool>(type: "bit", nullable: false),
Role = table.Column<int>(type: "int", nullable: false),
VerificationToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
Verified = table.Column<DateTime>(type: "datetime2", nullable: true),
PasswordResetToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
PasswordResetTokenExpires = table.Column<DateTime>(type: "datetime2", nullable: true),
PasswordReset = table.Column<DateTime>(type: "datetime2", nullable: true),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
Updated = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RefreshToken",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false),
Token = table.Column<string>(type: "nvarchar(max)", nullable: true),
Expires = table.Column<DateTime>(type: "datetime2", nullable: false),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedByIp = table.Column<string>(type: "nvarchar(max)", nullable: true),
Revoked = table.Column<DateTime>(type: "datetime2", nullable: true),
RevokedByIp = table.Column<string>(type: "nvarchar(max)", nullable: true),
ReplacedByToken = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshToken", x => x.Id);
table.ForeignKey(
name: "FK_RefreshToken_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_RefreshToken_UserId",
table: "RefreshToken",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Promotions");
migrationBuilder.DropTable(
name: "RefreshToken");
migrationBuilder.DropTable(
name: "SearchRecords");
migrationBuilder.DropTable(
name: "Users");
}
}
}
| 49.715447 | 106 | 0.516108 | [
"MIT"
] | InKolev/vetrina | src/Server/Migrations/20220221230644_Initial.cs | 6,117 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElastiCache.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElastiCache.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateGlobalReplicationGroup Request Marshaller
/// </summary>
public class CreateGlobalReplicationGroupRequestMarshaller : IMarshaller<IRequest, CreateGlobalReplicationGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateGlobalReplicationGroupRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateGlobalReplicationGroupRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ElastiCache");
request.Parameters.Add("Action", "CreateGlobalReplicationGroup");
request.Parameters.Add("Version", "2015-02-02");
if(publicRequest != null)
{
if(publicRequest.IsSetGlobalReplicationGroupDescription())
{
request.Parameters.Add("GlobalReplicationGroupDescription", StringUtils.FromString(publicRequest.GlobalReplicationGroupDescription));
}
if(publicRequest.IsSetGlobalReplicationGroupIdSuffix())
{
request.Parameters.Add("GlobalReplicationGroupIdSuffix", StringUtils.FromString(publicRequest.GlobalReplicationGroupIdSuffix));
}
if(publicRequest.IsSetPrimaryReplicationGroupId())
{
request.Parameters.Add("PrimaryReplicationGroupId", StringUtils.FromString(publicRequest.PrimaryReplicationGroupId));
}
}
return request;
}
private static CreateGlobalReplicationGroupRequestMarshaller _instance = new CreateGlobalReplicationGroupRequestMarshaller();
internal static CreateGlobalReplicationGroupRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateGlobalReplicationGroupRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.221053 | 172 | 0.639023 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/Internal/MarshallTransformations/CreateGlobalReplicationGroupRequestMarshaller.cs | 3,726 | C# |
// IRegisterdEncoding.cs
//
// Copyright (C) BEditor
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BEditor.Media.Encoding;
namespace BEditor.Media
{
/// <summary>
/// Provides the ability to create a encoder.
/// </summary>
public interface IRegisterdEncoding
{
/// <summary>
/// Gets the decoder name.
/// </summary>
public string Name { get; }
/// <summary>
/// Create the media file.
/// </summary>
/// <param name="file">The file name to output.</param>
/// <returns>Returns the output container created by this method.</returns>
public IOutputContainer? Create(string file);
/// <summary>
/// Gets the value if the specified media file is supported.
/// </summary>
/// <param name="file">File name of the media file.</param>
/// <returns>Returns a value if the specified media file is supported.</returns>
public bool IsSupported(string file)
{
return SupportExtensions().Contains(Path.GetExtension(file));
}
/// <summary>
/// Gets the supported extensions.
/// </summary>
/// <returns>Returns the supported extensions.</returns>
public IEnumerable<string> SupportExtensions();
}
/// <summary>
/// Controls the default settings of the encoder.
/// </summary>
public interface ISupportEncodingSettings : IRegisterdEncoding
{
/// <summary>
/// Gets the default settings for video encoder.
/// </summary>
/// <returns>Returns the default encoder setting.</returns>
public VideoEncoderSettings GetDefaultVideoSettings();
/// <summary>
/// Gets the default settings for audio encoder.
/// </summary>
/// <returns>Returns the default encoder setting.</returns>
public AudioEncoderSettings GetDefaultAudioSettings();
}
} | 31.432836 | 88 | 0.615385 | [
"MIT"
] | b-editor/BEditor | src/libraries/BEditor.Media/IRegisterdEncoding.cs | 2,108 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Chris.Service.Location
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 22.105263 | 61 | 0.585714 | [
"MIT"
] | namesunwei/MyProjects | Chris.Service.Location/Chris.Service.Location/Program.cs | 422 | C# |
namespace SBRW.Nancy
{
/// <summary>
/// HTTP Status Codes
/// </summary>
/// <remarks>The values are based on the list found at http://en.wikipedia.org/wiki/List_of_HTTP_status_codes </remarks>
public enum HttpStatusCode
{
/// <summary>
/// 100 Continue
/// </summary>
Continue = 100,
/// <summary>
/// 101 SwitchingProtocols
/// </summary>
SwitchingProtocols = 101,
/// <summary>
/// 102 Processing
/// </summary>
Processing = 102,
/// <summary>
/// 103 Checkpoint
/// </summary>
Checkpoint = 103,
/// <summary>
/// 200 OK
/// </summary>
OK = 200,
/// <summary>
/// 201 Created
/// </summary>
Created = 201,
/// <summary>
/// 202 Accepted
/// </summary>
Accepted = 202,
/// <summary>
/// 203 NonAuthoritativeInformation
/// </summary>
NonAuthoritativeInformation = 203,
/// <summary>
/// 204 NoContent
/// </summary>
NoContent = 204,
/// <summary>
/// 205 ResetContent
/// </summary>
ResetContent = 205,
/// <summary>
/// 206 PartialContent
/// </summary>
PartialContent = 206,
/// <summary>
/// 207 MultipleStatus
/// </summary>
MultipleStatus = 207,
/// <summary>
/// 226 IMUsed
/// </summary>
IMUsed = 226,
/// <summary>
/// 300 MultipleChoices
/// </summary>
MultipleChoices = 300,
/// <summary>
/// 301 MovedPermanently
/// </summary>
MovedPermanently = 301,
/// <summary>
/// 302 Found
/// </summary>
Found = 302,
/// <summary>
/// 303 SeeOther
/// </summary>
SeeOther = 303,
/// <summary>
/// 304 NotModified
/// </summary>
NotModified = 304,
/// <summary>
/// 305 UseProxy
/// </summary>
UseProxy = 305,
/// <summary>
/// 306 SwitchProxy
/// </summary>
SwitchProxy = 306,
/// <summary>
/// 307 TemporaryRedirect
/// </summary>
TemporaryRedirect = 307,
/// <summary>
/// 308 ResumeIncomplete
/// </summary>
ResumeIncomplete = 308,
/// <summary>
/// 400 BadRequest
/// </summary>
BadRequest = 400,
/// <summary>
/// 401 Unauthorized
/// </summary>
Unauthorized = 401,
/// <summary>
/// 402 PaymentRequired
/// </summary>
PaymentRequired = 402,
/// <summary>
/// 403 Forbidden
/// </summary>
Forbidden = 403,
/// <summary>
/// 404 NotFound
/// </summary>
NotFound = 404,
/// <summary>
/// 405 MethodNotAllowed
/// </summary>
MethodNotAllowed = 405,
/// <summary>
/// 406 NotAcceptable
/// </summary>
NotAcceptable = 406,
/// <summary>
/// 407 ProxyAuthenticationRequired
/// </summary>
ProxyAuthenticationRequired = 407,
/// <summary>
/// 408 RequestTimeout
/// </summary>
RequestTimeout = 408,
/// <summary>
/// 409 Conflict
/// </summary>
Conflict = 409,
/// <summary>
/// 410 Gone
/// </summary>
Gone = 410,
/// <summary>
/// 411 LengthRequired
/// </summary>
LengthRequired = 411,
/// <summary>
/// 412 PreconditionFailed
/// </summary>
PreconditionFailed = 412,
/// <summary>
/// 413 RequestEntityTooLarge
/// </summary>
RequestEntityTooLarge = 413,
/// <summary>
/// 414 RequestUriTooLong
/// </summary>
RequestUriTooLong = 414,
/// <summary>
/// 415 UnsupportedMediaType
/// </summary>
UnsupportedMediaType = 415,
/// <summary>
/// 416 RequestedRangeNotSatisfiable
/// </summary>
RequestedRangeNotSatisfiable = 416,
/// <summary>
/// 417 ExpectationFailed
/// </summary>
ExpectationFailed = 417,
/// <summary>
/// 418 ImATeapot
/// </summary>
ImATeapot = 418,
/// <summary>
/// 420 Enhance Your Calm
/// </summary>
EnhanceYourCalm = 420,
/// <summary>
/// 422 UnprocessableEntity
/// </summary>
UnprocessableEntity = 422,
/// <summary>
/// 423 Locked
/// </summary>
Locked = 423,
/// <summary>
/// 424 FailedDependency
/// </summary>
FailedDependency = 424,
/// <summary>
/// 425 UnorderedCollection
/// </summary>
UnorderedCollection = 425,
/// <summary>
/// 426 UpgradeRequired
/// </summary>
UpgradeRequired = 426,
/// <summary>
/// 429 Too Many Requests
/// </summary>
TooManyRequests = 429,
/// <summary>
/// 444 NoResponse
/// </summary>
NoResponse = 444,
/// <summary>
/// 449 RetryWith
/// </summary>
RetryWith = 449,
/// <summary>
/// 450 BlockedByWindowsParentalControls
/// </summary>
BlockedByWindowsParentalControls = 450,
/// <summary>
/// 451 UnavailableForLegalReasons
/// </summary>
UnavailableForLegalReasons = 451,
/// <summary>
/// 499 ClientClosedRequest
/// </summary>
ClientClosedRequest = 499,
/// <summary>
/// 500 InternalServerError
/// </summary>
InternalServerError = 500,
/// <summary>
/// 501 NotImplemented
/// </summary>
NotImplemented = 501,
/// <summary>
/// 502 BadGateway
/// </summary>
BadGateway = 502,
/// <summary>
/// 503 ServiceUnavailable
/// </summary>
ServiceUnavailable = 503,
/// <summary>
/// 504 GatewayTimeout
/// </summary>
GatewayTimeout = 504,
/// <summary>
/// 505 HttpVersionNotSupported
/// </summary>
HttpVersionNotSupported = 505,
/// <summary>
/// 506 VariantAlsoNegotiates
/// </summary>
VariantAlsoNegotiates = 506,
/// <summary>
/// 507 InsufficientStorage
/// </summary>
InsufficientStorage = 507,
/// <summary>
/// 509 BandwidthLimitExceeded
/// </summary>
BandwidthLimitExceeded = 509,
/// <summary>
/// 510 NotExtended
/// </summary>
NotExtended = 510
}
}
| 26.543726 | 124 | 0.463114 | [
"MIT"
] | DavidCarbon-SBRW/SBRW.Nancy | SBRW.Nancy/HttpStatusCode.cs | 6,981 | C# |
namespace Portal.DataObjects
{
public class PendingLoan : PendingBase
{
public string Reason { get; set; }
}
}
| 16.5 | 42 | 0.628788 | [
"MIT"
] | isboat/ibunionportal | src/Core/Portal.DataObjects/PendingLoan.cs | 134 | C# |
namespace Novel.Models
{
/// <summary>
/// Novel のステートメント モデルの実装です.
/// </summary>
internal class NStatement : INStatement
{
public string CommandName { get; }
public string SpriteTag { get; }
public string[] Arguments { get; }
public NStatement(string commandName, string spriteTag, string[] arguments)
{
CommandName = commandName;
SpriteTag = spriteTag;
Arguments = arguments;
}
}
}
| 19.863636 | 78 | 0.649886 | [
"MIT"
] | Citringo/Novel | NovelLib/Models/NStatement.cs | 473 | C# |
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Reflection;
namespace PEAPI {
#region Enums
/// <summary>
/// flags for the assembly (.corflags)
/// </summary>
public enum CorFlags {CF_IL_ONLY = 1, CF_32_BITREQUIRED = 2,
CF_STRONGNAMESIGNED = 8, CF_TRACKDEBUGDATA = 0x10000 }
/// <summary>
/// subsystem for the assembly (.subsystem)
/// </summary>
public enum SubSystem { Native = 1, Windows_GUI = 2,
Windows_CUI = 3, OS2_CUI = 5, POSIX_CUI = 7, Native_Windows = 8,
Windows_CE_GUI = 9}
/// <summary>
/// Hash algorithms for the assembly
/// </summary>
public enum HashAlgorithm { None, SHA1 }
/// <summary>
/// Attributes for this assembly
/// </summary>
public enum AssemAttr { Retargetable = 0x100, EnableJITCompileTracking = 0x8000,
DisableJITCompileOptimizer = 0x4000}
/// <summary>
/// Method call conventions
/// </summary>
[Flags]
public enum CallConv { Default, Cdecl, Stdcall, Thiscall,
Fastcall, Vararg, Instance = 0x20, Generic = 0x10, InstanceExplicit = 0x60 }
/// <summary>
/// Type custom modifier
/// </summary>
public enum CustomModifier { modreq = 0x1F, modopt };
/// <summary>
/// Attibutes for a class
/// </summary>
[Flags]
public enum TypeAttr {Private, Public, NestedPublic, NestedPrivate,
NestedFamily, NestedAssembly, NestedFamAndAssem, NestedFamOrAssem,
SequentialLayout, ExplicitLayout = 0x10, Interface = 0x20,
Abstract = 0x80, PublicAbstract = 0x81, Sealed = 0x100,
PublicSealed = 0x101, SpecialName = 0x400, RTSpecialName = 0x800,
Import = 0x1000, Serializable = 0x2000, UnicodeClass = 0x10000,
AutoClass = 0x20000, HasSecurity = 0x40000, BeforeFieldInit = 0x100000,
VisibilityMask = 0x07 }
/// <summary>
/// Attributes for a field
/// </summary>
public enum FieldAttr {Default, Private, FamAndAssem, Assembly,
Family, FamOrAssem, Public, Static = 0x10, PublicStatic = 0x16,
Initonly = 0x20, Literal = 0x40, Notserialized = 0x80,
SpecialName = 0x200, RTSpecialName = 0x400, HasFieldMarshal = 0x1000 }
/// <summary>
/// Attributes for a method
/// </summary>
public enum MethAttr { Default, Private, FamAndAssem, Assembly,
Family, FamOrAssem, Public, Static = 0x0010, PublicStatic = 0x16,
Final = 0x0020, PublicStaticFinal = 0x36, Virtual = 0x0040,
PrivateVirtual, PublicVirtual = 0x0046, HideBySig = 0x0080,
NewSlot = 0x0100, Strict = 0x200, Abstract = 0x0400, SpecialName = 0x0800,
RTSpecialName = 0x1000, SpecialRTSpecialName = 0x1800,
HasSecurity = 0x4000, RequireSecObject = 0x8000}
/// <summary>
/// Attributes for .pinvokeimpl method declarations
/// </summary>
public enum PInvokeAttr { nomangle = 1, ansi = 2, unicode = 4, autochar = 6,
bestfit_on = 0x0010, bestfit_off = 0x0020, bestfit_mask = 0x0030,
lasterr = 0x0040, winapi = 0x0100, cdecl = 0x0200,
stdcall = 0x0300, thiscall = 0x0400, fastcall = 0x0500,
charmaperror_on = 0x1000, charmaperror_off = 0x2000
}
/// <summary>
/// Implementation attributes for a method
/// </summary>
public enum ImplAttr { IL, Native, Runtime = 0x03, Unmanaged = 0x04,
ForwardRef = 0x10, PreserveSig = 0x0080, InternalCall = 0x1000,
Synchronised = 0x0020, Synchronized = 0x0020, NoInLining = 0x0008, Optil = 0x0002}
/// <summary>
/// Modes for a parameter
/// </summary>
public enum ParamAttr { Default, In, Out, Opt = 16, HasDefault = 0x1000, HasFieldMarshal = 0x2000 }
/// <summary>
/// CIL instructions
/// </summary>
public enum Op { nop, breakOp, ldarg_0, ldarg_1, ldarg_2, ldarg_3,
ldloc_0, ldloc_1, ldloc_2, ldloc_3, stloc_0, stloc_1, stloc_2, stloc_3,
ldnull = 0x14, ldc_i4_m1, ldc_i4_0, ldc_i4_1, ldc_i4_2, ldc_i4_3,
ldc_i4_4, ldc_i4_5, ldc_i4_6, ldc_i4_7, ldc_i4_8, dup = 0x25, pop,
ret = 0x2A, ldind_i1 = 0x46, ldind_u1, ldind_i2, ldind_u2, ldind_i4,
ldind_u4, ldind_i8, ldind_i, ldind_r4, ldind_r8, ldind_ref, stind_ref,
stind_i1, stind_i2, stind_i4, stind_i8, stind_r4, stind_r8, add, sub, mul,
div, div_un, rem, rem_un, and, or, xor, shl, shr, shr_un, neg, not,
conv_i1, conv_i2, conv_i4, conv_i8, conv_r4, conv_r8, conv_u4, conv_u8,
conv_r_un = 0x76, throwOp = 0x7A, conv_ovf_i1_un = 0x82, conv_ovf_i2_un,
conv_ovf_i4_un, conv_ovf_i8_un, conf_ovf_u1_un, conv_ovf_u2_un,
conv_ovf_u4_un, conv_ovf_u8_un, conv_ovf_i_un, conv_ovf_u_un,
ldlen = 0x8E, ldelem_i1 = 0x90, ldelem_u1, ldelem_i2, ldelem_u2,
ldelem_i4, ldelem_u4, ldelem_i8, ldelem_i, ldelem_r4, ldelem_r8,
ldelem_ref, stelem_i, stelem_i1, stelem_i2, stelem_i4, stelem_i8, stelem_r4 = 0xA0, stelem_r8,
stelem_ref, conv_ovf_i1 = 0xb3, conv_ovf_u1, conv_ovf_i2, conv_ovf_u2,
conv_ovf_i4, conv_ovf_u4, conv_ovf_i8, conv_ovf_u8, ckfinite = 0xC3,
conv_u2 = 0xD1, conv_u1, conv_i, conv_ovf_i, conv_ovf_u, add_ovf,
add_ovf_un, mul_ovf, mul_ovf_un, sub_ovf, sub_ovf_un, endfinally,
stind_i = 0xDF, conv_u, arglist = 0xFE00, ceq, cgt, cgt_un, clt, clt_un,
localloc = 0xFE0F, endfilter = 0xFE11, volatile_ = 0xFE13, tail_,
cpblk = 0xFE17, initblk, rethrow = 0xFE1A, refanytype = 0xFE1D, readonly_ = 0xFE1E }
/// <summary>
/// CIL instructions requiring an integer parameter
/// </summary>
public enum IntOp {ldarg_s = 0x0E, ldarga_s, starg_s, ldloc_s, ldloca_s,
stloc_s, ldc_i4_s = 0x1F, ldc_i4, ldarg = 0xFE09,
ldarga, starg, ldloc, ldloca, stloc, unaligned = 0xFE12 }
/// <summary>
/// CIL instructions requiring a field parameter
/// </summary>
public enum FieldOp {ldfld = 0x7B, ldflda, stfld, ldsfld, ldsflda,
stsfld, ldtoken = 0xD0 }
/// <summary>
/// CIL instructions requiring a method parameter
/// </summary>
public enum MethodOp {jmp = 0x27, call, callvirt = 0x6F, newobj = 0x73,
ldtoken = 0xD0, ldftn = 0xFE06, ldvirtfn }
/// <summary>
/// CIL instructions requiring a type parameter
/// </summary>
public enum TypeOp {cpobj = 0x70, ldobj, castclass = 0x74, isinst,
unbox = 0x79, stobj = 0x81, box = 0x8C, newarr,
ldelema = 0x8F, refanyval = 0xC2, mkrefany = 0xC6,
ldtoken = 0xD0, initobj = 0xFE15, constrained = 0xFE16,
sizeOf = 0xFE1C, ldelem = 0xA3, stelem = 0xA4, unbox_any }
/// <summary>
/// CIL branch instructions
/// </summary>
public enum BranchOp {
// short branches
br_s = 0x2B, brfalse_s, brtrue_s, beq_s, bge_s, bgt_s,
ble_s, blt_s, bne_un_s, bge_un_s, bgt_un_s, ble_un_s, blt_un_s,
// long branches
br = 0x38, brfalse, brtrue, beq, bge, bgt, ble, blt,
bne_un, bge_un, bgt_un, ble_un, blt_un,
leave = 0xDD, leave_s }
/// <summary>
/// Index for all the tables in the meta data
/// </summary>
public enum MDTable { Module, TypeRef, TypeDef, Field = 0x04, Method = 0x06,
Param = 0x08, InterfaceImpl, MemberRef, Constant, CustomAttribute,
FieldMarshal, DeclSecurity, ClassLayout, FieldLayout, StandAloneSig,
EventMap, Event = 0x14, PropertyMap, Property = 0x17, MethodSemantics,
MethodImpl, ModuleRef, TypeSpec, ImplMap, FieldRVA, Assembly = 0x20,
AssemblyProcessor, AssemblyOS, AssemblyRef, AssemblyRefProcessor,
AssemblyRefOS, File, ExportedType, ManifestResource, NestedClass,
GenericParam, MethodSpec, GenericParamConstraint }
public enum SafeArrayType { int16 = 2, int32, float32, float64,
currency, date, bstr, dispatch, error, boolean, variant, unknown,
Decimal, int8 = 16, uint8, uint16, uint32, Int = 22, UInt }
internal enum CIx { TypeDefOrRef, HasConst, HasCustomAttr, HasFieldMarshal,
HasDeclSecurity, MemberRefParent, HasSemantics, MethodDefOrRef,
MemberForwarded, Implementation, CustomAttributeType, ResolutionScope,
TypeOrMethodDef, MaxCIx }
internal enum MapType { eventMap, propertyMap, nestedClass }
public enum ValueClass { ValueType, Enum }
public enum GenParamType : byte {
Var = 0x13, MVar = 0x1E
}
[Flags]
public enum GenericParamAttributes : ushort {
VarianceMask = 0x0003,
NonVariant = 0x0000,
Covariant = 0x0001,
Contravariant = 0x0002,
SpecialConstraintMask = 0x001c,
ReferenceTypeConstraint = 0x0004,
NotNullableValueTypeConstraint = 0x0008,
DefaultConstructorConstrait = 0x0010
}
/* Taken from Mono.Cecil */
public enum SecurityAction : short {
Request = 1,
Demand = 2,
Assert = 3,
Deny = 4,
PermitOnly = 5,
LinkDemand = 6,
InheritDemand = 7,
RequestMinimum = 8,
RequestOptional = 9,
RequestRefuse = 10,
PreJitGrant = 11,
PreJitDeny = 12,
NonCasDemand = 13,
NonCasLinkDemand = 14,
NonCasInheritance = 15,
LinkDemandChoice = 16,
InheritDemandChoice = 17,
DemandChoice = 18
}
#endregion
/**************************************************************************/
/// <summary>
/// Base class for all Meta Data table elements
/// </summary>
public abstract class MetaDataElement: IComparable {
protected ArrayList customAttributes;
private uint row = 0;
protected bool done = false;
protected MDTable tabIx;
protected bool sortTable = false;
//Temporary hack..
private bool has_custom_attrs = false;
internal MetaDataElement() { }
public uint Row {
get {
return row;
}
set {
row = value;
}
}
public bool HasCustomAttr {
get { return has_custom_attrs; }
set { has_custom_attrs = value; }
}
internal virtual uint GetCodedIx(CIx code) { return 0; }
/// <summary>
/// Add a custom attribute to this item
/// </summary>
/// <param name="ctorMeth">the constructor method for this attribute</param>
/// <param name="val">the byte value of the parameters</param>
public void AddCustomAttribute(Method ctorMeth, byte[] val)
{
if (customAttributes == null) {
customAttributes = new ArrayList();
}
customAttributes.Add(new CustomAttribute(this,ctorMeth,val));
}
/// <summary>
/// Add a custom attribute to this item
/// </summary>
/// <param name="ctorMeth">the constructor method for this attribute</param>
/// <param name="val">the constant values of the parameters</param>
public void AddCustomAttribute(Method ctorMeth, Constant[] cVals)
{
if (customAttributes == null) {
customAttributes = new ArrayList();
}
// customAttributes.Add(new CustomAttribute(this,ctorMeth,cVals));
}
internal uint Token()
{
return (((uint)tabIx << 24) | row);
}
internal virtual void BuildTables(MetaData md)
{
done = true;
}
internal virtual uint Size(MetaData md)
{
return 0;
}
internal virtual void Write(FileImage output) { }
internal virtual uint SortKey()
{
throw new PEFileException("Trying to sort table of " + this);
//return 0;
}
internal virtual uint SortKey2()
{
return 0;
}
public int CompareTo(object obj)
{
uint otherKey = ((MetaDataElement)obj).SortKey();
uint thisKey = SortKey();
if (thisKey == otherKey) {
otherKey = ((MetaDataElement)obj).SortKey2();
thisKey = SortKey2();
if (thisKey == otherKey)
return 0;
if (thisKey < otherKey)
return -1;
return 1;
}
if (thisKey < otherKey) return -1;
return 1;
}
}
/**************************************************************************/
/// <summary>
/// Layout information for a class (.class [sequential | explicit])
/// </summary>
internal class ClassLayout : MetaDataElement {
ClassDef parent;
ushort packSize = 0;
uint classSize = 0;
internal ClassLayout(int pack, int cSize, ClassDef par)
{
packSize = (ushort)pack;
classSize = (uint)cSize;
parent = par;
tabIx = MDTable.ClassLayout;
}
internal sealed override uint Size(MetaData md)
{
return 6 + md.TableIndexSize(MDTable.TypeDef);
}
internal sealed override void Write(FileImage output)
{
output.Write(packSize);
output.Write(classSize);
output.WriteIndex(MDTable.TypeDef,parent.Row);
}
}
/**************************************************************************/
/// <summary>
/// Summary description for ConstantElem.
/// </summary>
internal class ConstantElem : MetaDataElement {
MetaDataElement parent;
Constant cValue;
uint valIx = 0;
internal ConstantElem(MetaDataElement parent, Constant val)
{
this.parent = parent;
cValue = val;
tabIx = MDTable.Constant;
sortTable = true;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasConst])
| parent.GetCodedIx(CIx.HasConst);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
valIx = cValue.GetBlobIndex(md);
done = true;
}
internal void AddToBlob(BinaryWriter bw)
{
cValue.Write(bw);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.CodedIndexSize(CIx.HasConst) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(cValue.GetTypeIndex());
output.Write((byte)0);
output.WriteCodedIndex(CIx.HasConst,parent);
output.BlobIndex(valIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a Custom Attribute (.custom)
/// </summary>
public class CustomAttribute : MetaDataElement {
private static readonly ushort prolog = 0x0001;
MetaDataElement parent;
Method type;
uint valIx;
Constant cVal;
byte[] byteVal;
ushort numNamed = 0;
ArrayList names, vals;
internal CustomAttribute(MetaDataElement paren, Method constrType,
Constant val) {
parent = paren;
type = constrType;
cVal = val;
tabIx = MDTable.CustomAttribute;
}
internal CustomAttribute(MetaDataElement paren, Method constrType,
byte[] val) {
parent = paren;
type = constrType;
tabIx = MDTable.CustomAttribute;
byteVal = val;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasCustomAttr])
| parent.GetCodedIx(CIx.HasCustomAttr);
}
public void AddFieldOrProp(string name, Constant val)
{
if (numNamed == 0) {
names = new ArrayList();
vals = new ArrayList();
}
names.Add(name);
vals.Add(val);
}
internal sealed override void BuildTables(MetaData md)
{
md.AddToTable(MDTable.CustomAttribute, this);
if (byteVal == null) {
valIx = 0;
return;
}
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(byteVal);
MemoryStream str = (MemoryStream)bw.BaseStream;
valIx = md.AddToBlobHeap(str.ToArray());
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.HasCustomAttr) + md.CodedIndexSize(CIx.CustomAttributeType) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.HasCustomAttr,parent);
output.WriteCodedIndex(CIx.CustomAttributeType,type);
output.BlobIndex(valIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for security permissions for a class or a method
/// </summary>
public abstract class BaseDeclSecurity : MetaDataElement {
ushort action;
MetaDataElement parent;
uint permissionIx;
internal BaseDeclSecurity(MetaDataElement paren, ushort act)
{
parent = paren;
action = act;
tabIx = MDTable.DeclSecurity;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasDeclSecurity])
| parent.GetCodedIx(CIx.HasDeclSecurity);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.CodedIndexSize(CIx.HasDeclSecurity) + md.BlobIndexSize();
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
BinaryWriter bw = new BinaryWriter (new MemoryStream ());
md.AddToTable (MDTable.DeclSecurity, this);
MemoryStream str = (MemoryStream)bw.BaseStream;
WriteSig (bw);
permissionIx = md.AddToBlobHeap(str.ToArray());
done = true;
}
internal abstract void WriteSig (BinaryWriter bw);
internal sealed override void Write(FileImage output)
{
output.Write(action);
output.WriteCodedIndex(CIx.HasDeclSecurity,parent);
output.BlobIndex(permissionIx);
}
}
public class DeclSecurity : BaseDeclSecurity {
byte [] byteVal;
internal DeclSecurity(MetaDataElement paren, ushort act, byte [] val)
: base (paren, act)
{
byteVal = val;
}
internal override void WriteSig (BinaryWriter bw)
{
bw.Write (byteVal);
}
}
public class DeclSecurity_20 : BaseDeclSecurity {
PermissionSet ps;
internal DeclSecurity_20 (MetaDataElement paren, ushort act, PermissionSet ps)
: base (paren, act)
{
this.ps = ps;
}
internal override void WriteSig (BinaryWriter bw)
{
ps.Write (bw);
}
}
public class PermissionMember {
MemberTypes member_type;
PEAPI.Type type;
string name;
object value;
public PermissionMember (MemberTypes member_type, PEAPI.Type type, string name, object value)
{
this.member_type = member_type;
this.type = type;
this.name = name;
this.value = value;
}
public void Write (BinaryWriter bw)
{
byte [] b;
if (member_type == MemberTypes.Field)
bw.Write ((byte) 0x53);
else
//Property
bw.Write ((byte) 0x54);
if (type is PrimitiveType) {
bw.Write (type.GetTypeIndex ());
} else {
//must be enum
bw.Write ((byte) 0x55); //ENUM
b = Encoding.UTF8.GetBytes (((ClassRef) type).TypeName ());
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
}
b = Encoding.UTF8.GetBytes (name);
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
((Constant) value).Write (bw);
}
}
public class Permission
{
PEAPI.Type type;
//PermissionMembers
ArrayList members;
string name;
public Permission (PEAPI.Type type, string name)
{
this.type = type;
this.name = name;
}
public void AddMember (PEAPI.PermissionMember member)
{
if (members == null)
members = new ArrayList ();
members.Add (member);
}
public void Write (BinaryWriter bw)
{
byte [] b = Encoding.UTF8.GetBytes (name);
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
BinaryWriter perm_writer = new BinaryWriter (new MemoryStream (), Encoding.Unicode);
MemoryStream str = (MemoryStream) perm_writer.BaseStream;
MetaData.CompressNum ((uint) members.Count, str);//number of params
foreach (PermissionMember member in members)
member.Write (perm_writer);
bw.Write ((byte) str.Length); //(optional) parameters length
bw.Write (str.ToArray ());
}
}
public class PermissionSet
{
PEAPI.SecurityAction sec_action;
ArrayList permissions;
PEAPI.PermissionSet ps;
public PermissionSet (PEAPI.SecurityAction sec_action)
{
this.sec_action = sec_action;
}
public void AddPermission (PEAPI.Permission perm)
{
if (permissions == null)
permissions = new ArrayList ();
permissions.Add (perm);
}
public void Write (BinaryWriter bw)
{
bw.Write ((byte) 0x2e);
MetaData.CompressNum ((uint) permissions.Count, (MemoryStream) bw.BaseStream);
foreach (Permission perm in permissions)
perm.Write (bw);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for layout information for a field
/// </summary>
public class FieldLayout : MetaDataElement {
Field field;
uint offset;
internal FieldLayout(Field field, uint offset)
{
this.field = field;
this.offset = offset;
tabIx = MDTable.FieldLayout;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.TableIndexSize(MDTable.Field);
}
internal sealed override void Write(FileImage output)
{
output.Write(offset);
output.WriteIndex(MDTable.Field,field.Row);
}
}
/*****************************************************************************/
/// <summary>
/// Marshalling information for a field or param
/// </summary>
public class FieldMarshal : MetaDataElement {
MetaDataElement field;
NativeType nt;
uint ntIx;
internal FieldMarshal(MetaDataElement field, NativeType nType)
{
this.field = field;
this.nt = nType;
tabIx = MDTable.FieldMarshal;
}
internal override uint SortKey()
{
return (field.Row << MetaData.CIxShiftMap[(uint)CIx.HasFieldMarshal])
| field.GetCodedIx(CIx.HasFieldMarshal);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
ntIx = md.AddToBlobHeap(nt.ToBlob());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.HasFieldMarshal) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.HasFieldMarshal,field);
output.BlobIndex(ntIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the address of a field's value in the PE file
/// </summary>
public class FieldRVA : MetaDataElement {
Field field;
DataConstant data;
internal FieldRVA(Field field, DataConstant data)
{
this.field = field;
this.data = data;
tabIx = MDTable.FieldRVA;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
md.AddData(data);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.TableIndexSize(MDTable.Field);
}
internal sealed override void Write(FileImage output)
{
output.WriteDataRVA(data.DataOffset);
output.WriteIndex(MDTable.Field,field.Row);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a file referenced in THIS assembly/module (.file)
/// </summary>
public class FileRef : MetaDataElement {
private static readonly uint NoMetaData = 0x1;
uint nameIx = 0, hashIx = 0;
uint flags = 0;
protected string name;
internal FileRef(string name, byte[] hashBytes, bool metaData,
bool entryPoint, MetaData md) {
if (!metaData) flags = NoMetaData;
if (entryPoint) md.SetEntryPoint(this);
this.name = name;
nameIx = md.AddToStringsHeap(name);
hashIx = md.AddToBlobHeap(hashBytes);
tabIx = MDTable.File;
}
internal FileRef(uint nameIx, byte[] hashBytes, bool metaData,
bool entryPoint, MetaData md) {
if (!metaData) flags = NoMetaData;
if (entryPoint) md.SetEntryPoint(this);
this.nameIx = nameIx;
hashIx = md.AddToBlobHeap(hashBytes);
tabIx = MDTable.File;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void BuildTables(MetaData md)
{
md.AddToTable(MDTable.File,this);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(hashIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 16;
case (CIx.Implementation) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for pinvoke information for a method NOT YET IMPLEMENTED
/// </summary>
public class ImplMap : MetaDataElement {
private static readonly ushort NoMangle = 0x01;
ushort flags;
Method meth;
string importName;
uint iNameIx;
ModuleRef importScope;
internal ImplMap(ushort flag, Method implMeth, string iName, ModuleRef mScope)
{
flags = flag;
meth = implMeth;
importName = iName;
importScope = mScope;
tabIx = MDTable.ImplMap;
if (iName == null) flags |= NoMangle;
//throw(new NotYetImplementedException("PInvoke "));
}
internal override uint SortKey()
{
return (meth.Row << MetaData.CIxShiftMap[(uint)CIx.MemberForwarded])
| meth.GetCodedIx(CIx.MemberForwarded);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
iNameIx = md.AddToStringsHeap(importName);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2+ md.CodedIndexSize(CIx.MemberForwarded) +
md.StringsIndexSize() + md.TableIndexSize(MDTable.ModuleRef);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.WriteCodedIndex(CIx.MemberForwarded,meth);
output.StringsIndex(iNameIx);
output.WriteIndex(MDTable.ModuleRef,importScope.Row);
}
}
/**************************************************************************/
public class GenericParameter : MetaDataElement {
MetaDataElement owner;
MetaData metadata;
public string name;
uint nameIx;
short index;
GenericParamAttributes attr;
internal GenericParameter (ClassDef owner, MetaData metadata,
short index, string name, GenericParamAttributes attr) : this (owner, metadata, index, name, attr, true)
{
}
internal GenericParameter (MethodDef owner, MetaData metadata,
short index, string name, GenericParamAttributes attr) : this (owner, metadata, index, name, attr, true)
{
}
private GenericParameter (MetaDataElement owner, MetaData metadata,
short index, string name, GenericParamAttributes attr, bool nadda) {
this.owner = owner;
this.metadata = metadata;
this.index = index;
tabIx = MDTable.GenericParam;
this.name = name;
this.attr = attr;
}
internal override uint SortKey()
{
return (owner.Row << MetaData.CIxShiftMap[(uint)CIx.TypeOrMethodDef])
| owner.GetCodedIx(CIx.TypeOrMethodDef);
}
internal override uint SortKey2 ()
{
return (uint) index;
}
public void AddConstraint (Type constraint)
{
metadata.AddToTable (MDTable.GenericParamConstraint,
new GenericParamConstraint (this, constraint));
}
internal sealed override uint Size(MetaData md)
{
return (uint) (4 +
md.CodedIndexSize(CIx.TypeOrMethodDef) +
md.StringsIndexSize ());
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
done = true;
}
internal sealed override void Write(FileImage output)
{
output.Write ((short) index);
output.Write ((short) attr);
output.WriteCodedIndex(CIx.TypeOrMethodDef, owner);
output.StringsIndex (nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 19;
}
return 0;
}
}
internal class GenericParamConstraint : MetaDataElement {
GenericParameter param;
Type type;
public GenericParamConstraint (GenericParameter param, Type type)
{
this.param = param;
this.type = type;
tabIx = MDTable.GenericParamConstraint;
}
internal override uint SortKey()
{
return param.Row;
}
internal sealed override uint Size(MetaData md)
{
return (uint) (md.TableIndexSize(MDTable.GenericParam) +
md.CodedIndexSize(CIx.TypeDefOrRef));
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.GenericParam, param.Row);
output.WriteCodedIndex(CIx.TypeDefOrRef, type);
}
}
internal class MethodSpec : Method {
Method meth;
GenericMethodSig g_sig;
uint sidx;
internal MethodSpec (Method meth, GenericMethodSig g_sig) : base ("")
{
this.meth = meth;
this.g_sig = g_sig;
tabIx = MDTable.MethodSpec;
}
internal override uint GetSigIx (MetaData md)
{
throw new Exception ("Should not be used.");
}
public override void AddCallConv (CallConv cconv)
{
throw new Exception ("Should not be used.");
}
internal sealed override void BuildTables (MetaData md)
{
if (done) return;
sidx = g_sig.GetSigIx (md);
done = true;
}
internal sealed override uint Size (MetaData md)
{
return (uint) (md.CodedIndexSize(CIx.MethodDefOrRef) +
md.BlobIndexSize ());
}
internal sealed override void Write (FileImage output)
{
output.WriteCodedIndex (CIx.MethodDefOrRef, meth);
output.BlobIndex (sidx);
}
internal sealed override void TypeSig (MemoryStream sig)
{
throw new Exception ("Should not be used.");
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for interface implemented by a class
/// </summary>
public class InterfaceImpl: MetaDataElement {
ClassDef theClass;
Class theInterface;
internal InterfaceImpl(ClassDef theClass, Class theInterface)
{
this.theClass = theClass;
this.theInterface = theInterface;
tabIx = MDTable.InterfaceImpl;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) +
md.CodedIndexSize(CIx.TypeDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,theClass.Row);
output.WriteCodedIndex(CIx.TypeDefOrRef,theInterface);
}
internal sealed override uint GetCodedIx(CIx code) { return 5; }
internal override uint SortKey ()
{
return (theClass.Row << MetaData.CIxShiftMap[(uint)CIx.TypeDefOrRef])
| theClass.GetCodedIx (CIx.TypeDefOrRef);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for resources used in this PE file
/// </summary>
public class ManifestResource : MetaDataElement {
public static readonly uint PublicResource = 0x1;
public static readonly uint PrivateResource = 0x2;
string mrName;
MetaDataElement rRef;
uint fileOffset;
uint nameIx = 0;
uint flags = 0;
byte [] resourceBytes;
public ManifestResource (string name, byte[] resBytes, uint flags)
{
InitResource (name, flags);
this.resourceBytes = resBytes;
}
public ManifestResource(string name, uint flags, FileRef fileRef)
{
InitResource (name, flags);
rRef = fileRef;
}
public ManifestResource(string name, uint flags, FileRef fileRef,
uint fileIx) {
InitResource (name, flags);
rRef = fileRef;
fileOffset = fileIx;
}
public ManifestResource(string name, uint flags, AssemblyRef assemRef)
{
InitResource (name, flags);
rRef = assemRef;
}
internal ManifestResource (ManifestResource mres)
{
mrName = mres.mrName;
flags = mres.flags;
rRef = mres.rRef;
fileOffset = mres.fileOffset;
resourceBytes = mres.resourceBytes;
}
private void InitResource (string name, uint flags)
{
mrName = name;
this.flags = flags;
tabIx = MDTable.ManifestResource;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
md.AddToTable (MDTable.ManifestResource, this);
nameIx = md.AddToStringsHeap(mrName);
if (resourceBytes != null) {
if (rRef != null)
throw new PEFileException ("Manifest Resource has byte value and file reference");
fileOffset = md.AddResource(resourceBytes);
} else {
if (rRef == null)
throw new PEFileException ("Manifest Resource has no implementation or value");
rRef.BuildTables (md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 8 + md.StringsIndexSize() +
md.CodedIndexSize(CIx.Implementation);
}
internal sealed override void Write(FileImage output)
{
output.Write(fileOffset);
output.Write(flags);
output.StringsIndex(nameIx);
output.WriteCodedIndex(CIx.Implementation,rRef);
}
internal sealed override uint GetCodedIx(CIx code) { return 18; }
public string Name {
get { return mrName; }
set { mrName = value; }
}
}
/**************************************************************************/
/// <summary>
/// Base class for elements in the PropertyMap, EventMap and
/// NestedClass MetaData tables
/// </summary>
public class MapElem : MetaDataElement {
ClassDef parent;
uint elemIx;
MDTable elemTable;
internal MapElem(ClassDef par, uint elIx, MDTable elemTab)
{
parent = par;
elemIx = elIx;
elemTable = elemTab;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) + md.TableIndexSize(elemTable);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,parent.Row);
output.WriteIndex(elemTable,elemIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an overriding method (.override)
/// </summary>
public class MethodImpl : MetaDataElement {
ClassDef parent;
Method header, body;
internal MethodImpl(ClassDef par, Method decl, Method bod)
{
parent = par;
header = decl;
body = bod;
tabIx = MDTable.MethodImpl;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) + 2 * md.CodedIndexSize(CIx.MethodDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,parent.Row);
output.WriteCodedIndex(CIx.MethodDefOrRef,body);
output.WriteCodedIndex(CIx.MethodDefOrRef,header);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for Property and Event methods
/// </summary>
public class MethodSemantics : MetaDataElement {
Feature.MethodType type;
MethodDef meth;
Feature eventOrProp;
internal MethodSemantics(Feature.MethodType mType, MethodDef method, Feature feature)
{
type = mType;
meth = method;
eventOrProp = feature;
tabIx = MDTable.MethodSemantics;
}
internal override uint SortKey()
{
return (eventOrProp.Row << MetaData.CIxShiftMap [(uint)CIx.HasSemantics])
| eventOrProp.GetCodedIx (CIx.HasSemantics);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.TableIndexSize(MDTable.Method) + md.CodedIndexSize(CIx.HasSemantics);
}
internal sealed override void Write(FileImage output)
{
output.Write((ushort)type);
output.WriteIndex(MDTable.Method,meth.Row);
output.WriteCodedIndex(CIx.HasSemantics,eventOrProp);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a parameter of a method defined in this assembly/module
/// </summary>
public class Param : MetaDataElement {
Type pType;
string pName;
internal ushort seqNo = 0;
ushort parMode;
ConstantElem defaultVal;
uint nameIx = 0;
FieldMarshal marshalInfo;
/// <summary>
/// Create a new parameter for a method
/// </summary>
/// <param name="mode">param mode (in, out, opt)</param>
/// <param name="parName">parameter name</param>
/// <param name="parType">parameter type</param>
public Param(ParamAttr mode, string parName, Type parType)
{
pName = parName;
pType = parType;
parMode = (ushort)mode;
tabIx = MDTable.Param;
}
public bool HasMarshalInfo {
get { return marshalInfo != null; }
}
/// <summary>
/// Add a default value to this parameter
/// </summary>
/// <param name="c">the default value for the parameter</param>
public void AddDefaultValue(Constant cVal)
{
defaultVal = new ConstantElem(this,cVal);
parMode |= (ushort) ParamAttr.HasDefault;
}
/// <summary>
/// Add marshalling information about this parameter
/// </summary>
public void AddMarshallInfo(NativeType marshallType)
{
parMode |= (ushort) ParamAttr.HasFieldMarshal;
marshalInfo = new FieldMarshal(this,marshallType);
}
internal Type GetParType() { return pType; }
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(pName);
if (defaultVal != null) {
md.AddToTable(MDTable.Constant,defaultVal);
defaultVal.BuildTables(md);
}
if (marshalInfo != null) {
md.AddToTable(MDTable.FieldMarshal,marshalInfo);
marshalInfo.BuildTables(md);
}
done = true;
}
internal void TypeSig(MemoryStream str)
{
pType.TypeSig(str);
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(parMode);
output.Write(seqNo);
output.StringsIndex(nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 4;
case (CIx.HasConst) : return 1;
case (CIx.HasFieldMarshal) : return 1;
}
return 0;
}
}
/**************************************************************************/
public abstract class Signature : MetaDataElement {
protected uint sigIx;
internal Signature()
{
tabIx = MDTable.StandAloneSig;
}
internal sealed override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return (uint)tabIx; }
}
/**************************************************************************/
public class TypeSpec : MetaDataElement {
uint sigIx = 0;
internal TypeSpec(Type aType, MetaData md)
{
MemoryStream sig = new MemoryStream();
aType.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
tabIx = MDTable.TypeSpec;
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 2;
case (CIx.HasCustomAttr) : return 13;
case (CIx.MemberRefParent) : return 4;
}
return 0;
}
internal override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
//Console.WriteLine("Writing the blob index for a TypeSpec");
output.BlobIndex(sigIx);
}
}
/**************************************************************************/
/// <summary>
/// Base class for all IL types
/// </summary>
public abstract class Type : MetaDataElement {
protected byte typeIndex;
protected TypeSpec typeSpec;
internal Type(byte tyIx) { typeIndex = tyIx; }
internal byte GetTypeIndex() { return typeIndex; }
internal void SetTypeIndex (byte b) { typeIndex = b; }
internal virtual MetaDataElement GetTypeSpec(MetaData md)
{
if (typeSpec == null) {
typeSpec = new TypeSpec(this,md);
md.AddToTable(MDTable.TypeSpec,typeSpec);
}
return typeSpec;
}
internal virtual void TypeSig(MemoryStream str)
{
throw(new TypeSignatureException(this.GetType().AssemblyQualifiedName +
" doesn't have a type signature!!"));
}
}
public class ClassRefInst : Type {
private Type type;
private bool is_value;
public ClassRefInst (Type type, bool is_value) : base (PrimitiveType.Class.GetTypeIndex ())
{
this.type = type;
this.is_value = is_value;
if (is_value)
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
type.TypeSig (str);
}
}
/**************************************************************************/
/// <summary>
/// The base descriptor for a class
/// </summary>
public abstract class Class : Type {
protected int row = 0;
public string name, nameSpace;
protected uint nameIx, nameSpaceIx;
protected MetaData _metaData;
internal Class(string nameSpaceName, string className, MetaData md)
: base(PrimitiveType.Class.GetTypeIndex ())
{
nameSpace = nameSpaceName;
name = className;
nameIx = md.AddToStringsHeap(name);
nameSpaceIx = md.AddToStringsHeap(nameSpace);
_metaData = md;
}
internal Class(uint nsIx, uint nIx) : base(PrimitiveType.Class.GetTypeIndex ())
{
nameSpaceIx = nsIx;
nameIx = nIx;
}
internal Class (byte typeIndex) : base (typeIndex)
{
nameSpace = "Should not be used";
name = "Should not be used";
}
internal virtual uint TypeDefOrRefToken() { return 0; }
internal virtual void MakeValueClass(ValueClass vClass)
{
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
}
internal virtual string TypeName()
{
return (nameSpace + "." + name);
}
internal override MetaDataElement GetTypeSpec(MetaData md)
{
return this;
}
}
/**************************************************************************/
// This Class produces entries in the TypeDef table of the MetaData
// in the PE meta data.
// NOTE: Entry 0 in TypeDef table is always the pseudo class <module>
// which is the parent for functions and variables declared a module level
/// <summary>
/// The descriptor for a class defined in the IL (.class) in the current assembly/module
/// </summary>
///
public class ClassDef : Class {
private static readonly byte ElementType_Class = 0x12;
Class superType;
ArrayList fields = new ArrayList();
ArrayList methods = new ArrayList();
ArrayList events;
ArrayList properties;
bool typeIndexChecked = true;
uint fieldIx = 0, methodIx = 0;
byte[] securityActions;
uint flags;
ClassLayout layout;
ClassDef parentClass;
MetaData metaData;
internal ClassDef(TypeAttr attrSet, string nsName, string name,
MetaData md) : base(nsName, name, md)
{
metaData = md;
if (! ((nsName == "" && name == "<Module>") || (nsName == "System" && name == "Object")) ) {
superType = metaData.mscorlib.GetSpecialSystemClass(PrimitiveType.Object);
}
flags = (uint)attrSet;
tabIx = MDTable.TypeDef;
}
internal void SetSuper(Class sClass)
{
superType = sClass;
if (! (sClass is GenericTypeInst))
typeIndexChecked = false;
}
internal override void MakeValueClass(ValueClass vClass)
{
if (vClass == ValueClass.Enum)
superType = metaData.mscorlib.EnumType();
else
superType = metaData.mscorlib.ValueType();
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
}
public void SpecialNoSuper()
{
superType = null;
}
/// <summary>
/// Add an attribute to this class
/// </summary>
/// <param name="ta">the attribute to be added</param>
public void AddAttribute(TypeAttr ta)
{
flags |= (uint)ta;
}
/// <summary>
/// Add an interface that is implemented by this class
/// </summary>
/// <param name="iFace">the interface that is implemented</param>
public void AddImplementedInterface(Class iFace)
{
metaData.AddToTable(MDTable.InterfaceImpl,new InterfaceImpl(this,iFace));
}
/// <summary>
/// Add a named generic type parameter
/// </summary>
public GenericParameter AddGenericParameter (short index, string name)
{
return AddGenericParameter (index, name, 0);
}
/// <summary>
/// Add a named generic type parameter with attributes
/// </summary>
public GenericParameter AddGenericParameter (short index, string name, GenericParamAttributes attr)
{
GenericParameter gp = new GenericParameter (this, metaData, index, name, attr);
metaData.AddToTable (MDTable.GenericParam, gp);
return gp;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this new field</returns>
public FieldDef AddField(string name, Type fType)
{
FieldDef field = new FieldDef(name,fType);
fields.Add(field);
return field;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="fAtts">attributes for this field</param>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this new field</returns>
public FieldDef AddField(FieldAttr fAtts, string name, Type fType)
{
FieldDef field = new FieldDef(fAtts,name,fType);
fields.Add(field);
return field;
}
public void SetFieldOrder (ArrayList fields)
{
this.fields = fields;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameters</param>
/// <returns>a descriptor for this new method</returns>
public MethodDef AddMethod(string name, Type retType, Param[] pars)
{
return AddMethod (name, new Param (ParamAttr.Default, "", retType), pars);
}
public MethodDef AddMethod (string name, Param ret_param, Param [] pars)
{
// Console.WriteLine("Adding method " + name + " to class " + this.name);
MethodDef meth = new MethodDef(metaData,name, ret_param, pars);
methods.Add(meth);
return meth;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="mAtts">attributes for this method</param>
/// <param name="iAtts">implementation attributes for this method</param>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameters</param>
/// <returns>a descriptor for this new method</returns>
public MethodDef AddMethod(MethAttr mAtts, ImplAttr iAtts, string name,
Param ret_param, Param [] pars) {
// Console.WriteLine("Adding method " + name + " to class " + this.name);
MethodDef meth = new MethodDef (metaData, mAtts, iAtts, name, ret_param, pars);
methods.Add(meth);
return meth;
}
/// <summary>
/// Add an event to this class
/// </summary>
/// <param name="name">event name</param>
/// <param name="eType">event type</param>
/// <returns>a descriptor for this new event</returns>
public Event AddEvent(string name, Type eType)
{
Event e = new Event(name,eType,this);
if (events == null) events = new ArrayList();
events.Add(e);
return e;
}
/// <summary>
/// Add a property to this class
/// </summary>
/// <param name="name">property name</param>
/// <param name="propType">property type</param>
/// <returns>a descriptor for this new property</returns>
public Property AddProperty(string name, Type retType, Type[] pars)
{
Property p = new Property(name, retType, pars, this);
if (properties == null) properties = new ArrayList();
properties.Add(p);
return p;
}
/// <summary>
/// Add a nested class to this class
/// </summary>
/// <param name="attrSet">attributes for this nested class</param>
/// <param name="nsName">nested name space name</param>
/// <param name="name">nested class name</param>
/// <returns>a descriptor for this new nested class</returns>
public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
string name) {
ClassDef nClass = new ClassDef(attrSet,"",name,metaData);
metaData.AddToTable(MDTable.TypeDef,nClass);
metaData.AddToTable(MDTable.NestedClass,new MapElem(nClass,Row,MDTable.TypeDef));
nClass.parentClass = this;
return (nClass);
}
public static bool IsValueType (Class type)
{
return IsValueType (type.nameSpace, type.name);
}
public static bool IsEnum (Class type)
{
return IsEnum (type.nameSpace, type.name);
}
public static bool IsValueType (string nsName, string name)
{
return (nsName == "System" && name == "ValueType");
}
public static bool IsEnum (string nsName, string name)
{
return (nsName == "System" && name == "Enum");
}
/// <summary>
/// Add a nested class to this class
/// </summary>
/// <param name="attrSet">attributes for this nested class</param>
/// <param name="nsName">nested name space name</param>
/// <param name="name">nested class name</param>
/// <param name="sType">super type of this nested class</param>
/// <returns>a descriptor for this new nested class</returns>
public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
string name, Class sType) {
ClassDef nClass = AddNestedClass (attrSet, nsName, name);
nClass.SetSuper(sType);
if (ClassDef.IsValueType (sType))
nClass.MakeValueClass (ValueClass.ValueType);
else
if (ClassDef.IsEnum (sType))
nClass.MakeValueClass (ValueClass.Enum);
if (ClassDef.IsValueType (sType) || ClassDef.IsEnum (sType))
nClass.SetTypeIndex (PrimitiveType.ValueType.GetTypeIndex ());
nClass.typeIndexChecked = true;
return (nClass);
}
/// <summary>
/// Add layout information for this class. This class must have the
/// sequential or explicit attribute.
/// </summary>
/// <param name="packSize">packing size (.pack)</param>
/// <param name="classSize">class size (.size)</param>
public void AddLayoutInfo (int packSize, int classSize)
{
layout = new ClassLayout(packSize,classSize,this);
}
/// <summary>
/// Use a method as the implementation for another method (.override)
/// </summary>
/// <param name="decl">the method to be overridden</param>
/// <param name="body">the implementation to be used</param>
public void AddMethodOverride(Method decl, Method body)
{
metaData.AddToTable(MDTable.MethodImpl,new MethodImpl(this,decl,body));
}
/// <summary>
/// Add security to this class NOT YET IMPLEMENTED
/// </summary>
/// <param name="permissionSet"></param>
public void AddSecurity(byte[] permissionSet)
{
throw(new NotYetImplementedException("Class security "));
//flags |= HasSecurity;
// securityActions = permissionSet;
}
//public void AddLineInfo(int row, int col) { }
internal void CheckTypeIndex()
{
if (typeIndexChecked) return;
if (superType is ClassDef)
((ClassDef)superType).CheckTypeIndex();
typeIndex = superType.GetTypeIndex();
typeIndexChecked = true;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
if ((flags & (uint)TypeAttr.Interface) != 0) { superType = null; }
// Console.WriteLine("Building tables for " + name);
if (layout != null) md.AddToTable(MDTable.ClassLayout,layout);
// Console.WriteLine("adding methods " + methods.Count);
methodIx = md.TableIndex(MDTable.Method);
for (int i=0; i < methods.Count; i++) {
md.AddToTable(MDTable.Method,(MetaDataElement)methods[i]);
((MethodDef)methods[i]).BuildTables(md);
}
// Console.WriteLine("adding fields");
fieldIx = md.TableIndex(MDTable.Field);
for (int i=0; i < fields.Count; i++) {
md.AddToTable(MDTable.Field,(MetaDataElement)fields[i]);
((FieldDef)fields[i]).BuildTables(md);
}
// Console.WriteLine("adding events and properties");
if (events != null) {
for (int i=0; i < events.Count; i++) {
md.AddToTable(MDTable.Event,(Event)events[i]);
((Event)events[i]).BuildTables(md);
}
md.AddToTable(MDTable.EventMap,
new MapElem(this,((Event)events[0]).Row,MDTable.Event));
}
if (properties != null) {
for (int i=0; i < properties.Count; i++) {
md.AddToTable(MDTable.Property,(Property)properties[i]);
((Property)properties[i]).BuildTables(md);
}
md.AddToTable(MDTable.PropertyMap,new MapElem(this,
((Property)properties[0]).Row,MDTable.Property));
}
// Console.WriteLine("End of building tables");
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 4 + 2 * md.StringsIndexSize() +
md.CodedIndexSize(CIx.TypeDefOrRef) +
md.TableIndexSize(MDTable.Field) +
md.TableIndexSize(MDTable.Method);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
//if (superType != null)
// Console.WriteLine("getting coded index for superType of " + name + " = " + superType.GetCodedIx(CIx.TypeDefOrRef));
output.WriteCodedIndex(CIx.TypeDefOrRef,superType);
output.WriteIndex(MDTable.Field,fieldIx);
output.WriteIndex(MDTable.Method,methodIx);
}
internal sealed override uint TypeDefOrRefToken()
{
uint cIx = Row;
cIx = cIx << 2;
return cIx;
}
internal sealed override void TypeSig(MemoryStream sig)
{
if (!typeIndexChecked) CheckTypeIndex();
sig.WriteByte(GetTypeIndex());
MetaData.CompressNum(TypeDefOrRefToken(),sig);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 0;
case (CIx.HasCustomAttr) : return 3;
case (CIx.HasDeclSecurity) : return 0;
case (CIx.TypeOrMethodDef) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class/interface declared in another module of THIS
/// assembly, or in another assembly.
/// </summary>
public class ClassRef : Class, IExternRef, IResolutionScope {
protected IResolutionScope parent;
ExternClass externClass;
protected MetaData metaData;
internal ClassRef(string nsName, string name, MetaData md) : base(nsName, name, md)
{
metaData = md;
tabIx = MDTable.TypeRef;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddMethod(string name, Type retType, Type[] pars)
{
return AddMethod (name, retType, pars, 0);
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <param name="gen_param_count">num of generic parameters</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddMethod (string name, Type retType, Type[] pars, int gen_param_count)
{
MethodRef meth = new MethodRef (this, name, retType, pars, false, null, gen_param_count);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddVarArgMethod(string name, Type retType,
Type[] pars, Type[] optPars)
{
MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this field</returns>
public FieldRef AddField(string name, Type fType)
{
FieldRef field = new FieldRef(this,name,fType);
metaData.AddToTable(MDTable.MemberRef,field);
return field;
}
public ClassRef AddClass (string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
public ClassRef AddValueClass (string nsName, string name)
{
ClassRef aClass = AddClass (nsName, name);
aClass.MakeValueClass (ValueClass.ValueType);
return aClass;
}
internal void SetParent(IResolutionScope par)
{
parent = par;
}
internal override string TypeName()
{
if ((parent != null) && (parent is AssemblyRef))
return (nameSpace + "." + name + ", " + ((AssemblyRef)parent).TypeName());
else
return (nameSpace + name);
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.ResolutionScope) + 2 *
md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.ResolutionScope,(MetaDataElement) parent);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
}
internal override sealed uint TypeDefOrRefToken()
{
uint cIx = Row;
cIx = (cIx << 2) | 0x1;
return cIx;
}
internal override void TypeSig(MemoryStream sig)
{
sig.WriteByte(GetTypeIndex());
MetaData.CompressNum(TypeDefOrRefToken(),sig);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 1;
case (CIx.HasCustomAttr) : return 2;
case (CIx.MemberRefParent) : return 1;
case (CIx.ResolutionScope) : return 3;
}
return 0;
}
}
/**************************************************************************/
public class ExternClassRef : ClassRef {
ExternClass externClass;
internal ExternClassRef(TypeAttr attrs, string nsName, string name,
FileRef declFile, MetaData md) : base(nsName,name,md)
{
externClass = new ExternClass(attrs,nameSpaceIx,nameIx,declFile);
metaData.AddToTable(MDTable.ExportedType,externClass);
}
internal ExternClassRef(string name, MetaData md) : base(null,name,md)
{
}
public ClassRef AddNestedClass(TypeAttr attrs, string name)
{
ExternClassRef nestedClass = new ExternClassRef(name,metaData);
externClass = new ExternClass(attrs,0,nameIx,this.externClass);
metaData.AddToTable(MDTable.ExportedType,externClass);
return nestedClass;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class defined in another module of THIS assembly
/// and exported (.class extern)
/// </summary>
internal class ExternClass : Class {
MetaDataElement parent;
uint flags;
internal ExternClass(TypeAttr attr, uint nsIx, uint nIx,
MetaDataElement paren) : base(nsIx,nIx)
{
flags = (uint)attr;
parent = paren;
tabIx = MDTable.ExportedType;
}
internal sealed override uint Size(MetaData md)
{
return 8 + 2* md.StringsIndexSize() + md.CodedIndexSize(CIx.Implementation);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.Write(0);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
output.WriteCodedIndex(CIx.Implementation,parent);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 17;
case (CIx.Implementation) : return 2;
}
return 0;
}
}
public class GenParam : Class {
private int index;
private string param_name;
private uint sigIx = 0;
public GenParam (int index, string name, GenParamType ptype) : base ((byte) ptype)
{
this.index = index;
this.param_name = name;
tabIx = MDTable.TypeSpec;
}
public int Index {
get { return index; }
set { index = value; }
}
public string Name {
get { return param_name; }
set { param_name = value; }
}
public GenParamType Type {
get { return (GenParamType) GetTypeIndex (); }
}
internal sealed override void BuildTables (MetaData md)
{
if (done)
return;
MemoryStream str = new MemoryStream ();
TypeSig (str);
sigIx = md.AddToBlobHeap (str.ToArray ());
done = true;
}
internal sealed override void TypeSig(MemoryStream str)
{
if (index < 0)
throw new PEFileException (String.Format ("Unresolved {0} - {1}", (GenParamType) GetTypeIndex (), param_name));
str.WriteByte(typeIndex);
MetaData.CompressNum ((uint) index, str);
}
internal override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write (FileImage output)
{
output.BlobIndex (sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 2;
case (CIx.HasCustomAttr) : return 13;
case (CIx.MemberRefParent) : return 4;
}
return 0;
}
}
public class GenericTypeInst : Class {
private Type gen_type;
private Type[] gen_param;
bool inTable = false;
uint sigIx = 0;
public GenericTypeInst (Type gen_type, Type[] gen_param)
: base ((byte) PrimitiveType.GenericInst.GetTypeIndex ())
{
this.gen_type = gen_type;
this.gen_param = gen_param;
tabIx = MDTable.TypeSpec;
}
internal override MetaDataElement GetTypeSpec (MetaData md)
{
if (!inTable) {
md.AddToTable (MDTable.TypeSpec, this);
inTable = true;
}
return this;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
gen_type.TypeSig (str);
MetaData.CompressNum ((uint) gen_param.Length, str);
foreach (Type param in gen_param)
param.TypeSig (str);
}
internal sealed override void BuildTables (MetaData md)
{
if (done)
return;
MemoryStream str = new MemoryStream ();
TypeSig (str);
sigIx = md.AddToBlobHeap (str.ToArray ());
done = true;
}
internal sealed override uint Size (MetaData md)
{
return md.BlobIndexSize ();
}
internal sealed override void Write (FileImage output)
{
output.BlobIndex (sigIx);
}
internal sealed override uint GetCodedIx (CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef): return 2;
case (CIx.MemberRefParent): return 4;
case (CIx.HasCustomAttr): return 13;
}
return 0;
}
}
public class GenericMethodSig {
private Type[] gen_param;
private bool done;
private uint sigIx = 0;
public GenericMethodSig (Type[] gen_param)
{
this.gen_param = gen_param;
done = false;
}
internal void TypeSig (MemoryStream str)
{
str.WriteByte (0x0A); /* GENERIC_INST */
MetaData.CompressNum ((uint) gen_param.Length, str);
foreach (Type param in gen_param)
param.TypeSig (str);
}
internal uint GetSigIx (MetaData md)
{
if (done)
return sigIx;
MemoryStream sig = new MemoryStream();
TypeSig (sig);
sigIx = md.AddToBlobHeap (sig.ToArray());
done = true;
return sigIx;
}
}
public class Sentinel : Type {
public Sentinel () : base (0x41) { }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a FunctionPointer type
/// </summary>
///
public class MethPtrType : Type {
bool varArgMeth;
Type retType;
Type [] parList;
Type [] optParList;
CallConv callConv;
uint numPars;
uint numOptPars;
uint sigIx = 0;
/// <summary>
/// Create a new function pointer type
/// </summary>
/// <param name="meth">the function to be referenced</param>
public MethPtrType (CallConv callconv, Type retType, Type[] pars,
bool varArgMeth, Type[] optPars) : base(0x1B)
{
this.retType = retType;
callConv = callconv;
parList = pars;
this.varArgMeth = varArgMeth;
if (parList != null) numPars = (uint)parList.Length;
if (varArgMeth) {
optParList = optPars;
if (optParList != null) numOptPars = (uint)optParList.Length;
callConv |= CallConv.Vararg;
}
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte(typeIndex);
// Bootlegged from method ref
sig.WriteByte((byte)callConv);
MetaData.CompressNum (numPars + numOptPars, sig);
retType.TypeSig (sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig (sig);
}
if (varArgMeth) {
sig.WriteByte (0x41); // Write the sentinel
for (int i=0; i < numOptPars; i++) {
optParList[i].TypeSig (sig);
}
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
MemoryStream sig = new MemoryStream();
TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return 0x1B; }
}
#region Array Types
/* Classes for Arrays */
/// <summary>
/// The IL Array type
/// </summary>
public abstract class Array : Type {
protected Type elemType;
protected MetaData metaData;
protected string cnameSpace, cname;
internal Array(Type eType, byte TypeId) : base(TypeId)
{
elemType = eType;
tabIx = MDTable.TypeSpec;
}
}
/// <summary>
/// Single dimensional array with zero lower bound
/// </summary>
public class ZeroBasedArray : Array {
/// <summary>
/// Create a new array - elementType[]
/// </summary>
/// <param name="elementType">the type of the array elements</param>
public ZeroBasedArray(Type elementType) : base (elementType, PrimitiveType.SZArray.GetTypeIndex ()) { }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
elemType.TypeSig(str);
}
}
/// <summary>
/// Multi dimensional array with explicit bounds
/// </summary>
public class BoundArray : Array {
int[] lowerBounds;
int[] sizes;
uint numDims;
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[1..5,3..10,5,,] would be
/// new BoundArray(elemType,5,[1,3,0],[5,10,4])
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
/// <param name="loBounds">lower bounds of dimensions</param>
/// <param name="sizes">sizes for the dimensions</param>
public BoundArray(Type elementType, uint dimensions, int[] loBounds,
int[] sizes) : base (elementType,0x14)
{
numDims = dimensions;
lowerBounds = loBounds;
this.sizes = sizes;
}
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[5,10,20] would be new BoundArray(elemType,3,[5,10,20])
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
/// <param name="size">the sizes of the dimensions</param>
public BoundArray(Type elementType, uint dimensions, int[] size)
: base (elementType,0x14)
{
numDims = dimensions;
sizes = size;
}
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[,,] would be new BoundArray(elemType,3)
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
public BoundArray(Type elementType, uint dimensions)
: base (elementType,0x14)
{
numDims = dimensions;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
elemType.TypeSig(str);
MetaData.CompressNum(numDims,str);
if ((sizes != null) && (sizes.Length > 0)) {
MetaData.CompressNum((uint)sizes.Length,str);
for (int i=0; i < sizes.Length; i++) {
MetaData.CompressNum((uint)sizes[i],str);
}
} else str.WriteByte(0);
if ((lowerBounds != null) && (lowerBounds.Length > 0)) {
MetaData.CompressNum((uint)lowerBounds.Length,str);
for (int i=0; i < lowerBounds.Length; i++) {
CompressSignedNum (lowerBounds[i],str);
}
} else str.WriteByte(0);
}
private void CompressSignedNum (int val, MemoryStream str)
{
uint uval = (uint) val;
byte sign = 0;
if (val < 0) {
val = -val;
sign = 1;
}
/* Map the signed number to an unsigned number in two ways.
fval: left-rotated 2's complement representation
sval: map the signed number to unsigned as follows: 0 -> 0, -1 -> 1, 1 -> 2, -2 -> 3, 2 -> 4, ....
the mapping is: x -> 2*|x| - signbit(x)
*/
uint fval = (uval << 1) | sign;
int sval = (val << 1) - sign;
/* An overly clever transformation:
a. sval is used to determine the number of bytes in the compressed representation.
b. fval is truncated to the appropriate number of bits and output using the
normal unsigned-int compressor.
However, or certain values, the truncated fval doesn't carry enough information to round trip.
(fval & 0x3FFF) <= 0x7F => compressor emits 1 byte, not 2 => there is aliasing of values
So, we use full 4 bytes to encode such values.
LAMESPEC: The Microsoft implementation doesn't appear to handle this subtle case.
e.g., it ends up encoding -8192 as the byte 0x01, which decodes to -64
*/
if (sval <= 0x7F)
MetaData.CompressNum (fval & 0x7F, str);
else if (sval <= 0x3FFF && (fval & 0x3FFF) > 0x7F)
MetaData.CompressNum (fval & 0x3FFF, str);
else if (sval <= 0x1FFFFFFF && (fval & 0x1FFFFFFF) > 0x3FFF)
MetaData.CompressNum (fval & 0x1FFFFFFF, str);
else
/* FIXME: number cannot be represented. Report a warning. */
// throw new Exception ("cannot represent signed value" + -val);
MetaData.CompressNum (fval, str);
}
}
#endregion
/* Empty interface for grouping TypeRef's possible ResolutionScope
namely : Module, ModuleRef, AssemblyRef and TypeRef */
public interface IResolutionScope {
}
/**************************************************************************/
/// <summary>
/// Base class for scopes (extended by Module, ModuleRef, Assembly, AssemblyRef)
/// </summary>
public abstract class ResolutionScope : MetaDataElement, IResolutionScope {
protected uint nameIx = 0;
protected MetaData metaData;
protected string name;
internal ResolutionScope(string name, MetaData md)
{
metaData = md;
this.name = name;
nameIx = md.AddToStringsHeap(name);
}
internal string GetName() { return name; }
}
/**************************************************************************/
/// <summary>
/// Descriptor for THIS assembly (.assembly)
/// </summary>
public class Assembly : ResolutionScope {
ushort majorVer, minorVer, buildNo, revisionNo;
uint flags;
uint hashAlgId;
uint keyIx = 0, cultIx = 0;
bool hasPublicKey = false;
internal Assembly(string name, MetaData md) : base(name,md)
{
tabIx = MDTable.Assembly;
}
/// <summary>
/// Add details about THIS assembly
/// </summary>
/// <param name="majVer">Major Version</param>
/// <param name="minVer">Minor Version</param>
/// <param name="bldNo">Build Number</param>
/// <param name="revNo">Revision Number</param>
/// <param name="key">Hash Key</param>
/// <param name="hash">Hash Algorithm</param>
/// <param name="cult">Culture</param>
public void AddAssemblyInfo(int majVer, int minVer, int bldNo, int revNo,
byte[] key, uint hash, string cult)
{
majorVer = (ushort)majVer;
minorVer = (ushort)minVer;
buildNo = (ushort)bldNo;
revisionNo = (ushort)revNo;
hashAlgId = hash;
hasPublicKey = (key != null);
keyIx = metaData.AddToBlobHeap(key);
cultIx = metaData.AddToStringsHeap(cult);
}
/// <summary>
/// Add an attribute to THIS assembly
/// </summary>
/// <param name="aa">assembly attribute</param>
public void AddAssemblyAttr(AssemAttr aa)
{
flags |= (uint)aa;
}
internal sealed override uint Size(MetaData md)
{
return 16 + md.BlobIndexSize() + 2 * md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
// Console.WriteLine("Writing assembly element with nameIx of " + nameIx + " at file offset " + output.Seek(0,SeekOrigin.Current));
output.Write((uint)hashAlgId);
output.Write(majorVer);
output.Write(minorVer);
output.Write(buildNo);
output.Write(revisionNo);
output.Write(flags);
output.BlobIndex(keyIx);
output.StringsIndex(nameIx);
output.StringsIndex(cultIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 14;
case (CIx.HasDeclSecurity) : return 2;
}
return 0;
}
internal bool HasPublicKey {
get { return hasPublicKey; }
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for THIS module
/// </summary>
public class Module : ResolutionScope, IExternRef {
Guid mvid;
uint mvidIx = 0;
internal Module(string name, MetaData md) : base(name,md)
{
mvid = Guid.NewGuid();
mvidIx = md.AddToGUIDHeap(mvid);
tabIx = MDTable.Module;
}
public Guid Guid {
get { return mvid; }
}
public ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef (nsName, name, metaData);
metaData.AddToTable (MDTable.TypeRef, aClass);
aClass.SetParent (this);
return aClass;
}
public ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = AddClass (nsName, name);
aClass.MakeValueClass (ValueClass.ValueType);
return aClass;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + 3 * md.GUIDIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write((short)0);
output.StringsIndex(nameIx);
output.GUIDIndex(mvidIx);
output.GUIDIndex(0);
output.GUIDIndex(0);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 7;
case (CIx.ResolutionScope) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for another module in THIS assembly
/// </summary>
public class ModuleRef : ResolutionScope, IExternRef {
internal ModuleRef(MetaData md, string name) : base(name,md)
{
tabIx = MDTable.ModuleRef;
}
/// <summary>
/// Add a class to this external module. This is a class declared in
/// another module of THIS assembly.
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns>a descriptor for this class in another module</returns>
public ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
/// <summary>
/// Make a file descriptor to correspond to this module. The file
/// descriptor will have the same name as the module descriptor
/// </summary>
/// <param name="hashBytes">the hash of the file</param>
/// <param name="hasMetaData">the file contains metadata</param>
/// <param name="entryPoint">the program entry point is in this file</param>
/// <returns>a descriptor for the file which contains this module</returns>
public FileRef MakeFile(byte[] hashBytes, bool hasMetaData, bool entryPoint)
{
FileRef file = new FileRef(nameIx,hashBytes,hasMetaData,entryPoint,metaData);
metaData.AddToTable(MDTable.File,file);
return file;
}
/// <summary>
/// Add a value class to this module. This is a class declared in
/// another module of THIS assembly.
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
/// <summary>
/// Add a class which is declared public in this external module of
/// THIS assembly. This class will be exported from this assembly.
/// The ilasm syntax for this is .extern class
/// </summary>
/// <param name="attrSet">attributes of the class to be exported</param>
/// <param name="nsName">name space name</param>
/// <param name="name">external class name</param>
/// <param name="declFile">the file where the class is declared</param>
/// <param name="isValueClass">is this class a value type?</param>
/// <returns>a descriptor for this external class</returns>
public ExternClassRef AddExternClass(TypeAttr attrSet, string nsName,
string name, FileRef declFile,
bool isValueClass) {
ExternClassRef cRef = new ExternClassRef(attrSet,nsName,name,declFile,metaData);
metaData.AddToTable(MDTable.TypeRef,cRef);
cRef.SetParent(this);
if (isValueClass) cRef.MakeValueClass(ValueClass.ValueType);
return cRef;
}
/// <summary>
/// Add a "global" method in another module
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">method parameter types</param>
/// <returns>a descriptor for this method in anther module</returns>
public MethodRef AddMethod(string name, Type retType, Type[] pars)
{
MethodRef meth = new MethodRef(this,name,retType,pars,false,null, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a vararg method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <param name="optPars">optional param types for this vararg method</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddVarArgMethod(string name, Type retType,
Type[] pars, Type[] optPars) {
MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a field in another module
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this field in another module</returns>
public FieldRef AddField(string name, Type fType)
{
FieldRef field = new FieldRef(this,name,fType);
metaData.AddToTable(MDTable.MemberRef,field);
return field;
}
internal sealed override uint Size(MetaData md)
{
return md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.StringsIndex(nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 12;
case (CIx.MemberRefParent) : return 2;
case (CIx.ResolutionScope) : return 1;
}
return 0;
}
}
#region Classes for Constants
/// <summary>
/// Descriptor for a constant value
/// </summary>
public abstract class Constant {
protected uint size = 0;
protected Type type;
protected uint blobIndex;
protected bool addedToBlobHeap = false;
internal Constant() { }
internal virtual uint GetBlobIndex(MetaData md) { return 0; }
internal uint GetSize() { return size; }
internal byte GetTypeIndex() { return type.GetTypeIndex(); }
internal virtual void Write(BinaryWriter bw) { }
}
/// <summary>
/// Descriptor for a constant value
/// </summary>
public abstract class DataConstant : Constant {
private uint dataOffset = 0;
internal DataConstant() { }
public uint DataOffset {
get { return dataOffset; }
set { dataOffset = value; }
}
}
/// <summary>
/// Boolean constant
/// </summary>
public class BoolConst : Constant {
bool val;
/// <summary>
/// Create a new boolean constant with the value "val"
/// </summary>
/// <param name="val">value of this boolean constant</param>
public BoolConst(bool val)
{
this.val = val;
size = 1;
type = PrimitiveType.Boolean;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
if (val) blobIndex = md.AddToBlobHeap((sbyte)1);
else blobIndex = md.AddToBlobHeap((sbyte)0);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
if (val) bw.Write((sbyte)1);
else bw.Write((sbyte)0);
}
}
public class ByteArrConst : DataConstant {
byte[] val;
public ByteArrConst(byte[] val)
{
type = PrimitiveType.String;
this.val = val;
size = (uint)val.Length;
}
public Type Type {
get { return type; }
set { type = value; }
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class CharConst : Constant {
char val;
public CharConst(char val)
{
this.val = val;
size = 2;
type = PrimitiveType.Char;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class FloatConst : DataConstant {
float val;
public FloatConst(float val)
{
this.val = val;
size = 4;
type = PrimitiveType.Float32;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class DoubleConst : DataConstant {
double val;
public DoubleConst(double val)
{
this.val = val;
size = 8;
type = PrimitiveType.Float64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class IntConst : DataConstant {
long val;
public IntConst(sbyte val)
{
this.val = val;
size = 1;
type = PrimitiveType.Int8;
}
public IntConst(short val)
{
this.val = val;
size = 2;
type = PrimitiveType.Int16;
}
public IntConst(int val)
{
this.val = val;
size = 4;
type = PrimitiveType.Int32;
}
public IntConst(long val)
{
this.val = val;
size = 8;
type = PrimitiveType.Int64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
switch (size) {
case (1) : blobIndex = md.AddToBlobHeap((sbyte)val); break;
case (2) : blobIndex = md.AddToBlobHeap((short)val); break;
case (4) : blobIndex = md.AddToBlobHeap((int)val); break;
default : blobIndex = md.AddToBlobHeap(val); break;
}
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
switch (size) {
case (1) : bw.Write((sbyte)val); break;
case (2) : bw.Write((short)val); break;
case (4) : bw.Write((int)val); break;
default : bw.Write(val); break;
}
}
}
public class UIntConst : Constant {
ulong val;
public UIntConst(byte val)
{
this.val = val;
size = 1;
type = PrimitiveType.UInt8;
}
public UIntConst(ushort val)
{
this.val = val;
size = 2;
type = PrimitiveType.UInt16;
}
public UIntConst(uint val)
{
this.val = val;
size = 4;
type = PrimitiveType.UInt32;
}
public UIntConst(ulong val)
{
this.val = val;
size = 8;
type = PrimitiveType.UInt64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
switch (size) {
case (1) : blobIndex = md.AddToBlobHeap((byte)val); break;
case (2) : blobIndex = md.AddToBlobHeap((ushort)val); break;
case (4) : blobIndex = md.AddToBlobHeap((uint)val); break;
default : blobIndex = md.AddToBlobHeap(val); break;
}
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
switch (size) {
case (1) : bw.Write((byte)val); break;
case (2) : bw.Write((ushort)val); break;
case (4) : bw.Write((uint)val); break;
default : bw.Write(val); break;
}
}
}
public class StringConst : DataConstant {
string val;
public StringConst(string val)
{
this.val = val;
size = (uint)val.Length; // need to add null ??
type = PrimitiveType.String;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
byte [] b = Encoding.Unicode.GetBytes (val);
blobIndex = md.AddToBlobHeap(b);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class NullConst : Constant {
public NullConst()
{
size = 4;
type = PrimitiveType.Class;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap((int)0);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write((int)0);
}
}
public class AddressConstant : DataConstant {
DataConstant data;
public AddressConstant(DataConstant dConst)
{
data = dConst;
size = 4;
type = PrimitiveType.TypedRef;
}
internal sealed override void Write(BinaryWriter bw)
{
((FileImage)bw).WriteDataRVA(data.DataOffset);
}
}
public class RepeatedConstant : DataConstant {
DataConstant data;
uint repCount;
public RepeatedConstant(DataConstant dConst, int repeatCount)
{
data = dConst;
repCount = (uint)repeatCount;
int[] sizes = new int[1];
sizes[0] = repeatCount;
type = new BoundArray(type,1,sizes);
size = data.GetSize() * repCount;
}
internal sealed override void Write(BinaryWriter bw)
{
for (int i=0; i < repCount; i++) {
data.Write(bw);
}
}
}
public class ArrayConstant : DataConstant {
DataConstant[] dataVals;
public ArrayConstant(DataConstant[] dVals)
{
dataVals = dVals;
for (int i=0; i < dataVals.Length; i++) {
size += dataVals[i].GetSize();
}
}
internal sealed override void Write(BinaryWriter bw)
{
for (int i=0; i < dataVals.Length; i++) {
dataVals[i].Write(bw);
}
}
}
public class ClassType : Constant {
string name;
Class desc;
public ClassType(string className)
{
name = className;
type = PrimitiveType.ClassType;
}
public ClassType(Class classDesc)
{
desc = classDesc;
type = PrimitiveType.ClassType;
}
internal override void Write(BinaryWriter bw)
{
if (name == null) name = desc.TypeName();
bw.Write(name);
}
}
#endregion
/**************************************************************************/
/// <summary>
/// Descriptor for a custom modifier of a type (modopt or modreq)
/// </summary>
public class CustomModifiedType : Type {
Type type;
Class cmodType;
/// <summary>
/// Create a new custom modifier for a type
/// </summary>
/// <param name="type">the type to be modified</param>
/// <param name="cmod">the modifier</param>
/// <param name="cmodType">the type reference to be associated with the type</param>
public CustomModifiedType(Type type, CustomModifier cmod, Class cmodType)
: base((byte)cmod)
{
this.type = type;
this.cmodType = cmodType;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
MetaData.CompressNum(cmodType.TypeDefOrRefToken(),str);
type.TypeSig(str);
}
}
/**************************************************************************/
/// <summary>
/// Base class for Event and Property descriptors
/// </summary>
public class Feature : MetaDataElement {
internal enum MethodType : ushort { Setter = 0x01, Getter, Other = 0x04, AddOn = 0x08,
RemoveOn = 0x10, Fire = 0x20 }
private static readonly int INITSIZE = 5;
private static readonly ushort specialName = 0x200;
private static readonly ushort rtSpecialName = 0x400;
protected ClassDef parent;
protected ushort flags = 0;
protected string name;
protected int tide = 0;
protected uint nameIx;
protected MethodSemantics[] methods = new MethodSemantics[INITSIZE];
internal Feature(string name, ClassDef par)
{
parent = par;
this.name = name;
}
internal void AddMethod(MethodDef meth, MethodType mType)
{
if (tide >= methods.Length) {
int len = methods.Length;
MethodSemantics[] mTmp = methods;
methods = new MethodSemantics[len * 2];
for (int i=0; i < len; i++) {
methods[i] = mTmp[i];
}
}
methods[tide++] = new MethodSemantics(mType,meth,this);
}
/// <summary>
/// Set the specialName attribute for this Event or Property
/// </summary>
public void SetSpecialName()
{
flags |= specialName;
}
/// <summary>
/// Set the RTSpecialName attribute for this Event or Property
/// </summary>
public void SetRTSpecialName()
{
flags |= rtSpecialName;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an event
/// </summary>
public class Event : Feature {
Type eventType;
internal Event(string name, Type eType, ClassDef parent)
: base(name, parent)
{
eventType = eType;
tabIx = MDTable.Event;
}
/// <summary>
/// Add the addon method to this event
/// </summary>
/// <param name="addon">the addon method</param>
public void AddAddon(MethodDef addon)
{
AddMethod(addon,MethodType.AddOn);
}
/// <summary>
/// Add the removeon method to this event
/// </summary>
/// <param name="removeOn">the removeon method</param>
public void AddRemoveOn(MethodDef removeOn)
{
AddMethod(removeOn,MethodType.RemoveOn);
}
/// <summary>
/// Add the fire method to this event
/// </summary>
/// <param name="fire">the fire method</param>
public void AddFire(MethodDef fire)
{
AddMethod(fire,MethodType.Fire);
}
/// <summary>
/// Add another method to this event
/// </summary>
/// <param name="other">the method to be added</param>
public void AddOther(MethodDef other)
{
AddMethod(other,MethodType.Other);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
for (int i=0; i < tide; i++) {
md.AddToTable(MDTable.MethodSemantics,methods[i]);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.CodedIndexSize(CIx.TypeDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.WriteCodedIndex(CIx.TypeDefOrRef,eventType);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 10;
case (CIx.HasSemantics) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the Property of a class
/// </summary>
public class Property : Feature {
private static readonly byte PropertyTag = 0x8;
private bool instance;
MethodDef getterMeth;
ConstantElem constVal;
uint typeBlobIx = 0;
Type[] parList;
Type returnType;
uint numPars = 0;
internal Property(string name, Type retType, Type[] pars, ClassDef parent) : base(name, parent)
{
returnType = retType;
parList = pars;
if (pars != null) numPars = (uint)pars.Length;
tabIx = MDTable.Property;
}
/// <summary>
/// Add a set method to this property
/// </summary>
/// <param name="setter">the set method</param>
public void AddSetter(MethodDef setter)
{
AddMethod(setter,MethodType.Setter);
}
/// <summary>
/// Add a get method to this property
/// </summary>
/// <param name="getter">the get method</param>
public void AddGetter(MethodDef getter)
{
AddMethod(getter,MethodType.Getter);
getterMeth = getter;
}
/// <summary>
/// Add another method to this property
/// </summary>
/// <param name="other">the method</param>
public void AddOther(MethodDef other)
{
AddMethod(other,MethodType.Other);
}
/// <summary>
/// Add an initial value for this property
/// </summary>
/// <param name="constVal">the initial value for this property</param>
public void AddInitValue(Constant constVal)
{
this.constVal = new ConstantElem(this,constVal);
}
public void SetInstance (bool isInstance)
{
this.instance = isInstance;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
byte tag = PropertyTag;
if (instance)
tag |= 0x20;
sig.WriteByte(tag);
MetaData.CompressNum(numPars,sig);
returnType.TypeSig(sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig(sig);
}
typeBlobIx = md.AddToBlobHeap(sig.ToArray());
for (int i=0; i < tide; i++) {
md.AddToTable(MDTable.MethodSemantics,methods[i]);
}
if (constVal != null) {
md.AddToTable(MDTable.Constant,constVal);
constVal.BuildTables(md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(typeBlobIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 9;
case (CIx.HasConst) : return 2;
case (CIx.HasSemantics) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Base class for field/methods (member of a class)
/// </summary>
public abstract class Member : MetaDataElement {
protected string name;
protected uint nameIx = 0, sigIx = 0;
internal Member(string memName)
{
name = memName;
tabIx = MDTable.MemberRef;
}
}
/*****************************************************************************/
/// <summary>
/// Descriptor for a field of a class
/// </summary>
public abstract class Field : Member {
protected static readonly byte FieldSig = 0x6;
protected Type type;
internal Field(string pfName, Type pfType) : base(pfName)
{
type = pfType;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a field defined in a class of THIS assembly/module
/// </summary>
public class FieldDef : Field {
//private static readonly uint PInvokeImpl = 0x2000;
private static readonly ushort HasFieldRVA = 0x100;
private static readonly ushort HasDefault = 0x8000;
FieldRVA rva;
ConstantElem constVal;
FieldLayout layout;
FieldMarshal marshalInfo;
ushort flags;
internal FieldDef(string name, Type fType) : base(name,fType)
{
tabIx = MDTable.Field;
}
internal FieldDef(FieldAttr attrSet, string name, Type fType) : base(name, fType)
{
flags = (ushort)attrSet;
tabIx = MDTable.Field;
}
/// <summary>
/// Add an attribute(s) to this field
/// </summary>
/// <param name="fa">the attribute(s) to be added</param>
public void AddFieldAttr(FieldAttr fa)
{
flags |= (ushort)fa;
}
/// <summary>
/// Add a value for this field
/// </summary>
/// <param name="val">the value for the field</param>
public void AddValue(Constant val)
{
constVal = new ConstantElem(this,val);
flags |= HasDefault;
}
/// <summary>
/// Add an initial value for this field (at dataLabel) (.data)
/// </summary>
/// <param name="val">the value for the field</param>
/// <param name="repeatVal">the number of repetitions of this value</param>
public void AddDataValue(DataConstant val)
{
flags |= HasFieldRVA;
rva = new FieldRVA(this,val);
}
/// <summary>
/// Set the offset of the field. Used for sequential or explicit classes.
/// (.field [offs])
/// </summary>
/// <param name="offs">field offset</param>
public void SetOffset(uint offs)
{
layout = new FieldLayout(this,offs);
}
/// <summary>
/// Set the marshalling info for a field
/// </summary>
/// <param name="mInf"></param>
public void SetMarshalInfo(NativeType marshallType)
{
flags |= (ushort) FieldAttr.HasFieldMarshal;
marshalInfo = new FieldMarshal(this,marshallType);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
sig.WriteByte(FieldSig);
type.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
if (rva != null) {
md.AddToTable(MDTable.FieldRVA,rva);
rva.BuildTables(md);
} else if (constVal != null) {
md.AddToTable(MDTable.Constant,constVal);
constVal.BuildTables(md);
}
if (layout != null) md.AddToTable(MDTable.FieldLayout,layout);
if (marshalInfo != null) {
md.AddToTable(MDTable.FieldMarshal,marshalInfo);
marshalInfo.BuildTables(md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasConst) : return 0;
case (CIx.HasCustomAttr) : return 1;
case (CIx.HasFieldMarshal) : return 0;
case (CIx.MemberForwarded) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a field of a class defined in another assembly/module
/// </summary>
public class FieldRef : Field {
MetaDataElement parent;
internal FieldRef(MetaDataElement paren, string name, Type fType) : base(name, fType)
{
parent = paren;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
sig.WriteByte(FieldSig);
type.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.MemberRefParent,parent);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return 6; }
}
/**************************************************************************/
/// <summary>
/// Base class for Method Descriptors
/// </summary>
public abstract class Method : Member {
internal Method (string methName) : base (methName)
{}
public abstract void AddCallConv(CallConv cconv);
internal abstract void TypeSig(MemoryStream sig);
internal abstract uint GetSigIx(MetaData md);
}
/**************************************************************************/
/// <summary>
/// Descriptor for a method defined in THIS assembly/module
/// IL .method
/// </summary>
public class MethodDef : Method {
private static readonly ushort PInvokeImpl = 0x2000;
//private static readonly uint UnmanagedExport = 0x0008;
// private static readonly byte LocalSigByte = 0x7;
uint parIx = 0, textOffset = 0;
private CallConv callConv = CallConv.Default;
private int gen_param_count;
MetaData metaData;
CILInstructions code;
ArrayList securityActions = new ArrayList();
Param[] parList;
Local[] locals;
bool initLocals;
ushort methFlags = 0, implFlags = 0;
int maxStack = 0, numPars = 0;
bool entryPoint = false;
LocalSig localSig;
ArrayList varArgSigList;
ImplMap pinvokeImpl;
Param ret_param;
internal MethodDef (MetaData md, string name, Param ret_param, Param [] pars)
: this (md, 0, 0, name, ret_param, pars)
{
}
internal MethodDef (MetaData md, MethAttr mAttrSet, ImplAttr iAttrSet, string name,
Param ret_param, Param [] pars)
: base (name)
{
methFlags = (ushort)mAttrSet;
implFlags = (ushort)iAttrSet;
this.ret_param = ret_param;
metaData = md;
parList = pars;
if (parList != null)
numPars = parList.Length;
tabIx = MDTable.Method;
}
internal Param[] GetPars()
{
return parList;
}
internal override uint GetSigIx(MetaData md)
{
MemoryStream sig = new MemoryStream();
TypeSig(sig);
return md.AddToBlobHeap(sig.ToArray());
}
public override void AddCallConv(CallConv cconv)
{
callConv |= cconv;
}
/// <summary>
/// Add some attributes to this method descriptor
/// </summary>
/// <param name="ma">the attributes to be added</param>
public void AddMethAttribute(MethAttr ma)
{
methFlags |= (ushort)ma;
}
/// <summary>
/// Add some implementation attributes to this method descriptor
/// </summary>
/// <param name="ia">the attributes to be added</param>
public void AddImplAttribute(ImplAttr ia)
{
implFlags |= (ushort)ia;
}
public void AddPInvokeInfo(ModuleRef scope, string methName,
PInvokeAttr callAttr) {
pinvokeImpl = new ImplMap((ushort)callAttr,this,methName,scope);
methFlags |= PInvokeImpl;
}
/// <summary>
/// Add a named generic type parameter
/// </summary>
public GenericParameter AddGenericParameter (short index, string name)
{
return AddGenericParameter (index, name, 0);
}
/// <summary>
/// Add a named generic type parameter with attributes
/// </summary>
public GenericParameter AddGenericParameter (short index, string name, GenericParamAttributes attr)
{
GenericParameter gp = new GenericParameter (this, metaData, index, name, attr);
metaData.AddToTable (MDTable.GenericParam, gp);
gen_param_count ++;
return gp;
}
/// <summary>
/// Set the maximum stack height for this method
/// </summary>
/// <param name="maxStack">the maximum height of the stack</param>
public void SetMaxStack(int maxStack)
{
this.maxStack = maxStack;
}
/// <summary>
/// Add local variables to this method
/// </summary>
/// <param name="locals">the locals to be added</param>
/// <param name="initLocals">are locals initialised to default values</param>
public void AddLocals(Local[] locals, bool initLocals)
{
this.locals = locals;
this.initLocals = initLocals;
}
/* Add Marshal info for return type */
public void AddRetTypeMarshallInfo (NativeType marshallType)
{
ret_param.AddMarshallInfo (marshallType);
}
/// <summary>
/// Mark this method as having an entry point
/// </summary>
public void DeclareEntryPoint()
{
entryPoint = true;
}
/// <summary>
/// Create a code buffer for this method to add the IL instructions to
/// </summary>
/// <returns>a buffer for this method's IL instructions</returns>
public CILInstructions CreateCodeBuffer()
{
code = new CILInstructions(metaData);
return code;
}
/// <summary>
/// Make a method reference descriptor for this method to be used
/// as a callsite signature for this vararg method
/// </summary>
/// <param name="optPars">the optional pars for the vararg method call</param>
/// <returns></returns>
public MethodRef MakeVarArgSignature(Type[] optPars)
{
Type[] pars = new Type[numPars];
MethodRef varArgSig;
for (int i=0; i < numPars; i++) {
pars[i] = parList[i].GetParType();
}
varArgSig = new MethodRef (this, name, ret_param.GetParType (), pars, true, optPars, 0);
if (varArgSigList == null)
varArgSigList = new ArrayList ();
varArgSigList.Add (varArgSig);
return varArgSig;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte((byte)callConv);
if ((callConv & CallConv.Generic) == CallConv.Generic)
MetaData.CompressNum ((uint) gen_param_count, sig);
MetaData.CompressNum((uint)numPars,sig);
ret_param.seqNo = 0;
ret_param.TypeSig (sig);
for (ushort i=0; i < numPars; i++) {
parList[i].seqNo = (ushort)(i+1);
parList[i].TypeSig(sig);
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
if (pinvokeImpl != null) {
md.AddToTable(MDTable.ImplMap,pinvokeImpl);
pinvokeImpl.BuildTables(md);
}
if (entryPoint) md.SetEntryPoint(this);
uint locToken = 0;
if (locals != null) {
localSig = new LocalSig(locals);
md.AddToTable(MDTable.StandAloneSig,localSig);
localSig.BuildTables(md);
locToken = localSig.Token();
}
if (code != null) {
code.CheckCode(locToken,initLocals,maxStack);
textOffset = md.AddCode(code);
}
nameIx = md.AddToStringsHeap(name);
sigIx = GetSigIx(md);
parIx = md.TableIndex(MDTable.Param);
if (ret_param.HasMarshalInfo || ret_param.HasCustomAttr) {
md.AddToTable(MDTable.Param, ret_param);
ret_param.BuildTables(md);
}
for (int i=0; i < numPars; i++) {
md.AddToTable(MDTable.Param,parList[i]);
parList[i].BuildTables(md);
}
if (varArgSigList != null) {
foreach (MethodRef varArgSig in varArgSigList) {
md.AddToTable(MDTable.MemberRef,varArgSig);
varArgSig.BuildTables(md);
}
}
// Console.WriteLine("method has " + numPars + " parameters");
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 8 + md.StringsIndexSize() + md.BlobIndexSize() + md.TableIndexSize(MDTable.Param);
}
internal sealed override void Write(FileImage output)
{
if (ZeroRva ()) output.Write(0);
else output.WriteCodeRVA(textOffset);
output.Write(implFlags);
output.Write(methFlags);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
output.WriteIndex(MDTable.Param,parIx);
}
internal bool ZeroRva ()
{
return (((methFlags & (ushort)MethAttr.Abstract) != 0) ||
((implFlags & (ushort)ImplAttr.Runtime) != 0) ||
((implFlags & (ushort)ImplAttr.InternalCall) != 0) ||
(pinvokeImpl != null)); // TODO: Not entirely true but works for now
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 0;
case (CIx.HasDeclSecurity) : return 1;
case (CIx.MemberRefParent) : return 3;
case (CIx.MethodDefOrRef) : return 0;
case (CIx.MemberForwarded) : return 1;
case (CIx.CustomAttributeType) : return 2;
case (CIx.TypeOrMethodDef) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a method defined in another assembly/module
/// </summary>
public class MethodRef : Method {
private static readonly byte Sentinel = 0x41;
Type[] parList, optParList;
MetaDataElement parent;
uint numPars = 0, numOptPars = 0;
CallConv callConv = CallConv.Default;
Type retType;
int gen_param_count;
internal MethodRef(MetaDataElement paren, string name, Type retType,
Type[] pars, bool varArgMeth, Type[] optPars, int gen_param_count) : base(name)
{
parent = paren;
parList = pars;
this.retType = retType;
if (parList != null) numPars = (uint)parList.Length;
if (varArgMeth) {
optParList = optPars;
if (optParList != null) numOptPars = (uint)optParList.Length;
callConv = CallConv.Vararg;
}
this.gen_param_count = gen_param_count;
}
internal override uint GetSigIx(MetaData md)
{
MemoryStream sig = new MemoryStream();
TypeSig(sig);
return md.AddToBlobHeap(sig.ToArray());
}
public override void AddCallConv(CallConv cconv)
{
callConv |= cconv;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte((byte)callConv);
if ((callConv & CallConv.Generic) == CallConv.Generic)
MetaData.CompressNum ((uint) gen_param_count, sig);
MetaData.CompressNum(numPars+numOptPars,sig);
retType.TypeSig(sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig(sig);
}
if (numOptPars > 0) {
sig.WriteByte(Sentinel);
for (int i=0; i < numOptPars; i++) {
optParList[i].TypeSig(sig);
}
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
sigIx = GetSigIx(md);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.MemberRefParent,parent);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 6;
case (CIx.MethodDefOrRef) : return 1;
case (CIx.CustomAttributeType) : return 3;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptors for native types used for marshalling
/// </summary>
public class NativeType {
public static readonly NativeType Void = new NativeType(0x01);
public static readonly NativeType Boolean = new NativeType(0x02);
public static readonly NativeType Int8 = new NativeType(0x03);
public static readonly NativeType UInt8 = new NativeType(0x04);
public static readonly NativeType Int16 = new NativeType(0x05);
public static readonly NativeType UInt16 = new NativeType(0x06);
public static readonly NativeType Int32 = new NativeType(0x07);
public static readonly NativeType UInt32 = new NativeType(0x08);
public static readonly NativeType Int64 = new NativeType(0x09);
public static readonly NativeType UInt64 = new NativeType(0x0A);
public static readonly NativeType Float32 = new NativeType(0x0B);
public static readonly NativeType Float64 = new NativeType(0x0C);
public static readonly NativeType Currency = new NativeType(0x0F);
public static readonly NativeType BStr = new NativeType(0x13);
public static readonly NativeType LPStr = new NativeType(0x14);
public static readonly NativeType LPWStr = new NativeType(0x15);
public static readonly NativeType LPTStr = new NativeType(0x16);
public static readonly NativeType FixedSysString = new NativeType(0x17);
public static readonly NativeType IUnknown = new NativeType(0x19);
public static readonly NativeType IDispatch = new NativeType(0x1A);
public static readonly NativeType Struct = new NativeType(0x1B);
public static readonly NativeType Interface = new NativeType(0x1C);
public static readonly NativeType Int = new NativeType(0x1F);
public static readonly NativeType UInt = new NativeType(0x20);
public static readonly NativeType ByValStr = new NativeType(0x22);
public static readonly NativeType AnsiBStr = new NativeType(0x23);
public static readonly NativeType TBstr = new NativeType(0x24);
public static readonly NativeType VariantBool = new NativeType(0x25);
public static readonly NativeType FuncPtr = new NativeType(0x26);
public static readonly NativeType AsAny = new NativeType(0x28);
public static readonly NativeType LPStruct = new NativeType(0x2b);
public static readonly NativeType Error = new NativeType(0x2d);
protected byte typeIndex;
internal NativeType(byte tyIx) { typeIndex = tyIx; }
internal byte GetTypeIndex() { return typeIndex; }
internal virtual byte[] ToBlob()
{
byte[] bytes = new byte[1];
bytes[0] = GetTypeIndex();
return bytes;
}
}
public class FixedSysString : NativeType {
uint size;
public FixedSysString (uint size) : base (NativeType.FixedSysString.GetTypeIndex ())
{
this.size = size;
}
internal override byte [] ToBlob ()
{
MemoryStream str = new MemoryStream ();
str.WriteByte (GetTypeIndex ());
MetaData.CompressNum (size, str);
return str.ToArray ();
}
}
public class NativeArray : NativeType {
NativeType elemType;
int numElem = -1, parNum = -1, elemMult = -1;
public NativeArray(NativeType elemType) : this (elemType, -1, -1, -1)
{
this.elemType = elemType;
}
/* public NativeArray(NativeType elemType, int len) : base(0x2A) {
this.elemType = elemType;
this.len = len;
}
*/
public NativeArray(NativeType elemType, int numElem, int parNumForLen, int elemMult) : base(0x2A)
{
this.elemType = elemType;
this.numElem = numElem;
parNum = parNumForLen;
this.elemMult = elemMult;
}
public NativeArray(NativeType elemType, int numElem, int parNumForLen)
: this (elemType, numElem, parNumForLen, -1)
{
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
str.WriteByte(GetTypeIndex());
if (elemType == null) str.WriteByte(0x50); // no info (MAX)
else str.WriteByte(elemType.GetTypeIndex());
/* see : mono/metadata/metadata.c:mono_metadata_parse_marshal_spec
* LAMESPEC: Older spec versions say elemMult comes before
* len. Newer spec versions don't talk about elemMult at
* all, but csc still emits it, and it is used to distinguish
* between parNum being 0, and parNum being omitted.
*/
if (parNum == -1)
// <native_type> []
return str.ToArray ();
MetaData.CompressNum((uint) parNum,str);
if (numElem != -1) {
MetaData.CompressNum ((uint) numElem, str);
if (elemMult != -1)
// <native_type> [ int32 ]
MetaData.CompressNum((uint) elemMult,str);
//else <native_type> [ int32 + int32 ]
} else if (elemMult != -1) {
// When can this occur ?
MetaData.CompressNum (0, str);
MetaData.CompressNum((uint) elemMult,str);
}
//else <native_type> [ + int32 ]
return str.ToArray();
}
}
public class SafeArray : NativeType {
SafeArrayType elemType;
bool hasElemType;
public SafeArray() : base(0x1D)
{
}
public SafeArray(SafeArrayType elemType) : base(0x1D)
{
this.elemType = elemType;
hasElemType = true;
}
internal override byte[] ToBlob()
{
byte[] bytes = new byte[hasElemType ? 2 : 1];
bytes[0] = GetTypeIndex();
if (hasElemType)
bytes[1] = (byte)elemType;
return bytes;
}
}
public class FixedArray : NativeType {
NativeType elemType;
uint numElem;
//public FixedArray(NativeType elemType, int numElems) : base(0x1E) {
public FixedArray(int numElems) : base(0x1E)
{
//this.elemType = elemType;
numElem = (uint)numElems;
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
str.WriteByte(GetTypeIndex());
MetaData.CompressNum(numElem,str);
/* FIXME:
fixed array [5] lpstr [2]
This format is not supported by ilasm 1.1.4322.2032,
but is supported by 2.0.5125..
ilasm 1.1 only supports "fixed array [5]"
if (elemType == null) str.WriteByte(0x50); // no info (MAX)
else str.WriteByte(elemType.GetTypeIndex());*/
return str.ToArray();
}
}
public class CustomMarshaller : NativeType {
string typeName;
string marshallerName;
string cookie;
public CustomMarshaller(string typeNameOrGUID, string marshallerName,
string optCookie) : base(0x2C)
{
typeName = typeNameOrGUID;
this.marshallerName = marshallerName;
cookie = optCookie;
}
public CustomMarshaller(string marshallerName, string optCookie)
:this (null, marshallerName, optCookie)
{
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
BinaryWriter bw = new BinaryWriter(str,new UTF8Encoding());
bw.Write(GetTypeIndex());
//Native type name & unmanaged type - unused
//See mono/metadata/metadata.c : mono_metadata_parse_marshal_spec
bw.Write ((byte) 0); // Native Type name, unused
bw.Write ((byte) 0); // Unmanaged type, unused
if (marshallerName != null) {
MetaData.CompressNum ((uint)marshallerName.Length, str);
bw.Write(marshallerName.ToCharArray());
} else {
bw.Write ((byte) 0);
}
if (cookie != null) {
MetaData.CompressNum ((uint)cookie.Length, str);
bw.Write(cookie.ToCharArray());
} else {
bw.Write ((byte) 0);
}
bw.Flush();
return str.ToArray();
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the Primitive types defined in IL
/// </summary>
public class PrimitiveType : Type {
private string name;
private int systemTypeIndex;
public static int NumSystemTypes = 18;
public static readonly PrimitiveType Void = new PrimitiveType(0x01,"Void",0);
public static readonly PrimitiveType Boolean = new PrimitiveType(0x02,"Boolean",1);
public static readonly PrimitiveType Char = new PrimitiveType(0x03,"Char",2);
public static readonly PrimitiveType Int8 = new PrimitiveType(0x04,"SByte",3);
public static readonly PrimitiveType UInt8 = new PrimitiveType(0x05,"Byte",4);
public static readonly PrimitiveType Int16 = new PrimitiveType(0x06,"Int16",5);
public static readonly PrimitiveType UInt16 = new PrimitiveType(0x07,"UInt16",6);
public static readonly PrimitiveType Int32 = new PrimitiveType(0x08,"Int32",7);
public static readonly PrimitiveType UInt32 = new PrimitiveType(0x09,"UInt32",8);
public static readonly PrimitiveType Int64 = new PrimitiveType(0x0A,"Int64",9);
public static readonly PrimitiveType UInt64 = new PrimitiveType(0x0B,"UInt64",10);
public static readonly PrimitiveType Float32 = new PrimitiveType(0x0C,"Single",11);
public static readonly PrimitiveType Float64 = new PrimitiveType(0x0D,"Double",12);
public static readonly PrimitiveType String = new PrimitiveType(0x0E,"String",13);
internal static readonly PrimitiveType Class = new PrimitiveType(0x12);
internal static readonly PrimitiveType Var = new PrimitiveType(0x13);
internal static readonly PrimitiveType GenericInst = new PrimitiveType(0x15);
public static readonly PrimitiveType TypedRef = new PrimitiveType(0x16,"TypedReference",14);
public static readonly PrimitiveType IntPtr = new PrimitiveType(0x18,"IntPtr",15);
public static readonly PrimitiveType UIntPtr = new PrimitiveType(0x19,"UIntPtr",16);
public static readonly PrimitiveType Object = new PrimitiveType(0x1C,"Object",17);
internal static readonly PrimitiveType ClassType = new PrimitiveType(0x50);
internal static readonly PrimitiveType SZArray = new PrimitiveType(0x1D);
internal static readonly PrimitiveType MVar = new PrimitiveType(0x1E);
internal static readonly PrimitiveType ValueType = new PrimitiveType(0x11, "ValueType", 18);
public static readonly PrimitiveType NativeInt = IntPtr;
public static readonly PrimitiveType NativeUInt = UIntPtr;
internal PrimitiveType(byte typeIx) : base(typeIx) { }
internal PrimitiveType(byte typeIx, string name, int STIx) : base(typeIx)
{
this.name = name;
this.systemTypeIndex = STIx;
}
internal string GetName() { return name; }
internal int GetSystemTypeIx() { return systemTypeIndex; }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
}
internal override MetaDataElement GetTypeSpec(MetaData md)
{
TypeSpec tS = md.GetPrimitiveTypeSpec(systemTypeIndex);
if (tS == null) {
tS = new TypeSpec(this,md);
md.SetPrimitiveTypeSpec(systemTypeIndex,tS);
md.AddToTable(MDTable.TypeSpec,tS);
}
return tS;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an pointer (type * or type &)
/// </summary>
public abstract class PtrType : Type {
Type baseType;
internal PtrType(Type bType, byte typeIx) : base(typeIx)
{
baseType = bType;
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
baseType.TypeSig(str);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a managed pointer (type & or byref)
/// </summary>
public class ManagedPointer : PtrType {
/// <summary>
/// Create new managed pointer to baseType
/// </summary>
/// <param name="bType">the base type of the pointer</param>
public ManagedPointer(Type baseType) : base(baseType,0x10) { }
}
/**************************************************************************/
/// <summary>
/// Descriptor for an unmanaged pointer (type *)
/// </summary>
public class UnmanagedPointer : PtrType {
/// <summary>
/// Create a new unmanaged pointer to baseType
/// </summary>
/// <param name="baseType">the base type of the pointer</param>
public UnmanagedPointer(Type baseType) : base(baseType, 0x0F) { }
}
/**************************************************************************/
public interface IExternRef {
ClassRef AddClass(string nsName, string name);
ClassRef AddValueClass(string nsName, string name);
}
/// <summary>
/// A reference to an external assembly (.assembly extern)
/// </summary>
public class AssemblyRef : ResolutionScope, IExternRef {
private ushort major, minor, build, revision;
uint flags, keyIx, hashIx, cultIx;
bool hasVersion = false, isKeyToken = false;
byte[] keyBytes;
string culture;
internal AssemblyRef(MetaData md, string name) : base(name,md)
{
tabIx = MDTable.AssemblyRef;
}
public void AddAssemblyAttr (AssemAttr aa)
{
flags |= (uint)aa;
}
/// <summary>
/// Add version information about this external assembly
/// </summary>
/// <param name="majVer">Major Version</param>
/// <param name="minVer">Minor Version</param>
/// <param name="bldNo">Build Number</param>
/// <param name="revNo">Revision Number</param>
public void AddVersionInfo(int majVer, int minVer, int bldNo, int revNo)
{
major = (ushort)majVer;
minor = (ushort)minVer;
build = (ushort)bldNo;
revision = (ushort)revNo;
hasVersion = true;
}
/// <summary>
/// Add the hash value for this external assembly
/// </summary>
/// <param name="hash">bytes of the hash value</param>
public void AddHash(byte[] hash)
{
hashIx = metaData.AddToBlobHeap(hash);
}
/// <summary>
/// Set the culture for this external assembly
/// </summary>
/// <param name="cult">the culture string</param>
public void AddCulture(string cult)
{
cultIx = metaData.AddToStringsHeap(cult);
culture = cult;
}
/// <summary>
/// Add the full public key for this external assembly
/// </summary>
/// <param name="key">bytes of the public key</param>
public void AddKey(byte[] key)
{
flags |= 0x0001; // full public key
keyBytes = key;
keyIx = metaData.AddToBlobHeap(key);
}
/// <summary>
/// Add the public key token (low 8 bytes of the public key)
/// </summary>
/// <param name="key">low 8 bytes of public key</param>
public void AddKeyToken(byte[] key)
{
keyIx = metaData.AddToBlobHeap(key);
keyBytes = key;
isKeyToken = true;
}
/// <summary>
/// Add a class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public virtual ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
/// <summary>
/// Add a value class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public virtual ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
internal string TypeName()
{
string result = name;
if (hasVersion)
result = result + ", Version=" + major + "." + minor + "." +
build + "." + revision;
if (keyBytes != null) {
string tokenStr = "=";
if (isKeyToken) tokenStr = "Token=";
result = result + ", PublicKey" + tokenStr;
for (int i=0; i < keyBytes.Length; i++) {
result = result + Hex.Byte(keyBytes[i]);
}
}
if (culture != null)
result = result + ", Culture=" + culture;
return result;
}
internal sealed override uint Size(MetaData md)
{
return 12 + 2 * md.StringsIndexSize() + 2 * md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(major);
output.Write(minor);
output.Write(build);
output.Write(revision);
output.Write(flags);
output.BlobIndex(keyIx);
output.StringsIndex(nameIx);
output.StringsIndex(cultIx);
output.BlobIndex(hashIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.ResolutionScope) : return 2;
case (CIx.HasCustomAttr) : return 15;
case (CIx.Implementation) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class defined in System (mscorlib)
/// </summary>
internal class SystemClass : ClassRef {
PrimitiveType elemType;
internal SystemClass(PrimitiveType eType, AssemblyRef paren, MetaData md)
: base("System",eType.GetName(),md) {
elemType = eType;
parent = paren;
}
internal override sealed MetaDataElement GetTypeSpec(MetaData md)
{
if (typeSpec == null) typeSpec = (TypeSpec)elemType.GetTypeSpec(md);
return typeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(elemType.GetTypeIndex());
}
}
/**************************************************************************/
/// <summary>
/// The assembly for mscorlib.
/// </summary>
public sealed class MSCorLib : AssemblyRef {
private static readonly int valueTypeIx = 18;
private readonly string systemName = "System";
private Class[] systemClasses = new Class[valueTypeIx+2];
private PrimitiveType[] systemTypes = new PrimitiveType[valueTypeIx];
private TypeSpec[] specialTypeSpecs = new TypeSpec[valueTypeIx];
private static int[] specialNames = {
PrimitiveType.Void.GetName().GetHashCode(),
PrimitiveType.Boolean.GetName().GetHashCode(),
PrimitiveType.Char.GetName().GetHashCode(),
PrimitiveType.Int8.GetName().GetHashCode(),
PrimitiveType.UInt8.GetName().GetHashCode(),
PrimitiveType.Int16.GetName().GetHashCode(),
PrimitiveType.UInt16.GetName().GetHashCode(),
PrimitiveType.Int32.GetName().GetHashCode(),
PrimitiveType.UInt32.GetName().GetHashCode(),
PrimitiveType.Int64.GetName().GetHashCode(),
PrimitiveType.UInt64.GetName().GetHashCode(),
PrimitiveType.Float32.GetName().GetHashCode(),
PrimitiveType.Float64.GetName().GetHashCode(),
PrimitiveType.String.GetName().GetHashCode(),
PrimitiveType.TypedRef.GetName().GetHashCode(),
PrimitiveType.IntPtr.GetName().GetHashCode(),
PrimitiveType.UIntPtr.GetName().GetHashCode(),
PrimitiveType.Object.GetName().GetHashCode(),
PrimitiveType.ValueType.GetName ().GetHashCode(),
"Enum".GetHashCode()
};
internal MSCorLib(MetaData md) : base(md,"mscorlib")
{
if (!PEFile.IsMSCorlib)
md.AddToTable(MDTable.AssemblyRef,this);
systemTypes[PrimitiveType.Void.GetSystemTypeIx()] = PrimitiveType.Void;
systemTypes[PrimitiveType.Boolean.GetSystemTypeIx()] = PrimitiveType.Boolean;
systemTypes[PrimitiveType.Char.GetSystemTypeIx()] = PrimitiveType.Char;
systemTypes[PrimitiveType.Int8.GetSystemTypeIx()] = PrimitiveType.Int8;
systemTypes[PrimitiveType.UInt8.GetSystemTypeIx()] = PrimitiveType.UInt8;
systemTypes[PrimitiveType.Int16.GetSystemTypeIx()] = PrimitiveType.Int16;
systemTypes[PrimitiveType.UInt16.GetSystemTypeIx()] = PrimitiveType.UInt16;
systemTypes[PrimitiveType.Int32.GetSystemTypeIx()] = PrimitiveType.Int32;
systemTypes[PrimitiveType.UInt32.GetSystemTypeIx()] = PrimitiveType.UInt32;
systemTypes[PrimitiveType.Int64.GetSystemTypeIx()] = PrimitiveType.Int64;
systemTypes[PrimitiveType.UInt64.GetSystemTypeIx()] = PrimitiveType.UInt64;
systemTypes[PrimitiveType.Float32.GetSystemTypeIx()] = PrimitiveType.Float32;
systemTypes[PrimitiveType.Float64.GetSystemTypeIx()] = PrimitiveType.Float64;
systemTypes[PrimitiveType.IntPtr.GetSystemTypeIx()] = PrimitiveType.IntPtr;
systemTypes[PrimitiveType.UIntPtr.GetSystemTypeIx()] = PrimitiveType.UIntPtr;
systemTypes[PrimitiveType.String.GetSystemTypeIx()] = PrimitiveType.String;
systemTypes[PrimitiveType.Object.GetSystemTypeIx()] = PrimitiveType.Object;
systemTypes[PrimitiveType.TypedRef.GetSystemTypeIx()] = PrimitiveType.TypedRef;
}
/// <summary>
/// Add a class to the mscorlib assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public override ClassRef AddClass(string nsName, string name)
{
/* This gets called by !mscorlib, for adding references INTO mscorlib, so
it should be returning ClassRef ..*/
Class aClass = GetSpecialClass(nsName,name);
if (aClass == null) {
aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
if (aClass is ClassRef)
((ClassRef) aClass).SetParent(this);
}
//FIXME: Check for !ClassRef here?
return (ClassRef) aClass;
}
private Class GetSpecialClass(string nsName,string name)
{
if (nsName.CompareTo(systemName) != 0) return null;
int hash = name.GetHashCode();
for (int i=0; i < specialNames.Length; i++) {
if (hash != specialNames[i])
continue;
if (systemClasses[i] == null) {
if (i < valueTypeIx) {
systemClasses[i] = new SystemClass(systemTypes[i],this,metaData);
if ((systemTypes[i] != PrimitiveType.Object) &&
(systemTypes[i] != PrimitiveType.String)) {
systemClasses[i].MakeValueClass(ValueClass.ValueType);
}
} else {
systemClasses[i] = new ClassRef(nsName,name,metaData);
((ClassRef) systemClasses[i]).SetParent(this);
if (!ClassDef.IsValueType (nsName, name) && !ClassDef.IsEnum (nsName, name))
systemClasses[i].MakeValueClass(ValueClass.ValueType);
}
metaData.AddToTable(MDTable.TypeRef,systemClasses[i]);
}
return systemClasses[i];
}
return null;
}
internal void SetSpecialSystemClass (string nsName, string name, Class aClass)
{
if (nsName != systemName) return;
int hash = name.GetHashCode ();
for (int i = 0; i < specialNames.Length; i++) {
if (hash != specialNames [i])
continue;
if (systemClasses [i] == null) {
systemClasses [i] = aClass;
}
}
}
internal Class GetSpecialSystemClass(PrimitiveType pType)
{
int ix = pType.GetSystemTypeIx();
if (systemClasses[ix] == null && !PEFile.IsMSCorlib) {
systemClasses[ix] = new SystemClass(pType,this,metaData);
metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
}
return systemClasses[ix];
}
private ClassRef GetValueClass(string name, int hash)
{
/* Called by MSCorLib.AddValueClass, which is called by
!mscorlib, for adding ref to value class INTO mscorlib,
so this should be classref */
int ix = valueTypeIx;
if (hash != specialNames[valueTypeIx]) ix++;
if (systemClasses[ix] == null) {
systemClasses[ix] = new ClassRef(systemName,name,metaData);
((ClassRef) systemClasses[ix]).SetParent(this);
((ClassRef) systemClasses[ix]).MakeValueClass(ValueClass.ValueType);
metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
}
return (ClassRef) systemClasses[ix];
}
internal Class ValueType()
{
if (systemClasses[valueTypeIx] == null && !PEFile.IsMSCorlib) {
ClassRef valType = new ClassRef("System","ValueType",metaData);
valType.SetParent(this);
valType.MakeValueClass(ValueClass.ValueType);
metaData.AddToTable(MDTable.TypeRef,valType);
systemClasses[valueTypeIx] = valType;
}
return systemClasses[valueTypeIx];
}
internal Class EnumType()
{
/* Called by both mscorlib & !mscorlib, so can be
either ClassRef or ClassDef */
//systemClasses [ valueTypeIx + 1] -> System.Enum
if (systemClasses[valueTypeIx + 1] == null && !PEFile.IsMSCorlib) {
ClassRef valType = new ClassRef("System","Enum",metaData);
valType.SetParent(this);
valType.MakeValueClass(ValueClass.Enum);
metaData.AddToTable(MDTable.TypeRef,valType);
systemClasses[valueTypeIx + 1] = valType;
}
return systemClasses[valueTypeIx + 1];
}
/// <summary>
/// Add a value class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public override ClassRef AddValueClass(string nsName, string name)
{
if (nsName.CompareTo(systemName) == 0) {
int hash = name.GetHashCode();
if ((hash == specialNames[valueTypeIx]) ||
(hash == specialNames[valueTypeIx+1])) {
return GetValueClass(name,hash);
}
}
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
}
/**************************************************************************/
/// <summary>
/// MetaData
/// Root (20 bytes + UTF-8 Version String + quad align padding)
/// StreamHeaders (8 bytes + null terminated name string + quad align padding)
/// Streams
/// #~ (always present - holds metadata tables)
/// #Strings (always present - holds identifier strings)
/// #US (Userstring heap)
/// #Blob (signature blobs)
/// #GUID (guids for assemblies or Modules)
/// </summary>
public class MetaData {
internal static readonly int[] CIxShiftMap = {2,2,5,1,2,3,1,1,1,2,3,2,1};
private static readonly byte StringsHeapMask = 0x1;
private static readonly byte GUIDHeapMask = 0x2;
private static readonly byte BlobHeapMask = 0x4;
private static readonly uint MetaDataSignature = 0x424A5342;
private static readonly uint maxSmlIxSize = 0xFFFF;
private static readonly uint max1BitSmlIx = 0x7FFF;
private static readonly uint max2BitSmlIx = 0x3FFF;
private static readonly uint max3BitSmlIx = 0x1FFF;
private static readonly uint max5BitSmlIx = 0x7FF;
// NOTE: version and stream name strings MUST always be quad padded
#if NET_2_0 || BOOTSTRAP_NET_2_0
private static readonly string version = "v2.0.50727\0\0";
#else
private static readonly string version = "v1.1.4322\0\0\0";
#endif
private static readonly char[] tildeName = {'#','~','\0','\0'};
private static readonly char[] stringsName = {'#','S','t','r','i','n','g','s','\0','\0','\0','\0'};
private static readonly char[] usName = {'#','U','S','\0'};
private static readonly char[] guidName = {'#','G','U','I','D','\0','\0','\0'};
private static readonly char[] blobName = {'#','B','l','o','b','\0','\0','\0'};
private static readonly uint MetaDataHeaderSize = 20 + (uint)version.Length;
private static readonly uint TildeHeaderSize = 24;
private static readonly uint StreamHeaderSize = 8;
private static readonly uint numMetaDataTables = (int)MDTable.GenericParamConstraint + 1;
private static readonly uint tildeHeaderSize = 8 + (uint)tildeName.Length;
MetaDataStream strings, us, guid, blob;
MetaDataStream[] streams = new MetaDataStream[5];
uint numStreams = 5;
uint tildeTide = 0, tildePadding = 0, tildeStart = 0;
uint numTables = 0, resourcesSize = 0;
ArrayList[] metaDataTables = new ArrayList[numMetaDataTables];
ArrayList byteCodes = new ArrayList();
uint codeSize = 0, codeStart, byteCodePadding = 0, metaDataSize = 0;
ulong valid = 0, /*sorted = 0x000002003301FA00;*/ sorted = 0;
bool[] largeIx = new bool[numMetaDataTables];
bool[] lgeCIx = new bool[(int)CIx.MaxCIx];
bool largeStrings = false, largeUS = false, largeGUID = false, largeBlob = false;
private FileImage file;
private byte heapSizes = 0;
MetaDataElement entryPoint;
BinaryWriter output;
public MSCorLib mscorlib;
private TypeSpec[] systemTypeSpecs = new TypeSpec[PrimitiveType.NumSystemTypes];
long mdStart;
private ArrayList cattr_list;
private ArrayList declsec_list;
ArrayList resources;
internal MetaData(FileImage file)
{
// tilde = new MetaDataStream(tildeName,false,0);
this.file = file;
strings = new MetaDataStream(stringsName,new UTF8Encoding(),true);
us = new MetaDataStream(usName,new UnicodeEncoding(),true);
guid = new MetaDataStream(guidName,false);
blob = new MetaDataStream(blobName,true);
streams[1] = strings;
streams[2] = us;
streams[3] = guid;
streams[4] = blob;
for (int i=0; i < numMetaDataTables; i++) {
largeIx[i] = false;
}
for (int i=0; i < lgeCIx.Length; i++) {
lgeCIx[i] = false;
}
mscorlib = new MSCorLib(this);
}
internal TypeSpec GetPrimitiveTypeSpec(int ix)
{
return systemTypeSpecs[ix];
}
internal void SetPrimitiveTypeSpec(int ix, TypeSpec typeSpec)
{
systemTypeSpecs[ix] = typeSpec;
}
internal uint Size()
{
return metaDataSize;
}
private void CalcHeapSizes ()
{
if (strings.LargeIx()) {
largeStrings = true;
heapSizes |= StringsHeapMask;
}
if (guid.LargeIx()) {
largeGUID = true;
heapSizes |= GUIDHeapMask;
}
if (blob.LargeIx()) {
largeBlob = true;
heapSizes |= BlobHeapMask;
}
largeUS = us.LargeIx();
}
internal void StreamSize(byte mask)
{
heapSizes |= mask;
}
internal uint AddToUSHeap(string str)
{
if (str == null) return 0;
return us.Add(str,true);
}
internal uint AddToUSHeap(byte[] str)
{
if (str == null) return 0;
return us.Add (str, true);
}
internal uint AddToStringsHeap(string str)
{
if ((str == null) || (str.CompareTo("") == 0)) return 0;
return strings.Add(str,false);
}
internal uint AddToGUIDHeap(Guid guidNum)
{
return guid.Add(guidNum, false);
}
internal uint AddToBlobHeap(byte[] blobBytes)
{
if (blobBytes == null) return 0;
return blob.Add(blobBytes, true);
}
internal uint AddToBlobHeap(byte val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(sbyte val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(ushort val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(short val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(uint val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(int val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(ulong val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(long val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(float val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(double val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(string val)
{
return blob.Add(val,true);
}
internal void AddCustomAttribute (CustomAttribute cattr)
{
if (cattr_list == null)
cattr_list = new ArrayList ();
cattr_list.Add (cattr);
}
internal void AddDeclSecurity (BaseDeclSecurity decl_sec)
{
if (declsec_list == null)
declsec_list = new ArrayList ();
declsec_list.Add (decl_sec);
}
private ArrayList GetTable(MDTable tableIx)
{
int tabIx = (int)tableIx;
if (metaDataTables[tabIx] == null) {
metaDataTables[tabIx] = new ArrayList();
valid |= ((ulong)0x1 << tabIx);
// Console.WriteLine("after creating table " + tableIx + "(" + tabIx + ") valid = " + valid);
numTables++;
}
return metaDataTables[tabIx];
}
internal void AddToTable(MDTable tableIx, MetaDataElement elem)
{
if (elem.Row > 0) {
// Console.Out.WriteLine("ERROR - element already in table " + tableIx);
return;
}
// updates Row field of the element
// Console.WriteLine("Adding element to table " + (uint)tableIx);
ArrayList table = GetTable(tableIx);
elem.Row = (uint)table.Count + 1;
table.Add(elem);
}
internal uint TableIndex(MDTable tableIx)
{
if (metaDataTables[(int)tableIx] == null) return 1;
return (uint)metaDataTables[(int)tableIx].Count+1;
}
internal uint AddCode(CILInstructions byteCode)
{
byteCodes.Add(byteCode);
uint offset = codeSize + codeStart;
codeSize += byteCode.GetCodeSize();
return offset;
}
internal void SetEntryPoint(MetaDataElement ep)
{
entryPoint = ep;
}
internal uint AddResource(byte[] resBytes)
{
if (resources == null) resources = new ArrayList ();
resources.Add (resBytes);
uint offset = resourcesSize;
resourcesSize += (uint)resBytes.Length + 4;
return offset;
}
internal void AddData(DataConstant cVal)
{
file.AddInitData(cVal);
}
internal static void CompressNum(uint val, MemoryStream sig)
{
if (val <= 0x7F) {
sig.WriteByte((byte)val);
} else if (val <= 0x3FFF) {
byte b1 = (byte)((val >> 8) | 0x80);
byte b2 = (byte)(val & FileImage.iByteMask[0]);
sig.WriteByte(b1);
sig.WriteByte(b2);
} else {
byte b1 = (byte)((val >> 24) | 0xC0);
byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
byte b4 = (byte)(val & FileImage.iByteMask[0]);
sig.WriteByte(b1);
sig.WriteByte(b2);
sig.WriteByte(b3);
sig.WriteByte(b4);
}
}
internal uint CodeSize()
{
return codeSize + byteCodePadding;
}
internal uint GetResourcesSize()
{
return resourcesSize;
}
internal uint StringsIndexSize()
{
if (largeStrings) return 4;
return 2;
}
internal uint GUIDIndexSize()
{
if (largeGUID) return 4;
return 2;
}
internal uint USIndexSize()
{
if (largeUS) return 4;
return 2;
}
internal uint BlobIndexSize()
{
if (largeBlob) return 4;
return 2;
}
internal uint CodedIndexSize(CIx code)
{
if (lgeCIx[(uint)code]) return 4;
return 2;
}
internal uint TableIndexSize(MDTable tabIx)
{
if (largeIx[(uint)tabIx]) return 4;
return 2;
}
private void SetIndexSizes()
{
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] == null)
continue;
uint count = (uint)metaDataTables[i].Count;
if (count > maxSmlIxSize)
largeIx[i] = true;
MDTable tabIx = (MDTable)i;
if (count > max5BitSmlIx) {
lgeCIx[(int)CIx.HasCustomAttr] = true;
}
if (count > max3BitSmlIx) {
if ((tabIx == MDTable.TypeRef) || (tabIx == MDTable.ModuleRef) || (tabIx == MDTable.Method) || (tabIx == MDTable.TypeSpec) || (tabIx == MDTable.Field))
lgeCIx[(int)CIx.CustomAttributeType] = true;
if ((tabIx == MDTable.Method) || (tabIx == MDTable.MemberRef))
lgeCIx[(int)CIx.MemberRefParent] = true;
}
if (count > max2BitSmlIx) {
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param) || (tabIx == MDTable.Property))
lgeCIx[(int)CIx.HasConst] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.TypeRef) || (tabIx == MDTable.TypeSpec))
lgeCIx[(int)CIx.TypeDefOrRef] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method) || (tabIx == MDTable.Assembly))
lgeCIx[(int)CIx.HasDeclSecurity] = true;
if ((tabIx == MDTable.File) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.ExportedType))
lgeCIx[(int)CIx.Implementation] = true;
if ((tabIx == MDTable.Module) || (tabIx == MDTable.ModuleRef) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.TypeRef))
lgeCIx[(int)CIx.ResolutionScope] = true;
}
if (count > max1BitSmlIx) {
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param))
lgeCIx[(int)CIx.HasFieldMarshal] = true;
if ((tabIx == MDTable.Event) || (tabIx == MDTable.Property))
lgeCIx[(int)CIx.HasSemantics] = true;
if ((tabIx == MDTable.Method) || (tabIx == MDTable.MemberRef))
lgeCIx[(int)CIx.MethodDefOrRef] = true;
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Method))
lgeCIx[(int)CIx.MemberForwarded] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method))
lgeCIx[(int)CIx.TypeOrMethodDef] = true;
}
}
}
private void SetStreamOffsets()
{
uint sizeOfHeaders = StreamHeaderSize + (uint)tildeName.Length;
for (int i=1; i < numStreams; i++) {
sizeOfHeaders += streams[i].headerSize();
}
metaDataSize = MetaDataHeaderSize + sizeOfHeaders;
tildeStart = metaDataSize;
metaDataSize += tildeTide + tildePadding;
for (int i=1; i < numStreams; i++) {
streams[i].Start = metaDataSize;
metaDataSize += streams[i].Size();
streams[i].WriteDetails();
}
}
internal void CalcTildeStreamSize()
{
CalcHeapSizes ();
//tilde.SetIndexSizes(strings.LargeIx(),us.LargeIx(),guid.LargeIx(),blob.LargeIx());
tildeTide = TildeHeaderSize;
tildeTide += 4 * numTables;
//Console.WriteLine("Tilde header + sizes = " + tildeTide);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
ArrayList table = metaDataTables[i];
// Console.WriteLine("Meta data table " + i + " at offset " + tildeTide);
tildeTide += (uint)table.Count * ((MetaDataElement)table[0]).Size(this);
// Console.WriteLine("Metadata table " + i + " has size " + table.Count);
// Console.WriteLine("tildeTide = " + tildeTide);
}
}
if ((tildeTide % 4) != 0) tildePadding = 4 - (tildeTide % 4);
//Console.WriteLine("tildePadding = " + tildePadding);
}
internal void WriteTildeStream(FileImage output)
{
long startTilde = output.Seek(0,SeekOrigin.Current);
output.Write((uint)0); // Reserved
#if NET_2_0 || BOOTSTRAP_NET_2_0
output.Write((byte)2); // MajorVersion
output.Write((byte)0); // MinorVersion
#else
output.Write((byte)1); // MajorVersion
output.Write((byte)0); // MinorVersion
#endif
output.Write(heapSizes);
output.Write((byte)1); // Reserved
output.Write(valid);
output.Write(sorted);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
uint count = (uint)metaDataTables[i].Count;
output.Write(count);
}
}
long tabStart = output.Seek(0,SeekOrigin.Current);
// Console.WriteLine("Starting metaData tables at " + tabStart);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
// Console.WriteLine("Starting metaData table " + i + " at " + (output.Seek(0,SeekOrigin.Current) - startTilde));
ArrayList table = metaDataTables[i];
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).Write(output);
}
}
}
// Console.WriteLine("Writing padding at " + output.Seek(0,SeekOrigin.Current));
for (int i=0; i < tildePadding; i++) output.Write((byte)0);
}
private void BuildTable(ArrayList table)
{
if (table == null) return;
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).BuildTables(this);
}
}
private void SortTable (ArrayList mTable)
{
if (mTable == null) return;
mTable.Sort();
for (int i=0; i < mTable.Count; i++) {
((MetaDataElement)mTable[i]).Row = (uint)i+1;
}
}
internal void BuildMetaData(uint codeStartOffset)
{
codeStart = codeStartOffset;
BuildTable(metaDataTables[(int)MDTable.TypeDef]);
BuildTable(metaDataTables[(int)MDTable.TypeSpec]);
BuildTable(metaDataTables[(int)MDTable.MemberRef]);
#if NET_2_0 || BOOTSTRAP_NET_2_0
BuildTable(metaDataTables[(int)MDTable.GenericParam]);
BuildTable(metaDataTables[(int)MDTable.MethodSpec]);
BuildTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
#endif
BuildTable(metaDataTables[(int)MDTable.ManifestResource]);
if (cattr_list != null) {
foreach (CustomAttribute cattr in cattr_list)
cattr.BuildTables (this);
}
if (declsec_list != null) {
foreach (BaseDeclSecurity decl_sec in declsec_list)
decl_sec.BuildTables (this);
}
/* for (int i=0; i < metaDataTables.Length; i++) {
ArrayList table = metaDataTables[i];
if (table != null) {
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).BuildTables(this);
}
}
}
*/
SetIndexSizes();
for (int i=1; i < numStreams; i++) {
streams[i].EndStream();
}
CalcTildeStreamSize();
SetStreamOffsets();
byteCodePadding = NumToAlign(codeSize,4);
if (entryPoint != null) file.SetEntryPoint(entryPoint.Token());
// Check ordering of specific tables
// Constant, CustomAttribute, FieldMarshal, DeclSecurity, MethodSemantics
// ImplMap, GenericParam
// Need to load GenericParamConstraint AFTER GenericParam table in correct order
// The tables:
// InterfaceImpl, ClassLayout, FieldLayout, MethodImpl, FieldRVA, NestedClass
// will _ALWAYS_ be in the correct order as embedded in BuildMDTables
SortTable(metaDataTables[(int)MDTable.Constant]);
SortTable(metaDataTables[(int)MDTable.FieldMarshal]);
SortTable(metaDataTables[(int)MDTable.DeclSecurity]);
SortTable(metaDataTables[(int)MDTable.MethodSemantics]);
SortTable(metaDataTables[(int)MDTable.ImplMap]);
#if NET_2_0 || BOOTSTRAP_NET_2_0
if (metaDataTables[(int)MDTable.GenericParam] != null) {
SortTable(metaDataTables[(int)MDTable.GenericParam]);
// Now add GenericParamConstraints
/*for (int i=0; i < metaDataTables[(int)MDTable.GenericParam].Count; i++) {
((GenericParameter)metaDataTables[(int)MDTable.GenericParam][i]).AddConstraints(this);
}*/
}
SortTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
#endif
SortTable(metaDataTables[(int)MDTable.InterfaceImpl]);
SortTable(metaDataTables[(int)MDTable.CustomAttribute]);
}
internal void WriteByteCodes(FileImage output)
{
for (int i=0; i < byteCodes.Count; i++) {
((CILInstructions)byteCodes[i]).Write(output);
}
for (int i=0; i < byteCodePadding; i++) {
output.Write((byte)0);
}
}
internal void WriteResources (FileImage output)
{
if (resources == null) return;
for (int i = 0; i < resources.Count; i ++) {
byte [] resBytes = (byte []) resources [i];
output.Write ((uint) resBytes.Length);
output.Write (resBytes);
}
}
internal void WriteMetaData(FileImage output)
{
this.output = output;
mdStart = output.Seek(0,SeekOrigin.Current);
// Console.WriteLine("Writing metaData at " + Hex.Long(mdStart));
output.Write(MetaDataSignature);
output.Write((short)1); // Major Version
output.Write((short)1); // Minor Version ECMA = 0, PEFiles = 1
output.Write(0); // Reserved
output.Write(version.Length);
output.Write(version.ToCharArray()); // version string is already zero padded
output.Write((short)0);
output.Write((ushort)numStreams);
// write tilde header
output.Write(tildeStart);
output.Write(tildeTide + tildePadding);
output.Write(tildeName);
for (int i=1; i < numStreams; i++) streams[i].WriteHeader(output);
// Console.WriteLine("Writing tilde stream at " + output.Seek(0,SeekOrigin.Current) + " = " + tildeStart);
WriteTildeStream(output);
for (int i=1; i < numStreams; i++) streams[i].Write(output);
// Console.WriteLine("Finished Writing metaData at " + output.Seek(0,SeekOrigin.Current));
}
internal bool LargeStringsIndex() { return strings.LargeIx(); }
internal bool LargeGUIDIndex() { return guid.LargeIx(); }
internal bool LargeUSIndex() { return us.LargeIx(); }
internal bool LargeBlobIndex() { return blob.LargeIx(); }
internal bool LargeIx(MDTable tabIx) { return largeIx[(uint)tabIx]; }
private uint NumToAlign(uint val, uint alignVal)
{
if ((val % alignVal) == 0) return 0;
return alignVal - (val % alignVal);
}
internal void WriteCodedIndex(CIx code, MetaDataElement elem, FileImage output)
{
uint ix = 0;
if (elem != null) {
ix = (elem.Row << CIxShiftMap[(uint)code]) | elem.GetCodedIx(code);
// Console.WriteLine("coded index = " + ix + " row = " + elem.Row);
//} else {
// Console.WriteLine("elem for coded index is null");
}
if (lgeCIx[(uint)code])
output.Write(ix);
else
output.Write((ushort)ix);
}
}
/**************************************************************************/
/// <summary>
/// Stream in the Meta Data (#Strings, #US, #Blob and #GUID)
/// </summary>
internal class MetaDataStream : BinaryWriter {
private static readonly uint StreamHeaderSize = 8;
private static uint maxSmlIxSize = 0xFFFF;
private uint start = 0;
uint size = 0, tide = 1;
bool largeIx = false;
uint sizeOfHeader;
char[] name;
Hashtable htable = new Hashtable();
Hashtable btable = new Hashtable (new ByteArrayHashCodeProvider (), new ByteArrayComparer ());
internal MetaDataStream(char[] name, bool addInitByte) : base(new MemoryStream())
{
if (addInitByte) { Write((byte)0); size = 1; }
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
internal MetaDataStream(char[] name, System.Text.Encoding enc, bool addInitByte) : base(new MemoryStream(),enc)
{
if (addInitByte) { Write((byte)0); size = 1; }
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
public uint Start {
get { return start; }
set { start = value; }
}
internal uint headerSize()
{
// Console.WriteLine(name + " stream has headersize of " + sizeOfHeader);
return sizeOfHeader;
}
internal void SetSize(uint siz)
{
size = siz;
}
internal uint Size()
{
return size;
}
internal bool LargeIx()
{
return largeIx;
}
internal void WriteDetails()
{
// Console.WriteLine(name + " - size = " + size);
}
internal uint Add(string str, bool prependSize)
{
Object val = htable[str];
uint index = 0;
if (val == null) {
index = size;
htable[str] = index;
char[] arr = str.ToCharArray();
if (prependSize) CompressNum((uint)arr.Length*2+1);
Write(arr);
Write((byte)0);
size = (uint)Seek(0,SeekOrigin.Current);
} else {
index = (uint)val;
}
return index;
}
internal uint Add (byte[] str, bool prependSize)
{
Object val = btable [str];
uint index = 0;
if (val == null) {
index = size;
btable [str] = index;
if (prependSize) CompressNum ((uint) str.Length);
Write (str);
size = (uint) Seek (0, SeekOrigin.Current);
} else {
index = (uint) val;
}
return index;
}
internal uint Add(Guid guid, bool prependSize)
{
byte [] b = guid.ToByteArray ();
if (prependSize) CompressNum ((uint) b.Length);
Write(guid.ToByteArray());
size =(uint)Seek(0,SeekOrigin.Current);
return tide++;
}
internal uint Add(byte[] blob)
{
uint ix = size;
CompressNum((uint)blob.Length);
Write(blob);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(byte val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(sbyte val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(ushort val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(short val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(uint val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(int val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (4);
Write (val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(ulong val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(long val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(float val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(double val, bool prependSize)
{
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
private void CompressNum(uint val)
{
if (val < 0x7F) {
Write((byte)val);
} else if (val < 0x3FFF) {
byte b1 = (byte)((val >> 8) | 0x80);
byte b2 = (byte)(val & FileImage.iByteMask[0]);
Write(b1);
Write(b2);
} else {
byte b1 = (byte)((val >> 24) | 0xC0);
byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
byte b4 = (byte)(val & FileImage.iByteMask[0]);
Write(b1);
Write(b2);
Write(b3);
Write(b4);
}
}
private void QuadAlign()
{
if ((size % 4) != 0) {
uint pad = 4 - (size % 4);
size += pad;
for (int i=0; i < pad; i++) {
Write((byte)0);
}
}
}
internal void EndStream()
{
QuadAlign();
if (size > maxSmlIxSize) {
largeIx = true;
}
}
internal void WriteHeader(BinaryWriter output)
{
output.Write(start);
output.Write(size);
output.Write(name);
}
internal virtual void Write(BinaryWriter output)
{
// Console.WriteLine("Writing " + name + " stream at " + output.Seek(0,SeekOrigin.Current) + " = " + start);
MemoryStream str = (MemoryStream)BaseStream;
output.Write(str.ToArray());
}
}
/**************************************************************************/
class ByteArrayComparer : IComparer {
public int Compare (object x, object y)
{
byte [] a = (byte []) x;
byte [] b = (byte []) y;
int len = a.Length;
if (b.Length != len)
return 1;
for (int i = 0; i < len; ++i)
if (a [i] != b [i])
return 1;
return 0;
}
}
class ByteArrayHashCodeProvider : IHashCodeProvider {
public int GetHashCode (Object key)
{
byte [] arr = (byte []) key;
int len = arr.Length;
int h = 0;
for (int i = 0; i < len; ++i)
h = (h << 5) - h + arr [i];
return h;
}
}
}
| 27.104488 | 157 | 0.65535 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/PEAPI/Metadata.cs | 158,236 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHintsProvider.cs" company="WildGums">
// Copyright (c) 2008 - 2014 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Orchestra.Services
{
using System.Collections.Generic;
using System.Windows;
using Models;
public interface IHintsProvider
{
#region Methods
IHint[] GetHintsFor(FrameworkElement element);
#endregion
}
}
| 30.571429 | 120 | 0.420561 | [
"MIT"
] | Dmitry-VF/Orchestra | src/Orchestra.Core/Services/Interfaces/IHintsProvider.cs | 644 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using HotChocolate.Configuration.Validation;
using HotChocolate.Internal;
using HotChocolate.Resolvers;
using HotChocolate.Resolvers.Expressions;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Descriptors.Definitions;
using static HotChocolate.Properties.TypeResources;
#nullable enable
namespace HotChocolate.Configuration
{
internal class TypeInitializer
{
private readonly Dictionary<FieldReference, RegisteredResolver> _resolvers = new();
private readonly List<FieldMiddleware> _globalComps = new();
private readonly List<ISchemaError> _errors = new();
private readonly IDescriptorContext _context;
private readonly ITypeInspector _typeInspector;
private readonly IReadOnlyList<ITypeReference> _initialTypes;
private readonly IReadOnlyList<Type> _externalResolverTypes;
private readonly TypeInterceptor _interceptor;
private readonly IsOfTypeFallback? _isOfType;
private readonly Func<TypeSystemObjectBase, RootTypeKind> _getTypeKind;
private readonly TypeRegistry _typeRegistry;
private readonly TypeLookup _typeLookup;
private readonly TypeReferenceResolver _typeReferenceResolver;
public TypeInitializer(
IDescriptorContext descriptorContext,
TypeRegistry typeRegistry,
IReadOnlyList<ITypeReference> initialTypes,
IReadOnlyList<Type> externalResolverTypes,
IsOfTypeFallback? isOfType,
Func<TypeSystemObjectBase, RootTypeKind> getTypeKind)
{
_context = descriptorContext ??
throw new ArgumentNullException(nameof(descriptorContext));
_typeRegistry = typeRegistry ??
throw new ArgumentNullException(nameof(typeRegistry));
_initialTypes = initialTypes ??
throw new ArgumentNullException(nameof(initialTypes));
_externalResolverTypes = externalResolverTypes ??
throw new ArgumentNullException(nameof(externalResolverTypes));
_isOfType = isOfType;
_getTypeKind = getTypeKind ??
throw new ArgumentNullException(nameof(_getTypeKind));
_interceptor = descriptorContext.TypeInterceptor;
_typeInspector = descriptorContext.TypeInspector;
_typeLookup = new TypeLookup(_typeInspector, _typeRegistry);
_typeReferenceResolver = new TypeReferenceResolver(
_typeInspector, _typeRegistry, _typeLookup);
}
public IList<FieldMiddleware> GlobalComponents => _globalComps;
public IDictionary<FieldReference, RegisteredResolver> Resolvers => _resolvers;
public void Initialize(
Func<ISchema> schemaResolver,
IReadOnlySchemaOptions options)
{
if (schemaResolver is null)
{
throw new ArgumentNullException(nameof(schemaResolver));
}
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
// first we are going to find and initialize all types that belong to our schema.
DiscoverTypes();
// now that we have the resolvers sorted and know what types our schema will roughly
// consist of we are going to have a look if we can infer interface usage
// from .NET classes that implement .NET interfaces.
RegisterImplicitInterfaceDependencies();
// with all types (implicit and explicit) known we complete the type names.
CompleteNames(schemaResolver);
// with the type names all known we can now build pairs to bring together types and
// their type extensions.
MergeTypeExtensions();
// Now that we merged the types it is time to register the resolvers.
RegisterResolvers();
// external resolvers are resolvers that are defined on the schema and are associated
// with the types after they have received a name and the extensions are removed.
RegisterExternalResolvers();
// with all resolvers in place we compile the once inferred from a C# member.
CompileResolvers();
// last we complete the types. Completing types means that we will assign all
// the fields resolving all missing parts and then making the types immutable.
CompleteTypes();
// at this point everything is completely initialized and we just trigger a type
// finalize to allow the type to cleanup any initialization data structures.
FinalizeTypes();
// if we do not have any errors we will validate the types for spec violations.
if (_errors.Count == 0)
{
_errors.AddRange(SchemaValidator.Validate(
_typeRegistry.Types.Select(t => t.Type),
options));
}
if (_errors.Count > 0)
{
throw new SchemaException(_errors);
}
}
private void DiscoverTypes()
{
_interceptor.OnBeforeDiscoverTypes();
var typeRegistrar = new TypeDiscoverer(
_context,
_typeRegistry,
_typeLookup,
_initialTypes,
_interceptor);
if (typeRegistrar.DiscoverTypes() is { Count: > 0 } errors)
{
throw new SchemaException(errors);
}
// lets tell the type interceptors what types we have initialized.
if (_interceptor.TriggerAggregations)
{
_interceptor.OnTypesInitialized(
_typeRegistry.Types.Select(t => t.DiscoveryContext).ToList());
}
_interceptor.OnAfterDiscoverTypes();
}
private void RegisterResolvers()
{
foreach (TypeDiscoveryContext context in
_typeRegistry.Types.Select(t => t.DiscoveryContext))
{
if (context.Type is ObjectType { Definition: { } typeDef })
{
typeDef.Name = context.Type.Name;
foreach (var fieldDef in typeDef.Fields)
{
if (TryRegisterResolver(
fieldDef,
typeDef,
out FieldReference? fieldRef,
out RegisteredResolver? registeredResolver) &&
!_resolvers.ContainsKey(fieldRef))
{
_resolvers.Add(fieldRef, registeredResolver);
}
}
}
}
}
private bool TryRegisterResolver(
ObjectFieldDefinition fieldDef,
ObjectTypeDefinition typeDef,
[NotNullWhen(true)] out FieldReference? fieldRef,
[NotNullWhen(true)] out RegisteredResolver? registeredResolver)
{
if (fieldDef.Resolver is null)
{
fieldRef = new FieldReference(typeDef.Name, fieldDef.Name);
if (fieldDef.Expression is not null)
{
registeredResolver = new RegisteredResolver(
fieldDef.ResolverType,
typeDef.RuntimeType,
fieldRef.WithExpression(fieldDef.Expression));
return true;
}
if (fieldDef.ResolverMember is not null)
{
registeredResolver = new RegisteredResolver(
fieldDef.ResolverType,
typeDef.RuntimeType,
fieldRef.WithMember(fieldDef.ResolverMember));
return true;
}
if (fieldDef.Member is not null)
{
registeredResolver = new RegisteredResolver(
fieldDef.ResolverType,
typeDef.RuntimeType,
fieldRef.WithMember(fieldDef.Member));
return true;
}
}
fieldRef = null;
registeredResolver = null;
return false;
}
private void RegisterImplicitInterfaceDependencies()
{
var withRuntimeType = _typeRegistry.Types
.Where(t => t.RuntimeType != typeof(object))
.Distinct()
.ToList();
var interfaceTypes = withRuntimeType
.Where(t => t.Type is InterfaceType)
.Distinct()
.ToList();
var objectTypes = withRuntimeType
.Where(t => t.Type is ObjectType)
.Distinct()
.ToList();
var dependencies = new List<TypeDependency>();
foreach (RegisteredType objectType in objectTypes)
{
foreach (RegisteredType interfaceType in interfaceTypes)
{
if (interfaceType.RuntimeType.IsAssignableFrom(objectType.RuntimeType))
{
dependencies.Add(
new TypeDependency(
_typeInspector.GetTypeRef(
interfaceType.RuntimeType,
TypeContext.Output),
TypeDependencyKind.Completed));
}
}
if (dependencies.Count > 0)
{
objectType.AddDependencies(dependencies);
_typeRegistry.Register(objectType);
dependencies.Clear();
}
}
}
private void CompleteNames(Func<ISchema> schemaResolver)
{
bool CompleteName(RegisteredType registeredType)
{
registeredType.SetCompletionContext(
new TypeCompletionContext(
registeredType.DiscoveryContext,
_typeReferenceResolver,
GlobalComponents,
Resolvers,
_isOfType,
schemaResolver));
registeredType.Type.CompleteName(registeredType.CompletionContext);
if (registeredType.IsNamedType || registeredType.IsDirectiveType)
{
_typeRegistry.Register(registeredType.Type.Name, registeredType);
}
TypeCompletionContext context = registeredType.CompletionContext;
RootTypeKind kind = _getTypeKind(registeredType.Type);
context.IsQueryType = kind == RootTypeKind.Query;
context.IsMutationType = kind == RootTypeKind.Mutation;
context.IsSubscriptionType = kind == RootTypeKind.Subscription;
return true;
}
_interceptor.OnBeforeCompleteTypeNames();
if (ProcessTypes(TypeDependencyKind.Named, CompleteName) &&
_interceptor.TriggerAggregations)
{
_interceptor.OnTypesCompletedName(
_typeRegistry.Types.Select(t => t.CompletionContext).ToList());
}
EnsureNoErrors();
_interceptor.OnAfterCompleteTypeNames();
}
private void MergeTypeExtensions()
{
_interceptor.OnBeforeMergeTypeExtensions();
var extensions = _typeRegistry.Types
.Where(t => t.IsExtension)
.ToList();
if (extensions.Count > 0)
{
var processed = new HashSet<RegisteredType>();
var types = _typeRegistry.Types
.Where(t => t.IsNamedType)
.ToList();
foreach (NameString typeName in extensions
.Select(t => t.Type)
.OfType<INamedTypeExtension>()
.Where(t => t.ExtendsType is null)
.Select(t => t.Name)
.Distinct())
{
RegisteredType? type = types.FirstOrDefault(t => t.Type.Name.Equals(typeName));
if (type?.Type is INamedType namedType)
{
MergeTypeExtension(
extensions.Where(t => t.Type.Name.Equals(typeName)),
type,
namedType,
processed);
}
}
var extensionArray = new RegisteredType[1];
foreach (var extension in extensions.Except(processed))
{
if (extension.Type is INamedTypeExtension {
ExtendsType: { } extendsType } namedTypeExtension)
{
var isSchemaType = typeof(INamedType).IsAssignableFrom(extendsType);
extensionArray[0] = extension;
foreach (var possibleMatchingType in types
.Where(t =>
t.Type is INamedType n &&
n.Kind == namedTypeExtension.Kind))
{
if (isSchemaType &&
extendsType.IsInstanceOfType(possibleMatchingType))
{
MergeTypeExtension(
extensionArray,
possibleMatchingType,
(INamedType)possibleMatchingType.Type,
processed);
}
else if (!isSchemaType &&
possibleMatchingType.RuntimeType != typeof(object) &&
extendsType.IsAssignableFrom(possibleMatchingType.RuntimeType))
{
MergeTypeExtension(
extensionArray,
possibleMatchingType,
(INamedType)possibleMatchingType.Type,
processed);
}
}
}
}
}
_interceptor.OnAfterMergeTypeExtensions();
}
private void MergeTypeExtension(
IEnumerable<RegisteredType> extensions,
RegisteredType registeredType,
INamedType namedType,
HashSet<RegisteredType> processed)
{
foreach (RegisteredType extension in extensions)
{
processed.Add(extension);
if (extension.Type is INamedTypeExtensionMerger m)
{
if (m.Kind != namedType.Kind)
{
throw new SchemaException(SchemaErrorBuilder.New()
.SetMessage(string.Format(
CultureInfo.InvariantCulture,
TypeInitializer_Merge_KindDoesNotMatch,
namedType.Name))
.SetTypeSystemObject((ITypeSystemObject)namedType)
.Build());
}
// merge
TypeCompletionContext context = extension.CompletionContext;
context.Status = TypeStatus.Named;
m.Merge(context, namedType);
// update dependencies
context = registeredType.CompletionContext;
registeredType.AddDependencies(extension.Dependencies);
_typeRegistry.Register(registeredType);
CopyAlternateNames(extension.CompletionContext, context);
}
}
}
private static void CopyAlternateNames(
TypeCompletionContext source,
TypeCompletionContext destination)
{
foreach (NameString name in source.AlternateTypeNames)
{
destination.AlternateTypeNames.Add(name);
}
}
private void RegisterExternalResolvers()
{
if (_externalResolverTypes.Count == 0)
{
return;
}
Dictionary<NameString, ObjectType> types =
_typeRegistry.Types.Select(t => t.Type)
.OfType<ObjectType>()
.ToDictionary(t => t.Name);
foreach (Type type in _externalResolverTypes)
{
GraphQLResolverOfAttribute? attribute =
type.GetCustomAttribute<GraphQLResolverOfAttribute>();
if (attribute?.TypeNames is not null)
{
foreach (string typeName in attribute.TypeNames)
{
if (types.TryGetValue(typeName, out ObjectType? objectType))
{
AddResolvers(_context, objectType, type);
}
}
}
if (attribute?.Types is not null)
{
foreach (Type sourceType in attribute.Types
.Where(t => !t.IsNonGenericSchemaType()))
{
ObjectType? objectType = types.Values
.FirstOrDefault(t =>
t.GetType() == sourceType ||
t.RuntimeType == sourceType);
if (objectType is not null)
{
AddResolvers(_context, objectType, type);
}
}
}
}
}
private void AddResolvers(
IDescriptorContext context,
ObjectType objectType,
Type resolverType)
{
foreach (MemberInfo member in
context.TypeInspector.GetMembers(resolverType))
{
if (IsResolverRelevant(objectType.RuntimeType, member))
{
NameString fieldName = context.Naming.GetMemberName(
member, MemberKind.ObjectField);
var fieldMember = new FieldMember(
objectType.Name, fieldName, member);
var resolver = new RegisteredResolver(
resolverType, objectType.RuntimeType, fieldMember);
_resolvers[fieldMember.ToFieldReference()] = resolver;
}
}
}
private static bool IsResolverRelevant(
Type sourceType,
MemberInfo resolver)
{
if (resolver is PropertyInfo)
{
return true;
}
if (resolver is MethodInfo m)
{
ParameterInfo? parent = m.GetParameters()
.FirstOrDefault(t => t.IsDefined(typeof(ParentAttribute)));
return parent is null
|| parent.ParameterType.IsAssignableFrom(sourceType);
}
return false;
}
private void CompileResolvers()
{
foreach (KeyValuePair<FieldReference, RegisteredResolver> item in _resolvers.ToArray())
{
RegisteredResolver registered = item.Value;
if (registered.Field is FieldMember member)
{
ResolverDescriptor descriptor = new(
registered.SourceType,
member,
resolverType: registered.IsSourceResolver
? null
: registered.ResolverType);
_resolvers[item.Key] = registered.WithField(
ResolverCompiler.Resolve.Compile(descriptor));
}
}
}
private void CompleteTypes()
{
bool CompleteType(RegisteredType registeredType)
{
if (!registeredType.IsExtension)
{
TypeCompletionContext context = registeredType.CompletionContext;
context.Status = TypeStatus.Named;
RootTypeKind kind = _getTypeKind(registeredType.Type);
context.IsQueryType = kind == RootTypeKind.Query;
context.IsMutationType = kind == RootTypeKind.Mutation;
context.IsSubscriptionType = kind == RootTypeKind.Subscription;
registeredType.Type.CompleteType(context);
}
return true;
}
_interceptor.OnBeforeCompleteTypes();
ProcessTypes(TypeDependencyKind.Completed, CompleteType);
EnsureNoErrors();
if (_interceptor.TriggerAggregations)
{
_interceptor.OnTypesCompleted(
_typeRegistry.Types.Select(t => t.CompletionContext).ToList());
}
_interceptor.OnAfterCompleteTypes();
}
private void FinalizeTypes()
{
foreach (var registeredType in _typeRegistry.Types)
{
if (!registeredType.IsExtension)
{
registeredType.Type.FinalizeType(registeredType.CompletionContext);
}
}
}
private bool ProcessTypes(
TypeDependencyKind kind,
Func<RegisteredType, bool> action)
{
var processed = new HashSet<ITypeReference>();
var batch = new List<RegisteredType>(GetInitialBatch(kind));
var failed = false;
while (!failed
&& processed.Count < _typeRegistry.Count
&& batch.Count > 0)
{
foreach (RegisteredType registeredType in batch)
{
if (!action(registeredType))
{
failed = true;
break;
}
foreach (ITypeReference reference in registeredType.References)
{
processed.Add(reference);
}
}
if (!failed)
{
batch.Clear();
batch.AddRange(GetNextBatch(processed, kind));
}
}
if (!failed && processed.Count < _typeRegistry.Count)
{
foreach (RegisteredType type in _typeRegistry.Types
.Where(t => !processed.Contains(t.References[0])))
{
string name = type.Type.Name.HasValue
? type.Type.Name.Value
: type.References[0].ToString()!;
ITypeReference[] references =
type.Dependencies.Where(t => t.Kind == kind)
.Select(t => t.TypeReference).ToArray();
IReadOnlyList<ITypeReference> needed =
TryNormalizeDependencies(references,
out IReadOnlyList<ITypeReference>? normalized)
? normalized.Except(processed).ToArray()
: references;
_errors.Add(SchemaErrorBuilder.New()
.SetMessage(
TypeInitializer_CannotResolveDependency,
name,
string.Join(", ", needed))
.SetTypeSystemObject(type.Type)
.Build());
}
return false;
}
return _errors.Count == 0;
}
private IEnumerable<RegisteredType> GetInitialBatch(
TypeDependencyKind kind)
{
return _typeRegistry.Types.Where(t => t.Dependencies.All(d => d.Kind != kind));
}
private IEnumerable<RegisteredType> GetNextBatch(
ISet<ITypeReference> processed,
TypeDependencyKind kind)
{
foreach (RegisteredType type in _typeRegistry.Types)
{
if (!processed.Contains(type.References[0]))
{
IEnumerable<ITypeReference> references =
type.Dependencies.Where(t => t.Kind == kind)
.Select(t => t.TypeReference);
if (TryNormalizeDependencies(references,
out IReadOnlyList<ITypeReference>? normalized)
&& processed.IsSupersetOf(normalized))
{
yield return type;
}
}
}
}
private bool TryNormalizeDependencies(
IEnumerable<ITypeReference> dependencies,
[NotNullWhen(true)] out IReadOnlyList<ITypeReference>? normalized)
{
var n = new List<ITypeReference>();
foreach (ITypeReference reference in dependencies)
{
if (!_typeLookup.TryNormalizeReference(
reference,
out ITypeReference? nr))
{
normalized = null;
return false;
}
if (!n.Contains(nr))
{
n.Add(nr);
}
}
normalized = n;
return true;
}
private void EnsureNoErrors()
{
var errors = new List<ISchemaError>(_errors);
foreach (TypeDiscoveryContext context in
_typeRegistry.Types.Select(t => t.DiscoveryContext))
{
errors.AddRange(context.Errors);
}
if (errors.Count > 0)
{
throw new SchemaException(errors);
}
}
}
internal enum RootTypeKind
{
Query,
Mutation,
Subscription,
None
}
}
| 37.035714 | 99 | 0.503709 | [
"MIT"
] | BaptisteGirard/hotchocolate | src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs | 26,962 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.AlertsManagement.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Data contract for patch.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class PatchObject
{
/// <summary>
/// Initializes a new instance of the PatchObject class.
/// </summary>
public PatchObject()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the PatchObject class.
/// </summary>
/// <param name="enabled">Indicates if the given alert processing rule
/// is enabled or disabled.</param>
/// <param name="tags">Tags to be updated.</param>
public PatchObject(bool? enabled = default(bool?), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
Enabled = enabled;
Tags = tags;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets indicates if the given alert processing rule is
/// enabled or disabled.
/// </summary>
[JsonProperty(PropertyName = "properties.enabled")]
public bool? Enabled { get; set; }
/// <summary>
/// Gets or sets tags to be updated.
/// </summary>
[JsonProperty(PropertyName = "tags")]
public IDictionary<string, string> Tags { get; set; }
}
}
| 31.41791 | 131 | 0.610926 | [
"MIT"
] | AhmedLeithy/azure-sdk-for-net | sdk/alertsmanagement/Microsoft.Azure.Management.AlertsManagement/src/Generated/Models/PatchObject.cs | 2,105 | C# |
using System;
using System.Collections.Generic;
namespace BrainSimulator
{
class FiringHistory
{
const int maxSamples = 1000;
public class Sample
{
public long generation = 0;
public float value = 0;
}
public class NeuronHistory
{
public int NeuronID;
public List<Sample> Samples = new();
}
public static List<NeuronHistory> history = new ();
public static long EarliestValue()
{
long retVal = long.MaxValue;
for (int i = 0; i < history.Count; i++)
{
if (history[i].Samples.Count > 0)
retVal = Math.Min(retVal, history[i].Samples[0].generation);
}
return retVal;
}
public static bool NeuronIsInFiringHistory(int id)
{
for (int i = 0; i < history.Count; i++)
{
if (history[i].NeuronID == id)
{
return true;
}
}
return false;
}
public static void AddNeuronToHistoryWindow(int id)
{
if (NeuronIsInFiringHistory(id)) return;
NeuronHistory entry = new();
entry.NeuronID = id;
history.Add(entry);
}
public static void RemoveNeuronFromHistoryWindow(int id)
{
for (int i = 0; i < history.Count; i++)
{
if (history[i].NeuronID == id)
{
history.RemoveAt(i);
return;
}
}
}
public static void UpdateFiringHistory()
{
if (MainWindow.theNeuronArray == null) return;
for (int i = 0; i < history.Count; i++)
{
NeuronHistory active = history[i];
float lastCharge = MainWindow.theNeuronArray.GetNeuron(active.NeuronID).lastCharge;
if (active.Samples.Count > maxSamples)
active.Samples.RemoveAt(0);
active.Samples.Add(new Sample { generation = MainWindow.theNeuronArray.Generation, value = lastCharge });
}
}
public static void Clear()
{
for (int i = 0; i < history.Count; i++)
{
history[i].Samples.Clear();
}
}
public static void ClearAll()
{
Clear();
history.Clear();
}
}
}
| 28.617978 | 121 | 0.47075 | [
"MIT"
] | Synchronicity89/BrainSimII | BrainSimulator/FiringHistory.cs | 2,549 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.