content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Person pepa = new Person(); pepa.Name = "Josef Kapusta"; pepa.Age = 12; Console.WriteLine("Jmeno: {0}, Vek {1}", pepa.Name, pepa.Age); Person kuba = new Person() { Name = "Jakub Kopriva", Age = 5}; Console.WriteLine("Jmeno: {0}, Vek {1}", kuba.Name, kuba.Age); Console.WriteLine(kuba); Console.ReadKey(); } } public class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return "Person: " + Name + " Age: " + Age; } } }
21.756757
74
0.504348
[ "MIT" ]
Andy-Merhaut/sssvt-prg-maturita
ConsoleApp5/ConsoleApp5/Program.cs
807
C#
// <auto-generated /> // Built from: hl7.fhir.r5.core version: 4.6.0 // Option: "NAMESPACE" = "fhirCsR5" using fhirCsR5.Models; namespace fhirCsR5.ValueSets { /// <summary> /// Medication Status Codes /// </summary> public static class MedicationStatusCodes { /// <summary> /// The medication is available for use. /// </summary> public static readonly Coding Active = new Coding { Code = "active", Display = "Active", System = "http://hl7.org/fhir/CodeSystem/medication-status" }; /// <summary> /// The medication was entered in error. /// </summary> public static readonly Coding EnteredInError = new Coding { Code = "entered-in-error", Display = "Entered in Error", System = "http://hl7.org/fhir/CodeSystem/medication-status" }; /// <summary> /// The medication is not available for use. /// </summary> public static readonly Coding Inactive = new Coding { Code = "inactive", Display = "Inactive", System = "http://hl7.org/fhir/CodeSystem/medication-status" }; }; }
25.837209
65
0.612961
[ "MIT" ]
FirelyTeam/fhir-codegen
src/Microsoft.Health.Fhir.SpecManager/fhir/R5/ValueSets/MedicationStatus.cs
1,111
C#
namespace PhotoShare.Data.Configurations { public static class PhotoShareDbConfiguration { public const string ConnectionString = @"Server=DESKTOP-DEHICSC\SQLEXPRESS01;Database=PhotoShareDb;Integrated Security=True"; } }
34.428571
133
0.771784
[ "MIT" ]
thelad43/Databases-Advanced-Entity-Framework-SoftUni
08. Exercise Best Practices And Architecture/PhotoShareSystem/PhotoShare.Data/Configurations/PhotoShareDbConfiguration.cs
243
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Text; namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json { internal struct IsoDate { internal int Year { get; set; } // 0-3000 internal int Month { get; set; } // 1-12 internal int Day { get; set; } // 1-31 internal int Hour { get; set; } // 0-24 internal int Minute { get; set; } // 0-60 (60 is a special case) internal int Second { get; set; } // 0-60 (60 is used for leap seconds) internal double Millisecond { get; set; } // 0-999.9... internal TimeSpan Offset { get; set; } internal DateTimeKind Kind { get; set; } internal TimeSpan TimeOfDay => new TimeSpan(Hour, Minute, Second); internal DateTime ToDateTime() { if (Kind == DateTimeKind.Utc || Offset == TimeSpan.Zero) { return new DateTime(Year, Month, Day, Hour, Minute, Second, (int)Millisecond, DateTimeKind.Utc); } return ToDateTimeOffset().DateTime; } internal DateTimeOffset ToDateTimeOffset() { return new DateTimeOffset( Year, Month, Day, Hour, Minute, Second, (int)Millisecond, Offset ); } internal DateTime ToUtcDateTime() { return ToDateTimeOffset().UtcDateTime; } public override string ToString() { var sb = new StringBuilder(); // yyyy-MM-dd sb.Append($"{Year}-{Month:00}-{Day:00}"); if (TimeOfDay > new TimeSpan(0)) { sb.Append($"T{Hour:00}:{Minute:00}"); if (TimeOfDay.Seconds > 0) { sb.Append($":{Second:00}"); } } if (Offset.Ticks == 0) { sb.Append('Z'); // UTC } else { if (Offset.Ticks >= 0) { sb.Append('+'); } sb.Append($"{Offset.Hours:00}:{Offset.Minutes:00}"); } return sb.ToString(); } internal static IsoDate FromDateTimeOffset(DateTimeOffset date) { return new IsoDate { Year = date.Year, Month = date.Month, Day = date.Day, Hour = date.Hour, Minute = date.Minute, Second = date.Second, Offset = date.Offset, Kind = date.Offset == TimeSpan.Zero ? DateTimeKind.Utc : DateTimeKind.Unspecified }; } private static readonly char[] timeSeperators = { ':', '.' }; internal static IsoDate Parse(string text) { var tzIndex = -1; var timeIndex = text.IndexOf('T'); var builder = new IsoDate { Day = 1, Month = 1 }; // TODO: strip the time zone offset off the end string dateTime = text; string timeZone = null; if (dateTime.IndexOf('Z') > -1) { tzIndex = dateTime.LastIndexOf('Z'); builder.Kind = DateTimeKind.Utc; } else if (dateTime.LastIndexOf('+') > 10) { tzIndex = dateTime.LastIndexOf('+'); } else if (dateTime.LastIndexOf('-') > 10) { tzIndex = dateTime.LastIndexOf('-'); } if (tzIndex > -1) { timeZone = dateTime.Substring(tzIndex); dateTime = dateTime.Substring(0, tzIndex); } string date = (timeIndex == -1) ? dateTime : dateTime.Substring(0, timeIndex); var dateParts = date.Split(Seperator.Dash); // '-' for (int i = 0; i < dateParts.Length; i++) { var part = dateParts[i]; switch (i) { case 0: builder.Year = int.Parse(part); break; case 1: builder.Month = int.Parse(part); break; case 2: builder.Day = int.Parse(part); break; } } if (timeIndex > -1) { string[] timeParts = dateTime.Substring(timeIndex + 1).Split(timeSeperators); for (int i = 0; i < timeParts.Length; i++) { var part = timeParts[i]; switch (i) { case 0: builder.Hour = int.Parse(part); break; case 1: builder.Minute = int.Parse(part); break; case 2: builder.Second = int.Parse(part); break; case 3: builder.Millisecond = double.Parse("0." + part) * 1000; break; } } } if (timeZone != null && timeZone != "Z") { var hours = int.Parse(timeZone.Substring(1, 2)); var minutes = int.Parse(timeZone.Substring(4, 2)); if (timeZone[0] == '-') { hours = -hours; minutes = -minutes; } builder.Offset = new TimeSpan(hours, minutes, 0); } return builder; } } /* YYYY # eg 1997 YYYY-MM # eg 1997-07 YYYY-MM-DD # eg 1997-07-16 YYYY-MM-DDThh:mmTZD # eg 1997-07-16T19:20+01:00 YYYY-MM-DDThh:mm:ssTZD # eg 1997-07-16T19:20:30+01:00 YYYY-MM-DDThh:mm:ss.sTZD # eg 1997-07-16T19:20:30.45+01:00 where: YYYY = four-digit year MM = two-digit month (01=January, etc.) DD = two-digit day of month (01 through 31) hh = two digits of hour (00 through 23) (am/pm NOT allowed) mm = two digits of minute (00 through 59) ss = two digits of second (00 through 59) s = one or more digits representing a decimal fraction of a second TZD = time zone designator (Z or +hh:mm or -hh:mm) */ }
31.781395
113
0.438168
[ "MIT" ]
3quanfeng/azure-powershell
src/ConnectedKubernetes/generated/runtime/Iso/IsoDate.cs
6,621
C#
using ExRam.Gremlinq.Core.Serialization; namespace ExRam.Gremlinq.Core { public sealed class NoneStep : Step { public static readonly NoneStep Instance = new NoneStep(); private NoneStep() { } public override void Accept(IGremlinQueryElementVisitor visitor) { visitor.Visit(this); } } public sealed class CoinStep : Step { public double Probability { get; } public CoinStep(double probability) { Probability = probability; } public override void Accept(IGremlinQueryElementVisitor visitor) { visitor.Visit(this); } } }
20.529412
72
0.584527
[ "MIT" ]
SyntaxUnknown/ExRam.Gremlinq
ExRam.Gremlinq.Core/Queries/Steps/CoinStep.cs
700
C#
using System; using EventStore.Core.Messaging; namespace EventStore.Projections.Core.Messages { public abstract class CoreProjectionManagementMessageBase : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } private readonly Guid _projectionIdId; protected CoreProjectionManagementMessageBase(Guid projectionId) { _projectionIdId = projectionId; } public Guid ProjectionId { get { return _projectionIdId; } } } }
24.481481
99
0.645991
[ "Apache-2.0", "CC0-1.0" ]
cuteant/EventStore-DotNetty-Fork
src/EventStore.Projections.Core/Messages/CoreProjectionManagementMessageBase.cs
663
C#
using System.ComponentModel.DataAnnotations; using Volo.Abp.Identity; using Volo.Abp.ObjectExtending; using Volo.Abp.Threading; namespace EShopOnAbp.IdentityService { public static class IdentityServiceModuleExtensionConfigurator { private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); public static void Configure() { OneTimeRunner.Run(() => { ConfigureExistingProperties(); ConfigureExtraProperties(); }); } private static void ConfigureExistingProperties() { /* You can change max lengths for properties of the * entities defined in the modules used by your application. * * Example: Change user and role name max lengths IdentityUserConsts.MaxNameLength = 99; IdentityRoleConsts.MaxNameLength = 99; * Notice: It is not suggested to change property lengths * unless you really need it. Go with the standard values wherever possible. * * If you are using EF Core, you will need to run the add-migration command after your changes. */ } private static void ConfigureExtraProperties() { /* You can configure extra properties for the * entities defined in the modules used by your application. * * This class can be used to define these extra properties * with a high level, easy to use API. * * Example: Add a new property to the user entity of the identity module ObjectExtensionManager.Instance.Modules() .ConfigureIdentity(identity => { identity.ConfigureUser(user => { user.AddOrUpdateProperty<string>( //property type: string "SocialSecurityNumber", //property name property => { //validation rules property.Attributes.Add(new RequiredAttribute()); property.Attributes.Add(new StringLengthAttribute(64) {MinimumLength = 4}); //...other configurations for this property } ); }); }); * See the documentation for more: * https://docs.abp.io/en/abp/latest/Module-Entity-Extensions */ } } }
36.986301
109
0.526296
[ "MIT" ]
271943794/eShopOnAbp
services/identity/src/EShopOnAbp.IdentityService.Domain.Shared/IdentityServiceModuleExtensionConfigurator.cs
2,702
C#
using Sushi.Mediakiwi.Data.MicroORM; using Sushi.MicroORM.Mapping; using System; using System.Threading.Tasks; namespace Sushi.Mediakiwi.Data { [DataMap(typeof(ComponentTargetMap))] public class ComponentTarget : IComponentTarget { public class ComponentTargetMap : DataMap<ComponentTarget> { public ComponentTargetMap() { Table("wim_ComponentTargets"); Id(x => x.ID, "ComponentTarget_Key").Identity(); Map(x => x.PageID, "ComponentTarget_Page_Key"); Map(x => x.Source, "ComponentTarget_Component_Source"); Map(x => x.Target, "ComponentTarget_Component_Target"); } } #region Properties public int ID { get; set; } public int PageID { get; set; } public Guid Source { get; set; } public Guid Target { get; set; } #endregion Properties /// <summary> /// Deletes this instance. /// </summary> public void Delete() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); connector.Delete(this); } /// <summary> /// Deletes this instance Async. /// </summary> public async Task DeleteAsync() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); await connector.DeleteAsync(this); } /// <summary> /// Selects one target based on the ID /// </summary> /// <param name="ID"></param> /// <returns></returns> public static IComponentTarget SelectOne(int ID) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); return connector.FetchSingle(ID); } /// <summary> /// Selects one target based on the ID Async /// </summary> /// <param name="ID"></param> /// <returns></returns> public static async Task<IComponentTarget> SelectOneAsync(int ID) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); return await connector.FetchSingleAsync(ID); } /// <summary> /// Selects all targets based on the PageID /// </summary> /// <param name="pageID"></param> /// <returns></returns> public static IComponentTarget[] SelectAll(int pageID) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.Add(x => x.PageID, pageID); return connector.FetchAll(filter).ToArray(); } /// <summary> /// Selects all targets based on the PageID /// </summary> /// <param name="pageID"></param> /// <returns></returns> public static async Task<IComponentTarget[]> SelectAllAsync(int pageID) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.Add(x => x.PageID, pageID); var result = await connector.FetchAllAsync(filter); return result.ToArray(); } /// <summary> /// Deletes all from Component Targets on the same page and with /// the same target /// </summary> public virtual void DeleteComplete() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.AddParameter("@thisTarget", Target); filter.AddParameter("@thisSource", Source); filter.AddParameter("@thisPageId", PageID); connector.ExecuteNonQuery(@" DELETE FROM [wim_ComponentTargets] WHERE [ComponentTarget_Page_Key] = @thisPageId AND [ComponentTarget_Component_Target] = @thisTarget AND NOT [ComponentTarget_Component_Source] = @thisSource", filter); connector.Cache?.FlushRegion(connector.CacheRegion); } /// <summary> /// Deletes all from Component Targets on the same page and with /// the same target Async /// </summary> public async virtual Task DeleteCompleteAsync() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.AddParameter("@thisTarget", Target); filter.AddParameter("@thisSource", Source); filter.AddParameter("@thisPageId", PageID); await connector.ExecuteNonQueryAsync(@" DELETE FROM [wim_ComponentTargets] WHERE [ComponentTarget_Page_Key] = @thisPageId AND [ComponentTarget_Component_Target] = @thisTarget AND NOT [ComponentTarget_Component_Source] = @thisSource", filter); connector.Cache?.FlushRegion(connector.CacheRegion); } /// <summary> /// Selects all with supplied Source GUID /// </summary> /// <param name="componentGuid"></param> /// <returns></returns> public static IComponentTarget[] SelectAll(Guid componentGuid) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.Add(x => x.Source, componentGuid); return connector.FetchAll(filter).ToArray(); } /// <summary> /// Selects all with supplied Source GUID /// </summary> /// <param name="componentGuid"></param> /// <returns></returns> public static async Task<IComponentTarget[]> SelectAllAsync(Guid componentGuid) { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); var filter = connector.CreateDataFilter(); filter.Add(x => x.Source, componentGuid); var result = await connector.FetchAllAsync(filter); return result.ToArray(); } /// <summary> /// Saves this instance /// </summary> /// <returns></returns> public virtual bool Save() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); try { connector.Save(this); return true; } catch (Exception ex) { throw ex; } } /// <summary> /// Saves this instance Async /// </summary> /// <returns></returns> public async virtual Task<bool> SaveAsync() { var connector = ConnectorFactory.CreateConnector<ComponentTarget>(); try { await connector.SaveAsync(this); return true; } catch (Exception ex) { throw ex; } } public bool IsNewInstance { get { return this.ID == 0; } } } }
32.893023
87
0.569287
[ "MIT" ]
Supershift/Sushi.Mediakiwi
src/Sushi.Mediakiwi.Data/Data/ComponentTarget.cs
7,074
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.DataBoxEdge.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// The storage account credential. /// </summary> [Rest.Serialization.JsonTransformation] public partial class StorageAccountCredential : ARMBaseModel { /// <summary> /// Initializes a new instance of the StorageAccountCredential class. /// </summary> public StorageAccountCredential() { CustomInit(); } /// <summary> /// Initializes a new instance of the StorageAccountCredential class. /// </summary> /// <param name="alias">Alias for the storage account.</param> /// <param name="sslStatus">Signifies whether SSL needs to be enabled /// or not. Possible values include: 'Enabled', 'Disabled'</param> /// <param name="accountType">Type of storage accessed on the storage /// account. Possible values include: 'GeneralPurposeStorage', /// 'BlobStorage'</param> /// <param name="id">The path ID that uniquely identifies the /// object.</param> /// <param name="name">The object name.</param> /// <param name="type">The hierarchical type of the object.</param> /// <param name="systemData">StorageAccountCredential object</param> /// <param name="userName">Username for the storage account.</param> /// <param name="accountKey">Encrypted storage key.</param> /// <param name="connectionString">Connection string for the storage /// account. Use this string if username and account key are not /// specified.</param> /// <param name="blobDomainName">Blob end point for private /// clouds.</param> /// <param name="storageAccountId">Id of the storage account.</param> public StorageAccountCredential(string alias, string sslStatus, string accountType, string id = default(string), string name = default(string), string type = default(string), SystemData systemData = default(SystemData), string userName = default(string), AsymmetricEncryptedSecret accountKey = default(AsymmetricEncryptedSecret), string connectionString = default(string), string blobDomainName = default(string), string storageAccountId = default(string)) : base(id, name, type) { SystemData = systemData; Alias = alias; UserName = userName; AccountKey = accountKey; ConnectionString = connectionString; SslStatus = sslStatus; BlobDomainName = blobDomainName; AccountType = accountType; StorageAccountId = storageAccountId; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets storageAccountCredential object /// </summary> [JsonProperty(PropertyName = "systemData")] public SystemData SystemData { get; set; } /// <summary> /// Gets or sets alias for the storage account. /// </summary> [JsonProperty(PropertyName = "properties.alias")] public string Alias { get; set; } /// <summary> /// Gets or sets username for the storage account. /// </summary> [JsonProperty(PropertyName = "properties.userName")] public string UserName { get; set; } /// <summary> /// Gets or sets encrypted storage key. /// </summary> [JsonProperty(PropertyName = "properties.accountKey")] public AsymmetricEncryptedSecret AccountKey { get; set; } /// <summary> /// Gets or sets connection string for the storage account. Use this /// string if username and account key are not specified. /// </summary> [JsonProperty(PropertyName = "properties.connectionString")] public string ConnectionString { get; set; } /// <summary> /// Gets or sets signifies whether SSL needs to be enabled or not. /// Possible values include: 'Enabled', 'Disabled' /// </summary> [JsonProperty(PropertyName = "properties.sslStatus")] public string SslStatus { get; set; } /// <summary> /// Gets or sets blob end point for private clouds. /// </summary> [JsonProperty(PropertyName = "properties.blobDomainName")] public string BlobDomainName { get; set; } /// <summary> /// Gets or sets type of storage accessed on the storage account. /// Possible values include: 'GeneralPurposeStorage', 'BlobStorage' /// </summary> [JsonProperty(PropertyName = "properties.accountType")] public string AccountType { get; set; } /// <summary> /// Gets or sets id of the storage account. /// </summary> [JsonProperty(PropertyName = "properties.storageAccountId")] public string StorageAccountId { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Alias == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Alias"); } if (SslStatus == null) { throw new ValidationException(ValidationRules.CannotBeNull, "SslStatus"); } if (AccountType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "AccountType"); } if (AccountKey != null) { AccountKey.Validate(); } } } }
40.189873
464
0.607874
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/databoxedge/Microsoft.Azure.Management.DataBoxEdge/src/Generated/Models/StorageAccountCredential.cs
6,350
C#
using System; using Mono.Cecil; using Mono.Cecil.Rocks; namespace DemonWeaver.Extensions { public static class MethodReferenceExtensions { public static MethodReference MakeGeneric(this MethodReference self, params TypeReference[] arguments) { var reference = new MethodReference(self.Name, self.ReturnType) { DeclaringType = self.DeclaringType.MakeGenericInstanceType(arguments), HasThis = self.HasThis, ExplicitThis = self.ExplicitThis, CallingConvention = self.CallingConvention, }; foreach (var parameter in self.Parameters) reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); foreach (var genericParameter in self.GenericParameters) reference.GenericParameters.Add(new GenericParameter(genericParameter.Name, reference)); return reference; } public static MethodReference MakeGenericMethod(this MethodReference self, params TypeReference[] arguments) { if (self.GenericParameters.Count != arguments.Length) throw new ArgumentException(); var instance = new GenericInstanceMethod(self); foreach (var argument in arguments) instance.GenericArguments.Add(argument); return instance; } } }
35.925
116
0.643702
[ "MIT" ]
GeorgePetri/Demon
DemonWeaver/Extensions/MethodReferenceExtensions.cs
1,437
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Linq; using System.Security.Claims; using Profile4d.Data; using Profile4d.Domain; namespace Profile4d.Web.Api.Controllers { [ApiController] [Route("[controller]")] [Authorize] public class ArchetypeDiscoverController : ControllerBase { private readonly ILogger<ArchetypeDiscoverController> _logger; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ArchetypeDiscover _questions; private string _user; public ArchetypeDiscoverController( ILogger<ArchetypeDiscoverController> logger, IHttpContextAccessor httpContextAccessor, ArchetypeDiscover MyArchetypeDiscover ) { _logger = logger; _questions = MyArchetypeDiscover; _httpContextAccessor = httpContextAccessor; ClaimsPrincipal currentUser = this.User; _user = (from c in _httpContextAccessor.HttpContext.User.Claims where c.Type == "UserID" select c.Value).FirstOrDefault() ; } [Authorize(Roles = "Admin")] [HttpGet("")] public ActionResult<Question.List> List() { try { return _questions.List(); } catch (System.Exception ex) { Question.List _return = new Question.List(); _return.Success = false; _return.Message = ex.Message; return _return; } } [Authorize(Roles = "Admin")] [HttpPost("ChangeActive")] public ActionResult<BasicReturn> ChangeActive(Question data) { BasicReturn _return = new BasicReturn(); Question _question = new Question( data.Guid, _user, data.Active ); try { _return = _questions.ChangeActive(_question); return _return; } catch (System.Exception ex) { _return.Success = false; _return.Message = ex.Message; return _return; } } [Authorize(Roles = "Admin")] [HttpPost("Add")] public ActionResult<BasicReturn> Add(Question data) { BasicReturn _return = new BasicReturn(); try { data.CreatedBy = _user; _return = _questions.Add(data); return _return; } catch (System.Exception ex) { _return.Success = false; _return.Message = ex.Message; _return.Details = ex.StackTrace; return _return; } } [Authorize(Roles = "Admin")] [HttpGet("Question/{id}")] public ActionResult<Question> Question(string id) { Question _return = new Question(); try { _return = _questions.Question(id); return _return; } catch (System.Exception ex) { _return.Success = false; _return.Message = ex.Message; return _return; } } [Authorize(Roles = "Admin")] [HttpPost("Edit")] public ActionResult<BasicReturn> Edit(Question data) { BasicReturn _return = new BasicReturn(); try { data.CreatedBy = _user; _return = _questions.Edit(data); return _return; } catch (System.Exception ex) { _return.Success = false; _return.Message = ex.Message; _return.Details = ex.StackTrace; return _return; } } } }
23.731034
69
0.614647
[ "MIT" ]
RicardoGaefke/profile4d
src/Web.Api/Controllers/DynamicContent/ArchetypeDiscover.cs
3,441
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace RTSEngine.RTSEngine { public class Time { public static float time; public Time() { } //Wait fucntion public static void wait(float x) { DateTime t = DateTime.Now; DateTime tf = DateTime.Now.AddSeconds(x); while (t < tf) { t = DateTime.Now; } } } }
17.333333
53
0.520979
[ "MIT" ]
RTSProductions/RTSEngine
RTSEngine/RTSEngine/Time.cs
574
C#
#if !NOJSONNET using NBitcoin.DataEncoders; using NBitcoin.Protocol; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NBitcoin.RPC { /* Category Name Implemented ------------------ --------------------------- ----------------------- ------------------ Overall control/query calls control getinfo control help control stop ------------------ P2P networking network getnetworkinfo network addnode Yes network disconnectnode network getaddednodeinfo Yes network getconnectioncount network getnettotals network getpeerinfo Yes network ping network setban network listbanned network clearbanned ------------------ Block chain and UTXO blockchain getblockchaininfo Yes blockchain getbestblockhash Yes blockchain getblockcount Yes blockchain getblock Yes blockchain getblockhash Yes blockchain getchaintips blockchain getdifficulty blockchain getmempoolinfo blockchain getrawmempool Yes blockchain gettxout Yes blockchain gettxoutproof blockchain verifytxoutproof blockchain gettxoutsetinfo blockchain verifychain ------------------ Mining mining getblocktemplate mining getmininginfo mining getnetworkhashps mining prioritisetransaction mining submitblock ------------------ Coin generation generating getgenerate generating setgenerate generating generate ------------------ Raw transactions rawtransactions createrawtransaction rawtransactions decoderawtransaction rawtransactions decodescript rawtransactions getrawtransaction rawtransactions sendrawtransaction rawtransactions signrawtransaction rawtransactions fundrawtransaction ------------------ Utility functions util createmultisig util validateaddress util verifymessage util estimatefee Yes util estimatesmartfee Yes ------------------ Not shown in help hidden invalidateblock Yes hidden reconsiderblock hidden setmocktime hidden resendwallettransactions ------------------ Wallet wallet addmultisigaddress wallet backupwallet Yes wallet dumpprivkey Yes wallet dumpwallet wallet encryptwallet wallet getaccountaddress Yes wallet getaccount wallet getaddressesbyaccount wallet getbalance wallet getnewaddress wallet getrawchangeaddress wallet getreceivedbyaccount wallet getreceivedbyaddress wallet gettransaction wallet getunconfirmedbalance wallet getwalletinfo wallet importprivkey Yes wallet importwallet wallet importaddress Yes wallet keypoolrefill wallet listaccounts Yes wallet listaddressgroupings Yes wallet listlockunspent wallet listreceivedbyaccount wallet listreceivedbyaddress wallet listsinceblock wallet listtransactions wallet listunspent Yes wallet lockunspent Yes wallet move wallet sendfrom wallet sendmany wallet sendtoaddress wallet setaccount wallet settxfee wallet signmessage wallet walletlock wallet walletpassphrasechange wallet walletpassphrase yes */ public partial class RPCClient : IBlockRepository { private string _Authentication; private readonly Uri _address; public Uri Address { get { return _address; } } RPCCredentialString _CredentialString; public RPCCredentialString CredentialString { get { return _CredentialString; } } private readonly Network _network; public Network Network { get { return _network; } } /// <summary> /// Use default bitcoin parameters to configure a RPCClient. /// </summary> /// <param name="network">The network used by the node. Must not be null.</param> public RPCClient(Network network) : this(null as string, BuildUri(null, null, network.RPCPort), network) { } [Obsolete("Use RPCClient(ConnectionString, string, Network)")] public RPCClient(NetworkCredential credentials, string host, Network network) : this(credentials, BuildUri(host, null, network.RPCPort), network) { } public RPCClient(RPCCredentialString credentials, Network network) : this(credentials, null as String, network) { } public RPCClient(RPCCredentialString credentials, string host, Network network) : this(credentials, BuildUri(host, credentials.ToString(), network.RPCPort), network) { } public RPCClient(RPCCredentialString credentials, Uri address, Network network) { credentials = credentials ?? new RPCCredentialString(); if(address != null && network == null) { network = Network.GetNetworks().FirstOrDefault(n => n.RPCPort == address.Port); if(network == null) throw new ArgumentNullException(nameof(network)); } if(credentials.UseDefault && network == null) throw new ArgumentException("network parameter is required if you use default credentials"); if(address == null && network == null) throw new ArgumentException("network parameter is required if you use default uri"); if(address == null) address = new Uri("http://127.0.0.1:" + network.RPCPort + "/"); if(credentials.UseDefault) { //will throw impossible to get the cookie path GetDefaultCookieFilePath(network); } _CredentialString = credentials; _address = address; _network = network; if(credentials.UserPassword != null) { _Authentication = $"{credentials.UserPassword.UserName}:{credentials.UserPassword.Password}"; } if(_Authentication == null) { TryRenewCookie(null); } } static ConcurrentDictionary<Network, string> _DefaultPaths = new ConcurrentDictionary<Network, string>(); static RPCClient() { #if !NOFILEIO var home = Environment.GetEnvironmentVariable("HOME"); var localAppData = Environment.GetEnvironmentVariable("APPDATA"); if(string.IsNullOrEmpty(home) && string.IsNullOrEmpty(localAppData)) return; if(!string.IsNullOrEmpty(home)) { var bitcoinFolder = Path.Combine(home, ".bitcoin"); var mainnet = Path.Combine(bitcoinFolder, ".cookie"); RegisterDefaultCookiePath(Network.Main, mainnet); var testnet = Path.Combine(bitcoinFolder, "testnet3", ".cookie"); RegisterDefaultCookiePath(Network.TestNet, testnet); var regtest = Path.Combine(bitcoinFolder, "regtest", ".cookie"); RegisterDefaultCookiePath(Network.RegTest, regtest); } else if(!string.IsNullOrEmpty(localAppData)) { var bitcoinFolder = Path.Combine(localAppData, "Bitcoin"); var mainnet = Path.Combine(bitcoinFolder, ".cookie"); RegisterDefaultCookiePath(Network.Main, mainnet); var testnet = Path.Combine(bitcoinFolder, "testnet3", ".cookie"); RegisterDefaultCookiePath(Network.TestNet, testnet); var regtest = Path.Combine(bitcoinFolder, "regtest", ".cookie"); RegisterDefaultCookiePath(Network.RegTest, regtest); } #endif } public static void RegisterDefaultCookiePath(Network network, string path) { _DefaultPaths.TryAdd(network, path); } private string GetCookiePath() { if(CredentialString.UseDefault && Network == null) throw new InvalidOperationException("NBitcoin bug, report to the developers"); if(CredentialString.UseDefault) return GetDefaultCookieFilePath(Network); if(CredentialString.CookieFile != null) return CredentialString.CookieFile; return null; } public static string GetDefaultCookieFilePath(Network network) { string path = null; if(!_DefaultPaths.TryGetValue(network, out path)) throw new ArgumentException("This network has no default cookie file path registered, use RPCClient.RegisterDefaultCookiePath to register", "network"); return path; } public static string TryGetDefaultCookieFilePath(Network network) { string path = null; if(!_DefaultPaths.TryGetValue(network, out path)) return null; return path; } /// <summary> /// Create a new RPCClient instance /// </summary> /// <param name="authenticationString">username:password, the content of the .cookie file, or cookiefile=pathToCookieFile</param> /// <param name="hostOrUri"></param> /// <param name="network"></param> public RPCClient(string authenticationString, string hostOrUri, Network network) : this(authenticationString, BuildUri(hostOrUri, authenticationString, network.RPCPort), network) { } private static Uri BuildUri(string hostOrUri, string connectionString, int port) { RPCCredentialString connString; if(connectionString != null && RPCCredentialString.TryParse(connectionString, out connString)) { if(connString.Server != null) hostOrUri = connString.Server; } if(hostOrUri != null) { hostOrUri = hostOrUri.Trim(); try { if(hostOrUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || hostOrUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) return new Uri(hostOrUri, UriKind.Absolute); } catch { } } hostOrUri = hostOrUri ?? "127.0.0.1"; var indexOfPort = hostOrUri.IndexOf(":"); if(indexOfPort != -1) { port = int.Parse(hostOrUri.Substring(indexOfPort + 1)); hostOrUri = hostOrUri.Substring(0, indexOfPort); } UriBuilder builder = new UriBuilder(); builder.Host = hostOrUri; builder.Scheme = "http"; builder.Port = port; return builder.Uri; } public RPCClient(NetworkCredential credentials, Uri address, Network network = null) : this(credentials == null ? null : (credentials.UserName + ":" + credentials.Password), address, network) { } /// <summary> /// Create a new RPCClient instance /// </summary> /// <param name="authenticationString">username:password or the content of the .cookie file or null to auto configure</param> /// <param name="address"></param> /// <param name="network"></param> public RPCClient(string authenticationString, Uri address, Network network = null) : this(authenticationString == null ? null as RPCCredentialString : RPCCredentialString.Parse(authenticationString), address, network) { } public string Authentication { get { return _Authentication; } } ConcurrentQueue<Tuple<RPCRequest, TaskCompletionSource<RPCResponse>>> _BatchedRequests; public RPCClient PrepareBatch() { return new RPCClient(CredentialString, Address, Network) { _BatchedRequests = new ConcurrentQueue<Tuple<RPCRequest, TaskCompletionSource<RPCResponse>>>() }; } public RPCResponse SendCommand(RPCOperations commandName, params object[] parameters) { return SendCommand(commandName.ToString(), parameters); } public BitcoinAddress GetNewAddress() { return BitcoinAddress.Create(SendCommand(RPCOperations.getnewaddress).Result.ToString(), Network); } public async Task<BitcoinAddress> GetNewAddressAsync() { var result = await SendCommandAsync(RPCOperations.getnewaddress).ConfigureAwait(false); return BitcoinAddress.Create(result.Result.ToString(), Network); } public BitcoinAddress GetRawChangeAddress() { return GetRawChangeAddressAsync().GetAwaiter().GetResult(); } public async Task<BitcoinAddress> GetRawChangeAddressAsync() { var result = await SendCommandAsync(RPCOperations.getrawchangeaddress).ConfigureAwait(false); return BitcoinAddress.Create(result.Result.ToString(), Network); } public Task<RPCResponse> SendCommandAsync(RPCOperations commandName, params object[] parameters) { return SendCommandAsync(commandName.ToString(), parameters); } /// <summary> /// Send a command /// </summary> /// <param name="commandName">https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list</param> /// <param name="parameters"></param> /// <returns></returns> public RPCResponse SendCommand(string commandName, params object[] parameters) { return SendCommand(new RPCRequest(commandName, parameters)); } public Task<RPCResponse> SendCommandAsync(string commandName, params object[] parameters) { return SendCommandAsync(new RPCRequest(commandName, parameters)); } public RPCResponse SendCommand(RPCRequest request, bool throwIfRPCError = true) { return SendCommandAsync(request, throwIfRPCError).GetAwaiter().GetResult(); } /// <summary> /// Send all commands in one batch /// </summary> public void SendBatch() { SendBatchAsync().GetAwaiter().GetResult(); } /// <summary> /// Cancel all commands /// </summary> public void CancelBatch() { var batches = _BatchedRequests; if(batches == null) throw new InvalidOperationException("This RPCClient instance is not a batch, use PrepareBatch"); _BatchedRequests = null; Tuple<RPCRequest, TaskCompletionSource<RPCResponse>> req; while(batches.TryDequeue(out req)) { req.Item2.TrySetCanceled(); } } /// <summary> /// Send all commands in one batch /// </summary> public async Task SendBatchAsync() { Tuple<RPCRequest, TaskCompletionSource<RPCResponse>> req; List<Tuple<RPCRequest, TaskCompletionSource<RPCResponse>>> requests = new List<Tuple<RPCRequest, TaskCompletionSource<RPCResponse>>>(); var batches = _BatchedRequests; if(batches == null) throw new InvalidOperationException("This RPCClient instance is not a batch, use PrepareBatch"); _BatchedRequests = null; while(batches.TryDequeue(out req)) { requests.Add(req); } if(requests.Count == 0) return; try { await SendBatchAsyncCore(requests).ConfigureAwait(false); } catch(WebException ex) { if(!IsUnauthorized(ex)) throw; if(GetCookiePath() == null) throw; TryRenewCookie(ex); await SendBatchAsyncCore(requests).ConfigureAwait(false); } } private async Task SendBatchAsyncCore(List<Tuple<RPCRequest, TaskCompletionSource<RPCResponse>>> requests) { var writer = new StringWriter(); writer.Write("["); bool first = true; foreach(var item in requests) { if(!first) { writer.Write(","); } first = false; item.Item1.WriteJSON(writer); } writer.Write("]"); writer.Flush(); var json = writer.ToString(); var bytes = Encoding.UTF8.GetBytes(json); var webRequest = CreateWebRequest(); #if !(PORTABLE || NETCORE) webRequest.ContentLength = bytes.Length; #endif int responseIndex = 0; var dataStream = await webRequest.GetRequestStreamAsync().ConfigureAwait(false); await dataStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); await dataStream.FlushAsync().ConfigureAwait(false); dataStream.Dispose(); JArray response; WebResponse webResponse = null; WebResponse errorResponse = null; try { webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false); response = JArray.Load(new JsonTextReader( new StreamReader( await ToMemoryStreamAsync(webResponse.GetResponseStream()).ConfigureAwait(false), Encoding.UTF8))); foreach(var jobj in response.OfType<JObject>()) { try { RPCResponse rpcResponse = new RPCResponse(jobj); requests[responseIndex].Item2.TrySetResult(rpcResponse); } catch(Exception ex) { requests[responseIndex].Item2.TrySetException(ex); } responseIndex++; } } catch(WebException ex) { if(IsUnauthorized(ex)) throw; if(ex.Response == null || ex.Response.ContentLength == 0 || !ex.Response.ContentType.Equals("application/json", StringComparison.Ordinal)) { foreach(var item in requests) { item.Item2.TrySetException(ex); } } else { errorResponse = ex.Response; try { RPCResponse rpcResponse = RPCResponse.Load(await ToMemoryStreamAsync(errorResponse.GetResponseStream()).ConfigureAwait(false)); foreach(var item in requests) { item.Item2.TrySetResult(rpcResponse); } } catch(Exception) { foreach(var item in requests) { item.Item2.TrySetException(ex); } } } } catch(Exception ex) { foreach(var item in requests) { item.Item2.TrySetException(ex); } } finally { if(errorResponse != null) { errorResponse.Dispose(); errorResponse = null; } if(webResponse != null) { webResponse.Dispose(); webResponse = null; } } } private static bool IsUnauthorized(WebException ex) { var httpResp = ex.Response as HttpWebResponse; var isUnauthorized = httpResp != null && httpResp.StatusCode == HttpStatusCode.Unauthorized; return isUnauthorized; } public async Task<RPCResponse> SendCommandAsync(RPCRequest request, bool throwIfRPCError = true) { try { return await SendCommandAsyncCore(request, throwIfRPCError).ConfigureAwait(false); } catch(WebException ex) { if(!IsUnauthorized(ex)) throw; if(GetCookiePath() == null) throw; TryRenewCookie(ex); return await SendCommandAsyncCore(request, throwIfRPCError).ConfigureAwait(false); } } private void TryRenewCookie(WebException ex) { if(GetCookiePath() == null) throw new InvalidOperationException("Bug in NBitcoin notify the developers"); #if !NOFILEIO try { _Authentication = File.ReadAllText(GetCookiePath()); } //We are only interested into the previous exception catch { if(ex == null) return; ExceptionDispatchInfo.Capture(ex).Throw(); } #else throw new NotSupportedException("Cookie authentication is not supported for this plateform"); #endif } async Task<RPCResponse> SendCommandAsyncCore(RPCRequest request, bool throwIfRPCError) { RPCResponse response = null; var batches = _BatchedRequests; if(batches != null) { TaskCompletionSource<RPCResponse> source = new TaskCompletionSource<RPCResponse>(); batches.Enqueue(Tuple.Create(request, source)); response = await source.Task.ConfigureAwait(false); } HttpWebRequest webRequest = response == null ? CreateWebRequest() : null; if(response == null) { var writer = new StringWriter(); request.WriteJSON(writer); writer.Flush(); var json = writer.ToString(); var bytes = Encoding.UTF8.GetBytes(json); #if !(PORTABLE || NETCORE) webRequest.ContentLength = bytes.Length; #endif var dataStream = await webRequest.GetRequestStreamAsync().ConfigureAwait(false); await dataStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); await dataStream.FlushAsync().ConfigureAwait(false); dataStream.Dispose(); } WebResponse webResponse = null; WebResponse errorResponse = null; try { webResponse = response == null ? await webRequest.GetResponseAsync().ConfigureAwait(false) : null; response = response ?? RPCResponse.Load(await ToMemoryStreamAsync(webResponse.GetResponseStream()).ConfigureAwait(false)); if(throwIfRPCError) response.ThrowIfError(); } catch(WebException ex) { if(ex.Response == null || ex.Response.ContentLength == 0 || !ex.Response.ContentType.Equals("application/json", StringComparison.Ordinal)) throw; errorResponse = ex.Response; response = RPCResponse.Load(await ToMemoryStreamAsync(errorResponse.GetResponseStream()).ConfigureAwait(false)); if(throwIfRPCError) response.ThrowIfError(); } finally { if(errorResponse != null) { errorResponse.Dispose(); errorResponse = null; } if(webResponse != null) { webResponse.Dispose(); webResponse = null; } } return response; } private HttpWebRequest CreateWebRequest() { var address = Address.AbsoluteUri; if(!string.IsNullOrEmpty(CredentialString.WalletName)) { if(!address.EndsWith("/")) address = address + "/"; address += "wallet/" + CredentialString.WalletName; } var webRequest = (HttpWebRequest)WebRequest.Create(address); webRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + Encoders.Base64.EncodeData(Encoders.ASCII.DecodeData(_Authentication)); webRequest.ContentType = "application/json-rpc"; webRequest.Method = "POST"; return webRequest; } private async Task<Stream> ToMemoryStreamAsync(Stream stream) { MemoryStream ms = new MemoryStream(); await stream.CopyToAsync(ms).ConfigureAwait(false); ms.Position = 0; return ms; } #region P2P Networking #if !NOSOCKET public PeerInfo[] GetPeersInfo() { PeerInfo[] peers = null; peers = GetPeersInfoAsync().GetAwaiter().GetResult(); return peers; } public async Task<PeerInfo[]> GetPeersInfoAsync() { var resp = await SendCommandAsync(RPCOperations.getpeerinfo).ConfigureAwait(false); var peers = resp.Result as JArray; var result = new PeerInfo[peers.Count]; var i = 0; foreach(var peer in peers) { var localAddr = (string)peer["addrlocal"]; var pingWait = peer["pingwait"] != null ? (double)peer["pingwait"] : 0; localAddr = string.IsNullOrEmpty(localAddr) ? "127.0.0.1:8333" : localAddr; ulong services; if(!ulong.TryParse((string)peer["services"], out services)) { services = Utils.ToUInt64(Encoders.Hex.DecodeData((string)peer["services"]), false); } result[i++] = new PeerInfo { Id = (int)peer["id"], Address = Utils.ParseIpEndpoint((string)peer["addr"], this.Network.DefaultPort), LocalAddress = Utils.ParseIpEndpoint(localAddr, this.Network.DefaultPort), Services = (NodeServices)services, LastSend = Utils.UnixTimeToDateTime((uint)peer["lastsend"]), LastReceive = Utils.UnixTimeToDateTime((uint)peer["lastrecv"]), BytesSent = (long)peer["bytessent"], BytesReceived = (long)peer["bytesrecv"], ConnectionTime = Utils.UnixTimeToDateTime((uint)peer["conntime"]), TimeOffset = TimeSpan.FromSeconds(Math.Min((long)int.MaxValue, (long)peer["timeoffset"])), PingTime = peer["pingtime"] == null ? (TimeSpan?)null : TimeSpan.FromSeconds((double)peer["pingtime"]), PingWait = TimeSpan.FromSeconds(pingWait), Blocks = peer["blocks"] != null ? (int)peer["blocks"] : -1, Version = (int)peer["version"], SubVersion = (string)peer["subver"], Inbound = (bool)peer["inbound"], StartingHeight = (int)peer["startingheight"], SynchronizedBlocks = (int)peer["synced_blocks"], SynchronizedHeaders = (int)peer["synced_headers"], IsWhiteListed = (bool)peer["whitelisted"], BanScore = peer["banscore"] == null ? 0 : (int)peer["banscore"], Inflight = peer["inflight"].Select(x => uint.Parse((string)x)).ToArray() }; } return result; } public void AddNode(EndPoint nodeEndPoint, bool onetry = false) { if(nodeEndPoint == null) throw new ArgumentNullException(nameof(nodeEndPoint)); SendCommand("addnode", nodeEndPoint.ToString(), onetry ? "onetry" : "add"); } public async Task AddNodeAsync(EndPoint nodeEndPoint, bool onetry = false) { if(nodeEndPoint == null) throw new ArgumentNullException(nameof(nodeEndPoint)); await SendCommandAsync(RPCOperations.addnode, nodeEndPoint.ToString(), onetry ? "onetry" : "add").ConfigureAwait(false); } public void RemoveNode(EndPoint nodeEndPoint) { if(nodeEndPoint == null) throw new ArgumentNullException(nameof(nodeEndPoint)); SendCommandAsync(RPCOperations.addnode, nodeEndPoint.ToString(), "remove"); } public async Task RemoveNodeAsync(EndPoint nodeEndPoint) { if(nodeEndPoint == null) throw new ArgumentNullException(nameof(nodeEndPoint)); await SendCommandAsync(RPCOperations.addnode, nodeEndPoint.ToString(), "remove").ConfigureAwait(false); } public async Task<AddedNodeInfo[]> GetAddedNodeInfoAsync(bool detailed) { var result = await SendCommandAsync(RPCOperations.getaddednodeinfo, detailed).ConfigureAwait(false); var obj = result.Result; return obj.Select(entry => new AddedNodeInfo { AddedNode = Utils.ParseIpEndpoint((string)entry["addednode"], 8333), Connected = (bool)entry["connected"], Addresses = entry["addresses"].Select(x => new NodeAddressInfo { Address = Utils.ParseIpEndpoint((string)x["address"], 8333), Connected = (bool)x["connected"] }) }).ToArray(); } public AddedNodeInfo[] GetAddedNodeInfo(bool detailed) { AddedNodeInfo[] addedNodesInfo = null; addedNodesInfo = GetAddedNodeInfoAsync(detailed).GetAwaiter().GetResult(); return addedNodesInfo; } public AddedNodeInfo GetAddedNodeInfo(bool detailed, EndPoint nodeEndPoint) { AddedNodeInfo addedNodeInfo = null; addedNodeInfo = GetAddedNodeInfoAync(detailed, nodeEndPoint).GetAwaiter().GetResult(); return addedNodeInfo; } public async Task<AddedNodeInfo> GetAddedNodeInfoAync(bool detailed, EndPoint nodeEndPoint) { if(nodeEndPoint == null) throw new ArgumentNullException(nameof(nodeEndPoint)); try { var result = await SendCommandAsync(RPCOperations.getaddednodeinfo, detailed, nodeEndPoint.ToString()).ConfigureAwait(false); var e = result.Result; return e.Select(entry => new AddedNodeInfo { AddedNode = Utils.ParseIpEndpoint((string)entry["addednode"], 8333), Connected = (bool)entry["connected"], Addresses = entry["addresses"].Select(x => new NodeAddressInfo { Address = Utils.ParseIpEndpoint((string)x["address"], 8333), Connected = (bool)x["connected"] }) }).FirstOrDefault(); } catch(RPCException ex) { if(ex.RPCCode == RPCErrorCode.RPC_CLIENT_NODE_NOT_ADDED) return null; throw; } } #endif #endregion #region Block chain and UTXO public async Task<BlockchainInfo> GetBlockchainInfoAsync() { var response = await SendCommandAsync(RPCOperations.getblockchaininfo).ConfigureAwait(false); var result = response.Result; var epochToDtateTimeOffset = new Func<long, DateTimeOffset>(epoch=>{ try{ return Utils.UnixTimeToDateTime(epoch); }catch(OverflowException){ return DateTimeOffset.MaxValue; } }); var blockchainInfo = new BlockchainInfo { Chain = Network.GetNetwork(result.Value<string>("chain")), Blocks = result.Value<ulong>("blocks"), Headers = result.Value<ulong>("headers"), BestBlockHash = new uint256(result.Value<string>("bestblockhash")), // the block hash Difficulty = result.Value<ulong>("difficulty"), MedianTime = result.Value<ulong>("mediantime"), VerificationProgress = result.Value<float>("verificationprogress"), InitialBlockDownload = result.Value<bool>("initialblockdownload"), ChainWork = new uint256(result.Value<string>("chainwork")), SizeOnDisk = result.Value<ulong>("size_on_disk"), Pruned = result.Value<bool>("pruned"), SoftForks = result["softforks"].Select(x=> new BlockchainInfo.SoftFork { Bip = (string)(x["id"]), Version = (int)(x["version"]), RejectStatus = bool.Parse((string)(x["reject"]["status"])) }).ToList(), Bip9SoftForks = result["bip9_softforks"].Select(x=> { var o = x.First(); return new BlockchainInfo.Bip9SoftFork { Name = ((JProperty)x).Name, Status = (string)o["status"], StartTime = epochToDtateTimeOffset((long)o["startTime"]), Timeout = epochToDtateTimeOffset((long)o["timeout"]), SinceHeight = (ulong)o["since"], }; }).ToList() }; return blockchainInfo; } public uint256 GetBestBlockHash() { return uint256.Parse((string)SendCommand(RPCOperations.getbestblockhash).Result); } public async Task<uint256> GetBestBlockHashAsync() { return uint256.Parse((string)(await SendCommandAsync(RPCOperations.getbestblockhash).ConfigureAwait(false)).Result); } public BlockHeader GetBlockHeader(int height) { var hash = GetBlockHash(height); return GetBlockHeader(hash); } public async Task<BlockHeader> GetBlockHeaderAsync(int height) { var hash = await GetBlockHashAsync(height).ConfigureAwait(false); return await GetBlockHeaderAsync(hash).ConfigureAwait(false); } /// <summary> /// Get the a whole block /// </summary> /// <param name="blockId"></param> /// <returns></returns> public async Task<Block> GetBlockAsync(uint256 blockId) { var resp = await SendCommandAsync(RPCOperations.getblock, blockId, false).ConfigureAwait(false); return Block.Parse(resp.Result.ToString(), Network); } /// <summary> /// Get the a whole block /// </summary> /// <param name="blockId"></param> /// <returns></returns> public Block GetBlock(uint256 blockId) { return GetBlockAsync(blockId).GetAwaiter().GetResult(); } public Block GetBlock(int height) { return GetBlockAsync(height).GetAwaiter().GetResult(); } public async Task<Block> GetBlockAsync(int height) { var hash = await GetBlockHashAsync(height).ConfigureAwait(false); return await GetBlockAsync(hash).ConfigureAwait(false); } public BlockHeader GetBlockHeader(uint256 blockHash) { var resp = SendCommand("getblockheader", blockHash); return ParseBlockHeader(resp); } public async Task<BlockHeader> GetBlockHeaderAsync(uint256 blockHash) { var resp = await SendCommandAsync("getblockheader", blockHash).ConfigureAwait(false); return ParseBlockHeader(resp); } private BlockHeader ParseBlockHeader(RPCResponse resp) { var header = Network.Consensus.ConsensusFactory.CreateBlockHeader(); header.Version = (int)resp.Result["version"]; header.Nonce = (uint)resp.Result["nonce"]; header.Bits = new Target(Encoders.Hex.DecodeData((string)resp.Result["bits"])); if(resp.Result["previousblockhash"] != null) { header.HashPrevBlock = uint256.Parse((string)resp.Result["previousblockhash"]); } if(resp.Result["time"] != null) { header.BlockTime = Utils.UnixTimeToDateTime((uint)resp.Result["time"]); } if(resp.Result["merkleroot"] != null) { header.HashMerkleRoot = uint256.Parse((string)resp.Result["merkleroot"]); } return header; } public uint256 GetBlockHash(int height) { var resp = SendCommand(RPCOperations.getblockhash, height); return uint256.Parse(resp.Result.ToString()); } public async Task<uint256> GetBlockHashAsync(int height) { var resp = await SendCommandAsync(RPCOperations.getblockhash, height).ConfigureAwait(false); return uint256.Parse(resp.Result.ToString()); } public int GetBlockCount() { return (int)SendCommand(RPCOperations.getblockcount).Result; } public async Task<int> GetBlockCountAsync() { return (int)(await SendCommandAsync(RPCOperations.getblockcount).ConfigureAwait(false)).Result; } public uint256[] GetRawMempool() { var result = SendCommand(RPCOperations.getrawmempool); var array = (JArray)result.Result; return array.Select(o => (string)o).Select(uint256.Parse).ToArray(); } public async Task<uint256[]> GetRawMempoolAsync() { var result = await SendCommandAsync(RPCOperations.getrawmempool).ConfigureAwait(false); var array = (JArray)result.Result; return array.Select(o => (string)o).Select(uint256.Parse).ToArray(); } /// <summary> /// Returns details about an unspent transaction output. /// </summary> /// <param name="txid">The transaction id</param> /// <param name="index">vout number</param> /// <param name="includeMempool">Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear.</param> /// <returns>null if spent or never existed</returns> public GetTxOutResponse GetTxOut(uint256 txid, int index, bool includeMempool = true) { return GetTxOutAsync(txid, index, includeMempool).GetAwaiter().GetResult(); } /// <summary> /// Returns details about an unspent transaction output. /// </summary> /// <param name="txid">The transaction id</param> /// <param name="index">vout number</param> /// <param name="includeMempool">Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear.</param> /// <returns>null if spent or never existed</returns> public async Task<GetTxOutResponse> GetTxOutAsync(uint256 txid, int index, bool includeMempool = true) { var response = await SendCommandAsync(RPCOperations.gettxout, txid, index, includeMempool).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(response?.ResultString)) { return null; } var result = response.Result; var value = result.Value<decimal>("value"); // The transaction value in BTC var txOut = new TxOut(Money.Coins(value), new Script(result["scriptPubKey"].Value<string>("asm"))); return new GetTxOutResponse { BestBlock = new uint256(result.Value<string>("bestblock")), // the block hash Confirmations = result.Value<int>("confirmations"), // The number of confirmations IsCoinBase = result.Value<bool>("coinbase"), // Coinbase or not ScriptPubKeyType = result["scriptPubKey"].Value<string>("type"), // The type, eg pubkeyhash TxOut = txOut }; } /// <summary> /// GetTransactions only returns on txn which are not entirely spent unless you run bitcoinq with txindex=1. /// </summary> /// <param name="blockHash"></param> /// <returns></returns> public IEnumerable<Transaction> GetTransactions(uint256 blockHash) { if(blockHash == null) throw new ArgumentNullException(nameof(blockHash)); var resp = SendCommand(RPCOperations.getblock, blockHash); var tx = resp.Result["tx"] as JArray; if(tx != null) { foreach(var item in tx) { var result = GetRawTransaction(uint256.Parse(item.ToString()), false); if(result != null) yield return result; } } } public IEnumerable<Transaction> GetTransactions(int height) { return GetTransactions(GetBlockHash(height)); } #endregion #region Coin generation #endregion #region Raw Transaction public Transaction DecodeRawTransaction(string rawHex) { var response = SendCommand(RPCOperations.decoderawtransaction, rawHex); return Transaction.Parse(response.Result.ToString(), RawFormat.Satoshi); } public Transaction DecodeRawTransaction(byte[] raw) { return DecodeRawTransaction(Encoders.Hex.EncodeData(raw)); } public async Task<Transaction> DecodeRawTransactionAsync(string rawHex) { var response = await SendCommandAsync(RPCOperations.decoderawtransaction, rawHex).ConfigureAwait(false); return Transaction.Parse(response.Result.ToString(), RawFormat.Satoshi); } public Task<Transaction> DecodeRawTransactionAsync(byte[] raw) { return DecodeRawTransactionAsync(Encoders.Hex.EncodeData(raw)); } /// <summary> /// getrawtransaction only returns on txn which are not entirely spent unless you run bitcoinq with txindex=1. /// </summary> /// <param name="txid"></param> /// <returns></returns> public Transaction GetRawTransaction(uint256 txid, bool throwIfNotFound = true) { return GetRawTransactionAsync(txid, throwIfNotFound).GetAwaiter().GetResult(); } public async Task<Transaction> GetRawTransactionAsync(uint256 txid, bool throwIfNotFound = true) { var response = await SendCommandAsync(new RPCRequest(RPCOperations.getrawtransaction, new[] { txid }), throwIfNotFound).ConfigureAwait(false); if(throwIfNotFound) response.ThrowIfError(); if(response.Error != null && response.Error.Code == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY) return null; response.ThrowIfError(); var tx = new Transaction(); tx.ReadWrite(Encoders.Hex.DecodeData(response.Result.ToString())); return tx; } public RawTransactionInfo GetRawTransactionInfo(uint256 txid) { return GetRawTransactionInfoAsync(txid).GetAwaiter().GetResult(); } public async Task<RawTransactionInfo> GetRawTransactionInfoAsync(uint256 txId) { var request = new RPCRequest(RPCOperations.getrawtransaction, new object[]{ txId, true }); var response = await SendCommandAsync(request); var json = response.Result; return new RawTransactionInfo{ Transaction = Transaction.Parse(json.Value<string>("hex")), TransactionId = uint256.Parse(json.Value<string>("txid")), TransactionTime = json["time"] != null ? NBitcoin.Utils.UnixTimeToDateTime(json.Value<long>("time")): (DateTimeOffset?)null, Hash = uint256.Parse(json.Value<string>("hash")), Size = json.Value<uint>("size"), VirtualSize = json.Value<uint>("vsize"), Version = json.Value<uint>("version"), LockTime = new LockTime(json.Value<uint>("locktime")), BlockHash = json["blockhash"] != null ? uint256.Parse(json.Value<string>("blockhash")): null, Confirmations = json.Value<uint>("confirmations"), BlockTime = json["blocktime"] != null ? NBitcoin.Utils.UnixTimeToDateTime(json.Value<long>("blocktime")) : (DateTimeOffset?)null }; } public void SendRawTransaction(Transaction tx) { SendRawTransaction(tx.ToBytes()); } public void SendRawTransaction(byte[] bytes) { SendCommand(RPCOperations.sendrawtransaction, Encoders.Hex.EncodeData(bytes)); } public Task SendRawTransactionAsync(Transaction tx) { return SendRawTransactionAsync(tx.ToBytes()); } public Task SendRawTransactionAsync(byte[] bytes) { return SendCommandAsync(RPCOperations.sendrawtransaction, Encoders.Hex.EncodeData(bytes)); } public BumpResponse BumpFee(uint256 txid) { return BumpFeeAsync(txid).GetAwaiter().GetResult(); } public async Task<BumpResponse> BumpFeeAsync(uint256 txid) { var response = await SendCommandAsync(RPCOperations.bumpfee, txid); var o = response.Result; return new BumpResponse{ TransactionId = uint256.Parse((string)o["txid"]), OriginalFee = (ulong)o["origfee"], Fee = (ulong)o["fee"], Errors = o["errors"].Select(x=>(string)x).ToList() }; } #endregion #region Utility functions // Estimates the approximate fee per kilobyte needed for a transaction to begin // confirmation within conf_target blocks if possible and return the number of blocks // for which the estimate is valid.Uses virtual transaction size as defined // in BIP 141 (witness data is discounted). #region Fee Estimation /// <summary> /// (>= Bitcoin Core v0.14) Get the estimated fee per kb for being confirmed in nblock /// </summary> /// <param name="confirmationTarget">Confirmation target in blocks (1 - 1008)</param> /// <param name="estimateMode">Whether to return a more conservative estimate which also satisfies a longer history. A conservative estimate potentially returns a higher feerate and is more likely to be sufficient for the desired target, but is not as responsive to short term drops in the prevailing fee market.</param> /// <returns>The estimated fee rate, block number where estimate was found</returns> /// <exception cref="NoEstimationException">The Fee rate couldn't be estimated because of insufficient data from Bitcoin Core</exception> public EstimateSmartFeeResponse EstimateSmartFee(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { return EstimateSmartFeeAsync(confirmationTarget, estimateMode).GetAwaiter().GetResult(); } /// <summary> /// (>= Bitcoin Core v0.14) Tries to get the estimated fee per kb for being confirmed in nblock /// </summary> /// <param name="confirmationTarget">Confirmation target in blocks (1 - 1008)</param> /// <param name="estimateMode">Whether to return a more conservative estimate which also satisfies a longer history. A conservative estimate potentially returns a higher feerate and is more likely to be sufficient for the desired target, but is not as responsive to short term drops in the prevailing fee market.</param> /// <returns>The estimated fee rate, block number where estimate was found or null</returns> public async Task<EstimateSmartFeeResponse> TryEstimateSmartFeeAsync(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { return await EstimateSmartFeeImplAsync(confirmationTarget, estimateMode).ConfigureAwait(false); } /// <summary> /// (>= Bitcoin Core v0.14) Tries to get the estimated fee per kb for being confirmed in nblock /// </summary> /// <param name="confirmationTarget">Confirmation target in blocks (1 - 1008)</param> /// <param name="estimateMode">Whether to return a more conservative estimate which also satisfies a longer history. A conservative estimate potentially returns a higher feerate and is more likely to be sufficient for the desired target, but is not as responsive to short term drops in the prevailing fee market.</param> /// <returns>The estimated fee rate, block number where estimate was found or null</returns> public EstimateSmartFeeResponse TryEstimateSmartFee(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { return TryEstimateSmartFeeAsync(confirmationTarget, estimateMode).GetAwaiter().GetResult(); } /// <summary> /// (>= Bitcoin Core v0.14) Get the estimated fee per kb for being confirmed in nblock /// </summary> /// <param name="confirmationTarget">Confirmation target in blocks (1 - 1008)</param> /// <param name="estimateMode">Whether to return a more conservative estimate which also satisfies a longer history. A conservative estimate potentially returns a higher feerate and is more likely to be sufficient for the desired target, but is not as responsive to short term drops in the prevailing fee market.</param> /// <returns>The estimated fee rate, block number where estimate was found</returns> /// <exception cref="NoEstimationException">when fee couldn't be estimated</exception> public async Task<EstimateSmartFeeResponse> EstimateSmartFeeAsync(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { var feeRate = await EstimateSmartFeeImplAsync(confirmationTarget, estimateMode); if (feeRate == null) throw new NoEstimationException(confirmationTarget); return feeRate; } /// <summary> /// (>= Bitcoin Core v0.14) /// </summary> private async Task<EstimateSmartFeeResponse> EstimateSmartFeeImplAsync(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { var request = new RPCRequest(RPCOperations.estimatesmartfee.ToString(), new object[] { confirmationTarget, estimateMode.ToString().ToUpperInvariant() }); var response = await SendCommandAsync(request, throwIfRPCError: false).ConfigureAwait(false); if (response?.Error != null) { return null; } var resultJToken = response.Result; var feeRateDecimal = resultJToken.Value<decimal>("feerate"); // estimate fee-per-kilobyte (in BTC) var blocks = resultJToken.Value<int>("blocks"); // block number where estimate was found var money = Money.Coins(feeRateDecimal); if (money.Satoshi <= 0) { return null; } return new EstimateSmartFeeResponse { FeeRate = new FeeRate(money), Blocks = blocks }; } #endregion // DEPRECATED. Please use estimatesmartfee for more intelligent estimates. // Estimates the approximate fee per kilobyte needed for a transaction to begin // confirmation within nblocks blocks.Uses virtual transaction size of transaction // as defined in BIP 141 (witness data is discounted). #region Obsoleted Fee Estimation #endregion /// <summary> /// Requires wallet support. Requires an unlocked wallet or an unencrypted wallet. /// </summary> /// <param name="address">A P2PKH or P2SH address to which the bitcoins should be sent</param> /// <param name="amount">The amount to spend</param> /// <param name="commentTx">A locally-stored (not broadcast) comment assigned to this transaction. Default is no comment</param> /// <param name="commentDest">A locally-stored (not broadcast) comment assigned to this transaction. Meant to be used for describing who the payment was sent to. Default is no comment</param> /// <param name="subtractFeeFromAmount">The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. </param> /// <param name="replaceable">Allow this transaction to be replaced by a transaction with higher fees. </param> /// <returns>The TXID of the sent transaction</returns> public uint256 SendToAddress( BitcoinAddress address, Money amount, string commentTx = null, string commentDest = null, bool subtractFeeFromAmount = false, bool replaceable = false ) { uint256 txid = null; txid = SendToAddressAsync(address, amount, commentTx, commentDest, subtractFeeFromAmount, replaceable).GetAwaiter().GetResult(); return txid; } /// <summary> /// Requires wallet support. Requires an unlocked wallet or an unencrypted wallet. /// </summary> /// <param name="address">A P2PKH or P2SH address to which the bitcoins should be sent</param> /// <param name="amount">The amount to spend</param> /// <param name="commentTx">A locally-stored (not broadcast) comment assigned to this transaction. Default is no comment</param> /// <param name="commentDest">A locally-stored (not broadcast) comment assigned to this transaction. Meant to be used for describing who the payment was sent to. Default is no comment</param> /// <param name="subtractFeeFromAmount">The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. </param> /// <param name="replaceable">Allow this transaction to be replaced by a transaction with higher fees. </param> /// <returns>The TXID of the sent transaction</returns> public async Task<uint256> SendToAddressAsync( BitcoinAddress address, Money amount, string commentTx = null, string commentDest = null, bool subtractFeeFromAmount = false, bool replaceable = false ) { List<object> parameters = new List<object>(); parameters.Add(address.ToString()); parameters.Add(amount.ToString()); parameters.Add($"{commentTx}"); parameters.Add($"{commentDest}"); if(subtractFeeFromAmount || replaceable) { parameters.Add(subtractFeeFromAmount); if(replaceable) parameters.Add(replaceable); } var resp = await SendCommandAsync(RPCOperations.sendtoaddress, parameters.ToArray()).ConfigureAwait(false); return uint256.Parse(resp.Result.ToString()); } public bool SetTxFee(FeeRate feeRate) { return SendCommand(RPCOperations.settxfee, new[] { feeRate.FeePerK.ToString() }).Result.ToString() == "true"; } #endregion public async Task<uint256[]> GenerateAsync(int nBlocks) { if(nBlocks < 0) throw new ArgumentOutOfRangeException("nBlocks"); var result = (JArray)(await SendCommandAsync(RPCOperations.generate, nBlocks).ConfigureAwait(false)).Result; return result.Select(r => new uint256(r.Value<string>())).ToArray(); } public uint256[] Generate(int nBlocks) { return GenerateAsync(nBlocks).GetAwaiter().GetResult(); } #region Region Hidden Methods /// <summary> /// Permanently marks a block as invalid, as if it violated a consensus rule. /// </summary> /// <param name="blockhash">the hash of the block to mark as invalid</param> public void InvalidateBlock(uint256 blockhash) { SendCommand(RPCOperations.invalidateblock, blockhash); } /// <summary> /// Permanently marks a block as invalid, as if it violated a consensus rule. /// </summary> /// <param name="blockhash">the hash of the block to mark as invalid</param> public async Task InvalidateBlockAsync(uint256 blockhash) { await SendCommandAsync(RPCOperations.invalidateblock, blockhash).ConfigureAwait(false); } /// <summary> /// Marks a transaction and all its in-wallet descendants as abandoned which will allow /// for their inputs to be respent. /// </summary> /// <param name="txId">the transaction id to be marked as abandoned.</param> public void AbandonTransaction(uint256 txId) { SendCommand(RPCOperations.abandontransaction, txId.ToString()); } /// <summary> /// Marks a transaction and all its in-wallet descendants as abandoned which will allow /// for their inputs to be respent. /// </summary> /// <param name="txId">the transaction id to be marked as abandoned.</param> public async Task AbandonTransactionAsync(uint256 txId) { await SendCommandAsync(RPCOperations.abandontransaction, txId.ToString()).ConfigureAwait(false); } #endregion } #if !NOSOCKET public class PeerInfo { public int Id { get; internal set; } public IPEndPoint Address { get; internal set; } public IPEndPoint LocalAddress { get; internal set; } public NodeServices Services { get; internal set; } public DateTimeOffset LastSend { get; internal set; } public DateTimeOffset LastReceive { get; internal set; } public long BytesSent { get; internal set; } public long BytesReceived { get; internal set; } public DateTimeOffset ConnectionTime { get; internal set; } public TimeSpan? PingTime { get; internal set; } public int Version { get; internal set; } public string SubVersion { get; internal set; } public bool Inbound { get; internal set; } public int StartingHeight { get; internal set; } public int BanScore { get; internal set; } public int SynchronizedHeaders { get; internal set; } public int SynchronizedBlocks { get; internal set; } public uint[] Inflight { get; internal set; } public bool IsWhiteListed { get; internal set; } public TimeSpan PingWait { get; internal set; } public int Blocks { get; internal set; } public TimeSpan TimeOffset { get; internal set; } } public class AddedNodeInfo { public EndPoint AddedNode { get; internal set; } public bool Connected { get; internal set; } public IEnumerable<NodeAddressInfo> Addresses { get; internal set; } } public class NodeAddressInfo { public IPEndPoint Address { get; internal set; } public bool Connected { get; internal set; } } #endif public class BlockchainInfo { public class SoftFork { public string Bip { get; set; } public int Version { get; set; } public bool RejectStatus { get; set; } } public class Bip9SoftFork { public string Name { get; set; } public string Status { get; set; } public DateTimeOffset StartTime { get; set; } public DateTimeOffset Timeout { get; set; } public ulong SinceHeight { get; set; } } public Network Chain { get; set; } public ulong Blocks { get; set; } public ulong Headers { get; set; } public uint256 BestBlockHash { get; set; } public ulong Difficulty { get; set; } public ulong MedianTime { get; set; } public float VerificationProgress { get; set; } public bool InitialBlockDownload { get; set; } public uint256 ChainWork { get; set; } public ulong SizeOnDisk { get; set; } public bool Pruned { get; set; } public List<SoftFork> SoftForks { get; set; } public List<Bip9SoftFork> Bip9SoftForks { get; set; } } public class RawTransactionInfo { public Transaction Transaction {get; internal set;} public uint256 TransactionId {get; internal set;} public uint256 Hash {get; internal set;} public uint Size {get; internal set;} public uint VirtualSize {get; internal set;} public uint Version {get; internal set;} public LockTime LockTime {get; internal set;} public uint256 BlockHash {get; internal set;} public uint Confirmations {get; internal set;} public DateTimeOffset? TransactionTime {get; internal set;} public DateTimeOffset? BlockTime {get; internal set;} } public class BumpResponse { public uint256 TransactionId { get; set; } public ulong OriginalFee { get; set; } public ulong Fee { get; set; } public List<string> Errors { get; set; } } public class NoEstimationException : Exception { public NoEstimationException(int nblock) : base("The FeeRate couldn't be estimated because of insufficient data from Bitcoin Core. Try to use smaller nBlock, or wait Bitcoin Core to gather more data.") { } } } #endif
33.016443
323
0.687215
[ "MIT" ]
endink/NBitcoin
NBitcoin/RPC/RPCClient.cs
54,215
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace NameChanger { public class MemoryBlock { private Scan scan; private long address = 0; private int size = 0; public List<long> results = new List<long>(); public MemoryBlock(Scan scan, long address, long size) { this.address = address; this.size = (int)size; this.scan = scan; } public void Scan(byte[] target) { var buffer = new byte[this.size]; if (!NativeMethods.ReadProcessMemory(scan.processHandle, new IntPtr(address), buffer, size, out var bytesRead)) { if (bytesRead.ToInt32() > 0) { this.size = bytesRead.ToInt32(); } else { return; } } for (int i = 0; i < this.size; i++) { if (i + target.Length > buffer.Length) break; for (int j = 0; j < target.Length; j++) { if (buffer[i + j] != target[j]) break; if (j == target.Length - 1) { results.Add(this.address + i); break; } } } } } public class Scan { public static NativeMethods.AllocationProtect READABLEMEMORY { get; private set; } = NativeMethods.AllocationProtect.PAGE_EXECUTE_READ | NativeMethods.AllocationProtect.PAGE_READWRITE | NativeMethods.AllocationProtect.PAGE_EXECUTE_READWRITE; public static NativeMethods.AllocationProtect COPYONWRITEMEMORY { get; private set; } = NativeMethods.AllocationProtect.PAGE_EXECUTE_WRITECOPY | NativeMethods.AllocationProtect.PAGE_WRITECOPY; public static NativeMethods.AllocationProtect MemoryType { get; set; } = READABLEMEMORY | COPYONWRITEMEMORY; public List<MemoryBlock> memoryBlocks = null; public long blockSize = 256 * 1024; public IntPtr processHandle; public Scan(IntPtr handle) { this.processHandle = handle; this.memoryBlocks = new List<MemoryBlock>(); this.Query(); } public List<long> GetResults() { var results = new List<long>(); foreach (var block in memoryBlocks) { results.AddRange(block.results); } return results; } public void Process(byte[] target, Action scanComplete = null) { NativeMethods.GetSystemInfo(out var systemInfo); Task.Factory.StartNew(() => { object lockie = new object(); try { Parallel.ForEach( this.memoryBlocks, new ParallelOptions() { MaxDegreeOfParallelism = (int)systemInfo.NumberOfProcessors }, block => { block.Scan(target); }); if (scanComplete != null) { scanComplete.Invoke(); } } catch (OperationCanceledException) { System.Diagnostics.Debug.Print("Scan aborted"); } }); } public void Query() { long address = 0; long maxAddress = long.MaxValue; int remainder = 0; long baseAddress = address; NativeMethods.GetSystemInfo(out var systemInfo); long maxPagesPerBlock = blockSize / systemInfo.PageSize; var mbi = default(NativeMethods.MEMORY_BASIC_INFORMATION64); uint size = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORY_BASIC_INFORMATION64)); while (NativeMethods.VirtualQueryEx(processHandle, new IntPtr(address), out mbi, size) != 0) { if ((mbi.State & (int)NativeMethods.AllocationType.Commit) != 0 && (mbi.AllocationProtect & (int)MemoryType) != 0) { baseAddress = (long)mbi.BaseAddress; remainder = Convert.ToInt32((long)mbi.RegionSize / systemInfo.PageSize); while (true) { if (remainder <= maxPagesPerBlock) { blockSize = remainder * systemInfo.PageSize; } else { blockSize = Convert.ToInt32(maxPagesPerBlock * systemInfo.PageSize); } this.memoryBlocks.Add( new MemoryBlock( this, baseAddress, blockSize)); baseAddress += blockSize; remainder -= Convert.ToInt32(blockSize / systemInfo.PageSize); if (remainder == 0) { break; } } } address = (long)mbi.BaseAddress + (long)mbi.RegionSize; if (address >= maxAddress) { break; } } } } }
33.128655
249
0.468667
[ "Unlicense" ]
plumbwicked/Gta5-Name-Changer
NameChanger/Scan.cs
5,667
C#
/** * Copyright 2016 d-fens GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; namespace biz.dfch.CS.Examples.DI.StructureMap.InjectionDependingOnAppConfig { public class DefaultPlugin : IPlugin { private readonly DefaultPluginSettings settings; public DefaultPlugin() { // N/A } public DefaultPlugin(DefaultPluginSettings settings) { Contract.Requires(null != settings); this.settings = settings; } public string Invoke(int value) { return settings.Magic == value ? settings.Magic.ToString() : settings.Sep; } } }
27.42
76
0.661561
[ "Apache-2.0" ]
dfensgmbh/biz.dfch.CS.Examples.DI
src/biz.dfch.CS.Examples.DI.StructureMap/InjectionDependingOnAppConfig/DefaultPlugin.cs
1,373
C#
/*-------------------------------------------------------------------------------------- Copyright © 2013 Theodoros Bebekis teo.bebekis@gmail.com --------------------------------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Text; namespace Tripous.Data.Metadata { /// <summary> /// Represents schema information for a field in a table /// </summary> public class MetaField : NamedItem, IMetaNode { private string defaultValue; private string maxLength; private string precision; private string scale; /* construction */ /// <summary> /// Constructor /// </summary> public MetaField() { } /* properties */ /// <summary> /// Get the table this field belongs to /// </summary> public MetaTable Table { get { return CollectionOwner as MetaTable; } } /// <summary> /// Gets the display text for the field, i.e. FIELD_NAME datatype(size), null /// </summary> public string DisplayText { get { StringBuilder SB = new StringBuilder(); SB.Append(Name); if (IsPrimaryKey) SB.Append(" PK"); SB.Append(" " + DataType); if ((MetaType != null) && MetaType.IsString) SB.Append(string.Format("({0})", MaxLength)); SB.Append(string.Format(" {0}", IsNullable ? "null" : "not null")); if (IsIdentity) SB.Append(" Identity"); if (IsUniqueKey) SB.Append(" Unique"); return SB.ToString(); } } /// <summary> /// The kind of this meta-node, i.e. Tables, Table, Columns, Column, etc /// </summary> public MetaNodeKind Kind { get { return MetaNodeKind.Field; } } /// <summary> /// A user defined value /// </summary> public object Tag { get; set; } /// <summary> /// Gets the ordinal position of this field in the table /// </summary> public int Ordinal { get; set; } /// <summary> /// Gets the default value, if any, defined for the field, else SysConst.NULL /// </summary> public string DefaultValue { get { return string.IsNullOrEmpty(defaultValue) ? string.Empty : defaultValue; } set { defaultValue = value; } } /// <summary> /// Get a boolean valued indicating whether this field is nullable /// </summary> public bool IsNullable { get; set; } /// <summary> /// Gets the meta type object, that is an object with data type information regarding this field /// </summary> public MetaType MetaType { get; set; } /// <summary> /// Gets the data type as it is defined in the CREATE TABLE (ie varchar, int, float etc) /// </summary> public string DataType { get { return MetaType != null ? MetaType.Name : string.Empty; } } /// <summary> /// Gets the .Net data type of this field, ie System.String, System.Double etc /// </summary> public string NetType { get { return MetaType != null ? MetaType.NetType : string.Empty; } } /// <summary> /// Gets the maximum length of a string (varchar) field /// </summary> public string MaxLength { get { return string.IsNullOrEmpty(maxLength) ? string.Empty : maxLength; } set { maxLength = value; } } /// <summary> /// Gets the precision. /// <para>Valid when this is a float etc field</para> /// <para>Precision is the number of digits in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.</para> /// </summary> public string Precision { get { return string.IsNullOrEmpty(precision) ? string.Empty : precision; } set { precision = value; } } /// <summary> /// Gets the scale. /// <para>Valid when this is a float etc field</para> /// <para>Precision is the number of digits in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.</para> /// </summary> public string Scale { get { return string.IsNullOrEmpty(scale) ? string.Empty : scale; } set { scale = value; } } /* flags */ /// <summary> /// True when this is an identity column (auto-increment, etc) /// </summary> public bool IsIdentity { get; set; } /// <summary> /// True when this is a primary key field /// </summary> public bool IsPrimaryKey { get; set; } /// <summary> /// True when this is a unique key field /// </summary> public bool IsUniqueKey { get; set; } } }
34.072368
141
0.505889
[ "Unlicense" ]
tbebekis/Tripous
Tripous.Data/Metadata/MetaField.cs
5,182
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 codestar-2017-04-19.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.CodeStar.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeStar.Model.Internal.MarshallTransformations { /// <summary> /// DisassociateTeamMember Request Marshaller /// </summary> public class DisassociateTeamMemberRequestMarshaller : IMarshaller<IRequest, DisassociateTeamMemberRequest> , 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((DisassociateTeamMemberRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DisassociateTeamMemberRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeStar"); string target = "CodeStar_20170419.DisassociateTeamMember"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-04-19"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetProjectId()) { context.Writer.WritePropertyName("projectId"); context.Writer.Write(publicRequest.ProjectId); } if(publicRequest.IsSetUserArn()) { context.Writer.WritePropertyName("userArn"); context.Writer.Write(publicRequest.UserArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DisassociateTeamMemberRequestMarshaller _instance = new DisassociateTeamMemberRequestMarshaller(); internal static DisassociateTeamMemberRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DisassociateTeamMemberRequestMarshaller Instance { get { return _instance; } } } }
35.945946
159
0.628822
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CodeStar/Generated/Model/Internal/MarshallTransformations/DisassociateTeamMemberRequestMarshaller.cs
3,990
C#
using PKISharp.WACS.Plugins.Base.Options; using PKISharp.WACS.Plugins.Interfaces; using PKISharp.WACS.Services; using System.Threading.Tasks; namespace PKISharp.WACS.Plugins.Base.Factories { /// <summary> /// StorePluginFactory base implementation /// </summary> /// <typeparam name="TPlugin"></typeparam> public abstract class StorePluginOptionsFactory<TPlugin, TOptions> : PluginOptionsFactory<TPlugin, TOptions>, IStorePluginOptionsFactory where TPlugin : IStorePlugin where TOptions : StorePluginOptions, new() { public abstract Task<TOptions> Aquire(IInputService inputService, RunLevel runLevel); public abstract Task<TOptions> Default(); async Task<StorePluginOptions> IStorePluginOptionsFactory.Aquire(IInputService inputService, RunLevel runLevel) => await Aquire(inputService, runLevel); async Task<StorePluginOptions> IStorePluginOptionsFactory.Default() => await Default(); } }
36.555556
160
0.735562
[ "Apache-2.0" ]
SparebankenVest/win-acme
src/main.lib/Plugins/Base/OptionsFactories/StorePluginOptionsFactory.cs
989
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using TEventStore.Exceptions; using TEventStore.Test.DomainEvents; using Xunit; namespace TEventStore.Test { public class ExceptionHandlingTest { private readonly EventStoreRepository _eventStoreRepository; public ExceptionHandlingTest() { _eventStoreRepository = new EventStoreRepository(null); } [Fact] public void GivenNullAggregateId_WhenConstructingAggregateRecord_ShouldThrowInvalidAggregateIdException() { // Given string aggregateId = null; const string name = "Boo"; const int version = 0; // When + Then Assert.Throws<InvalidAggregateIdException>(() => new AggregateRecord(aggregateId, name, version)); } [Fact] public void GivenEmptyAggregateId_WhenConstructingAggregateRecord_ShouldThrowInvalidAggregateIdException() { // Given var aggregateId = string.Empty; const string name = "Boo"; const int version = 0; // When + Then Assert.Throws<InvalidAggregateIdException>(() => new AggregateRecord(aggregateId, name, version)); } [Fact] public void GivenNullAggregateName_WhenConstructingAggregateRecord_ShouldThrowInvalidAggregateRecordException() { // Given const string aggregateId = "BooId"; const string name = null; const int version = 0; // When + Then Assert.Throws<InvalidAggregateRecordException>(() => new AggregateRecord(aggregateId, name, version)); } [Fact] public void GivenEmptyAggregateName_WhenConstructingAggregateRecord_ShouldThrowInvalidAggregateRecordException() { // Given const string aggregateId = "BooId"; var name = string.Empty; const int version = 0; // When + Then Assert.Throws<InvalidAggregateRecordException>(() => new AggregateRecord(aggregateId, name, version)); } [Fact] public void GivenVersionLessThenZero_WhenConstructingAggregateRecord_ShouldThrowInvalidAggregateRecordException() { // Given const string aggregateId = "BooId"; const string name = "Boo"; const int version = -1; // When + Then Assert.Throws<InvalidAggregateRecordException>(() => new AggregateRecord(aggregateId, name, version)); } [Fact] public void GivenEmptyEventId_WhenConstructingEventRecord_ShouldThrowInvalidEventIdException() { // Given var eventId = Guid.Empty; var createdAt = DateTime.Now; var @event = new BooCreated("AggregateId", 100M, false); // When + Then Assert.Throws<InvalidEventIdException>(() => new EventRecord<DomainEvent>(eventId, createdAt, @event)); } [Fact] public void GivenDefaultCreatedAt_WhenConstructingEventRecord_ShouldThrowInvalidEventRecordException() { // Given var eventId = Guid.NewGuid(); var createdAt = (DateTime)default; var @event = new BooCreated("AggregateId", 100M, false); // When + Then Assert.Throws<InvalidEventRecordException>(() => new EventRecord<DomainEvent>(eventId, createdAt, @event)); } [Fact] public void GivenNullEvent_WhenConstructingEventRecord_ShouldThrowInvalidEventRecordException() { // Given var eventId = Guid.NewGuid(); var createdAt = DateTime.Now; BooCreated @event = null; // When + Then Assert.Throws<InvalidEventRecordException>(() => new EventRecord<DomainEvent>(eventId, createdAt, @event)); } [Fact] public async Task GivenNullAggregateRecord_WhenSaveAsync_ShouldThrowInvalidAggregateRecordException() { // Given var @event = new BooCreated("AggregateId", 100M, false); AggregateRecord aggregateRecord = null; var eventRecords = new List<EventRecord<DomainEvent>> { new EventRecord<DomainEvent>(Guid.NewGuid(), DateTime.Now, @event) }; // When + Then await Assert.ThrowsAsync<InvalidAggregateRecordException > (() => _eventStoreRepository.SaveAsync(aggregateRecord, eventRecords)); } [Fact] public async Task GivenAnyNullEventRecord_WhenSaveAsync_ShouldThrowInvalidEventRecordException() { // Given var @event = new BooCreated("AggregateId", 100M, false); var aggregateRecord = new AggregateRecord("AggregateId", "AggregateName", 0); var eventRecords = new List<EventRecord<DomainEvent>> { null, new EventRecord<DomainEvent>(Guid.NewGuid(), DateTime.Now, @event) }; // When + Then await Assert.ThrowsAsync<InvalidEventRecordException>(() => _eventStoreRepository.SaveAsync(aggregateRecord, eventRecords)); } [Fact] public async Task GivenNullSqlConnection_WhenSaveAsync_ShouldThrowNullReferenceException() { // Given var @event = new BooCreated("AggregateId", 100M, false); var aggregateRecord = new AggregateRecord("AggregateId", "AggregateName", 0); var eventRecords = new List<EventRecord<DomainEvent>> { new EventRecord<DomainEvent>(Guid.NewGuid(), DateTime.Now, @event) }; // When + Then await Assert.ThrowsAsync<NullReferenceException>(() => _eventStoreRepository.SaveAsync(aggregateRecord, eventRecords)); } [Fact] public async Task GivenNullAggregateId_WhenGetAsync_ShouldThrowInvalidAggregateIdException() { // Given string aggregateId = null; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetAsync<DomainEvent>(aggregateId)); } [Fact] public async Task GivenWhiteSpaceAggregateId_WhenGetAsync_ShouldThrowInvalidAggregateIdException() { // Given var aggregateId = string.Empty; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetAsync<DomainEvent>(aggregateId)); } [Fact] public async Task GivenSequenceLessThenZero_WhenGetFromSequenceAsync_ShouldThrowInvalidSequenceException() { // Given const int sequence = -1; // When + Then await Assert.ThrowsAsync<InvalidSequenceException>(() => _eventStoreRepository.GetFromSequenceAsync<DomainEvent>(sequence)); } [Fact] public async Task GivenNullAggregateId_WhenGetUntilAsync_ShouldThrowInvalidAggregateIdException() { // Given const int sequence = 2; const string aggregateId = null; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, sequence)); } [Fact] public async Task GivenEmptyAggregateId_WhenGetUntilAsync_ShouldThrowInvalidAggregateIdException() { // Given const int sequence = 2; var aggregateId = string.Empty; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, sequence)); } [Fact] public async Task GivenSequenceLessThenZero_WhenGetUntilAsync_ShouldThrowInvalidSequenceException() { // Given const int sequence = -1; const string aggregateId = "AggregateId"; // When + Then await Assert.ThrowsAsync<InvalidSequenceException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, sequence)); } [Fact] public async Task GivenZeroSequence_WhenGetUntilAsync_ShouldThrowInvalidSequenceException() { // Given const int sequence = 0; const string aggregateId = "AggregateId"; // When + Then await Assert.ThrowsAsync<InvalidSequenceException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, sequence)); } [Fact] public async Task GivenEmptyEventId_WhenGetUntilEventAsync_ShouldThrowInvalidEventIdException() { // Given var eventId = Guid.Empty; const string aggregateId = "AggregateId"; // When + Then await Assert.ThrowsAsync<InvalidEventIdException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, eventId)); } [Fact] public async Task GivenNullAggregateId_WhenGetUntilEventAsync_ShouldThrowInvalidAggregateIdException() { // Given var eventId = Guid.NewGuid(); const string aggregateId = null; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, eventId)); } [Fact] public async Task GivenEmptyAggregateId_WhenGetUntilEventAsync_ShouldThrowInvalidAggregateIdException() { // Given var eventId = Guid.NewGuid(); var aggregateId = string.Empty; // When + Then await Assert.ThrowsAsync<InvalidAggregateIdException>(() => _eventStoreRepository.GetUntilAsync<DomainEvent>(aggregateId, eventId)); } } }
36.106007
121
0.610883
[ "Apache-2.0" ]
nusreta/TEventStore
TEventStore.Test/ExceptionHandlingTest.cs
10,220
C#
using Microsoft.Extensions.Logging; using Roadie.Library.Caching; using Roadie.Library.Configuration; using Roadie.Library.MetaData.ID3Tags; using Roadie.Library.Utility; using System; using System.IO; using System.Linq; namespace Roadie.Library.Inspect.Plugins.Directory { public class EnsureArtistConsistent : FolderPluginBase { public override string Description => "Consistent: Ensure all MP3 files in folder have same Artist (TPE1)"; public override bool IsEnabled => false; public override int Order { get; } = 1; public EnsureArtistConsistent(IRoadieSettings configuration, ICacheManager cacheManager, ILogger logger, IID3TagsHelper tagsHelper) : base(configuration, cacheManager, logger, tagsHelper) { } public override OperationResult<string> Process(DirectoryInfo directory) { var result = new OperationResult<string>(); var data = string.Empty; var found = 0; var modified = 0; var metaDatasForFilesInFolder = GetAudioMetaDatasForDirectory(directory); if (metaDatasForFilesInFolder.Any()) { found = metaDatasForFilesInFolder.Count(); var firstMetaData = metaDatasForFilesInFolder.OrderBy(x => x.Filename ?? string.Empty) .ThenBy(x => SafeParser.ToNumber<short>(x.TrackNumber)).FirstOrDefault(); if (firstMetaData == null) { return new OperationResult<string>("Error Getting First MetaData") { Data = $"Unable to read Metadatas for Directory [{directory.FullName}]" }; } var artist = firstMetaData.Artist; foreach (var metaData in metaDatasForFilesInFolder.Where(x => x.Artist != artist)) { modified++; Console.WriteLine( $"╟ Setting Artist to [{artist}], was [{metaData.Artist}] on file [{metaData.FileInfo.Name}"); metaData.Artist = artist; if (!Configuration.Inspector.IsInReadOnlyMode) { TagsHelper.WriteTags(metaData, metaData.Filename); } } data = $"Found [{found}] files, Modified [{modified}] files"; } result.Data = data; result.IsSuccess = true; return result; } } }
38.671642
118
0.567734
[ "MIT" ]
sphildreth/roadie
Roadie.Api.Library/Inspect/Plugins/Directory/EnsureArtistConsistent.cs
2,595
C#
using SujaySarma.Sdk.WikipediaApi.SerializationObjects; using System; using System.Collections.Generic; using System.Text.Json; namespace SujaySarma.Sdk.WikipediaApi.Data { /// <summary> /// Implements the "/data/citation/*" endpoints /// </summary> public class CitationClient : WikipediaClient { /// <summary> /// Get the citation reference for an item in MediaWiki format /// </summary> /// <param name="itemIdentifier"> /// Identifier for the citation (what do you want to cite?). Accepted identifiers are: /// ISBN, article URL, DOI, PMCID or PMID /// </param> /// <returns>List of citation information, or NULL</returns> public List<CitationResultMediaWiki> GetCitationMediaWiki(string itemIdentifier) { if (string.IsNullOrWhiteSpace(itemIdentifier)) { throw new ArgumentNullException(nameof(itemIdentifier)); } string responseJson = GET($"data/citation/mediawiki/{Uri.EscapeDataString(itemIdentifier)}"); if (!string.IsNullOrWhiteSpace(responseJson)) { return JsonSerializer.Deserialize<List<CitationResultMediaWiki>>(responseJson); } return new List<CitationResultMediaWiki>(); } /// <summary> /// Get the citation reference for an item in Zotero format /// </summary> /// <param name="itemIdentifier"> /// Identifier for the citation (what do you want to cite?). Accepted identifiers are: /// ISBN, article URL, DOI, PMCID or PMID /// </param> /// <returns>List of citation information, or NULL</returns> public List<CitationResultZotero> GetCitationZotero(string itemIdentifier) { if (string.IsNullOrWhiteSpace(itemIdentifier)) { throw new ArgumentNullException(nameof(itemIdentifier)); } string responseJson = GET($"data/citation/zotero/{Uri.EscapeDataString(itemIdentifier)}"); if (!string.IsNullOrWhiteSpace(responseJson)) { return JsonSerializer.Deserialize<List<CitationResultZotero>>(responseJson); } return new List<CitationResultZotero>(); } /// <summary> /// Get the citation reference for an item in Wikibase format /// </summary> /// <param name="itemIdentifier"> /// Identifier for the citation (what do you want to cite?). Accepted identifiers are: /// ISBN, article URL, DOI, PMCID or PMID /// </param> /// <returns>List of citation information, or NULL</returns> /// <remarks> /// Note: The REST endpoint does actually return the data in Zotero format! /// </remarks> public List<CitationResultZotero> GetCitationWikibase(string itemIdentifier) { if (string.IsNullOrWhiteSpace(itemIdentifier)) { throw new ArgumentNullException(nameof(itemIdentifier)); } string responseJson = GET($"data/citation/zotero/{Uri.EscapeDataString(itemIdentifier)}"); if (!string.IsNullOrWhiteSpace(responseJson)) { return JsonSerializer.Deserialize<List<CitationResultZotero>>(responseJson); } return new List<CitationResultZotero>(); } /// <summary> /// Get the citation reference for an item in BibText format /// </summary> /// <param name="itemIdentifier"> /// Identifier for the citation (what do you want to cite?). Accepted identifiers are: /// ISBN, article URL, DOI, PMCID or PMID /// </param> /// <returns>Citation information as text!</returns> /// <remarks> /// Though the result is structured (in TeX), we don't parse it here. That's upto the /// caller to parse and make use of the data. /// </remarks> public string GetCitationBibText(string itemIdentifier) { if (string.IsNullOrWhiteSpace(itemIdentifier)) { throw new ArgumentNullException(nameof(itemIdentifier)); } return GET($"data/citation/bibtex/{Uri.EscapeDataString(itemIdentifier)}"); } /// <summary> /// Constructor (blank) /// </summary> public CitationClient() : base() { } } }
38.432203
105
0.592282
[ "Apache-2.0" ]
sujayvsarma/SujaySarma.Sdk.WikipediaApi
src/Data/CitationClient.cs
4,537
C#
using AdventOfCode2018.Helpers; using AdventOfCode2018.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace AdventOfCode2018 { public partial class Day3 { [Fact] public void Part1() { #region // Arrange string exampleInput1 = @"#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2"; #endregion // Act int actual1 = CalculateSquareInchesOfOverlappedFabric(exampleInput1); int actual = CalculateSquareInchesOfOverlappedFabric(_puzzleInput); // Assert Assert.Equal(4, actual1); Assert.Equal(105231, actual); } [Fact] public void Part2() { #region // Arrange string exampleInput1 = @"#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2"; #endregion // Act int actual1 = FindIdOfClaimWithNoOverlap(exampleInput1); int actual = FindIdOfClaimWithNoOverlap(_puzzleInput); // Assert Assert.Equal(3, actual1); Assert.Equal(164, actual); } private int FindIdOfClaimWithNoOverlap(string input) { var fabricClaims = new List<FabricClaim>(); var coordinateMap = new Dictionary<Coordinate, int>(); string[] elfFabricClaims = Parsing.SplitOnNewLine(input); foreach (string claimString in elfFabricClaims) { FabricClaim fabricClaim = ConvertFabricClaimString(claimString); fabricClaims.Add(fabricClaim); foreach (Coordinate coordinate in fabricClaim.Coordinates) { if (coordinateMap.ContainsKey(coordinate)) coordinateMap[coordinate]++; else coordinateMap.Add(coordinate, 1); } } return fabricClaims .Single(c => c.Coordinates.All(coor => coordinateMap[coor] == 1)) .Id; } private int CalculateSquareInchesOfOverlappedFabric(string input) { var coordinateMap = new Dictionary<Coordinate, int>(); string[] elfFabricClaims = Parsing.SplitOnNewLine(input); foreach (string claimString in elfFabricClaims) { FabricClaim fabricClaim = ConvertFabricClaimString(claimString); foreach (Coordinate coordinate in fabricClaim.Coordinates) { if (coordinateMap.ContainsKey(coordinate)) coordinateMap[coordinate]++; else coordinateMap.Add(coordinate, 1); } } return coordinateMap.Where(kvp => kvp.Value > 1).Count(); ; } private FabricClaim ConvertFabricClaimString(string claimString) { var fabricClaim = new FabricClaim(); string[] delimitedValues = claimString.Split(new[] { " @ ", ": " }, StringSplitOptions.None); fabricClaim.Id = int.Parse(delimitedValues[0].Substring(1)); string[] positionInfo = delimitedValues[1].Split(','); string[] sizeInfo = delimitedValues[2].Split('x'); int cornerCoordinateX = int.Parse(positionInfo[0]) + 1; int cornerCoordinateY = int.Parse(positionInfo[1]) + 1; fabricClaim.Width = int.Parse(sizeInfo[0]); fabricClaim.Height = int.Parse(sizeInfo[1]); for (int i = cornerCoordinateX; i < cornerCoordinateX + fabricClaim.Width; i++) { for (int j = cornerCoordinateY; j < cornerCoordinateY + fabricClaim.Height; j++) { fabricClaim.Coordinates.Add(new Coordinate { X = i, Y = j }); } } return fabricClaim; } } }
30.259542
105
0.54667
[ "Unlicense" ]
TeddMcAdams/AdventOfCode2018
AdventOfCode2018/AdventOfCode2018/Day3.cs
3,966
C#
using NimbleSearch.Foundation.Abstractions.Pipelines.MapResult; namespace NimbleSearch.Foundation.Core.Pipelines.MapResult { public class SetNoResultsMessage : MapResultProcessor { public override void Process(MapResultArgs args) { if (args.TotalSearchResults <= 0) { args.Response.NoResultsMessage = args.TabItem.NoResultsHTML; } } } }
29.333333
77
0.629545
[ "MIT" ]
aokour/NimbleSearch
src/Foundation/NimbleSearch.Core/Code/Pipelines/MapResult/SetNoResultsMessage.cs
442
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json; namespace Trackable.Models { public class User : ModelBase<string> { public string Email { get; set; } public string Name { get; set; } [JsonIgnore] public string ClaimsId { get; set; } public Role Role { get; set; } } }
19.85
60
0.622166
[ "MIT" ]
Microsoft/Bing-Maps-Fleet-Tracker
Backend/src/Trackable.Models/User.cs
397
C#
// Generated by TankLibHelper // ReSharper disable All namespace TankLib.STU.Types { [STU(0x3D579F4F, 64)] public class STUConfigVarExpressionData : STUInstance { [STUField(0x882D0868, 0, ReaderType = typeof(InlineInstanceFieldReader))] // size: 16 public STUConfigVarExpressionFragment[] m_fragments; [STUField(0xEFF7FAE7, 16)] // size: 16 public byte[] m_opcodes; [STUField(0x03AEACC1, 32, ReaderType = typeof(EmbeddedInstanceFieldReader))] // size: 16 public STUConfigVarDynamic[] m_dynamicVars; [STUField(0xD99EF254, 48)] // size: 16 public float[] m_D99EF254; } }
30.772727
96
0.65288
[ "MIT" ]
Pandaaa2507/OWLib
TankLib/STU/Types/STUConfigVarExpressionData.cs
677
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type Windows10DeviceFirmwareConfigurationInterfaceRequest. /// </summary> public partial class Windows10DeviceFirmwareConfigurationInterfaceRequest : BaseRequest, IWindows10DeviceFirmwareConfigurationInterfaceRequest { /// <summary> /// Constructs a new Windows10DeviceFirmwareConfigurationInterfaceRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public Windows10DeviceFirmwareConfigurationInterfaceRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Windows10DeviceFirmwareConfigurationInterface using POST. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToCreate">The Windows10DeviceFirmwareConfigurationInterface to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Windows10DeviceFirmwareConfigurationInterface.</returns> public async System.Threading.Tasks.Task<Windows10DeviceFirmwareConfigurationInterface> CreateAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified Windows10DeviceFirmwareConfigurationInterface using POST and returns a <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToCreate">The Windows10DeviceFirmwareConfigurationInterface to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows10DeviceFirmwareConfigurationInterface>> CreateResponseAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToCreate, cancellationToken); } /// <summary> /// Deletes the specified Windows10DeviceFirmwareConfigurationInterface. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<Windows10DeviceFirmwareConfigurationInterface>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified Windows10DeviceFirmwareConfigurationInterface and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified Windows10DeviceFirmwareConfigurationInterface. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Windows10DeviceFirmwareConfigurationInterface.</returns> public async System.Threading.Tasks.Task<Windows10DeviceFirmwareConfigurationInterface> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<Windows10DeviceFirmwareConfigurationInterface>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified Windows10DeviceFirmwareConfigurationInterface and returns a <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows10DeviceFirmwareConfigurationInterface>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<Windows10DeviceFirmwareConfigurationInterface>(null, cancellationToken); } /// <summary> /// Updates the specified Windows10DeviceFirmwareConfigurationInterface using PATCH. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToUpdate">The Windows10DeviceFirmwareConfigurationInterface to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated Windows10DeviceFirmwareConfigurationInterface.</returns> public async System.Threading.Tasks.Task<Windows10DeviceFirmwareConfigurationInterface> UpdateAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified Windows10DeviceFirmwareConfigurationInterface using PATCH and returns a <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToUpdate">The Windows10DeviceFirmwareConfigurationInterface to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows10DeviceFirmwareConfigurationInterface>> UpdateResponseAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToUpdate, cancellationToken); } /// <summary> /// Updates the specified Windows10DeviceFirmwareConfigurationInterface using PUT. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToUpdate">The Windows10DeviceFirmwareConfigurationInterface object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<Windows10DeviceFirmwareConfigurationInterface> PutAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified Windows10DeviceFirmwareConfigurationInterface using PUT and returns a <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/> object. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToUpdate">The Windows10DeviceFirmwareConfigurationInterface object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{Windows10DeviceFirmwareConfigurationInterface}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<Windows10DeviceFirmwareConfigurationInterface>> PutResponseAsync(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<Windows10DeviceFirmwareConfigurationInterface>(windows10DeviceFirmwareConfigurationInterfaceToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWindows10DeviceFirmwareConfigurationInterfaceRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWindows10DeviceFirmwareConfigurationInterfaceRequest Expand(Expression<Func<Windows10DeviceFirmwareConfigurationInterface, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWindows10DeviceFirmwareConfigurationInterfaceRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWindows10DeviceFirmwareConfigurationInterfaceRequest Select(Expression<Func<Windows10DeviceFirmwareConfigurationInterface, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="windows10DeviceFirmwareConfigurationInterfaceToInitialize">The <see cref="Windows10DeviceFirmwareConfigurationInterface"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Windows10DeviceFirmwareConfigurationInterface windows10DeviceFirmwareConfigurationInterfaceToInitialize) { } } }
60.696
272
0.705615
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/Windows10DeviceFirmwareConfigurationInterfaceRequest.cs
15,174
C#
using System; using System.Collections.Generic; using System.Text; namespace PlayersAndMonsters { public class Knight:Hero { public Knight(string name, int level) :base(name, level) { } } }
14.8125
45
0.616034
[ "MIT" ]
tonkatawe/SoftUni-Advanced
OOP/Inheritance - Exercise/PlayersAndMonsters/Knight.cs
239
C#
using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace PyrusApiClient { [JsonConverter(typeof(StringEnumConverter))] public enum SendSmsStatus { [EnumMember(Value = "sent")] Sent, [EnumMember(Value = "delivered")] Delivered, [EnumMember(Value = "delivery_failed")] DeliveryFailed, [EnumMember(Value = "send_failed")] SendFailed } }
17.608696
45
0.738272
[ "MIT" ]
Vanwards/pyrusapi-csharp
Enums/SendSmsStatus.cs
407
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BackgroundMove : MonoBehaviour { private float startPos,length,temp,dist; [SerializeField] private GameObject cam; [SerializeField] private SpriteRenderer[] spriteRenderer; [SerializeField] private Sprite[] sprite; [SerializeField] private bool hello=false; [SerializeField] private GameObject leftWall; void Start() { for(int i=0;i<3;i++) spriteRenderer[i].sprite = sprite[GameManager.instance.GetSaveInt("Background",0)]; startPos = transform.position.y; length = GetComponent<SpriteRenderer>().bounds.size.y; } void Update() { if(GameManager.instance.isEnding) gameObject.SetActive(false); if(hello) return; temp = cam.transform.position.y; transform.position = new Vector3(transform.position.x, startPos, transform.position.z); if(temp > startPos + length) {startPos += length;leftWall.SetActive(true);} else if(temp < startPos - length) startPos -= length; } public void UpdateUi(){ for(int i=0;i<3;i++) spriteRenderer[i].sprite = sprite[GameManager.instance.GetSaveInt("Background",0)]; } }
29.613636
95
0.649271
[ "MIT" ]
pqowp90/The-jet-man
Assets/code/BackgroundMove.cs
1,303
C#
//////////////////////////////////////////////////////////////////////////////// using Markdig.Renderers; using Markdig.Syntax.Inlines; namespace MG.MDV { /// <see cref="Markdig.Renderers.Html.Inlines.DelimiterInlineRenderer"/> public class RendererInlineDelimiter : MarkdownObjectRenderer<RendererMarkdown, DelimiterInline> { protected override void Write( RendererMarkdown renderer, DelimiterInline node ) { renderer.Text( node.ToLiteral() ); renderer.WriteChildren( node ); } } }
29.947368
101
0.567663
[ "MIT" ]
963148894/QFramework
QFramework/QFramework.Unity.Editor/EasyIMGUI/MarkdownView/Scripts/Renderer/RendererInlineDelimiter.cs
571
C#
using System; namespace Wrld.Transport { /// <summary> /// Allows a coordinate to be matched to a point on a transport network. /// </summary> public class TransportPositioner { /// <summary> /// Uniquely identifies this object instance. /// </summary> public int Id { get; private set; } /// <summary> /// Input latitude coordinate in degrees. /// </summary> public double InputLatitudeDegrees { get; private set; } /// <summary> /// Input longitude coordinate in degrees. /// </summary> public double InputLongitudeDegrees { get; private set; } /// <summary> /// True if optional input heading is set. /// </summary> public bool HasInputHeading { get; private set; } /// <summary> /// Optional input heading angle in degrees clockwise from North. /// </summary> public double InputHeadingDegrees { get; private set; } /// <summary> /// Constraint threshold for the maximum allowed difference between InputHeadingDegrees and the tangent /// direction of a candidate on a TransportDirectedEdge, in degrees. /// </summary> public double MaxHeadingDeviationToMatchedPointDegrees { get; private set; } /// <summary> /// Constraint threshold for the maximum allowed distance between the input coordinates and a candidate point /// on a TransportDirectedEdge, in meters. /// </summary> public double MaxDistanceToMatchedPointMeters { get; private set; } /// <summary> /// The transport network on which to attempt to find a matching point. /// </summary> public TransportNetworkType TransportNetworkType { get; private set; } /// <summary> /// Notfication that the matched point on the transport graph has changed. This may be due to the input of /// this object changing, or due to transport network resources streaming in and out. /// </summary> public event Action OnPointOnGraphChanged; private static int InvalidId = 0; private TransportApiInternal m_transportApiInternal; // Use Api.Instance.TransportApi.CreatePositioner for public construction internal TransportPositioner( TransportApiInternal transportApiInternal, int id, TransportPositionerOptions options) { if (transportApiInternal == null) { throw new ArgumentNullException("transportApiInternal"); } if (id == InvalidId) { throw new ArgumentException("invalid id"); } m_transportApiInternal = transportApiInternal; Id = id; InputLatitudeDegrees = options.InputLatitudeDegrees; InputLongitudeDegrees = options.InputLongitudeDegrees; InputHeadingDegrees = options.InputHeadingDegrees; MaxHeadingDeviationToMatchedPointDegrees = options.MaxHeadingDeviationToMatchedPointDegrees; MaxDistanceToMatchedPointMeters = options.MaxDistanceToMatchedPointMeters; TransportNetworkType = options.TransportNetworkType; HasInputHeading = options.HasHeading; } /// <summary> /// Set the input coordinate. /// </summary> /// <param name="latitudeDegrees">Input latitude, in degrees.</param> /// <param name="longitudeDegrees">Input longitude, in degrees.</param> public void SetInputCoordinates(double latitudeDegrees, double longitudeDegrees) { InputLatitudeDegrees = latitudeDegrees; InputLongitudeDegrees = longitudeDegrees; m_transportApiInternal.SetPositionerInputCoordinates(this, latitudeDegrees, longitudeDegrees); } /// <summary> /// Set the optional input heading. /// </summary> /// <param name="headingDegrees">Input heading angle, as clockwise degrees from North.</param> public void SetInputHeading(double headingDegrees) { InputHeadingDegrees = headingDegrees; HasInputHeading = true; m_transportApiInternal.SetPositionerInputHeading(this, headingDegrees); } /// <summary> /// Clear the optional input heading. /// </summary> public void ClearInputHeading() { InputHeadingDegrees = 0.0; HasInputHeading = false; m_transportApiInternal.ClearPositionerInputHeading(this); } /// <summary> /// Query whether this object currently has a matched point on the transport network. /// See GetPointOnGraph() for reasons why IsMatched() may return false. /// </summary> /// <returns>True if a match has been found, else false.</returns> public bool IsMatched() { return m_transportApiInternal.IsPositionerMatched(this); } /// <summary> /// Get results of the currently best-matched point on the transport network, if any. /// For a successful match to be made, the following constraints must be fulfilled by the currently streamed-in set for the specified transport network: /// &lt;br/&gt; /// * A point on the network can be found that is less than or equal to MaxDistanceToMatchedPointMeters from the input coordinate. /// &lt;br/&gt; /// * If a heading was specified (HasInputHeading is true), the angle between the input heading, and the tangential /// heading of the way at the candiate match point is less than or equal to MaxHeadingDeviationToMatchedPointDegrees. /// &lt;br/&gt; /// </summary> /// <returns>A TransportPositionerPointOnGraph result object.</returns> public TransportPositionerPointOnGraph GetPointOnGraph() { return m_transportApiInternal.GetPositionerPointOnGraph(this); } /// <summary> /// Destroys this TransportPositioner. /// </summary> public void Discard() { m_transportApiInternal.DestroyPositioner(this); Id = InvalidId; } internal void NotifyPointOnGraphChanged() { if (OnPointOnGraphChanged != null) { OnPointOnGraphChanged(); } } } }
39.744048
162
0.606859
[ "BSD-2-Clause" ]
Itchy-Fingerz/wrld-unity-ar-samples
Assets/Wrld/Scripts/Transport/TransportPositioner.cs
6,677
C#
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Denis Kuzmin <x-3F@outlook.com> github/3F // Copyright (c) IeXod contributors https://github.com/3F/IeXod/graphs/contributors // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace net.r_eg.IeXod.UnitTests.OM.ObjectModelRemoting { using System; using System.Collections.Generic; using System.Linq; using net.r_eg.IeXod.Construction; using net.r_eg.IeXod.ObjectModelRemoting; using net.r_eg.IeXod.Evaluation; using Xunit; using System.Runtime.ExceptionServices; using System.Xml.Schema; using System.Collections; using net.r_eg.IeXod.Framework; internal enum ObjectType { Real = 1, View = 2 } internal class LinkPair<T> { public LinkPair(T view, T real) { ViewValidation.VerifyLinkedNotNull(view); ViewValidation.VerifyNotLinkedNotNull(real); this.View = view; this.Real = real; } public T Get(ObjectType type) => type == ObjectType.Real ? this.Real : this.View; public T View { get; } public T Real { get; } public void VerifyNotSame(LinkPair<T> other) { Assert.NotSame((object)this.View, (object)other.View); Assert.NotSame((object)this.Real, (object)other.Real); } public void VerifySame(LinkPair<T> other) { Assert.Same((object)this.View, (object)other.View); Assert.Same((object)this.Real, (object)other.Real); } public void VerifySetter(bool finalValue, Func<T, bool> getter, Action<T, bool> setter) { var current = getter(this.Real); Assert.Equal(current, getter(this.View)); // set via the view setter(this.View, !current); Assert.Equal(!current, getter(this.View)); Assert.Equal(!current, getter(this.Real)); // set via the real. setter(this.Real, current); Assert.Equal(current, getter(this.View)); Assert.Equal(current, getter(this.Real)); setter(this.View, finalValue); Assert.Equal(finalValue, getter(this.View)); Assert.Equal(finalValue, getter(this.Real)); } public void VerifySetter(string newValue, Func<T, string> getter, Action<T, string> setter) { var newValue1 = newValue.Ver(1); var current = getter(this.Real); Assert.Equal(current, getter(this.View)); Assert.NotEqual(current, newValue); Assert.NotEqual(current, newValue1); // set via the view setter(this.View, newValue1); Assert.Equal(newValue1, getter(this.View)); Assert.Equal(newValue1, getter(this.Real)); // set via the real. setter(this.Real, newValue); Assert.Equal(newValue, getter(this.View)); Assert.Equal(newValue, getter(this.Real)); this.Verify(); } public virtual void Verify() { ViewValidation.VerifyFindType(this.View, this.Real); } } internal class ValidationContext { public ValidationContext() { } public ValidationContext(ProjectPair pair) { this.Pair = pair; } public ProjectPair Pair { get; set; } public Action<ElementLocation, ElementLocation> ValidateLocation { get; set; } } internal static partial class ViewValidation { private static bool VerifyCheckType<T>(object view, object real, ValidationContext context, Action<T, T, ValidationContext> elementValidator) { if (view is T viewTypedXml) { Assert.True(real is T); elementValidator(viewTypedXml, (T)real, context); return true; } else { Assert.False(real is T); return false; } } // "Slow" Verify, probing all known link types public static void VerifyFindType(object view, object real, ValidationContext context = null) { if (view == null && real == null) return; VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); // construction if (VerifyCheckType<ProjectMetadataElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectChooseElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectWhenElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectOtherwiseElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectTaskElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectOutputElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectUsingTaskBodyElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectUsingTaskParameterElement>(view, real, context, Verify)) return; if (VerifyCheckType<UsingTaskParameterGroupElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectUsingTaskElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectTargetElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectRootElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectExtensionsElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectImportElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectImportGroupElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItemDefinitionElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItemDefinitionGroupElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItemElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItemGroupElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectPropertyElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectPropertyGroupElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectSdkElement>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectOnErrorElement>(view, real, context, Verify)) return; // evaluation if (VerifyCheckType<ProjectProperty>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectMetadata>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItemDefinition>(view, real, context, Verify)) return; if (VerifyCheckType<ProjectItem>(view, real, context, Verify)) return; if (VerifyCheckType<Project>(view, real, context, Verify)) return; throw new NotImplementedException($"Unknown type:{view.GetType().Name}"); } public static void VerifyMetadata(IEnumerable<KeyValuePair<string, string>> expected, Func<string, string> getMetadata, Func<string, bool> hasMetadata = null) { if (expected == null) return; foreach (var md in expected) { if (hasMetadata != null) { Assert.True(hasMetadata(md.Key)); } Assert.Equal(md.Value, getMetadata(md.Key)); } } public static void Verify<T>(IEnumerable<T> viewCollection, IEnumerable<T> realCollection, Action<T, T, ValidationContext> validator, ValidationContext context = null) { if (viewCollection == null && realCollection == null) return; Assert.NotNull(viewCollection); Assert.NotNull(realCollection); var viewXmlList = viewCollection.ToList(); var realXmlList = realCollection.ToList(); Assert.Equal(realXmlList.Count, viewXmlList.Count); for (int i = 0; i < realXmlList.Count; i++) { validator(viewXmlList[i], realXmlList[i], context); } } public static void Verify<T>(IDictionary<string, T> viewCollection, IDictionary<string, T> realCollection, Action<T, T, ValidationContext> validator, ValidationContext context = null) { if (viewCollection == null && realCollection == null) return; Assert.NotNull(viewCollection); Assert.NotNull(realCollection); Assert.Equal(realCollection.Count, viewCollection.Count); foreach (var k in realCollection.Keys) { Assert.True(viewCollection.TryGetValue(k, out var vv)); Assert.True(realCollection.TryGetValue(k, out var rv)); validator(vv, rv, context); } } public static void Verify<T>(IEnumerable<T> viewXmlCollection, IEnumerable<T> realXmlCollection, ValidationContext context = null) { var viewXmlList = viewXmlCollection.ToList(); var realXmlList = realXmlCollection.ToList(); Assert.Equal(realXmlList.Count, viewXmlList.Count); for (int i = 0; i < realXmlList.Count; i++) { VerifyFindType(viewXmlList[i], realXmlList[i], context); } } } }
42.484444
191
0.617219
[ "MIT" ]
3F/IeXod
src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.cs
9,561
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Dolittle. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. * --------------------------------------------------------------------------------------------*/ using System.Collections.Generic; using Dolittle.DependencyInversion; using Dolittle.Execution; using Dolittle.Tenancy; namespace Dolittle.Runtime.Events.Relativity { /// <summary> /// Retrieves the offsets for all tenants for a particular Event Horizon /// </summary> public interface ITenantOffsetRepository { /// <summary> /// Gets the Offset for each tenant /// </summary> /// <param name="tenants">Tenants to get the offset for</param> /// <param name="key">Key identifying the Event Horizon (Application and Bounded Context)</param> /// <returns></returns> IEnumerable<TenantOffset> Get(IEnumerable<TenantId> tenants, EventHorizonKey key); } }
39.555556
105
0.565543
[ "MIT" ]
joelhoisko/Runtime
Source/Events/Relativity/Consumer/ITenantOffsetRepository.cs
1,068
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 discovery-2015-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ApplicationDiscoveryService.Model { /// <summary> /// This is the response object from the ListConfigurations operation. /// </summary> public partial class ListConfigurationsResponse : AmazonWebServiceResponse { private List<Dictionary<string, string>> _configurations = new List<Dictionary<string, string>>(); private string _nextToken; /// <summary> /// Gets and sets the property Configurations. /// <para> /// Returns configuration details, including the configuration ID, attribute names, and /// attribute values. /// </para> /// </summary> public List<Dictionary<string, string>> Configurations { get { return this._configurations; } set { this._configurations = value; } } // Check to see if Configurations property is set internal bool IsSetConfigurations() { return this._configurations != null && this._configurations.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// Token to retrieve the next set of results. For example, if your call to ListConfigurations /// returned 100 items, but you set <code>ListConfigurationsRequest$maxResults</code> /// to 10, you received a set of 10 results along with this token. Use this token in the /// next query to retrieve the next set of 10. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
34.35443
107
0.644805
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ApplicationDiscoveryService/Generated/Model/ListConfigurationsResponse.cs
2,714
C#
using System; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.LogicalTree; using Avalonia.Styling; using DataBox.Primitives.Layout; namespace DataBox.Controls; public class DataBoxPanel : VirtualizingStackPanel, IStyleable { Type IStyleable.StyleKey => typeof(DataBoxPanel); internal DataBox? DataBox { get; set; } public override void ApplyTemplate() { base.ApplyTemplate(); DataBox = this.GetLogicalAncestors().FirstOrDefault(x => x is DataBox) as DataBox; } protected override Size MeasureOverride(Size availableSize) { if (DataBox is null) { return availableSize; } return DataBoxRowsLayout.Measure(availableSize, DataBox, base.MeasureOverride, base.InvalidateMeasure, Children); } protected override Size ArrangeOverride(Size finalSize) { if (DataBox is null) { return finalSize; } return DataBoxRowsLayout.Arrange(finalSize, DataBox, base.ArrangeOverride, Children); } }
24.136364
121
0.685499
[ "MIT" ]
wieslawsoltes/CellPanelDemo
src/DataBox/Controls/DataBoxPanel.cs
1,064
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Diagnostics; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; namespace IronPython.Runtime.Types { public sealed class PythonTypeUserDescriptorSlot : PythonTypeSlot { private object _value; private int _descVersion; private PythonTypeSlot _desc; private const int UserDescriptorFalse = -1; internal PythonTypeUserDescriptorSlot(object value) { _value = value; } internal PythonTypeUserDescriptorSlot(object value, bool isntDescriptor) { _value = value; if (isntDescriptor) { _descVersion = UserDescriptorFalse; } } internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { try { value = PythonOps.GetUserDescriptor(Value, instance, owner); return true; } catch (MissingMemberException) { value = null; return false; } } internal object GetValue(CodeContext context, object instance, PythonType owner) { if (_descVersion == UserDescriptorFalse) { return _value; } else if (_descVersion != DynamicHelpers.GetPythonType(_value).Version) { CalculateDescriptorInfo(); if (_descVersion == UserDescriptorFalse) { return _value; } } object res; Debug.Assert(_desc.GetAlwaysSucceeds); _desc.TryGetValue(context, _value, DynamicHelpers.GetPythonType(_value), out res); return PythonContext.GetContext(context).Call(context, res, instance, owner); } private void CalculateDescriptorInfo() { PythonType pt = DynamicHelpers.GetPythonType(_value); if (!pt.IsSystemType) { _descVersion = pt.Version; if (!pt.TryResolveSlot(pt.Context.SharedClsContext, "__get__", out _desc)) { _descVersion = UserDescriptorFalse; } } else { _descVersion = UserDescriptorFalse; } } internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { return PythonOps.TryDeleteUserDescriptor(Value, instance); } internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { return PythonOps.TrySetUserDescriptor(Value, instance, value); } internal override bool IsSetDescriptor(CodeContext context, PythonType owner) { object dummy; return PythonOps.TryGetBoundAttr(context, Value, "__set__", out dummy); } internal object Value { get { return _value; } set { _value = value; } } } }
36.910891
118
0.583423
[ "Apache-2.0" ]
0xFireball/exascript2
Src/IronPython/Runtime/Types/PythonTypeUserDescriptorSlot.cs
3,728
C#
namespace GSMTest { using System; public class Display { private const int InitialNumber = 0; private int width; private int heigth; private int depth; private long numberOfColors; public Display() { this.Width = InitialNumber; this.Heigth = InitialNumber; this.Depth = InitialNumber; this.NumberOfColors = InitialNumber; } public Display(int displayWidth, int displayHeigth, int displayDepth, long displayNumberOfColors) { this.Width = displayWidth; this.Heigth = displayHeigth; this.Depth = displayDepth; this.NumberOfColors = displayNumberOfColors; } public int Width { get { return this.width; } set { if(value < 1) { throw new ArgumentOutOfRangeException("Invalid number!"); } this.width = value; } } public int Heigth { get { return this.heigth; } set { if (value < 1) { throw new ArgumentOutOfRangeException("Negative number!"); } this.heigth = value; } } public int Depth { get { return this.depth; } set { if (value < 1) { throw new ArgumentOutOfRangeException("Negative number!"); } this.depth = value; } } public long NumberOfColors { get { return this.numberOfColors; } set { if (value < 1) { throw new ArgumentOutOfRangeException("Invalid number!"); } this.numberOfColors = value; } } } }
22.30303
105
0.40625
[ "MIT" ]
TeeeeeC/TelerikAcademy2015-2016
03. OOP/01. DefiningClassesPart1/GSMCallHistoryTest/Display.cs
2,210
C#
using System.Threading.Tasks; using AElf.Kernel.Blockchain.Application; using AElf.Kernel.SmartContract.Application; using AElf.Kernel.Txn.Application; using AElf.Types; using Microsoft.Extensions.Logging; namespace AElf.Kernel.TransactionPool.Application { internal class TransactionToAddressValidationProvider : ITransactionValidationProvider { public bool ValidateWhileSyncing => false; private readonly IDeployedContractAddressProvider _deployedContractAddressProvider; private readonly IBlockchainService _blockchainService; public ILogger<TransactionToAddressValidationProvider> Logger { get; set; } public TransactionToAddressValidationProvider(IDeployedContractAddressProvider deployedContractAddressProvider, IBlockchainService blockchainService) { _deployedContractAddressProvider = deployedContractAddressProvider; _blockchainService = blockchainService; } public async Task<bool> ValidateTransactionAsync(Transaction transaction) { var chain = await _blockchainService.GetChainAsync(); var chainContext = new ChainContext { BlockHash = chain.BestChainHash, BlockHeight = chain.BestChainHeight }; if (_deployedContractAddressProvider.CheckContractAddress(chainContext, transaction.To)) { return true; } Logger.LogWarning($"Invalid contract address: {transaction}"); return false; } } }
36.883721
119
0.702396
[ "MIT" ]
380086154/AElf
src/AElf.Kernel.TransactionPool/Application/TransactionToAddressValidationProvider.cs
1,586
C#
namespace SPICA.PICA.Commands { public enum PICATextureCombinerColorOp { Color = 0, OneMinusColor = 1, Alpha = 2, OneMinusAlpha = 3, Red = 4, OneMinusRed = 5, Green = 8, OneMinusGreen = 9, Blue = 12, OneMinusBlue = 13 } }
18.529412
42
0.501587
[ "Unlicense" ]
AkelaSnow/SPICA
SPICA/PICA/Commands/PICATextureCombinerColorOp.cs
317
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00021643", true, 0xE1FF)] [Attributes(9)] public class LteB41TxGainIndex0 { [ElementsCount(64)] [ElementType("uint16")] [Description("")] public ushort[] Value { get; set; } } }
21.666667
60
0.615385
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/LteB41TxGainIndex0I.cs
455
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\IEntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The interface IPlannerPlansCollectionPage. /// </summary> [JsonConverter(typeof(InterfaceConverter<PlannerPlansCollectionPage>))] public interface IPlannerPlansCollectionPage : ICollectionPage<PlannerPlan> { /// <summary> /// Gets the next page <see cref="IPlannerPlansCollectionRequest"/> instance. /// </summary> IPlannerPlansCollectionRequest NextPageRequest { get; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString); } }
37.28125
153
0.606035
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IPlannerPlansCollectionPage.cs
1,193
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Ecs.Model.V20140526; namespace Aliyun.Acs.Ecs.Transform.V20140526 { public class CreateActivationResponseUnmarshaller { public static CreateActivationResponse Unmarshall(UnmarshallerContext _ctx) { CreateActivationResponse createActivationResponse = new CreateActivationResponse(); createActivationResponse.HttpResponse = _ctx.HttpResponse; createActivationResponse.RequestId = _ctx.StringValue("CreateActivation.RequestId"); createActivationResponse.ActivationId = _ctx.StringValue("CreateActivation.ActivationId"); createActivationResponse.ActivationCode = _ctx.StringValue("CreateActivation.ActivationCode"); return createActivationResponse; } } }
38.833333
97
0.767627
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Transform/V20140526/CreateActivationResponseUnmarshaller.cs
1,631
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Owin; using Whitelist_Administration_Tool.Models; namespace Whitelist_Administration_Tool.Account { public partial class Manage : System.Web.UI.Page { protected string SuccessMessage { get; private set; } private bool HasPassword(ApplicationUserManager manager) { return manager.HasPassword(User.Identity.GetUserId()); } public bool HasPhoneNumber { get; private set; } public bool TwoFactorEnabled { get; private set; } public bool TwoFactorBrowserRemembered { get; private set; } public int LoginsCount { get; set; } protected void Page_Load() { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(User.Identity.GetUserId())); // Enable this after setting up two-factor authentientication //PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty; TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId()); LoginsCount = manager.GetLogins(User.Identity.GetUserId()).Count; var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; if (!IsPostBack) { // Determine the sections to render if (HasPassword(manager)) { ChangePassword.Visible = true; } else { CreatePassword.Visible = true; ChangePassword.Visible = false; } // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); SuccessMessage = message == "ChangePwdSuccess" ? "Your password has been changed." : message == "SetPwdSuccess" ? "Your password has been set." : message == "RemoveLoginSuccess" ? "The account was removed." : message == "AddPhoneNumberSuccess" ? "Phone number has been added" : message == "RemovePhoneNumberSuccess" ? "Phone number was removed" : String.Empty; successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage); } } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } // Remove phonenumber from user protected void RemovePhone_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var result = manager.SetPhoneNumber(User.Identity.GetUserId(), null); if (!result.Succeeded) { return; } var user = manager.FindById(User.Identity.GetUserId()); if (user != null) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess"); } } // DisableTwoFactorAuthentication protected void TwoFactorDisable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), false); Response.Redirect("/Account/Manage"); } //EnableTwoFactorAuthentication protected void TwoFactorEnable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), true); Response.Redirect("/Account/Manage"); } } }
36.054688
101
0.587866
[ "MIT" ]
TannerBragg/MinecraftWhitelistAdminTool
src/UI/Whitelist Administration Tool/Whitelist Administration Tool/Account/Manage.aspx.cs
4,617
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using GAPoTNumLib.Text.Linear.LineHeader; namespace GAPoTNumLib.Text.Linear { public class LinearTextComposer { /// <summary> /// The list of lines added to the text log /// </summary> private readonly List<string> _lines = new List<string>(); /// <summary> /// The log line buffer holding the last line to be appended to /// </summary> private readonly StringBuilder _newLine = new StringBuilder(512); /// <summary> /// The list of line header objects to be added to each line in the log /// </summary> private readonly List<LtcLineHeader> _lineHeaders = new List<LtcLineHeader>(); /// <summary> /// The indentation header object /// </summary> private readonly LtcStackIndentation _indentation = new LtcStackIndentation(); /// <summary> /// The separator of each two header objects text /// </summary> public string LineHeadersSeparator { get; set; } /// <summary> /// If set to true a call to ToString() method clears the contents of this text builder /// </summary> public bool ClearOnRead { get; set; } /// <summary> /// The current number of lines in the log including the log line buffer if not empty /// </summary> public int LinesCount => _newLine.Length > 0 ? _lines.Count + 1 : _lines.Count; /// <summary> /// The current number of lines in the log not including the log line buffer /// </summary> public int StoredLinesCount => _lines.Count; /// <summary> /// Get a list of all lines in the log including the contents of the log line buffer if not empty /// </summary> public IEnumerable<string> LinesText { get { foreach (var line in _lines) yield return line; if (_newLine.Length > 0) yield return _newLine.ToString(); } } /// <summary> /// Get a list of all lines in the log not including the contents of the log line buffer /// </summary> public IEnumerable<string> StoredLinesText => _lines; /// <summary> /// Get the contents of the log line buffer /// </summary> public string LineBufferText => _newLine.ToString(); /// <summary> /// Get the current indentation width /// </summary> public int IndentationWidth => _indentation.IndentationWidth; /// <summary> /// Get the current indentation level /// </summary> public int IndentationLevel => _indentation.IndentationLevel; /// <summary> /// Get or set the default indentation string /// </summary> public string IndentationDefault { get { return _indentation.DefaultIndentation; } set { _indentation.DefaultIndentation = value; } } /// <summary> /// Get the current full indentation string /// </summary> public string IndentationString => _indentation.IndentationString; /// <summary> /// The current text in the log. This does not clear the contents of the log. The ToString() method /// returns the same value but clears the log completely. /// </summary> public string CurrentText { get { var s = new StringBuilder(); foreach (var line in _lines) s.AppendLine(line); if (_newLine.Length > 0) s.Append(_newLine); return s.ToString(); } } /// <summary> /// Increase the indentation by one level using the default indentation /// </summary> /// <returns>The current indentation level</returns> public LinearTextComposer IncreaseIndentation() { _indentation.PushIndentation(); return this; } /// <summary> /// Increase the indentation by one level using the given string /// </summary> /// <param name="indent"></param> /// <returns></returns> public LinearTextComposer IncreaseIndentation(string indent) { if (string.IsNullOrEmpty(indent)) _indentation.PushIndentation(); else _indentation.PushIndentation(indent); return this; } /// <summary> /// Decrease the indentation by one level /// </summary> /// <returns>The current indentation level</returns> public LinearTextComposer DecreaseIndentation() { _indentation.PopIndentation(); return this; } /// <summary> /// Clear the indentation line header object /// </summary> public LinearTextComposer ClearIndentation() { _indentation.Reset(); return this; } /// <summary> /// Clear the log lines and line buffer and reset all header objects without removing any of them /// </summary> public virtual LinearTextComposer Clear() { _indentation.Reset(); _lines.Clear(); _newLine.Clear(); _newLine.Capacity = 512; foreach (var lineHeader in _lineHeaders) lineHeader.Reset(); return this; } /// <summary> /// Remove all text from log including last line without resetting any of the indentation or line header objects /// </summary> public LinearTextComposer ClearText() { _lines.Clear(); _newLine.Clear(); return this; } /// <summary> /// Clear the log line buffer only /// </summary> public LinearTextComposer ClearLastLine() { _newLine.Clear(); return this; } /// <summary> /// Remove i characters from the right of the log string /// </summary> /// <param name="i">The number of characters to be removed</param> public LinearTextComposer Trim(int i) { _newLine.Length = Math.Max(_newLine.Length - i, 0); return this; } /// <summary> /// Append the line header text using the header objects to the log line buffer /// </summary> private void AppendLineHeader() { foreach (var lineHeader in _lineHeaders) { _newLine.Append(lineHeader.GetHeaderText()); _newLine.Append(LineHeadersSeparator); } _newLine.Append(_indentation.IndentationString); } /// <summary> /// Append a full empty line to the log line buffer and add the buffer to the log lines then clear the buffer /// </summary> public LinearTextComposer AppendLine() { if (_newLine.Length == 0) AppendLineHeader(); _lines.Add(_newLine.ToString()); _newLine.Clear(); return this; } /// <summary> /// Append a full line of text to the log line buffer and add the buffer to the log lines then clear the buffer /// </summary> public LinearTextComposer AppendNewLine() { return AppendLine(); } public LinearTextComposer AppendSpaces(int n = 1) { return Append("".PadLeft(n, ' ')); } public LinearTextComposer AppendCharacters(char c, int n = 1) { return Append("".PadLeft(n, c)); } /// <summary> /// Make sure the log line buffer is currently empty by adding it to the log lines if it has text /// </summary> public LinearTextComposer AppendAtNewLine() { if (_newLine.Length > 0) AppendLine(); return this; } /// <summary> /// If the log line buffer is empty this function just appends a full empty new line. /// If the log line buffer is not empty this function first adds the buffer to the log lines then appends a full empty new line. /// </summary> public LinearTextComposer AppendLineAtNewLine() { if (_newLine.Length > 0) AppendLine(); return AppendLine(); } /// <summary> /// Append a number of empty lines at the end of this linear text composer /// If the buffer is not empty it's contents are added to the text before /// adding the empty lines /// </summary> /// <param name="n"></param> /// <returns></returns> public LinearTextComposer AppendEmptyLines(int n) { if (n < 1) return this; if (_newLine.Length > 0) AppendLine(); while (n > 0) { AppendLine(); n--; } return this; } /// <summary> /// Append text to the log line buffer and add more lines if needed (if text is multi-line) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="text"></param> /// <returns></returns> public LinearTextComposer Append<T>(T text) { if (ReferenceEquals(text, null)) return this; return Append(text.ToString()); } /// <summary> /// Append text to the log line buffer and add more lines if needed (if text is multi-line) /// </summary> /// <param name="text">The text to be added</param> public LinearTextComposer Append(string text) { if (string.IsNullOrEmpty(text)) return this; //Separate the input text into lines var lines = text.SplitLines(); //Each line will be added separately for (var i = 0; i < lines.Length; i++) { //For the first line of added text, if the log line buffer is empty add the line header //Do the same for all following added text lines. if (i > 0 || (i == 0 && _newLine.Length == 0))//(i > 0 && i < lines.Length - 1)) AppendLineHeader(); //Append the added text line to the log line buffer _newLine.Append(lines[i]); //For all added lined except the last one, add the log line buffer to the log and clear the buffer if (i >= lines.Length - 1) continue; _lines.Add(_newLine.ToString()); _newLine.Clear(); } return this; } /// <summary> /// Append a full line of text to the log line buffer and add the buffer to the log lines then clear the buffer /// </summary> /// <typeparam name="T"></typeparam> /// <param name="text"></param> /// <returns></returns> public LinearTextComposer AppendLine<T>(T text) { if (ReferenceEquals(text, null)) return AppendLine(); return AppendLine(text.ToString()); } /// <summary> /// Append a full line of text to the log line buffer and add the buffer to the log lines then clear the buffer /// </summary> /// <param name="text">The text to be appended</param> public LinearTextComposer AppendLine(string text) { Append(text); return AppendLine(); } /// <summary> /// Append a full empty line to the log line buffer and then append text to the buffer /// </summary> /// <typeparam name="T"></typeparam> /// <param name="text"></param> /// <returns></returns> public LinearTextComposer AppendNewLine<T>(T text) { if (ReferenceEquals(text, null)) return AppendNewLine(); return AppendNewLine(text.ToString()); } /// <summary> /// Append a full empty line to the log line buffer and then append text to the buffer /// </summary> /// <param name="text">The text to be appended</param> public LinearTextComposer AppendNewLine(string text) { AppendLine(); return Append(text); } /// <summary> /// If the log line buffer is empty this function just appends the text to the buffer. /// If the log line buffer is not empty this function first adds the buffer to the log lines then appends the text /// </summary> /// <typeparam name="T"></typeparam> /// <param name="text"></param> /// <returns></returns> public LinearTextComposer AppendAtNewLine<T>(T text) { if (ReferenceEquals(text, null)) return AppendAtNewLine(); return AppendAtNewLine(text.ToString()); } /// <summary> /// If the log line buffer is empty this function just appends the text to the buffer. /// If the log line buffer is not empty this function first adds the buffer to the log lines then appends the text /// </summary> /// <param name="text">The text to be appended</param> public LinearTextComposer AppendAtNewLine(string text) { if (_newLine.Length > 0) AppendLine(); return Append(text); } /// <summary> /// If the log line buffer is empty this function just appends the text to the buffer as a full new line. /// If the log line buffer is not empty this function first adds the buffer to the log lines then appends the text as a full new line. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="text"></param> /// <returns></returns> public LinearTextComposer AppendLineAtNewLine<T>(T text) { if (ReferenceEquals(text, null)) return AppendLineAtNewLine(); return AppendLineAtNewLine(text.ToString()); } /// <summary> /// If the log line buffer is empty this function just appends the text to the buffer as a full new line. /// If the log line buffer is not empty this function first adds the buffer to the log lines then appends the text as a full new line. /// </summary> /// <param name="text"></param> public LinearTextComposer AppendLineAtNewLine(string text) { if (_newLine.Length > 0) AppendLine(); return AppendLine(text); } /// <summary> /// Create and add a line counter header object to the header objects of the log /// </summary> /// <returns>The added header object</returns> public LtcLineCount AddLineCountHeader() { var lineHeader = new LtcLineCount(this); _lineHeaders.Add(lineHeader); return lineHeader; } /// <summary> /// Create and add a line counter header object to the header objects of the log /// </summary> /// <param name="formatString"></param> /// <returns>The added header object</returns> public LtcLineCount AddLineCountHeader(string formatString) { var lineHeader = new LtcLineCount(this, formatString); _lineHeaders.Add(lineHeader); return lineHeader; } public LtcTimeStamp AddTimeStampHeader() { var lineHeader = new LtcTimeStamp(); _lineHeaders.Add(lineHeader); return lineHeader; } public LtcTimeStamp AddTimeStampHeader(string formatString) { var lineHeader = new LtcTimeStamp(formatString); _lineHeaders.Add(lineHeader); return lineHeader; } public LtcStopWatch AddStopWatchHeader() { var lineHeader = new LtcStopWatch(); _lineHeaders.Add(lineHeader); return lineHeader; } public LtcStopWatch AddStopWatchHeader(bool resetOnRead) { var lineHeader = new LtcStopWatch() { ResetOnRead = resetOnRead }; _lineHeaders.Add(lineHeader); return lineHeader; } public LtcStopWatch AddStopWatchHeader(string formatString) { var lineHeader = new LtcStopWatch(formatString); _lineHeaders.Add(lineHeader); return lineHeader; } public LtcStopWatch AddStopWatchHeader(bool resetOnRead, string formatString) { var lineHeader = new LtcStopWatch(formatString) { ResetOnRead = resetOnRead }; _lineHeaders.Add(lineHeader); return lineHeader; } public LtcLineHeader AddLineHeader(LtcLineHeader lineHeader) { _lineHeaders.Add(lineHeader); return lineHeader; } /// <summary> /// Save the full text of the log into a text file /// </summary> /// <param name="fileName">The path of the text file to be saved</param> public void SaveToFile(string fileName) { File.WriteAllText(fileName, ToString()); } /// <summary> /// Append the full text of the log into a text file /// </summary> /// <param name="fileName"></param> public void AppendToFile(string fileName) { File.AppendAllText(fileName, ToString()); } /// <summary> /// Append the full text of the log into a text stream /// </summary> /// <param name="stream"></param> public void AppendToStream(TextWriter stream) { stream.Write(ToString()); } public override string ToString() { var curText = CurrentText; if (ClearOnRead) Clear(); return curText; } } }
30.838063
142
0.548452
[ "MIT" ]
ga-explorer/GAPoTNumLib
GAPoTNumLib/GAPoTNumLib/Text/Linear/LinearTextComposer.cs
18,474
C#
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ApacheJenaSample.Csv.Aotp.Mapper; using ApacheJenaSample.Csv.Aotp.Model; using TinyCsvParser; namespace ApacheJenaSample.Csv.Aotp.Parser { public static class Parsers { public static CsvParser<Flight> FlightStatisticsParser { get { CsvParserOptions csvParserOptions = new CsvParserOptions(true, ','); return new CsvParser<Flight>(csvParserOptions, new FlightMapper()); } } public static CsvParser<Airport> AirportParser { get { CsvParserOptions csvParserOptions = new CsvParserOptions(true, ','); return new CsvParser<Airport>(csvParserOptions, new AirportMapper()); } } public static CsvParser<Carrier> CarrierParser { get { CsvParserOptions csvParserOptions = new CsvParserOptions(true, ','); return new CsvParser<Carrier>(csvParserOptions, new CarrierMapper()); } } } }
29.261905
101
0.603743
[ "MIT" ]
bytefish/ApacheJenaSample
ApacheJenaSample/ApacheJenaSample.Csv.Aotp/Parser/Parsers.cs
1,229
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Solution.Base.Implementation.DTOs { public class WebApiPagedRequestDTO : BaseDTO { [JsonIgnore] public int PageSize { get { return Rows; } set { Rows = value; } } // no. of records to fetch public int Rows { get; set; } // the page index public int Page { get; set; } [JsonIgnore] public string OrderBy { get { return Sidx; } set { Sidx = value; } } // sort column name public string Sidx { get; set; } [JsonIgnore] public string OrderType { get { return Sord; } set { Sord = value; } } // sort order "asc" or "desc" public string Sord { get; set; } public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
21.035714
99
0.535654
[ "MIT" ]
davidikin45/DigitalNomadDave
Solution.Base/Implementation/DTOs/WebApiPagedRequestDTO.cs
1,180
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.Build.Framework; using Microsoft.Build.Logging.StructuredLogger; using NUnit.Framework; using Xamarin.ProjectTools; namespace Xamarin.Android.Build.Tests { [TestFixture, NonParallelizable] public class PerformanceTest : DeviceTest { const int Retry = 2; static readonly Dictionary<string, int> csv_values = new Dictionary<string, int> (); [OneTimeSetUp] public static void Setup () { var csv = Path.Combine (XABuildPaths.TopDirectory, "tests", "msbuild-times-reference", "MSBuildDeviceIntegration.csv"); using (var reader = File.OpenText (csv)) { bool foundHeader = false; while (!reader.EndOfStream) { var line = reader.ReadLine (); if (line.StartsWith ("#") || string.IsNullOrWhiteSpace (line)) { continue; } var split = line.Split (','); Assert.AreEqual (2, split.Length, $"{csv} should have two entries per line."); if (!foundHeader) { // Ignore the first-line header foundHeader = true; continue; } string text = split [1]; if (int.TryParse (text, out int value)) { csv_values [split [0]] = value; } else { Assert.Fail ($"'{text}' is not a valid integer!"); } } } } void Profile (ProjectBuilder builder, Action<ProjectBuilder> action, [CallerMemberName] string caller = null) { if (!csv_values.TryGetValue (caller, out int expected)) { Assert.Fail ($"No timeout value found for a key of {caller}"); } if (Builder.UseDotNet) { //TODO: there is currently a slight performance regression in .NET 6 expected += 500; } action (builder); var actual = GetDurationFromBinLog (builder); TestContext.Out.WriteLine($"expected: {expected}ms, actual: {actual}ms"); if (actual > expected) { Assert.Fail ($"Exceeded expected time of {expected}ms, actual {actual}ms"); } } double GetDurationFromBinLog (ProjectBuilder builder) { var binlog = Path.Combine (Root, builder.ProjectDirectory, "msbuild.binlog"); FileAssert.Exists (binlog); var build = BinaryLog.ReadBuild (binlog); var duration = build .FindChildrenRecursive<Project> () .Aggregate (TimeSpan.Zero, (duration, project) => duration + project.Duration); if (duration == TimeSpan.Zero) throw new InvalidDataException ($"No project build duration found in {binlog}"); return duration.TotalMilliseconds; } ProjectBuilder CreateBuilderWithoutLogFile (string directory = null, bool isApp = true) { var builder = isApp ? CreateApkBuilder (directory) : CreateDllBuilder (directory); builder.BuildLogFile = null; builder.Verbosity = LoggerVerbosity.Quiet; return builder; } XamarinAndroidApplicationProject CreateApplicationProject () { var proj = new XamarinAndroidApplicationProject () { }; proj.SetAndroidSupportedAbis ("x86"); // Use a single ABI return proj; } [Test] [Retry (Retry)] public void Build_From_Clean_DontIncludeRestore () { var proj = CreateApplicationProject (); using (var builder = CreateBuilderWithoutLogFile ()) { builder.AutomaticNuGetRestore = false; builder.Target = "Build"; builder.Restore (proj); Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_No_Changes () { var proj = CreateApplicationProject (); proj.MainActivity = proj.DefaultMainActivity; using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile no changes Profile (builder, b => b.Build (proj)); // Change C# and build proj.MainActivity += $"{Environment.NewLine}//comment"; proj.Touch ("MainActivity.cs"); builder.Build (proj); // Profile no changes Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_CSharp_Change () { var proj = CreateApplicationProject (); proj.MainActivity = proj.DefaultMainActivity; using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile C# change proj.MainActivity += $"{Environment.NewLine}//comment"; proj.Touch ("MainActivity.cs"); Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_AndroidResource_Change () { var proj = CreateApplicationProject (); using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile AndroidResource change proj.LayoutMain += $"{Environment.NewLine}<!--comment-->"; proj.Touch ("Resources\\layout\\Main.axml"); Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_AndroidAsset_Change () { var bytes = new byte [1024*1024*10]; var rnd = new Random (); rnd.NextBytes (bytes); var lib = new XamarinAndroidLibraryProject () { ProjectName = "Library1", }; lib.OtherBuildItems.Add (new AndroidItem.AndroidAsset ("Assets\\foo.bar") { BinaryContent = () => bytes, }); var proj = CreateApplicationProject (); proj.ProjectName = "App1"; proj.References.Add (new BuildItem.ProjectReference ("..\\Library1\\Library1.csproj")); rnd.NextBytes (bytes); proj.OtherBuildItems.Add (new AndroidItem.AndroidAsset ("Assets\\foo.bar") { BinaryContent = () => bytes, }); using (var libBuilder = CreateBuilderWithoutLogFile (Path.Combine ("temp", TestName, lib.ProjectName), isApp: false)) using (var builder = CreateBuilderWithoutLogFile (Path.Combine ("temp", TestName, proj.ProjectName))) { builder.Target = "Build"; libBuilder.Build (lib); builder.Build (proj); libBuilder.AutomaticNuGetRestore = builder.AutomaticNuGetRestore = false; rnd.NextBytes (bytes); lib.Touch ("Assets\\foo.bar"); libBuilder.Build (lib); builder.Target = "SignAndroidPackage"; // Profile AndroidAsset change Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_Designer_Change () { var proj = CreateApplicationProject (); using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Change AndroidResource & run SetupDependenciesForDesigner proj.LayoutMain += $"{Environment.NewLine}<!--comment-->"; proj.Touch ("Resources\\layout\\Main.axml"); var parameters = new [] { "DesignTimeBuild=True", "AndroidUseManagedDesignTimeResourceGenerator=False" }; builder.RunTarget (proj, "SetupDependenciesForDesigner", parameters: parameters); // Profile AndroidResource change Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_JLO_Change () { var className = "Foo"; var proj = CreateApplicationProject (); proj.Sources.Add (new BuildItem.Source ("Foo.cs") { TextContent = () => $"class {className} : Java.Lang.Object {{}}" }); using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile Java.Lang.Object rename className = "Foo2"; proj.Touch ("Foo.cs"); Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_AndroidManifest_Change () { var proj = CreateApplicationProject (); using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile AndroidManifest.xml change proj.AndroidManifest += $"{Environment.NewLine}<!--comment-->"; proj.Touch ("Properties\\AndroidManifest.xml"); Profile (builder, b => b.Build (proj)); } } [Test] [Retry (Retry)] public void Build_CSProj_Change () { var proj = CreateApplicationProject (); using (var builder = CreateBuilderWithoutLogFile ()) { builder.Target = "Build"; builder.Build (proj); builder.AutomaticNuGetRestore = false; // Profile .csproj change proj.Sources.Add (new BuildItem ("None", "Foo.txt") { TextContent = () => "Bar", }); Profile (builder, b => b.Build (proj)); } } static object [] XAML_Change = new object [] { new object [] { /* produceReferenceAssembly */ false, /* install */ false, }, new object [] { /* produceReferenceAssembly */ true, /* install */ false, }, new object [] { /* produceReferenceAssembly */ true, /* install */ true, }, }; [Test] [TestCaseSource (nameof (XAML_Change))] [Category ("UsesDevice")] [Retry (Retry)] public void Build_XAML_Change (bool produceReferenceAssembly, bool install) { if (install) { AssertCommercialBuild (); // This test will fail without Fast Deployment AssertHasDevices (); } var path = Path.Combine ("temp", TestName); var xaml = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" x:Class=""MyLibrary.MyPage""> </ContentPage>"; var caller = nameof (Build_XAML_Change); if (install) { caller = caller.Replace ("Build", "Install"); } else if (produceReferenceAssembly) { caller += "_RefAssembly"; } var app = CreateApplicationProject (); app.ProjectName = "MyApp"; app.Sources.Add (new BuildItem.Source ("Foo.cs") { TextContent = () => "public class Foo : Bar { }" }); //NOTE: this will skip a 382ms <VerifyVersionsTask/> from the support library app.SetProperty ("XamarinAndroidSupportSkipVerifyVersions", "True"); int count = 0; var lib = new DotNetStandard { ProjectName = "MyLibrary", Sdk = "Microsoft.NET.Sdk", TargetFramework = "netstandard2.0", Sources = { new BuildItem.Source ("Bar.cs") { TextContent = () => "public class Bar { public Bar () { System.Console.WriteLine (" + count++ + "); } }" }, new BuildItem ("EmbeddedResource", "MyPage.xaml") { TextContent = () => xaml, } }, PackageReferences = { KnownPackages.XamarinForms_4_0_0_425677 } }; lib.SetProperty ("ProduceReferenceAssembly", produceReferenceAssembly.ToString ()); app.References.Add (new BuildItem.ProjectReference ($"..\\{lib.ProjectName}\\{lib.ProjectName}.csproj", lib.ProjectName, lib.ProjectGuid)); using (var libBuilder = CreateBuilderWithoutLogFile (Path.Combine (path, lib.ProjectName), isApp: false)) using (var appBuilder = CreateBuilderWithoutLogFile (Path.Combine (path, app.ProjectName))) { libBuilder.Build (lib); appBuilder.Target = "Build"; if (install) { appBuilder.Install (app); } else { appBuilder.Build (app); } libBuilder.AutomaticNuGetRestore = appBuilder.AutomaticNuGetRestore = false; // Profile XAML change xaml += $"{Environment.NewLine}<!--comment-->"; lib.Touch ("MyPage.xaml"); libBuilder.Build (lib, doNotCleanupOnUpdate: true); if (install) { Profile (appBuilder, b => b.Install (app, doNotCleanupOnUpdate: true), caller); } else { Profile (appBuilder, b => b.Build (app, doNotCleanupOnUpdate: true), caller); } } } [Test] [Category ("UsesDevice")] [Retry (Retry)] public void Install_CSharp_Change () { AssertCommercialBuild (); // This test will fail without Fast Deployment AssertHasDevices (); var proj = CreateApplicationProject (); proj.PackageName = "com.xamarin.install_csharp_change"; proj.MainActivity = proj.DefaultMainActivity; using (var builder = CreateBuilderWithoutLogFile ()) { builder.Install (proj); builder.AutomaticNuGetRestore = false; // Profile C# change proj.MainActivity += $"{Environment.NewLine}//comment"; proj.Touch ("MainActivity.cs"); Profile (builder, b => b.Install (proj)); } } } }
30.674185
142
0.660103
[ "MIT" ]
explorest/xamarin-android
tests/MSBuildDeviceIntegration/Tests/PerformanceTest.cs
12,239
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Infrastructure.Migrations { public partial class Update1 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Creators", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Username = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false), UsernameNormalize = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false), Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false), Bio = table.Column<string>(type: "nvarchar(140)", maxLength: 140, nullable: false), Salt = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), AccountXAddress = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), AccountSecret = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), AccountClassicAddress = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), AccountAddress = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), IsAccountValid = table.Column<bool>(type: "bit", nullable: false), DateAccountAcquired = table.Column<DateTime>(type: "datetime2", nullable: false), DateRegistered = table.Column<DateTime>(type: "datetime2", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Creators", x => x.Id); }); migrationBuilder.CreateTable( name: "CreatorPasswords", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CreatorId = table.Column<int>(type: "int", nullable: false), Salt = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), Digest = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_CreatorPasswords", x => x.Id); table.ForeignKey( name: "FK_CreatorPasswords_Creators_CreatorId", column: x => x.CreatorId, principalTable: "Creators", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CreatorSubscribers", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CreatorId = table.Column<int>(type: "int", nullable: false), SubsciberId = table.Column<int>(type: "int", nullable: true) }, constraints: table => { table.PrimaryKey("PK_CreatorSubscribers", x => x.Id); table.ForeignKey( name: "FK_CreatorSubscribers_Creators_CreatorId", column: x => x.CreatorId, principalTable: "Creators", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_CreatorSubscribers_Creators_SubsciberId", column: x => x.SubsciberId, principalTable: "Creators", principalColumn: "Id"); }); migrationBuilder.CreateIndex( name: "IX_CreatorPasswords_CreatorId", table: "CreatorPasswords", column: "CreatorId"); migrationBuilder.CreateIndex( name: "IX_Creators_Username", table: "Creators", column: "Username", unique: true); migrationBuilder.CreateIndex( name: "IX_Creators_UsernameNormalize", table: "Creators", column: "UsernameNormalize", unique: true); migrationBuilder.CreateIndex( name: "IX_CreatorSubscribers_CreatorId", table: "CreatorSubscribers", column: "CreatorId"); migrationBuilder.CreateIndex( name: "IX_CreatorSubscribers_SubsciberId", table: "CreatorSubscribers", column: "SubsciberId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "CreatorPasswords"); migrationBuilder.DropTable( name: "CreatorSubscribers"); migrationBuilder.DropTable( name: "Creators"); } } }
45.346774
121
0.514138
[ "MIT" ]
mecvillarina/Vider
src/backend/Infrastructure/Migrations/20220220090508_Update1.cs
5,625
C#
// <auto-generated /> namespace Musicas.AcessoDados.Entity.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.4.4")] public sealed partial class AdicaoMusica : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AdicaoMusica)); string IMigrationMetadata.Id { get { return "202101261438547_AdicaoMusica"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.633333
95
0.623643
[ "MIT" ]
guiagostini/Cursos-Tutoriais
Musicas/Musicas.AcessoDados.Entity/Migrations/202101261438547_AdicaoMusica.Designer.cs
831
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Rancher2.Inputs { public sealed class ClusterRkeConfigCloudProviderAwsCloudProviderGlobalArgs : Pulumi.ResourceArgs { /// <summary> /// Default `false` (bool) /// </summary> [Input("disableSecurityGroupIngress")] public Input<bool>? DisableSecurityGroupIngress { get; set; } /// <summary> /// Default `false` (bool) /// </summary> [Input("disableStrictZoneCheck")] public Input<bool>? DisableStrictZoneCheck { get; set; } /// <summary> /// (string) /// </summary> [Input("elbSecurityGroup")] public Input<string>? ElbSecurityGroup { get; set; } /// <summary> /// (string) /// </summary> [Input("kubernetesClusterId")] public Input<string>? KubernetesClusterId { get; set; } /// <summary> /// (string) /// </summary> [Input("kubernetesClusterTag")] public Input<string>? KubernetesClusterTag { get; set; } /// <summary> /// (string) /// </summary> [Input("roleArn")] public Input<string>? RoleArn { get; set; } /// <summary> /// (string) /// </summary> [Input("routeTableId")] public Input<string>? RouteTableId { get; set; } /// <summary> /// (string) /// </summary> [Input("subnetId")] public Input<string>? SubnetId { get; set; } /// <summary> /// (string) /// </summary> [Input("vpc")] public Input<string>? Vpc { get; set; } /// <summary> /// The GKE cluster zone. Required if `region` not set (string) /// </summary> [Input("zone")] public Input<string>? Zone { get; set; } public ClusterRkeConfigCloudProviderAwsCloudProviderGlobalArgs() { } } }
27.8875
101
0.550426
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-rancher2
sdk/dotnet/Inputs/ClusterRkeConfigCloudProviderAwsCloudProviderGlobalArgs.cs
2,231
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingSpecialMember : CSharpTestBase { [Fact] public void Missing_System_Collections_Generic_IEnumerable_T__GetEnumerator() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateStandardCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerable`1.GetEnumerator' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.Collections.Generic.IEnumerable`1", "GetEnumerator").WithLocation(10, 5) ); } [Fact] public void Missing_System_IDisposable__Dispose() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateStandardCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose); comp.VerifyEmitDiagnostics( // (10,5): error CS0656: Missing compiler required member 'System.IDisposable.Dispose' // { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{ yield return 0; yield return 1; }").WithArguments("System.IDisposable", "Dispose").WithLocation(10, 5) ); } [Fact] public void Missing_System_Diagnostics_DebuggerHiddenAttribute__ctor() { var source = @"using System.Collections.Generic; public class Program { public static void Main(string[] args) { } public IEnumerable<int> M() { yield return 0; yield return 1; } }"; var comp = CreateStandardCompilation(source, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // the DebuggerHidden attribute is optional. ); } [Fact] public void Missing_System_Runtime_CompilerServices_ExtensionAttribute__ctor() { var source = @"using System.Collections.Generic; public static class Program { public static void Main(string[] args) { } public static void Extension(this string x) {} }"; var comp = CreateCompilation(source, new[] { MscorlibRef }, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor); comp.VerifyEmitDiagnostics( // (9,34): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? // public static void Extension(this string x) {} Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(9, 34) ); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialType() { var source = @" namespace System { public class Object { public Object() { } } internal class String : Object { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_String); Assert.Equal(TypeKind.Error, specialType.TypeKind); Assert.Equal(SpecialType.System_String, specialType.SpecialType); Assert.Equal(Accessibility.NotApplicable, specialType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.String"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(SpecialType.None, lookupType.SpecialType); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(source, validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicSpecialTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} {0} virtual String ToString() {{ return null; }} }} {0} class String : Object {{ public static String Concat(String s1, String s2) {{ return null; }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; Action<CSharpCompilation> validateMissing = comp => { Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)); Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public"), validatePresent); ValidateSourceAndMetadata(string.Format(sourceTemplate, "internal"), validateMissing); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnSpecialType() { var source = @" namespace System { public class Object { public Object() { } } public struct Nullable<T> where T : new() { } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var specialType = comp.GetSpecialType(SpecialType.System_Nullable_T); Assert.Equal(TypeKind.Struct, specialType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, specialType.SpecialType); var lookupType = comp.GetTypeByMetadataName("System.Nullable`1"); Assert.Equal(TypeKind.Struct, lookupType.TypeKind); Assert.Equal(SpecialType.System_Nullable_T, lookupType.SpecialType); }; ValidateSourceAndMetadata(source, validate); } // No special type members have type parameters that could (incorrectly) be constrained. [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } internal class Type : Object { } public class ValueType { } public struct Void { } } "; var comp = CreateCompilation(source); var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Type); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); Assert.Equal(Accessibility.Internal, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Type"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); Assert.Equal(Accessibility.Internal, lookupType.DeclaredAccessibility); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownType_Nested() { var sourceTemplate = @" namespace System.Diagnostics {{ {0} class DebuggableAttribute {{ {1} enum DebuggingModes {{ }} }} }} namespace System {{ public class Object {{ }} public class ValueType {{ }} public class Enum : ValueType {{ }} public struct Void {{ }} public struct Int32 {{ }} }} "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); Assert.Equal(TypeKind.Error, wellKnownType.TypeKind); Assert.Equal(Accessibility.NotApplicable, wellKnownType.DeclaredAccessibility); var lookupType = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes"); Assert.Equal(TypeKind.Enum, lookupType.TypeKind); Assert.NotEqual(Accessibility.NotApplicable, lookupType.DeclaredAccessibility); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "protected"), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, "public", "private"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void NonPublicWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} {0} class Type : Object {{ public static readonly Object Missing = new Object(); }} public static class Math : Object {{ {0} static Double Round(Double d) {{ return d; }} }} public class ValueType {{ }} public struct Void {{ }} public struct Double {{ }} }} "; Action<CSharpCompilation> validatePresent = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)); Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Math__RoundDouble)); comp.GetDiagnostics(); }; validatePresent(CreateCompilation(string.Format(sourceTemplate, "public"))); validatePresent(CreateCompilation(string.Format(sourceTemplate, "internal"))); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownType() { var source = @" namespace System { public class Object { public Object() { } } namespace Threading.Tasks { public class Task<T> where T : new() { } } public class ValueType { } public struct Void { } } "; Action<CSharpCompilation> validate = comp => { var wellKnownType = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); Assert.Equal(TypeKind.Class, wellKnownType.TypeKind); var lookupType = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1"); Assert.Equal(TypeKind.Class, lookupType.TypeKind); }; ValidateSourceAndMetadata(source, validate); } // Document the fact that we don't reject type parameters with constraints (yet?). [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void GenericConstraintsOnWellKnownTypeMember() { var sourceTemplate = @" namespace System {{ public class Object {{ public Object() {{ }} }} namespace Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T t1, T t2, T t3){0} {{ return t1; }} }} }} public class ValueType {{ }} public struct Void {{ }} }} "; Action<CSharpCompilation> validate = comp => { Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T)); comp.GetDiagnostics(); }; ValidateSourceAndMetadata(string.Format(sourceTemplate, ""), validate); ValidateSourceAndMetadata(string.Format(sourceTemplate, " where T : new()"), validate); } [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] [Fact] public void PublicVersusInternalWellKnownType() { var corlibSource = @" namespace System { public class Object { public Object() { } } public class String { } public class Attribute { } public class ValueType { } public struct Void { } } namespace System.Runtime.CompilerServices { public class InternalsVisibleToAttribute : Attribute { public InternalsVisibleToAttribute(String s) { } } } "; var libSourceTemplate = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Test"")] namespace System {{ {0} class Type {{ }} }} "; var corlibRef = CreateCompilation(corlibSource).EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var publicLibRef = CreateCompilation(string.Format(libSourceTemplate, "public"), new[] { corlibRef }).EmitToImageReference(); var internalLibRef = CreateCompilation(string.Format(libSourceTemplate, "internal"), new[] { corlibRef }).EmitToImageReference(); var comp = CreateCompilation("", new[] { corlibRef, publicLibRef, internalLibRef }, assemblyName: "Test"); var wellKnown = comp.GetWellKnownType(WellKnownType.System_Type); Assert.NotNull(wellKnown); Assert.Equal(TypeKind.Class, wellKnown.TypeKind); Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility); var lookup = comp.GetTypeByMetadataName("System.Type"); Assert.Null(lookup); // Ambiguous } private static void ValidateSourceAndMetadata(string source, Action<CSharpCompilation> validate) { var comp1 = CreateCompilation(source); validate(comp1); var reference = comp1.EmitToImageReference(expectedWarnings: new[] { // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) }); var comp2 = CreateCompilation("", new[] { reference }); validate(comp2); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypes() { var comp = CreateCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); for (var special = SpecialType.None + 1; special <= SpecialType.Count; special++) { var symbol = comp.GetSpecialType(special); Assert.NotNull(symbol); Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllSpecialTypeMembers() { var comp = CreateCompilation("", new[] { MscorlibRef_v4_0_30316_17626 }); foreach (SpecialMember special in Enum.GetValues(typeof(SpecialMember))) { if (special == SpecialMember.Count) continue; // Not a real value; var symbol = comp.GetSpecialTypeMember(special); Assert.NotNull(symbol); } } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypes() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateCompilation("", refs); for (var wkt = WellKnownType.First; wkt < WellKnownType.NextAvailable; wkt++) { switch (wkt) { case WellKnownType.Microsoft_VisualBasic_Embedded: case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators: // Not applicable in C#. continue; case WellKnownType.System_FormattableString: case WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory: case WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute: case WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute: case WellKnownType.System_Span_T: // Not yet in the platform. case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation: // Not always available. continue; case WellKnownType.ExtSentinel: // Not a real type continue; } switch (wkt) { case WellKnownType.System_ValueTuple_T1: case WellKnownType.System_ValueTuple_T2: case WellKnownType.System_ValueTuple_T3: case WellKnownType.System_ValueTuple_T4: case WellKnownType.System_ValueTuple_T5: case WellKnownType.System_ValueTuple_T6: case WellKnownType.System_ValueTuple_T7: case WellKnownType.System_ValueTuple_TRest: Assert.True(wkt.IsValueTupleType()); break; default: Assert.False(wkt.IsValueTupleType()); break; } var symbol = comp.GetWellKnownType(wkt); Assert.NotNull(symbol); Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); } } [Fact] public void AllWellKnownTypesBeforeCSharp7() { foreach (var type in new[] { WellKnownType.System_Math, WellKnownType.System_Array, WellKnownType.System_Attribute, WellKnownType.System_CLSCompliantAttribute, WellKnownType.System_Convert, WellKnownType.System_Exception, WellKnownType.System_FlagsAttribute, WellKnownType.System_FormattableString, WellKnownType.System_Guid, WellKnownType.System_IFormattable, WellKnownType.System_RuntimeTypeHandle, WellKnownType.System_RuntimeFieldHandle, WellKnownType.System_RuntimeMethodHandle, WellKnownType.System_MarshalByRefObject, WellKnownType.System_Type, WellKnownType.System_Reflection_AssemblyKeyFileAttribute, WellKnownType.System_Reflection_AssemblyKeyNameAttribute, WellKnownType.System_Reflection_MethodInfo, WellKnownType.System_Reflection_ConstructorInfo, WellKnownType.System_Reflection_MethodBase, WellKnownType.System_Reflection_FieldInfo, WellKnownType.System_Reflection_MemberInfo, WellKnownType.System_Reflection_Missing, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, WellKnownType.System_Runtime_InteropServices_StructLayoutAttribute, WellKnownType.System_Runtime_InteropServices_UnknownWrapper, WellKnownType.System_Runtime_InteropServices_DispatchWrapper, WellKnownType.System_Runtime_InteropServices_CallingConvention, WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, WellKnownType.System_Runtime_InteropServices_CoClassAttribute, WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, WellKnownType.System_Runtime_InteropServices_ComInterfaceType, WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, WellKnownType.System_Runtime_InteropServices_DispIdAttribute, WellKnownType.System_Runtime_InteropServices_GuidAttribute, WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, WellKnownType.System_Runtime_InteropServices_Marshal, WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, WellKnownType.System_Activator, WellKnownType.System_Threading_Tasks_Task, WellKnownType.System_Threading_Tasks_Task_T, WellKnownType.System_Threading_Interlocked, WellKnownType.System_Threading_Monitor, WellKnownType.System_Threading_Thread, WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, WellKnownType.Microsoft_VisualBasic_CallType, WellKnownType.Microsoft_VisualBasic_Embedded, WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, WellKnownType.Microsoft_VisualBasic_CompareMethod, WellKnownType.Microsoft_VisualBasic_Strings, WellKnownType.Microsoft_VisualBasic_ErrObject, WellKnownType.Microsoft_VisualBasic_FileSystem, WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase, WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase, WellKnownType.Microsoft_VisualBasic_Information, WellKnownType.Microsoft_VisualBasic_Interaction, WellKnownType.System_Func_T, WellKnownType.System_Func_T2, WellKnownType.System_Func_T3, WellKnownType.System_Func_T4, WellKnownType.System_Func_T5, WellKnownType.System_Func_T6, WellKnownType.System_Func_T7, WellKnownType.System_Func_T8, WellKnownType.System_Func_T9, WellKnownType.System_Func_T10, WellKnownType.System_Func_T11, WellKnownType.System_Func_T12, WellKnownType.System_Func_T13, WellKnownType.System_Func_T14, WellKnownType.System_Func_T15, WellKnownType.System_Func_T16, WellKnownType.System_Func_T17, WellKnownType.System_Action, WellKnownType.System_Action_T, WellKnownType.System_Action_T2, WellKnownType.System_Action_T3, WellKnownType.System_Action_T4, WellKnownType.System_Action_T5, WellKnownType.System_Action_T6, WellKnownType.System_Action_T7, WellKnownType.System_Action_T8, WellKnownType.System_Action_T9, WellKnownType.System_Action_T10, WellKnownType.System_Action_T11, WellKnownType.System_Action_T12, WellKnownType.System_Action_T13, WellKnownType.System_Action_T14, WellKnownType.System_Action_T15, WellKnownType.System_Action_T16, WellKnownType.System_AttributeUsageAttribute, WellKnownType.System_ParamArrayAttribute, WellKnownType.System_NonSerializedAttribute, WellKnownType.System_STAThreadAttribute, WellKnownType.System_Reflection_DefaultMemberAttribute, WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IUnknownConstantAttribute, WellKnownType.System_Runtime_CompilerServices_IDispatchConstantAttribute, WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, WellKnownType.System_Runtime_CompilerServices_InternalsVisibleToAttribute, WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, WellKnownType.System_Runtime_CompilerServices_CallSite, WellKnownType.System_Runtime_CompilerServices_CallSite_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, WellKnownType.Windows_Foundation_IAsyncAction, WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T, WellKnownType.Windows_Foundation_IAsyncOperation_T, WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2, WellKnownType.System_Diagnostics_Debugger, WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, WellKnownType.System_Diagnostics_DebuggerBrowsableState, WellKnownType.System_Diagnostics_DebuggableAttribute, WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, WellKnownType.System_ComponentModel_DesignerSerializationVisibilityAttribute, WellKnownType.System_IEquatable_T, WellKnownType.System_Collections_IList, WellKnownType.System_Collections_ICollection, WellKnownType.System_Collections_Generic_EqualityComparer_T, WellKnownType.System_Collections_Generic_List_T, WellKnownType.System_Collections_Generic_IDictionary_KV, WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV, WellKnownType.System_Collections_ObjectModel_Collection_T, WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T, WellKnownType.System_Collections_Specialized_INotifyCollectionChanged, WellKnownType.System_ComponentModel_INotifyPropertyChanged, WellKnownType.System_ComponentModel_EditorBrowsableAttribute, WellKnownType.System_ComponentModel_EditorBrowsableState, WellKnownType.System_Linq_Enumerable, WellKnownType.System_Linq_Expressions_Expression, WellKnownType.System_Linq_Expressions_Expression_T, WellKnownType.System_Linq_Expressions_ParameterExpression, WellKnownType.System_Linq_Expressions_ElementInit, WellKnownType.System_Linq_Expressions_MemberBinding, WellKnownType.System_Linq_Expressions_ExpressionType, WellKnownType.System_Linq_IQueryable, WellKnownType.System_Linq_IQueryable_T, WellKnownType.System_Xml_Linq_Extensions, WellKnownType.System_Xml_Linq_XAttribute, WellKnownType.System_Xml_Linq_XCData, WellKnownType.System_Xml_Linq_XComment, WellKnownType.System_Xml_Linq_XContainer, WellKnownType.System_Xml_Linq_XDeclaration, WellKnownType.System_Xml_Linq_XDocument, WellKnownType.System_Xml_Linq_XElement, WellKnownType.System_Xml_Linq_XName, WellKnownType.System_Xml_Linq_XNamespace, WellKnownType.System_Xml_Linq_XObject, WellKnownType.System_Xml_Linq_XProcessingInstruction, WellKnownType.System_Security_UnverifiableCodeAttribute, WellKnownType.System_Security_Permissions_SecurityAction, WellKnownType.System_Security_Permissions_SecurityAttribute, WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, WellKnownType.System_NotSupportedException, WellKnownType.System_Runtime_CompilerServices_ICriticalNotifyCompletion, WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, WellKnownType.System_Windows_Forms_Form, WellKnownType.System_Windows_Forms_Application, WellKnownType.System_Environment, WellKnownType.System_Runtime_GCLatencyMode, WellKnownType.System_IFormatProvider } ) { Assert.True(type <= WellKnownType.CSharp7Sentinel); } // There were 204 well-known types prior to CSharp7 Assert.Equal(204, (int)(WellKnownType.CSharp7Sentinel - WellKnownType.First)); } [Fact] [WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void AllWellKnownTypeMembers() { var refs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929, DesktopCSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray(); var comp = CreateCompilation("", refs); foreach (WellKnownMember wkm in Enum.GetValues(typeof(WellKnownMember))) { switch (wkm) { case WellKnownMember.Count: // Not a real value; continue; case WellKnownMember.Microsoft_VisualBasic_Embedded__ctor: case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean: // C# can't embed VB core. continue; case WellKnownMember.System_Array__Empty: case WellKnownMember.System_Span_T__ctor: // Not yet in the platform. continue; case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile: case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles: case WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor: // Not always available. continue; } if (wkm == WellKnownMember.Count) continue; // Not a real value. var symbol = comp.GetWellKnownTypeMember(wkm); Assert.NotNull(symbol); } } [Fact, WorkItem(377890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377890")] public void System_IntPtr__op_Explicit_FromInt32() { string source = @" using System; public class MyClass { static void Main() { ((IntPtr)0).GetHashCode(); } } "; var comp = CreateStandardCompilation(source); comp.MakeMemberMissing(SpecialMember.System_IntPtr__op_Explicit_FromInt32); comp.VerifyEmitDiagnostics( // (8,10): error CS0656: Missing compiler required member 'System.IntPtr.op_Explicit' // ((IntPtr)0).GetHashCode(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr)0").WithArguments("System.IntPtr", "op_Explicit").WithLocation(8, 10) ); } [Fact] public void System_Delegate__Combine() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); compilation.MakeMemberMissing(SpecialMember.System_Delegate__Combine); compilation.VerifyEmitDiagnostics( // (13,12): error CS0656: Missing compiler required member 'System.Delegate.Combine' // MyEvent += async delegate { await Task.Delay(0); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "MyEvent += async delegate { await Task.Delay(0); }").WithArguments("System.Delegate", "Combine").WithLocation(13, 12) ); } [Fact] public void System_Nullable_T__ctor_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (20,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // int? qa = 5; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "5").WithArguments("System.Nullable`1", ".ctor").WithLocation(20, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", ".ctor").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_get_HasValue_01() { string source = @" using System; public struct S { public static implicit operator int(S n) // 1 native compiler { Console.WriteLine(1); return 0; } public static implicit operator int?(S n) // 2 Roslyn compiler { Console.WriteLine(2); return null; } public static void Main() { int? qa = 5; S b = default(S); var sum = qa + b; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19), // (22,19): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var sum = qa + b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "qa + b").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(22, 19) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_02() { string source = @" using System; namespace Test { static class Program { static void Main() { int? i = 123; C c = (C)i; } } public class C { public readonly int v; public C(int v) { this.v = v; } public static implicit operator C(int v) { Console.Write(v); return new C(v); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // C c = (C)i; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(C)i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 19) ); } [Fact] public void System_Nullable_T_get_Value() { var source = @" using System; class C { static void Test() { byte? b = 0; IntPtr p = (IntPtr)b; Console.WriteLine(p); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_Value); compilation.VerifyEmitDiagnostics( // (9,28): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value' // IntPtr p = (IntPtr)b; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "b").WithArguments("System.Nullable`1", "get_Value").WithLocation(9, 28) ); } [Fact] public void System_Nullable_T__ctor_02() { var source = @" using System; class C { static void Main() { Console.WriteLine((IntPtr?)M_int()); Console.WriteLine((IntPtr?)M_int(42)); Console.WriteLine((IntPtr?)M_long()); Console.WriteLine((IntPtr?)M_long(300)); } static int? M_int(int? p = null) { return p; } static long? M_long(long? p = null) { return p; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int()").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 27), // (9,42): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "42").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 42), // (9,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_int(42)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_int(42)").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 27), // (10,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long()); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 27), // (11,43): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "300").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 43), // (11,27): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Console.WriteLine((IntPtr?)M_long(300)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(IntPtr?)M_long(300)").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 27) ); } [Fact] public void System_Nullable_T__ctor_03() { var source = @" using System; class Class1 { static void Main() { MyClass b = (int?)1; } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (9,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // MyClass b = (int?)1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(int?)1").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 21), // (9,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // MyClass b = (int?)1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "(int?)1").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 21) ); } [Fact] public void System_Nullable_T__ctor_04() { var source1 = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public static class Test { public static void Generic<T>([Optional][DecimalConstant(0, 0, 0, 0, 50)] T x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Decimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal x) { Console.WriteLine(x.ToString()); } public static void NullableDecimal([Optional][DecimalConstant(0, 0, 0, 0, 50)] Decimal? x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Object([Optional][DecimalConstant(0, 0, 0, 0, 50)] object x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void String([Optional][DecimalConstant(0, 0, 0, 0, 50)] string x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void Int32([Optional][DecimalConstant(0, 0, 0, 0, 50)] int x) { Console.WriteLine(x.ToString()); } public static void IComparable([Optional][DecimalConstant(0, 0, 0, 0, 50)] IComparable x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } public static void ValueType([Optional][DecimalConstant(0, 0, 0, 0, 50)] ValueType x) { Console.WriteLine(x == null ? ""null"" : x.ToString()); } } "; var source2 = @" class Program { public static void Main() { // Respects default value Test.Generic<decimal>(); Test.Generic<decimal?>(); Test.Generic<object>(); Test.Decimal(); Test.NullableDecimal(); Test.Object(); Test.IComparable(); Test.ValueType(); Test.Int32(); // Null, since not convertible Test.Generic<string>(); Test.String(); } } "; var compilation = CreateCompilationWithMscorlib45(source1 + source2); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (55,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.Generic<decimal?>(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.Generic<decimal?>()").WithArguments("System.Nullable`1", ".ctor").WithLocation(55, 9), // (58,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // Test.NullableDecimal(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "Test.NullableDecimal()").WithArguments("System.Nullable`1", ".ctor").WithLocation(58, 9) ); } [Fact] public void System_String__ConcatObjectObject() { var source = @" using System; class Class1 { static void Main() { } } class MyClass { public static implicit operator MyClass(decimal Value) { Console.WriteLine(""Value is: "" + Value); return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObjectObject); compilation.VerifyEmitDiagnostics( // (16,27): error CS0656: Missing compiler required member 'System.String.Concat' // Console.WriteLine("Value is: " + Value); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"""Value is: "" + Value").WithArguments("System.String", "Concat").WithLocation(16, 27) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_04() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21), // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_get_HasValue_02() { var source = @" using System; class Class1 { static void Main() { int? a = 1; a.ToString(); MyClass b = a; b.ToString(); } } class MyClass { public static implicit operator MyClass(decimal Value) { Console.WriteLine(""Value is: "" + Value); return new MyClass(); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // MyClass b = a; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(11, 21) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_03() { string source = @"using System; namespace Test { static class Program { static void Main() { S.v = 0; S? S2 = 123; // not lifted, int=>int?, int?=>S, S=>S? Console.WriteLine(S.v == 123); } } public struct S { public static int v; // s == null, return v = -1 public static implicit operator S(int? s) { Console.Write(""Imp S::int? -> S ""); S ss = new S(); S.v = s ?? -1; return ss; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (23,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // S.v = s ?? -1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(23, 19) ); } [Fact] public void System_String__ConcatStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+'").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringStringStringString() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringStringStringString); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str").WithArguments("System.String", "Concat").WithLocation(8, 58) ); } [Fact] public void System_String__ConcatStringArray() { string source = @" using System; struct S { private string str; public S(char chr) { this.str = chr.ToString(); } public S(string str) { this.str = str; } public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } public override string ToString() { return this.str; } } class C { static void Main() { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringArray); compilation.VerifyEmitDiagnostics( // (8,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '+' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(8, 58), // (9,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '-' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(9, 58), // (10,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '%' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(10, 58), // (11,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '/' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(11, 58), // (12,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '*' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(12, 58), // (13,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '&' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(13, 58), // (14,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '|' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(14, 58), // (15,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '^' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(15, 58), // (16,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '<' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(16, 61), // (17,61): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '>' + y.ToString() + ')'").WithArguments("System.String", "Concat").WithLocation(17, 61), // (18,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(18, 59), // (19,59): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + '=' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(19, 59), // (20,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '>' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(20, 58), // (21,58): error CS0656: Missing compiler required member 'System.String.Concat' // public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "'(' + x.str + '<' + y.str + ')'").WithArguments("System.String", "Concat").WithLocation(21, 58) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_05() { string source = @" struct S { public static int operator +(S s) { return 1; } public static void Main() { S s = new S(); S? sq = s; var j = +sq; System.Console.WriteLine(j); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? sq = s; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "s").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 17), // (9,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // var j = +sq; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "+sq").WithArguments("System.Nullable`1", ".ctor").WithLocation(9, 17) ); } [Fact] public void System_Nullable_T__ctor_06() { string source = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(int? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,5): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // c++; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c++").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 5), // (11,5): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // c++; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c++").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 5) ); } [Fact] public void System_Decimal__op_Multiply() { string source = @" using System; class Program { static void Main() { Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Multiply); compilation.VerifyEmitDiagnostics( // (7,65): error CS0656: Missing compiler required member 'System.Decimal.op_Multiply' // Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "a * a").WithArguments("System.Decimal", "op_Multiply").WithLocation(7, 65) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_06() { string source = @" using System; struct S : IDisposable { public void Dispose() { Console.WriteLine(123); } static void Main() { using (S? r = new S()) { Console.Write(r); } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,9): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // using (S? r = new S()) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"using (S? r = new S()) { Console.Write(r); }").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T__ctor_07() { string source = @" using System; class C { static void Main() { decimal q = 10; decimal? x = 10; T(2, (x++).Value == (q++)); } static void T(int line, bool b) { } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (8,18): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // decimal? x = 10; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "10").WithArguments("System.Nullable`1", ".ctor").WithLocation(8, 18), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11), // (10,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (x++).Value == (q++)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x++").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 11) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_08() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(2, (n++).Value.x == (s++).x); } static void T(int line, bool b) { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (15,12): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // S? n = new S(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new S(1)").WithArguments("System.Nullable`1", ".ctor").WithLocation(15, 12), // (18,11): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(2, (n++).Value.x == (s++).x); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "n++").WithArguments("System.Nullable`1", ".ctor").WithLocation(18, 11) ); } [Fact] public void System_Nullable_T__ctor_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(1, true & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (11,21): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // bool? bnt = bt; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bt").WithArguments("System.Nullable`1", ".ctor").WithLocation(11, 21), // (13,14): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(1, true & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "true").WithArguments("System.Nullable`1", ".ctor").WithLocation(13, 14), // (13,14): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // T(1, true & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "true & bnt").WithArguments("System.Nullable`1", ".ctor").WithLocation(13, 14) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_09() { string source = @" using System; class C { static void T(int x, bool? b) {} static void Main() { bool bt = true; bool? bnt = bt; T(13, bnt & bnt); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15), // (13,15): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // T(13, bnt & bnt); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "bnt & bnt").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(13, 15) ); } [Fact] public void System_String__op_Equality_01() { string source = @" using System; struct SZ { public string str; public SZ(string str) { this.str = str; } public SZ(char c) { this.str = c.ToString(); } public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; } public override bool Equals(object x) { return true; } public override int GetHashCode() { return 0; } } class C { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (8,61): error CS0656: Missing compiler required member 'System.String.op_Equality' // public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "sz1.str == sz2.str").WithArguments("System.String", "op_Equality").WithLocation(8, 61) ); } [Fact] public void System_Nullable_T_get_HasValue_03() { var source = @" using System; static class LiveList { struct WhereInfo<TSource> { public int Key { get; set; } } static void Where<TSource>() { Action subscribe = () => { WhereInfo<TSource>? previous = null; var previousKey = previous?.Key; }; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_get_HasValue); compilation.VerifyEmitDiagnostics( // (17,31): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue' // var previousKey = previous?.Key; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "previous?.Key").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 31) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_10() { var source = @"using System; public class X { public static void Main() { var s = nameof(Main); if (s is string t) Console.WriteLine(""1. {0}"", t); s = null; Console.WriteLine(""2. {0}"", s is string w ? w : nameof(X)); int? x = 12; {if (x is var y) Console.WriteLine(""3. {0}"", y);} {if (x is int y) Console.WriteLine(""4. {0}"", y);} x = null; {if (x is var y) Console.WriteLine(""5. {0}"", y);} {if (x is int y) Console.WriteLine(""6. {0}"", y);} Console.WriteLine(""7. {0}"", (x is bool is bool)); } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (16,38): warning CS0184: The given expression is never of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "x is bool").WithArguments("bool").WithLocation(16, 38), // (16,38): warning CS0183: The given expression is always of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "x is bool is bool").WithArguments("bool").WithLocation(16, 38), // (12,19): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // {if (x is int y) Console.WriteLine("4. {0}", y);} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int y").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(12, 19) ); } [Fact] public void System_String__op_Equality_02() { var source = @" using System; public class X { public static void Main() { } public static void M(object o) { switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__op_Equality); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.String.op_Equality' // switch (o) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; }").WithArguments("System.String", "op_Equality").WithLocation(11, 9), // (11,9): error CS0656: Missing compiler required member 'System.String.op_Equality' // switch (o) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; }").WithArguments("System.String", "op_Equality").WithLocation(11, 9) ); } [Fact] public void System_String__Chars() { var source = @"using System; class Program { public static void Main(string[] args) { bool hasB = false; foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } } Console.WriteLine(hasB); } public static bool IsB(char value) { return value == 'b'; } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__Chars); compilation.VerifyEmitDiagnostics( // (8,9): error CS0656: Missing compiler required member 'System.String.get_Chars' // foreach (var c in "ab") Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var c in ""ab"") { switch (c) { case char b when IsB(b): hasB = true; break; default: hasB = false; break; } }").WithArguments("System.String", "get_Chars").WithLocation(8, 9) ); } [Fact] public void System_Nullable_T_GetValueOrDefault_11() { var source = @"using System; class Program { static void Main(string[] args) { } static void M(X? x) { switch (x) { case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(1); break; } } } struct X { public static implicit operator int? (X x) { return 1; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); compilation.VerifyEmitDiagnostics( // (9,13): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // switch (x) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 13), // (9,5): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault' // switch (x) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (x) { case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(1); break; }").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(9, 5) ); } [Fact] public void System_String__ConcatObject() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + null); Console.WriteLine(S + null); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatObject); compilation.VerifyEmitDiagnostics( // (11,27): error CS0656: Missing compiler required member 'System.String.Concat' // Console.WriteLine(O + null); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "O + null").WithArguments("System.String", "Concat").WithLocation(11, 27) ); } [Fact] public void System_Object__ToString() { var source = @" using System; public class Test { static void Main() { char c = 'c'; Console.WriteLine(c + ""3""); } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Object__ToString); compilation.VerifyEmitDiagnostics( // (9,27): error CS0656: Missing compiler required member 'System.Object.ToString' // Console.WriteLine(c + "3"); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"c + ""3""").WithArguments("System.Object", "ToString").WithLocation(9, 27) ); } [Fact] public void System_String__ConcatStringString() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<string, string, string>> testExpr = (x, y) => x + y; var result = testExpr.Compile()(""Hello "", ""World!""); Console.WriteLine(result); } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_String__ConcatStringString); compilation.VerifyEmitDiagnostics( // (10,71): error CS0656: Missing compiler required member 'System.String.Concat' // Expression<Func<string, string, string>> testExpr = (x, y) => x + y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x + y").WithArguments("System.String", "Concat").WithLocation(10, 71) ); } [Fact] public void System_Array__GetLowerBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetLowerBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetLowerBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetLowerBound").WithLocation(11, 9) ); } [Fact] public void System_Array__GetUpperBound() { var source = @" class C { static void Main() { double[,] values = { { 1.2, 2.3, 3.4, 4.5 }, { 5.6, 6.7, 7.8, 8.9 }, }; foreach (var x in values) { System.Console.WriteLine(x); } } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Array__GetUpperBound); compilation.VerifyEmitDiagnostics( // (11,9): error CS0656: Missing compiler required member 'System.Array.GetUpperBound' // foreach (var x in values) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var x in values) { System.Console.WriteLine(x); }").WithArguments("System.Array", "GetUpperBound").WithLocation(11, 9) ); } [Fact] public void System_Decimal__op_Implicit_FromInt32() { var source = @"using System; using System.Linq.Expressions; public struct SampStruct { public static implicit operator int(SampStruct ss1) { return 1; } } public class Test { static void Main() { Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }); compilation.MakeMemberMissing(SpecialMember.System_Decimal__op_Implicit_FromInt32); compilation.VerifyEmitDiagnostics( // (16,78): error CS0656: Missing compiler required member 'System.Decimal.op_Implicit' // Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x ?? y").WithArguments("System.Decimal", "op_Implicit").WithLocation(16, 78) ); } [Fact] public void System_Nullable_T__ctor_10() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; class Test { static void LogCallerLineNumber5([CallerLineNumber] int? lineNumber = 5) { Console.WriteLine(""line: "" + lineNumber); } public static void Main() { LogCallerLineNumber5(); } }"; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemRef }); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T__ctor); compilation.VerifyEmitDiagnostics( // (10,9): error CS0656: Missing compiler required member 'System.Nullable`1..ctor' // LogCallerLineNumber5(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "LogCallerLineNumber5()").WithArguments("System.Nullable`1", ".ctor").WithLocation(10, 9) ); } } }
39.78733
230
0.582623
[ "Apache-2.0" ]
iseneirik/roslyn-pt
src/Compilers/CSharp/Test/Symbol/Symbols/MissingSpecialMember.cs
96,725
C#
namespace FatturaElettronica.Common { /// <summary> /// XML serialization options for BusinessObject instances. /// </summary> public class XmlOptions { /// <summary> /// Format string to be applied on DateTime properties. This format will be ignored if the IgnoreXmlDateFormat attribute has been set /// for the property. /// </summary> public string DateTimeFormat { get; set;} /// <summary> /// Format string to be applied on Decimal properties. /// </summary> public string DecimalFormat { get; set;} /// <summary> /// Whether null properties should be serialized or not. Defaults to <value>false</value>. /// </summary> public bool SerializeNullValues { get; set; } /// <summary> /// Whether empty BusinessObject children should be serialized or not. Defaults to <value>false</value>. /// </summary> public bool SerializeEmptyBusinessObjects { get; set; } /// <summary> /// Wether emty strings should be serialized or not. Defaults to <value>false</value>. /// </summary> public bool SerializeEmptyStrings { get; set; } } }
39.451613
142
0.611611
[ "BSD-3-Clause" ]
andmattia/FatturaElettronica.Core
XmlOptions.cs
1,225
C#
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; using static LiteDB.Constants; namespace LiteDB { /// <summary> /// Class that converts your entity class to/from BsonDocument /// If you prefer use a new instance of BsonMapper (not Global), be sure cache this instance for better performance /// Serialization rules: /// - Classes must be "public" with a public constructor (without parameters) /// - Properties must have public getter (can be read-only) /// - Entity class must have Id property, [ClassName]Id property or [BsonId] attribute /// - No circular references /// - Fields are not valid /// - IList, Array supports /// - IDictionary supports (Key must be a simple datatype - converted by ChangeType) /// </summary> public partial class BsonMapper { #region Properties /// <summary> /// Mapping cache between Class/BsonDocument /// </summary> private Dictionary<Type, EntityMapper> _entities = new Dictionary<Type, EntityMapper>(); /// <summary> /// Map serializer/deserialize for custom types /// </summary> private ConcurrentDictionary<Type, Func<object, BsonValue>> _customSerializer = new ConcurrentDictionary<Type, Func<object, BsonValue>>(); private ConcurrentDictionary<Type, Func<BsonValue, object>> _customDeserializer = new ConcurrentDictionary<Type, Func<BsonValue, object>>(); /// <summary> /// Type instantiator function to support IoC /// </summary> private readonly Func<Type, object> _typeInstantiator; /// <summary> /// Type name binder to control how type names are serialized to BSON documents /// </summary> private readonly ITypeNameBinder _typeNameBinder; /// <summary> /// Global instance used when no BsonMapper are passed in LiteDatabase ctor /// </summary> public static BsonMapper Global = new BsonMapper(); /// <summary> /// A resolver name for field /// </summary> public Func<string, string> ResolveFieldName; /// <summary> /// Indicate that mapper do not serialize null values (default false) /// </summary> public bool SerializeNullValues { get; set; } /// <summary> /// Apply .Trim() in strings when serialize (default true) /// </summary> public bool TrimWhitespace { get; set; } /// <summary> /// Convert EmptyString to Null (default true) /// </summary> public bool EmptyStringToNull { get; set; } /// <summary> /// Get/Set if enum must be converted into Integer value. If false, enum will be converted into String value. /// MUST BE "true" to support LINQ expressions (default false) /// </summary> public bool EnumAsInteger { get; set; } /// <summary> /// Get/Set that mapper must include fields (default: false) /// </summary> public bool IncludeFields { get; set; } /// <summary> /// Get/Set that mapper must include non public (private, protected and internal) (default: false) /// </summary> public bool IncludeNonPublic { get; set; } /// <summary> /// Get/Set maximum depth for nested object (default 20) /// </summary> public int MaxDepth { get; set; } /// <summary> /// A custom callback to change MemberInfo behavior when converting to MemberMapper. /// Use mapper.ResolveMember(Type entity, MemberInfo property, MemberMapper documentMappedField) /// Set FieldName to null if you want remove from mapped document /// </summary> public Action<Type, MemberInfo, MemberMapper> ResolveMember; /// <summary> /// Custom resolve name collection based on Type /// </summary> public Func<Type, string> ResolveCollectionName; #endregion public BsonMapper(Func<Type, object> customTypeInstantiator = null, ITypeNameBinder typeNameBinder = null) { this.SerializeNullValues = false; this.TrimWhitespace = true; this.EmptyStringToNull = true; this.EnumAsInteger = false; this.ResolveFieldName = (s) => s; this.ResolveMember = (t, mi, mm) => { }; this.ResolveCollectionName = (t) => Reflection.IsEnumerable(t) ? Reflection.GetListItemType(t).Name : t.Name; this.IncludeFields = false; this.MaxDepth = 20; _typeInstantiator = customTypeInstantiator ?? ((Type t) => null); _typeNameBinder = typeNameBinder ?? DefaultTypeNameBinder.Instance; #region Register CustomTypes RegisterType<Uri>(uri => uri.AbsoluteUri, bson => new Uri(bson.AsString)); RegisterType<DateTimeOffset>(value => new BsonValue(value.UtcDateTime), bson => bson.AsDateTime.ToUniversalTime()); RegisterType<TimeSpan>(value => new BsonValue(value.Ticks), bson => new TimeSpan(bson.AsInt64)); RegisterType<Regex>( r => r.Options == RegexOptions.None ? new BsonValue(r.ToString()) : new BsonDocument { { "p", r.ToString() }, { "o", (int)r.Options } }, value => value.IsString ? new Regex(value) : new Regex(value.AsDocument["p"].AsString, (RegexOptions)value.AsDocument["o"].AsInt32) ); #endregion } #region Register CustomType /// <summary> /// Register a custom type serializer/deserialize function /// </summary> public void RegisterType<T>(Func<T, BsonValue> serialize, Func<BsonValue, T> deserialize) { _customSerializer[typeof(T)] = (o) => serialize((T)o); _customDeserializer[typeof(T)] = (b) => (T)deserialize(b); } /// <summary> /// Register a custom type serializer/deserialize function /// </summary> public void RegisterType(Type type, Func<object, BsonValue> serialize, Func<BsonValue, object> deserialize) { _customSerializer[type] = (o) => serialize(o); _customDeserializer[type] = (b) => deserialize(b); } #endregion /// <summary> /// Map your entity class to BsonDocument using fluent API /// </summary> public EntityBuilder<T> Entity<T>() { return new EntityBuilder<T>(this, _typeNameBinder); } #region Get LinqVisitor processor /// <summary> /// Resolve LINQ expression into BsonExpression /// </summary> public BsonExpression GetExpression<T, K>(Expression<Func<T, K>> predicate) { var visitor = new LinqExpressionVisitor(this, predicate); var expr = visitor.Resolve(typeof(K) == typeof(bool)); LOG($"`{predicate.ToString()}` -> `{expr.Source}`", "LINQ"); return expr; } #endregion #region Predefinded Property Resolvers /// <summary> /// Use lower camel case resolution for convert property names to field names /// </summary> public BsonMapper UseCamelCase() { this.ResolveFieldName = (s) => char.ToLower(s[0]) + s.Substring(1); return this; } private Regex _lowerCaseDelimiter = new Regex("(?!(^[A-Z]))([A-Z])", RegexOptions.Compiled); /// <summary> /// Uses lower camel case with delimiter to convert property names to field names /// </summary> public BsonMapper UseLowerCaseDelimiter(char delimiter = '_') { this.ResolveFieldName = (s) => _lowerCaseDelimiter.Replace(s, delimiter + "$2").ToLower(); return this; } #endregion #region GetEntityMapper /// <summary> /// Get property mapper between typed .NET class and BsonDocument - Cache results /// </summary> internal EntityMapper GetEntityMapper(Type type) { //TODO: needs check if Type if BsonDocument? Returns empty EntityMapper? if (!_entities.TryGetValue(type, out EntityMapper mapper)) { lock (_entities) { if (!_entities.TryGetValue(type, out mapper)) { return _entities[type] = this.BuildEntityMapper(type); } } } return mapper; } /// <summary> /// Use this method to override how your class can be, by default, mapped from entity to Bson document. /// Returns an EntityMapper from each requested Type /// </summary> protected virtual EntityMapper BuildEntityMapper(Type type) { var mapper = new EntityMapper(type); var idAttr = typeof(BsonIdAttribute); var ignoreAttr = typeof(BsonIgnoreAttribute); var fieldAttr = typeof(BsonFieldAttribute); var dbrefAttr = typeof(BsonRefAttribute); var members = this.GetTypeMembers(type); var id = this.GetIdMember(members); foreach (var memberInfo in members) { // checks [BsonIgnore] if (CustomAttributeExtensions.IsDefined(memberInfo, ignoreAttr, true)) continue; // checks field name conversion var name = this.ResolveFieldName(memberInfo.Name); // check if property has [BsonField] var field = (BsonFieldAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, fieldAttr, true).FirstOrDefault(); // check if property has [BsonField] with a custom field name if (field != null && field.Name != null) { name = field.Name; } // checks if memberInfo is id field if (memberInfo == id) { name = "_id"; } // create getter/setter function var getter = Reflection.CreateGenericGetter(type, memberInfo); var setter = Reflection.CreateGenericSetter(type, memberInfo); // check if property has [BsonId] to get with was setted AutoId = true var autoId = (BsonIdAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, idAttr, true).FirstOrDefault(); // get data type var dataType = memberInfo is PropertyInfo ? (memberInfo as PropertyInfo).PropertyType : (memberInfo as FieldInfo).FieldType; // check if datatype is list/array var isEnumerable = Reflection.IsEnumerable(dataType); // create a property mapper var member = new MemberMapper { AutoId = autoId == null ? true : autoId.AutoId, FieldName = name, MemberName = memberInfo.Name, DataType = dataType, IsEnumerable = isEnumerable, UnderlyingType = isEnumerable ? Reflection.GetListItemType(dataType) : dataType, Getter = getter, Setter = setter }; // check if property has [BsonRef] var dbRef = (BsonRefAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, dbrefAttr, false).FirstOrDefault(); if (dbRef != null && memberInfo is PropertyInfo) { BsonMapper.RegisterDbRef(this, member, _typeNameBinder, dbRef.Collection ?? this.ResolveCollectionName((memberInfo as PropertyInfo).PropertyType)); } // support callback to user modify member mapper this.ResolveMember?.Invoke(type, memberInfo, member); // test if has name and there is no duplicate field if (member.FieldName != null && mapper.Members.Any(x => x.FieldName.Equals(name, StringComparison.OrdinalIgnoreCase)) == false) { mapper.Members.Add(member); } } return mapper; } /// <summary> /// Gets MemberInfo that refers to Id from a document object. /// </summary> protected virtual MemberInfo GetIdMember(IEnumerable<MemberInfo> members) { return Reflection.SelectMember(members, x => CustomAttributeExtensions.IsDefined(x, typeof(BsonIdAttribute), true), x => x.Name.Equals("Id", StringComparison.OrdinalIgnoreCase), x => x.Name.Equals(x.DeclaringType.Name + "Id", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Returns all member that will be have mapper between POCO class to document /// </summary> protected virtual IEnumerable<MemberInfo> GetTypeMembers(Type type) { var members = new List<MemberInfo>(); var flags = this.IncludeNonPublic ? (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) : (BindingFlags.Public | BindingFlags.Instance); members.AddRange(type.GetProperties(flags) .Where(x => x.CanRead && x.GetIndexParameters().Length == 0) .Select(x => x as MemberInfo)); if (this.IncludeFields) { members.AddRange(type.GetFields(flags).Where(x => !x.Name.EndsWith("k__BackingField") && x.IsStatic == false).Select(x => x as MemberInfo)); } return members; } /// <summary> /// Get best construtor to use to initialize this entity. /// - Look if contains [BsonCtor] attribute /// - Look for parameterless ctor /// - Look for first contructor with parameter and use BsonDocument to send RawValue /// </summary> protected virtual CreateObject GetTypeCtor(EntityMapper mapper) { var ctors = mapper.ForType.GetConstructors(); var ctor = ctors.FirstOrDefault(x => x.GetCustomAttribute<BsonCtorAttribute>() != null && x.GetParameters().All(p => Reflection.ConvertType.ContainsKey(p.ParameterType) || _basicTypes.Contains(p.ParameterType) || p.ParameterType.GetTypeInfo().IsEnum)) ?? ctors.FirstOrDefault(x => x.GetParameters().Length == 0) ?? ctors.FirstOrDefault(x => x.GetParameters().All(p => Reflection.ConvertType.ContainsKey(p.ParameterType) || _customDeserializer.ContainsKey(p.ParameterType) || _basicTypes.Contains(p.ParameterType) || p.ParameterType.GetTypeInfo().IsEnum)); if (ctor == null) return null; var pars = new List<Expression>(); var pDoc = Expression.Parameter(typeof(BsonDocument), "_doc"); // otherwise, need access ctor with parameter foreach (var p in ctor.GetParameters()) { // try first get converted named (useful for Id => _id) var name = mapper.Members.FirstOrDefault(x => x.MemberName.Equals(p.Name, StringComparison.OrdinalIgnoreCase))?.FieldName ?? p.Name; var expr = Expression.MakeIndex(pDoc, Reflection.DocumentItemProperty, new[] { Expression.Constant(name) }); if (_customDeserializer.TryGetValue(p.ParameterType, out var func)) { var deserializer = Expression.Constant(func); var call = Expression.Invoke(deserializer, expr); var cast = Expression.Convert(call, p.ParameterType); pars.Add(cast); } else if (_basicTypes.Contains(p.ParameterType)) { var typeExpr = Expression.Constant(p.ParameterType); var rawValue = Expression.Property(expr, typeof(BsonValue).GetProperty("RawValue")); var convertTypeFunc = Expression.Call(typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) }), rawValue, typeExpr); var cast = Expression.Convert(convertTypeFunc, p.ParameterType); pars.Add(cast); } else if (p.ParameterType.GetTypeInfo().IsEnum && this.EnumAsInteger) { var typeExpr = Expression.Constant(p.ParameterType); var rawValue = Expression.PropertyOrField(expr, "AsInt32"); var convertTypeFunc = Expression.Call(typeof(Enum).GetMethod("ToObject", new Type[] { typeof(Type), typeof(Int32) }), typeExpr, rawValue); var cast = Expression.Convert(convertTypeFunc, p.ParameterType); pars.Add(cast); } else if (p.ParameterType.GetTypeInfo().IsEnum) { var typeExpr = Expression.Constant(p.ParameterType); var rawValue = Expression.PropertyOrField(expr, "AsString"); var convertTypeFunc = Expression.Call(typeof(Enum).GetMethod("Parse", new Type[] { typeof(Type), typeof(string) }), typeExpr, rawValue); var cast = Expression.Convert(convertTypeFunc, p.ParameterType); pars.Add(cast); } else { var propInfo = Reflection.ConvertType[p.ParameterType]; var prop = Expression.Property(expr, propInfo); pars.Add(prop); } } // get `new MyClass([params])` expression var newExpr = Expression.New(ctor, pars.ToArray()); // get lambda expression var fn = mapper.ForType.GetTypeInfo().IsClass ? Expression.Lambda<CreateObject>(newExpr, pDoc).Compile() : // Class Expression.Lambda<CreateObject>(Expression.Convert(newExpr, typeof(object)), pDoc).Compile(); // Struct return fn; } #endregion #region Register DbRef /// <summary> /// Register a property mapper as DbRef to serialize/deserialize only document reference _id /// </summary> internal static void RegisterDbRef(BsonMapper mapper, MemberMapper member, ITypeNameBinder typeNameBinder, string collection) { member.IsDbRef = true; if (member.IsEnumerable) { RegisterDbRefList(mapper, member, typeNameBinder, collection); } else { RegisterDbRefItem(mapper, member, typeNameBinder, collection); } } /// <summary> /// Register a property as a DbRef - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only /// </summary> private static void RegisterDbRefItem(BsonMapper mapper, MemberMapper member, ITypeNameBinder typeNameBinder, string collection) { // get entity var entity = mapper.GetEntityMapper(member.DataType); member.Serialize = (obj, m) => { // supports null values when "SerializeNullValues = true" if (obj == null) return BsonValue.Null; var idField = entity.Id; // #768 if using DbRef with interface with no ID mapped if (idField == null) throw new LiteException(0, "There is no _id field mapped in your type: " + member.DataType.FullName); var id = idField.Getter(obj); var bsonDocument = new BsonDocument { ["$id"] = m.Serialize(id.GetType(), id, 0), ["$ref"] = collection }; if (member.DataType != obj.GetType()) { bsonDocument["$type"] = typeNameBinder.GetName(obj.GetType()); } return bsonDocument; }; member.Deserialize = (bson, m) => { // if not a document (maybe BsonValue.null) returns null if (bson == null || bson.IsDocument == false) return null; var doc = bson.AsDocument; var idRef = doc["$id"]; var missing = doc["$missing"] == true; var included = doc.ContainsKey("$ref") == false; if (missing) return null; if (included) { doc["_id"] = idRef; if (doc.ContainsKey("$type")) { doc["_type"] = bson["$type"]; } return m.Deserialize(entity.ForType, doc); } else { return m.Deserialize(entity.ForType, doc.ContainsKey("$type") ? new BsonDocument { ["_id"] = idRef, ["_type"] = bson["$type"] } : new BsonDocument { ["_id"] = idRef }); // if has $id, deserialize object using only _id object } }; } /// <summary> /// Register a property as a DbRefList - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only /// </summary> private static void RegisterDbRefList(BsonMapper mapper, MemberMapper member, ITypeNameBinder typeNameBinder, string collection) { // get entity from list item type var entity = mapper.GetEntityMapper(member.UnderlyingType); member.Serialize = (list, m) => { // supports null values when "SerializeNullValues = true" if (list == null) return BsonValue.Null; var result = new BsonArray(); var idField = entity.Id; foreach (var item in (IEnumerable)list) { if (item == null) continue; var id = idField.Getter(item); var bsonDocument = new BsonDocument { ["$id"] = m.Serialize(id.GetType(), id, 0), ["$ref"] = collection }; if (member.UnderlyingType != item.GetType()) { bsonDocument["$type"] = typeNameBinder.GetName(item.GetType()); } result.Add(bsonDocument); } return result; }; member.Deserialize = (bson, m) => { if (bson.IsArray == false) return null; var array = bson.AsArray; if (array.Count == 0) return m.Deserialize(member.DataType, array); // copy array changing $id to _id var result = new BsonArray(); foreach (var item in array) { if (item.IsDocument == false) continue; var doc = item.AsDocument; var idRef = doc["$id"]; var missing = doc["$missing"] == true; var included = doc.ContainsKey("$ref") == false; // if referece document are missing, do not inlcude on output list if (missing) continue; // if refId is null was included by "include" query, so "item" is full filled document if (included) { item["_id"] = idRef; if (item.AsDocument.ContainsKey("$type")) { item["_type"] = item["$type"]; } result.Add(item); } else { var bsonDocument = new BsonDocument { ["_id"] = idRef }; if (item.AsDocument.ContainsKey("$type")) { bsonDocument["_type"] = item["$type"]; } result.Add(bsonDocument); } } return m.Deserialize(member.DataType, result); }; } #endregion } }
40
259
0.547953
[ "MIT" ]
AppyxDaniel/LiteDB
LiteDB/Client/Mapper/BsonMapper.cs
24,922
C#
using System.Threading.Tasks; namespace Proto.TestFixtures { public class DoNothingActor : IActor { public Task ReceiveAsync(IContext context) => Task.CompletedTask; } }
19.2
73
0.708333
[ "Apache-2.0" ]
AsynkronIT/protoactor-dotnet-contrib
tests/Proto.TestFixtures/DoNothingActor.cs
194
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FluentBuilder.Br")] [assembly: AssemblyDescription("Criação de objetos com foco em testes - versão em português do FluentBuilder")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Robson Castilho - robsoncastilho.com.br")] [assembly: AssemblyProduct("FluentBuilder.Br")] [assembly: AssemblyCopyright("Copyright © RCS 2015")] [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("43f97a05-38d1-405f-8b21-3ce54fa69320")] // 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")]
41.114286
111
0.750521
[ "MIT" ]
robsoncastilho/FluentBuilder
src/Nosbor.FluentBuilder.Br/Properties/AssemblyInfo.cs
1,446
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; using NetOffice.OfficeApi; namespace NetOffice.OfficeApi.Behind { /// <summary> /// DispatchInterface SmartArtQuickStyles /// SupportByVersion Office, 14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff864858.aspx </remarks> public class SmartArtQuickStyles : NetOffice.OfficeApi.Behind._IMsoDispObj, NetOffice.OfficeApi.SmartArtQuickStyles { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.OfficeApi.SmartArtQuickStyles); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(SmartArtQuickStyles); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public SmartArtQuickStyles() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion Office 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff860543.aspx </remarks> [SupportByVersion("Office", 14, 15, 16), ProxyResult] public virtual object Parent { get { return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Office 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff863986.aspx </remarks> [SupportByVersion("Office", 14, 15, 16)] public virtual Int32 Count { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Count"); } } #endregion #region Methods /// <summary> /// SupportByVersion Office 14, 15, 16 /// </summary> /// <param name="index">object index</param> [SupportByVersion("Office", 14, 15, 16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] public virtual NetOffice.OfficeApi.SmartArtQuickStyle this[object index] { get { return InvokerService.InvokeInternal.ExecuteKnownReferenceMethodGet<NetOffice.OfficeApi.SmartArtQuickStyle>(this, "Item", typeof(NetOffice.OfficeApi.SmartArtQuickStyle), index); } } #endregion #region IEnumerableProvider<NetOffice.OfficeApi.SmartArtQuickStyle> ICOMObject IEnumerableProvider<NetOffice.OfficeApi.SmartArtQuickStyle>.GetComObjectEnumerator(ICOMObject parent) { return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false); } IEnumerable IEnumerableProvider<NetOffice.OfficeApi.SmartArtQuickStyle>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator) { return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false); } #endregion #region IEnumerable<NetOffice.OfficeApi.SmartArtQuickStyle> /// <summary> /// SupportByVersion Office, 14,15,16 /// </summary> [SupportByVersion("Office", 14, 15, 16)] public virtual IEnumerator<NetOffice.OfficeApi.SmartArtQuickStyle> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.OfficeApi.SmartArtQuickStyle item in innerEnumerator) yield return item; } #endregion #region IEnumerable /// <summary> /// SupportByVersion Office, 14,15,16 /// </summary> [SupportByVersion("Office", 14, 15, 16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false); } #endregion #pragma warning restore } }
30.66092
193
0.610122
[ "MIT" ]
igoreksiz/NetOffice
Source/Office/Behind/DispatchInterfaces/SmartArtQuickStyles.cs
5,337
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("SVGE")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SVGE")] [assembly: AssemblyCopyright("Copyright © 2019")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
43.053571
99
0.691414
[ "MIT" ]
demidko/SVGE
SVGE/Properties/AssemblyInfo.cs
2,414
C#
using System; namespace Unity.WebRTC { public class RefCountedObject : IDisposable { internal IntPtr self; protected bool disposed; internal RefCountedObject(IntPtr ptr) { self = ptr; WebRTC.Context.AddRefPtr(self); } public virtual void Dispose() { if (this.disposed) { return; } if (self != IntPtr.Zero && !WebRTC.Context.IsNull) { WebRTC.Context.DeleteRefPtr(self); self = IntPtr.Zero; } this.disposed = true; GC.SuppressFinalize(this); } } }
19.885714
62
0.479885
[ "Apache-2.0" ]
GravitySketch/com.unity.webrtc
Runtime/Scripts/RefCountedObject.cs
696
C#
using System; using System.Collections; using System.Collections.Generic; namespace Metaheuristics { public class DiscretePSOBL42SP : DiscretePSO { public TwoSPInstance Instance { get; protected set; } protected int generatedSolutions; public DiscretePSOBL42SP(TwoSPInstance instance, int partsCount, double prevConf, double neighConf, int[] lowerBounds, int[] upperBounds) : base(partsCount, prevConf, neighConf, lowerBounds, upperBounds) { Instance = instance; generatedSolutions = 0; } protected override double Fitness(int[] individual) { return TwoSPUtils.Fitness(Instance, TwoSPUtils.BLCoordinates(Instance, individual)); } protected override int[] InitialSolution () { int[] solution; if (generatedSolutions == 0) { solution = TwoSPUtils.DecreasingArea(Instance); } else if (generatedSolutions == 1) { solution = TwoSPUtils.DecreasingWidth(Instance); } else if (generatedSolutions == 2) { solution = TwoSPUtils.DecreasingHeight(Instance); } else { solution = TwoSPUtils.RandomSolution(Instance); } generatedSolutions++; return solution; } } }
26.93617
96
0.654818
[ "MIT" ]
yasserglez/metaheuristics
Common/2SP/DiscretePSOBL42SP.cs
1,266
C#
using System.Runtime.Serialization; namespace Xbox.Music { /// <summary> /// /// </summary> [DataContract] public class Error { /// <summary> /// The error code, as described in the following table of error codes. /// </summary> [DataMember] public string ErrorCode { get; set; } /// <summary> /// A user-friendly description of the error code. /// </summary> [DataMember] public string Description { get; set; } /// <summary> /// A more contextual message describing what may have gone wrong. /// </summary> [DataMember] public string Message { get; set; } } }
21.117647
79
0.54039
[ "MIT", "Unlicense" ]
luizbon/Xbox.Music
src/Xbox.Music/Models/Error.cs
720
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Gallio.Common.Collections; using Gallio.Common.Reflection; using Gallio.Runtime; using Gallio.Runtime.Extensibility; using Gallio.Runtime.Extensibility.Schema; using MbUnit.Framework; using Rhino.Mocks; using File = Gallio.Runtime.Extensibility.Schema.File; namespace Gallio.Tests.Runtime.Extensibility { [TestsOn(typeof(PluginCatalog))] public class PluginCatalogTest { public class AddingPlugins { [Test] public void AddPlugin_WhenPluginIsNull_Throws() { var catalog = new PluginCatalog(); var baseDirectory = new DirectoryInfo(@"C:\"); Assert.Throws<ArgumentNullException>(() => catalog.AddPlugin(null, baseDirectory)); } [Test] public void AddPlugin_WhenBaseDirectoryIsNull_Throws() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId"); Assert.Throws<ArgumentNullException>(() => catalog.AddPlugin(plugin, null)); } } public class ApplyingConfigurationToRegistry { [Test] public void ApplyTo_WhenRegistryIsNull_Throws() { var catalog = new PluginCatalog(); Assert.Throws<ArgumentNullException>(() => catalog.ApplyTo(null)); } [Test] public void ApplyTo_WhenPluginTypeIsNull_RegistersThePluginWithDefaultPluginType() { var catalog = new PluginCatalog(); var codeBase = AssemblyUtils.GetFriendlyAssemblyCodeBase(typeof(IRuntime).Assembly); var plugin = new Plugin("pluginId") { Parameters = new KeyValueTable() { PropertySet = { { "Parameter", "Value" } } }, Traits = new KeyValueTable() { PropertySet = { { "Trait", "Value" } } }, Assemblies = { new Assembly("Gallio") { CodeBase = codeBase } }, EnableCondition = "${minFramework:NET35}", RecommendedInstallationPath = "Path", Files = { new File("file1.txt"), new File("file2.dll") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateStub<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); Assert.Multiple(() => { Assert.AreEqual("pluginId", pluginRegistrations[0].PluginId); Assert.AreEqual(baseDirectory, pluginRegistrations[0].BaseDirectory); Assert.AreEqual(new TypeName(typeof(DefaultPlugin)), pluginRegistrations[0].PluginTypeName); Assert.AreEqual(new PropertySet() { { "Parameter", "Value" } }, pluginRegistrations[0].PluginProperties); Assert.AreEqual(new PropertySet() { { "Trait", "Value" } }, pluginRegistrations[0].TraitsProperties); Assert.AreEqual("Gallio", pluginRegistrations[0].AssemblyBindings[0].AssemblyName.Name); Assert.AreEqual(new Uri(codeBase), pluginRegistrations[0].AssemblyBindings[0].CodeBase); Assert.AreEqual("${minFramework:NET35}", pluginRegistrations[0].EnableCondition.ToString()); Assert.AreEqual("Path", pluginRegistrations[0].RecommendedInstallationPath); Assert.AreElementsEqual(new[] { "file1.txt", "file2.dll" }, pluginRegistrations[0].FilePaths); }); } [Test] public void ApplyTo_WhenPluginTypeIsNotNull_RegistersThePluginWithSpecifiedPluginType() { var catalog = new PluginCatalog(); var codeBase = AssemblyUtils.GetFriendlyAssemblyCodeBase(typeof(IRuntime).Assembly); var plugin = new Plugin("pluginId") { PluginType = "Plugin, Assembly", }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateStub<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); Assert.Multiple(() => { Assert.AreEqual(new TypeName("Plugin, Assembly"), pluginRegistrations[0].PluginTypeName); }); } [Test] public void ApplyTo_WhenPluginRegistrationFails_Throws() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId"); var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Throw(new InvalidOperationException("Boom")); catalog.AddPlugin(plugin, baseDirectory); var ex = Assert.Throws<RuntimeException>(() => catalog.ApplyTo(registry)); Assert.AreEqual("Could not register plugin 'pluginId'.", ex.Message); registry.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenServiceRegistrationWellFormed_RegistersTheService() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Services = { new Service("serviceId", "Service, Assembly") { DefaultComponentType = "DefaultComponent, Assembly" }} }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateStub<IPluginDescriptor>(); var serviceRegistrations = new List<ServiceRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Return(pluginDescriptor); registry.Expect(x => x.RegisterService(null)).Callback(Enlist(serviceRegistrations)).Return(MockRepository.GenerateStub<IServiceDescriptor>()); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); Assert.Multiple(() => { Assert.AreSame(pluginDescriptor, serviceRegistrations[0].Plugin); Assert.AreEqual("serviceId", serviceRegistrations[0].ServiceId); Assert.AreEqual(new TypeName("Service, Assembly"), serviceRegistrations[0].ServiceTypeName); Assert.AreEqual(new TypeName("DefaultComponent, Assembly"), serviceRegistrations[0].DefaultComponentTypeName); }); } [Test] public void ApplyTo_WhenServiceRegistrationFails_Throws() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Services = { new Service("serviceId", "Service, Assembly") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Return(MockRepository.GenerateStub<IPluginDescriptor>()); registry.Expect(x => x.RegisterService(null)).IgnoreArguments().Throw(new InvalidOperationException("Boom")); catalog.AddPlugin(plugin, baseDirectory); var ex = Assert.Throws<RuntimeException>(() => catalog.ApplyTo(registry)); Assert.AreEqual("Could not register service 'serviceId' of plugin 'pluginId'.", ex.Message); registry.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenComponentRegistrationWellFormed_RegistersTheComponent() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Components = { new Component("componentId", "serviceId", "Component, Assembly") { Parameters = new KeyValueTable() { PropertySet = { { "Parameter", "Value" } } }, Traits = new KeyValueTable() { PropertySet = { { "Trait", "Value" } } } } } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var services = MockRepository.GenerateMock<IServices>(); var pluginDescriptor = MockRepository.GenerateStub<IPluginDescriptor>(); var serviceDescriptor = MockRepository.GenerateStub<IServiceDescriptor>(); var componentRegistrations = new List<ComponentRegistration>(); registry.Stub(x => x.Services).Return(services); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Return(pluginDescriptor); registry.Expect(x => x.RegisterComponent(null)).Callback(Enlist(componentRegistrations)).Return(MockRepository.GenerateStub<IComponentDescriptor>()); services.Expect(x => x["serviceId"]).Return(serviceDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); services.VerifyAllExpectations(); Assert.Multiple(() => { Assert.AreSame(pluginDescriptor, componentRegistrations[0].Plugin); Assert.AreSame(serviceDescriptor, componentRegistrations[0].Service); Assert.AreEqual("componentId", componentRegistrations[0].ComponentId); Assert.AreEqual(new TypeName("Component, Assembly"), componentRegistrations[0].ComponentTypeName); Assert.AreEqual(new PropertySet() { { "Parameter", "Value" } }, componentRegistrations[0].ComponentProperties); Assert.AreEqual(new PropertySet() { { "Trait", "Value" } }, componentRegistrations[0].TraitsProperties); }); } [Test] public void ApplyTo_WhenComponentRegistrationFails_Throws() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Components = { new Component("componentId", "serviceId", "Component, Assembly") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var services = MockRepository.GenerateMock<IServices>(); registry.Stub(x => x.Services).Return(services); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Return(MockRepository.GenerateStub<IPluginDescriptor>()); registry.Expect(x => x.RegisterComponent(null)).IgnoreArguments().Throw(new InvalidOperationException("Boom")); services.Expect(x => x["serviceId"]).Return(MockRepository.GenerateStub<IServiceDescriptor>()); catalog.AddPlugin(plugin, baseDirectory); var ex = Assert.Throws<RuntimeException>(() => catalog.ApplyTo(registry)); Assert.AreEqual("Could not register component 'componentId' of plugin 'pluginId'.", ex.Message); registry.VerifyAllExpectations(); services.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenComponentRefersToUnregisteredService_Throws() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Components = { new Component("componentId", "serviceId", "Component, Assembly") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var services = MockRepository.GenerateMock<IServices>(); registry.Stub(x => x.Services).Return(services); registry.Expect(x => x.RegisterPlugin(null)).IgnoreArguments().Return(MockRepository.GenerateStub<IPluginDescriptor>()); services.Expect(x => x["serviceId"]).Return(null); catalog.AddPlugin(plugin, baseDirectory); var ex = Assert.Throws<RuntimeException>(() => catalog.ApplyTo(registry)); Assert.AreEqual("Could not register component 'componentId' of plugin 'pluginId' because it implements service 'serviceId' which was not found in the registry.", ex.Message); registry.VerifyAllExpectations(); services.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenWellFormed_RegistersAllPluginsThenAllServicesThenAllComponents() { var catalog = new PluginCatalog(); catalog.AddPlugin(new Plugin("plugin1Id") { Services = { new Service("service1Id", "Service1, Assembly"), new Service("service2Id", "Service2, Assembly") }, Components = { new Component("component1Id", "service2Id", "Component1, Assembly"), new Component("component2Id", "service3Id", "Component2, Assembly"), } }, new DirectoryInfo(@"C:\Plugin1")); catalog.AddPlugin(new Plugin("plugin2Id") { Services = { new Service("service3Id", "Service3, Assembly") }, Components = { new Component("component3Id", "service1Id", "Component3, Assembly"), new Component("component4Id", "service3Id", "Component4, Assembly"), } }, new DirectoryInfo(@"C:\Plugin2")); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginRegistrations = new List<PluginRegistration>(); var serviceRegistrations = new List<ServiceRegistration>(); var componentRegistrations = new List<ComponentRegistration>(); var services = MockRepository.GenerateMock<IServices>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)) .Return(MockRepository.GenerateStub<IPluginDescriptor>()) .Repeat.Twice(); registry.Expect(x => x.RegisterService(null)).Callback(Enlist(serviceRegistrations)) .Return(MockRepository.GenerateStub<IServiceDescriptor>()) .Repeat.Times(3); registry.Expect(x => x.RegisterComponent(null)).Callback(Enlist(componentRegistrations)) .Return(MockRepository.GenerateStub<IComponentDescriptor>()) .Repeat.Times(4); registry.Stub(x => x.Services).Return(services); services.Expect(x => x["service2Id"]).Repeat.Once().Return(MockRepository.GenerateStub<IServiceDescriptor>()); services.Expect(x => x["service3Id"]).Repeat.Twice().Return(MockRepository.GenerateStub<IServiceDescriptor>()); services.Expect(x => x["service1Id"]).Repeat.Once().Return(MockRepository.GenerateStub<IServiceDescriptor>()); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); services.VerifyAllExpectations(); Assert.Multiple(() => { Assert.AreEqual("plugin1Id", pluginRegistrations[0].PluginId); Assert.AreEqual("plugin2Id", pluginRegistrations[1].PluginId); Assert.AreEqual("service1Id", serviceRegistrations[0].ServiceId); Assert.AreEqual("service2Id", serviceRegistrations[1].ServiceId); Assert.AreEqual("service3Id", serviceRegistrations[2].ServiceId); Assert.AreEqual("component1Id", componentRegistrations[0].ComponentId); Assert.AreEqual("component2Id", componentRegistrations[1].ComponentId); Assert.AreEqual("component3Id", componentRegistrations[2].ComponentId); Assert.AreEqual("component4Id", componentRegistrations[3].ComponentId); }); } } public class ResolvingPluginDependencies { [Test] public void ApplyTo_WhenPluginDependenciesPresent_RegistersPluginsInTopologicallySortedOrder() { var catalog = new PluginCatalog(); var plugin1 = new Plugin("plugin1Id") { Dependencies = { new Dependency("plugin3Id"), new Dependency("plugin2Id") } }; var plugin2 = new Plugin("plugin2Id") { Dependencies = { new Dependency("plugin4Id") } }; var plugin3 = new Plugin("plugin3Id") { Dependencies = { new Dependency("plugin4Id") } }; var plugin4 = new Plugin("plugin4Id") { Dependencies = { } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginRegistrations = new List<PluginRegistration>(); var plugins = MockRepository.GenerateMock<IPlugins>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(MockRepository.GenerateStub<IPluginDescriptor>()).Repeat.Times(4); registry.Stub(x => x.Plugins).Return(plugins); plugins.Expect(x => x[null]).IgnoreArguments().Return(MockRepository.GenerateStub<IPluginDescriptor>()); catalog.AddPlugin(plugin2, baseDirectory); catalog.AddPlugin(plugin4, baseDirectory); catalog.AddPlugin(plugin1, baseDirectory); catalog.AddPlugin(plugin3, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); plugins.VerifyAllExpectations(); Assert.AreElementsEqual(new[] { "plugin4Id", "plugin2Id", "plugin3Id", "plugin1Id" }, pluginRegistrations.ConvertAll(p => p.PluginId), "Plugins should appear in sorted dependency order."); } [Test] public void ApplyTo_WhenPluginDependencyCycleExists_Throws() { var catalog = new PluginCatalog(); var plugin1 = new Plugin("plugin1Id") { Dependencies = { new Dependency("plugin3Id"), new Dependency("plugin2Id") } }; var plugin2 = new Plugin("plugin2Id") { Dependencies = { new Dependency("plugin1Id") } }; var plugin3 = new Plugin("plugin3Id") { Dependencies = { } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); catalog.AddPlugin(plugin2, baseDirectory); catalog.AddPlugin(plugin1, baseDirectory); catalog.AddPlugin(plugin3, baseDirectory); var ex = Assert.Throws<RuntimeException>(() => catalog.ApplyTo(registry)); Assert.AreEqual("Could not topologically sort the following plugins either due to dependency cycles or duplicate dependencies: 'plugin2Id', 'plugin1Id'.", ex.Message); registry.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenPluginDependencyCannotBeResolved_DisablesAffectedPLugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Dependencies = { new Dependency("unresolvedPluginId") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); var plugins = MockRepository.GenerateMock<IPlugins>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); pluginDescriptor.Expect(x => x.Disable("Could not find plugin 'unresolvedPluginId' upon which this plugin depends.")); registry.Stub(x => x.Plugins).Return(plugins); plugins.Expect(x => x["unresolvedPluginId"]).Return(null); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); plugins.VerifyAllExpectations(); } } public class ProbingForAssembliesAndDisablingPlugins { [Test] public void ApplyTo_WhenAssemblyCodeBaseIsRootedAndExists_DoesNotDisablePlugin() { var catalog = new PluginCatalog(); var codeBase = AssemblyUtils.GetFriendlyAssemblyCodeBase(typeof(IRuntime).Assembly); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("Gallio") { CodeBase = codeBase } } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenAssemblyCodeBaseIsRelativeToPluginBaseDirectoryAndExists_DoesNotDisablePlugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("Gallio") { CodeBase = "Gallio.dll" } } }; var baseDirectory = new DirectoryInfo(Path.GetDirectoryName(AssemblyUtils.GetFriendlyAssemblyCodeBase(typeof(IRuntime).Assembly))); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenAssemblyCodeBaseIsRelativeToProbingPathAndExists_DoesNotDisablePlugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("Gallio") { CodeBase = "Gallio.dll" } }, ProbingPaths = { Path.GetDirectoryName(AssemblyUtils.GetFriendlyAssemblyCodeBase(typeof(IRuntime).Assembly)) } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } [Test] public void ApplyTo_WhenAssemblyHasNoCodeBaseAndIsFoundInTheGAC_DoesNotDisablePlugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("System") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } #if STRICT_GAC_CHECKS [Test] public void ApplyTo_WhenAssemblyHasNoCodeBaseAndIsNotInTheGAC_DisablesPlugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("ThisAssemblyDoesNotExistInTheGAC") } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); pluginDescriptor.Expect(x => x.Disable("Could not find assembly 'ThisAssemblyDoesNotExistInTheGAC' in the global assembly cache.")); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } #endif [Test] public void ApplyTo_WhenAssemblyHasACodeBaseButIsNotFoundByProbing_DisablesPlugin() { var catalog = new PluginCatalog(); var plugin = new Plugin("pluginId") { Assemblies = { new Assembly("ThisAssemblyCannotBeFoundByProbing") { CodeBase = "ThisAssemblyCannotBeFoundByProbing.dll" } }, ProbingPaths = { "probing" } }; var baseDirectory = new DirectoryInfo(@"C:\"); var registry = MockRepository.GenerateMock<IRegistry>(); var pluginDescriptor = MockRepository.GenerateMock<IPluginDescriptor>(); var pluginRegistrations = new List<PluginRegistration>(); registry.Expect(x => x.RegisterPlugin(null)).Callback(Enlist(pluginRegistrations)).Return(pluginDescriptor); pluginDescriptor.Expect(x => x.Disable("Could not find assembly 'ThisAssemblyCannotBeFoundByProbing' after probing for its code base in 'C:\\ThisAssemblyCannotBeFoundByProbing.dll', 'C:\\bin\\ThisAssemblyCannotBeFoundByProbing.dll', 'C:\\probing\\ThisAssemblyCannotBeFoundByProbing.dll', 'C:\\bin\\probing\\ThisAssemblyCannotBeFoundByProbing.dll'.")); catalog.AddPlugin(plugin, baseDirectory); catalog.ApplyTo(registry); registry.VerifyAllExpectations(); pluginDescriptor.VerifyAllExpectations(); } } private static Gallio.Common.Func<T, bool> Enlist<T>(ICollection<T> list) { return value => { list.Add(value); return true; }; } } }
50.043548
368
0.573984
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v3
src/Gallio/Gallio.Tests/Runtime/Extensibility/PluginCatalogTest.cs
31,027
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.Json; namespace Zen.Utilities { [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] public class DataList<T> : IEnumerable<T> where T : IIdentifiedById { protected readonly List<T> Items; protected DataList() { Items = new List<T>(); } private DataList(List<T> items) { Items = new List<T>(); foreach (var item in items) { Items.Add(item); } } public static DataList<T> Create() { return new DataList<T>(); } public static DataList<T> Create(List<T> items) { return new DataList<T>(items); } public static DataList<T> Create(IEnumerable<T> items) { return new DataList<T>(items.ToList()); } public static DataList<T> CreateFromJson(string json) { var deserialized = JsonSerializer.Deserialize<List<T>>(json); var list = Create(deserialized); return list; } public int Count => Items.Count; public T this[int index] { get { if (index < 0 || index >= Items.Count) { throw new IndexOutOfRangeException($"Index out of range. Item with index [{index}] not found."); } return Items[index]; } } // CRUD public void Add(T item) { Items.Add(item); } public T GetById(int id) { foreach (var item in Items) { if (item.Id == id) { return item; } } throw new Exception($"Id [{id}] not found."); } public void Update(T item) { var index = FindIndexOfId(item.Id); Items[index] = item; } public void Remove(int id) { var index = FindIndexOfId(id); Items.RemoveAt(index); } public string Serialize(bool prettyPrint = false) { var options = new JsonSerializerOptions {WriteIndented = prettyPrint}; var serialized = JsonSerializer.Serialize(Items, options); return serialized; } private int FindIndexOfId(int id) { for (var i = 0; i < Items.Count; i++) { var item = Items[i]; if (item.Id == id) { return i; } } throw new Exception($"Id [{id}] not found."); } public IEnumerator<T> GetEnumerator() { foreach (var item in Items) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() { return DebuggerDisplay; } private string DebuggerDisplay => $"{{{typeof(T).Name} List: Count={Items.Count}}}"; } }
23.687943
116
0.469461
[ "MIT" ]
gmoller/Zen.Utilities
Utilities/DataList.cs
3,342
C#
/* * Piping is a way to compose a handler piple line, allowing a handler be composed of * smaller and potentially reusable operations. */ // ReSharper disable once CheckNamespace namespace Cedar.CommandHandling.Example.Piping { using System.Threading.Tasks; using Cedar.CommandHandling; public class Command {} public class CommandModule : CommandHandlerModule { public CommandModule() { // 1. Here we use a pipe to perform a command validation operation For<Command>() .Pipe(next => (commandMessage, ct) => { Validate(commandMessage.Command); return next(commandMessage, ct); }) .Handle((commandMessage, ct) => Task.FromResult(0)); } private static void Validate<TCommand>(TCommand command) {} } }
27.393939
86
0.594027
[ "MIT" ]
heynickc/Cedar.CommandHandling
src/Cedar.CommandHandling.Example/02_Piping.cs
906
C#
using System; namespace PrismOutlook.Core { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class DependentViewAttribute : Attribute { public string Region { get; set; } public Type Type { get; set; } public DependentViewAttribute(string region, Type type) { if (region is null) throw new ArgumentNullException(nameof(region)); if (type == null) throw new ArgumentNullException(nameof(type)); Region = region; Type = type; } } }
23.72
66
0.583474
[ "MIT" ]
ComtelJeremy/PrismOutlook
PrismOutlook.Core/DependentViewAttribute.cs
595
C#
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; namespace UnityEngine.Experimental.Input.Editor { internal class CopyPasteUtility { const string kInputAssetMarker = "INPUTASSET\n"; InputActionListTreeView m_TreeView; ActionInspectorWindow m_Window; SerializedObject m_SerializedObject; GUIContent m_CutGUI = EditorGUIUtility.TrTextContent("Cut"); GUIContent m_CopyGUI = EditorGUIUtility.TrTextContent("Copy"); GUIContent m_PasteGUI = EditorGUIUtility.TrTextContent("Paste"); GUIContent m_DeleteGUI = EditorGUIUtility.TrTextContent("Delete"); GUIContent m_Duplicate = EditorGUIUtility.TrTextContent("Duplicate"); public CopyPasteUtility(ActionInspectorWindow window, InputActionListTreeView tree, SerializedObject serializedObject) { m_Window = window; m_TreeView = tree; m_SerializedObject = serializedObject; } void HandleCopyEvent() { if (!CanCopySelection()) { EditorGUIUtility.systemCopyBuffer = null; EditorApplication.Beep(); return; } var selectedRows = m_TreeView.GetSelectedRows(); var rowTypes = selectedRows.Select(r => r.GetType()).Distinct().ToList(); // Don't allow to copy different type. It will hard to handle pasting if (rowTypes.Count() > 1) { EditorGUIUtility.systemCopyBuffer = null; EditorApplication.Beep(); return; } var copyList = new StringBuilder(kInputAssetMarker); foreach (var selectedRow in selectedRows) { copyList.Append(selectedRow.GetType().Name); copyList.Append(selectedRow.SerializeToString()); copyList.Append(kInputAssetMarker); if (selectedRow is ActionTreeItem && selectedRow.children != null && selectedRow.children.Count > 0) { var action = selectedRow as ActionTreeItem; foreach (var child in action.children) { copyList.Append(child.GetType().Name); copyList.Append((child as BindingTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); // Copy composites if (child.hasChildren) { foreach (var innerChild in child.children) { copyList.Append(innerChild.GetType().Name); copyList.Append((innerChild as BindingTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); } } } } if (selectedRow is CompositeGroupTreeItem && selectedRow.children != null && selectedRow.children.Count > 0) { var composite = selectedRow as CompositeGroupTreeItem; foreach (var child in composite.children) { if (!(child is CompositeTreeItem)) continue; copyList.Append(child.GetType().Name); copyList.Append((child as CompositeTreeItem).SerializeToString()); copyList.Append(kInputAssetMarker); } } } EditorGUIUtility.systemCopyBuffer = copyList.ToString(); } bool CanCopySelection() { var selectedRows = m_TreeView.GetSelectedRows(); var rowTypes = selectedRows.Select(r => r.GetType()).Distinct().ToList(); if (rowTypes.Count != 1) return false; if (rowTypes.Single() == typeof(CompositeTreeItem)) return false; return true; } void HandlePasteEvent() { var json = EditorGUIUtility.systemCopyBuffer; var elements = json.Split(new[] { kInputAssetMarker }, StringSplitOptions.RemoveEmptyEntries); if (!json.StartsWith(kInputAssetMarker)) return; for (var i = 0; i < elements.Length; i++) { var row = elements[i]; if (IsRowOfType<ActionMapTreeItem>(ref row)) { var map = JsonUtility.FromJson<InputActionMap>(row); InputActionSerializationHelpers.AddActionMapFromObject(m_SerializedObject, map); m_Window.Apply(); continue; } if (IsRowOfType<ActionTreeItem>(ref row)) { var action = JsonUtility.FromJson<InputAction>(row); var actionMap = m_TreeView.GetSelectedActionMap(); var newActionProperty = actionMap.AddActionFromObject(action); while (i + 1 < elements.Length) { try { var nextRow = elements[i + 1]; if (nextRow.StartsWith(typeof(BindingTreeItem).Name)) { nextRow = nextRow.Substring(typeof(BindingTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeGroupTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeGroupTreeItem).Name.Length); } else if (nextRow.StartsWith(typeof(CompositeTreeItem).Name)) { nextRow = nextRow.Substring(typeof(CompositeTreeItem).Name.Length); } else { break; } var binding = JsonUtility.FromJson<InputBinding>(nextRow); InputActionSerializationHelpers.AppendBindingFromObject(binding, newActionProperty, actionMap.elementProperty); i++; } catch (ArgumentException e) { Debug.LogException(e); break; } } m_Window.Apply(); continue; } if (IsRowOfType<BindingTreeItem>(ref row) || IsRowOfType<CompositeGroupTreeItem>(ref row) || IsRowOfType<CompositeTreeItem>(ref row)) { var binding = JsonUtility.FromJson<InputBinding>(row); var selectedRow = m_TreeView.GetSelectedAction(); if (selectedRow == null) { EditorApplication.Beep(); continue; } selectedRow.AppendBindingFromObject(binding); m_Window.Apply(); continue; } } } bool IsRowOfType<T>(ref string row) { if (row.StartsWith(typeof(T).Name)) { row = row.Substring(typeof(T).Name.Length); return true; } return false; } public bool IsValidCommand(string currentCommandName) { return Event.current.commandName == "Copy" || Event.current.commandName == "Paste" || Event.current.commandName == "Cut" || Event.current.commandName == "Duplicate" || Event.current.commandName == "Delete"; } public void HandleCommandEvent(string currentCommandName) { switch (Event.current.commandName) { case "Copy": HandleCopyEvent(); Event.current.Use(); break; case "Paste": HandlePasteEvent(); Event.current.Use(); break; case "Cut": HandleCopyEvent(); DeleteSelectedRows(); Event.current.Use(); break; case "Duplicate": HandleCopyEvent(); HandlePasteEvent(); Event.current.Use(); break; case "Delete": DeleteSelectedRows(); Event.current.Use(); break; } } void DeleteSelectedRows() { var rows = m_TreeView.GetSelectedRows().ToArray(); var rowTypes = rows.Select(r => r.GetType()).Distinct().ToList(); // Don't allow to delete different types at once because it's hard to handle. if (rowTypes.Count() > 1) { EditorApplication.Beep(); return; } // Remove composite bindings foreach (var compositeGroup in FindRowsToDeleteOfType<CompositeGroupTreeItem>(rows)) { var action = (compositeGroup.parent as ActionTreeItem); for (var i = compositeGroup.children.Count - 1; i >= 0; i--) { var composite = (CompositeTreeItem)compositeGroup.children[i]; action.RemoveBinding(composite.index); } action.RemoveBinding(compositeGroup.index); } // Remove bindings foreach (var bindingRow in FindRowsToDeleteOfType<BindingTreeItem>(rows)) { var action = bindingRow.parent as ActionTreeItem; action.RemoveBinding(bindingRow.index); } // Remove actions foreach (var actionRow in FindRowsToDeleteOfType<ActionTreeItem>(rows)) { var action = actionRow; var actionMap = actionRow.parent as ActionMapTreeItem; for (var i = actionRow.bindingsCount - 1; i >= 0; i--) { action.RemoveBinding(i); } actionMap.DeleteAction(actionRow.index); } //Remove action maps foreach (var mapRow in FindRowsToDeleteOfType<ActionMapTreeItem>(rows)) { InputActionSerializationHelpers.DeleteActionMap(m_SerializedObject, mapRow.index); } m_Window.Apply(); m_Window.OnSelectionChanged(); } IEnumerable<T> FindRowsToDeleteOfType<T>(InputTreeViewLine[] rows) { return rows.Where(r => r.GetType() == typeof(T)).OrderByDescending(r => r.index).Cast<T>(); } public void AddOptionsToMenu(GenericMenu menu) { var canCopySelection = CanCopySelection(); menu.AddSeparator(""); if (canCopySelection) { menu.AddItem(m_CutGUI, false, () => EditorApplication.ExecuteMenuItem("Edit/Cut")); menu.AddItem(m_CopyGUI, false, () => EditorApplication.ExecuteMenuItem("Edit/Copy")); } else { menu.AddDisabledItem(m_CutGUI, false); menu.AddDisabledItem(m_CopyGUI, false); } menu.AddItem(m_PasteGUI, false, () => EditorApplication.ExecuteMenuItem("Edit/Paste")); menu.AddItem(m_DeleteGUI, false, () => EditorApplication.ExecuteMenuItem("Edit/Delete")); if (canCopySelection) { menu.AddItem(m_Duplicate, false, () => EditorApplication.ExecuteMenuItem("Edit/Duplicate")); } else { menu.AddDisabledItem(m_Duplicate, false); } } } } #endif // UNITY_EDITOR
39.015674
139
0.493974
[ "Apache-2.0" ]
sirslade/ssjAug2018
Packages/com.unity.inputsystem/InputSystem/Editor/InputActionAsset/CopyPasteUtility.cs
12,446
C#
// Copyright (c) 2019 DHGMS Solutions and Contributors. All rights reserved. // This file is licensed to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; namespace Whipstaff.AspNetCore.Features.Generics { /// <summary> /// Helper methods for dealing with generics. /// </summary> public static class GenericHelpers { /// <summary> /// Checks to see if a class is a subclass of a generic class. /// </summary> /// <remarks> /// taken from https://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-generic-class. /// </remarks> /// <param name="generic">The generic class type.</param> /// <param name="toCheck">The type to check.</param> /// <returns>Whether the class is a subclass of a specific generic.</returns> public static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) { Type? temp = toCheck; while (temp != null && temp != typeof(object)) { var cur = temp.IsGenericType ? temp.GetGenericTypeDefinition() : temp; if (generic == cur) { return true; } temp = temp.BaseType; } return false; } } }
33.682927
115
0.573497
[ "MIT" ]
dpvreony/whipstaff
src/Whipstaff.AspNetCore/Features/Generics/GenericHelpers.cs
1,383
C#
using System; using System.Collections.Generic; using De.Osthus.Ambeth.Cache; using De.Osthus.Ambeth.Merge.Model; using De.Osthus.Ambeth.Test.Model; using De.Osthus.Ambeth.Cache.Model; namespace De.Osthus.Ambeth.Xml.Test { public class CacheMock : ICache, IDisposableCache { public void Dispose() { // Intended blank } public void CascadeLoadPath(Type entityType, string cascadeLoadPath) { throw new NotImplementedException(); } public IList<E> GetObjects<E>(params object[] ids) { throw new NotImplementedException(); } public IList<E> GetObjects<E>(IList<object> ids) { throw new NotImplementedException(); } public IList<object> GetObjects(Type type, params object[] ids) { throw new NotImplementedException(); } public IList<object> GetObjects(Type type, IList<object> ids) { throw new NotImplementedException(); } public IList<object> GetObjects(IList<IObjRef> orisToGet, CacheDirective cacheDirective) { IList<object> objs = new List<object>(); foreach (IObjRef ori in orisToGet) { object obj; if (ori == null) { obj = null; } else if (ori is IDirectObjRef) { obj = ((IDirectObjRef)ori).Direct; } else { obj = GetObject(ori.RealType, ori.Id); } objs.Add(obj); } return objs; } public IList<IObjRelationResult> GetObjRelations(IList<IObjRelation> objRels, CacheDirective cacheDirective) { throw new NotImplementedException(); } public object GetObject(IObjRef oriToGet, CacheDirective cacheDirective) { throw new NotImplementedException(); } public object GetObject(Type type, object id) { object obj = Activator.CreateInstance(type); if (obj is Material) { Material material = obj as Material; material.Id = (int)id; material.Version = 1; material.Buid = "Material " + id; material.Name = "Material name " + id; material.MaterialGroup = GetObject<MaterialGroup>(id); } else if (obj is MaterialGroup) { MaterialGroup materialGroup = obj as MaterialGroup; materialGroup.Id = "" + id; materialGroup.Version = 1; materialGroup.Buid = "MaterialGroup " + id; materialGroup.Name = "MaterialGroup name " + id; } return obj; } public object GetObject(Type type, object id, CacheDirective cacheDirective) { throw new NotImplementedException(); } public E GetObject<E>(object id) { return (E)GetObject(typeof(E), id); } public void GetContent(HandleContentDelegate handleContentDelegate) { throw new NotImplementedException(); } public De.Osthus.Ambeth.Util.Lock ReadLock { get { throw new NotImplementedException(); } } public De.Osthus.Ambeth.Util.Lock WriteLock { get { throw new NotImplementedException(); } } public bool Privileged { get { return true; } } public ICache CurrentCache { get { return this; } } } }
27.948529
116
0.524862
[ "Apache-2.0" ]
Dennis-Koch/ambeth
ambeth/Ambeth.Test/ambeth/xml/CacheMock.cs
3,803
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FizzBuzz { class Program { static void Main(string[] args) { foreach(var line in File.ReadAllLines(args[0])) { var numbers = line.Split(new char[] { ' ' }); int m1 = int.Parse(numbers[0]); int m2 = int.Parse(numbers[1]); int end = int.Parse(numbers[2]); for(int i = 1; i <= end; i++) { if (i % m1 != 0 && i % m2 != 0) Console.Write(i); if (i % m1 == 0) Console.Write("F"); if (i % m2 == 0) Console.Write("B"); if (i < end) Console.Write(" "); } Console.WriteLine(); } Console.ReadLine(); } } }
27.114286
69
0.433087
[ "MIT" ]
idstam/codeeval
csharp/FizzBuzz/Program.cs
951
C#
// Copyright (c) Zuzana Dankovcikova. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using BugHunter.Core.ApiReplacementAnalysis; using BugHunter.Core.Constants; using BugHunter.Core.Helpers.DiagnosticDescriptors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace BugHunter.Analyzers.CmsApiReplacementRules.Analyzers { /// <summary> /// Access to one of <c>RegisterArrayDeclaration</c>, <c>RegisterClientScriptBlock</c>, <c>RegisterClientScriptInclude</c>, or <c>RegisterStartupScript</c> /// methods of <c>System.Web.UI.ClientScriptManager</c> /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ClientScriptMethodsAnalyzer : DiagnosticAnalyzer { /// <summary> /// The ID for diagnostics raised by <see cref="ClientScriptMethodsAnalyzer"/> /// </summary> public const string DiagnosticId = DiagnosticIds.ClientScriptMethods; private static readonly DiagnosticDescriptor Rule = ApiReplacementRulesProvider.GetRule(DiagnosticId, "ClientScript methods"); private static readonly ApiReplacementConfig Config = new ApiReplacementConfig( Rule, new[] { "System.Web.UI.ClientScriptManager" }, new[] { "RegisterArrayDeclaration", "RegisterClientScriptBlock", "RegisterClientScriptInclude", "RegisterStartupScript" }); private static readonly ApiReplacementForMethodAnalyzer Analyzer = new ApiReplacementForMethodAnalyzer(Config); /// <inheritdoc /> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); /// <inheritdoc /> public override void Initialize(AnalysisContext context) { Analyzer.RegisterAnalyzers(context); } } }
42.977778
159
0.726991
[ "MIT" ]
Kentico/bug-hunter
src/BugHunter.Analyzers/CmsApiReplacementRules/Analyzers/ClientScriptMethodsAnalyzer.cs
1,934
C#
/* * Copyright (c) 2018 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * http://github.com/piranhacms/piranha * */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Piranha.Models; using Piranha.Repositories; namespace Piranha.Services { public class PostTypeService : IPostTypeService { private readonly IPostTypeRepository _repo; private readonly ICache _cache; /// <summary> /// Default constructor. /// </summary> /// <param name="repo">The main repository</param> /// <param name="cache">The optional model cache</param> public PostTypeService(IPostTypeRepository repo, ICache cache) { _repo = repo; if ((int)App.CacheLevel > 1) { _cache = cache; } } /// <summary> /// Gets all available models. /// </summary> /// <returns>The available models</returns> public Task<IEnumerable<PostType>> GetAllAsync() { return GetTypes(); } /// <summary> /// Gets the model with the specified id. /// </summary> /// <param name="id">The unique i</param> /// <returns></returns> public async Task<PostType> GetByIdAsync(string id) { var types = await GetTypes().ConfigureAwait(false); return types.FirstOrDefault(t => t.Id == id); } /// <summary> /// Adds or updates the given model in the database /// depending on its state. /// </summary> /// <param name="model">The model</param> public async Task SaveAsync(PostType model) { // Validate model var context = new ValidationContext(model); Validator.ValidateObject(model, context, true); // Call hooks & save App.Hooks.OnBeforeSave<PostType>(model); await _repo.Save(model).ConfigureAwait(false); App.Hooks.OnAfterSave<PostType>(model); // Clear cache _cache?.Remove("Piranha_PostTypes"); } /// <summary> /// Deletes the model with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task DeleteAsync(string id) { var model = await _repo.GetById(id).ConfigureAwait(false); if (model != null) { await DeleteAsync(model).ConfigureAwait(false); } } /// <summary> /// Deletes the given model. /// </summary> /// <param name="model">The model</param> public async Task DeleteAsync(PostType model) { // Call hooks & delete App.Hooks.OnBeforeDelete<PostType>(model); await _repo.Delete(model.Id).ConfigureAwait(false); App.Hooks.OnAfterDelete<PostType>(model); // Clear cache _cache?.Remove("Piranha_PostTypes"); } /// <summary> /// Reloads the page types from the database. /// </summary> private async Task<IEnumerable<PostType>> GetTypes() { var types = _cache?.Get<IEnumerable<PostType>>("Piranha_PostTypes"); if (types == null) { types = await _repo.GetAll().ConfigureAwait(false); _cache?.Set("Piranha_PostTypes", types); } return types; } } }
29.96875
81
0.53415
[ "MIT" ]
Bia10/piranha.core
core/Piranha/Services/PostTypeService.cs
3,839
C#
using Bushtail_Sports.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bushtail_Sports.Viewmodel { public class VM_Settings : ViewModelBase { } }
17.428571
44
0.770492
[ "MIT" ]
Lamiput/Bushtail-Sports
Bushtail-Sports/Viewmodel/VM_Settings.cs
246
C#
using System.Text.Json.Serialization; namespace Iot.PnpDashboard.Devices.Dtdl { public class InterfaceSchema { [DTMI] [JsonPropertyName("@id")] public string Id { get; set; } [IRI] [JsonPropertyName("@type")] public string Type { get; set; } [JsonPropertyName("comment")] public string Comment { get; set; } [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("displayName")] public string DisplayName { get; set; } } }
22.96
47
0.592334
[ "MIT" ]
Azure-Samples/azure-iot-dashboard
src/Iot.Pnp.Dashboard/Devices/DTDL/InterfaceSchema.cs
576
C#
using System; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// MybankCreditSceneprodVidGetModel Data Structure. /// </summary> [Serializable] public class MybankCreditSceneprodVidGetModel : AlipayObject { /// <summary> /// 支付宝版本号 /// </summary> [JsonProperty("alipay_version")] public string AlipayVersion { get; set; } /// <summary> /// 机构编码 /// </summary> [JsonProperty("org_code")] public string OrgCode { get; set; } /// <summary> /// 外部站点,比如:ALIPAY:支付宝站点,MYBANK:银行会员,B2B_CN:B2B中文站,B2B_EN:B2B国际站,TAOBAO:淘宝 /// </summary> [JsonProperty("site")] public string Site { get; set; } /// <summary> /// 蚂蚁统一会员ID /// </summary> [JsonProperty("site_user_id")] public string SiteUserId { get; set; } } }
25.324324
82
0.563501
[ "MIT" ]
gebiWangshushu/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/MybankCreditSceneprodVidGetModel.cs
1,039
C#
using System; using System.Text.Json.Serialization; using Trakx.Common.Serialisation.Converters; namespace Trakx.Common.Sources.Messari.DTOs { public partial class MarketData { [JsonPropertyName("price_usd")] public decimal? PriceUsd { get; set; } [JsonPropertyName("price_btc")] public decimal? PriceBtc { get; set; } [JsonPropertyName("volume_last_24_hours")] public decimal? VolumeLast24_Hours { get; set; } [JsonPropertyName("real_volume_last_24_hours")] public decimal? RealVolumeLast24_Hours { get; set; } [JsonPropertyName("volume_last_24_hours_overstatement_multiple")] public decimal? VolumeLast24_HoursOverstatementMultiple { get; set; } [JsonPropertyName("percent_change_usd_last_24_hours")] public double? PercentChangeUsdLast24_Hours { get; set; } [JsonPropertyName("percent_change_btc_last_24_hours")] public double? PercentChangeBtcLast24_Hours { get; set; } [JsonPropertyName("ohlcv_last_1_hour")] public OhlcvLastHour OhlcvLast1_Hour { get; set; } [JsonPropertyName("ohlcv_last_24_hour")] public OhlcvLastHour OhlcvLast24_Hour { get; set; } [JsonPropertyName("last_trade_at")] [JsonConverter(typeof(DateTimeOffsetConverter))] public DateTimeOffset? LastTradeAt { get; set; } } }
34.65
77
0.698413
[ "MIT" ]
fakecoinbase/trakxslashtrakx-tools
src/Trakx.Common/Sources/Messari/DTOs/MarketData.cs
1,388
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 elasticfilesystem-2015-02-01.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.ElasticFileSystem.Model { ///<summary> /// ElasticFileSystem exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class MountTargetNotFoundException : AmazonElasticFileSystemException { /// <summary> /// Constructs a new MountTargetNotFoundException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public MountTargetNotFoundException(string message) : base(message) {} /// <summary> /// Construct instance of MountTargetNotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public MountTargetNotFoundException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of MountTargetNotFoundException /// </summary> /// <param name="innerException"></param> public MountTargetNotFoundException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of MountTargetNotFoundException /// </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 MountTargetNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of MountTargetNotFoundException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public MountTargetNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the MountTargetNotFoundException 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 MountTargetNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.804124
178
0.655448
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ElasticFileSystem/Generated/Model/MountTargetNotFoundException.cs
4,249
C#
/* Exemplary file for Chapter 4 - Data Storage. Recipe: Writing a binary file. */ using CH04.Models; using PropertyChanged; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Windows.Storage; namespace CH04.ViewModels { [ImplementPropertyChanged] public class MainViewModel { public int Minimum { get; set; } public int Maximum { get; set; } public int Average { get; set; } public int Count { get; set; } public int Time { get; set; } public List<ResultViewModel> Results { get; set; } public ICommand CmdStart { get; set; } public ICommand CmdSave { get; set; } public MainViewModel() { Results = new List<ResultViewModel>(); CmdStart = new RelayCommand(() => Start()); CmdSave = new RelayCommand(async () => await Save()); } private void Start() { Results.Clear(); DateTime startTime = DateTime.Now; Minimum = int.MaxValue; Maximum = int.MinValue; Random random = new Random(); for (int i = 0; i < 100000; i++) { int value = random.Next(); int time = (int)(DateTime.Now.Subtract(startTime).TotalMilliseconds); ResultViewModel result = new ResultViewModel() { Value = value, Time = time }; Results.Add(result); } Minimum = Results.Min(r => r.Value); Maximum = Results.Max(r => r.Value); Average = (int)Results.Average(r => r.Value); Count = Results.Count; Time = Results.Last().Time; } private async Task Save() { List<byte> bytes = new List<byte>(); foreach (ResultViewModel result in Results) { byte[] timeBytes = BitConverter.GetBytes(result.Time); byte[] valueBytes = BitConverter.GetBytes(result.Value); bytes.AddRange(timeBytes); bytes.AddRange(valueBytes); } StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("Results.bin", CreationCollisionOption.OpenIfExists); await FileIO.WriteBytesAsync(file, bytes.ToArray()); } } }
31.4125
113
0.549542
[ "MIT" ]
PacktPublishing/Windows-Application-Development-Cookbook
Chapter 4/04-15 - Writing a binary file/MainViewModel.cs
2,513
C#
using System.ComponentModel.DataAnnotations; namespace MediaLibrary.Models { public class Genre : EntityBase { [Required] public string Name { get; set; } } }
17.909091
48
0.624365
[ "MIT" ]
mrbiglari/MediaLibrary
src/MediaLibrary/MediaLibrary/Entity/Genre/Genre.cs
199
C#
namespace More.VisualStudio.Views { using Microsoft.CodeAnalysis.MSBuild; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows; using System.Windows.Interop; using ViewModels; /// <content> /// Provides additional implementation for the <see cref="TypePicker"/> class. /// </content> public partial class TypePicker { /// <summary> /// Represents the proxy that can be used to marshal type selection via another AppDomain. /// </summary> sealed class Proxy : MarshalByRefObject { Assembly localAssembly; IReadOnlyList<AssemblyName> localAssemblyReferences; [SuppressMessage( "Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "False positive. The field is initialized inline and a method cannot be called any other way." )] static Proxy() => SetDefaultTypeBrowserSize( new Size( 500, 500 ) ); public bool? ShowDialog( IntPtr owner ) { var model = new TypeBrowserViewModel() { NameConvention = NameConvention, FilterByConvention = !string.IsNullOrEmpty( NameConvention ), LocalAssembly = localAssembly }; model.RestrictedBaseTypeNames.AddRange( RestrictedBaseTypeNames ?? Enumerable.Empty<string>() ); model.LocalAssemblyReferences.AddRange( localAssemblyReferences ); using ( var view = new TypeBrowserDialog( model ) ) { var helper = new WindowInteropHelper( view ) { Owner = owner }; if ( !string.IsNullOrEmpty( Title ) ) { model.Title = Title; } var result = view.ShowDialog(); if ( ( result ?? false ) ) { SelectedType = new SimpleType( model.SelectedType ); } helper.Owner = IntPtr.Zero; return result; } } static void SetDefaultTypeBrowserSize( Size size ) { // HACK: there seems to be no way in the api to set the default TypeBrowser size (which is an internal type) // using TypePresenter or Style was considered, but no other workable solution was found. the // TypeBrowser does remember it's size between calls, but in most scenarios this only occurs once // and the assembly is unloaded because it's in another AppDomain (which restarts the process) var assemblyName = typeof( System.Activities.Presentation.View.TypePresenter ).Assembly.FullName; var typeName = "System.Activities.Presentation.View.TypeBrowser, " + assemblyName; var type = Type.GetType( typeName, true ); var field = type.GetField( "size", BindingFlags.Static | BindingFlags.NonPublic ); field.SetValue( null, size ); } public async Task CreateLocalAssemblyAsync( AssemblyName localAssemblyName ) { Contract.Requires( localAssemblyName != null ); Contract.Ensures( Contract.Result<Task>() != null ); try { var result = await CreateDynamicAssemblyAsync( SourceProject, localAssemblyName.ContentType ); if ( ( localAssembly = result.Item1 ) != null ) { localAssemblyReferences = result.Item2 ?? localAssembly.GetReferencedAssemblies(); return; } } catch { Debug.WriteLine( "Dynamic assembly generation failed." ); } if ( ( localAssembly = LoadLocalAssemblyFromExistingBuild( SourceProject ) ) == null ) { localAssemblyReferences = Array.Empty<AssemblyName>(); } else { localAssemblyReferences = localAssembly.GetReferencedAssemblies(); } } static async Task<Tuple<Assembly, IReadOnlyList<AssemblyName>>> CreateDynamicAssemblyAsync( ProjectInformation projectInfo, AssemblyContentType contentType ) { Contract.Ensures( Contract.Result<Task<Tuple<Assembly, IReadOnlyList<AssemblyName>>>>() != null ); var rawAssembly = default( byte[] ); var referencedAssemblies = default( IReadOnlyList<AssemblyName> ); if ( projectInfo == null ) { referencedAssemblies = Array.Empty<AssemblyName>(); return Tuple.Create( default( Assembly ), referencedAssemblies ); } using ( var workspace = MSBuildWorkspace.Create() ) { var project = await workspace.OpenProjectAsync( projectInfo.ProjectPath ).ConfigureAwait( false ); var compilation = await project.GetCompilationAsync().ConfigureAwait( false ); using ( var stream = new MemoryStream() ) { var result = compilation.Emit( stream ); if ( !result.Success ) { referencedAssemblies = Array.Empty<AssemblyName>(); return Tuple.Create( default( Assembly ), referencedAssemblies ); } rawAssembly = stream.ToArray(); } // loading assemblies from binary will result in no location information being available. to ensure that referenced // assemblies can be resolved, build a list of referenced assembly names from the metadata referencedAssemblies = project.MetadataReferences.Select( mr => AssemblyName.GetAssemblyName( mr.Display ) ).ToArray(); } var assembly = Assembly.ReflectionOnlyLoad( rawAssembly ); return Tuple.Create( assembly, referencedAssemblies ); } static Assembly LoadLocalAssemblyFromExistingBuild( ProjectInformation projectInfo ) { if ( projectInfo == null ) { return null; } var assemblyFile = projectInfo.TargetPath; if ( !File.Exists( assemblyFile ) ) { return null; } Debug.WriteLine( $"Attempting to load existing assembly from {assemblyFile}." ); return Assembly.ReflectionOnlyLoadFrom( assemblyFile ); } public string Title { get; set; } public Type SelectedType { get; set; } public string NameConvention { get; set; } public string[] RestrictedBaseTypeNames { get; set; } public ProjectInformation SourceProject { get; set; } } } }
41.065217
220
0.54685
[ "MIT" ]
JTOne123/More
src/Sdk/More.VisualStudio.TemplateWizards/Views/TypePicker.Proxy.cs
7,558
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class VTrajectory : ITrajectory { private VTrajectoryData _data; public StraightTrajectory[] _straights; private float[] _xPos = new float[3]; private StraightTrajectory _currentTrajectory; public void Init(ITrajectoryData data) { if (data is VTrajectoryData) { _data = data as VTrajectoryData; } else { Debug.LogError("当前传入数据类型错误,传入类型为:"+data); } _xPos = _data.XPos; InitStraights(_data); _currentTrajectory = _straights[0]; } private void InitStraights(VTrajectoryData data) { _straights = new StraightTrajectory[2]; _straights[0] = new StraightTrajectory(); _straights[0].Init((float)data.Angle); _straights[1] = new StraightTrajectory(); _straights[1].Init(-(float)data.Angle); } public float[] GetY(float x, Vector2 startPos) { _currentTrajectory = _straights[GetTrajectoryIndex(x)]; return _currentTrajectory.GetY(x, startPos); } private int GetTrajectoryIndex(float x) { if (x < _xPos[1]) { return 0; } else { return 1; } } public float[] GetX(float y, Vector2 startPos) { Debug.LogError("W轨迹的GetX方法无法获取正确的值"); return null; } public bool SetCurrentTrajectory(float x) { if (x >= _xPos[0] && x <= _xPos[2]) { _currentTrajectory = _straights[GetTrajectoryIndex(x)]; return true; } else { return false; } } public Vector2 GetDirection() { return _currentTrajectory.GetDirection(); } public float GetZRotate() { return 0; } }
22.662651
67
0.572568
[ "MIT" ]
BlueMonk1107/AirCombatGameDemo
Assets/Scripts/Logic/Trajectory/VTrajectory.cs
1,943
C#
using System; using System.Threading.Tasks; using Crunch.NET.Request; using Microsoft.Extensions.Logging; namespace Bot.Builder.Community.Adapters.Crunch.Core { /// <summary> /// Alexa Authorization Handler. /// </summary> public class AlexaAuthorizationHandler { /// <summary> /// SignatureCertChainUrl header name. /// </summary> public const string SignatureCertChainUrlHeader = @"SignatureCertChainUrl"; /// <summary> /// Signature header name. /// </summary> public const string SignatureHeader = @"Signature"; private readonly ILogger _logger; public AlexaAuthorizationHandler(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <summary> /// Verify the skill request is for the skill with the specified skill id. /// </summary> /// <param name="skillRequest">Incoming SkillRequest from Alexa.</param> /// <param name="alexaSkillId">Alexa Skill Id.</param> /// <returns>True if the SkillRequest is for this skill.</returns> public virtual bool ValidateSkillId(CrunchRequest skillRequest, string alexaSkillId) { return true; } /// <summary> /// Authorize the SkillRequest is coming from Alexa. /// </summary> /// <param name="skillRequest">Incoming SkillRequest from Alexa.</param> /// <param name="requestBody">Full request body from Alexa.</param> /// <param name="signatureChainUrl">Signature Chain Url. This is the SignatureCertChainUrl header value.</param> /// <param name="signature">Signature. This is the Signature header value.</param> /// <returns>True if this is a valid SkillRequest otherwise false.</returns> public virtual async Task<bool> ValidateSkillRequest(CrunchRequest skillRequest, string requestBody, string signatureChainUrl, string signature) { if (skillRequest == null) { _logger.LogError("Validation failed. No incoming skill request."); return false; } if (string.IsNullOrWhiteSpace(signatureChainUrl)) { _logger.LogError("Validation failed. Empty SignatureCertChainUrl header."); return false; } Uri certUrl; try { certUrl = new Uri(signatureChainUrl); } catch { _logger.LogError($"Validation failed. SignatureChainUrl not valid: {signatureChainUrl}."); return false; } if (string.IsNullOrWhiteSpace(signature)) { _logger.LogError("Validation failed. Empty Signature header."); return false; } if (!RequestVerification.RequestTimestampWithinTolerance(skillRequest)) { _logger.LogError("Validation failed. Request timestamp outside of tolerance."); return false; } if (!await RequestVerification.Verify(signature, certUrl, requestBody)) { _logger.LogError("Validation failed. Alexa certificate validation failed."); return false; } return true; } } }
36.052632
152
0.590365
[ "MIT" ]
heckej/Music-master
MusicMaster/MusicMasterBot/MusicMasterBot/Bot.Builder.Community.Adapters.Alexa.Core/AlexaAuthorizationHandler.cs
3,427
C#
using System; namespace UtmCliUtility { public static class EnumerableHelper { public static int FirstIndexOf<T>(this T[] array, Func<T, bool> predicate) { for (int i = 0; i < array.Length; i++) { if (predicate(array[i])) return i; } throw new Exception(); } public static bool FirstIndexOf<T>(this T[] array, Func<T, bool> predicate, out int index) { index = 0; for (int i = 0; i < array.Length; i++) { if (predicate(array[i])) { index = i; return true; } } return false; } } }
24.322581
98
0.428382
[ "MIT" ]
sharakadi/utm-cli-utility
EnumerableHelper.cs
756
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Network.Models; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Network { [Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "LoadBalancerInboundNatPoolConfig"), OutputType(typeof(PSLoadBalancer))] public class RemoveAzureLoadBalancerInboundNatPoolConfigCommand : NetworkBaseCmdlet { [Parameter( Mandatory = false, HelpMessage = "The name of the Inbound NAT pool")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipeline = true, HelpMessage = "The loadbalancer")] public PSLoadBalancer LoadBalancer { get; set; } public override void Execute() { base.Execute(); var inboundNatPool = this.LoadBalancer.InboundNatPools.SingleOrDefault(resource => string.Equals(resource.Name, this.Name, System.StringComparison.CurrentCultureIgnoreCase)); if (inboundNatPool != null) { this.LoadBalancer.InboundNatPools.Remove(inboundNatPool); } WriteObject(this.LoadBalancer); } } }
40.254902
187
0.616171
[ "MIT" ]
FonsecaSergio/azure-powershell
src/ResourceManager/Network/Commands.Network/LoadBalancer/InboundNatPool/RemoveAzureLoadBalancerInboundNatPoolConfigCommand.cs
2,005
C#
// Copyright (c) Gurmit Teotia. Please see the LICENSE file in the project root for license information. using System.Linq; using Amazon.SimpleWorkflow; using Guflow.Decider; using Guflow.Tests.TestWorkflows; using Moq; using NUnit.Framework; namespace Guflow.Tests.Decider { [TestFixture] public class ActivityCompletedEventTests { private const string Result = "result"; private const string ActivityName = "Download"; private const string ActivityVersion = "1.0"; private const string PositionalName = "First"; private const string Identity = "machine name"; private const string Input = "input"; private ActivityCompletedEvent _activityCompletedEvent; private EventGraphBuilder _builder; private ScheduleId _scheduleId; [SetUp] public void Setup() { _builder = new EventGraphBuilder(); _scheduleId = Guflow.Decider.Identity.New(ActivityName, ActivityVersion, PositionalName).ScheduleId(); var completedActivityEventGraph = _builder.ActivityCompletedGraph(_scheduleId, Identity, Result,Input); _activityCompletedEvent = new ActivityCompletedEvent(completedActivityEventGraph.First(), completedActivityEventGraph); } [Test] public void Populate_activity_details_from_history_events() { Assert.That(_activityCompletedEvent.Result, Is.EqualTo(Result)); Assert.That(_activityCompletedEvent.WorkerIdentity, Is.EqualTo(Identity)); Assert.That(_activityCompletedEvent.IsActive,Is.False); Assert.That(_activityCompletedEvent.Input,Is.EqualTo(Input)); } [Test] public void Throws_exception_when_completed_activity_is_not_found_in_workflow() { var incompatibleWorkflow = new EmptyWorkflow(); Assert.Throws<IncompatibleWorkflowException>(()=> _activityCompletedEvent.Interpret(incompatibleWorkflow)); } [Test] public void Does_not_populate_worker_id_when_activity_started_event_not_found_in_event_graph() { var completedActivityEventGraph = _builder.ActivityCompletedGraph(_scheduleId, Identity, Result); var activityCompletedEvent= new ActivityCompletedEvent(completedActivityEventGraph.First(), completedActivityEventGraph.Where(h=>h.EventType!=EventType.ActivityTaskStarted)); Assert.That(activityCompletedEvent.WorkerIdentity,Is.Null); } [Test] public void Throws_exception_when_activity_scheduled_event_not_found_in_event_graph() { var completedActivityEventGraph = _builder.ActivityCompletedGraph(_scheduleId, Identity, Result); Assert.Throws<IncompleteEventGraphException>(() => new ActivityCompletedEvent(completedActivityEventGraph.First(), completedActivityEventGraph.Where(h => h.EventType != EventType.ActivityTaskScheduled))); } [Test] public void By_default_return_continue_workflow_action() { var workflow = new SingleActivityWorkflow(); var workflowAction = _activityCompletedEvent.Interpret(workflow); Assert.That(workflowAction,Is.EqualTo(WorkflowAction.ContinueWorkflow(new ActivityItem(Guflow.Decider.Identity.New(ActivityName,ActivityVersion,PositionalName),null)))); } [Test] public void Can_return_custom_workflow_action() { var workflowAction = new Mock<WorkflowAction>(); var workflow = new WorkflowWithCustomAction(workflowAction.Object); var interpretedAction = _activityCompletedEvent.Interpret(workflow); Assert.That(interpretedAction,Is.EqualTo(workflowAction.Object)); } private class SingleActivityWorkflow : Workflow { public SingleActivityWorkflow() { ScheduleActivity(ActivityName,ActivityVersion,PositionalName); } } private class WorkflowWithCustomAction : Workflow { public WorkflowWithCustomAction(WorkflowAction workflowAction) { ScheduleActivity(ActivityName, ActivityVersion, PositionalName).OnCompletion(c => workflowAction); } } } }
41.209524
216
0.693552
[ "Apache-2.0" ]
Seekatar/guflow
Guflow.Tests/Decider/Activity/ActivityCompletedEventTests.cs
4,329
C#
#region License // Copyright 2004-2010 Castle Project - http://www.castleproject.org/ // // 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 namespace Castle.Facilities.NHibernateIntegration.SessionStores { using System; using System.Collections; using NHibernate; /// <summary> /// /// </summary> public abstract class AbstractSessionStore : MarshalByRefObject, ISessionStore { /// <summary> /// Gets the stack of <see cref="SessionDelegate"/> objects for the specified <paramref name="alias"/>. /// </summary> /// <param name="alias">The alias.</param> /// <returns></returns> protected abstract Stack GetStackFor(String alias); /// <summary> /// Should return a previously stored session /// for the given alias if available, otherwise null. /// </summary> /// <param name="alias"></param> /// <returns></returns> public SessionDelegate FindCompatibleSession(String alias) { var stack = GetStackFor(alias); if (stack.Count == 0) return null; return stack.Peek() as SessionDelegate; } /// <summary> /// Should store the specified session instance /// </summary> /// <param name="alias"></param> /// <param name="session"></param> public void Store(String alias, SessionDelegate session) { var stack = GetStackFor(alias); stack.Push(session); session.SessionStoreCookie = stack; } /// <summary> /// Should remove the session from the store /// only. /// </summary> /// <param name="session"></param> public void Remove(SessionDelegate session) { var stack = (Stack) session.SessionStoreCookie; if (stack == null) { throw new InvalidProgramException("AbstractSessionStore.Remove called " + "with no cookie - no pun intended"); } if (stack.Count == 0) { throw new InvalidProgramException("AbstractSessionStore.Remove called " + "for an empty stack"); } var current = stack.Peek() as ISession; if (session != current) { throw new InvalidProgramException("AbstractSessionStore.Remove tried to " + "remove a session which is not on the top or not in the stack at all"); } stack.Pop(); } /// <summary> /// Returns <c>true</c> if the current activity /// (which is an execution activity context) has no /// sessions available /// </summary> /// <param name="alias"></param> /// <returns></returns> public bool IsCurrentActivityEmptyFor(String alias) { var stack = GetStackFor(alias); var statelessSessionStack = GetStatelessSessionStackFor(alias); return stack.Count == 0 && statelessSessionStack.Count == 0; } /// <summary> /// Gets the stack of <see cref="StatelessSessionDelegate"/> objects /// for the specified <paramref name="alias"/>. /// </summary> /// <param name="alias">The alias.</param> /// <returns></returns> protected abstract Stack GetStatelessSessionStackFor(String alias); /// <summary> /// Should return a previously stored stateless session /// for the given alias if available, otherwise null. /// </summary> /// <param name="alias"></param> /// <returns></returns> public StatelessSessionDelegate FindCompatibleStatelessSession(string alias) { var stack = GetStatelessSessionStackFor(alias); if (stack.Count == 0) return null; return stack.Peek() as StatelessSessionDelegate; } /// <summary> /// Should store the specified stateless session instance. /// </summary> /// <param name="alias"></param> /// <param name="session"></param> public void Store(string alias, StatelessSessionDelegate session) { var stack = GetStatelessSessionStackFor(alias); stack.Push(session); session.SessionStoreCookie = stack; } /// <summary> /// Should remove the stateless session from the store only. /// </summary> /// <param name="session"></param> public void Remove(StatelessSessionDelegate session) { var stack = (Stack) session.SessionStoreCookie; if (stack == null) { throw new InvalidProgramException("AbstractSessionStore.Remove called " + "with no cookie - no pun intended"); } if (stack.Count == 0) { throw new InvalidProgramException("AbstractSessionStore.Remove called " + "for an empty stack"); } var current = stack.Peek() as IStatelessSession; if (session != current) { throw new InvalidProgramException("AbstractSessionStore.Remove tried to " + "remove a session which is not on the top or not in the stack at all"); } stack.Pop(); } } }
29.010989
106
0.647538
[ "Apache-2.0" ]
ByteDecoder/Castle.Facilities.NHibernateIntegration
src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractSessionStore.cs
5,099
C#
// Copyright 2019 faddenSoft. All Rights Reserved. // See the LICENSE.txt file for distribution terms (Apache 2.0). using System; using System.Collections.Generic; using PluginCommon; namespace RuntimeData.Test2022 { public class Test2022B : MarshalByRefObject, IPlugin, IPlugin_InlineBrk { private IApplication mAppRef; private byte[] mFileData; private AddressTranslate mAddrTrans; public string Identifier { get { return "Test 2022-extension-scripts B"; } } public void Prepare(IApplication appRef, byte[] fileData, AddressTranslate addrTrans) { mAppRef = appRef; mFileData = fileData; mAddrTrans = addrTrans; mAppRef.DebugLog("Test2022-B(id=" + AppDomain.CurrentDomain.Id + "): prepare()"); } public void Unprepare() { mAppRef = null; mFileData = null; mAddrTrans = null; } public void CheckBrk(int offset, bool twoByteBrk, out bool noContinue) { noContinue = true; // need BRK, function byte, and two-byte address if (!Util.IsInBounds(mFileData, offset, 4)) { return; } byte func = mFileData[offset + 1]; if (func != 0x85 && (func < 0x01 || func > 0x02)) { return; } Util.FormatBrkByte(mAppRef, twoByteBrk, offset, DataSubType.Hex, null); mAppRef.SetInlineDataFormat(offset + 2, 2, DataType.NumericLE, DataSubType.Address, null); noContinue = false; int structAddr = Util.GetWord(mFileData, offset + 2, 2, false); int structOff = mAddrTrans.AddressToOffset(offset, structAddr); if (structOff < 0) { mAppRef.DebugLog("Unable to get offset for address $" + structAddr.ToString("x6")); return; } switch (func) { case 0x01: if (!Util.IsInBounds(mFileData, structOff, 27)) { mAppRef.DebugLog("Struct doesn't fit in file"); return; } mAppRef.SetInlineDataFormat(structOff + 0, 2, DataType.NumericLE, DataSubType.Decimal, null); mAppRef.SetInlineDataFormat(structOff + 2, 2, DataType.NumericBE, DataSubType.Hex, null); mAppRef.SetInlineDataFormat(structOff + 4, 4, DataType.NumericLE, DataSubType.Hex, null); mAppRef.SetInlineDataFormat(structOff + 8, 4, DataType.NumericBE, DataSubType.Hex, null); mAppRef.SetInlineDataFormat(structOff + 12, 1, DataType.NumericLE, DataSubType.Ascii, null); mAppRef.SetInlineDataFormat(structOff + 13, 1, DataType.NumericLE, DataSubType.HighAscii, null); mAppRef.SetInlineDataFormat(structOff + 14, 8, DataType.StringDci, DataSubType.Ascii, null); mAppRef.SetInlineDataFormat(structOff + 22, 3, DataType.NumericLE, DataSubType.Address, null); mAppRef.SetInlineDataFormat(structOff + 25, 2, DataType.NumericLE, DataSubType.Symbol, "data02"); break; case 0x02: if (!Util.IsInBounds(mFileData, structOff, 2)) { mAppRef.DebugLog("Struct doesn't fit in file"); return; } mAppRef.SetInlineDataFormat(structOff, 2, DataType.NumericLE, DataSubType.Address, null); int nextAddr = Util.GetWord(mFileData, structOff + 2, 2, false); int nextOff = mAddrTrans.AddressToOffset(structOff, nextAddr); if (!Util.IsInBounds(mFileData, nextOff, 1)) { mAppRef.DebugLog("Struct doesn't fit in file"); return; } mAppRef.SetInlineDataFormat(nextOff, 8, DataType.StringGeneric, DataSubType.HighAscii, null); break; case 0x85: // do nothing further break; } } } }
41.971963
99
0.524605
[ "Apache-2.0" ]
Michaelangel007/6502bench
SourceGen/SGTestData/2022-extension-scripts-b.cs
4,493
C#
using System; using System.Linq; using CMS.DataEngine; using CMS.Ecommerce; using CMS.Ecommerce.Web.UI; using CMS.FormEngine.Web.UI; using CMS.Helpers; using CMS.SiteProvider; using CMS.UIControls; public partial class CMSModules_Ecommerce_FormControls_DepartmentSelector : SiteSeparatedObjectSelector { #region "Variables and constants" private const int WITHOUT_DEPARTMENT = -5; private bool mReflectGlobalProductsUse; private bool mDropDownListMode = true; private bool mAddWithoutDepartmentRecord; private bool mShowAllSites; #endregion #region "Properties" /// <summary> /// Allows to access uniselector object /// </summary> public override UniSelector UniSelector { get { return uniSelector; } } /// <summary> /// If true, selected value is DepartmentName, if false, selected value is DepartmentID. /// </summary> public override bool UseNameForSelection { get { return ValidationHelper.GetBoolean(GetValue("UseDepartmentNameForSelection"), base.UseNameForSelection); } set { SetValue("UseDepartmentNameForSelection", value); base.UseNameForSelection = value; } } /// <summary> /// Returns ClientID of the dropdown list. /// </summary> public override string ValueElementID { get { if (DropDownListMode) { return uniSelector.DropDownSingleSelect.ClientID; } return uniSelector.TextBoxSelect.ClientID; } } /// <summary> /// Indicates whether global items are to be offered. /// </summary> public override bool DisplayGlobalItems { get { return base.DisplayGlobalItems || (ReflectGlobalProductsUse && ECommerceSettings.AllowGlobalProducts(SiteID)); } set { base.DisplayGlobalItems = value; } } /// <summary> /// Gets or sets a value that indicates if the global items should be displayed when the global products are used on the site. /// </summary> public bool ReflectGlobalProductsUse { get { return ValidationHelper.GetBoolean(GetValue("ReflectGlobalProductsUse"), mReflectGlobalProductsUse); } set { SetValue("ReflectGlobalProductsUse", value); mReflectGlobalProductsUse = value; } } /// <summary> /// Indicates if drop down list mode is used. Default value is true. /// </summary> public bool DropDownListMode { get { return ValidationHelper.GetBoolean(GetValue("DropDownListMode"), mDropDownListMode); } set { SetValue("DropDownListMode", value); mDropDownListMode = value; } } /// <summary> /// Gets or sets the value which determines, whether to add 'without department' item record to the dropdown list. /// </summary> public bool AddWithoutDepartmentRecord { get { return ValidationHelper.GetBoolean(GetValue("AddWithoutDepartmentRecord"), mAddWithoutDepartmentRecord); } set { SetValue("AddWithoutDepartmentRecord", value); mAddWithoutDepartmentRecord = value; } } /// <summary> /// Gets the value of 'Without department' record. /// </summary> public int WithoutDepartmentRecordValue { get { return WITHOUT_DEPARTMENT; } } /// <summary> /// Indicates whether departments from all sites are to be shown. Default value is false. /// </summary> public virtual bool ShowAllSites { get { return ValidationHelper.GetBoolean(GetValue("ShowAllSites"), mShowAllSites); } set { mShowAllSites = value; SetValue("ShowAllSites", value); } } #endregion #region "Lifecycle" protected override void OnInit(EventArgs e) { uniSelector.SelectionMode = (DropDownListMode ? SelectionModeEnum.SingleDropDownList : SelectionModeEnum.SingleTextBox); base.OnInit(e); } protected override void OnLoad(EventArgs e) { TryInitByForm(); base.OnLoad(e); } protected override void OnPreRender(EventArgs e) { if (RequestHelper.IsPostBack() && DependsOnAnotherField) { InitSelector(); } uniSelector.Reload(true); base.OnPreRender(e); } #endregion #region "Initialization" protected override void InitSelector() { // Add special records if (AddWithoutDepartmentRecord) { uniSelector.SpecialFields.Add(new SpecialField { Text = GetString("general.empty"), Value = WithoutDepartmentRecordValue.ToString() }); } base.InitSelector(); if (ShowAllSites) { uniSelector.FilterControl = "~/CMSFormControls/Filters/SiteFilter.ascx"; uniSelector.SetValue("FilterMode", "department"); } if (UseNameForSelection) { uniSelector.AllRecordValue = ""; uniSelector.NoneRecordValue = ""; } } /// <summary> /// Convert given department name to its ID for specified site. /// </summary> /// <param name="name">Name of the department to be converted.</param> /// <param name="siteName">Name of the site of the department.</param> protected override int GetID(string name, string siteName) { DepartmentInfo dept; if (ShowAllSites) { // Take any department dept = DepartmentInfoProvider.GetDepartments() .TopN(1) .WithCodeName(name) .OrderByAscending("DepartmentSiteID") .FirstOrDefault(); } else { dept = DepartmentInfoProvider.GetDepartmentInfo(name, siteName); } return dept?.DepartmentID ?? 0; } /// <summary> /// Appends site where to given where condition. /// </summary> /// <param name="where">Original where condition to append site where to.</param> protected override string AppendSiteWhere(string where) { // Do not filter by site when showing all sites departments if (ShowAllSites) { return where; } return base.AppendSiteWhere(where); } private void TryInitByForm() { if ((Value != null) || (Form == null) || !Form.AdditionalData.ContainsKey("DataClassID")) { return; } var dataClassId = ValidationHelper.GetInteger(Form.AdditionalData["DataClassID"], 0); var dataClass = DataClassInfoProvider.GetDataClassInfo(dataClassId); if (dataClass != null) { var department = DepartmentInfoProvider.GetDepartmentInfo(dataClass.ClassSKUDefaultDepartmentName, SiteInfoProvider.GetSiteName(SiteID)); if (department == null) { return; } Value = (UseNameForSelection) ? dataClass.ClassSKUDefaultDepartmentName : department.DepartmentID.ToString(); } } #endregion }
25.084175
149
0.594228
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/Ecommerce/FormControls/DepartmentSelector.ascx.cs
7,452
C#
using Saucery.Dojo; using Saucery.Options.Base; using Saucery.Options.ConcreteProducts; namespace Saucery.Options.ConcreteCreators; internal class EdgeCreator : Creator { public override BaseOptions Create(BrowserVersion browserVersion, string testName) { return new EdgeBrowserOptions(browserVersion, testName); } } /* * Copyright Andrew Gray, SauceForge * Date: 5th February 2020 * */
25.375
88
0.773399
[ "MIT" ]
Sauceforge/Saucery
Saucery/Options/ConcreteCreators/EdgeCreator.cs
408
C#
#pragma checksum "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "46e08a7b483874cbac43a0f385b1d02207927a1c" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Room_Create), @"mvc.1.0.view", @"/Views/Room/Create.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\CastleChat\CastleChat\Views\_ViewImports.cshtml" using CastleChat; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\CastleChat\CastleChat\Views\_ViewImports.cshtml" using CastleChat.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"46e08a7b483874cbac43a0f385b1d02207927a1c", @"/Views/Room/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e8b580e13bf9a297530e5b3c79e406951892c64b", @"/Views/_ViewImports.cshtml")] public class Views_Room_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<CastleChat.Models.Room> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("enctype", new global::Microsoft.AspNetCore.Html.HtmlString("multipart/form-data"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 2 "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" ViewData["Title"] = "Create"; #line default #line hidden #nullable disable WriteLiteral("<h1 class=\"text-center\">Create</h1>\r\n"); #nullable restore #line 6 "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" if (ViewBag.Error != null) { #line default #line hidden #nullable disable WriteLiteral(" <h4 class=\"text-danger\">"); #nullable restore #line 8 "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" Write(ViewBag.Error); #line default #line hidden #nullable disable WriteLiteral("</h4>\r\n"); #nullable restore #line 9 "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" } #line default #line hidden #nullable disable WriteLiteral("\r\n<script src=\"https://cdn.tiny.cloud/1/uvgdoko25cnan2u4rt9n9uat33hvoah26qqhieavnv49kfxy/tinymce/5/tinymce.min.js\" referrerpolicy=\"origin\"></script>\r\n<center>\r\n <div>\r\n <div>\r\n\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "46e08a7b483874cbac43a0f385b1d02207927a1c4825", async() => { WriteLiteral("\r\n <div class=\"alert alert-secondary border-0\" style=\"width: 100%;\">Castle: "); #nullable restore #line 17 "D:\CastleChat\CastleChat\Views\Room\Create.cshtml" Write(ViewBag.Castle.title); #line default #line hidden #nullable disable WriteLiteral(@"</div> <input name=""title"" class=""form-control"" type=""text"" placeholder=""Room Title"" style=""width: 100%;"" /><br> <textarea name=""text"" class=""form-control"" style=""width: 100%; height:500px;"" id=""summernote""></textarea><br> <small>*Optional</small> <input type=""file"" name=""file"" class=""form-control"" style=""width: 100%;"" accept=""image/*""><br> <input type=""submit"" value=""Create"" class=""btn btn-outline-secondary"" style=""width: 100%"" /> "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n </div>\r\n <script>tinymce.init({ selector: \'textarea\' });</script>\r\n\r\n</center>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<CastleChat.Models.Room> Html { get; private set; } } } #pragma warning restore 1591
57.852113
359
0.72112
[ "MIT" ]
yosa12978/CastleChat
CastleChat/obj/Debug/netcoreapp3.1/Razor/Views/Room/Create.cshtml.g.cs
8,215
C#
namespace StardewMods.FuryCore.Models.CustomEvents; using System; using System.Collections.Generic; using StardewMods.FuryCore.Interfaces.CustomEvents; using StardewMods.FuryCore.Interfaces.GameObjects; /// <inheritdoc cref="StardewMods.FuryCore.Interfaces.CustomEvents.IGameObjectsRemovedEventArgs" /> internal class GameObjectsRemovedEventArgs : EventArgs, IGameObjectsRemovedEventArgs { /// <summary> /// Initializes a new instance of the <see cref="GameObjectsRemovedEventArgs" /> class. /// </summary> /// <param name="removed">The <see cref="IGameObject" /> removed.</param> internal GameObjectsRemovedEventArgs(IEnumerable<IGameObject> removed) { this.Removed = removed; } /// <inheritdoc /> public IEnumerable<IGameObject> Removed { get; } }
36.409091
99
0.745318
[ "MIT" ]
Brex09/StardewMods
FuryCore/Models/CustomEvents/GameObjectsRemovedEventArgs.cs
803
C#
// Copyright 2017 Google Inc. 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. using GoogleCloudExtension.Utils; using System.IO; namespace GoogleCloudExtension.VsVersion.VS15 { /// <summary> /// The implementation of <seealso cref="Deployment.IToolsPathProvider"/> for Visual Studio 2017 (v 15.0). /// </summary> internal class ToolsPathProvider : ToolsPathProviderBase { public const string MSBuildSubPath = @"MSBuild\15.0\Bin\MSBuild.exe"; public override string GetMsbuildPath() { string result = Path.Combine(VsRootDirectoryPath, MSBuildSubPath); GcpOutputWindow.Default.OutputDebugLine($"Msbuild V15 Path: {result}"); return result; } } }
36.314286
110
0.707317
[ "Apache-2.0" ]
amanda-tarafa/google-cloud-visualstudio
GoogleCloudExtension/GoogleCloudExtension/VsVersion/VS15/ToolsPathProvider.cs
1,273
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Material.Demo.Pages { public class TypographyDemo : UserControl { public TypographyDemo() { this.InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
18.1
45
0.60221
[ "MIT" ]
Al-Dyachkov/Material.Avalonia
Material.Demo/Pages/TypographyDemo.axaml.cs
364
C#
using System.Collections.Generic; using RiotGamesApi.Enums; using RiotGamesApi.Libraries.Lol.Enums; using RiotGamesApi.Libraries.Lol.v3.NonStaticEndPoints.ChampionMastery; using RiotGamesApi.Models; using RiotGamesApi.Tests.Others; using Xunit; namespace RiotGamesApi.Tests.RiotGamesApis { public class CHAMPION_MASTERY_V3 : BaseTestClass { [Fact] public void GetChampionMasteries() { var rit = new ApiCall() .SelectApi<List<ChampionMasteryDto>>(LolApiName.ChampionMastery) .For(LolApiMethodName.ChampionMasteries) .AddParameter(new ApiParameter(LolApiPath.BySummoner, SummonerId)) .Build(Service_Platform) .Get(); Assert.False(rit.HasError); } [Fact] public void GetChampionMastery() { var rit = new ApiCall() .SelectApi<ChampionMasteryDto>(LolApiName.ChampionMastery) .For(LolApiMethodName.ChampionMasteries) .AddParameter(new ApiParameter(LolApiPath.BySummoner, SummonerId), new ApiParameter(LolApiPath.ByChampion, ChampionId)) .Build(Service_Platform) .Get(); Assert.False(rit.HasError); } [Fact] public void GetChampionScore() { var rit = new ApiCall() .SelectApi<int>(LolApiName.ChampionMastery) .For(LolApiMethodName.Scores) .AddParameter(new ApiParameter(LolApiPath.BySummoner, SummonerId)) .Build(Service_Platform) .Get(); Assert.False(rit.HasError); } } }
34.4
83
0.6
[ "MIT" ]
msx752/RiotGamesAPI
RiotGamesApi.Tests/RiotGamesApis/CHAMPION_MASTERY_V3.cs
1,722
C#
using System; using System.ComponentModel.DataAnnotations; using System.Globalization; namespace ModernSlavery.WebUI.Shared.Classes.Attributes { /// <summary> /// This attribute is used in place of MaxLengthAttribute to avoid rendering of maxlength attributes onto form fields /// The code was copied from https://github.com/microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/MaxLengthAttribute.cs /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)] public class TextLengthAttribute : ValidationAttribute { private const int MaxAllowableLength = -1; private const string InvalidMaxLength= "TextLengthAttribute must have a Length value that is greater than zero.Use TextLength() without parameters to indicate that the string or array can have the maximum allowable length."; private const string ValidationError = "The field {0} must be a string or array type with a maximum length of '{1}'."; /// <summary> /// Gets the maximum allowable length of the array/string data. /// </summary> public int Length { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="TextLengthAttribute"/> class. /// </summary> /// <param name="length"> /// The maximum allowable length of array/string data. /// Value must be greater than zero. /// </param> public TextLengthAttribute(int length) : base(() => DefaultErrorMessageString) { Length = length; } private static string DefaultErrorMessageString =>ValidationError; /// <summary> /// Determines whether a specified object is valid. (Overrides <see cref = "ValidationAttribute.IsValid(object)" />) /// </summary> /// <remarks> /// This method returns <c>true</c> if the <paramref name = "value" /> is null. /// It is assumed the <see cref = "RequiredAttribute" /> is used if the value may not be null. /// </remarks> /// <param name = "value">The object to validate.</param> /// <returns><c>true</c> if the value is null or less than or equal to the specified maximum length, otherwise <c>false</c></returns> /// <exception cref = "InvalidOperationException">Length is zero or less than negative one.</exception> public override bool IsValid(object value) { // Check the lengths for legality EnsureLegalLengths(); var length = 0; // Automatically pass if value is null. RequiredAttribute should be used to assert a value is not null. if (value == null) { return true; } else { var str = value as string; if (str != null) { length = str.Length; } else { // We expect a cast exception if a non-{string|array} property was passed in. length = ((Array)value).Length; } } return MaxAllowableLength == Length || length <= Length; } /// <summary> /// Applies formatting to a specified error message. (Overrides <see cref = "ValidationAttribute.FormatErrorMessage" />) /// </summary> /// <param name = "name">The name to include in the formatted string.</param> /// <returns>A localized string to describe the maximum acceptable length.</returns> public override string FormatErrorMessage(string name) { // An error occurred, so we know the value is greater than the maximum if it was specified return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length); } /// <summary> /// Checks that Length has a legal value. /// </summary> /// <exception cref="InvalidOperationException">Length is zero or less than negative one.</exception> private void EnsureLegalLengths() { if (Length == 0 || Length < -1)throw new InvalidOperationException(InvalidMaxLength); } } }
45.354167
232
0.612311
[ "MIT" ]
mccabesp/ModernSlavery-Beta
ModernSlavery.WebUI.Shared/Classes/Attributes/TextLengthAttribute.cs
4,356
C#
using System; using Quartz.Plugin.Xml; using Quartz.Util; namespace Quartz { public static class PluginConfigurationExtensions { public static T UseXmlSchedulingConfiguration<T>( this T configurer, Action<XmlSchedulingOptions> configure) where T : IPropertyConfigurationRoot { configurer.SetProperty("quartz.plugin.xml.type", typeof(XMLSchedulingDataProcessorPlugin).AssemblyQualifiedNameWithoutVersion()); configure.Invoke(new XmlSchedulingOptions(configurer)); return configurer; } } public class XmlSchedulingOptions : PropertiesSetter { internal XmlSchedulingOptions(IPropertySetter parent) : base(parent, "quartz.plugin.xml") { } public string[] Files { set => SetProperty("fileNames", string.Join(",", value)); } public bool FailOnFileNotFound { set => SetProperty("failOnFileNotFound", value.ToString().ToLowerInvariant()); } public bool FailOnSchedulingError { set => SetProperty("failOnSchedulingError", value.ToString().ToLowerInvariant()); } public TimeSpan ScanInterval { set => SetProperty("scanInterval", ((int) value.TotalSeconds).ToString()); } } }
28.680851
141
0.629822
[ "Apache-2.0" ]
KravaNick/quartznet
src/Quartz.Plugins/PluginConfigurationExtensions.cs
1,348
C#
// TODO LIST /* Add filters to ESPs? Make ESP less laggy?? */ // On Risk of Rain 2 Update: Update Unlockables.txt, Update Unreleased items list if needed // On Menu update, Update Version Variable and ffs Update Assembly Version... // When Adding A Button To A Menu, Update Menu Value Range in Navigation.UpdateIndexValues() using System; using System.Collections.Generic; using UnityEngine; using RoR2; using UnityEngine.SceneManagement; using System.Linq; namespace Poke { public class Main : MonoBehaviour { public const string NAME = "K K P", VERSION = ""; public static string log = "[" + NAME + "] "; // Used to unlock all items public static List<string> unlockableNames = Utility.GetAllUnlockables(); // These Values are needed for navigation to create Enumerable and indexable values with the items I've excluded public static List<GameObject> bodyPrefabs = Utility.GetBodyPrefabs(); public static List<EquipmentIndex> equipment = Utility.GetEquipment(); public static List<ItemIndex> items = Utility.GetItems(); public static List<SpawnCard> spawnCards = Utility.GetSpawnCards(); // These Are updated in FixedUpdate for performance reasons public static List<UnityEngine.Object> purchaseInteractables; public static List<UnityEngine.Object> teleporterInteractables; public static List<HurtBox> hurtBoxes; public static Scene currentScene; // Used for RollItems public static WeightedSelection<List<ItemIndex>> weightedSelection = ItemManager.BuildRollItemsDropTable(); // Used to make sure navigation intraMenuIndex doesnt go over when in the lobby management menu public static int numberOfPlayers; public static List<bool> menuBools = new List<bool>() { _isTeleMenuOpen, _isESPMenuOpen, _isLobbyMenuOpen, _isPlayerMod, _isItemManagerOpen, _isMovementOpen, _isSpawnMenuOpen }; public static List<bool> menusOpen = new List<bool>(); #region Player Variables public static CharacterMaster LocalPlayer; public static CharacterBody LocalPlayerBody; public static Inventory LocalPlayerInv; public static HealthComponent LocalHealth; public static SkillLocator LocalSkills; public static NetworkUser LocalNetworkUser; public static CharacterMotor LocalMotor; #endregion #region Menu Checks public static bool _isMenuOpen = false; public static bool _ifDragged = false; public static bool _CharacterCollected = false; public static bool _isStatMenuOpen = false; public static bool _isTeleMenuOpen = false; public static bool _isESPMenuOpen = false; public static bool _isChangeCharacterMenuOpen = false; public static bool _isLobbyMenuOpen = false; public static bool _isEditStatsOpen = false; public static bool _isItemSpawnMenuOpen = false; public static bool _isPlayerMod = false; public static bool _isEquipmentSpawnMenuOpen = false; public static bool _isBuffMenuOpen = false; public static bool _isItemManagerOpen = false; public static bool _isMovementOpen = false; public static bool _isSpawnListMenuOpen = false; public static bool _isSpawnMenuOpen = false; public static bool enableRespawnButton = false; #endregion #region Button Styles / Toggles public static GUIStyle MainBgStyle, StatBgSytle, TeleBgStyle, OnStyle, OffStyle, LabelStyle, TitleStyle, BtnStyle, ItemBtnStyle, CornerStyle, DisplayStyle, BgStyle, HighlightBtnStyle, ActiveModsStyle, renderTeleporterStyle, renderMobsStyle, renderInteractablesStyle, WatermarkStyle, StatsStyle; public static GUIStyle BtnStyle1, BtnStyle2, BtnStyle3; public static bool skillToggle, renderInteractables, renderMobs, damageToggle, critToggle, attackSpeedToggle, armorToggle, regenToggle, moveSpeedToggle, MouseToggle, FlightToggle, listItems, noEquipmentCooldown, listBuffs, aimBot, alwaysSprint, godToggle, unloadConfirm, jumpPackToggle; public static bool renderActiveMods = true; public static float delay = 0, widthSize = 350; public static bool navigationToggle = false; #endregion #region UI Rects public static Rect mainRect; public static Rect statRect; public static Rect teleRect; public static Rect ESPRect; public static Rect lobbyRect; public static Rect itemSpawnerRect; public static Rect equipmentSpawnerRect; public static Rect buffMenuRect; public static Rect characterRect; public static Rect playerModRect; public static Rect itemManagerRect; public static Rect editStatsRect; public static Rect movementRect; public static Rect spawnListRect; public static Rect spawnRect; #endregion #region Rect Start Position Values public static int topY = 10; public static int leftX = 10; public static int firstRightX = 424; public static int secondRightX = 838; public static int belowMainY = 290; public static int belowTeleY = 660; #endregion public static Texture2D NewTexture2D { get { return new Texture2D(1, 1); } } public static Texture2D Image = null, ontexture, onpresstexture, offtexture, offpresstexture, highlightTexture, highlightPressTexture, cornertexture, backtexture, btntexture, btnpresstexture, btntexturelabel; public static int PlayerModBtnY, MainMulY, StatMulY, TeleMulY, ESPMulY, LobbyMulY, itemSpawnerMulY, equipmentSpawnerMulY, buffMenuMulY, CharacterMulY, PlayerModMulY, ItemManagerMulY, ItemManagerBtnY, editStatsMulY, editStatsBtnY, movementMulY, spawnListMulY, spawnMulY, spawnBtnY; public static int btnY, mulY; public static Rect rect = new Rect(10, 10, 20, 20); public Rect dropDownRect = new Rect(10, 10, 20, 20); public static string[] Players = new string[16]; #region On GUI private void OnGUI() { if (Updates.updateAvailable) { GUI.Label(new Rect(Screen.width - 100, 1f, 100, 50f), $"Poke (v{VERSION}) <color=grey>-</color> <color=yellow>Lastest (v{Updates.latestVersion})</color>", WatermarkStyle); } else if (Updates.upToDate) { GUI.Label(new Rect(Screen.width - 100, 1f, 100, 50f), $"Poke (v{VERSION})", WatermarkStyle); } else if (Updates.devBuild) { GUI.Label(new Rect(Screen.width - 100, 1f, 100, 50f), $"Poke (v{VERSION}) <color=grey>-</color> <color=yellow>Dev Build</color>", WatermarkStyle); } #region GenerateMenus mainRect = GUI.Window(0, mainRect, new GUI.WindowFunction(SetMainBG), "", new GUIStyle()); if (_isMenuOpen) { DrawAllMenus(); } if (_isStatMenuOpen) { statRect = GUI.Window(1, statRect, new GUI.WindowFunction(SetStatsBG), "", new GUIStyle()); DrawMenu.DrawStatsMenu(statRect.x, statRect.y, widthSize, StatMulY, MainBgStyle, StatsStyle, LabelStyle); } if (_isTeleMenuOpen) { teleRect = GUI.Window(2, teleRect, new GUI.WindowFunction(SetTeleBG), "", new GUIStyle()); DrawMenu.DrawTeleMenu(teleRect.x, teleRect.y, widthSize, TeleMulY, MainBgStyle, BtnStyle, LabelStyle); // Debug.Log("X : " + teleRect.x + " Y : " + teleRect.y); } if (_isESPMenuOpen) { ESPRect = GUI.Window(3, ESPRect, new GUI.WindowFunction(SetESPBG), "", new GUIStyle()); DrawMenu.DrawRenderMenu(ESPRect.x, ESPRect.y, widthSize, ESPMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); // Debug.Log("X : " + ESPRect.x + " Y : " + ESPRect.y); } if (_isLobbyMenuOpen) { lobbyRect = GUI.Window(4, lobbyRect, new GUI.WindowFunction(SetLobbyBG), "", new GUIStyle()); DrawMenu.DrawLobbyMenu(lobbyRect.x, lobbyRect.y, widthSize, LobbyMulY, MainBgStyle, BtnStyle, LabelStyle); // Debug.Log("X : " + lobbyRect.x + " Y : " + lobbyRect.y); } if (_isItemSpawnMenuOpen) { itemSpawnerRect = GUI.Window(5, itemSpawnerRect, new GUI.WindowFunction(SetItemSpawnerBG), "", new GUIStyle()); DrawMenu.DrawItemMenu(itemSpawnerRect.x, itemSpawnerRect.y, widthSize, itemSpawnerMulY, MainBgStyle, BtnStyle, LabelStyle); // Debug.Log("X : " + itemSpawnerRect.x + " Y : " + itemSpawnerRect.y); } if (_isPlayerMod) { playerModRect = GUI.Window(6, playerModRect, new GUI.WindowFunction(SetPlayerModBG), "", new GUIStyle()); DrawMenu.DrawPlayerModMenu(playerModRect.x, playerModRect.y, widthSize, PlayerModMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); // Debug.Log("X : " + playerModRect.x + " Y : " + playerModRect.y); } if (_isEquipmentSpawnMenuOpen) { equipmentSpawnerRect = GUI.Window(7, equipmentSpawnerRect, new GUI.WindowFunction(SetEquipmentBG), "", new GUIStyle()); DrawMenu.DrawEquipmentMenu(equipmentSpawnerRect.x, equipmentSpawnerRect.y, widthSize, equipmentSpawnerMulY, MainBgStyle, BtnStyle, LabelStyle, OffStyle); // Debug.Log("X : " + equipmentSpawnerRect.x + " Y : " + equipmentSpawnerRect.y); } if (_isBuffMenuOpen) { buffMenuRect = GUI.Window(8, buffMenuRect, new GUI.WindowFunction(SetBuffBG), "", new GUIStyle()); DrawMenu.DrawBuffMenu(buffMenuRect.x, buffMenuRect.y, widthSize, buffMenuMulY, MainBgStyle, BtnStyle, LabelStyle, OffStyle); } if (_isChangeCharacterMenuOpen) { characterRect = GUI.Window(9, characterRect, new GUI.WindowFunction(SetCharacterBG), "", new GUIStyle()); DrawMenu.CharacterWindowMethod(characterRect.x, characterRect.y, widthSize, CharacterMulY, MainBgStyle, BtnStyle, LabelStyle); // Debug.Log("X : " + characterRect.x + " Y : " + characterRect.y); } if (_isItemManagerOpen) { itemManagerRect = GUI.Window(10, itemManagerRect, new GUI.WindowFunction(SetItemManagerBG), "", new GUIStyle()); DrawMenu.DrawItemManagementMenu(itemManagerRect.x, itemManagerRect.y, widthSize, ItemManagerMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); // Debug.Log("X : " + itemManagerRect.x + " Y : " + itemManagerRect.y); } if (_isEditStatsOpen) { editStatsRect = GUI.Window(11, editStatsRect, new GUI.WindowFunction(SetEditStatBG), "", new GUIStyle()); DrawMenu.DrawStatsModMenu(editStatsRect.x, editStatsRect.y, widthSize, editStatsMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); // Debug.Log("X : " + editStatsRect.x + " Y : " + editStatsRect.y); } if (_isMovementOpen) { movementRect = GUI.Window(12, movementRect, new GUI.WindowFunction(SetMovementBG), "", new GUIStyle()); DrawMenu.DrawMovementMenu(movementRect.x, movementRect.y, widthSize, movementMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); // Debug.Log("X : " + movementRect.x + " Y : " + movementRect.y); } if (_isSpawnMenuOpen) { spawnRect = GUI.Window(13, spawnRect, new GUI.WindowFunction(SetSpawnBG), "", new GUIStyle()); DrawMenu.DrawSpawnMenu(spawnRect.x, spawnRect.y, widthSize, spawnMulY, MainBgStyle, BtnStyle, OnStyle, OffStyle, LabelStyle); } if (_isSpawnListMenuOpen) { spawnListRect = GUI.Window(14, spawnListRect, new GUI.WindowFunction(SetSpawnListBG), "", new GUIStyle()); DrawMenu.DrawSpawnMobMenu(spawnListRect.x, spawnListRect.y, widthSize, spawnListMulY, MainBgStyle, BtnStyle, LabelStyle); } if (_CharacterCollected) { ESPRoutine(); } #endregion } #endregion On GUI #region Start public void Start() { SceneManager.sceneLoaded += OnSceneLoaded; #region CondenseMenuValues if (Screen.height > 1080) { mainRect = new Rect(10, 10, 20, 20); // start position playerModRect = new Rect(374, 10, 20, 20); // start position movementRect = new Rect(374, 560, 20, 20); // start position itemManagerRect = new Rect(738, 10, 20, 20); // start positions teleRect = new Rect(10, 425, 20, 20); // start position ESPRect = new Rect(10, 795, 20, 20); // start position lobbyRect = new Rect(10, 985, 20, 20); // start position spawnRect = new Rect(738, 470, 20, 20); // start position statRect = new Rect(1626, 457, 20, 20); // start position spawnListRect = new Rect(1503, 10, 20, 20); // start position itemSpawnerRect = new Rect(1503, 10, 20, 20); // start position equipmentSpawnerRect = new Rect(1503, 10, 20, 20); // start positions buffMenuRect = new Rect(1503, 10, 20, 20); // start position characterRect = new Rect(1503, 10, 20, 20); // start position editStatsRect = new Rect(1503, 10, 20, 20); // start position } else { mainRect = new Rect(10, 10, 20, 20); // start position playerModRect = new Rect(374, 10, 20, 20); // start position movementRect = new Rect(374, 560, 20, 20); // start position itemManagerRect = new Rect(738, 10, 20, 20); // start positions teleRect = new Rect(10, 425, 20, 20); // start position ESPRect = new Rect(10, 795, 20, 20); // start position lobbyRect = new Rect(374, 750, 20, 20); // start position spawnRect = new Rect(738, 470, 20, 20); // start position statRect = new Rect(1626, 457, 20, 20); // start position spawnListRect = new Rect(1503, 10, 20, 20);// start position itemSpawnerRect = new Rect(1503, 10, 20, 20); // start position equipmentSpawnerRect = new Rect(1503, 10, 20, 20); // start positions buffMenuRect = new Rect(1503, 10, 20, 20); // start position characterRect = new Rect(1503, 10, 20, 20); // start position editStatsRect = new Rect(1503, 10, 20, 20); // start position } #endregion #region Styles if (MainBgStyle == null) { MainBgStyle = new GUIStyle(); MainBgStyle.normal.background = BackTexture; MainBgStyle.onNormal.background = BackTexture; MainBgStyle.active.background = BackTexture; MainBgStyle.onActive.background = BackTexture; MainBgStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); MainBgStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); MainBgStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); MainBgStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); MainBgStyle.fontSize = 15; MainBgStyle.fontStyle = FontStyle.Normal; MainBgStyle.alignment = TextAnchor.UpperCenter; } if (CornerStyle == null) { CornerStyle = new GUIStyle(); CornerStyle.normal.background = BtnTexture; CornerStyle.onNormal.background = BtnTexture; CornerStyle.active.background = BtnTexture; CornerStyle.onActive.background = BtnTexture; CornerStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); CornerStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); CornerStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); CornerStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); CornerStyle.fontSize = 18; CornerStyle.fontStyle = FontStyle.Normal; CornerStyle.alignment = TextAnchor.UpperCenter; } if (LabelStyle == null) { LabelStyle = new GUIStyle(); LabelStyle.normal.textColor = Color.grey; LabelStyle.onNormal.textColor = Color.grey; LabelStyle.active.textColor = Color.grey; LabelStyle.onActive.textColor = Color.grey; LabelStyle.fontSize = 18; LabelStyle.fontStyle = FontStyle.Normal; LabelStyle.alignment = TextAnchor.UpperCenter; } if (StatsStyle == null) { StatsStyle = new GUIStyle(); StatsStyle.normal.textColor = Color.grey; StatsStyle.onNormal.textColor = Color.grey; StatsStyle.active.textColor = Color.grey; StatsStyle.onActive.textColor = Color.grey; StatsStyle.fontSize = 18; StatsStyle.fontStyle = FontStyle.Normal; StatsStyle.alignment = TextAnchor.MiddleLeft; } if (TitleStyle == null) { TitleStyle = new GUIStyle(); TitleStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); TitleStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); TitleStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); TitleStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); TitleStyle.fontSize = 18; TitleStyle.fontStyle = FontStyle.Normal; TitleStyle.alignment = TextAnchor.UpperCenter; } if (ActiveModsStyle == null) { ActiveModsStyle = new GUIStyle(); ActiveModsStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ActiveModsStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ActiveModsStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ActiveModsStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ActiveModsStyle.fontSize = 20; ActiveModsStyle.wordWrap = true; ActiveModsStyle.fontStyle = FontStyle.Normal; ActiveModsStyle.alignment = TextAnchor.MiddleLeft; } if (renderInteractablesStyle == null) { renderInteractablesStyle = new GUIStyle(); renderInteractablesStyle.normal.textColor = Color.green; renderInteractablesStyle.onNormal.textColor = Color.green; renderInteractablesStyle.active.textColor = Color.green; renderInteractablesStyle.onActive.textColor = Color.green; renderInteractablesStyle.fontStyle = FontStyle.Normal; renderInteractablesStyle.alignment = TextAnchor.MiddleLeft; } if (renderTeleporterStyle == null) { renderTeleporterStyle = new GUIStyle { fontStyle = FontStyle.Normal, alignment = TextAnchor.MiddleLeft }; } if (renderMobsStyle == null) { renderMobsStyle = new GUIStyle(); renderMobsStyle.normal.textColor = Color.red; renderMobsStyle.onNormal.textColor = Color.red; renderMobsStyle.active.textColor = Color.red; renderMobsStyle.onActive.textColor = Color.red; renderMobsStyle.fontStyle = FontStyle.Normal; renderMobsStyle.alignment = TextAnchor.MiddleLeft; } if (WatermarkStyle == null) { WatermarkStyle = new GUIStyle(); WatermarkStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); WatermarkStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); WatermarkStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); WatermarkStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); WatermarkStyle.fontSize = 14; WatermarkStyle.fontStyle = FontStyle.Normal; WatermarkStyle.alignment = TextAnchor.MiddleRight; } if (OffStyle == null) { OffStyle = new GUIStyle(); OffStyle.normal.background = OffTexture; OffStyle.onNormal.background = OffTexture; OffStyle.active.background = OffPressTexture; OffStyle.onActive.background = OffPressTexture; OffStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OffStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OffStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OffStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OffStyle.fontSize = 15; OffStyle.fontStyle = FontStyle.Normal; OffStyle.alignment = TextAnchor.MiddleCenter; } if (OnStyle == null) { OnStyle = new GUIStyle(); OnStyle.normal.background = OnTexture; OnStyle.onNormal.background = OnTexture; OnStyle.active.background = OnPressTexture; OnStyle.onActive.background = OnPressTexture; OnStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OnStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OnStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OnStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); OnStyle.fontSize = 15; OnStyle.fontStyle = FontStyle.Normal; OnStyle.alignment = TextAnchor.MiddleCenter; } if (BtnStyle == null) { BtnStyle = new GUIStyle(); BtnStyle.normal.background = BtnTexture; BtnStyle.onNormal.background = BtnTexture; BtnStyle.active.background = BtnPressTexture; BtnStyle.onActive.background = BtnPressTexture; BtnStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); BtnStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); BtnStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); BtnStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); BtnStyle.fontSize = 15; BtnStyle.fontStyle = FontStyle.Normal; BtnStyle.alignment = TextAnchor.MiddleCenter; } if (ItemBtnStyle == null) { ItemBtnStyle = new GUIStyle(); ItemBtnStyle.normal.background = BtnTexture; ItemBtnStyle.onNormal.background = BtnTexture; ItemBtnStyle.active.background = BtnPressTexture; ItemBtnStyle.onActive.background = BtnPressTexture; ItemBtnStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ItemBtnStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ItemBtnStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ItemBtnStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); ItemBtnStyle.fontSize = 15; ItemBtnStyle.fontStyle = FontStyle.Normal; ItemBtnStyle.alignment = TextAnchor.MiddleCenter; } if (HighlightBtnStyle == null) { HighlightBtnStyle = new GUIStyle(); HighlightBtnStyle.normal.background = highlightTexture; HighlightBtnStyle.onNormal.background = highlightTexture; HighlightBtnStyle.active.background = highlightPressTexture; HighlightBtnStyle.onActive.background = highlightPressTexture; HighlightBtnStyle.normal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); HighlightBtnStyle.onNormal.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); HighlightBtnStyle.active.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); HighlightBtnStyle.onActive.textColor = Color.HSVToRGB(0.5256f, 0.9286f, 0.9333f); HighlightBtnStyle.fontSize = 15; HighlightBtnStyle.fontStyle = FontStyle.Normal; HighlightBtnStyle.alignment = TextAnchor.MiddleCenter; } #endregion } #endregion Start #region Update public void Update() { try { CharacterRoutine(); CheckInputs(); StatsRoutine(); EquipCooldownRoutine(); ModStatsRoutine(); FlightRoutine(); SprintRoutine(); JumpPackRoutine(); AimBotRoutine(); GodRoutine(); UpdateNavIndexRoutine(); // UpdateMenuPositions(); } catch (NullReferenceException) { } } #endregion Update #region FixedUpdate public void FixedUpdate() { currentScene = SceneManager.GetActiveScene(); if (renderInteractables) { purchaseInteractables = Utility.GetPurchaseInteractions(); teleporterInteractables = Utility.GetTeleporterInteractions(); } if (renderMobs) { hurtBoxes = Utility.GetHurtBoxes(); } } #endregion #region Inputs private void CheckInputs() { if (_isMenuOpen) { Cursor.visible = true; if (_CharacterCollected) { if (Input.GetKeyDown(KeyCode.DownArrow)) { if (!navigationToggle) { Utility.CloseAllMenus(); } navigationToggle = true; Navigation.intraMenuIndex++; } if (Input.GetKeyDown(KeyCode.UpArrow)) { if (!navigationToggle) { Utility.CloseAllMenus(); } navigationToggle = true; Navigation.intraMenuIndex--; } } if (navigationToggle) { if (Input.GetKeyDown(KeyCode.V)) { int oldMenuIndex = (int)Navigation.menuIndex; Navigation.PressBtn(Navigation.menuIndex, Navigation.intraMenuIndex); int newMenuIndex = (int)Navigation.menuIndex; if (oldMenuIndex != newMenuIndex) { Navigation.intraMenuIndex = 0; } } if (Input.GetKeyDown(KeyCode.RightArrow)) { bool playerPlusMinusBtn = Navigation.menuIndex == 1 && Enumerable.Range(0, 3).Contains(Navigation.intraMenuIndex); bool statsPlusMinusBtn = Navigation.menuIndex == 1.3f && Enumerable.Range(0, 5).Contains(Navigation.intraMenuIndex); bool itemPlusMinusBtn = Navigation.menuIndex == 3 && Enumerable.Range(0, 2).Contains(Navigation.intraMenuIndex); bool spawnPlusMinusBtn = Navigation.menuIndex == 4 && Enumerable.Range(0, 3).Contains(Navigation.intraMenuIndex); if (playerPlusMinusBtn || itemPlusMinusBtn || statsPlusMinusBtn || spawnPlusMinusBtn) { Navigation.IncreaseValue(Navigation.menuIndex, Navigation.intraMenuIndex); } else { float oldMenuIndex = Navigation.menuIndex; Navigation.PressBtn(Navigation.menuIndex, Navigation.intraMenuIndex); float newMenuIndex = Navigation.menuIndex; if (oldMenuIndex != newMenuIndex) { Navigation.intraMenuIndex = 0; } } } if (Input.GetKeyDown(KeyCode.LeftArrow)) { bool playerPlusMinusBtn = Navigation.menuIndex == 1 && Enumerable.Range(0, 3).Contains(Navigation.intraMenuIndex); bool statsPlusMinusBtn = Navigation.menuIndex == 1.3f && Enumerable.Range(0, 5).Contains(Navigation.intraMenuIndex); bool itemPlusMinusBtn = Navigation.menuIndex == 3 && Enumerable.Range(0, 2).Contains(Navigation.intraMenuIndex); bool spawnPlusMinusBtn = Navigation.menuIndex == 4 && Enumerable.Range(0, 3).Contains(Navigation.intraMenuIndex); if (playerPlusMinusBtn || itemPlusMinusBtn || statsPlusMinusBtn || spawnPlusMinusBtn) { Navigation.DecreaseValue(Navigation.menuIndex, Navigation.intraMenuIndex); } else { Navigation.GoBackAMenu(); } } if (Input.GetKeyDown(KeyCode.Backspace)) { Navigation.GoBackAMenu(); } } } else if (!_isMenuOpen) { navigationToggle = false; Navigation.intraMenuIndex = -1; Navigation.menuIndex = 0; Cursor.visible = false; } if (Input.GetKeyDown(KeyCode.Insert)) { unloadConfirm = false; numberOfPlayers = Lobby.NumberOfPlayers(); spawnCards = Utility.GetSpawnCards(); if (_isMenuOpen && navigationToggle) { Utility.CloseAllMenus(); } _isMenuOpen = !_isMenuOpen; GetCharacter(); SceneManager.sceneLoaded += OnSceneLoaded; } } #endregion Inputs #region Routines private void CharacterRoutine() { if (!_CharacterCollected) { GetCharacter(); } } private void ESPRoutine() { if (renderInteractables) { Render.Interactables(); } if (renderMobs) { Render.Mobs(); } if (renderActiveMods) { Render.ActiveMods(); } } private void EquipCooldownRoutine() { if (noEquipmentCooldown) { ItemManager.NoEquipmentCooldown(); } } private void StatsRoutine() { if (_CharacterCollected) { if (skillToggle) { LocalSkills.ApplyAmmoPack(); } } } private void AimBotRoutine() { if (aimBot) PlayerMod.AimBot(); } private void GodRoutine() { if (godToggle) { PlayerMod.GodMode(); } else { LocalHealth.godMode = false; } } private void SprintRoutine() { if (alwaysSprint) Movement.AlwaysSprint(); } private void FlightRoutine() { if (FlightToggle) { Movement.Flight(); } } private void ModStatsRoutine() { if (_CharacterCollected) { if (damageToggle) { PlayerMod.LevelPlayersDamage(); } if (critToggle) { PlayerMod.LevelPlayersCrit(); } if (attackSpeedToggle) { PlayerMod.SetplayersAttackSpeed(); } if (armorToggle) { PlayerMod.SetplayersArmor(); } if (moveSpeedToggle) { PlayerMod.SetplayersMoveSpeed(); } LocalPlayerBody.RecalculateStats(); } } private void UpdateNavIndexRoutine() { if (navigationToggle) { Navigation.UpdateIndexValues(); } } private void JumpPackRoutine() { if (jumpPackToggle) { Movement.JumpPack(); } } #endregion Routines #region On Scene Loaded public void OnSceneLoaded(Scene scene, LoadSceneMode mode) { purchaseInteractables = Utility.GetPurchaseInteractions(); teleporterInteractables = Utility.GetTeleporterInteractions(); if (!InGameCheck()) { Utility.ResetMenu(); } else { ModStatsRoutine(); Utility.SoftResetMenu(); } } #endregion #region In Game Check public static bool InGameCheck() { if (currentScene != null) { bool inGame = currentScene.name != "title" && currentScene.name != "lobby" && currentScene.name != "" && currentScene.name != " "; return inGame; } return false; } #endregion #region SetBG public static void SetBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * mulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) _isMenuOpen = !_isMenuOpen; _ifDragged = false; } GUI.DragWindow(); } public static void SetMainBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * MainMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isMenuOpen = !_isMenuOpen; GetCharacter(); } _ifDragged = false; } GUI.DragWindow(); } public static void SetCharacterBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * CharacterMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isChangeCharacterMenuOpen = !_isChangeCharacterMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetEquipmentBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * equipmentSpawnerMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isEquipmentSpawnMenuOpen = !_isEquipmentSpawnMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetBuffBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * buffMenuMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isBuffMenuOpen = !_isBuffMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetStatsBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * StatMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isStatMenuOpen = !_isStatMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetTeleBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * TeleMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isTeleMenuOpen = !_isTeleMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetESPBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * ESPMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isESPMenuOpen = !_isESPMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetLobbyBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * LobbyMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isLobbyMenuOpen = !_isLobbyMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetEditStatBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * editStatsMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isEditStatsOpen = !_isEditStatsOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetItemSpawnerBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * MainMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isItemSpawnMenuOpen = !_isItemSpawnMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetPlayerModBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * PlayerModMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isPlayerMod = !_isPlayerMod; } _ifDragged = false; } GUI.DragWindow(); } public static void SetItemManagerBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * ItemManagerMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isItemManagerOpen = !_isItemManagerOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetMovementBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * movementMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isMovementOpen = !_isMovementOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetSpawnListBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * spawnListMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isSpawnListMenuOpen = !_isSpawnListMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } public static void SetSpawnBG(int windowID) { GUI.Box(new Rect(0f, 0f, widthSize + 10, 50f + 45 * spawnMulY), "", CornerStyle); if (Event.current.type == EventType.MouseDrag) { delay += Time.deltaTime; if (delay > 0.3f) { _ifDragged = true; } } else if (Event.current.type == EventType.MouseUp) { delay = 0; if (!_ifDragged) { _isSpawnMenuOpen = !_isSpawnMenuOpen; } _ifDragged = false; } GUI.DragWindow(); } #endregion SetBG #region Draw all Menus public static void DrawAllMenus() { GUI.Box(new Rect(mainRect.x + 0f, mainRect.y + 0f, widthSize + 10, 50f + 45 * MainMulY), "", MainBgStyle); if (Updates.updateAvailable) { GUI.Label(new Rect(mainRect.x + 5f, mainRect.y + 5f, widthSize + 5, 85f), $"Poke \n<color=yellow>O U T D A T E D</color>", TitleStyle); } else if (Updates.upToDate) { GUI.Label(new Rect(mainRect.x + 5f, mainRect.y + 5f, widthSize + 5, 85f), $"Poke \n<color=grey>v{VERSION}</color>", TitleStyle); } else if (Updates.devBuild) { GUI.Label(new Rect(mainRect.x + 5f, mainRect.y + 5f, widthSize + 5, 85f), $"Poke \n<color=yellow>D E V</color>", TitleStyle); } if (!_CharacterCollected) { DrawMenu.DrawNotCollectedMenu(LabelStyle, OnStyle, OffStyle); } if (_CharacterCollected) { DrawMenu.DrawMainMenu(mainRect.x, mainRect.y, widthSize, MainMulY, MainBgStyle, OnStyle, OffStyle, BtnStyle); } } #endregion #region Textures public static Texture2D BtnTexture { get { if (btntexture == null) { btntexture = NewTexture2D; btntexture.SetPixel(0, 0, new Color32(120, 120, 120, 240)); btntexture.Apply(); } return btntexture; } } public static Texture2D BtnTextureLabel { get { if (BtnTextureLabel == null) { btntexture = NewTexture2D; btntexture.SetPixel(0, 0, new Color32(255, 0, 0, 255)); btntexture.Apply(); } return BtnTextureLabel; } } public static Texture2D BtnPressTexture { get { if (btnpresstexture == null) { btnpresstexture = NewTexture2D; btnpresstexture.SetPixel(0, 0, new Color32(99, 99, 99, 240)); btnpresstexture.Apply(); } return btnpresstexture; } } public static Texture2D OnPressTexture { get { if (onpresstexture == null) { onpresstexture = NewTexture2D; onpresstexture.SetPixel(0, 0, new Color32(50, 50, 50, 240)); onpresstexture.Apply(); } return onpresstexture; } } public static Texture2D OnTexture { get { if (ontexture == null) { ontexture = NewTexture2D; ontexture.SetPixel(0, 0, new Color32(67, 67, 67, 240)); ontexture.Apply(); } return ontexture; } } public static Texture2D OffPressTexture { get { if (offpresstexture == null) { offpresstexture = NewTexture2D; offpresstexture.SetPixel(0, 0, new Color32(99, 99, 99, 240)); offpresstexture.Apply(); } return offpresstexture; } } public static Texture2D OffTexture { get { if (offtexture == null) { offtexture = NewTexture2D; offtexture.SetPixel(0, 0, new Color32(120, 120, 120, 240)); // byte[] FileData = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/BepInEx/plugins/UmbraRoR/Resources/Images/OffStyle.png"); // offtexture.LoadImage(FileData); offtexture.Apply(); } return offtexture; } } public static Texture2D BackTexture { get { if (backtexture == null) { backtexture = NewTexture2D; //backtexture.SetPixel(0, 0, new Color32(0, 0, 0, 158)); backtexture.SetPixel(0, 0, new Color32(0, 0, 0, 120)); backtexture.Apply(); } return backtexture; } } public static Texture2D CornerTexture { get { if (cornertexture == null) { cornertexture = NewTexture2D; // ToHtmlStringRGBA new Color(33, 150, 243, 1) cornertexture.SetPixel(0, 0, new Color32(42, 42, 42, 0)); cornertexture.Apply(); } return cornertexture; } } public static Texture2D HighlightTexture { get { if (highlightTexture == null) { highlightTexture = NewTexture2D; highlightTexture.SetPixel(0, 0, new Color32(0, 0, 0, 0)); highlightTexture.Apply(); } return highlightTexture; } } public static Texture2D HighlightPressTexture { get { if (highlightPressTexture == null) { highlightPressTexture = NewTexture2D; highlightPressTexture.SetPixel(0, 0, new Color32(0, 0, 0, 0)); highlightPressTexture.Apply(); } return highlightPressTexture; } } #endregion Textures #region Get Character // try and setup our character, if we hit an error we set it to false // TODO: Still tries to collect character after death and returning to lobby/title. public static void GetCharacter() { try { if (InGameCheck()) { LocalNetworkUser = null; foreach (NetworkUser readOnlyInstance in NetworkUser.readOnlyInstancesList) { //localplayer is you! if (readOnlyInstance.isLocalPlayer) { LocalNetworkUser = readOnlyInstance; LocalPlayer = LocalNetworkUser.master; LocalPlayerInv = LocalPlayer.GetComponent<Inventory>(); LocalHealth = LocalPlayer.GetBody().GetComponent<HealthComponent>(); LocalSkills = LocalPlayer.GetBody().GetComponent<SkillLocator>(); LocalPlayerBody = LocalPlayer.GetBody().GetComponent<CharacterBody>(); if (LocalHealth.alive) _CharacterCollected = true; else _CharacterCollected = false; } } } } catch (Exception e) { Debug.LogError(e); _CharacterCollected = false; } } #endregion } }
39.354421
302
0.509737
[ "MIT" ]
Mochongli/Umbra-Mod-Menu
Main.cs
54,742
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GraphQL; using GraphQL.Types; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using RESTfullDemo.GraphQLSchema; namespace RESTfullDemo.Controllers { [Route("graphql")] [ApiController] public class GraphQLController : ControllerBase { public GraphQLController(ISchema librarySchema, IDocumentExecuter documentExecuter) { LibrarySchema = librarySchema; DocumentExecuter = documentExecuter; } public ISchema LibrarySchema { get; } public IDocumentExecuter DocumentExecuter { get; } [HttpPost] public async Task<IActionResult> Post([FromBody]GraphQLRequest query) { var result = await DocumentExecuter.ExecuteAsync(options => { options.Schema = LibrarySchema; options.Query = query.Query; }); if(result.Errors?.Count>0) { return BadRequest(result); } return Ok(result); } } }
26.045455
91
0.626527
[ "MIT" ]
dotnet9/ASP.NET-Core-Test
src/RESTfullDemo/Controllers/GraphQLController.cs
1,148
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// RetailItemDescription Data Structure. /// </summary> [Serializable] public class RetailItemDescription : AlipayObject { /// <summary> /// 标题下的描述列表,列表类型,每项不得超过100个中文字符,最多10项 /// </summary> [JsonProperty("details")] public List<string> Details { get; set; } /// <summary> /// 商品描述title /// </summary> [JsonProperty("title")] public string Title { get; set; } } }
23.692308
53
0.594156
[ "MIT" ]
gebiWangshushu/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/RetailItemDescription.cs
682
C#
namespace GildedRose.Console { public class RetailItem { public const int MaxQuality = 50; public RetailItem(Item item) { Item = item; } private Item Item { get; set; } public string Name { get { return Item.Name; } set { Item.Name = value; } } public int SellIn { get { return Item.SellIn; } set { Item.SellIn = value; } } public int Quality { get { return Item.Quality; } set { Item.Quality = value; } } public void Update() { UpdateItemQuality(); UpdateItemSellInValue(); if (SellIn >= 0) { return; } UpdateExpiredItemQuality(); } protected virtual void UpdateItemSellInValue() { SellIn--; } protected virtual void UpdateItemQuality() { if (Quality > 0) { Quality--; } } protected virtual void UpdateExpiredItemQuality() { if (Quality > 0) { Quality--; } } } }
19.149254
57
0.41855
[ "MIT" ]
nlinas/GildedRoseRefactor
src/GildedRose.Console/Items/RetailItem.cs
1,283
C#
using RealTime.Controllers; using Microsoft.AspNetCore.Mvc; namespace RealTime.Extensions { public static class UrlHelperExtensions { public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme) { return urlHelper.Action( action: nameof(AccountController.ConfirmEmail), controller: "Account", values: new { userId, code }, protocol: scheme); } public static string ResetPasswordCallbackLink(this IUrlHelper urlHelper, string userId, string code, string scheme) { return urlHelper.Action( action: nameof(AccountController.ResetPassword), controller: "Account", values: new { userId, code }, protocol: scheme); } } }
32.62963
124
0.607264
[ "BSD-2-Clause" ]
earth-emoji/realtime
Extensions/UrlHelperExtensions.cs
881
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Xaml; namespace Microsoft.Maui.Controls.ControlGallery.TabIndexTest { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DaysOfWeekView : Grid { public DaysOfWeekView() { InitializeComponent(); } } }
20.6
61
0.791262
[ "MIT" ]
jongalloway/maui
src/ControlGallery/src/Xamarin.Forms.Controls/TabIndexTest/DaysOfWeekView.xaml.cs
414
C#