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; using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading.Tasks; using AutoMapper; using GeneralStockMarket.Bll.Interfaces; using GeneralStockMarket.DTO.ProductItem; using GeneralStockMarket.DTO.Request; using GeneralStockMarket.DTO.Response; using GeneralStockMarket.DTO.Wallet; using GeneralStockMarket.Entities.Concrete; namespace GeneralStockMarket.Bll.Managers { public class RequestManager : IRequestService { private readonly IProductDepositRequestService ProductRequestService; private readonly IProductItemService productItemService; private readonly IGenericService<ProductItem> genericProductItemService; private readonly IGenericService<NewTypeRequest> genericNewTypeRequestService; private readonly IGenericService<DepositRequest> genericDepositRequestService; private readonly IGenericService<ProductDepositRequest> genericProductDepositRequestService; private readonly IGenericService<Wallet> genericWalletService; private readonly HttpClient httpClient; private readonly IMapper mapper; public RequestManager( IProductDepositRequestService ProductRequestService, IProductItemService productItemService, IGenericService<ProductItem> genericProductItemService, IGenericService<NewTypeRequest> genericNewTypeRequestService, IGenericService<DepositRequest> genericDepositRequestService, IGenericService<ProductDepositRequest> genericProductDepositRequestService, IGenericService<Wallet> genericWalletService, HttpClient httpClient, IMapper mapper) { this.ProductRequestService = ProductRequestService; this.productItemService = productItemService; this.genericProductItemService = genericProductItemService; this.genericNewTypeRequestService = genericNewTypeRequestService; this.genericDepositRequestService = genericDepositRequestService; this.genericProductDepositRequestService = genericProductDepositRequestService; this.genericWalletService = genericWalletService; this.httpClient = httpClient; this.mapper = mapper; } public async Task<RequestDto> GetRequestsAsync(Guid id) { var productRequests = await ProductRequestService.GetAllByUserIdWhitAsync(id); var depositRequests = await genericDepositRequestService.GetAllByUserIdAsync<DepositRequestDto>(id); var newTypeRequests = await genericNewTypeRequestService.GetAllByUserIdAsync<NewTypeRequestDto>(id); return new() { DepositRequestDtos = depositRequests, NewTypeRequestDtos = newTypeRequests, ProductDepositRequestDtos = mapper.Map<IEnumerable<ProductDepositRequestDto>>(productRequests) }; } public async Task<RequestDto> GetAllRequestsAsync() { var productRequests = await ProductRequestService.GetAllIncludeProductAsync(); var depositRequests = await genericDepositRequestService.GetAllAsync<DepositRequestDto>(); var newTypeRequests = await genericNewTypeRequestService.GetAllAsync<NewTypeRequestDto>(); return new() { DepositRequestDtos = depositRequests.Where(x => x.Verify == null).ToList(), NewTypeRequestDtos = newTypeRequests.Where(x => x.Verify == null).ToList(), ProductDepositRequestDtos = mapper.Map<IEnumerable<ProductDepositRequestDto>>(productRequests).Where(x => x.Verify == null).ToList() }; } public async Task DepositRequestVerifyConditionAsync(VerifyDto dto) { if (dto.Verify.HasValue && dto.Verify.Value) { var entityDto = await genericDepositRequestService.GetByIdAsync<DepositRequestDto>(dto.Id); var walletDto = await genericWalletService.GetByUserIdAsync<WalletDto>(entityDto.CreatedUserId); var exchangeResponse = await httpClient.GetFromJsonAsync<ExchangeResponse>("https://api.exchangerate.host/latest?base=TRY&symbols=USD,EUR,GBP,TRY"); var ratio = exchangeResponse.Rates.GetMoney(entityDto.MoneyType); walletDto.Money += entityDto.Amount/ ratio; var updateDto = mapper.Map<WalletUpdateDto>(walletDto); updateDto.UpdateUserId = dto.UpdateUserId; await genericWalletService.UpdateAsync(updateDto); await genericWalletService.Commit(); } } public async Task ProductDepositRequestVerifyConditionAsync(VerifyDto dto) { if (dto.Verify.HasValue && dto.Verify.Value) { var entityDto = await genericProductDepositRequestService.GetByIdAsync<ProductDepositRequestDto>(dto.Id); var walletDto = await genericWalletService.GetByUserIdAsync<WalletDto>(entityDto.CreatedUserId); var productItem = await productItemService.GetByProductIdWithWalletIdAsync(walletDto.Id, entityDto.ProductId); if (productItem == null) productItem = await genericProductItemService.AddAsync(new ProductItemCreateDto() { CreatedUserId = entityDto.CreatedUserId, ProductId = entityDto.ProductId, WalletId = walletDto.Id, Amount = entityDto.Amount }); else { productItem.Amount += entityDto.Amount; productItem.UpdateUserId = dto.UpdateUserId; var updateDto = mapper.Map<ProductItemUpdateDto>(productItem); await genericProductItemService.UpdateAsync(updateDto); } await genericProductItemService.Commit(); } } } }
49.467742
164
0.67835
[ "MIT" ]
SenRecep/GeneralStockMarketSystem
API/WEBAPI/Layers/GeneralStockMarket.Bll/Managers/RequestManager.cs
6,136
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PanelDesigner { /// <summary> /// Interaction logic for ToolboxControl.xaml /// </summary> public partial class ToolboxControl : ContentControl { #region Static Members public static readonly DependencyProperty CategoriesProperty = DependencyProperty.Register("Categories", typeof(ObservableCollection<ToolboxCategory>), typeof(ToolboxControl), new PropertyMetadata(new ObservableCollection<ToolboxCategory>(), CategoriesPropertyCallback)); private static void CategoriesPropertyCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var obj = sender as ToolboxControl; if (obj != null) obj.OnCategoriesPropertyChanged(e); } #endregion public ToolboxControl() { InitializeComponent(); } public ObservableCollection<ToolboxCategory> Categories { get { return (ObservableCollection<ToolboxCategory>)GetValue(CategoriesProperty); } set { SetValue(CategoriesProperty, value); } } protected virtual void OnCategoriesPropertyChanged(DependencyPropertyChangedEventArgs e) { } private void treeViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e) { } private void treeViewItem_PreviewMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton != MouseButtonState.Pressed) return; var item = (TreeViewItem)sender; var type = item.DataContext as Type; if (type == null) return; var data = new DataObject(typeof(Type), type); DragDrop.DoDragDrop(this, data, DragDropEffects.Move); } } }
31.589041
280
0.651778
[ "MIT" ]
nordleif/PanelDesigner
PanelDesigner/ToolboxControl.xaml.cs
2,308
C#
namespace Dissonance.Audio.Capture { public enum AecSuppressionLevels { // Implementation note - these specific values are important - the WebRtcPreprocessor uses these exact same // int values. Don't change them without also changing them there and recompiling on all platforms! Disabled = -1, Low = 0, Moderate = 1, High = 2 } }
26.266667
115
0.647208
[ "MIT" ]
edowney29/Cops-and-Robert
Assets/Plugins/Dissonance/Core/Audio/Capture/AecSuppressionLevels.cs
396
C#
namespace Bible2PPT.Bibles { class Bible : BibleBase { public string OnlineId { get; set; } public string Name { get; set; } //public List<Book> Books => Source.GetBooks(this); public override string ToString() => Name ?? base.ToString(); } }
23.230769
70
0.569536
[ "MIT" ]
sunghwan2789/Bible2PPT
Bible2PPT/Bibles/Bible.cs
292
C#
using System.Collections.Immutable; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime.French { public class FrenchSetParserConfiguration : BaseOptionsConfiguration, ISetParserConfiguration { public IDateTimeExtractor DurationExtractor { get; } public IDateTimeParser DurationParser { get; } public IDateTimeExtractor TimeExtractor { get; } public IDateTimeParser TimeParser { get; } public IDateExtractor DateExtractor { get; } public IDateTimeParser DateParser { get; } public IDateTimeExtractor DateTimeExtractor { get; } public IDateTimeParser DateTimeParser { get; } public IDateTimeExtractor DatePeriodExtractor { get; } public IDateTimeParser DatePeriodParser { get; } public IDateTimeExtractor TimePeriodExtractor { get; } public IDateTimeParser TimePeriodParser { get; } public IDateTimeExtractor DateTimePeriodExtractor { get; } public IDateTimeParser DateTimePeriodParser { get; } public IImmutableDictionary<string, string> UnitMap { get; } public Regex EachPrefixRegex { get; } public Regex PeriodicRegex { get; } public Regex EachUnitRegex { get; } public Regex EachDayRegex { get; } public Regex SetWeekDayRegex { get; } public Regex SetEachRegex { get; } public FrenchSetParserConfiguration(ICommonDateTimeParserConfiguration config) : base(config) { DurationExtractor = config.DurationExtractor; TimeExtractor = config.TimeExtractor; DateExtractor = config.DateExtractor; DateTimeExtractor = config.DateTimeExtractor; DatePeriodExtractor = config.DatePeriodExtractor; TimePeriodExtractor = config.TimePeriodExtractor; DateTimePeriodExtractor = config.DateTimePeriodExtractor; DurationParser = config.DurationParser; TimeParser = config.TimeParser; DateParser = config.DateParser; DateTimeParser = config.DateTimeParser; DatePeriodParser = config.DatePeriodParser; TimePeriodParser = config.TimePeriodParser; DateTimePeriodParser = config.DateTimePeriodParser; UnitMap = config.UnitMap; EachPrefixRegex = FrenchSetExtractorConfiguration.EachPrefixRegex; PeriodicRegex = FrenchSetExtractorConfiguration.PeriodicRegex; EachUnitRegex = FrenchSetExtractorConfiguration.EachUnitRegex; EachDayRegex = FrenchSetExtractorConfiguration.EachDayRegex; SetWeekDayRegex = FrenchSetExtractorConfiguration.SetWeekDayRegex; SetEachRegex = FrenchSetExtractorConfiguration.SetEachRegex; } public bool GetMatchedDailyTimex(string text, out string timex) { var trimmedText = text.Trim().ToLowerInvariant(); if (trimmedText.Equals("quotidien") || trimmedText.Equals("quotidienne") || trimmedText.Equals("jours") || trimmedText.Equals("journellement")) // daily { timex = "P1D"; } else if (trimmedText.Equals("hebdomadaire")) // weekly { timex = "P1W"; } else if (trimmedText.Equals("bihebdomadaire")) // bi weekly { timex = "P2W"; } else if (trimmedText.Equals("mensuel") || trimmedText.Equals("mensuelle")) // monthly { timex = "P1M"; } else if (trimmedText.Equals("annuel") || trimmedText.Equals("annuellement")) // yearly/annually { timex = "P1Y"; } else { timex = null; return false; } return true; } public bool GetMatchedUnitTimex(string text, out string timex) { var trimmedText = text.Trim().ToLowerInvariant(); if (trimmedText.Equals("jour")||trimmedText.Equals("journee")) { timex = "P1D"; } else if (trimmedText.Equals("semaine")) { timex = "P1W"; } else if (trimmedText.Equals("mois")) { timex = "P1M"; } else if (trimmedText.Equals("an")||trimmedText.Equals("annee")) // year { timex = "P1Y"; } else { timex = null; return false; } return true; } } }
34
110
0.586331
[ "MIT" ]
Irrelevances/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/French/Parsers/FrenchSetParserConfiguration.cs
4,728
C#
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using telledge.Models; //プロジェクトのテスト対象 namespace UnitTest.Teachers { [TestClass] public class TeacherGetRooms { [TestMethod] public void TestGetRooms() { Teacher teacher = new Teacher(); teacher.id = 1; Room[] test = teacher.getRooms(); Assert.IsNotNull(test); } [TestMethod] public void TestGetRoomsFailed() { Teacher teacher = new Teacher(); teacher.id = 999; Room[] test = teacher.getRooms(); Assert.IsNull(test); } } }
22.645161
52
0.609687
[ "MIT" ]
18jn02-8/telledge
UnitTest/Teacher/GetRooms.cs
726
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mfapi.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.Versioning; namespace TerraFX.Interop.Windows; /// <include file='MF_FLOAT2.xml' path='doc/member[@name="MF_FLOAT2"]/*' /> [SupportedOSPlatform("windows10.0")] public partial struct MF_FLOAT2 { /// <include file='MF_FLOAT2.xml' path='doc/member[@name="MF_FLOAT2.x"]/*' /> public float x; /// <include file='MF_FLOAT2.xml' path='doc/member[@name="MF_FLOAT2.y"]/*' /> public float y; }
35.4
145
0.714689
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/mfapi/MF_FLOAT2.cs
710
C#
using System; using System.IO; ////using GM.LoadDatabase; using GM.Utilities; namespace GM.Utilities.DevelopLoadDatabase { class Program { static void Main(string[] args) { ////LoadDatabase loadDatabase = new LoadDatabase(); string projectFolder = GMFileAccess.FindParentFolderWithName("DevelopLoadDatabase"); string sampleDataFile = Path.Combine(projectFolder, "SampleTranscriptViewModel.json"); ////loadDatabase.LoadSampleData(sampleDataFile); } } }
26.95
98
0.667904
[ "MIT" ]
govmeeting/govmeeting
Utilities/DevelopLoadDatabase/Program.cs
541
C#
// // ClientTargetTest.cs // - unit tests for System.Web.Configuration.ClientTarget // // Author: // Chris Toshok <toshok@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Configuration; using System.Web.Configuration; using System.Web; using System.Web.Security; using System.IO; using System.Xml; using System.Reflection; namespace MonoTests.System.Web.Configuration { [TestFixture] public class ClientTargetTest { [Test] public void EqualsAndHashCode () { ClientTarget c1, c2; c1 = new ClientTarget ("alias", "userAgent"); c2 = new ClientTarget ("alias", "userAgent"); Assert.IsTrue (c1.Equals (c2), "A1"); Assert.AreEqual (c1.GetHashCode (), c2.GetHashCode (), "A2"); } [Test] [ExpectedException (typeof (ConfigurationErrorsException))] public void ctor_validationFailure1 () { ClientTarget c = new ClientTarget ("", "hi"); } [Test] [ExpectedException (typeof (ConfigurationErrorsException))] public void ctor_validationFailure2 () { ClientTarget c = new ClientTarget ("hi", ""); } } }
29.118421
73
0.729779
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.Web/Test/System.Web.Configuration/ClientTargetTest.cs
2,213
C#
 using System.Collections.Generic; using IdentityServer4.Models; namespace IdentityServer { public class Config { private const string ClientUsername = "MicroserviceClient"; private const string ClientPassword = "p@ssw0rd"; private const string ClientResource1 = "Microservice1"; private const string ClientResource2 = "Microservice2"; // scopes define the API resources in your system public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource(ClientResource1, "Microservice1"), new ApiResource(ClientResource2, "Microservice2") }; } // clients want to access resources (aka scopes) public static IEnumerable<Client> GetClients() { // client credentials client return new List<Client> { new Client { ClientId = ClientUsername, AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret(ClientPassword.Sha256()) }, AllowedScopes = { ClientResource1, ClientResource2 } } }; } } }
29.12766
72
0.547845
[ "Apache-2.0" ]
vicentegnz/MicroservicesArchitecture
IdentityServer/Config.cs
1,371
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace MicroRabbit { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); } } }
25.309524
116
0.742239
[ "MIT" ]
bunda3d/MicroRabbit
MicroRabbit/MicroRabbit/Startup.cs
1,063
C#
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using Projac.Sql; namespace Projac.SqlClient { /// <summary> /// Represents the T-SQL NVARCHAR NULL parameter value. /// </summary> public class TSqlNVarCharNullValue : IDbParameterValue { private readonly TSqlNVarCharSize _size; /// <summary> /// Initializes a new instance of the <see cref="TSqlNVarCharNullValue" /> class. /// </summary> /// <param name="size">The size.</param> public TSqlNVarCharNullValue(TSqlNVarCharSize size) { _size = size; } /// <summary> /// Creates a <see cref="DbParameter" /> instance based on this instance. /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <returns> /// A <see cref="DbParameter" />. /// </returns> public DbParameter ToDbParameter(string parameterName) { return ToSqlParameter(parameterName); } /// <summary> /// Creates a <see cref="SqlParameter" /> instance based on this instance. /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <returns> /// A <see cref="SqlParameter" />. /// </returns> public SqlParameter ToSqlParameter(string parameterName) { #if NET46 || NET452 return new SqlParameter( parameterName, SqlDbType.NVarChar, _size, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Default, DBNull.Value); #elif NETSTANDARD2_0 return new SqlParameter { ParameterName = parameterName, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.NVarChar, Size = _size, Value = DBNull.Value, SourceColumn = "", IsNullable = true, Precision = 0, Scale = 0, SourceVersion = DataRowVersion.Default }; #endif } private bool Equals(TSqlNVarCharNullValue value) { return value._size == _size; } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) return false; return Equals((TSqlNVarCharNullValue) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return _size.GetHashCode(); } } }
33.142857
125
0.517529
[ "BSD-3-Clause" ]
BitTacklr/Projac
src/Projac.SqlClient/TSqlNVarCharNullValue.cs
3,480
C#
using System; using System.Threading.Tasks; namespace DigitalArchitecture.Services { public abstract class Cache: ICache { public abstract void Add(object objectToCache, string key); public abstract void Add<T>(object objectToCache, string key); public abstract void Add<T>(object objectToCache, string key, double cacheDuration); public abstract void ClearAll(); public abstract bool Exists(string key); public abstract object Get(string key); public abstract T Get<T>(string key); public abstract void Remove(string key); public virtual TResponse FromCacheOrService<TResponse>(Func<TResponse> action, string key, double cacheDuration) { var cached = Get(key); if (cached == null) { cached = action(); Add<TResponse>(cached, key, cacheDuration); } return (TResponse)cached; } public async Task<TResponse> FromCacheOrServiceAsync<TResponse>(Func<Task<TResponse>> action, string key, double cacheDuration) { var cached = Get(key); if (cached == null) { cached = await action(); Add<TResponse>(cached, key, cacheDuration); } return (TResponse)cached; } public virtual TResponse FromCacheOrService<TResponse>(Func<TResponse> action, string key) { var cached = Get(key); if (cached == null) { cached = action(); Add(cached, key); } return (TResponse)cached; } public async Task<TResponse> FromCacheOrServiceAsync<TResponse>(Func<Task<TResponse>> action, string key) { var cached = Get(key); if (cached == null) { cached = await action(); Add(cached, key); } return (TResponse)cached; } } }
32.758065
135
0.557361
[ "MIT" ]
QuinntyneBrown/digital-architecture
DigitalArchitecture/Services/Cache.cs
2,031
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Xml; using System.Xml.Linq; namespace Aoite.Reflection.Probing { /// <summary> /// Helper class for converting values between various types. /// </summary> public static class TypeConverter { #region GetValue methods /// <summary> /// Convert the supplied XmlNode into the specified target type. Only the InnerXml portion /// of the XmlNode is used in the conversion, unless the target type is itself an XmlNode. /// </summary> /// <param name="targetType">The type into which to convert</param> /// <param name="node">The source value used in the conversion operation</param> /// <returns>The converted value</returns> public static object Get(Type targetType, XmlNode node) { if(targetType == typeof(XmlNode)) { return node; } return Get(targetType, node.InnerXml); } /// <summary> /// Convert the supplied XAttribute into the specified target type. Only the Value portion /// of the XAttribute is used in the conversion, unless the target type is itself an XAttribute. /// </summary> /// <param name="targetType">The type into which to convert</param> /// <param name="attribute">The source value used in the conversion operation</param> /// <returns>The converted value</returns> public static object Get(Type targetType, XAttribute attribute) { if(targetType == typeof(XAttribute)) { return attribute; } return Get(targetType, attribute.Value); } /// <summary> /// Convert the supplied XElement into the specified target type. Only the Value portion /// of the XElement is used in the conversion, unless the target type is itself an XElement. /// </summary> /// <param name="targetType">The type into which to convert</param> /// <param name="element">The source value used in the conversion operation</param> /// <returns>The converted value</returns> public static object Get(Type targetType, XElement element) { if(targetType == typeof(XElement)) { return element; } return Get(targetType, element.Value); } /// <summary> /// Convert the supplied string into the specified target type. /// </summary> /// <param name="targetType">The type into which to convert</param> /// <param name="value">The source value used in the conversion operation</param> /// <returns>The converted value</returns> public static object Get(Type targetType, string value) { Type sourceType = typeof(string); if(sourceType == targetType) { return value; } try { if(targetType.IsEnum) { return ConvertEnums(targetType, sourceType, value); } if(targetType == typeof(Guid)) { return ConvertGuids(targetType, sourceType, value); } if(targetType == typeof(Type)) { return ConvertTypes(targetType, sourceType, value); } return !string.IsNullOrEmpty(value) ? Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture) : null; } catch(FormatException) { return null; // no conversion was possible } } /// <summary> /// Convert the supplied object into the specified target type. /// </summary> /// <param name="targetType">The type into which to convert</param> /// <param name="value">The source value used in the conversion operation</param> /// <returns>The converted value</returns> public static object Get(Type targetType, object value) { if(value == null) { return null; } Type sourceType = value.GetType(); if(sourceType == targetType) { return value; } if(sourceType == typeof(string)) { return Get(targetType, value as string); } if(sourceType == typeof(XmlNode)) { return Get(targetType, value as XmlNode); } if(sourceType == typeof(XAttribute)) { return Get(targetType, value as XAttribute); } if(sourceType == typeof(XElement)) { return Get(targetType, value as XElement); } if(targetType.IsEnum || sourceType.IsEnum) { return ConvertEnums(targetType, sourceType, value); } if(targetType == typeof(Guid) || sourceType == typeof(Guid)) { return ConvertGuids(targetType, sourceType, value); } if(targetType == typeof(Type) || sourceType == typeof(Type)) { return ConvertTypes(targetType, sourceType, value); } return value is IConvertible ? Convert.ChangeType(value, targetType) : null; } #endregion #region Type conversions /// <summary> /// A method that will convert between types and their textual names. /// </summary> /// <param name="targetType">The target type</param> /// <param name="sourceType">The type of the provided value.</param> /// <param name="value">The value representing the type.</param> /// <returns></returns> public static object ConvertTypes(Type targetType, Type sourceType, object value) { if(value == null) { return null; } if(targetType == typeof(Type)) { return Type.GetType(Convert.ToString(value)); } if(sourceType == typeof(Type) && targetType == typeof(string)) { return sourceType.FullName; } return null; } #endregion #region Enum conversions /// <summary> /// Helper method for converting enums from/to different types. /// </summary> private static object ConvertEnums(Type targetType, Type sourceType, object value) { if(targetType.IsEnum) { if(sourceType == typeof(string)) { // assume the string represents the name of the enumeration element string source = (string)value; // first try to clean out unnecessary information (like assembly name and FQTN) source = source.Split(',')[0]; int pos = source.LastIndexOf('.'); if(pos > 0) source = source.Substring(pos + 1).Trim(); if(Enum.IsDefined(targetType, source)) { return Enum.Parse(targetType, source); } } // convert the source object to the appropriate type of value value = Convert.ChangeType(value, Enum.GetUnderlyingType(targetType)); return Enum.ToObject(targetType, value); } return Convert.ChangeType(value, targetType); } #endregion #region Guid conversions /// <summary> /// Convert the binary string (16 bytes) into a Guid. /// </summary> public static Guid StringToGuid(string guid) { char[] charBuffer = guid.ToCharArray(); byte[] byteBuffer = new byte[16]; int nCurrByte = 0; foreach(char currChar in charBuffer) { byteBuffer[nCurrByte++] = (byte)currChar; } return new Guid(byteBuffer); } /// <summary> /// Convert the Guid into a binary string. /// </summary> public static string GuidToBinaryString(Guid guid) { StringBuilder sb = new StringBuilder(16); foreach(byte currByte in guid.ToByteArray()) { sb.Append((char)currByte); } return sb.ToString(); } /// <summary> /// A method that will convert guids from and to different types /// </summary> private static object ConvertGuids(Type targetType, Type sourceType, object sourceObj) { if(targetType == typeof(Guid)) { if(sourceType == typeof(string)) { string value = sourceObj as string; if(value != null && value.Length == 16) { return StringToGuid(value); } return value != null ? new Guid(value) : Guid.Empty; } if(sourceType == typeof(byte[])) { return new Guid((byte[])sourceObj); } } else if(sourceType == typeof(Guid)) { Guid g = (Guid)sourceObj; if(targetType == typeof(string)) { return GuidToBinaryString(g); } if(targetType == typeof(byte[])) { return g.ToByteArray(); } } return null; // Check.FailPostcondition( typeof(TypeConverter), "Cannot convert type {0} to type {1}.", sourceType, targetType ); } #endregion } }
37.60223
129
0.516658
[ "Apache-2.0" ]
jeenlee/Aoite
src/core/Aoite/Aoite/Reflection/Extensions/Services/Probing/TypeConverter.cs
10,117
C#
using MailKit; using MailKit.Net.Imap; using MailKit.Search; using MailKit.Security; using MimeKit; using System.Collections.Generic; namespace Mail2BigQuery { internal class ImapReceiver { internal ImapReceiver(string host, int port, string userName, string password) { _host = host; _port = port; _userName = userName; _password = password; } private readonly string _host; private readonly int _port; private readonly string _userName; private readonly string _password; internal IEnumerable<MimeMessage> DownloadMessages(SearchQuery query) { using (var client = new ImapClient(new ProtocolLogger("imap.log"))) { client.Connect(_host, _port, SecureSocketOptions.SslOnConnect); client.Authenticate(_userName, _password); client.Inbox.Open(FolderAccess.ReadOnly); foreach (var uid in client.Inbox.Search(query)) { yield return client.Inbox.GetMessage(uid); } client.Disconnect(true); } } } }
28.714286
86
0.591211
[ "MIT" ]
monmaru/Mail2BigQuery
Source/Mail2BigQuery/ImapReceiver.cs
1,208
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IMessageInfo.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Declares the IMessageInfo interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Messaging.Reflection { using Kephas.Reflection; /// <summary> /// Interface for message information. /// </summary> public interface IMessageInfo : ITypeInfo { } }
36.619048
120
0.475943
[ "MIT" ]
kephas-software/kephas
src/Kephas.Messaging/Reflection/IMessageInfo.cs
771
C#
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic.Models { using Azure; using Management; using Logic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for KeyType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum KeyType { [EnumMember(Value = "NotSpecified")] NotSpecified, [EnumMember(Value = "Primary")] Primary, [EnumMember(Value = "Secondary")] Secondary } }
26.588235
74
0.673673
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SDKs/Logic/Management.Logic/Generated/Models/KeyType.cs
904
C#
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using XenAdmin; namespace XenAPI { public static class pvs_proxy_status_extensions { public static string ToFriendlyString(pvs_proxy_status x) { switch (x) { case pvs_proxy_status.stopped: return Messages.STOPPED; case pvs_proxy_status.initialised: return Messages.INITIALIZED; case pvs_proxy_status.caching: return Messages.CACHING; case pvs_proxy_status.incompatible_write_cache_mode: return Messages.INCOMPATIBLE_WRITE_CACHE_MODE; case pvs_proxy_status.incompatible_protocol_version: return Messages.INCOMPATIBLE_PROTOCOL_VERSION; default: return Messages.UNKNOWN; } } } }
40.155172
71
0.665092
[ "BSD-2-Clause" ]
CitrixChris/xenadmin
XenModel/XenAPI-Extensions/pvs_proxy_status.cs
2,329
C#
using Abp.Application.Services.Dto; using Abp.Events.Bus.Entities; using System; using System.Collections.Generic; using System.Text; namespace TigerAdmin.Auditing.Dto { public class EntityChangeListDto:EntityDto<long> { public long? UserId { get; set; } public string UserName { get; set; } public DateTime ChangeTime { get; set; } public string EntityTypeFullName { get; set; } public EntityChangeType ChangeType { get; set; } public string ChangeTypeName => ChangeType.ToString(); public long EntityChangeSetId { get; set; } } }
23.384615
62
0.677632
[ "Apache-2.0" ]
AllenHongjun/ddu
TigerAdminZero/5.8.1/aspnet-core/src/TigerAdmin.Application/Auditing/Dto/EntityChangeListDto.cs
610
C#
using System; using System.ComponentModel; using System.Threading.Tasks; using Wikiled.Mvvm.Core; namespace Wikiled.Mvvm.Async { /// <summary> /// Watches a task and raises property-changed notifications when the task completes. /// </summary> public sealed class NotifyTask : INotifyPropertyChanged { /// <summary> /// Initializes a task notifier watching the specified task. /// </summary> /// <param name="task">The task to watch.</param> private NotifyTask(Task task) { Task = task; TaskCompleted = MonitorTaskAsync(task); } private async Task MonitorTaskAsync(Task task) { try { await task; } catch { } finally { NotifyProperties(task); } } private void NotifyProperties(Task task) { var propertyChanged = PropertyChanged; if (propertyChanged == null) return; if (task.IsCanceled) { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsCanceled")); } else if (task.IsFaulted) { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Exception")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("InnerException")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("ErrorMessage")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsFaulted")); } else { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsSuccessfullyCompleted")); } propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsCompleted")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsNotCompleted")); } /// <summary> /// Gets the task being watched. This property never changes and is never <c>null</c>. /// </summary> public Task Task { get; private set; } /// <summary> /// Gets a task that completes successfully when <see cref="Task"/> completes (successfully, faulted, or canceled). This property never changes and is never <c>null</c>. /// </summary> public Task TaskCompleted { get; private set; } /// <summary> /// Gets the current task status. This property raises a notification when the task completes. /// </summary> public TaskStatus Status { get { return Task.Status; } } /// <summary> /// Gets whether the task has completed. This property raises a notification when the value changes to <c>true</c>. /// </summary> public bool IsCompleted { get { return Task.IsCompleted; } } /// <summary> /// Gets whether the task is busy (not completed). This property raises a notification when the value changes to <c>false</c>. /// </summary> public bool IsNotCompleted { get { return !Task.IsCompleted; } } /// <summary> /// Gets whether the task has completed successfully. This property raises a notification when the value changes to <c>true</c>. /// </summary> public bool IsSuccessfullyCompleted { get { return Task.Status == TaskStatus.RanToCompletion; } } /// <summary> /// Gets whether the task has been canceled. This property raises a notification only if the task is canceled (i.e., if the value changes to <c>true</c>). /// </summary> public bool IsCanceled { get { return Task.IsCanceled; } } /// <summary> /// Gets whether the task has faulted. This property raises a notification only if the task faults (i.e., if the value changes to <c>true</c>). /// </summary> public bool IsFaulted { get { return Task.IsFaulted; } } /// <summary> /// Gets the wrapped faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public AggregateException Exception { get { return Task.Exception; } } /// <summary> /// Gets the original faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public Exception InnerException { get { return (Exception == null) ? null : Exception.InnerException; } } /// <summary> /// Gets the error message for the original faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public string ErrorMessage { get { return (InnerException == null) ? null : InnerException.Message; } } /// <summary> /// Event that notifies listeners of property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Creates a new task notifier watching the specified task. /// </summary> /// <param name="task">The task to watch.</param> public static NotifyTask Create(Task task) { return new NotifyTask(task); } /// <summary> /// Creates a new task notifier watching the specified task. /// </summary> /// <typeparam name="TResult">The type of the task result.</typeparam> /// <param name="task">The task to watch.</param> /// <param name="defaultResult">The default "result" value for the task while it is not yet complete.</param> public static NotifyTask<TResult> Create<TResult>(Task<TResult> task, TResult defaultResult = default(TResult)) { return new NotifyTask<TResult>(task, defaultResult); } /// <summary> /// Executes the specified asynchronous code and creates a new task notifier watching the returned task. /// </summary> /// <param name="asyncAction">The asynchronous code to execute.</param> public static NotifyTask Create(Func<Task> asyncAction) { return Create(asyncAction()); } /// <summary> /// Executes the specified asynchronous code and creates a new task notifier watching the returned task. /// </summary> /// <param name="asyncAction">The asynchronous code to execute.</param> /// <param name="defaultResult">The default "result" value for the task while it is not yet complete.</param> public static NotifyTask<TResult> Create<TResult>(Func<Task<TResult>> asyncAction, TResult defaultResult = default(TResult)) { return Create(asyncAction(), defaultResult); } } /// <summary> /// Watches a task and raises property-changed notifications when the task completes. /// </summary> /// <typeparam name="TResult">The type of the task result.</typeparam> public sealed class NotifyTask<TResult> : INotifyPropertyChanged { /// <summary> /// The "result" of the task when it has not yet completed. /// </summary> private readonly TResult _defaultResult; /// <summary> /// Initializes a task notifier watching the specified task. /// </summary> /// <param name="task">The task to watch.</param> /// <param name="defaultResult">The value to return from <see cref="Result"/> while the task is not yet complete.</param> internal NotifyTask(Task<TResult> task, TResult defaultResult) { _defaultResult = defaultResult; Task = task; TaskCompleted = MonitorTaskAsync(task); } private async Task MonitorTaskAsync(Task task) { try { await task; } catch { } finally { NotifyProperties(task); } } private void NotifyProperties(Task task) { var propertyChanged = PropertyChanged; if (propertyChanged == null) return; if (task.IsCanceled) { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsCanceled")); } else if (task.IsFaulted) { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Exception")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("InnerException")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("ErrorMessage")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsFaulted")); } else { propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Result")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("Status")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsSuccessfullyCompleted")); } propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsCompleted")); propertyChanged(this, PropertyChangedEventArgsCache.Instance.Get("IsNotCompleted")); } /// <summary> /// Gets the task being watched. This property never changes and is never <c>null</c>. /// </summary> public Task<TResult> Task { get; private set; } /// <summary> /// Gets a task that completes successfully when <see cref="Task"/> completes (successfully, faulted, or canceled). This property never changes and is never <c>null</c>. /// </summary> public Task TaskCompleted { get; private set; } /// <summary> /// Gets the result of the task. Returns the "default result" value specified in the constructor if the task has not yet completed successfully. This property raises a notification when the task completes successfully. /// </summary> public TResult Result { get { return (Task.Status == TaskStatus.RanToCompletion) ? Task.Result : _defaultResult; } } /// <summary> /// Gets the current task status. This property raises a notification when the task completes. /// </summary> public TaskStatus Status { get { return Task.Status; } } /// <summary> /// Gets whether the task has completed. This property raises a notification when the value changes to <c>true</c>. /// </summary> public bool IsCompleted { get { return Task.IsCompleted; } } /// <summary> /// Gets whether the task is busy (not completed). This property raises a notification when the value changes to <c>false</c>. /// </summary> public bool IsNotCompleted { get { return !Task.IsCompleted; } } /// <summary> /// Gets whether the task has completed successfully. This property raises a notification when the value changes to <c>true</c>. /// </summary> public bool IsSuccessfullyCompleted { get { return Task.Status == TaskStatus.RanToCompletion; } } /// <summary> /// Gets whether the task has been canceled. This property raises a notification only if the task is canceled (i.e., if the value changes to <c>true</c>). /// </summary> public bool IsCanceled { get { return Task.IsCanceled; } } /// <summary> /// Gets whether the task has faulted. This property raises a notification only if the task faults (i.e., if the value changes to <c>true</c>). /// </summary> public bool IsFaulted { get { return Task.IsFaulted; } } /// <summary> /// Gets the wrapped faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public AggregateException Exception { get { return Task.Exception; } } /// <summary> /// Gets the original faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public Exception InnerException { get { return (Exception == null) ? null : Exception.InnerException; } } /// <summary> /// Gets the error message for the original faulting exception for the task. Returns <c>null</c> if the task is not faulted. This property raises a notification only if the task faults (i.e., if the value changes to non-<c>null</c>). /// </summary> public string ErrorMessage { get { return (InnerException == null) ? null : InnerException.Message; } } /// <summary> /// Event that notifies listeners of property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; } }
46.575251
241
0.616616
[ "MIT" ]
AndMu/Mvvm.Async
src/Wikiled.Mvvm.Async/NotifyTask.cs
13,928
C#
using System; namespace Dalion.HttpMessageSigning.Verification { /// <inheritdoc /> public class HeaderMissingSignatureVerificationFailure : SignatureVerificationFailure { /// <inheritdoc /> public HeaderMissingSignatureVerificationFailure(string message, Exception ex) : base( "HEADER_MISSING", message, ex) {} } }
31.75
94
0.666667
[ "MIT" ]
DavidLievrouw/HttpMessageSigning
src/HttpMessageSigning.Verification/HeaderMissingSignatureVerificationFailure.cs
383
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using FluentValidation; using FluentValidation.Results; using SimpleInjector; namespace CoreSharp.Validation.Internal { internal class ValidatorDecorator<TModel> : IValidator<TModel>, IEnumerable<IValidationRule> { private readonly AbstractValidator<TModel> _validator; private readonly Container _container; public ValidatorDecorator(IValidator<TModel> validator, Container container) { _validator = (AbstractValidator<TModel>)validator; _container = container; var abstractValidator = (AbstractValidator<TModel>)validator; var addRuleMethod = abstractValidator.GetType().GetMethod("AddRule", BindingFlags.Instance | BindingFlags.NonPublic); addRuleMethod.Invoke(abstractValidator, new object[] { new DomainValidatorsValidator(GetRulesToValidate, GetAsyncRulesToValidate) }); } private IEnumerable<IAsyncDomainValidator> GetAsyncRulesToValidate(ValidationContext context) { var domainValidatorType = typeof(IAsyncDomainValidator<TModel>); try { var domainValidators = (IEnumerable<IAsyncDomainValidator<TModel>>) _container.GetAllInstances(domainValidatorType); domainValidators = domainValidators.Where(x => { var validRuleSets = x.RuleSets ?? new string[] { }; if (!validRuleSets.Any() && !context.Selector.CanExecute(RuleSetValidationRule.GetRule(null), "", context)) { return false; } if (validRuleSets.Any() && !context.Selector.CanExecute(RuleSetValidationRule.GetRule(validRuleSets), "", context)) { return false; } return true; }); return domainValidators; } catch (ActivationException) { return Enumerable.Empty<IAsyncDomainValidator>(); } } private IEnumerable<IDomainValidator> GetRulesToValidate(ValidationContext context) { var domainValidatorType = typeof(IDomainValidator<TModel>); try { var domainValidators = (IEnumerable<IDomainValidator<TModel>>) _container.GetAllInstances(domainValidatorType); domainValidators = domainValidators.Where(x => { var validRuleSets = x.RuleSets ?? new string[] { }; if (!validRuleSets.Any() && !context.Selector.CanExecute(RuleSetValidationRule.GetRule(null), "", context)) { return false; } if (validRuleSets.Any() && !context.Selector.CanExecute(RuleSetValidationRule.GetRule(validRuleSets), "", context)) { return false; } return true; }); return domainValidators; } catch (ActivationException) { return Enumerable.Empty<IDomainValidator>(); } } public ValidationResult Validate(object instance) { return Validate((TModel) instance); } public Task<ValidationResult> ValidateAsync(object instance, CancellationToken cancellation = new CancellationToken()) { return ValidateAsync((TModel)instance, cancellation); } public ValidationResult Validate(ValidationContext context) { return ((IValidator)_validator).Validate(context); } public Task<ValidationResult> ValidateAsync(ValidationContext context, CancellationToken cancellation = new CancellationToken()) { return ((IValidator)_validator).ValidateAsync(context, cancellation); } public ValidationResult Validate(TModel instance) { return _validator.Validate(instance); } public Task<ValidationResult> ValidateAsync(TModel instance, CancellationToken cancellation = new CancellationToken()) { return _validator.ValidateAsync(instance, cancellation); } public IValidatorDescriptor CreateDescriptor() { return _validator.CreateDescriptor(); } public bool CanValidateInstancesOfType(Type type) { return ((IValidator)_validator).CanValidateInstancesOfType(type); } public CascadeMode CascadeMode { get => _validator.CascadeMode; set => _validator.CascadeMode = value; } public IEnumerator<IValidationRule> GetEnumerator() { return _validator.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_validator).GetEnumerator(); } } }
33.890323
145
0.591852
[ "MIT" ]
maca88/CoreSharp
CoreSharp.Validation/Internal/ValidatorDecorator.cs
5,253
C#
/* The MIT License (MIT) Copyright 2021 Adam Reilly, Call to Action Software LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Cta { /// <summary> /// Data structure that is associated with Systems in order to quickly and easily identify them /// </summary> [System.Serializable] public struct SystemID { public int id; public int version; public SystemID(int id) { this.id = id; this.version = 0; } public SystemID(int id, int version) { this.id = id; this.version = version; } static public implicit operator int(SystemID system) { return system.id; } static public implicit operator SystemID(int id) { SystemID system; system.id = id; system.version = 0; return system; } public static readonly SystemID Null = new SystemID(0, 0); static public bool operator ==(SystemID lhs, SystemID rhs) { return lhs.id == rhs.id; } static public bool operator !=(SystemID lhs, SystemID rhs) { return !(lhs.id == rhs.id); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return id; } public override string ToString() { return string.Format("[id={0}] [version={1}]", id, version); } } }
33.842105
460
0.631026
[ "MIT" ]
areilly711/CtaApi
Unity/CtaApi/Packages/com.calltoaction.ctaapi/CtaApi/Runtime/Scripts/Core/SystemID.cs
2,572
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal sealed partial class DecryptorPalWindows : DecryptorPal { internal static DecryptorPalWindows Decode( byte[] encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes ) { SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (hCryptMsg == null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedMessage, encodedMessage.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); CryptMsgType cryptMsgType = hCryptMsg.GetMessageType(); if (cryptMsgType != CryptMsgType.CMSG_ENVELOPED) throw ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); version = hCryptMsg.GetVersion(); contentInfo = hCryptMsg.GetContentInfo(); using (SafeHandle sh = hCryptMsg.GetMsgParamAsMemory(CryptMsgParamType.CMSG_ENVELOPE_ALGORITHM_PARAM)) { unsafe { CRYPT_ALGORITHM_IDENTIFIER* pCryptAlgorithmIdentifier = (CRYPT_ALGORITHM_IDENTIFIER*)(sh.DangerousGetHandle()); contentEncryptionAlgorithm = (*pCryptAlgorithmIdentifier).ToAlgorithmIdentifier(); } } originatorCerts = hCryptMsg.GetOriginatorCerts(); unprotectedAttributes = hCryptMsg.GetUnprotectedAttributes(); RecipientInfoCollection recipientInfos = CreateRecipientInfos(hCryptMsg); return new DecryptorPalWindows(hCryptMsg, recipientInfos); } } }
41.409836
146
0.69517
[ "MIT" ]
Acidburn0zzz/corefx
src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decode.cs
2,526
C#
using System; using System.Collections.Generic; using System.Linq; using LibHac.Fs; namespace LibHac.FsSystem { public class Aes128CtrExStorage : Aes128CtrStorage { private List<AesSubsectionEntry> SubsectionEntries { get; } private List<long> SubsectionOffsets { get; } private BucketTree<AesSubsectionEntry> BucketTree { get; } private readonly object _locker = new object(); public Aes128CtrExStorage(IStorage baseStorage, IStorage bucketTreeData, byte[] key, long counterOffset, byte[] ctrHi, bool leaveOpen) : base(baseStorage, key, counterOffset, ctrHi, leaveOpen) { BucketTree = new BucketTree<AesSubsectionEntry>(bucketTreeData); SubsectionEntries = BucketTree.GetEntryList(); SubsectionOffsets = SubsectionEntries.Select(x => x.Offset).ToList(); } public Aes128CtrExStorage(IStorage baseStorage, IStorage bucketTreeData, byte[] key, byte[] counter, bool leaveOpen) : base(baseStorage, key, counter, leaveOpen) { BucketTree = new BucketTree<AesSubsectionEntry>(bucketTreeData); SubsectionEntries = BucketTree.GetEntryList(); SubsectionOffsets = SubsectionEntries.Select(x => x.Offset).ToList(); } protected override Result ReadImpl(long offset, Span<byte> destination) { AesSubsectionEntry entry = GetSubsectionEntry(offset); long inPos = offset; int outPos = 0; int remaining = destination.Length; while (remaining > 0) { int bytesToRead = (int)Math.Min(entry.OffsetEnd - inPos, remaining); lock (_locker) { UpdateCounterSubsection(entry.Counter); Result rc = base.ReadImpl(inPos, destination.Slice(outPos, bytesToRead)); if (rc.IsFailure()) return rc; } outPos += bytesToRead; inPos += bytesToRead; remaining -= bytesToRead; if (remaining != 0 && inPos >= entry.OffsetEnd) { entry = entry.Next; } } return Result.Success; } protected override Result WriteImpl(long offset, ReadOnlySpan<byte> source) { return ResultFs.UnsupportedOperationInAesCtrExStorageWrite.Log(); } protected override Result FlushImpl() { return Result.Success; } private AesSubsectionEntry GetSubsectionEntry(long offset) { int index = SubsectionOffsets.BinarySearch(offset); if (index < 0) index = ~index - 1; return SubsectionEntries[index]; } private void UpdateCounterSubsection(uint value) { Counter[7] = (byte)value; Counter[6] = (byte)(value >> 8); Counter[5] = (byte)(value >> 16); Counter[4] = (byte)(value >> 24); } } }
34.139785
143
0.56378
[ "BSD-3-Clause" ]
CaitSith2/libhac
src/LibHac/FsSystem/Aes128CtrExStorage.cs
3,085
C#
using System; using System.Collections.Generic; using System.Text; namespace DIaLOGIKa.b2xtranslator.OfficeDrawing.Shapetypes { [OfficeShapeTypeAttribute(115)] public class FlowChartMultidocumentType : ShapeType { public FlowChartMultidocumentType() { this.ShapeConcentricFill = false; this.Joins = JoinStyle.miter; this.Path = "m,20465v810,317,1620,452,2397,725c3077,21325,3790,21417,4405,21597v1620,,2202,-180,2657,-272c7580,21280,8002,21010,8455,20917v422,-135,810,-405,1327,-542c10205,20150,10657,19967,11080,19742v517,-182,970,-407,1425,-590c13087,19017,13605,18745,14255,18610v615,-180,1262,-318,1942,-408c16975,18202,17785,18022,18595,18022r,-1670l19192,16252r808,l20000,14467r722,-75l21597,14392,21597,,2972,r,1815l1532,1815r,1860l,3675,,20465xem1532,3675nfl18595,3675r,12677em2972,1815nfl20000,1815r,12652e"; this.ConnectorLocations = "10800,0;0,10800;10800,19890;21600,10800"; this.TextboxRectangle = "0,3675,18595,18022"; } } }
42.76
514
0.712816
[ "BSD-3-Clause" ]
datadiode/B2XTranslator
src/Common/OfficeDrawing/Shapetypes/FlowChartMultidocumentType.cs
1,069
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Polymorphism.AbstractTypes; namespace Polymorphism.Operations { public class AddOperation : OperationNode { public override double Evaluate() { return LeftNode.Evaluate() + RigthNode.Evaluate(); } } }
20.722222
62
0.69437
[ "Unlicense" ]
yigityuksel/Fundamentals
Polymorphism/Operations/AddOperation.cs
375
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using BenchmarkDotNet.Attributes; using MicroBenchmarks; namespace System.Text.Json.Tests { [BenchmarkCategory(Categories.Libraries, Categories.JSON)] public class Perf_Guids { private const int DataSize = 100_000; private ArrayBufferWriter<byte> _arrayBufferWriter; private Guid[] _guidArrayValues; [Params(true, false)] public bool Formatted; [Params(true, false)] public bool SkipValidation; [GlobalSetup] public void Setup() { _arrayBufferWriter = new ArrayBufferWriter<byte>(); _guidArrayValues = new Guid[DataSize]; for (int i = 0; i < DataSize; i++) { _guidArrayValues[i] = new Guid(); } } [Benchmark] public void WriteGuids() { _arrayBufferWriter.Clear(); using (var json = new Utf8JsonWriter(_arrayBufferWriter, new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation })) { json.WriteStartArray(); for (int i = 0; i < DataSize; i++) { json.WriteStringValue(_guidArrayValues[i]); } json.WriteEndArray(); json.Flush(); } } } }
27.526316
150
0.576163
[ "MIT" ]
333fred/performance
src/benchmarks/micro/libraries/System.Text.Json/Utf8JsonWriter/Perf.Guids.cs
1,571
C#
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Xels.Bitcoin.Base; using Xels.Bitcoin.Builder; using Xels.Bitcoin.Builder.Feature; namespace Xels.Bitcoin.IntegrationTests.Common { public static class OverrideServiceFeatureExtension { /// <summary> /// Adds a feature to the node that will allow certain services to be overridden. /// </summary> /// <param name="fullNodeBuilder">The object used to build the current node.</param> /// <typeparam name="TFeature">The feature that the service should be added to.</typeparam> /// <typeparam name="T">The serice to add.</typeparam> /// <returns>The full node builder, enriched with the new component.</returns> public static IFullNodeBuilder AddService<TFeature, T>(this IFullNodeBuilder fullNodeBuilder) { fullNodeBuilder.ConfigureFeature(features => { IFeatureRegistration feature = features.FeatureRegistrations.FirstOrDefault(f => f.FeatureType == typeof(TFeature)); if (feature != null) { feature.FeatureServices(services => { services.AddSingleton(typeof(T)); }); } }); return fullNodeBuilder; } /// <summary> /// Adds a feature to the node that will allow certain services to be overridden. /// </summary> /// <param name="fullNodeBuilder">The object used to build the current node.</param> /// <param name="serviceToOverride">Callback routine that will override a given service.</param> /// <typeparam name="T">The feature that the service will be replaced in.</typeparam> /// <returns>The full node builder, enriched with the new component.</returns> public static IFullNodeBuilder OverrideService<T>(this IFullNodeBuilder fullNodeBuilder, Action<IServiceCollection> serviceToOverride) { fullNodeBuilder.ConfigureFeature(features => { IFeatureRegistration feature = features.FeatureRegistrations.FirstOrDefault(f => f.FeatureType == typeof(T)); if (feature != null) { feature.FeatureServices(services => { serviceToOverride(services); }); } }); return fullNodeBuilder; } /// <summary> /// Replaces a service in a given feature with another implementation. /// </summary> /// <param name="fullNodeBuilder">The object used to build the current node.</param> /// <param name="serviceToOverride">Callback routine that will override a given service.</param> /// <typeparam name="T">The services to be replaced.</typeparam> /// <typeparam name="TFeature">The feature that the service exists in.</typeparam> /// <returns>The full node builder, with the replaced service.</returns> public static IFullNodeBuilder ReplaceService<T, TFeature>(this IFullNodeBuilder fullNodeBuilder, T serviceToOverride) { fullNodeBuilder.ConfigureFeature(features => { IFeatureRegistration feature = features.FeatureRegistrations.FirstOrDefault(f => f.FeatureType == typeof(TFeature)); if (feature != null) { feature.FeatureServices(services => { ServiceDescriptor service = services.FirstOrDefault(s => s.ServiceType == typeof(T)); if (service != null) { services.Remove(service); services.AddSingleton(typeof(T), serviceToOverride); } }); } }); return fullNodeBuilder; } /// <summary> /// Removes an implementation from a given feature. /// </summary> /// <param name="fullNodeBuilder">The object used to build the current node.</param> /// <typeparam name="T">The service to remove.</typeparam> /// <returns>The full node builder, with the service removed.</returns> public static IFullNodeBuilder RemoveImplementation<T>(this IFullNodeBuilder fullNodeBuilder) { fullNodeBuilder.ConfigureFeature(features => { IFeatureRegistration feature = features.FeatureRegistrations.FirstOrDefault(f => f.FeatureType == typeof(BaseFeature)); if (feature != null) { feature.FeatureServices(services => { ServiceDescriptor service = services.FirstOrDefault(s => s.ImplementationType == typeof(T)); if (service != null) services.Remove(service); }); } }); return fullNodeBuilder; } } }
44.353448
142
0.571429
[ "MIT" ]
xels-io/SideChain-SmartContract
src/Xels.Bitcoin.IntegrationTests.Common/Extensions/OverrideServiceFeatureExtension.cs
5,147
C#
// ----------------------------------------------------------------------- // <copyright file="ItemsPanelTemplate.cs" company="Steven Kirk"> // Copyright 2013 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Controls { using System; public class ItemsPanelTemplate { public ItemsPanelTemplate(Func<Panel> build) { Contract.Requires<ArgumentNullException>(build != null); this.Build = build; } public Func<Panel> Build { get; private set; } } }
27.434783
75
0.486529
[ "MIT" ]
GeorgeHahn/Perspex
Perspex.Controls/ItemsPanelTemplate.cs
633
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Primitives; using Microsoft.Azure.WebJobs.EventHubs.Processor; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.Host.TestCommon; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using NUnit.Framework; namespace Microsoft.Azure.WebJobs.EventHubs.UnitTests { public class EventHubTests { [Test] public void GetStaticBindingContract_ReturnsExpectedValue() { var strategy = new EventHubTriggerBindingStrategy(); var contract = strategy.GetBindingContract(); Assert.AreEqual(7, contract.Count); Assert.AreEqual(typeof(PartitionContext), contract["PartitionContext"]); Assert.AreEqual(typeof(string), contract["Offset"]); Assert.AreEqual(typeof(long), contract["SequenceNumber"]); Assert.AreEqual(typeof(DateTime), contract["EnqueuedTimeUtc"]); Assert.AreEqual(typeof(IDictionary<string, object>), contract["Properties"]); Assert.AreEqual(typeof(IDictionary<string, object>), contract["SystemProperties"]); } [Test] public void GetBindingContract_SingleDispatch_ReturnsExpectedValue() { var strategy = new EventHubTriggerBindingStrategy(); var contract = strategy.GetBindingContract(true); Assert.AreEqual(7, contract.Count); Assert.AreEqual(typeof(PartitionContext), contract["PartitionContext"]); Assert.AreEqual(typeof(string), contract["Offset"]); Assert.AreEqual(typeof(long), contract["SequenceNumber"]); Assert.AreEqual(typeof(DateTime), contract["EnqueuedTimeUtc"]); Assert.AreEqual(typeof(IDictionary<string, object>), contract["Properties"]); Assert.AreEqual(typeof(IDictionary<string, object>), contract["SystemProperties"]); } [Test] public void GetBindingContract_MultipleDispatch_ReturnsExpectedValue() { var strategy = new EventHubTriggerBindingStrategy(); var contract = strategy.GetBindingContract(false); Assert.AreEqual(7, contract.Count); Assert.AreEqual(typeof(PartitionContext), contract["PartitionContext"]); Assert.AreEqual(typeof(string[]), contract["PartitionKeyArray"]); Assert.AreEqual(typeof(string[]), contract["OffsetArray"]); Assert.AreEqual(typeof(long[]), contract["SequenceNumberArray"]); Assert.AreEqual(typeof(DateTime[]), contract["EnqueuedTimeUtcArray"]); Assert.AreEqual(typeof(IDictionary<string, object>[]), contract["PropertiesArray"]); Assert.AreEqual(typeof(IDictionary<string, object>[]), contract["SystemPropertiesArray"]); } [Test] public void GetBindingData_SingleDispatch_ReturnsExpectedValue() { var evt = GetSystemProperties(new byte[] { }); var input = EventHubTriggerInput.New(evt); input.PartitionContext = GetPartitionContext(); var strategy = new EventHubTriggerBindingStrategy(); var bindingData = strategy.GetBindingData(input); Assert.AreEqual(7, bindingData.Count); Assert.AreSame(input.PartitionContext, bindingData["PartitionContext"]); Assert.AreEqual(evt.PartitionKey, bindingData["PartitionKey"]); Assert.AreEqual(evt.Offset, bindingData["Offset"]); Assert.AreEqual(evt.SequenceNumber, bindingData["SequenceNumber"]); Assert.AreEqual(evt.EnqueuedTime.DateTime, bindingData["EnqueuedTimeUtc"]); Assert.AreSame(evt.Properties, bindingData["Properties"]); IDictionary<string, object> bindingDataSysProps = bindingData["SystemProperties"] as Dictionary<string, object>; Assert.NotNull(bindingDataSysProps); Assert.AreEqual(bindingDataSysProps["PartitionKey"], bindingData["PartitionKey"]); Assert.AreEqual(bindingDataSysProps["Offset"], bindingData["Offset"]); Assert.AreEqual(bindingDataSysProps["SequenceNumber"], bindingData["SequenceNumber"]); Assert.AreEqual(bindingDataSysProps["EnqueuedTimeUtc"], bindingData["EnqueuedTimeUtc"]); Assert.AreEqual(bindingDataSysProps["iothub-connection-device-id"], "testDeviceId"); Assert.AreEqual(bindingDataSysProps["iothub-enqueuedtime"], DateTime.MinValue); } private static TestEventData GetSystemProperties(byte[] body, string partitionKey = "TestKey") { long testSequence = 4294967296; return new TestEventData(body, partitionKey: partitionKey, offset: 140, enqueuedTime: DateTimeOffset.MinValue, sequenceNumber: testSequence, systemProperties: new Dictionary<string, object>() { {"iothub-connection-device-id", "testDeviceId"}, {"iothub-enqueuedtime", DateTime.MinValue} }); } [Test] public void GetBindingData_MultipleDispatch_ReturnsExpectedValue() { var events = new EventData[3] { GetSystemProperties(Encoding.UTF8.GetBytes("Event 1"), $"pk0"), GetSystemProperties(Encoding.UTF8.GetBytes("Event 2"), $"pk1"), GetSystemProperties(Encoding.UTF8.GetBytes("Event 3"),$"pk2"), }; var input = new EventHubTriggerInput { Events = events, PartitionContext = GetPartitionContext(), }; var strategy = new EventHubTriggerBindingStrategy(); var bindingData = strategy.GetBindingData(input); Assert.AreEqual(7, bindingData.Count); Assert.AreSame(input.PartitionContext, bindingData["PartitionContext"]); // verify an array was created for each binding data type Assert.AreEqual(events.Length, ((string[])bindingData["PartitionKeyArray"]).Length); Assert.AreEqual(events.Length, ((string[])bindingData["OffsetArray"]).Length); Assert.AreEqual(events.Length, ((long[])bindingData["SequenceNumberArray"]).Length); Assert.AreEqual(events.Length, ((DateTime[])bindingData["EnqueuedTimeUtcArray"]).Length); Assert.AreEqual(events.Length, ((IDictionary<string, object>[])bindingData["PropertiesArray"]).Length); Assert.AreEqual(events.Length, ((IDictionary<string, object>[])bindingData["SystemPropertiesArray"]).Length); Assert.AreEqual(events[0].PartitionKey, ((string[])bindingData["PartitionKeyArray"])[0]); Assert.AreEqual(events[1].PartitionKey, ((string[])bindingData["PartitionKeyArray"])[1]); Assert.AreEqual(events[2].PartitionKey, ((string[])bindingData["PartitionKeyArray"])[2]); } [Test] public void TriggerStrategy() { string data = "123"; var strategy = new EventHubTriggerBindingStrategy(); EventHubTriggerInput triggerInput = strategy.ConvertFromString(data); var contract = strategy.GetBindingData(triggerInput); EventData single = strategy.BindSingle(triggerInput, null); string body = Encoding.UTF8.GetString(single.Body.ToArray()); Assert.AreEqual(data, body); Assert.Null(contract["PartitionContext"]); Assert.Null(contract["partitioncontext"]); // case insensitive } [TestCase("e", "n1", "n1/e/")] [TestCase("e--1", "host_.path.foo", "host_.path.foo/e--1/")] [TestCase("Ab", "Cd", "cd/ab/")] [TestCase("A=", "Cd", "cd/a:3D/")] [TestCase("A:", "Cd", "cd/a:3A/")] public void EventHubBlobPrefix(string eventHubName, string serviceBusNamespace, string expected) { string actual = EventHubOptions.GetBlobPrefix(eventHubName, serviceBusNamespace); Assert.AreEqual(expected, actual); } [TestCase(1)] [TestCase(5)] [TestCase(200)] public void EventHubBatchCheckpointFrequency(int num) { var options = new EventHubOptions(); options.BatchCheckpointFrequency = num; Assert.AreEqual(num, options.BatchCheckpointFrequency); } [TestCase(-1)] [TestCase(0)] public void EventHubBatchCheckpointFrequency_Throws(int num) { var options = new EventHubOptions(); Assert.Throws<InvalidOperationException>(() => options.BatchCheckpointFrequency = num); } [Test] public void InitializeFromHostMetadata() { // TODO: It's tough to wire all this up without using a new host. IHost host = new HostBuilder() .ConfigureDefaultTestHost(builder => { builder.AddEventHubs(); }) .ConfigureAppConfiguration(c => { c.AddInMemoryCollection(new Dictionary<string, string> { { "AzureWebJobs:extensions:EventHubs:EventProcessorOptions:MaxBatchSize", "100" }, { "AzureWebJobs:extensions:EventHubs:EventProcessorOptions:PrefetchCount", "200" }, { "AzureWebJobs:extensions:EventHubs:BatchCheckpointFrequency", "5" }, { "AzureWebJobs:extensions:EventHubs:PartitionManagerOptions:LeaseDuration", "00:00:31" }, { "AzureWebJobs:extensions:EventHubs:PartitionManagerOptions:RenewInterval", "00:00:21" } }); }) .Build(); // Force the ExtensionRegistryFactory to run, which will initialize the EventHubConfiguration. var extensionRegistry = host.Services.GetService<IExtensionRegistry>(); var options = host.Services.GetService<IOptions<EventHubOptions>>().Value; var eventProcessorOptions = options.EventProcessorOptions; Assert.AreEqual(200, eventProcessorOptions.PrefetchCount); Assert.AreEqual(5, options.BatchCheckpointFrequency); Assert.AreEqual(100, options.MaxBatchSize); Assert.AreEqual(31, options.EventProcessorOptions.PartitionOwnershipExpirationInterval.TotalSeconds); Assert.AreEqual(21, options.EventProcessorOptions.LoadBalancingUpdateInterval.TotalSeconds); } internal static EventProcessorHostPartition GetPartitionContext(string partitionId = "0", string eventHubPath = "path", string consumerGroupName = "group", string owner = null) { var processor = new EventProcessorHost(consumerGroupName, "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123=", eventHubPath, new EventProcessorOptions(), Int32.MaxValue, false, null); return new EventProcessorHostPartition(partitionId) { ProcessorHost = processor }; } } }
48.504202
203
0.643624
[ "MIT" ]
ChenglongLiu/azure-sdk-for-net
sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/tests/EventHubTests.cs
11,546
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Site.Areas.Blogs.Pages { public partial class Blogs { /// <summary> /// CurrentEntity control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Microsoft.Xrm.Portal.Web.UI.WebControls.CrmEntityDataSource CurrentEntity; /// <summary> /// BlogDataSource control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ObjectDataSource BlogDataSource; /// <summary> /// BlogAggregationDataSource control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ObjectDataSource BlogAggregationDataSource; } }
34.883721
100
0.532
[ "MIT" ]
Adoxio/xRM-Portals-Community-Edition
Samples/MasterPortal/Areas/Blogs/Pages/Blogs.aspx.designer.cs
1,502
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HingePush : MonoBehaviour { public Rigidbody2D rb2d; public float leftPushRange; public float rightPushRange; public float velocityThreshold; // Start is called before the first frame update void Start() { rb2d = GetComponent<Rigidbody2D>(); rb2d.angularVelocity = velocityThreshold; } // Update is called once per frame void Update() { Push(); } private void Push() { if(transform.rotation.z > 0 && transform.rotation.z < rightPushRange && (rb2d.angularVelocity > 0) && rb2d.angularVelocity < velocityThreshold) { rb2d.angularVelocity = velocityThreshold; } else if(transform.rotation.z < 0 && transform.rotation.z > leftPushRange && (rb2d.angularVelocity < 0) && rb2d.angularVelocity > velocityThreshold * -1) { rb2d.angularVelocity = velocityThreshold * -1; } } }
24.045455
56
0.621928
[ "MIT" ]
Pzq-jw/CBX_RL
Assets/GamePlay/Scripts/Utilities/NoUse/HingePush.cs
1,060
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.PerformanceManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Get_Competencies_ResponseType : INotifyPropertyChanged { private CompetencyObjectType[] request_ReferencesField; private Competency_Request_CriteriaType request_CriteriaField; private Response_FilterType response_FilterField; private Competency_Response_GroupType response_GroupField; private Response_ResultsType response_ResultsField; private CompetencyType[] response_DataField; private string versionField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlArray(Order = 0), XmlArrayItem("Competency_Reference", IsNullable = false)] public CompetencyObjectType[] Request_References { get { return this.request_ReferencesField; } set { this.request_ReferencesField = value; this.RaisePropertyChanged("Request_References"); } } [XmlElement(Order = 1)] public Competency_Request_CriteriaType Request_Criteria { get { return this.request_CriteriaField; } set { this.request_CriteriaField = value; this.RaisePropertyChanged("Request_Criteria"); } } [XmlElement(Order = 2)] public Response_FilterType Response_Filter { get { return this.response_FilterField; } set { this.response_FilterField = value; this.RaisePropertyChanged("Response_Filter"); } } [XmlElement(Order = 3)] public Competency_Response_GroupType Response_Group { get { return this.response_GroupField; } set { this.response_GroupField = value; this.RaisePropertyChanged("Response_Group"); } } [XmlElement(Order = 4)] public Response_ResultsType Response_Results { get { return this.response_ResultsField; } set { this.response_ResultsField = value; this.RaisePropertyChanged("Response_Results"); } } [XmlArray(Order = 5), XmlArrayItem("Competency", IsNullable = false)] public CompetencyType[] Response_Data { get { return this.response_DataField; } set { this.response_DataField = value; this.RaisePropertyChanged("Response_Data"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string version { get { return this.versionField; } set { this.versionField = value; this.RaisePropertyChanged("version"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.319149
136
0.727545
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.PerformanceManagement/Get_Competencies_ResponseType.cs
3,006
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Threading.Tasks; using WasmClientEFCore.Db; namespace WasmClientEFCore.Server.Controllers { [ApiController] [Route("[controller]")] public class OrderController : ControllerBase { private WasmClientEFCoreDbContext Db { get; } public OrderController(WasmClientEFCoreDbContext db) { Db = db; } [HttpGet] public async Task<List<Order>> Get() { var orders = await Db.Orders.Include(x => x.OrderDetails).ToListAsync(); return orders; } } }
24.107143
84
0.645926
[ "MIT" ]
aherrick/WasmClientEFCore
WasmClientEFCore.Server/Controllers/OrderController.cs
677
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace FScruiser.XF.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SettingsView : ContentPage { public SettingsView () { InitializeComponent (); } } }
18.2
50
0.769231
[ "CC0-1.0" ]
FMSC-Measurements/NatCruise
src/FScruiser.Xamarin/Views/SettingsView.xaml.cs
366
C#
using System; namespace SharpPdb.Windows.SymbolRecords { /// <summary> /// Corresponds to the CV_PUBSYMFLAGS bitfield. /// </summary> [Flags] public enum PublicSymbolFlags : uint { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Set if internal symbol refers to a code address. /// </summary> Code = 0x00000001, /// <summary> /// Set if internal symbol is a function. /// </summary> Function = 0x00000002, /// <summary> /// Set if managed code (native or IL). /// </summary> Managed = 0x00000004, /// <summary> /// Set if managed IL code. /// </summary> MSIL = 0x00000008, } }
21.459459
60
0.496222
[ "MIT" ]
codehz/SharpPdb
Source/Windows/SymbolRecords/PublicSymbolFlags.cs
796
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Dolittle.Runtime.Events.Processing.EventHandlers; using Dolittle.Runtime.Events.Store.Streams; using Integration.Tests.Events.Processing.EventHandlers.given; using Machine.Specifications; namespace Integration.Tests.Events.Processing.EventHandlers.with_a_single.scoped.not_partitioned.event_handler.with_implicit_filter.processing_all_event_types.and_failing; [Ignore("Implicit filter does not work yet with event handlers")] class after_2_events : given.single_tenant_and_event_handlers { static IEventHandler event_handler; static string failure_reason; static PartitionId failing_partition; Establish context = () => { failing_partition = "some event source"; failure_reason = "some reason"; fail_after_processing_number_of_events(2, failure_reason); event_handler = setup_event_handler(); }; Because of = () => { commit_events_after_starting_event_handler((4, failing_partition.Value)); }; It should_the_correct_number_of_events_in_stream = () => expect_number_of_filtered_events(event_handler, scope_events_for_event_types(event_handler_scope, number_of_event_types).LongCount()); It should_have_persisted_correct_stream = () => expect_stream_definition(event_handler); It should_have_the_correct_stream_processor_states = () => expect_stream_processor_state_with_failure(event_handler, new failing_unpartitioned_state(1)); }
44.27027
195
0.790598
[ "MIT" ]
dolittle-runtime/Runtime
Integration/Tests/Events.Processing/EventHandlers/with_a_single/scoped/not_partitioned/event_handler/with_implicit_filter/processing_all_event_types/and_failing/after_2_events.cs
1,638
C#
using System; using System.IO; using System.Linq; using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Shell.PropertySystem; namespace GoPRO_MP4_Renamer { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("GoPROMP4Renamer <source directory>"); return; } var sourceDir = new DirectoryInfo(args[0]); if (sourceDir.Exists == false) { Console.WriteLine($"GoPROMP4Renamer <source> does not exists - [{sourceDir.FullName}]"); return; } var fileInfos = sourceDir.EnumerateFiles("*.MP4", SearchOption.AllDirectories).Union(sourceDir.EnumerateFiles("*.JPG", SearchOption.AllDirectories)); foreach (FileInfo fileInfo in fileInfos) { DateTime? dateEncoded = null; if (string.Equals(fileInfo.Extension, ".MP4", StringComparison.OrdinalIgnoreCase)) { ShellObject shellObject = ShellObject.FromParsingName(fileInfo.FullName); if (shellObject == null) { Console.WriteLine($"GoPROMP4Renamer - ParsingName for [{fileInfo.Name}] to ShellObject failed."); continue; } dateEncoded = shellObject.Properties.GetProperty(SystemProperties.System.Media.DateEncoded)?.ValueAsObject as DateTime?; if (dateEncoded == null) { Console.WriteLine($"GoPROMP4Renamer - System.Media.DateEncoded for [{fileInfo.Name}] returned null."); continue; } } else if (string.Equals(fileInfo.Extension, ".JPG", StringComparison.OrdinalIgnoreCase)) { ShellObject shellObject = ShellObject.FromParsingName(fileInfo.FullName); if (shellObject == null) { Console.WriteLine($"GoPROMP4Renamer - ParsingName for [{fileInfo.Name}] to ShellObject failed."); continue; } dateEncoded = shellObject.Properties.GetProperty(SystemProperties.System.Photo.DateTaken)?.ValueAsObject as DateTime?; if (dateEncoded == null) { Console.WriteLine($"GoPROMP4Renamer - System.Media.DateEncoded for [{fileInfo.Name}] returned null."); continue; } } if (dateEncoded == null) continue; if (fileInfo.DirectoryName == null) continue; DateTime mediaCreated = dateEncoded.Value; FileInfo newFileInfo = new FileInfo(Path.Combine(fileInfo.DirectoryName, $"Img{mediaCreated:yyyyMMdd}_{mediaCreated:HHmmss}{fileInfo.Extension}")); if (newFileInfo.Exists) { Console.WriteLine($"GoPROMP4Renamer - Cannot rename [{fileInfo.Name}] => [{newFileInfo.Name}] - File already exists."); continue; } try { Console.WriteLine($"GoPROMP4Renamer - Rename file [{fileInfo.Name}] => [{newFileInfo.Name}]"); fileInfo.MoveTo(newFileInfo.FullName); } catch (Exception e) { Console.WriteLine($"GoPROMP4Renamer - Cannot rename [{fileInfo.Name}] => [{newFileInfo.Name}]"); Console.WriteLine($"- Type:{e.GetType()} : {e.Message}{Environment.NewLine}"); } } } } }
39.84375
163
0.527582
[ "Unlicense" ]
rdyhalt/GoPRO-MP4-Renamer
GoPRO-MP4-Renamer/Program.cs
3,827
C#
using CHModel; using System.Collections.Generic; using System.Threading.Tasks; using System.Data; using Microsoft.Data.SqlClient; using System; namespace CHDL { //sql repo is to connect to the database and coordinate data/tables to maniuplate and update the data connected to the //user input through the methods in the Repo public class SqlRepository : IRepository { public const string connectionStringFilePath = "C:/Revature/Project_0/ChopHouseDraft/CHDL/Connection-string.txt"; readonly string connectionString; public SqlRepository(string connectionString) //initalizing the connection string variable on line 14 and file path on Line 13 { connectionString = File.ReadAllText(connectionStringFilePath); //assigning the connection string file path and reading the text. this.connectionString = connectionString; } public ChopHouse AddRestaurant(ChopHouse rest) /// <summary> /// "Restaurant added" /// </summary> /// <param name="rest"></param> /// <returns>the added restaurant <returns { string commandString = "INSERT INTO ChopHouse(StoreID,Name,City,State) VALUES" + "(@storeid,@name,@city,@state)"; using SqlConnection connection = new(connectionString); using SqlCommand command = new(commandString, connection); command.Parameters.AddWithValue("@storeid", rest.StoreID); command.Parameters.AddWithValue("@name", rest.Name); command.Parameters.AddWithValue("@city", rest.City); command.Parameters.AddWithValue("@state", rest.State); connection.Open(); command.ExecuteNonQuery(); return rest; } public HouseReview AddHouseReview(HouseReview view) { string selectCommandString = "INSERT INTO HouseReview(StoreID,UserId,Rating,Feedback) VALUES" + "(@storeid,@userid,@rating,@feedback)"; using SqlConnection connection = new(connectionString); using SqlCommand command = new(selectCommandString, connection); command.Parameters.AddWithValue("@storeid", view.StoreID); command.Parameters.AddWithValue("@userid", view.UserId); command.Parameters.AddWithValue("@rating", view.Rating); command.Parameters.AddWithValue("@feedback", view.Feedback); connection.Open(); command.ExecuteNonQuery(); return view; } public List<ChopHouse> SearchRestaurants() { string selectCommandString = "SELECT * FROM ChopHouse;"; //string selectCommandString = $"SELECT * FROM ChopHouse WHERE {name} = '{s}';"; //string commandString = "SELECT * FROM ChopHouse"; using SqlConnection connection = new(connectionString); using SqlCommand command = new(selectCommandString, connection); connection.Open(); using SqlDataReader reader = command.ExecuteReader(); //IDataAdapter adapter = new SqlDataAdapter(command); var Restaurants = new List<ChopHouse>(); while (reader.Read()) { Restaurants.Add(new ChopHouse { StoreID = reader.GetString(0), Name = reader.GetString(1), City = reader.GetString(2), State = reader.GetString(3), /*Rating = (int)row[3], Review = (string)row[4], NumRatings = (int)row[5],*/ }); } return Restaurants; } public async Task<List<ChopHouse>> GetAllChopHouseConnected() { string commandString = "SELECT * FROM ChopHouse;"; using SqlConnection connection = new(connectionString); using SqlCommand command = new SqlCommand(commandString, connection); await connection.OpenAsync();//Async using SqlDataReader reader = await command.ExecuteReaderAsync();//Async w/ await var chophouse = new List<ChopHouse>(); while (await reader.ReadAsync())//Async w/ await keyword { //put all constructors for ChopHouse and Users chophouse.Add(new ChopHouse { StoreID = reader.GetString(0), Name = reader.GetString(1), City = reader.GetString(2), State = reader.GetString(3), }); }// return chophouse; }// GetAllConnected() method Async.. and return task of list of ChopHouse Restaurants public List<ChopHouse> GetAllChopHouses() { //var seeAll = DisplayAll(); string commandString = $"SELECT * FROM ChopHouse;"; //string selectCommandString = $"SELECT * FROM ChopHouse WHERE = '{All}';"; using SqlConnection connection = new(connectionString); using SqlCommand command = new(commandString, connection); IDataAdapter adapter = new SqlDataAdapter(command); DataSet dataSet = new(); try { connection.Open(); adapter.Fill(dataSet); // this sends the query. DataAdapter uses a DataReader to read.} } catch (SqlException ex) { throw; //rethrow the exeption } catch(Exception ex) { } finally { connection.Close(); } var chophouse = new List<ChopHouse>(); DataColumn levelColumn = dataSet.Tables[0].Columns[2]; foreach (DataRow row in dataSet.Tables[0].Rows) { chophouse.Add(new ChopHouse { StoreID = (string)row[0], Name = (string)row[1], City = (string)row[2], State = (string)row[3], }); } return chophouse; } public async Task<List<ChopHouse>> GetAllChopHouseAsync() { string commandString = $"SELECT * FROM ChopHouse;"; //string selectCommandString = $"SELECT * FROM ChopHouse WHERE = '{All}';"; using SqlConnection connection = new(connectionString); using SqlCommand command = new(commandString, connection); IDataAdapter adapter = new SqlDataAdapter(command); DataSet dataSet = new(); try { /* async or */ await connection.OpenAsync(); adapter.Fill(dataSet); // this sends the query. DataAdapter uses a DataReader to read.} } catch (SqlException ex) { System.Console.WriteLine(ex.Message); } finally { connection.Close(); } var chophouse = new List<ChopHouse>(); DataColumn levelColumn = dataSet.Tables[0].Columns[2]; foreach (DataRow row in dataSet.Tables[0].Rows) { chophouse.Add(new ChopHouse { StoreID = (string)row[0], Name = (string)row[1], City = (string)row[2], State = (string)row[3], }); } return chophouse; } /*public async Task<List<ChopHouse>> SearchAllAsync() { return await Repo.GetAllPokemonsAsync(); }*/ } /*connection.Open(); using SqlDataReader reader = command.ExecuteReader(); var Restaurants = new List<ChopHouse>(); while (reader.Read()) { Restaurants.Add(new ChopHouse { Name = reader.GetString(0), City = reader.GetString(1), State = reader.GetString(2), StoreID = reader.GetString(6), }); } return Restaurants;*/ }
34.597561
140
0.529315
[ "MIT" ]
220328-uta-sh-net-ext/EdithKennedyTynes
Project_0/ChopHouseDraft/CHDL/SqlRepository.cs
8,513
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace WebAddressbookTests { public class NavigationHelper : HelperBase { private string baseURL; public NavigationHelper(ApplicationManager manager, string baseURL) : base(manager) { this.baseURL = baseURL; } public void GoToHomePage() { if (driver.Url == baseURL) { return; } driver.Navigate().GoToUrl(baseURL); } public void GoToGroupsPage() { if (driver.Url == baseURL + "/group.php" && IsElementPresent(By.Name("new"))) { return; } driver.FindElement(By.LinkText("groups")).Click(); } public void GoToContactsPage() { if (driver.Url == baseURL + "/edit.php" && IsElementPresent(By.Name("submit"))) { return; } driver.FindElement(By.LinkText("add new")).Click(); } } }
24.27451
91
0.531502
[ "Apache-2.0" ]
anastasiyaburaya/charp_training
addressbook-web-tests/addressbook-web-tests/appmanager/NavigationHelper.cs
1,240
C#
// // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. namespace Orc.Metadata.Model.Models.Model { using System; using Anotar.Catel; using Catel; using Orc.Metadata.Model.Models.Interfaces; /// <summary> /// <see cref="IModelMetadataCollection" /> instance with associated object instance. /// <see cref="ModelObjectWithMetadata" /> for a non-generic version. /// </summary> /// <typeparam name="TModel"> /// <see cref="IModelObjectWithMetadata{TModel}" /> model type constraint for /// (optional) providers contract. /// </typeparam> public class ModelObjectWithMetadata<TModel> : IModelObjectWithMetadata<TModel> where TModel : class, IModelMetadataCollection { #region Constructors /// <summary> /// Initializes a new instance of the /// <see cref="ModelObjectWithMetadata{TModel}" /> class. /// </summary> /// <param name="instance">The instance.</param> /// <param name="modelMetadataCollection">The model metadata.</param> public ModelObjectWithMetadata(object instance, TModel modelMetadataCollection) { Argument.IsNotNull(() => instance); Argument.IsNotNull(() => modelMetadataCollection); Instance = instance; ModelMetadataCollection = modelMetadataCollection; } #endregion #region Properties public object Instance { get; } public IMetadataCollection MetadataCollection => ModelMetadataCollection; public TModel ModelMetadataCollection { get; } #endregion #region Methods public IModelPropertyObjectWithMetadata GetPropertyObjectWithMetadataByName( string propertyName) { return ModelMetadataCollection.GetPropertyObjectWithMetadataByName( Instance, propertyName); } public object GetMetadataValue(string key) { var metadata = ModelMetadataCollection.GetMetadata(key); return metadata?.GetValue(Instance); } public bool SetMetadataValue(string key, object value) { var metadata = ModelMetadataCollection.GetMetadata(key); if (metadata == null) { return false; } try { metadata.SetValue(Instance, value); } catch (Exception ex) { LogTo.Error(ex, "Failed to set value on Metadata"); return false; } return true; } #endregion } /// <summary> /// <see cref="IModelMetadataCollection" /> instance with associated object instance. /// </summary> public class ModelObjectWithMetadata : ModelObjectWithMetadata<IModelMetadataCollection> { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ModelObjectWithMetadata" /> class. /// </summary> /// <param name="instance">The instance.</param> /// <param name="modelMetadataCollection">The model metadata.</param> public ModelObjectWithMetadata( object instance, IModelMetadataCollection modelMetadataCollection) : base(instance, modelMetadataCollection) { } #endregion } }
32.992647
95
0.63918
[ "MIT" ]
alexis-/Orc.Metadata.Model
src/Orc.Metadata.Model/Orc.Metadata.Model.Shared/Models/Model/ModelObjectWithMetadata.cs
4,489
C#
namespace CalculatorApp.Constants { public static class HomeControllerConstants { public const string ResultString = "{0} {1} {2} = {3:f2}"; public const string ResultOneNumberString = "{0} {1} = {2:f2}"; public const string InvalidOperationMessage = "Invalid operation!"; public const string FirstNumberParameterName = "numberOne"; public const string SecondNumberParameterName = "numberTwo"; public const string OperatorParameterName = "operation"; public const string Result = "result"; } }
28.45
75
0.671353
[ "MIT" ]
MJordanov81/SimpleCalculator
CalculatorApp/Constants/HomeControllerConstants.cs
571
C#
using Sys.Workflow.Cloud.Services.Api.Events; using Sys.Workflow.Cloud.Services.Events.Configurations; using Sys.Workflow.Engine.Delegate.Events; namespace Sys.Workflow.Cloud.Services.Events.Converters { /// <summary> /// /// </summary> public abstract class AbstractEventConverter : IEventConverter { /// <summary> /// /// </summary> public abstract string HandledType(); /// <summary> /// /// </summary> public abstract IProcessEngineEvent From(IActivitiEvent @event); /// <summary> /// /// </summary> private readonly RuntimeBundleProperties runtimeBundleProperties; /// <summary> /// /// </summary> public AbstractEventConverter(RuntimeBundleProperties runtimeBundleProperties) { this.runtimeBundleProperties = runtimeBundleProperties; } /// <summary> /// /// </summary> protected internal virtual RuntimeBundleProperties RuntimeBundleProperties { get { return runtimeBundleProperties; } } } }
22.566038
86
0.573579
[ "Apache-2.0" ]
18502079446/cusss
NActiviti/Sys.Bpm.Rest.API/events/converter/AbstractEventConverter.cs
1,198
C#
using BoSSS.Foundation.Grid; using BoSSS.Foundation.XDG; using BoSSS.Foundation.XDG.OperatorFactory; using BoSSS.Solution.XNSECommon; using ilPSP; using System; using System.Collections; using System.Collections.Generic; namespace BoSSS.Application.XNSEC { /// <summary> /// Reynolds number for homotopy /// </summary> public class ReynoldsNumber : Coefficient { double m_reynolds; public override IList<string> CoefficientsNames => new string[] { "Reynolds" }; public override DelCoefficientFactory Factory => ReynoldsNumberInit; public ReynoldsNumber(XNSEC_OperatorConfiguration config) { m_reynolds = config.Reynolds; } (string, object)[] ReynoldsNumberInit(LevelSetTracker lstrk, SpeciesId spc, int quadOrder, int TrackerHistoryIdx, double time) { var Ret = new (string, object)[1]; Ret[0] = (CoefficientsNames[0], m_reynolds); return Ret; } } }
29.771429
149
0.642035
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L4-application/XNSEC2/Coefficients.cs
1,010
C#
using System.Runtime.CompilerServices; using Xamarin.Forms; [assembly: InternalsVisibleTo ("Xamarin.Forms.ControlGallery.Android")] [assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms/customurl1", "Xamarin.Forms.Controls.CustomNamespace1")] [assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms/customurl1", "Xamarin.Forms.Controls.CustomNamespace2")] [assembly: XmlnsDefinition("http://xamarin.com/schemas/2014/forms/customurl2", "Xamarin.Forms.Controls.CustomNamespace3")]
55.888889
122
0.809145
[ "MIT" ]
Arobono/Xamarin.Forms
Xamarin.Forms.Controls/Properties/AssemblyInfo.cs
503
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("G6IdlToCpp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("G6IdlToCpp")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
36.181818
84
0.737856
[ "MIT" ]
kpengk/Mercury
VsPlugin/G6IdlToCpp/Properties/AssemblyInfo.cs
1,196
C#
using System.Globalization; using System.Linq; using FirebirdSql.EntityFrameworkCore.Firebird.Extensions; using Microsoft.EntityFrameworkCore; using SuperPowerEditor.Base.DataAccess.Entities; namespace SuperPowerEditor.Base.DataAccess { public class SuperPowerEditorDbContext : DbContext { private readonly string _connectionString; public SuperPowerEditorDbContext(string connectionString) { _connectionString = connectionString; } public DbSet<City> Cities { get; set; } public DbSet<Country> Countries { get; set; } public DbSet<CovOpsCell> CovOpsCells { get; set; } public DbSet<Design> Designs { get; set; } public DbSet<DesignFormat> DesignFormats { get; set; } public DbSet<GroupUnit> GroupUnits { get; set; } public DbSet<GvtType> GvtTypes { get; set; } public DbSet<Language> Languages { get; set; } public DbSet<LanguageMapping> LanguageMappings { get; set; } public DbSet<LanguagesStatus> LanguagesStatuses { get; set; } public DbSet<Missile> Missiles { get; set; } public DbSet<PoliticalParty> PoliticalParties { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<Relation> Relations { get; set; } public DbSet<Religion> Religions { get; set; } public DbSet<ReligionMapping> ReligionMappings { get; set; } public DbSet<ReligionsStatus> ReligionsStatuses { get; set; } public DbSet<Research> Researches { get; set; } public DbSet<ResourceName> ResourceNames { get; set; } public DbSet<Resources> Resourceses { get; set; } public DbSet<SellingUnit> SellingUnits { get; set; } public DbSet<Status> Statuses { get; set; } public DbSet<Treaty> Treaties { get; set; } public DbSet<TreatyCondition> TreatyConditions { get; set; } public DbSet<TreatyMember> TreatyMembers { get; set; } public DbSet<UnitGroup> UnitGroups { get; set; } public DbSet<UnitMapping> UnitMappings { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseFirebird(_connectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<City>().ToTable("CITIES"); modelBuilder.Entity<Country>().ToTable("COUNTRY"); modelBuilder.Entity<CovOpsCell>().ToTable("COV_OPS_CELL"); modelBuilder.Entity<Design>().ToTable("DESIGN"); modelBuilder.Entity<DesignFormat>().ToTable("DESIGN_FORMAT"); modelBuilder.Entity<GroupUnit>().ToTable("GROUP_UNIT"); modelBuilder.Entity<GvtType>().ToTable("GVT_TYPE"); modelBuilder.Entity<Language>().ToTable("LANGUAGE"); modelBuilder.Entity<LanguageMapping>().ToTable("LANGUAGES"); modelBuilder.Entity<LanguagesStatus>().ToTable("LANGUAGES_STATUS"); modelBuilder.Entity<Missile>().ToTable("MISSILE"); modelBuilder.Entity<PoliticalParty>().ToTable("PARTIES"); modelBuilder.Entity<Region>().ToTable("REGION"); modelBuilder.Entity<Relation>().ToTable("RELATIONS"); modelBuilder.Entity<Religion>().ToTable("RELIGION"); modelBuilder.Entity<ReligionMapping>().ToTable("RELIGIONS"); modelBuilder.Entity<ReligionsStatus>().ToTable("RELIGIONS_STATUS"); modelBuilder.Entity<Research>().ToTable("RESEARCH"); modelBuilder.Entity<ResourceName>().ToTable("RESOURCE_NAME"); modelBuilder.Entity<Resources>().ToTable("RESOURCES"); modelBuilder.Entity<SellingUnit>().ToTable("SELLING_UNITS"); modelBuilder.Entity<Status>().ToTable("STATUS"); modelBuilder.Entity<Treaty>().ToTable("TREATY"); modelBuilder.Entity<TreatyCondition>().ToTable("TREATY_CONDITION"); modelBuilder.Entity<TreatyMember>().ToTable("TREATY_MEMBER"); modelBuilder.Entity<UnitGroup>().ToTable("UNIT_GROUPS"); modelBuilder.Entity<UnitMapping>().ToTable("UNITS"); foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { property.Relational().ColumnName = ToColumnName(property.Name); } } modelBuilder.Entity<Country>() .Property(country => country.Pop1565Unemployed) .HasColumnName("POP_15_65_UNEMPLOYED"); modelBuilder.Entity<Design>() .HasOne(d => d.CountryDesignerRef) .WithMany() .HasForeignKey(design => design.CountryDesigner); modelBuilder.Entity<Design>() .Ignore(b => b.TypeRef); } private string ToColumnName(string propertyName) { return string.Concat(propertyName.Select((c, i) => i > 0 && char.IsUpper(c) ? "_" + c.ToString() : c.ToString().ToUpper(CultureInfo.GetCultureInfo("en-US")))); } } }
46.734513
85
0.63132
[ "MIT" ]
Blind-Striker/super-power-2-editor
src/Base/DataAccess/SuperPowerEditorDbContext.cs
5,283
C#
using System; using CoreGraphics; using Foundation; using UIKit; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Platform.iOS { public abstract class TemplatedCell : ItemsViewCell { public event EventHandler<EventArgs> ContentSizeChanged; protected CGSize ConstrainedSize; protected nfloat ConstrainedDimension; DataTemplate _currentTemplate; // Keep track of the cell size so we can verify whether a measure invalidation // actually changed the size of the cell Size _size; [Export("initWithFrame:")] [Internals.Preserve(Conditional = true)] protected TemplatedCell(CGRect frame) : base(frame) { } internal IVisualElementRenderer VisualElementRenderer { get; private set; } public override void ConstrainTo(CGSize constraint) { ConstrainedSize = constraint; } public override void ConstrainTo(nfloat constant) { ConstrainedDimension = constant; // Reset constrained size in case ItemSizingStrategy changes // and we want to measure each item ConstrainedSize = default(CGSize); } public override UICollectionViewLayoutAttributes PreferredLayoutAttributesFittingAttributes( UICollectionViewLayoutAttributes layoutAttributes) { var preferredAttributes = base.PreferredLayoutAttributesFittingAttributes(layoutAttributes); // Measure this cell (including the Forms element) if there is no constrained size var size = ConstrainedSize == default(CGSize) ? Measure() : ConstrainedSize; // Update the size of the root view to accommodate the Forms element var nativeView = VisualElementRenderer.NativeView; nativeView.Frame = new CGRect(CGPoint.Empty, size); // Layout the Forms element var nativeBounds = nativeView.Frame.ToRectangle(); VisualElementRenderer.Element.Layout(nativeBounds); _size = nativeBounds.Size; // Adjust the preferred attributes to include space for the Forms element preferredAttributes.Frame = new CGRect(preferredAttributes.Frame.Location, size); return preferredAttributes; } public void Bind(DataTemplate template, object bindingContext, ItemsView itemsView) { var oldElement = VisualElementRenderer?.Element; // Run this through the extension method in case it's really a DataTemplateSelector var itemTemplate = template.SelectDataTemplate(bindingContext, itemsView); if (itemTemplate != _currentTemplate) { // Remove the old view, if it exists if (oldElement != null) { oldElement.MeasureInvalidated -= MeasureInvalidated; itemsView.RemoveLogicalChild(oldElement); ClearSubviews(); _size = Size.Zero; } // Create the content and renderer for the view var view = itemTemplate.CreateContent() as View; // Set the binding context _before_ we create the renderer; that way, it's available during OnElementChanged view.BindingContext = bindingContext; var renderer = TemplateHelpers.CreateRenderer(view); SetRenderer(renderer); // And make the new Element a "child" of the ItemsView // We deliberately do this _after_ setting the binding context for the new element; // if we do it before, the element briefly inherits the ItemsView's bindingcontext and we // emit a bunch of needless binding errors itemsView.AddLogicalChild(view); } else { // Same template, different data var currentElement = VisualElementRenderer?.Element; if (currentElement != null) currentElement.BindingContext = bindingContext; } _currentTemplate = itemTemplate; } void SetRenderer(IVisualElementRenderer renderer) { VisualElementRenderer = renderer; var nativeView = VisualElementRenderer.NativeView; InitializeContentConstraints(nativeView); renderer.Element.MeasureInvalidated += MeasureInvalidated; } protected void Layout(CGSize constraints) { var nativeView = VisualElementRenderer.NativeView; var width = constraints.Width; var height = constraints.Height; VisualElementRenderer.Element.Measure(width, height, MeasureFlags.IncludeMargins); nativeView.Frame = new CGRect(0, 0, width, height); VisualElementRenderer.Element.Layout(nativeView.Frame.ToRectangle()); } void ClearSubviews() { for (int n = ContentView.Subviews.Length - 1; n >= 0; n--) { ContentView.Subviews[n].RemoveFromSuperview(); } } public override bool Selected { get => base.Selected; set { base.Selected = value; var element = VisualElementRenderer?.Element; if (element != null) { VisualStateManager.GoToState(element, value ? VisualStateManager.CommonStates.Selected : VisualStateManager.CommonStates.Normal); } } } protected abstract (bool, Size) NeedsContentSizeUpdate(Size currentSize); void MeasureInvalidated(object sender, EventArgs args) { var (needsUpdate, toSize) = NeedsContentSizeUpdate(_size); if (!needsUpdate) { return; } // Cache the size for next time _size = toSize; // Let the controller know that things need to be laid out again OnContentSizeChanged(); } protected void OnContentSizeChanged() { ContentSizeChanged?.Invoke(this, EventArgs.Empty); } } }
27.935484
112
0.737298
[ "MIT" ]
Ezeji/Xamarin.Forms
Xamarin.Forms.Platform.iOS/CollectionView/TemplatedCell.cs
5,198
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppWPF.Model { public class OnlineCourse { public int CourseID { get; set; } public string URL { get; set; } public virtual Course Course { get; set; }//Relación uno a uno } }
21.25
70
0.670588
[ "MIT" ]
johnsvill/app-wpf
Model/OnlineCourse.cs
343
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** 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.AzureNative.DataShare { public static class GetShareSubscription { /// <summary> /// A share subscription data transfer object. /// API Version: 2020-09-01. /// </summary> public static Task<GetShareSubscriptionResult> InvokeAsync(GetShareSubscriptionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetShareSubscriptionResult>("azure-native:datashare:getShareSubscription", args ?? new GetShareSubscriptionArgs(), options.WithVersion()); } public sealed class GetShareSubscriptionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the share account. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// The resource group name. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the shareSubscription. /// </summary> [Input("shareSubscriptionName", required: true)] public string ShareSubscriptionName { get; set; } = null!; public GetShareSubscriptionArgs() { } } [OutputType] public sealed class GetShareSubscriptionResult { /// <summary> /// Time at which the share subscription was created. /// </summary> public readonly string CreatedAt; /// <summary> /// The expiration date of the share subscription. /// </summary> public readonly string? ExpirationDate; /// <summary> /// The resource id of the azure resource /// </summary> public readonly string Id; /// <summary> /// The invitation id. /// </summary> public readonly string InvitationId; /// <summary> /// Name of the azure resource /// </summary> public readonly string Name; /// <summary> /// Email of the provider who created the resource /// </summary> public readonly string ProviderEmail; /// <summary> /// Name of the provider who created the resource /// </summary> public readonly string ProviderName; /// <summary> /// Tenant name of the provider who created the resource /// </summary> public readonly string ProviderTenantName; /// <summary> /// Provisioning state of the share subscription /// </summary> public readonly string ProvisioningState; /// <summary> /// Description of share /// </summary> public readonly string ShareDescription; /// <summary> /// Kind of share /// </summary> public readonly string ShareKind; /// <summary> /// Name of the share /// </summary> public readonly string ShareName; /// <summary> /// Gets the current status of share subscription. /// </summary> public readonly string ShareSubscriptionStatus; /// <summary> /// Terms of a share /// </summary> public readonly string ShareTerms; /// <summary> /// Source share location. /// </summary> public readonly string SourceShareLocation; /// <summary> /// System Data of the Azure resource. /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Type of the azure resource /// </summary> public readonly string Type; /// <summary> /// Email of the user who created the resource /// </summary> public readonly string UserEmail; /// <summary> /// Name of the user who created the resource /// </summary> public readonly string UserName; [OutputConstructor] private GetShareSubscriptionResult( string createdAt, string? expirationDate, string id, string invitationId, string name, string providerEmail, string providerName, string providerTenantName, string provisioningState, string shareDescription, string shareKind, string shareName, string shareSubscriptionStatus, string shareTerms, string sourceShareLocation, Outputs.SystemDataResponse systemData, string type, string userEmail, string userName) { CreatedAt = createdAt; ExpirationDate = expirationDate; Id = id; InvitationId = invitationId; Name = name; ProviderEmail = providerEmail; ProviderName = providerName; ProviderTenantName = providerTenantName; ProvisioningState = provisioningState; ShareDescription = shareDescription; ShareKind = shareKind; ShareName = shareName; ShareSubscriptionStatus = shareSubscriptionStatus; ShareTerms = shareTerms; SourceShareLocation = sourceShareLocation; SystemData = systemData; Type = type; UserEmail = userEmail; UserName = userName; } } }
30.418848
192
0.576764
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataShare/GetShareSubscription.cs
5,810
C#
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Pomelo.EntityFrameworkCore.MySql.Storage.Internal { /// <summary> /// <para> /// Represents the mapping between a .NET <see cref="bool" /> type and a database type. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// </summary> public class MySqlBoolTypeMapping : RelationalTypeMapping { /// <summary> /// Initializes a new instance of the <see cref="BoolTypeMapping" /> class. /// </summary> /// <param name="storeType"> The name of the database type. </param> public MySqlBoolTypeMapping( string storeType = null) : this( new RelationalTypeMappingParameters( new CoreTypeMappingParameters(typeof(bool)), storeType ?? "bit", StoreTypePostfix.None, System.Data.DbType.Boolean)) { } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected MySqlBoolTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override RelationalTypeMapping Clone(string storeType, int? size) => new MySqlBoolTypeMapping(Parameters.WithStoreTypeAndSize(storeType, size)); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override CoreTypeMapping Clone(ValueConverter converter) => new MySqlBoolTypeMapping(Parameters.WithComposedConverter(converter)); /// <summary> /// Generates the SQL representation of a literal value. /// </summary> /// <param name="value">The literal value.</param> /// <returns> /// The generated string. /// </returns> protected override string GenerateNonNullSqlLiteral(object value) => (bool)value ? "TRUE" : "FALSE"; } }
42.188406
105
0.611474
[ "MIT" ]
DeeJayTC/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql/Storage/Internal/MySqlBoolTypeMapping.cs
2,911
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : VSCommanding.ICommandHandler<InvokeCompletionListCommandArgs> { public bool ExecuteCommand(InvokeCompletionListCommandArgs args, CommandExecutionContext context) { AssertIsForeground(); if (EventHookupSessionManager.QuickInfoSession == null || EventHookupSessionManager.QuickInfoSession.IsDismissed) { return false; } return true; } public VSCommanding.CommandState GetCommandState(InvokeCompletionListCommandArgs args) { AssertIsForeground(); return VSCommanding.CommandState.Unspecified; } } }
36.9
161
0.718157
[ "Apache-2.0" ]
AdamSpeight2008/roslyn-1
src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_ShadowedCommands.cs
1,109
C#
namespace Loon.Core.Input { using Loon.Utils.Collection; using Microsoft.Xna.Framework.Input; public class LKey { internal int type; internal int keyCode; internal char keyChar; internal double timer; public LKey(byte[] o) { In(o); } internal LKey() { } LKey(LKey key) { this.type = key.type; this.keyCode = key.keyCode; this.keyChar = key.keyChar; } public double GetTimer() { return timer; } public bool Equals(LKey e) { if (e == null) { return false; } if (e == this) { return true; } if (e.type == type && e.keyCode == keyCode && e.keyChar == keyChar) { return true; } return false; } public char GetKeyChar() { return keyChar; } public int GetKeyCode() { return keyCode; } public int GetCode() { return type; } public bool IsDown() { return type == Key.KEY_DOWN; } public bool IsUp() { return type == Key.KEY_UP; } public byte[] Out() { ArrayByte touchByte = new ArrayByte(); touchByte.WriteInt(type); touchByte.WriteInt(keyCode); touchByte.WriteInt(keyChar); return touchByte.GetData(); } public void In(byte[] o) { ArrayByte touchByte = new ArrayByte(o); type = touchByte.ReadInt(); keyCode = touchByte.ReadInt(); keyChar = (char)touchByte.ReadInt(); type = touchByte.ReadInt(); } } }
19.58
79
0.430541
[ "Apache-2.0" ]
TheMadTitanSkid/LGame
C#/WindowsPhone/LGame-XNA-lib/Loon.Core.Input/LKey.cs
1,958
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WeatherBot.Services.Wit { public class WitIntent { public decimal confidence { get; set; } public string value { get; set; } } }
19.461538
47
0.675889
[ "MIT" ]
wojciech-stelmaszewski/chatbots_sandbox
WeatherBot/Services/Wit/WitIntent.cs
255
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.Domain.Model.V20180129; namespace Aliyun.Acs.Domain.Transform.V20180129 { public class SaveSingleTaskForQueryingTransferAuthorizationCodeResponseUnmarshaller { public static SaveSingleTaskForQueryingTransferAuthorizationCodeResponse Unmarshall(UnmarshallerContext context) { SaveSingleTaskForQueryingTransferAuthorizationCodeResponse saveSingleTaskForQueryingTransferAuthorizationCodeResponse = new SaveSingleTaskForQueryingTransferAuthorizationCodeResponse(); saveSingleTaskForQueryingTransferAuthorizationCodeResponse.HttpResponse = context.HttpResponse; saveSingleTaskForQueryingTransferAuthorizationCodeResponse.RequestId = context.StringValue("SaveSingleTaskForQueryingTransferAuthorizationCode.RequestId"); saveSingleTaskForQueryingTransferAuthorizationCodeResponse.TaskNo = context.StringValue("SaveSingleTaskForQueryingTransferAuthorizationCode.TaskNo"); return saveSingleTaskForQueryingTransferAuthorizationCodeResponse; } } }
46.634146
189
0.810146
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-domain/Domain/Transform/V20180129/SaveSingleTaskForQueryingTransferAuthorizationCodeResponseUnmarshaller.cs
1,912
C#
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Nest; using Tests.Framework.Integration; using Tests.Framework.MockData; using static Nest.Infer; namespace Tests.Aggregations.Bucket.Range { public class RangeAggregationUsageTests : AggregationUsageTestBase { public RangeAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object ExpectJson => new { aggs = new { commit_ranges = new { range = new { field = "numberOfCommits", ranges = new object[] { new { to = 100.0 }, new { from = 100.0, to = 500.0 }, new { from = 500.0 } } } } } }; protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s .Aggregations(a => a .Range("commit_ranges", ra => ra .Field(p => p.NumberOfCommits) .Ranges( r => r.To(100), r => r.From(100).To(500), r => r.From(500) ) ) ); protected override SearchRequest<Project> Initializer => new SearchRequest<Project> { Aggregations = new RangeAggregation("commit_ranges") { Field = Field<Project>(p => p.NumberOfCommits), Ranges = new List<Nest.Range> { { new Nest.Range { To = 100 } }, { new Nest.Range { From = 100, To = 500 } }, { new Nest.Range { From = 500 } } } } }; protected override void ExpectResponse(ISearchResponse<Project> response) { response.IsValid.Should().BeTrue(); var commitRanges = response.Aggs.Range("commit_ranges"); commitRanges.Should().NotBeNull(); commitRanges.Buckets.Count.Should().Be(3); commitRanges.Buckets.Where(r => r.Key == "*-100.0").FirstOrDefault().Should().NotBeNull(); commitRanges.Buckets.Where(r => r.Key == "100.0-500.0").FirstOrDefault().Should().NotBeNull(); commitRanges.Buckets.Where(r => r.Key == "500.0-*").FirstOrDefault().Should().NotBeNull(); } } }
26.797297
97
0.631871
[ "Apache-2.0" ]
RossLieberman/NEST
src/Tests/Aggregations/Bucket/Range/RangeAggregationUsageTests.cs
1,985
C#
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace Tests.Analysis.Dcca { using System; using System.Linq; using ISSE.SafetyChecking.AnalysisModelTraverser; using ISSE.SafetyChecking.MinimalCriticalSetAnalysis; using SafetySharp.Analysis; using SafetySharp.Modeling; using ISSE.SafetyChecking.Modeling; using SafetySharp.Runtime; using Shouldly; using ISSE.SafetyChecking.ExecutedModel; internal class Exception : AnalysisTestObject { protected override void Check() { if ((SafetyAnalysisBackend)Arguments[0] == SafetyAnalysisBackend.FaultOptimizedStateGraph) { var exception = Should.Throw<AnalysisException>(() => Dcca(true, new C())); exception.CounterExample.ShouldNotBeNull(); //SimulateCounterExample(exception.ExecutableCounterExample, // simulator => Should.Throw<ArgumentException>(() => simulator.FastForward(100)).Message.ShouldBe("arg")); } else { var c = new C(); var result = Dcca(c.X > 4, c); result.Faults.Count().ShouldBe(3); result.CheckedSets.Count.ShouldBe(4); result.MinimalCriticalSets.Count.ShouldBe(3); result.Exceptions.Count.ShouldBe(2); result.IsComplete.ShouldBe(true); result.SuppressedFaults.ShouldBeEmpty(); result.ForcedFaults.ShouldBeEmpty(); ShouldContain(result.CheckedSets); ShouldContain(result.CheckedSets, c.F1); ShouldContain(result.CheckedSets, c.F2); ShouldContain(result.CheckedSets, c.F3); ShouldContain(result.MinimalCriticalSets, c.F1); ShouldContain(result.MinimalCriticalSets, c.F2); ShouldContain(result.MinimalCriticalSets, c.F3); result.CounterExamples.Count.ShouldBe(3); foreach (var set in result.MinimalCriticalSets) result.CounterExamples.ContainsKey(set).ShouldBe(true); foreach (var exceptionSet in result.Exceptions.Keys) { ShouldContain(result.CheckedSets, exceptionSet.ToArray()); ShouldContain(result.MinimalCriticalSets, exceptionSet.ToArray()); } foreach (var set in result.MinimalCriticalSets) { if (!result.Exceptions.ContainsKey(set)) continue; if (set.Contains(c.F2)) { SimulateCounterExample(result.CounterExamples[set], simulator => Should.Throw<ArgumentException>(() => simulator.FastForward(100)).Message.ShouldBe("arg")); } else { SimulateCounterExample(result.CounterExamples[set], simulator => Should.Throw<InvalidOperationException>(() => simulator.FastForward(100)).Message.ShouldBe("test")); } } } } private class C : Component { public readonly Fault F1 = new TransientFault(); public readonly Fault F2 = new PermanentFault(); public readonly Fault F3 = new PermanentFault(); public int X; public override void Update() { X = 3; } [FaultEffect(Fault = nameof(F1))] [Priority(1)] private class E1 : C { public override void Update() { base.Update(); X += 4; } } [FaultEffect(Fault = nameof(F2))] [Priority(2)] private class E2 : C { public override void Update() { base.Update(); X += 1; throw new ArgumentException("arg"); } } [FaultEffect(Fault = nameof(F3))] [Priority(3)] private class E3 : C { public override void Update() { base.Update(); X += 1; throw new InvalidOperationException("test"); } } } } }
30.761905
120
0.70345
[ "MIT" ]
isse-augsburg/ssharp
SafetySharpTests/Analysis/Dcca/exception.cs
4,524
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using Core; using Domain; using Service; namespace WebUI.Areas.Admin.Models.NormTypeVM { public class NormTypeForEditViewModel { #region Properties /// <summary> /// ID /// </summary> [Display(Name = "编号")] public int ID { get; set; } ///<summary> /// 评价类型名称 /// </summary> [Display(Name = "评价类型名称")] [Required] public string InputName { get; set; } ///<summary> /// 排序码 /// </summary> [Display(Name = "排序码")] [Required] public int InputSortCode { get; set; } ///<summary> /// 权重 /// </summary> [Display(Name = "权重")] [Required] public decimal InputWeight { get; set; } ///<summary> ///颜色值 /// </summary> [Display(Name = "颜色值")] public string InputColor { get; set; } ///<summary> ///评价类型代码 /// </summary> [Display(Name = "评价类型代码")] [Required] public string InputNormTypeCode { get; set; } #endregion #region Methods #region 数据库模型->输入\视图模型 public static explicit operator NormTypeForEditViewModel(NormType dbModel) { NormTypeForEditViewModel viewModel = null; viewModel = new NormTypeForEditViewModel { ID = dbModel.ID, InputColor = dbModel.Color, InputName = dbModel.Name, InputNormTypeCode = dbModel.NormTypeCode, InputSortCode = dbModel.SortCode, InputWeight = dbModel.Weight }; return viewModel; } #endregion #region 输入模型->数据库模型 public static explicit operator NormType(NormTypeForEditViewModel inputModel) { NormType dbModel = null; if (inputModel.ID == 0) { // 创建 dbModel = new NormType(); } else { // 修改 dbModel = Container.Instance.Resolve<NormTypeService>().GetEntity(inputModel.ID); } dbModel.Name = inputModel.InputName?.Trim(); dbModel.Color = inputModel.InputColor?.Trim(); dbModel.SortCode = inputModel.InputSortCode; dbModel.Weight = inputModel.InputWeight; dbModel.NormTypeCode = inputModel.InputNormTypeCode; return dbModel; } #endregion #endregion } }
25.6
97
0.520089
[ "Apache-2.0" ]
yiyungent/TES
src/WebUI/Areas/Admin/Models/NormTypeVM/NormTypeForEditViewModel.cs
2,822
C#
/* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace EasyLocalization.Annotations { /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage. /// </summary> /// <example><code> /// [CanBeNull] object Test() => null; /// /// void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can never be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] public sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] public sealed class ItemCanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form. /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// void ShowError(string message, params object[] args) { /* do something */ } /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] public sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } [NotNull] public string FormatParameterName { get; private set; } } /// <summary> /// For a parameter that is expected to be one of the limited set of values. /// Specify fields of which type should be used as values for this parameter. /// </summary> [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] public sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/>. /// </summary> /// <example><code> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] public sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method /// is used to notify that some property value changed. /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// string _name; /// /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method)] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } [CanBeNull] public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output. /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output /// means that the methos doesn't return normally (throws or terminates the process).<br/> /// Value <c>canbenull</c> is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute /// with rows separated by semicolon. There is no notion of order rows, all rows are checked /// for applicability and applied per each program state tracked by R# analysis.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=&gt; halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null =&gt; true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null =&gt; null; notnull =&gt; notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("=&gt; true, result: notnull; =&gt; false, result: null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } [NotNull] public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not. /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// class Foo { /// string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] public sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// /// class UsesNoEquality { /// void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// class ComponentAttribute : Attribute { } /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] public sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections). /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes /// as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] public sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] public enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used.</summary> Access = 1, /// <summary>Indicates implicit assignment to a member.</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type.</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked /// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>. /// </summary> [Flags] public enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used.</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used.</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used. /// </summary> [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] public sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [CanBeNull] public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>. /// </summary> /// <example><code> /// [Pure] int Multiply(int x, int y) => x * y; /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] public sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that the return value of method invocation must be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class MustUseReturnValueAttribute : Attribute { public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } [CanBeNull] public string Justification { get; private set; } } /// <summary> /// Indicates the type member or parameter of some type, that should be used instead of all other ways /// to get the value that type. This annotation is useful when you have some "context" value evaluated /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. /// </summary> /// <example><code> /// class Foo { /// [ProvidesContext] IBarService _barService = ...; /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] public sealed class ProvidesContextAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder within a web project. /// Path can be relative or absolute, starting from web root (~). /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([NotNull, PathReference] string basePath) { BasePath = basePath; } [CanBeNull] public string BasePath { get; private set; } } /// <summary> /// An extension method marked with this attribute is processed by ReSharper code completion /// as a 'Source Template'. When extension method is completed over some expression, it's source code /// is automatically expanded like a template at call site. /// </summary> /// <remarks> /// Template method body can contain valid source code and/or special comments starting with '$'. /// Text inside these comments is added as source code when the template is applied. Template parameters /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. /// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters. /// </remarks> /// <example> /// In this example, the 'forEach' method is a source template available over all values /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: /// <code> /// [SourceTemplate] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; xs) { /// foreach (var x in xs) { /// //$ $END$ /// } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public sealed class SourceTemplateAttribute : Attribute { } /// <summary> /// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>. /// </summary> /// <remarks> /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression /// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target /// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently /// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1. /// </remarks> /// <example> /// Applying the attribute on a source template method: /// <code> /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection) { /// foreach (var item in collection) { /// //$ $END$ /// } /// } /// </code> /// Applying the attribute on a template method parameter: /// <code> /// [SourceTemplate] /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /// /*$ var $x$Id = "$newguid$" + x.ToString(); /// x.DoSomething($x$Id); */ /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] public sealed class MacroAttribute : Attribute { /// <summary> /// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see> /// parameter when the template is expanded. /// </summary> [CanBeNull] public string Expression { get; set; } /// <summary> /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. /// </summary> /// <remarks> /// If the target parameter is used several times in the template, only one occurrence becomes editable; /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. /// </remarks>> public int Editable { get; set; } /// <summary> /// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the /// <see cref="MacroAttribute"/> is applied on a template method. /// </summary> [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcAreaAttribute : Attribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is /// an MVC controller. If applied to a method, the MVC controller name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC /// partial view. If applied to a method, the MVC partial view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcPartialViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AspMvcSuppressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component name. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcViewComponentAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewComponentViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name. /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] public sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [CanBeNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] public sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method, constructor invocation or property access /// over collection type affects content of the collection. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class CollectionAccessAttribute : Attribute { public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } public CollectionAccessType CollectionAccessType { get; private set; } } [Flags] public enum CollectionAccessType { /// <summary>Method does not use or modify content of the collection.</summary> None = 0, /// <summary>Method only reads content of the collection but does not modify it.</summary> Read = 1, /// <summary>Method can change content of the collection but does not add new elements.</summary> ModifyExistingContent = 2, /// <summary>Method can add new elements to the collection.</summary> UpdatedContent = ModifyExistingContent | 4 } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// <see cref="AssertionConditionAttribute"/> attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AssertionConditionAttribute : Attribute { public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } public AssertionConditionType ConditionType { get; private set; } } /// <summary> /// Specifies assertion type. If the assertion method argument satisfies the condition, /// then the execution continues. Otherwise, execution is assumed to be halted. /// </summary> public enum AssertionConditionType { /// <summary>Marked parameter should be evaluated to true.</summary> IS_TRUE = 0, /// <summary>Marked parameter should be evaluated to false.</summary> IS_FALSE = 1, /// <summary>Marked parameter should be evaluated to null value.</summary> IS_NULL = 2, /// <summary>Marked parameter should be evaluated to not null value.</summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception. /// </summary> [Obsolete("Use [ContractAnnotation('=> halt')] instead")] [AttributeUsage(AttributeTargets.Method)] public sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters /// of delegate type by analyzing LINQ method chains. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class RegexPatternAttribute : Attribute { } /// <summary> /// Prevents the Member Reordering feature from tossing members of the marked class. /// </summary> /// <remarks> /// The attribute must be mentioned in your member reordering patterns /// </remarks> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] public sealed class NoReorderAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated /// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that /// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will /// enable the <c>DataContext</c> type resolve for XAML bindings for such properties. /// </summary> /// <remarks> /// Property should have the tree ancestor of the <c>ItemsControl</c> type or /// marked with the <see cref="XamlItemsControlAttribute"/> attribute. /// </remarks> [AttributeUsage(AttributeTargets.Property)] public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } [NotNull] public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] public sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorDirectiveAttribute : Attribute { public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } [NotNull] public string Directive { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorPageBaseTypeAttribute : Attribute { public RazorPageBaseTypeAttribute([NotNull] string baseType) { BaseType = baseType; } public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) { BaseType = baseType; PageName = pageName; } [NotNull] public string BaseType { get; private set; } [CanBeNull] public string PageName { get; private set; } } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class RazorWriteMethodParameterAttribute : Attribute { } }
39.179343
120
0.708096
[ "MIT" ]
mashbrno/EasyLocalization
EasyLocalization.Demo/Properties/Annotations.cs
41,728
C#
using System; using System.Collections.Generic; using System.Linq; using BNA.Common; using BNA.Exceptions; namespace BNA.Compile { /// <summary> /// A collection of tokens that make up a whole valid statement or instruction. /// Each statement maps to a "line of code". /// </summary> public struct Statement { /// <summary> /// The StatementType of this Statement /// </summary> public Operation Type { get; init; } /// <summary> /// First operand of this Statement, the storage variable for operations that store a value /// </summary> public Token Operand1 { get; init; } /// <summary> /// Second operand of this Statement /// </summary> public Token Operand2 { get; init; } /// <summary> /// The raw string of the line that generated this statement. /// </summary> public string Line { get; init; } public Statement( string line , Operation type , Token? operand1 = null , Token? operand2 = null ) { this.Line = line; this.Type = type; this.Operand1 = operand1 ?? default; this.Operand2 = operand2 ?? default; } /// <summary> /// Stringify the Statement with type information. /// </summary> /// <returns>String description of this Statement</returns> public override string ToString( ) { string str = "[" + this.Type + "] \t"; str += $"op1={this.Operand1,-24} op2={this.Operand2,-24}"; return str; } public override bool Equals( object? obj ) => obj is Statement other && this.Type == other.Type && this.Operand1 == other.Operand1 && this.Operand2 == other.Operand2 && this.Line == other.Line; public (Token, Token) GetPrimaryAndSecondaryTokens( ) { // TODO remove this function switch ( this.Type ) { case Operation.NULL: case Operation.LABEL: case Operation.SCOPE_OPEN: case Operation.SCOPE_CLOSE: case Operation.EXIT: return (default, default); case Operation.ADD: case Operation.SUBTRACT: case Operation.MODULUS: case Operation.LOGARITHM: case Operation.APPEND: case Operation.OPEN_READ: case Operation.OPEN_WRITE: case Operation.READ: case Operation.WRITE: case Operation.SET: case Operation.MULTIPLY: case Operation.DIVIDE: case Operation.RANDOM: case Operation.POWER: case Operation.LIST: case Operation.SIZE: case Operation.TEST_GREATER_THAN: case Operation.TEST_LESS_THAN: case Operation.TEST_EQUAL: case Operation.TEST_NOT_EQUAL: case Operation.GOTO: case Operation.TYPE: return (this.Operand1, this.Operand2); case Operation.ROUND: case Operation.CLOSE: case Operation.INPUT: return (this.Operand1, default); case Operation.PRINT: case Operation.WAIT: case Operation.ERROR: return (this.Operand2, default); case Operation.BITWISE_OR: case Operation.BITWISE_AND: case Operation.BITWISE_XOR: case Operation.BITWISE_NEGATE: throw new NotImplementedException( $"Token sorting not implemented for {this.Type}." ); default: throw new Exception( $"Unexpected statement type in token sorting: {this.Type}." ); } } public override int GetHashCode( ) { return System.HashCode.Combine( this.Type , this.Operand1 , this.Operand2 , this.Line ); } } }
26.512
100
0.666566
[ "MIT" ]
jfmekker/bna-language
BNA/Compile/Statement.cs
3,316
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 System; using System.Collections.Generic; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Packets; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Brokerages.Oanda { /// <summary> /// Provides an implementations of <see cref="IBrokerageFactory"/> that produces a <see cref="OandaBrokerage"/> /// </summary> public class OandaBrokerageFactory: BrokerageFactory { /// <summary> /// Initializes a new instance of the <see cref="OandaBrokerageFactory"/> class. /// </summary> public OandaBrokerageFactory() : base(typeof(OandaBrokerage)) { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { } /// <summary> /// Gets the brokerage data required to run the brokerage from configuration/disk /// </summary> /// <remarks> /// The implementation of this property will create the brokerage data dictionary required for /// running live jobs. See <see cref="IJobQueueHandler.NextJob"/> /// </remarks> public override Dictionary<string, string> BrokerageData { get { return new Dictionary<string, string> { { "oanda-environment", Config.Get("oanda-environment") }, { "oanda-access-token", Config.Get("oanda-access-token") }, { "oanda-account-id", Config.Get("oanda-account-id") }, { "oanda-agent", Config.Get("oanda-agent", OandaRestApiBase.OandaAgentDefaultValue) } }; } } /// <summary> /// Gets a new instance of the <see cref="OandaBrokerageModel"/> /// </summary> /// <param name="orderProvider">The order provider</param> public override IBrokerageModel GetBrokerageModel(IOrderProvider orderProvider) => new OandaBrokerageModel(); /// <summary> /// Creates a new <see cref="IBrokerage"/> instance /// </summary> /// <param name="job">The job packet to create the brokerage for</param> /// <param name="algorithm">The algorithm instance</param> /// <returns>A new brokerage instance</returns> public override IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm) { var errors = new List<string>(); // read values from the brokerage data var environment = Read<Environment>(job.BrokerageData, "oanda-environment", errors); var accessToken = Read<string>(job.BrokerageData, "oanda-access-token", errors); var accountId = Read<string>(job.BrokerageData, "oanda-account-id", errors); var agent = Read<string>(job.BrokerageData, "oanda-agent", errors); if (errors.Count != 0) { // if we had errors then we can't create the instance throw new Exception(string.Join(System.Environment.NewLine, errors)); } var brokerage = new OandaBrokerage( algorithm.Transactions, algorithm.Portfolio, Composer.Instance.GetExportedValueByTypeName<IDataAggregator>(Config.Get("data-aggregator", "QuantConnect.Lean.Engine.DataFeeds.AggregationManager"), forceTypeNameOnExisting: false), environment, accessToken, accountId, agent); Composer.Instance.AddPart<IDataQueueHandler>(brokerage); return brokerage; } } }
40.666667
198
0.628046
[ "Apache-2.0" ]
Algoman2010/Lean
Brokerages/Oanda/OandaBrokerageFactory.cs
4,516
C#
// Copyright (c) 2012-2020 VLINGO LABS. All rights reserved. // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL // was not distributed with this file, You can obtain // one at https://mozilla.org/MPL/2.0/. using System; using System.Collections.Generic; using Vlingo.Actors; using Vlingo.Common; namespace Vlingo.Http.Resource { public class RequestHandler4<T, R, U, I> : RequestHandler { internal ParameterResolver<T> ResolverParam1 { get; } internal ParameterResolver<R> ResolverParam2 { get; } internal ParameterResolver<U> ResolverParam3 { get; } internal ParameterResolver<I> ResolverParam4 { get; } private ParamExecutor4? _executor; public delegate ICompletes<Response> Handler4(T param1, R param2, U param3, I param4); public delegate ICompletes<IObjectResponse> ObjectHandler4(T param1, R param2, U param3, I param4); internal delegate ICompletes<Response> ParamExecutor4( Request request, T param1, R param2, U param3, I param4, MediaTypeMapper mediaTypeMapper, IErrorHandler errorHandler, ILogger logger); internal RequestHandler4( Method method, string path, ParameterResolver<T> resolverParam1, ParameterResolver<R> resolverParam2, ParameterResolver<U> resolverParam3, ParameterResolver<I> resolverParam4, IErrorHandler errorHandler, MediaTypeMapper mediaTypeMapper) : base(method, path, new List<IParameterResolver> { resolverParam1, resolverParam2, resolverParam3, resolverParam4 }, errorHandler, mediaTypeMapper) { ResolverParam1 = resolverParam1; ResolverParam2 = resolverParam2; ResolverParam3 = resolverParam3; ResolverParam4 = resolverParam4; } internal ICompletes<Response> Execute(Request request, T param1, R param2, U param3, I param4, ILogger logger) { Func<ICompletes<Response>> exec = () => _executor?.Invoke(request, param1, param2, param3, param4, MediaTypeMapper, ErrorHandler, logger)!; return RunParamExecutor(_executor, () => RequestExecutor.ExecuteRequest(exec, ErrorHandler, logger)); } public RequestHandler4<T, R, U, I>? Handle(Handler4 handler) { _executor = (request, param1, param2, param3, param4, mediaTypeMapper1, errorHandler1, logger1) => RequestExecutor.ExecuteRequest(() => handler.Invoke(param1, param2, param3, param4), errorHandler1, logger1); return this; } public RequestHandler4<T, R, U, I> Handle(ObjectHandler4 handler) { _executor = (request, param1, param2, param3, param4, mediaTypeMapper1, errorHandler1, logger) => RequestObjectExecutor.ExecuteRequest( request, mediaTypeMapper1, () => handler.Invoke(param1, param2, param3, param4), errorHandler1, logger); return this; } public RequestHandler4<T, R, U, I> OnError(IErrorHandler errorHandler) { ErrorHandler = errorHandler; return this; } internal override ICompletes<Response> Execute( Request request, Action.MappedParameters mappedParameters, ILogger logger) { var param1 = ResolverParam1.Apply(request, mappedParameters); var param2 = ResolverParam2.Apply(request, mappedParameters); var param3 = ResolverParam3.Apply(request, mappedParameters); var param4 = ResolverParam4.Apply(request, mappedParameters); return Execute(request, param1, param2, param3, param4, logger); } public RequestHandler5<T, R, U, I, J> Param<J>() => new RequestHandler5<T, R, U, I, J>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Path<J>(4), ErrorHandler, MediaTypeMapper); public RequestHandler5<T, R, U, I, J> Body<J>() => new RequestHandler5<T, R, U, I, J>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Body<J>(MediaTypeMapper), ErrorHandler, MediaTypeMapper); [Obsolete("Deprecated in favor of using the ContentMediaType method, which handles media types appropriately. Use Body<J>(Type, MediaTypeMapper) or Body<J>(Type).")] public RequestHandler5<T, R, U, I, J> Body<J>(Type mapperClass) => Body<J>(MapperFrom(mapperClass)); [Obsolete("Deprecated in favor of using the ContentMediaType method, which handles media types appropriately. Use Body<J>(Type, MediaTypeMapper) or Body<J>(Type).")] public RequestHandler5<T, R, U, I, J> Body<J>(IMapper mapper) => new RequestHandler5<T, R, U, I, J>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Body<J>(mapper), ErrorHandler, MediaTypeMapper); public RequestHandler5<T, R, U, I, J> Body<J>(MediaTypeMapper mediaTypeMapper) => new RequestHandler5<T, R, U, I, J>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Body<J>(mediaTypeMapper), ErrorHandler, mediaTypeMapper); public RequestHandler5<T, R, U, I, string> Query(string name) => Query<string>(name, typeof(string)); public RequestHandler5<T, R, U, I, J> Query<J>(string name, Type queryClass) => new RequestHandler5<T, R, U, I, J>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Query<J>(name), ErrorHandler, MediaTypeMapper); public RequestHandler5<T, R, U, I, Header> Header(string name) => new RequestHandler5<T, R, U, I, Header>( Method, Path, ResolverParam1, ResolverParam2, ResolverParam3, ResolverParam4, ParameterResolver.Header(name), ErrorHandler, MediaTypeMapper); } }
39.662921
173
0.574788
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Luteceo/vlingo-all
vlingo-net-http/src/Vlingo.Http/Resource/RequestHandler4.cs
7,062
C#
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace EC { public class Persistent : MonoBehaviour { static private Persistent _instance; private readonly Dictionary<Type, Component> ComponentDictionary = new Dictionary<Type, Component>(); private void Awake() { _instance = this; } static private void Init() { GameObject prefab = (GameObject)Resources.Load("Persistent"); GameObject instance = Instantiate(prefab); _instance = instance.GetComponent<Persistent>(); DontDestroyOnLoad(_instance); } static public T Get<T>() where T : Component { if (_instance == null) Init(); Component component; _instance.ComponentDictionary.TryGetValue(typeof(T), out component); if (component != null) { return (T)component; } else { component = _instance.GetComponentInChildren<T>(); _instance.ComponentDictionary.Add(typeof(T), component); return (T)component; } } } }
21.297872
103
0.702298
[ "MIT" ]
rygo6/HoldBlack-Unity
Assets/HoldBlack/Scripts/Component/Persistent.cs
1,003
C#
using System.Collections.Generic; using UnityEditor; using UnityEngine; [CustomEditor(typeof(SoundLibrary))] public class SoundLibraryInspector : Editor { string textSearch; HashSet<string> soundEntryNames = new HashSet<string>(); public override void OnInspectorGUI() { serializedObject.Update(); SerializedProperty soundEntriesProperty = serializedObject.FindProperty("soundEntries"); textSearch = GUILayout.TextField(textSearch); if (GUILayout.Button("Collapse All")) { for (int i = 0; i < soundEntriesProperty.arraySize; i++) { SerializedProperty soundEntryProperty = soundEntriesProperty.GetArrayElementAtIndex( i ); soundEntryProperty.isExpanded = false; } } EditorGUILayout.PropertyField(serializedObject.FindProperty("audioMixerGroup")); GUILayout.Space(40); ShowSoundEntries(soundEntriesProperty); serializedObject.ApplyModifiedProperties(); } private void ShowSoundEntries(SerializedProperty soundEntriesProperty) { if (soundEntriesProperty.arraySize == 0) soundEntriesProperty.arraySize += 1; soundEntryNames.Clear(); for (int i = 0; i < soundEntriesProperty.arraySize; i++) { SerializedProperty soundEntryProperty = soundEntriesProperty.GetArrayElementAtIndex(i); Object audioClip = soundEntryProperty.FindPropertyRelative("audioClip").objectReferenceValue; //Skip the entry if text search is active and entry does not have relevant alias if (!string.IsNullOrEmpty(textSearch) && audioClip != null) { SerializedProperty aliases = soundEntryProperty.FindPropertyRelative("aliases"); HashSet<string> _aliases = new HashSet<string>(); if (aliases != null) { for (int j = 0; j < aliases.arraySize; j++) { SerializedProperty alias = aliases.GetArrayElementAtIndex(j); _aliases.Add(alias.stringValue.ToLower()); } } _aliases.Add(audioClip.name); string lowerTextSearch = textSearch.ToLower(); bool match = false; foreach (string alias in _aliases) { if (alias.Contains(textSearch.ToLower())) { match = true; break; } } if (!match) continue; } ShowSoundEntry(soundEntriesProperty, soundEntryProperty, i); //Remove entries that are null (unless it is the last one) or already added if ( i < soundEntriesProperty.arraySize - 1 && ( audioClip == null || (audioClip != null && soundEntryNames.Contains(audioClip.name)) ) ) { soundEntriesProperty.DeleteArrayElementAtIndex(i); i--; //Was questioning whether it is necessary. It is, otherwise the object reference window does not work properly continue; } if (audioClip != null) soundEntryNames.Add(audioClip.name); } //Add an entry if the final audioClip is not null SerializedProperty finalSoundEntry = soundEntriesProperty.GetArrayElementAtIndex( soundEntriesProperty.arraySize - 1 ); Object finalAudioClip = finalSoundEntry.FindPropertyRelative("audioClip").objectReferenceValue; if (finalAudioClip != null) { SoundLibrary soundLibrary = target as SoundLibrary; List<SoundEntry> soundEntries = soundLibrary.soundEntries; soundEntries.Add(new SoundEntry()); } } private static void ShowSoundEntry( SerializedProperty soundEntriesProperty, SerializedProperty soundEntryProperty, int index ) { EditorGUILayout.PropertyField(soundEntryProperty); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if ( index < soundEntriesProperty.arraySize - 1 && GUILayout.Button("-", GUILayout.MaxWidth(20), GUILayout.MaxHeight(16)) ) { soundEntriesProperty.DeleteArrayElementAtIndex(index); } GUILayout.EndHorizontal(); GUILayout.Space(5); } }
35.240602
131
0.576488
[ "MIT" ]
alexjhetherington/FootnoteUtilities
FootnoteUtilities/Sound Manager/Editor/SoundLibraryInspector.cs
4,689
C#
using System; using System.Diagnostics; using System.IO.Ports; using System.Text; using static MeadowCLI.DeviceManagement.MeadowFileManager; using MeadowCLI.DeviceManagement; namespace MeadowCLI.Hcom { public class SendTargetData { const int HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH = 12; const int HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH = 32; const int HCOM_PROTOCOL_COMMAND_SEQ_NUMBER = 0; const UInt16 HCOM_PROTOCOL_CURRENT_VERSION_NUMBER = 0x0005; const UInt16 HCOM_PROTOCOL_EXTRA_DATA_DEFAULT_VALUE = 0x0000; // Currently not used field //questioning if this class should send or just create the message MeadowSerialDevice _device; //refactor this .... uint _packetCrc32; //========================================================================== // Constructor public SendTargetData(MeadowSerialDevice device, bool verbose = true) { _device = device; this.Verbose = verbose; } //========================================================================== public bool Verbose { get; protected set; } public void SendTheEntireFile(HcomMeadowRequestType requestType, string destFileName, uint partitionId, byte[] fileBytes, UInt32 mcuAddr, UInt32 payloadCrc32, string md5Hash, bool lastInSeries) { _packetCrc32 = 0; try { // Build and send the header BuildAndSendFileRelatedCommand(requestType, partitionId, (UInt32)fileBytes.Length, payloadCrc32, mcuAddr, md5Hash, destFileName); //-------------------------------------------------------------- // Build each data packet int fileBufOffset = 0; int numbToSend; UInt16 sequenceNumber = 1; while (fileBufOffset <= fileBytes.Length - 1) // equal would mean past the end { if ((fileBufOffset + MeadowDeviceManager.MaxAllowableDataBlock) > (fileBytes.Length - 1)) numbToSend = fileBytes.Length - fileBufOffset; // almost done, last packet else numbToSend = MeadowDeviceManager.MaxAllowableDataBlock; BuildAndSendDataPacketRequest(fileBytes, fileBufOffset, numbToSend, sequenceNumber); fileBufOffset += numbToSend; sequenceNumber++; //if (sequenceNumber % 1000 == 0) // Console.WriteLine("Have sent {0:N0} bytes out of {1:N0} in {2:N0} packets", // fileBufOffset, fileBytes.Length, sequenceNumber); } //-------------------------------------------------------------- // Build and send the trailer BuildAndSendSimpleCommand(HcomMeadowRequestType.HCOM_MDOW_REQUEST_END_FILE_TRANSFER, lastInSeries ? (uint)1 : (uint)0); // set UserData // bufferOffset should point to the byte after the last byte Debug.Assert(fileBufOffset == fileBytes.Length); if(Verbose) Console.WriteLine($"Total bytes sent {fileBufOffset:N0} in {sequenceNumber:N0} packets. PacketCRC:{_packetCrc32:x08}"); } catch (Exception except) { Debug.WriteLine("Exception sending to Meadow:{0}", except); throw; } } //========================================================================== internal void SendSimpleCommand(HcomMeadowRequestType requestType, uint userData = 0) { BuildAndSendSimpleCommand(requestType, userData); } //========================================================================== // Prepare a data packet for sending private void BuildAndSendDataPacketRequest(byte[] messageBytes, int messageOffset, int messageSize, UInt16 seqNumb) { try { // Need to prepend the sequence number to the packet int xmitSize = messageSize + sizeof(UInt16); byte[] fullMsg = new byte[xmitSize]; byte[] encodedBytes = new byte[MeadowDeviceManager.MaxSizeOfXmitPacket]; byte[] seqBytes = BitConverter.GetBytes(seqNumb); Array.Copy(seqBytes, fullMsg, sizeof(UInt16)); Array.Copy(messageBytes, messageOffset, fullMsg, sizeof(UInt16), messageSize); EncodeAndSendPacket(fullMsg, 0, xmitSize); } catch (Exception except) { Console.WriteLine($"An exception was caught: {except}"); throw; } } //========================================================================== // Build and send a "simple" message with data // Added for Visual Studio Debugging internal void BuildAndSendSimpleData(byte[] additionalData, HcomMeadowRequestType requestType, UInt32 userData) { int totalMsgLength = additionalData.Length + HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH; var messageBytes = new byte[totalMsgLength]; // Populate the header BuildMeadowBoundSimpleCommand(requestType, userData, ref messageBytes); // Copy the payload into the message Array.Copy(additionalData, 0, messageBytes, HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH, additionalData.Length); EncodeAndSendPacket(messageBytes, 0, totalMsgLength); } //========================================================================== // Build and send a "simple" message with only a header internal void BuildAndSendSimpleCommand(HcomMeadowRequestType requestType, UInt32 userData) { var messageBytes = new byte[HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH]; // Populate the header BuildMeadowBoundSimpleCommand(requestType, userData, ref messageBytes); EncodeAndSendPacket(messageBytes, 0, HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH); } //========================================================================== // This is most of the mandatory part of every non-data packet private int BuildMeadowBoundSimpleCommand(HcomMeadowRequestType requestType, UInt32 userData, ref byte[] messageBytes) { // Note: Could use the StructLayout attribute to build int offset = 0; // Two byte seq numb Array.Copy(BitConverter.GetBytes((UInt16)HCOM_PROTOCOL_COMMAND_SEQ_NUMBER), 0, messageBytes, offset, sizeof(UInt16)); offset += sizeof(UInt16); // Protocol version Array.Copy(BitConverter.GetBytes((UInt16)HCOM_PROTOCOL_CURRENT_VERSION_NUMBER), 0, messageBytes, offset, sizeof(UInt16)); offset += sizeof(UInt16); // Command type (2 bytes) Array.Copy(BitConverter.GetBytes((UInt16)requestType), 0, messageBytes, offset, sizeof(UInt16)); offset += sizeof(UInt16); // Extra Data Array.Copy(BitConverter.GetBytes((UInt16)HCOM_PROTOCOL_EXTRA_DATA_DEFAULT_VALUE), 0, messageBytes, offset, sizeof(UInt16)); offset += sizeof(UInt16); // User Data Array.Copy(BitConverter.GetBytes((UInt32)userData), 0, messageBytes, offset, sizeof(UInt32)); offset += sizeof(UInt32); return offset; } //========================================================================== internal void BuildAndSendFileRelatedCommand(HcomMeadowRequestType requestType, UInt32 userData, UInt32 fileSize, UInt32 fileCheckSum, UInt32 mcuAddr, string md5Hash, string destFileName) { // Future: Try to use the StructLayout attribute Debug.Assert(md5Hash.Length == 0 || md5Hash.Length == HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH); // Allocate the correctly size message buffers byte[] targetFileName = Encoding.UTF8.GetBytes(destFileName); // Using UTF-8 works for ASCII but should be Unicode in nuttx byte[] md5HashBytes = Encoding.UTF8.GetBytes(md5Hash); int optionalDataLength = sizeof(UInt32) + sizeof(UInt32) + sizeof(UInt32) + HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH + targetFileName.Length; byte[] messageBytes = new byte[HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH + optionalDataLength]; // Add the required header int offset = BuildMeadowBoundSimpleCommand(requestType, userData, ref messageBytes); // File Size Array.Copy(BitConverter.GetBytes(fileSize), 0, messageBytes, offset, sizeof(UInt32)); offset += sizeof(UInt32); // CRC32 checksum or delete file partition number Array.Copy(BitConverter.GetBytes(fileCheckSum), 0, messageBytes, offset, sizeof(UInt32)); offset += sizeof(UInt32); // MCU address for this file. Used for ESP32 file downloads Array.Copy(BitConverter.GetBytes(mcuAddr), 0, messageBytes, offset, sizeof(UInt32)); offset += sizeof(UInt32); // Include ESP32 MD5 hash if it's needed if (string.IsNullOrEmpty(md5Hash)) Array.Clear(messageBytes, offset, HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH); else Array.Copy(md5HashBytes, 0, messageBytes, offset, HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH); offset += HCOM_PROTOCOL_REQUEST_MD5_HASH_LENGTH; // Destination File Name Array.Copy(targetFileName, 0, messageBytes, offset, targetFileName.Length); offset += targetFileName.Length; Debug.Assert(offset == optionalDataLength + HCOM_PROTOCOL_COMMAND_REQUIRED_HEADER_LENGTH); EncodeAndSendPacket(messageBytes, 0, offset); } //========================================================================== // Last stop before transmitting information private void EncodeAndSendPacket(byte[] messageBytes, int messageOffset, int messageSize) { try { // For testing calculate the crc including the sequence number _packetCrc32 = CrcTools.Crc32part(messageBytes, messageSize, 0, _packetCrc32); byte[] encodedBytes = new byte[MeadowDeviceManager.MaxSizeOfXmitPacket]; int encodedToSend = CobsTools.CobsEncoding(messageBytes, messageOffset, messageSize, ref encodedBytes); // Verify COBS - any delimiters left? for (int i = 0; i < encodedToSend; i++) { if (encodedBytes[i] == 0x00) { throw new InvalidProgramException("All zeros should have been removed. " + $"There's one at {i}"); } } // Terminate packet with delimiter so packet boundaries can be found encodedBytes[encodedToSend] = 0; encodedToSend++; try { if (_device.Socket != null) { _device.Socket.Send(encodedBytes, encodedToSend, System.Net.Sockets.SocketFlags.None); } else { if (_device.SerialPort == null) throw new ArgumentException("SerialPort cannot be null"); _device.SerialPort.Write(encodedBytes, 0, encodedToSend); } } catch (InvalidOperationException ioe) // Port not opened { Console.WriteLine("Write but port not opened. Exception: {0}", ioe); throw; } catch (ArgumentOutOfRangeException aore) // offset or count don't match buffer { Console.WriteLine("Write buffer, offset and count don't line up. Exception: {0}", aore); throw; } catch (ArgumentException ae) // offset plus count > buffer length { Console.WriteLine("Write offset plus count > buffer length. Exception: {0}", ae); throw; } catch (TimeoutException te) // Took too long to send { Console.WriteLine("Write took too long to send. Exception: {0}", te); throw; } } catch (Exception except) { Debug.WriteLine($"EncodeAndSendPacket threw: {except}"); throw; } } } }
46.027304
148
0.536037
[ "Apache-2.0" ]
patridge/Meadow.CLI
Meadow.CLI.Core/Internals/MeadowComms/SendTargetData.cs
13,488
C#
namespace MicroLite.Tests.Collections { using MicroLite.Collections; using Xunit; public class StackCollectionTests { public class WhenAddingItems { private readonly StackCollection<string> collection = new StackCollection<string>(); [Fact] public void ItemsAreAddedToTheTopOfTheCollection() { collection.Add("Added First"); Assert.Equal(1, collection.Count); Assert.Equal("Added First", collection[0]); collection.Add("Added Second"); Assert.Equal(2, collection.Count); Assert.Equal("Added Second", collection[0]); Assert.Equal("Added First", collection[1]); } } public class WhenConstructed { private readonly StackCollection<string> collection = new StackCollection<string>(); [Fact] public void TheCollectionIsEmpty() { Assert.Empty(collection); } } } }
30.135135
97
0.533632
[ "Apache-2.0" ]
orangesocks/MicroLite
MicroLite.Tests/Collections/StackCollectionTests.cs
1,081
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; #pragma warning disable 1591 namespace OpenCvSharp { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal unsafe struct WCvConDensation { public int MP; public int DP; public float* DynamMatr; public float* State; public int SamplesNum; public float** flSamples; public float** flNewSamples; public float* flConfidence; public float* flCumulative; public float* Temp; public float* RandomSample; public void* RandS; } }
24.37037
65
0.662614
[ "BSD-3-Clause" ]
0sv/opencvsharp
src/OpenCvSharp/Src/PInvoke/Struct/Etc/WCvConDensation.cs
660
C#
using Mzg.Core.Data; using System; namespace Mzg.Data.Abstractions { /// <summary> /// 事务工作单元 /// </summary> public class UnitOfWork : IDisposable { private readonly IDbContext _dbContext; //禁止用注入的方式实例化 private UnitOfWork(IDbContext dbContext) { _dbContext = dbContext; _dbContext.BeginTransaction(); } public void Dispose() { if (!_dbContext.TransactionCancelled) { _dbContext.CompleteTransaction(); } } public static UnitOfWork Build(IDbContext dbContext) { return new UnitOfWork(dbContext); } } }
21.333333
60
0.548295
[ "MIT" ]
lygwys/dlvm_lygwys
Libraries/DataCore/Mzg.Data.Abstractions/UnitOfWork.cs
740
C#
/* * Square Connect API * * Client library for accessing the Square Connect APIs * * OpenAPI spec version: 2.0 * Contact: developers@squareup.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Square.Connect.Model { /// <summary> /// /// </summary> [DataContract] [Obsolete] public partial class V1ListCategoriesResponse : IEquatable<V1ListCategoriesResponse>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="V1ListCategoriesResponse" /> class. /// </summary> /// <param name="Items">.</param> public V1ListCategoriesResponse(List<V1Category> Items = default(List<V1Category>)) { this.Items = Items; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="items", EmitDefaultValue=false)] public List<V1Category> Items { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class V1ListCategoriesResponse {\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as V1ListCategoriesResponse); } /// <summary> /// Returns true if V1ListCategoriesResponse instances are equal /// </summary> /// <param name="other">Instance of V1ListCategoriesResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(V1ListCategoriesResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Items == other.Items || this.Items != null && this.Items.SequenceEqual(other.Items) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Items != null) hash = hash * 59 + this.Items.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
31.024194
109
0.565636
[ "Apache-2.0" ]
square/connect-csharp-sdk
src/Square.Connect/Model/V1ListCategoriesResponse.cs
3,847
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. ==================================================================== */ namespace TestCases.POIFS.Crypt { using ICSharpCode.SharpZipLib.Zip; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXml4Net.Util; using NPOI.POIFS.Crypt; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.XSSF; using NUnit.Framework; using Org.BouncyCastle.Security; using System; using System.Collections; using System.IO; [TestFixture] public class TestSecureTempZip { /** * Test case for #59841 - this is an example on how to use encrypted temp files, * which are streamed into POI opposed to having everything in memory */ [Test] public void ProtectedTempZip() { FileInfo tmpFile = TempFile.CreateTempFile("protectedXlsx", ".zip"); FileInfo tikaProt = XSSFTestDataSamples.GetSampleFile("protected_passtika.xlsx"); FileInputStream fis = new FileInputStream(tikaProt.Open(FileMode.Open)); POIFSFileSystem poifs = new POIFSFileSystem(fis); EncryptionInfo ei = new EncryptionInfo(poifs); Decryptor dec = ei.Decryptor; bool passOk = dec.VerifyPassword("tika"); Assert.IsTrue(passOk); // generate session key SecureRandom sr = new SecureRandom(); byte[] ivBytes = new byte[16], keyBytes = new byte[16]; sr.NextBytes(ivBytes); sr.NextBytes(keyBytes); // extract encrypted ooxml file and write to custom encrypted zip file InputStream is1 = dec.GetDataStream(poifs); CopyToFile(is1, tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); is1.Close(); // provide ZipEntrySource to poi which decrypts on the fly ZipEntrySource source = fileToSource(tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); // test the source OPCPackage opc = OPCPackage.Open(source); String expected = "This is an Encrypted Excel spreadsheet."; //XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc); //extractor.IncludeSheetNames = (/*setter*/false); //String txt = extractor.Text; //Assert.AreEqual(expected, txt.Trim()); //XSSFWorkbook wb = new XSSFWorkbook(opc); //txt = wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue; //Assert.AreEqual(expected, txt); //extractor.Close(); //wb.Close(); opc.Close(); source.Close(); poifs.Close(); fis.Close(); tmpFile.Delete(); throw new NotImplementedException(); } private void CopyToFile(InputStream is1, FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes) { SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); Cipher ciEnc = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, "PKCS5PAdding"); ZipInputStream zis = new ZipInputStream(is1); //FileOutputStream fos = new FileOutputStream(tmpFile); //ZipOutputStream zos = new ZipOutputStream(fos); //ZipEntry ze; //while ((ze = zis.NextEntry) != null) //{ // // the cipher output stream pads the data, therefore we can't reuse the ZipEntry with Set sizes // // as those will be validated upon close() // ZipEntry zeNew = new ZipEntry(ze.Name); // zeNew.Comment = (/*setter*/ze.Comment); // zeNew.Extra = (/*setter*/ze.Extra); // zeNew.Time = (/*setter*/ze.Time); // // zeNew.Method=(/*setter*/ze.Method); // zos.PutNextEntry(zeNew); // FilterOutputStream fos2 = new FilterOutputStream(zos) // { // // don't close underlying ZipOutputStream // public void close() { } //}; //CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc); // IOUtils.Copy(zis, cos); // cos.Close(); // fos2.Close(); // zos.CloseEntry(); // zis.CloseEntry(); //} //zos.Close(); //fos.Close(); //zis.Close(); throw new NotImplementedException(); } private ZipEntrySource fileToSource(FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes) { SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); Cipher ciDec = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5PAdding"); ZipFile zf = new ZipFile(tmpFile.FullName); return new AesZipFileZipEntrySource(zf, ciDec); } class AesZipFileZipEntrySource : ZipEntrySource { ZipFile zipFile; Cipher ci; bool closed; public AesZipFileZipEntrySource(ZipFile zipFile, Cipher ci) { this.zipFile = zipFile; this.ci = ci; this.closed = false; } /** * Note: the file sizes are rounded up to the next cipher block size, * so don't rely on file sizes of these custom encrypted zip file entries! */ public IEnumerator Entries { get { return zipFile.GetEnumerator(); } } public Stream GetInputStream(ZipEntry entry) { Stream is1 = zipFile.GetInputStream(entry); throw new NotImplementedException(); //return new CipherInputStream(is1, ci); } public void Close() { zipFile.Close(); closed = true; } public bool IsClosed { get { return closed; } } } } }
38.637838
144
0.570649
[ "Apache-2.0" ]
68681395/npoi
testcases/ooxml/POIFS/Crypt/TestSecureTempZip.cs
7,148
C#
using System.Collections.Generic; using System.IO; namespace CarrierPidgeon.InterfaceLoad { public class FileSystem : IFileSystem { public IEnumerable<string> GetDllFiles() { var path = Path.Combine(Directory.GetCurrentDirectory(), "interfaces"); if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } return Directory.GetFiles(path, "*.dll*"); } } }
22.714286
83
0.584906
[ "MIT" ]
DillonAd/CarrierPidgeon
CarrierPidgeon/InterfaceLoad/FileSystem.cs
479
C#
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_UnityEngine_AnimationEvent : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int constructor(IntPtr l) { try { UnityEngine.AnimationEvent o; o=new UnityEngine.AnimationEvent(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_stringParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.stringParameter); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_stringParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); string v; checkType(l,2,out v); self.stringParameter=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_floatParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.floatParameter); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_floatParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); float v; checkType(l,2,out v); self.floatParameter=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_intParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.intParameter); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_intParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); int v; checkType(l,2,out v); self.intParameter=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_objectReferenceParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.objectReferenceParameter); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_objectReferenceParameter(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); UnityEngine.Object v; checkType(l,2,out v); self.objectReferenceParameter=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_functionName(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.functionName); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_functionName(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); string v; checkType(l,2,out v); self.functionName=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_time(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.time); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_time(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); float v; checkType(l,2,out v); self.time=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_messageOptions(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.messageOptions); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_messageOptions(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); UnityEngine.SendMessageOptions v; checkEnum(l,2,out v); self.messageOptions=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_isFiredByLegacy(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.isFiredByLegacy); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_isFiredByAnimator(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.isFiredByAnimator); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_animationState(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.animationState); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_animatorStateInfo(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.animatorStateInfo); return 2; } catch(Exception e) { return error(l,e); } } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_animatorClipInfo(IntPtr l) { try { UnityEngine.AnimationEvent self=(UnityEngine.AnimationEvent)checkSelf(l); pushValue(l,true); pushValue(l,self.animatorClipInfo); return 2; } catch(Exception e) { return error(l,e); } } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.AnimationEvent"); addMember(l,"stringParameter",get_stringParameter,set_stringParameter,true); addMember(l,"floatParameter",get_floatParameter,set_floatParameter,true); addMember(l,"intParameter",get_intParameter,set_intParameter,true); addMember(l,"objectReferenceParameter",get_objectReferenceParameter,set_objectReferenceParameter,true); addMember(l,"functionName",get_functionName,set_functionName,true); addMember(l,"time",get_time,set_time,true); addMember(l,"messageOptions",get_messageOptions,set_messageOptions,true); addMember(l,"isFiredByLegacy",get_isFiredByLegacy,null,true); addMember(l,"isFiredByAnimator",get_isFiredByAnimator,null,true); addMember(l,"animationState",get_animationState,null,true); addMember(l,"animatorStateInfo",get_animatorStateInfo,null,true); addMember(l,"animatorClipInfo",get_animatorClipInfo,null,true); createTypeMetatable(l,constructor, typeof(UnityEngine.AnimationEvent)); } }
28.561873
105
0.74274
[ "MIT" ]
MonkeyKingMKY/luaide-lite
test/slua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_AnimationEvent.cs
8,542
C#
using AutoMapper; using Domain.AppTrainer; namespace Application.AppTrainer.Lores.Others { public class MappingProfile : Profile { public MappingProfile() { CreateMap<Tome, TomeLoresDto>(); } } }
23.2
47
0.663793
[ "MIT" ]
rafaelmmedeiros/Timetoplayone
Application/AppTrainer/Lores/Others/MappingProfile.cs
232
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace RaycastVision { class Player { public static Vector2 Position = new Vector2(50, 50); public static float Rotation = 0; public static float FOV = 30; public static int Health = 100; public static int LoadedAmmo = 6; public static int Magazines = 4; public static float ShotTime = 500; public static float ReloadTime = 1000; public static void Reload() { Magazines--; LoadedAmmo = 6; } public static void Shoot() { LoadedAmmo--; RayVision.Sounds[0].Play(); Vector2 dir = new Vector2(); dir.X = 1 * (float)Math.Cos(180 - (Rotation + 10) * 0.01754f) - 1 * (float)Math.Sin( 180 - (Rotation + 10) * 0.01745f); dir.Y = 1 * (float)Math.Sin(180 - (Rotation + 10) * 0.01754f) + 1 * (float)Math.Cos( 180 - (Rotation + 10) * 0.01745f); Console.WriteLine(-dir); foreach (Enemy enemy in RayVision.Grid.Enemies) { Vector2 cast = Raycasting.CastObjects(RayVision.Grid, Player.Position, dir); if (Vector2.Distance(cast, enemy.Position) < 0.5f) { enemy.Health -= 35; } } } private static float _shotTimer, _reloadTimer, _infoTextTimer, _keyDownDelay; public static void Update(GameTime gameTime) { var state = Keyboard.GetState(); var direction = new Vector2(); if (state.IsKeyDown(Keys.Z)) direction.Y = -0.1f; if (state.IsKeyDown(Keys.S)) direction.Y = 0.1f; if (state.IsKeyDown(Keys.D)) Rotation += 1f; if (state.IsKeyDown(Keys.Q)) Rotation -= 1f; if (state.IsKeyDown(Keys.OemPlus)) FOV += 1f; if (state.IsKeyDown(Keys.OemMinus)) FOV -= 1f; if (state.IsKeyDown(Keys.R) && _reloadTimer == 0 && LoadedAmmo == 0 && Magazines > 0) { _reloadTimer = 1; RayVision.Sounds[1].Play(); } else if (state.IsKeyDown(Keys.R) && LoadedAmmo > 0) { RayVision.InfoText = "Don't waste a magazine !"; } if (state.IsKeyDown(Keys.R) && Magazines <= 0 && _keyDownDelay == 0) { RayVision.InfoText = "You don't have any magazine"; RayVision.Sounds[2].Play(); _keyDownDelay = 1; } if (_reloadTimer == 0) { if (state.IsKeyDown(Keys.Space) && _shotTimer == 0 && LoadedAmmo > 0) { _shotTimer = ShotTime / 6; RayVision.WeapAnimState = 1; } else if (state.IsKeyDown(Keys.Space) && LoadedAmmo <= 0 && _keyDownDelay == 0) { RayVision.InfoText = "You don't have any loaded ammo"; RayVision.Sounds[2].Play(); _keyDownDelay = 1; } } if (_shotTimer > 0) { RayVision.WeapAnimState = (int)(_shotTimer / (ShotTime / 4)); _shotTimer += gameTime.ElapsedGameTime.Milliseconds; if (RayVision.LastAnim == 1 && RayVision.LastAnim != RayVision.WeapAnimState) { Shoot(); } if (_shotTimer > ShotTime) { _shotTimer = 0; RayVision.WeapAnimState = 0; } RayVision.LastAnim = RayVision.WeapAnimState; } if (_reloadTimer > 0) { _reloadTimer += gameTime.ElapsedGameTime.Milliseconds; if (_reloadTimer < ReloadTime / 2) RayVision.WeapOffset -= 0.01f; else RayVision.WeapOffset += 0.01f; if (_reloadTimer >= ReloadTime) { _reloadTimer = 0; RayVision.WeapOffset = 0; Reload(); } } if (_keyDownDelay > 0) { _keyDownDelay += gameTime.ElapsedGameTime.Milliseconds; if (_keyDownDelay > 1000) _keyDownDelay = 0; } if (RayVision.InfoText.Length > 0) { _infoTextTimer += gameTime.ElapsedGameTime.Milliseconds; if (_infoTextTimer > 1000) { RayVision.InfoText = ""; _infoTextTimer = 0; } } var movement = new Vector2( direction.X * (float)Math.Cos((360 - Rotation) * 0.01745f) - direction.Y * (float)Math.Sin((360 - Rotation) * 0.01745f), direction.X * (float)Math.Sin((360 - Rotation) * 0.01745f) + direction.Y * (float)Math.Cos((360 - Rotation) * 0.01745f)); if (movement != new Vector2() && Vector2.Distance(Position, Raycasting.LineCast(RayVision.Grid, Position, Position + movement * 100, false)) > 1) { Position += movement; if (RayVision.Offset > 0.05f) RayVision.OffsetVariation = -0.005f; else if (RayVision.Offset < -0.05f) RayVision.OffsetVariation = 0.005f; RayVision.Offset += RayVision.OffsetVariation; } } } }
36.359281
132
0.459816
[ "MIT" ]
MrBrenan/RaycastVision
RaycastVision/Player.cs
6,074
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V28.Segment; using NHapi.Model.V28.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V28.Group { ///<summary> ///Represents the ORG_O20_RESPONSE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: ORG_O20_PATIENT (a Group object) optional </li> ///<li>1: ORG_O20_ORDER (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class ORG_O20_RESPONSE : AbstractGroup { ///<summary> /// Creates a new ORG_O20_RESPONSE Group. ///</summary> public ORG_O20_RESPONSE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(ORG_O20_PATIENT), false, false); this.add(typeof(ORG_O20_ORDER), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORG_O20_RESPONSE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns ORG_O20_PATIENT (a Group object) - creates it if necessary ///</summary> public ORG_O20_PATIENT PATIENT { get{ ORG_O20_PATIENT ret = null; try { ret = (ORG_O20_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of ORG_O20_ORDER (a Group object) - creates it if necessary ///</summary> public ORG_O20_ORDER GetORDER() { ORG_O20_ORDER ret = null; try { ret = (ORG_O20_ORDER)this.GetStructure("ORDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of ORG_O20_ORDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public ORG_O20_ORDER GetORDER(int rep) { return (ORG_O20_ORDER)this.GetStructure("ORDER", rep); } /** * Returns the number of existing repetitions of ORG_O20_ORDER */ public int ORDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ORDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the ORG_O20_ORDER results */ public IEnumerable<ORG_O20_ORDER> ORDERs { get { for (int rep = 0; rep < ORDERRepetitionsUsed; rep++) { yield return (ORG_O20_ORDER)this.GetStructure("ORDER", rep); } } } ///<summary> ///Adds a new ORG_O20_ORDER ///</summary> public ORG_O20_ORDER AddORDER() { return this.AddStructure("ORDER") as ORG_O20_ORDER; } ///<summary> ///Removes the given ORG_O20_ORDER ///</summary> public void RemoveORDER(ORG_O20_ORDER toRemove) { this.RemoveStructure("ORDER", toRemove); } ///<summary> ///Removes the ORG_O20_ORDER at the given index ///</summary> public void RemoveORDERAt(int index) { this.RemoveRepetition("ORDER", index); } } }
28.421053
154
0.685979
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V28/Group/ORG_O20_RESPONSE.cs
3,780
C#
using System; using System.Globalization; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.pdf.draw; using OptigemLdapSync.Models; using static iTextSharp.text.Utilities; namespace OptigemLdapSync { internal class NewUserReport { private const float BaseFontSize = 10; private readonly TempFilemanager fileManager; protected Font TitleFont { get; } = FontFactory.GetFont("Arial", 1.2F * BaseFontSize, Font.BOLD); protected Font StandardFont { get; } = FontFactory.GetFont("Arial", BaseFontSize, Font.NORMAL); protected Font StandardBoldFont { get; } = FontFactory.GetFont("Arial", BaseFontSize, Font.BOLD); protected IHyphenationEvent Hyphenation = new HyphenationAuto("de", "DE", 2, 2); public NewUserReport(TempFilemanager fileManager) { if (fileManager == null) throw new ArgumentException(nameof(fileManager)); this.fileManager = fileManager; } public string Create(PersonModel person) { var pdfdoc = new Document(); pdfdoc.SetPageSize(PageSize.A4); pdfdoc.SetMargins(MillimetersToPoints(25), MillimetersToPoints(20), MillimetersToPoints(25), MillimetersToPoints(15)); var culture = CultureInfo.GetCultureInfo("de-DE"); var stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(pdfdoc, stream); pdfdoc.Open(); Image logo = Image.GetInstance(Properties.Resources.FegLogo, System.Drawing.Imaging.ImageFormat.Png); logo.ScaleToFit(MillimetersToPoints(55f), MillimetersToPoints(500f)); logo.SetAbsolutePosition(pdfdoc.PageSize.Width - MillimetersToPoints(73f) - MillimetersToPoints(55f), pdfdoc.PageSize.Height - MillimetersToPoints(23f)); pdfdoc.Add(logo); var header = new PdfPTable(1) { WidthPercentage = 100, HeaderRows = 0 }; header.DefaultCell.Border = Rectangle.NO_BORDER; var paragraph = new Paragraph(this.CreatePhrase("Zugangsdaten zum Intranet", this.TitleFont)) { Alignment = Element.ALIGN_CENTER, SpacingBefore = 2, SpacingAfter = 2 }; header.AddCell(paragraph); var cell = header.GetRow(0).GetCells()[0]; cell.BackgroundColor = new BaseColor(191, 191, 191); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 2; cell.PaddingBottom = 5; header.CompleteRow(); pdfdoc.Add(header); pdfdoc.Add(new Paragraph(this.CreatePhrase(person.Briefanrede + ",")) { SpacingBefore = MillimetersToPoints(5) }); pdfdoc.Add(new Paragraph(this.CreatePhrase("die Webadresse der Gemeinde lautet")) { SpacingBefore = MillimetersToPoints(2) }); paragraph = new Paragraph(this.CreatePhrase("www.feg-giessen.de", StandardBoldFont)) { SpacingBefore = MillimetersToPoints(2), Alignment = Element.ALIGN_CENTER }; pdfdoc.Add(paragraph); paragraph = new Paragraph(this.CreatePhrase("Über die öffentlichen Informationen hinaus gibt es auch noch geschützte, interne Bereiche, die weitere nützliche und aktuelle Zusatzinformationen enthalten. Diese sind nur für Gemeindemitglieder gedacht und deshalb nur mit entsprechender Zugangsberechtigung erreichbar, sobald das zugehörige Passwort mitgeteilt wurde. Folgende Schritte sind dann dazu erforderlich:")); paragraph.SpacingBefore = MillimetersToPoints(2); paragraph.Alignment = Element.ALIGN_JUSTIFIED; pdfdoc.Add(paragraph); var table = new PdfPTable(2) { WidthPercentage = 100, HeaderRows = 0, SpacingBefore = MillimetersToPoints(5), SpacingAfter = MillimetersToPoints(5) }; table.DefaultCell.Border = Rectangle.NO_BORDER; table.SetTotalWidth(new[] { 1.2f, 5f }); table.AddCell(this.CreatePhrase("Benutzername", this.StandardBoldFont)); table.AddCell(this.CreatePhrase(person.Username)); table.CompleteRow(); table.AddCell(this.CreatePhrase("Passwort", this.StandardBoldFont)); table.AddCell(this.CreatePhrase("(kommt per E-Mail)")); table.CompleteRow(); pdfdoc.Add(table); pdfdoc.Add(new Paragraph(this.CreatePhrase("1.) Nach einem Klick rechts oben auf \"Login\" erscheint das Anmeldeformular"))); pdfdoc.Add(new Paragraph(this.CreatePhrase("2.) Der o.g. Benutzername kann mit Kleinbuchstaben und Punkt in der Mitte eingegeben werden"))); pdfdoc.Add(new Paragraph(this.CreatePhrase("3.) Das per E-Mail zugeschickte persönliche, geheime Passwort ist einzugeben"))); pdfdoc.Add(new Paragraph(this.CreatePhrase("4.) Klick auf \"Anmelden\" gewährt den Intranetzugang, erkennbar durch den Login-Namen oben rechts"))); pdfdoc.Add(new Paragraph(this.CreatePhrase("Und nun freuen wir uns über viele Besucher - und Rückmeldungen, wenn etwas gefällt, etwas fehlt, etwas falsch ist, oder irgendwas noch nicht ganz klappt :-). Das Online-Internet-Team ist unter internet@feg-giessen.de zu erreichen.")) { SpacingBefore = MillimetersToPoints(2), Alignment = Element.ALIGN_JUSTIFIED }); pdfdoc.Add(new Paragraph(this.CreatePhrase("Freunde, Gäste, Sucher und Besucher können natürlich gerne auf die öffentliche Website hingewiesen werden. Dort sind stets die aktuellen Informationen über unsere Gemeinde zu finden.")) { SpacingBefore = MillimetersToPoints(2), SpacingAfter = MillimetersToPoints(5), Alignment = Element.ALIGN_JUSTIFIED }); pdfdoc.Close(); writer.Flush(); byte[] data = stream.ToArray(); string filename = this.fileManager.GetTempFile(person.Username.Replace(".", "-") + ".pdf"); using (var fs = File.OpenWrite(filename)) { fs.Write(data, 0, (int)data.Length); stream.Dispose(); fs.Flush(); } return filename; } protected Phrase CreatePhrase(string text, Font font) { var p = new Phrase(text, font); foreach (Chunk c in p.Chunks) { c.SetHyphenation(this.Hyphenation); } return p; } protected Phrase CreatePhrase(string text) { return this.CreatePhrase(text, this.StandardFont); } private class CustomDashedLineSeparator : DottedLineSeparator { public float Dash { get; set; } = 5; public float Phase { get; set; } = 2.5f; public override void Draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { canvas.SaveState(); canvas.SetLineWidth(lineWidth); canvas.SetLineDash(Dash, gap, Phase); DrawLine(canvas, llx, urx, y); canvas.RestoreState(); } } } }
42.674419
426
0.628883
[ "MIT" ]
feg-giessen/OptigemLdapSync
OptigemLdapSync/NewUserReport.cs
7,358
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Nz.Models.Common; using KeyPayV2.Nz.Enums; namespace KeyPayV2.Nz.Models.Common { public class AttachmentModel { public int? Id { get; set; } public string FriendlyName { get; set; } public DateTime? DateCreated { get; set; } public string Url { get; set; } public DateTime? DateScanned { get; set; } public bool? IsInfected { get; set; } } }
27.105263
51
0.631068
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Nz/Models/Common/AttachmentModel.cs
515
C#
using System; using MongoDB.Bson.Serialization.Attributes; namespace ETModel { // 登录日志 public class Log_Login : EntityDB { public long Uid { set; get; } public string ip { set; get; } public string clientVersion { set; get; } } }
20.615385
49
0.626866
[ "MIT" ]
zhangfengqwer/NjmjNew
Server/Model/Njmj/Entity/Db/Log_Login.cs
278
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** 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.AzureNextGen.Network.V20200501 { public static class GetFirewallPolicyRuleCollectionGroup { public static Task<GetFirewallPolicyRuleCollectionGroupResult> InvokeAsync(GetFirewallPolicyRuleCollectionGroupArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetFirewallPolicyRuleCollectionGroupResult>("azure-nextgen:network/v20200501:getFirewallPolicyRuleCollectionGroup", args ?? new GetFirewallPolicyRuleCollectionGroupArgs(), options.WithVersion()); } public sealed class GetFirewallPolicyRuleCollectionGroupArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the Firewall Policy. /// </summary> [Input("firewallPolicyName", required: true)] public string FirewallPolicyName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the FirewallPolicyRuleCollectionGroup. /// </summary> [Input("ruleCollectionGroupName", required: true)] public string RuleCollectionGroupName { get; set; } = null!; public GetFirewallPolicyRuleCollectionGroupArgs() { } } [OutputType] public sealed class GetFirewallPolicyRuleCollectionGroupResult { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> public readonly string? Name; /// <summary> /// Priority of the Firewall Policy Rule Collection Group resource. /// </summary> public readonly int? Priority; /// <summary> /// The provisioning state of the firewall policy rule collection group resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Group of Firewall Policy rule collections. /// </summary> public readonly ImmutableArray<Union<Outputs.FirewallPolicyFilterRuleCollectionResponse, Outputs.FirewallPolicyNatRuleCollectionResponse>> RuleCollections; /// <summary> /// Rule Group type. /// </summary> public readonly string Type; [OutputConstructor] private GetFirewallPolicyRuleCollectionGroupResult( string etag, string? name, int? priority, string provisioningState, ImmutableArray<Union<Outputs.FirewallPolicyFilterRuleCollectionResponse, Outputs.FirewallPolicyNatRuleCollectionResponse>> ruleCollections, string type) { Etag = etag; Name = name; Priority = priority; ProvisioningState = provisioningState; RuleCollections = ruleCollections; Type = type; } } }
36.125
249
0.652826
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20200501/GetFirewallPolicyRuleCollectionGroup.cs
3,468
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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 System.Linq; using System.Reflection; using NUnit.Framework; using Remotion.Development.UnitTesting.Enumerables; using Remotion.Development.UnitTesting.Reflection; using Remotion.TypePipe.Development.UnitTesting.Expressions; using Remotion.TypePipe.Development.UnitTesting.ObjectMothers.Expressions; using Remotion.TypePipe.Development.UnitTesting.ObjectMothers.MutableReflection; using Remotion.TypePipe.Dlr.Ast; using Remotion.TypePipe.MutableReflection; using Remotion.TypePipe.MutableReflection.BodyBuilding; using Remotion.TypePipe.MutableReflection.Implementation; using Remotion.TypePipe.MutableReflection.Implementation.MemberFactory; using Remotion.TypePipe.MutableReflection.MemberSignatures; using Remotion.Utilities; using Moq; using Remotion.TypePipe.UnitTests.NUnit; namespace Remotion.TypePipe.UnitTests.MutableReflection.Implementation.MemberFactory { [TestFixture] public class MethodFactoryTest { private Mock<IRelatedMethodFinder> _relatedMethodFinderMock; private MethodFactory _factory; private MutableType _mutableType; [SetUp] public void SetUp () { _relatedMethodFinderMock = new Mock<IRelatedMethodFinder> (MockBehavior.Strict); _factory = new MethodFactory (_relatedMethodFinderMock.Object); _mutableType = MutableTypeObjectMother.Create (baseType: typeof (DomainType)); } [Test] public void CreateMethod () { var name = "Method"; var attributes = MethodAttributes.Public; var baseConstraint = ReflectionObjectMother.GetSomeClassType (); var interfaceConstraint = ReflectionObjectMother.GetSomeInterfaceType (); GenericParameterContext genericParameterContext = null; Type firstGenericParameter = null; Func<GenericParameterContext, IEnumerable<Type>> constraintProvider = ctx => { genericParameterContext = ctx; Assert.That (ctx.GenericParameters, Has.Count.EqualTo (2)); Assert.That (ctx.GenericParameters[1].GenericParameterPosition, Is.EqualTo (1)); firstGenericParameter = ctx.GenericParameters[0]; Assert.That (firstGenericParameter.DeclaringMethod, Is.Null); Assert.That (firstGenericParameter.GenericParameterPosition, Is.EqualTo (0)); Assert.That (firstGenericParameter.Name, Is.EqualTo ("T1")); Assert.That (firstGenericParameter.Namespace, Is.EqualTo (_mutableType.Namespace)); Assert.That (firstGenericParameter.GenericParameterAttributes, Is.EqualTo (GenericParameterAttributes.Covariant)); return new[] { baseConstraint, interfaceConstraint }.AsOneTime(); }; var genericParameters = new[] { GenericParameterDeclarationObjectMother.Create ("T1", GenericParameterAttributes.Covariant, constraintProvider), GenericParameterDeclarationObjectMother.Create() }; var returnType = typeof (IComparable); Func<GenericParameterContext, Type> returnTypeProvider = ctx => { Assert.That (ctx, Is.Not.Null.And.SameAs (genericParameterContext)); return returnType; }; var parameter = ParameterDeclarationObjectMother.Create (name: "paramName"); Func<GenericParameterContext, IEnumerable<ParameterDeclaration>> parameterProvider = ctx => { Assert.That (ctx, Is.Not.Null.And.SameAs (genericParameterContext)); return new[] { parameter }.AsOneTime (); }; var fakeBody = ExpressionTreeObjectMother.GetSomeExpression (typeof (int)); Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => { Assert.That (ctx.This.Type, Is.SameAs (_mutableType)); Assert.That (ctx.Parameters.Single ().Name, Is.EqualTo ("paramName")); Assert.That (ctx.IsStatic, Is.False); Assert.That (ctx.GenericParameters, Is.EqualTo (genericParameterContext.GenericParameters)); Assert.That (ctx.ReturnType, Is.SameAs (returnType)); Assert.That (ctx.HasBaseMethod, Is.False); return fakeBody; }; var method = _factory.CreateMethod ( _mutableType, name, attributes, genericParameters.AsOneTime(), returnTypeProvider, parameterProvider, bodyProvider); Assert.That (method.DeclaringType, Is.SameAs (_mutableType)); Assert.That (method.Name, Is.EqualTo (name)); Assert.That (method.Attributes, Is.EqualTo (attributes)); Assert.That (method.ReturnType, Is.SameAs (returnType)); Assert.That (method.BaseMethod, Is.Null); var returnParameter = method.ReturnParameter; Assertion.IsNotNull (returnParameter); Assert.That (returnParameter.Position, Is.EqualTo (-1)); Assert.That (returnParameter.Name, Is.Null); Assert.That (returnParameter.ParameterType, Is.SameAs (returnType)); Assert.That (returnParameter.Attributes, Is.EqualTo (ParameterAttributes.None)); Assert.That (method.GetGenericArguments (), Has.Length.EqualTo (2)); var actualFirstGenericParameter = method.GetGenericArguments ()[0]; Assert.That (actualFirstGenericParameter, Is.SameAs (firstGenericParameter)); Assert.That (actualFirstGenericParameter.DeclaringMethod, Is.SameAs (method)); Assert.That (actualFirstGenericParameter.GetGenericParameterConstraints (), Is.EqualTo (new[] { baseConstraint, interfaceConstraint })); Assert.That (method.GetParameters ().Single ().Name, Is.EqualTo (parameter.Name)); var expectedBody = Expression.Convert (fakeBody, returnType); ExpressionTreeComparer.CheckAreEqualTrees (expectedBody, method.Body); } [Test] public void CreateMethod_Static () { var name = "StaticMethod"; var attributes = MethodAttributes.Static; var returnType = ReflectionObjectMother.GetSomeType (); var parameterDeclarations = ParameterDeclarationObjectMother.CreateMultiple (2); Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => { Assert.That (ctx.IsStatic, Is.True); return ExpressionTreeObjectMother.GetSomeExpression (returnType); }; var method = CallCreateMethod (_mutableType, name, attributes, returnType, parameterDeclarations, bodyProvider); Assert.That (method.IsStatic, Is.True); } [Test] public void CreateMethod_OnInterface () { var mutableType = MutableTypeObjectMother.CreateInterface(); var name = "name"; var attributes = MethodAttributes.Virtual | MethodAttributes.ReuseSlot; CallCreateMethod (mutableType, name, attributes, typeof (void), ParameterDeclaration.None, ctx => Expression.Empty()); var signature = new MethodSignature (typeof (void), Type.EmptyTypes, 0); _relatedMethodFinderMock.Verify (mock => mock.GetMostDerivedVirtualMethod (name, signature, null), Times.Never()); } [Test] public void CreateMethod_Shadowing_NonVirtual () { var shadowedMethod = _mutableType.GetMethod ("ToString"); Assert.That (shadowedMethod, Is.Not.Null); Assert.That (shadowedMethod.DeclaringType, Is.SameAs (typeof (object))); var nonVirtualAttributes = (MethodAttributes) 0; Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => { Assert.That (ctx.HasBaseMethod, Is.False); return Expression.Constant ("string"); }; var method = CallCreateMethod ( _mutableType, "ToString", nonVirtualAttributes, typeof (string), ParameterDeclaration.None, bodyProvider); Assert.That (method, Is.Not.Null.And.Not.EqualTo (shadowedMethod)); Assert.That (method.BaseMethod, Is.Null); Assert.That (method.GetBaseDefinition (), Is.SameAs (method)); } [Test] public void CreateMethod_Shadowing_VirtualAndNewSlot () { var shadowedMethod = _mutableType.GetMethod ("ToString"); Assert.That (shadowedMethod, Is.Not.Null); Assert.That (shadowedMethod.DeclaringType, Is.SameAs (typeof (object))); var nonVirtualAttributes = MethodAttributes.Virtual | MethodAttributes.NewSlot; Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => { Assert.That (ctx.HasBaseMethod, Is.False); return Expression.Constant ("string"); }; var method = CallCreateMethod ( _mutableType, "ToString", nonVirtualAttributes, typeof (string), ParameterDeclaration.None, bodyProvider); Assert.That (method, Is.Not.Null.And.Not.EqualTo (shadowedMethod)); Assert.That (method.BaseMethod, Is.Null); Assert.That (method.GetBaseDefinition (), Is.SameAs (method)); } [Test] public void CreateMethod_ImplicitOverride () { var fakeOverridenMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod ((B obj) => obj.OverrideHierarchy (7)); _relatedMethodFinderMock .Setup (mock => mock.GetMostDerivedVirtualMethod ("Method", new MethodSignature (typeof (int), Type.EmptyTypes, 0), _mutableType.BaseType)) .Returns (fakeOverridenMethod) .Verifiable(); Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => { Assert.That (ctx.HasBaseMethod, Is.True); Assert.That (ctx.BaseMethod, Is.SameAs (fakeOverridenMethod)); return Expression.Default (typeof (int)); }; var method = CallCreateMethod ( _mutableType, "Method", MethodAttributes.Public | MethodAttributes.Virtual, typeof (int), ParameterDeclaration.None, bodyProvider); _relatedMethodFinderMock.Verify(); Assert.That (method.BaseMethod, Is.EqualTo (fakeOverridenMethod)); Assert.That (method.GetBaseDefinition (), Is.EqualTo (fakeOverridenMethod.GetBaseDefinition ())); } [Test] public void CreateMethod_ImplicitOverride_FinalBaseMethod () { var signature = new MethodSignature (typeof (void), Type.EmptyTypes, 0); var fakeBaseMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod ((B obj) => obj.FinalBaseMethodInB (7)); _relatedMethodFinderMock .Setup (mock => mock.GetMostDerivedVirtualMethod ("MethodName", signature, _mutableType.BaseType)) .Returns (fakeBaseMethod) .Verifiable(); Assert.That ( () => CallCreateMethod ( _mutableType, "MethodName", MethodAttributes.Public | MethodAttributes.Virtual, typeof (void), ParameterDeclaration.None, ctx => Expression.Empty()), Throws.InstanceOf<NotSupportedException>() .With.Message.EqualTo ( "Cannot override final method 'B.FinalBaseMethodInB'.")); } [Test] public void CreateMethod_ImplicitOverride_InaccessibleBaseMethod () { var signature = new MethodSignature (typeof (void), Type.EmptyTypes, 0); var fakeBaseMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod ((B obj) => obj.InaccessibleBaseMethodInB (7)); _relatedMethodFinderMock .Setup (mock => mock.GetMostDerivedVirtualMethod ("MethodName", signature, _mutableType.BaseType)) .Returns (fakeBaseMethod) .Verifiable(); Assert.That ( () => CallCreateMethod ( _mutableType, "MethodName", MethodAttributes.Public | MethodAttributes.Virtual, typeof (void), ParameterDeclaration.None, ctx => Expression.Empty()), Throws.InstanceOf<NotSupportedException>() .With.Message.EqualTo ("Cannot override method 'B.InaccessibleBaseMethodInB' as it is not visible from the proxy.")); } [Test] public void CreateMethod_ThrowsIfNotAbstractAndNullBodyProvider () { Assert.That ( () => CallCreateMethod (_mutableType, "NotImportant", 0, typeof (void), ParameterDeclaration.None, null), Throws.ArgumentNullException .With.ArgumentExceptionMessageEqualTo ( "Non-abstract methods must have a body.", "bodyProvider")); } [Test] public void CreateMethod_ThrowsIfAbstractAndBodyProvider () { Assert.That ( () => CallCreateMethod (_mutableType, "NotImportant", MethodAttributes.Abstract, typeof (void), ParameterDeclaration.None, ctx => null), Throws.ArgumentException .With.ArgumentExceptionMessageEqualTo ( "Abstract methods cannot have a body.", "bodyProvider")); } [Test] public void CreateMethod_ThrowsForInvalidMethodAttributes () { var message = "The following MethodAttributes are not supported for methods: RequireSecObject."; var paramName = "attributes"; Assert.That (() => CreateMethod (_mutableType, MethodAttributes.RequireSecObject), Throws.ArgumentException.With.ArgumentExceptionMessageEqualTo (message, paramName)); } [Test] public void CreateMethod_ThrowsIfAbstractAndNotVirtual () { Assert.That ( () => CallCreateMethod (_mutableType, "NotImportant", MethodAttributes.Abstract, typeof (void), ParameterDeclaration.None, null), Throws.ArgumentException .With.ArgumentExceptionMessageEqualTo ( "Abstract methods must also be virtual.", "attributes")); } [Test] public void CreateMethod_ThrowsIfNonVirtualAndNewSlot () { Assert.That ( () => CallCreateMethod (_mutableType, "NotImportant", MethodAttributes.NewSlot, typeof (void), ParameterDeclaration.None, ctx => Expression.Empty ()), Throws.ArgumentException .With.ArgumentExceptionMessageEqualTo ( "NewSlot methods must also be virtual.", "attributes")); } [Test] public void CreateMethod_ThrowsForNullReturningReturnTypeProvider () { Assert.That ( () => _factory.CreateMethod ( _mutableType, "NotImportant", 0, GenericParameterDeclaration.None, ctx => null, ctx => ParameterDeclaration.None, ctx => Expression.Empty ()), Throws.ArgumentException .With.ArgumentExceptionMessageEqualTo ( "Provider must not return null.", "returnTypeProvider")); } [Test] public void CreateMethod_ThrowsForNullReturningParameterProvider () { Assert.That ( () => _factory.CreateMethod ( _mutableType, "NotImportant", 0, GenericParameterDeclaration.None, ctx => typeof (int), ctx => null, ctx => Expression.Empty ()), Throws.ArgumentException .With.ArgumentExceptionMessageEqualTo ( "Provider must not return null.", "parameterProvider")); } [Test] public void CreateMethod_ThrowsIfAlreadyExists () { Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => Expression.Empty (); var method = _mutableType.AddMethod ("Method", 0, typeof (void), ParameterDeclarationObjectMother.CreateMultiple (2), bodyProvider); var methodParameters = method.GetParameters().Select (p => new ParameterDeclaration (p.ParameterType, p.Name, p.Attributes)); Assert.That (() => CallCreateMethod (_mutableType, "OtherName", 0, method.ReturnType, methodParameters, bodyProvider), Throws.Nothing); Assert.That ( () => CallCreateMethod (_mutableType, method.Name, 0, typeof (int), methodParameters, ctx => Expression.Constant (7)), Throws.Nothing); Assert.That ( () => CallCreateMethod (_mutableType, method.Name, 0, method.ReturnType, ParameterDeclarationObjectMother.CreateMultiple (3), bodyProvider), Throws.Nothing); Assert.That ( () => CallCreateMethod (_mutableType, method.Name, 0, method.ReturnType, methodParameters, bodyProvider), Throws.InvalidOperationException.With.Message.EqualTo ("Method with equal name and signature already exists.")); } [Test] public void CreateMethod_ThrowsIfAlreadyExists_Generic () { var genericParameters = new[] { new GenericParameterDeclaration ("T1"), new GenericParameterDeclaration ("T2") }; Func<GenericParameterContext, Type> returnTypeProvider = ctx => typeof (void); Func<GenericParameterContext, IEnumerable<ParameterDeclaration>> parameterProvider = ctx => new[] { new ParameterDeclaration (ctx.GenericParameters[0], "t1"), new ParameterDeclaration (ctx.GenericParameters[1], "t2") }; Func<MethodBodyCreationContext, Expression> bodyProvider = ctx => Expression.Empty (); var method = _mutableType.AddMethod ("GenericMethod", 0, genericParameters, returnTypeProvider, parameterProvider, bodyProvider); Func<GenericParameterContext, IEnumerable<ParameterDeclaration>> parameterProvider1 = ctx => new[] { new ParameterDeclaration (ctx.GenericParameters[0], "t1") }; Assert.That ( () => _factory.CreateMethod (_mutableType, method.Name, 0, new[] { genericParameters[0] }, returnTypeProvider, parameterProvider1, bodyProvider), Throws.Nothing); Func<GenericParameterContext, IEnumerable<ParameterDeclaration>> parameterProvider2 = ctx => new[] { new ParameterDeclaration (ctx.GenericParameters[1], "t1"), new ParameterDeclaration (ctx.GenericParameters[0], "t2") }; Assert.That ( () => _factory.CreateMethod (_mutableType, method.Name, 0, genericParameters, returnTypeProvider, parameterProvider2, bodyProvider), Throws.Nothing); Assert.That ( () => _factory.CreateMethod (_mutableType, method.Name, 0, genericParameters, returnTypeProvider, parameterProvider, bodyProvider), Throws.InvalidOperationException.With.Message.EqualTo ("Method with equal name and signature already exists.")); } private MutableMethodInfo CreateMethod (MutableType mutableType, MethodAttributes attributes) { return CallCreateMethod ( mutableType, "dummy", attributes, typeof (void), ParameterDeclaration.None, ctx => Expression.Empty ()); } private MutableMethodInfo CallCreateMethod ( MutableType declaringType, string name, MethodAttributes attributes, Type returnType, IEnumerable<ParameterDeclaration> parameters, Func<MethodBodyCreationContext, Expression> bodyProvider) { return _factory.CreateMethod ( declaringType, name, attributes, GenericParameterDeclaration.None, ctx => returnType, ctx => parameters, bodyProvider); } public class A { // base definition public virtual void OverrideHierarchy (int aaa) { } public virtual void FinalBaseMethodInB (int i) { } } public class B : A { // CreateMethodOverride input public override void OverrideHierarchy (int bbb) { } protected internal virtual void ProtectedOrInternalVirtualNewSlotMethodInB (int protectedOrInternal) { } public override sealed void FinalBaseMethodInB (int i) { } internal virtual void InaccessibleBaseMethodInB (int i) { } } public class C : B { // base inputMethod public override void OverrideHierarchy (int ccc) { } } public class DomainType : C, IDomainInterface { public virtual void InterfaceMethod (int interfaceMethodOnDomainType) { } public void NonVirtualBaseMethod () { } } public interface IDomainInterface { void InterfaceMethod (int i); } public interface IAddedInterface { void AddedInterfaceMethod (int addedInterface); void InvalidCandidate (); } public abstract class AbstractTypeWithOneMethod { public abstract void Method (); } public abstract class DerivedAbstractTypeLeavesAbstractBaseMethod : AbstractTypeWithOneMethod { } } }
42.670103
173
0.691568
[ "ECL-2.0", "Apache-2.0" ]
bubdm/TypePipe
Core.UnitTests/MutableReflection/Implementation/MemberFactory/MethodFactoryTest.cs
20,695
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SceneNormalControl : BaseSceneControl { private int houseCount; private int monsterCount; public override void onAwake() { base.onAwake(); MessageCenter.Instance.addListener(MsgCmd.Die_Main_Player, onMainPlayerDie); MessageCenter.Instance.addListener(MsgCmd.Die_Crystal_Entity, onCrystalDie); MessageCenter.Instance.addListener(MsgCmd.Die_Monster_Entity, onMonsterDie); } private void OnDestroy() { MessageCenter.Instance.removeListener(MsgCmd.Die_Main_Player, onMainPlayerDie); MessageCenter.Instance.removeListener(MsgCmd.Die_Crystal_Entity, onCrystalDie); MessageCenter.Instance.removeListener(MsgCmd.Die_Monster_Entity, onMonsterDie); } public override void onStart() { if (this.info != null) { DDOLObj.Instance.StartCoroutine(createEntityHouse(info.HouseTime)); //DDOLObj.Instance.StartCoroutine(createEntityMonster(info.AISpawnTimer)); TimeMgr.Instance.setTimerHandler(new TimerHandler(info.AIWave * info.AISpawnTimer + 1, true, info.AISpawnTimer, createMonster, false)); } } //创建怪 protected void createMonster() { for (int i = 0; i < info.LstAI.Count; i++) { EntityMgr.Instance.createEntity(info.LstAI[i], uid); uid++; } } public override void onSetData() { this.houseCount = 1;/*this.info.HouseId.Count;*/ this.monsterCount = this.info.LstAI.Count * this.info.AIWave; } //玩家死亡 private void onMainPlayerDie(Message msg) { //死亡游戏结束 败 //弹出死亡界面 倒计时切换到 列表场景 StartCoroutine(gameOverByFail(8f, "你已经死亡...准备重新开始游戏")); } //水晶都死亡 private void onCrystalDie(Message msg) { //水晶全部死亡 游戏结束 败 this.houseCount--; if (this.houseCount <= 0) StartCoroutine(gameOverByFail(8f, "水晶全部死亡...准备重新开始游戏")); } //怪物都死亡 private void onMonsterDie(Message msg) { //怪物全部死亡 游戏结束 胜 this.monsterCount--; if (this.monsterCount <= 0) StartCoroutine(gameOverBySuccess(8f, "游戏胜利...准备开始下一关卡")); } private IEnumerator gameOverByFail(float time, string str) { TimeMgr.Instance.removeALLTimerHanlder(); UIMgr.Instance.setCountDown(8, str); EntityMgr.Instance.removeAllEntity(); yield return new WaitForSeconds(time); SceneMgr.Instance.onLoadScene("GameStart", null, (progress) => { DDOLCanvas.Instance.setFill(progress); }, true); SoundMgr.Instance.playAudioBg("enterbgMusic"); } private IEnumerator gameOverBySuccess(float time, string str) { TimeMgr.Instance.removeALLTimerHanlder(); UIMgr.Instance.setCountDown(8, str); EntityMgr.Instance.removeAllEntity(); yield return new WaitForSeconds(time); int index = info.LevelIndex + 1; SceneMgr.Instance.onLoadScene("CrossFire" + index, null, (progress) => { DDOLCanvas.Instance.setFill(progress); }, true); SoundMgr.Instance.playAudioBg("bgMusic"); } }
31.480769
147
0.644166
[ "Apache-2.0" ]
Tritend/ZombieWar
Assets/Scripts/Scene/SceneControl/Scenes/SceneNormalControl.cs
3,478
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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IGroupRejectedSendersCollectionRequest. /// </summary> public partial interface IGroupRejectedSendersCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified DirectoryObject to the collection via POST. /// </summary> /// <param name="directoryObject">The DirectoryObject to add.</param> /// <returns>The created DirectoryObject.</returns> System.Threading.Tasks.Task<DirectoryObject> AddAsync(DirectoryObject directoryObject); /// <summary> /// Adds the specified DirectoryObject to the collection via POST. /// </summary> /// <param name="directoryObject">The DirectoryObject to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DirectoryObject.</returns> System.Threading.Tasks.Task<DirectoryObject> AddAsync(DirectoryObject directoryObject, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IGroupRejectedSendersCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IGroupRejectedSendersCollectionPage> GetAsync(CancellationToken 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> IGroupRejectedSendersCollectionRequest Expand(string value); /// <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> IGroupRejectedSendersCollectionRequest Expand(Expression<Func<DirectoryObject, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IGroupRejectedSendersCollectionRequest Select(string value); /// <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> IGroupRejectedSendersCollectionRequest Select(Expression<Func<DirectoryObject, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IGroupRejectedSendersCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IGroupRejectedSendersCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IGroupRejectedSendersCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IGroupRejectedSendersCollectionRequest OrderBy(string value); } }
44.584906
153
0.625476
[ "MIT" ]
twsouthwick/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IGroupRejectedSendersCollectionRequest.cs
4,726
C#
using System; using System.Windows.Media; namespace Smellyriver.TankInspector.Pro.Modularity.Input { public abstract class CommandBase<TCommand, TArgument> where TCommand : ICommand { private static readonly Func<TArgument, bool> s_alwaysExecutable = o => true; private readonly Guid _guid; public Guid Guid { get { return _guid; } } private readonly string _name; public string Name { get { return _name; } } private readonly string _description; public string Description { get { return _description; } } private readonly int _priority; public int Priority { get { return _priority; } } private readonly ImageSource _icon; public ImageSource Icon { get { return _icon; } } private Func<TArgument, bool> _canExecute; public bool CanExecute(object parameter) { return _canExecute((TArgument)parameter); } public event EventHandler CanExecuteChanged; private Action<TArgument> _execute; public void Execute(object parameter) { _execute((TArgument)parameter); } public CommandBase(Guid guid, string name, Action<TArgument> execute, Func<TArgument, bool> canExecute = null, string description = null, ImageSource icon = null, int priority = 0) { _guid = guid; _name = name; _execute = execute; _canExecute = canExecute ?? s_alwaysExecutable; _description = description; _icon = icon; _priority = priority; } public CommandBase(Guid guid, string name, ICommand command, string description = null, ImageSource icon = null, int priority = 0) : this(guid, name, k => command.Execute(k), k => command.CanExecute(k), description, icon, priority) { command.CanExecuteChanged += command_CanExecuteChanged; } void command_CanExecuteChanged(object sender, EventArgs e) { if (this.CanExecuteChanged != null) this.CanExecuteChanged(this, e); } } }
27.938144
85
0.496679
[ "MIT" ]
smellyriver/tank-inspector-pro
src/Smellyriver.TankInspector.Pro/Modularity/Input/CommandBase.cs
2,712
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Roslynator { internal static class EnumValueComparer { public static IComparer<object> GetInstance(SpecialType enumSpecialType) { switch (enumSpecialType) { case SpecialType.System_SByte: return SByteValueComparer.Instance; case SpecialType.System_Byte: return ByteValueComparer.Instance; case SpecialType.System_Int16: return ShortValueComparer.Instance; case SpecialType.System_UInt16: return UShortValueComparer.Instance; case SpecialType.System_Int32: return IntValueComparer.Instance; case SpecialType.System_UInt32: return UIntValueComparer.Instance; case SpecialType.System_Int64: return LongValueComparer.Instance; case SpecialType.System_UInt64: return ULongValueComparer.Instance; default: throw new ArgumentException("", nameof(enumSpecialType)); } } private class SByteValueComparer : IComparer<object> { private SByteValueComparer() { } public static readonly SByteValueComparer Instance = new SByteValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is sbyte xvalue && y is sbyte yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class ByteValueComparer : IComparer<object> { private ByteValueComparer() { } public static readonly ByteValueComparer Instance = new ByteValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is byte xvalue && y is byte yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class ShortValueComparer : IComparer<object> { private ShortValueComparer() { } public static readonly ShortValueComparer Instance = new ShortValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is short xvalue && y is short yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class UShortValueComparer : IComparer<object> { private UShortValueComparer() { } public static readonly UShortValueComparer Instance = new UShortValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is ushort xvalue && y is ushort yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class IntValueComparer : IComparer<object> { private IntValueComparer() { } public static readonly IntValueComparer Instance = new IntValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is int xvalue && y is int yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class UIntValueComparer : IComparer<object> { private UIntValueComparer() { } public static readonly UIntValueComparer Instance = new UIntValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is uint xvalue && y is uint yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class LongValueComparer : IComparer<object> { private LongValueComparer() { } public static readonly LongValueComparer Instance = new LongValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is long xvalue && y is long yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } private class ULongValueComparer : IComparer<object> { private ULongValueComparer() { } public static readonly ULongValueComparer Instance = new ULongValueComparer(); public int Compare(object x, object y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (x is ulong xvalue && y is ulong yvalue) { return xvalue.CompareTo(yvalue); } return 0; } } } }
26.724907
160
0.439282
[ "Apache-2.0" ]
JosefPihrt/Roslynator
src/Core/EnumValueComparer.cs
7,191
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore.TestModels.InheritanceRelationshipsModel; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; namespace Microsoft.EntityFrameworkCore.Query { public abstract class InheritanceRelationshipsQueryFixtureBase : SharedStoreFixtureBase<InheritanceRelationshipsContext>, IQueryFixtureBase { protected override string StoreName { get; } = "InheritanceRelationships"; public Func<DbContext> GetContextCreator() => () => CreateContext(); public ISetSource GetExpectedData() => new InheritanceRelationshipsData(); public IReadOnlyDictionary<Type, object> GetEntitySorters() => new Dictionary<Type, Func<object, object>> { { typeof(BaseCollectionOnBase), e => ((BaseCollectionOnBase)e)?.Id }, { typeof(DerivedCollectionOnBase), e => ((DerivedCollectionOnBase)e)?.Id }, { typeof(BaseCollectionOnDerived), e => ((BaseCollectionOnDerived)e)?.Id }, { typeof(DerivedCollectionOnDerived), e => ((DerivedCollectionOnDerived)e)?.Id }, { typeof(BaseInheritanceRelationshipEntity), e => ((BaseInheritanceRelationshipEntity)e)?.Id }, { typeof(DerivedInheritanceRelationshipEntity), e => ((DerivedInheritanceRelationshipEntity)e)?.Id }, { typeof(BaseReferenceOnBase), e => ((BaseReferenceOnBase)e)?.Id }, { typeof(DerivedReferenceOnBase), e => ((DerivedReferenceOnBase)e)?.Id }, { typeof(BaseReferenceOnDerived), e => ((BaseReferenceOnDerived)e)?.Id }, { typeof(DerivedReferenceOnDerived), e => ((DerivedReferenceOnDerived)e)?.Id }, { typeof(CollectionOnBase), e => ((CollectionOnBase)e)?.Id }, { typeof(CollectionOnDerived), e => ((CollectionOnDerived)e)?.Id }, { typeof(NestedCollectionBase), e => ((NestedCollectionBase)e)?.Id }, { typeof(NestedCollectionDerived), e => ((NestedCollectionDerived)e)?.Id }, { typeof(NestedReferenceBase), e => ((NestedReferenceBase)e)?.Id }, { typeof(NonEntityBase), e => ((NonEntityBase)e)?.Id }, { typeof(PrincipalEntity), e => ((PrincipalEntity)e)?.Id }, { typeof(OwnedEntity), e => ((OwnedEntity)e)?.Id }, { typeof(ReferencedEntity), e => ((ReferencedEntity)e)?.Id }, { typeof(ReferenceOnBase), e => ((ReferenceOnBase)e)?.Id }, { typeof(ReferenceOnDerived), e => ((ReferenceOnDerived)e)?.Id }, }.ToDictionary(e => e.Key, e => (object)e.Value); public IReadOnlyDictionary<Type, object> GetEntityAsserters() => new Dictionary<Type, Action<object, object>> { { typeof(BaseCollectionOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (BaseCollectionOnBase)e; var aa = (BaseCollectionOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); } } }, { typeof(DerivedCollectionOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (DerivedCollectionOnBase)e; var aa = (DerivedCollectionOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); Assert.Equal(ee.DerivedProperty, aa.DerivedProperty); } } }, { typeof(BaseCollectionOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (BaseCollectionOnDerived)e; var aa = (BaseCollectionOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, { typeof(DerivedCollectionOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (DerivedCollectionOnDerived)e; var aa = (DerivedCollectionOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, { typeof(BaseInheritanceRelationshipEntity), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (BaseInheritanceRelationshipEntity)e; var aa = (BaseInheritanceRelationshipEntity)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.OwnedReferenceOnBase?.Id, aa.OwnedReferenceOnBase?.Id); Assert.Equal(ee.OwnedReferenceOnBase?.Name, aa.OwnedReferenceOnBase?.Name); Assert.Equal(ee.OwnedCollectionOnBase?.Count, aa.OwnedCollectionOnBase?.Count); if (ee.OwnedCollectionOnBase?.Count > 0) { for (var i = 0; i < ee.OwnedCollectionOnBase.Count; i++) { Assert.Equal(ee.OwnedCollectionOnBase[i].Id, aa.OwnedCollectionOnBase[i].Id); Assert.Equal(ee.OwnedCollectionOnBase[i].Name, aa.OwnedCollectionOnBase[i].Name); } } } } }, { typeof(DerivedInheritanceRelationshipEntity), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (DerivedInheritanceRelationshipEntity)e; var aa = (DerivedInheritanceRelationshipEntity)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseId, aa.BaseId); Assert.Equal(ee.OwnedReferenceOnBase?.Id, aa.OwnedReferenceOnBase?.Id); Assert.Equal(ee.OwnedReferenceOnBase?.Name, aa.OwnedReferenceOnBase?.Name); Assert.Equal(ee.OwnedReferenceOnDerived?.Id, aa.OwnedReferenceOnDerived?.Id); Assert.Equal(ee.OwnedReferenceOnDerived?.Name, aa.OwnedReferenceOnDerived?.Name); Assert.Equal(ee.OwnedCollectionOnBase?.Count, aa.OwnedCollectionOnBase?.Count); if (ee.OwnedCollectionOnBase?.Count > 0) { for (var i = 0; i < ee.OwnedCollectionOnBase.Count; i++) { Assert.Equal(ee.OwnedCollectionOnBase[i].Id, aa.OwnedCollectionOnBase[i].Id); Assert.Equal(ee.OwnedCollectionOnBase[i].Name, aa.OwnedCollectionOnBase[i].Name); } } Assert.Equal(ee.OwnedCollectionOnDerived?.Count, aa.OwnedCollectionOnDerived?.Count); if (ee.OwnedCollectionOnDerived?.Count > 0) { for (var i = 0; i < ee.OwnedCollectionOnDerived.Count; i++) { Assert.Equal(ee.OwnedCollectionOnDerived[i].Id, aa.OwnedCollectionOnDerived[i].Id); Assert.Equal(ee.OwnedCollectionOnDerived[i].Name, aa.OwnedCollectionOnDerived[i].Name); } } } } }, { typeof(BaseReferenceOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (BaseReferenceOnBase)e; var aa = (BaseReferenceOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); } } }, { typeof(DerivedReferenceOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (DerivedReferenceOnBase)e; var aa = (DerivedReferenceOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); } } }, { typeof(BaseReferenceOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (BaseReferenceOnDerived)e; var aa = (BaseReferenceOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); } } }, { typeof(DerivedReferenceOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (DerivedReferenceOnDerived)e; var aa = (DerivedReferenceOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.BaseParentId, aa.BaseParentId); } } }, { typeof(CollectionOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (CollectionOnBase)e; var aa = (CollectionOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, { typeof(CollectionOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (CollectionOnDerived)e; var aa = (CollectionOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, { typeof(NestedCollectionBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (NestedCollectionBase)e; var aa = (NestedCollectionBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentReferenceId, aa.ParentReferenceId); Assert.Equal(ee.ParentCollectionId, aa.ParentCollectionId); } } }, { typeof(NestedCollectionDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (NestedCollectionDerived)e; var aa = (NestedCollectionDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentReferenceId, aa.ParentReferenceId); Assert.Equal(ee.ParentCollectionId, aa.ParentCollectionId); } } }, { typeof(NestedReferenceBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (NestedReferenceBase)e; var aa = (NestedReferenceBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentReferenceId, aa.ParentReferenceId); Assert.Equal(ee.ParentCollectionId, aa.ParentCollectionId); } } }, { typeof(NonEntityBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (NonEntityBase)e; var aa = (NonEntityBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); } } }, { typeof(PrincipalEntity), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (PrincipalEntity)e; var aa = (PrincipalEntity)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); } } }, { typeof(ReferencedEntity), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (ReferencedEntity)e; var aa = (ReferencedEntity)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); } } }, { typeof(ReferenceOnBase), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (ReferenceOnBase)e; var aa = (ReferenceOnBase)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, { typeof(ReferenceOnDerived), (e, a) => { Assert.Equal(e == null, a == null); if (a != null) { var ee = (ReferenceOnDerived)e; var aa = (ReferenceOnDerived)a; Assert.Equal(ee.Id, aa.Id); Assert.Equal(ee.Name, aa.Name); Assert.Equal(ee.ParentId, aa.ParentId); } } }, //{ typeof(OwnedEntity), e => ((OwnedEntity)e)?.Id }, }.ToDictionary(e => e.Key, e => (object)e.Value); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { modelBuilder.Owned<OwnedEntity>(); modelBuilder.Entity<NestedReferenceDerived>(); modelBuilder.Entity<NestedCollectionDerived>(); modelBuilder.Entity<DerivedReferenceOnBase>(); modelBuilder.Entity<DerivedCollectionOnBase>(); modelBuilder.Entity<DerivedReferenceOnDerived>(); modelBuilder.Entity<DerivedCollectionOnDerived>(); modelBuilder.Entity<BaseCollectionOnBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseCollectionOnDerived>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseInheritanceRelationshipEntity>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseReferenceOnBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseReferenceOnDerived>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<CollectionOnBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<CollectionOnDerived>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<NestedCollectionBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<NestedReferenceBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<PrincipalEntity>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<ReferencedEntity>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<ReferenceOnBase>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<ReferenceOnDerived>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .HasOne(e => e.DerivedSefReferenceOnBase) .WithOne(e => e.BaseSelfReferenceOnDerived) .HasForeignKey<DerivedInheritanceRelationshipEntity>(e => e.BaseId) .IsRequired(false); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .HasOne(e => e.BaseReferenceOnBase) .WithOne(e => e.BaseParent) .HasForeignKey<BaseReferenceOnBase>(e => e.BaseParentId) .IsRequired(false); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .HasOne(e => e.ReferenceOnBase) .WithOne(e => e.Parent) .HasForeignKey<ReferenceOnBase>(e => e.ParentId) .IsRequired(false); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .HasMany(e => e.BaseCollectionOnBase) .WithOne(e => e.BaseParent) .HasForeignKey(e => e.BaseParentId) .IsRequired(false); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .HasMany(e => e.CollectionOnBase) .WithOne(e => e.Parent) .HasForeignKey(e => e.ParentId) .IsRequired(false); modelBuilder.Entity<BaseInheritanceRelationshipEntity>() .OwnsMany(e => e.OwnedCollectionOnBase) .Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasOne(e => e.DerivedReferenceOnDerived) .WithOne() .HasForeignKey<DerivedReferenceOnDerived>("DerivedInheritanceRelationshipEntityId") .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasOne(e => e.ReferenceOnDerived) .WithOne(e => e.Parent) .HasForeignKey<ReferenceOnDerived>(e => e.ParentId) .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasMany(e => e.BaseCollectionOnDerived) .WithOne(e => e.BaseParent) .HasForeignKey(e => e.ParentId) .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasMany(e => e.CollectionOnDerived) .WithOne(e => e.Parent) .HasForeignKey(e => e.ParentId) .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasMany(e => e.DerivedCollectionOnDerived) .WithOne() .HasForeignKey("DerivedInheritanceRelationshipEntityId") .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .HasOne(e => e.BaseReferenceOnDerived) .WithOne(e => e.BaseParent) .HasForeignKey<BaseReferenceOnDerived>(e => e.BaseParentId) .IsRequired(false); modelBuilder.Entity<DerivedInheritanceRelationshipEntity>() .OwnsMany(e => e.OwnedCollectionOnDerived) .Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BaseReferenceOnBase>() .HasOne(e => e.NestedReference) .WithOne(e => e.ParentReference) .HasForeignKey<NestedReferenceBase>(e => e.ParentReferenceId) .IsRequired(false); modelBuilder.Entity<BaseReferenceOnBase>() .HasMany(e => e.NestedCollection) .WithOne(e => e.ParentReference) .HasForeignKey(e => e.ParentReferenceId) .IsRequired(false); modelBuilder.Entity<BaseCollectionOnBase>() .HasOne(e => e.NestedReference) .WithOne(e => e.ParentCollection) .HasForeignKey<NestedReferenceBase>(e => e.ParentCollectionId) .IsRequired(false); modelBuilder.Entity<BaseCollectionOnBase>() .HasMany(e => e.NestedCollection) .WithOne(e => e.ParentCollection) .HasForeignKey(e => e.ParentCollectionId) .IsRequired(false); modelBuilder.Entity<PrincipalEntity>() .HasOne(e => e.Reference) .WithMany() .IsRequired(false); modelBuilder.Entity<ReferencedEntity>() .HasMany(e => e.Principals) .WithOne() .IsRequired(false); } protected override void Seed(InheritanceRelationshipsContext context) => InheritanceRelationshipsContext.Seed(context); public override InheritanceRelationshipsContext CreateContext() { var context = base.CreateContext(); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; return context; } } }
44.457143
125
0.451117
[ "Apache-2.0" ]
0b01/efcore
test/EFCore.Specification.Tests/Query/InheritanceRelationshipsQueryFixtureBase.cs
24,896
C#
using System; using System.Diagnostics.CodeAnalysis; namespace Spv.Generator { internal class DeterministicStringKey : IEquatable<DeterministicStringKey> { private string _value; public DeterministicStringKey(string value) { _value = value; } public override int GetHashCode() { return DeterministicHashCode.GetHashCode(_value); } public bool Equals(DeterministicStringKey other) { return _value == other._value; } public override bool Equals([NotNullWhen(true)] object obj) { return obj is DeterministicStringKey && Equals((DeterministicStringKey)obj); } } }
23.548387
88
0.619178
[ "MIT" ]
Cellinnek/Ryujinx
Spv.Generator/DeterministicStringKey.cs
732
C#
using System; namespace Rollvolet.CRM.APIContracts.DTO.PlanningEvents { public class PlanningEventAttributesDto { public DateTime? Date { get; set; } public string MsObjectId { get; set; } public string Subject { get; set; } public string Period { get; set; } public string FromHour { get; set; } public string UntilHour { get; set; } public bool IsNotAvailableInCalendar { get; set; } } }
30.533333
58
0.637555
[ "MIT" ]
rollvolet/crm-ap
src/Rollvolet.CRM.APIContracts/DTO/PlanningEvents/PlanningEventAttributesDto.cs
458
C#
using System.Collections.Generic; using System.Security.Claims; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Pims.Dal.Entities; using Pims.Dal.Entities.Models; using Pims.Dal.Helpers.Extensions; using Pims.Dal.Repositories; using Pims.Dal.Security; namespace Pims.Dal.Services { public class ResearchFileService : IResearchFileService { private readonly ClaimsPrincipal _user; private readonly ILogger _logger; private readonly IResearchFileRepository _researchFileRepository; private readonly IPropertyRepository _propertyRepository; public ResearchFileService(ClaimsPrincipal user, ILogger<ResearchFileService> logger, IResearchFileRepository researchFileRepository, IPropertyRepository propertyRepository) { _user = user; _logger = logger; _researchFileRepository = researchFileRepository; _propertyRepository = propertyRepository; } public PimsResearchFile GetById(long id) { _logger.LogInformation("Getting research file with id {id}", id); _user.ThrowIfNotAuthorized(Permissions.ResearchFileView); return _researchFileRepository.GetById(id); } public PimsResearchFile Add(PimsResearchFile researchFile) { _logger.LogInformation("Adding research file..."); _user.ThrowIfNotAuthorized(Permissions.ResearchFileAdd); researchFile.ResearchFileStatusTypeCode = "ACTIVE"; foreach (var researchProperty in researchFile.PimsPropertyResearchFiles) { if (researchProperty.Property.Pid.HasValue) { var pid = researchProperty.Property.Pid.Value; try { var foundProperty = _propertyRepository.GetByPid(pid); researchProperty.Property = foundProperty; } catch (KeyNotFoundException e) { _logger.LogDebug("Adding new property with pid:{prop}", pid); PopulateResearchFile(researchProperty.Property); } } else { _logger.LogDebug("Adding new property without a pid"); PopulateResearchFile(researchProperty.Property); } } var newResearchFile = _researchFileRepository.Add(researchFile); _researchFileRepository.CommitTransaction(); return newResearchFile; } public PimsResearchFile Update(PimsResearchFile researchFile) { _logger.LogInformation("Updating research file..."); _user.ThrowIfNotAuthorized(Permissions.ResearchFileEdit); var newResearchFile = _researchFileRepository.Update(researchFile); _researchFileRepository.CommitTransaction(); return newResearchFile; } public Paged<PimsResearchFile> GetPage(ResearchFilter filter) { _logger.LogInformation("Searching for research files..."); _logger.LogDebug("Research file search with filter", filter); _user.ThrowIfNotAuthorized(Permissions.ResearchFileView); return _researchFileRepository.GetPage(filter); } public PimsResearchFile UpdateProperty(long researchFileId, long researchFilePropertyId, long researchFileVersion, PimsPropertyResearchFile propertyResearchFile) { _logger.LogInformation("Updating property research file..."); _user.ThrowIfNotAuthorized(Permissions.ResearchFileEdit); ValidateVersion(researchFileId, researchFileVersion); return _researchFileRepository.UpdateProperty(researchFileId, propertyResearchFile); } private void PopulateResearchFile(PimsProperty property) { property.PropertyClassificationTypeCode = "UNKNOWN"; property.PropertyDataSourceEffectiveDate = System.DateTime.Now; property.PropertyDataSourceTypeCode = "PMBC"; property.PropertyTypeCode = "UNKNOWN"; property.PropertyStatusTypeCode = "UNKNOWN"; property.SurplusDeclarationTypeCode = "UNKNOWN"; } private void ValidateVersion(long researchFileId, long researchFileVersion) { long currentRowVersion = _researchFileRepository.GetRowVersion(researchFileId); if (currentRowVersion != researchFileVersion) { throw new DbUpdateConcurrencyException("You are working with an older version of this research file, please refresh the application and retry."); } } } }
40.966102
181
0.650186
[ "Apache-2.0" ]
FuriousLlama/PSP
backend/dal/Services/ResearchFileService.cs
4,834
C#
/*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:CommonApi.Menu.cs 文件功能描述:自定义菜单API 创建标识:Senparc - 20150313 修改标识:Senparc - 20150313 修改描述:整理接口 修改标识:Senparc - 20150313 修改描述:开放代理请求超时时间 修改标识:Senparc - 20160720 修改描述:增加其接口的异步方法 ----------------------------------------------------------------*/ /* 获取AccessToken API地址:http://qydev.weixin.qq.com/wiki/index.php?title=%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Senparc.Weixin.Entities; using Senparc.Weixin.Exceptions; using Senparc.Weixin.HttpUtility; using Senparc.Weixin.QY.Entities; using Senparc.Weixin.QY.Entities.Menu; #if NET45 using System.Web.Script.Serialization; #else using Newtonsoft.Json; #endif namespace Senparc.Weixin.QY.CommonAPIs { public partial class CommonApi { #region 同步请求 /// <summary> /// 创建菜单【QY移植修改】 /// </summary> /// <param name="accessToken"></param> /// <param name="agentId"></param> /// <param name="buttonData">菜单内容</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> public static QyJsonResult CreateMenu(string accessToken, int agentId, ButtonGroup buttonData, int timeOut = Config.TIME_OUT) { var urlFormat = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); ////对特殊符号进行URL转义 //foreach (var button in buttonData.button) //{ // button.name = ButtonNameEncode(button.name);//button.name.UrlEncode(); // if (button is SubButton) // { // var subButtonList = button as SubButton; // foreach (var subButton in subButtonList.sub_button) // { // subButton.name = ButtonNameEncode(button.name);//button.name.UrlEncode(); // } // } //} return CommonJsonSend.Send(null, urlFormat, buttonData, CommonJsonSendType.POST, timeOut); } #region GetMenu /// <summary> /// 获取单击按钮【QY移植修改】 /// </summary> /// <param name="objs"></param> /// <returns></returns> [Obsolete("配合GetMenuFromJson方法使用")] private static SingleClickButton GetSingleButtonFromJsonObject(Dictionary<string, object> objs) { var sb = new SingleClickButton() { key = objs["key"] as string, name = objs["name"] as string, type = objs["type"] as string }; return sb; } /// <summary> /// 从JSON字符串获取菜单对象【QY移植修改】 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> [Obsolete("此方法通过判断GetMenuResult并结合object类型转换得到结果。结果准确。但更推荐使用GetMenuFromJsonResult方法。")] public static GetMenuResult GetMenuFromJson(string jsonString) { var finalResult = new GetMenuResult(); try { //@"{""menu"":{""button"":[{""type"":""click"",""name"":""单击测试"",""key"":""OneClick"",""sub_button"":[]},{""name"":""二级菜单"",""sub_button"":[{""type"":""click"",""name"":""返回文本"",""key"":""SubClickRoot_Text"",""sub_button"":[]},{""type"":""click"",""name"":""返回图文"",""key"":""SubClickRoot_News"",""sub_button"":[]},{""type"":""click"",""name"":""返回音乐"",""key"":""SubClickRoot_Music"",""sub_button"":[]}]}]}}" object jsonResult = null; #if NET45 #else jsonResult = JsonConvert.DeserializeObject<object>(jsonString); #endif var fullResult = jsonResult as Dictionary<string, object>; if (fullResult != null && fullResult.ContainsKey("menu")) { //得到菜单 var menu = fullResult["menu"]; var buttons = (menu as Dictionary<string, object>)["button"] as object[]; foreach (var rootButton in buttons) { var fullButton = rootButton as Dictionary<string, object>; if (fullButton.ContainsKey("key") && !string.IsNullOrEmpty(fullButton["key"] as string)) { //按钮,无下级菜单 finalResult.menu.button.Add(GetSingleButtonFromJsonObject(fullButton)); } else { //二级菜单 var subButton = new SubButton(fullButton["name"] as string); finalResult.menu.button.Add(subButton); foreach (var sb in fullButton["sub_button"] as object[]) { subButton.sub_button.Add(GetSingleButtonFromJsonObject(sb as Dictionary<string, object>)); } } } } else if (fullResult != null && fullResult.ContainsKey("errmsg")) { //菜单不存在 throw new ErrorJsonResultException(fullResult["errmsg"] as string, null, null); } } catch (ErrorJsonResultException ex) { finalResult = null; //如果没有惨淡会返回错误代码:46003:menu no exist } catch (Exception ex) { //其他异常 finalResult = null; } return finalResult; } /// <summary> /// 获取当前菜单,如果菜单不存在,将返回null【QY移植修改】 /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="agentId">企业应用的id,整型。可在应用的设置页面查看</param> /// <returns></returns> public static GetMenuResult GetMenu(string accessToken, int agentId) { var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var jsonString = RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; try { #if NET45 JavaScriptSerializer js = new JavaScriptSerializer(); var jsonResult = js.Deserialize<GetMenuResultFull>(jsonString); #else var jsonResult = JsonConvert.DeserializeObject<GetMenuResultFull>(jsonString); #endif if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return finalResult; } /// <summary> /// 根据微信返回的Json数据得到可用的GetMenuResult结果【QY移植修改】 /// </summary> /// <param name="resultFull"></param> /// <returns></returns> public static GetMenuResult GetMenuFromJsonResult(GetMenuResultFull resultFull) { GetMenuResult result = null; try { //重新整理按钮信息 ButtonGroup bg = new ButtonGroup(); foreach (var rootButton in resultFull.menu.button) { if (rootButton.name == null) { continue;//没有设置一级菜单 } var availableSubButton = rootButton.sub_button.Count(z => !string.IsNullOrEmpty(z.name));//可用二级菜单按钮数量 if (availableSubButton == 0) { //底部单击按钮 if (rootButton.type == null || (rootButton.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(rootButton.key))) { throw new WeixinMenuException("单击按钮的key不能为空!"); } if (rootButton.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase)) { //点击 bg.button.Add(new SingleClickButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else if (rootButton.type.Equals("VIEW", StringComparison.OrdinalIgnoreCase)) { //URL bg.button.Add(new SingleViewButton() { name = rootButton.name, url = rootButton.url, type = rootButton.type }); } else if (rootButton.type.Equals("LOCATION_SELECT", StringComparison.OrdinalIgnoreCase)) { //弹出地理位置选择器 bg.button.Add(new SingleLocationSelectButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else if (rootButton.type.Equals("PIC_PHOTO_OR_ALBUM", StringComparison.OrdinalIgnoreCase)) { //弹出拍照或者相册发图 bg.button.Add(new SinglePicPhotoOrAlbumButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else if (rootButton.type.Equals("PIC_SYSPHOTO", StringComparison.OrdinalIgnoreCase)) { //弹出系统拍照发图 bg.button.Add(new SinglePicSysphotoButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else if (rootButton.type.Equals("PIC_WEIXIN", StringComparison.OrdinalIgnoreCase)) { //弹出微信相册发图器 bg.button.Add(new SinglePicWeixinButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else if (rootButton.type.Equals("SCANCODE_PUSH", StringComparison.OrdinalIgnoreCase)) { //扫码推事件 bg.button.Add(new SingleScancodePushButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } else { //扫码推事件且弹出“消息接收中”提示框 bg.button.Add(new SingleScancodeWaitmsgButton() { name = rootButton.name, key = rootButton.key, type = rootButton.type }); } } else { //底部二级菜单 var subButton = new SubButton(rootButton.name); bg.button.Add(subButton); foreach (var subSubButton in rootButton.sub_button) { if (subSubButton.name == null) { continue; //没有设置菜单 } if (subSubButton.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(subSubButton.key)) { throw new WeixinMenuException("单击按钮的key不能为空!"); } if (subSubButton.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase)) { //点击 subButton.sub_button.Add(new SingleClickButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else if (subSubButton.type.Equals("VIEW", StringComparison.OrdinalIgnoreCase)) { //URL subButton.sub_button.Add(new SingleViewButton() { name = subSubButton.name, url = subSubButton.url, type = subSubButton.type }); } else if (subSubButton.type.Equals("LOCATION_SELECT", StringComparison.OrdinalIgnoreCase)) { //弹出地理位置选择器 subButton.sub_button.Add(new SingleLocationSelectButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else if (subSubButton.type.Equals("PIC_PHOTO_OR_ALBUM", StringComparison.OrdinalIgnoreCase)) { //弹出拍照或者相册发图 subButton.sub_button.Add(new SinglePicPhotoOrAlbumButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else if (subSubButton.type.Equals("PIC_SYSPHOTO", StringComparison.OrdinalIgnoreCase)) { //弹出系统拍照发图 subButton.sub_button.Add(new SinglePicSysphotoButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else if (subSubButton.type.Equals("PIC_WEIXIN", StringComparison.OrdinalIgnoreCase)) { //弹出微信相册发图器 subButton.sub_button.Add(new SinglePicWeixinButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else if (subSubButton.type.Equals("SCANCODE_PUSH", StringComparison.OrdinalIgnoreCase)) { //扫码推事件 subButton.sub_button.Add(new SingleScancodePushButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } else { //扫码推事件且弹出“消息接收中”提示框 subButton.sub_button.Add(new SingleScancodeWaitmsgButton() { name = subSubButton.name, key = subSubButton.key, type = subSubButton.type }); } } } } result = new GetMenuResult() { menu = bg }; } catch (Exception ex) { throw new WeixinMenuException(ex.Message, ex); } return result; } #endregion /// <summary> /// 删除菜单【QY移植修改】 /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="agentId">企业应用的id,整型。可在应用的设置页面查看</param> /// <returns></returns> public static QyJsonResult DeleteMenu(string accessToken, int agentId) { var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var result = Get.GetJson<QyJsonResult>(url); return result; } #endregion #if !NET35 && !NET40 #region 异步请求 /// <summary> /// 【异步方法】删除菜单【QY移植修改】 /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="agentId">企业应用的id,整型。可在应用的设置页面查看</param> /// <returns></returns> public static async Task<QyJsonResult> DeleteMenuAsync(string accessToken, int agentId) { var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token={0}&agentid={1}", accessToken.AsUrlData(), agentId); var result = await Get.GetJsonAsync<QyJsonResult>(url); return result; } //TODO:更多异步方法 #endregion #endif } }
41.300216
423
0.421452
[ "Apache-2.0" ]
007008aabb/WeiXinMPSDK
src/Senparc.Weixin.QY/Senparc.Weixin.QY/CommonAPIs/CommonApi.Menu.cs
20,310
C#
using DragonSpark.Model.Selection.Alterations; using LinqKit; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Linq.Expressions; namespace DragonSpark.Application.Entities.Queries.Compiled; sealed class ExpectedType<TIn, TOut> : IAlteration<Expression<Func<DbContext, TIn, IQueryable<TOut>>>> { public static ExpectedType<TIn, TOut> Default { get; } = new ExpectedType<TIn, TOut>(); ExpectedType() {} public Expression<Func<DbContext, TIn, IQueryable<TOut>>> Get( Expression<Func<DbContext, TIn, IQueryable<TOut>>> parameter) => (context, @in) => parameter.Invoke(context, @in).AsQueryable(); }
33.684211
102
0.765625
[ "MIT" ]
DragonSpark/Framework
DragonSpark.Application/Entities/Queries/Compiled/ExpectedType.cs
642
C#
namespace Chapter02.Examples.SOLID.BreakingLID { public class Reader { public virtual string Read(string filePath) { // implementation how to read file contents // complex logic return ""; } } }
20.615385
55
0.55597
[ "MIT" ]
PacktWorkshops/The-C-Sharp-Workshop
Chapter02/Examples/SOLID/BreakingLID/Reader.cs
270
C#
namespace Service.ViewModels.Project { public class ProjectAssigneesViewModel { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } }
26.5
45
0.611321
[ "MIT" ]
yrshaikh/Issue-Tracker
Src/Service/ViewModels/Project/ProjectAssigneesViewModel.cs
267
C#
// Copyright 2018 Andreas Müller // This file is a part of Amusoft and is licensed under Apache 2.0 // See https://github.com/taori/Amusoft.EventManagement/blob/master/LICENSE.MD for details using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Amusoft.EventManagement.Compatibility { internal static class CompatReflectionExtensions { public static MethodInfo GetMethodInfo(Delegate source) { #if NET35 || NET40 return source.Method; #else return RuntimeReflectionExtensions.GetMethodInfo(source); #endif } public static ConstructorInfo GetConstructorInfo(Type source, Type[] constructorParameterTypes) { #if NETSTANDARD1_1 foreach (var constructorInfo in source.GetTypeInfo().DeclaredConstructors) { var currentParams = constructorInfo.GetParameters(); if(currentParams.Length != constructorParameterTypes.Length) continue; for (int i = 0; i < currentParams.Length; i++) { if (currentParams[i].ParameterType != constructorParameterTypes[i]) continue; } return constructorInfo; } return null; #else return source.GetConstructor(constructorParameterTypes); #endif } public static MethodInfo GetRuntimeMethod(Type source, string name, params Type[] parameters) { #if NET35 || NET40 return source.GetMethod(name, parameters); #else return RuntimeReflectionExtensions.GetRuntimeMethod(source, name, parameters); #endif } public static PropertyInfo GetRuntimeProperty(Type source, string name) { #if NET35 || NET40 return source.GetProperty(name); #else return RuntimeReflectionExtensions.GetRuntimeProperty(source, name); #endif } public static MethodInfo GetGetMethod(this PropertyInfo source) { #if NET35 || NET40 return source.GetGetMethod(); #else return source.GetMethod; #endif } public static IEnumerable<MethodInfo> GetRuntimeMethods(Type source) { #if NET35 || NET40 return source.GetMethods(); #else return source.GetRuntimeMethods(); #endif } } }
24.829268
97
0.752947
[ "Apache-2.0" ]
taori/Amusoft.EventManagement
src/Amusoft.EventManagement/Compatibility/ReflectionExtensions.cs
2,039
C#
using System; namespace Cosmos.Logging.Extensions.Exceptions.Core.Internals { internal static class TypeExtensions { #if NETSTANDARD1_3 public static TypeCode GetTypeCode(this Type type) { if (type is null) { return TypeCode.Empty; } if (type == typeof(bool)) { return TypeCode.Boolean; } else if (type == typeof(char)) { return TypeCode.Char; } else if (type == typeof(sbyte)) { return TypeCode.SByte; } else if (type == typeof(byte)) { return TypeCode.Byte; } else if (type == typeof(short)) { return TypeCode.Int16; } else if (type == typeof(ushort)) { return TypeCode.UInt16; } else if (type == typeof(int)) { return TypeCode.Int32; } else if (type == typeof(uint)) { return TypeCode.UInt32; } else if (type == typeof(long)) { return TypeCode.Int64; } else if (type == typeof(ulong)) { return TypeCode.UInt64; } else if (type == typeof(float)) { return TypeCode.Single; } else if (type == typeof(double)) { return TypeCode.Double; } else if (type == typeof(decimal)) { return TypeCode.Decimal; } else if (type == typeof(DateTime)) { return TypeCode.DateTime; } else if (type == typeof(string)) { return TypeCode.String; } else if (type.GetTypeInfo().IsEnum) { return TypeCode.Int32; } return TypeCode.Object; } #else public static TypeCode GetTypeCode(this Type type) => Type.GetTypeCode(type); #endif } }
26.785714
85
0.415111
[ "Apache-2.0" ]
alexinea/Cosmos.Logging
src/Cosmos.Logging.Extensions.Exceptions/Cosmos/Logging/Extensions/Exceptions/Core/Internals/Extensions.Type.cs
2,250
C#
using ETModel; using System; using UnityEngine; namespace ET { [ActorMessageHandler] public class G2M_CreateUnitHandler : AMActorRpcHandler<Scene, G2M_CreateUnit, M2G_CreateUnit> { protected override async ETTask Run(Scene scene, G2M_CreateUnit request, M2G_CreateUnit response, Action reply) { Unit unit = EntityFactory.CreateWithId<Unit, int>(scene, IdGenerater.Instance.GenerateId(), 1001); unit.AddComponent<MoveComponent>(); unit.Position = new Vector3(-10, 0, -10); NumericComponent numericComponent = unit.AddComponent<NumericComponent>(); numericComponent.Set(NumericType.Speed, 6f); // 速度是6米每秒 unit.AddComponent<MailBoxComponent>(); await unit.AddLocation(); unit.AddComponent<UnitGateComponent, long>(request.GateSessionId); scene.GetComponent<UnitComponent>().Add(unit); response.UnitId = unit.Id; // 把自己广播给周围的人 M2C_CreateUnits createUnits = new M2C_CreateUnits(); createUnits.Units.Add(UnitHelper.CreateUnitInfo(unit)); MessageHelper.Broadcast(unit, createUnits); // 把周围的人通知给自己 createUnits.Units.Clear(); Unit[] units = scene.GetComponent<UnitComponent>().GetAll(); foreach (Unit u in units) { createUnits.Units.Add(UnitHelper.CreateUnitInfo(u)); } MessageHelper.SendActor(unit.GetComponent<UnitGateComponent>().GateSessionActorId, createUnits); reply(); } } }
31.883721
113
0.743982
[ "MIT" ]
dayfox5317/et_ilruntime
Server/Hotfix/Demo/G2M_CreateUnitHandler.cs
1,423
C#
using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Abp.Runtime.Security; namespace TestApp.Web.Host.Startup { public static class AuthConfigurer { public static void Configure(IServiceCollection services, IConfiguration configuration) { if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"])) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }).AddJwtBearer("JwtBearer", options => { options.Audience = configuration["Authentication:JwtBearer:Audience"]; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = configuration["Authentication:JwtBearer:Issuer"], // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = configuration["Authentication:JwtBearer:Audience"], // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here ClockSkew = TimeSpan.Zero }; options.Events = new JwtBearerEvents { OnMessageReceived = QueryStringTokenResolver }; }); } } /* This method is needed to authorize SignalR javascript client. * SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */ private static Task QueryStringTokenResolver(MessageReceivedContext context) { if (!context.HttpContext.Request.Path.HasValue || !context.HttpContext.Request.Path.Value.StartsWith("/signalr")) { // We are just looking for signalr clients return Task.CompletedTask; } var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault(); if (qsAuthToken == null) { // Cookie value does not matches to querystring value return Task.CompletedTask; } // Set auth token from cookie context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase); return Task.CompletedTask; } } }
41.037975
148
0.582048
[ "MIT" ]
hasan-ak1996/boilerplate
aspnet-core/src/TestApp.Web.Host/Startup/AuthConfigurer.cs
3,244
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; namespace DataStorage.Mappers { public class MessageDTOMapper : IMapper<MessageDTO> { public MessageDTO ReadItem(SqlDataReader rd) { return new MessageDTO { Id = (string)rd["Id"], From = (string)rd["From"], To = (string)rd["To"], Text = (string)rd["Text"], IsSent = (int)rd["IsSent"], }; } } }
23.307692
55
0.546205
[ "MIT" ]
egdegd/Event-Bus
src/DAL/DataStorage/Mappers/MessageDTOMapper.cs
608
C#
using System; using Autodesk.Revit.DB; namespace SpatialElementGeometryCalculator { class SpatialBoundaryCache { public string roomName; public ElementId idElement; public ElementId idMaterial; public double dblNetArea; public double dblOpeningArea; public string AreaReport { get { return string.Format( "net {0}; opening {1}; gross {2}", dblNetArea, dblOpeningArea, dblNetArea + dblOpeningArea ); } } } }
20.384615
45
0.609434
[ "MIT" ]
jeremytammik/SpatialElementGeometryCalculator
SpatialElementGeometryCalculator/SpatialDataCache.cs
532
C#
using System.Collections.Generic; using System.Xml.Serialization; namespace DotNetForce.Common.Models.Xml { [XmlRoot(ElementName = "results", Namespace = "http://www.force.com/2009/06/asyncapi/dataload")] public class BatchResultList { [XmlElement("result")] public IList<BatchResult> Items; public BatchResultList() { Items = new List<BatchResult>(); } } }
23.833333
70
0.641026
[ "MIT" ]
ste80/DotNetForce
DotNetForce/Common/Models/Xml/BatchResultList.cs
431
C#