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
#if !NETSTANDARD13 /* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-email-2018-07-26.normal.json service model. */ using Amazon.Runtime; namespace Amazon.PinpointEmail.Model { /// <summary> /// Paginator for the GetDedicatedIps operation ///</summary> public interface IGetDedicatedIpsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<GetDedicatedIpsResponse> Responses { get; } } } #endif
32.4
112
0.706349
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/PinpointEmail/Generated/Model/_bcl45+netstandard/IGetDedicatedIpsPaginator.cs
1,134
C#
using SIL.Machine.WebApi.Models; namespace SIL.Machine.WebApi.DataAccess { public enum EntityChangeType { None, Insert, Update, Delete } public struct EntityChange<T> where T : class, IEntity<T> { public EntityChange(EntityChangeType type, T entity) { Type = type; Entity = entity; } public EntityChangeType Type { get; } public T Entity { get; } } }
15.4
58
0.685714
[ "MIT" ]
sillsdev/machine
src/SIL.Machine.WebApi/DataAccess/EntityChange.cs
387
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class Pausable:MonoBehaviour { public virtual void Pause(bool value) { // do nothing } }
17.25
46
0.710145
[ "Apache-2.0" ]
aprithul/Nukem
Assets/Scripts/Controller/Pausable.cs
209
C#
using System.Collections.Generic; using System.IO; using template.Api.DataAccess; using template.Api.Infrastructure.Configuration; using template.Api.Models; using template.Api.Services; using Microsoft.AspNetCore.Http; using Moq; using NUnit.Framework; namespace Mcg.Webservice.UnitTests { [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [SetUpFixture] internal static class Helpers { internal static UserModel TestModel => new UserModel() { EmailAddress = "unit@test.cs", ID = 42, Username = "Testy McTestFace" }; internal static UserModel NullModel => null; internal static IExampleDataRepository MockExampleDataAccess() { var da = new Mock<IExampleDataRepository>(); da.Setup(b => b.SelectAll()).Returns(new[] { TestModel }); da.Setup(b => b.SelectOneById(It.IsAny<int>())) .Returns((int id) => { if (id == 42) { return TestModel; } else { return NullModel; } }); da.Setup(b => b.SelectOneByEmail(It.IsAny<string>())) .Returns((string email) => { if (email == "unit@test.cs") { return TestModel; } else { return NullModel; } }); da.Setup(b => b.Insert(It.IsAny<UserModel>())); da.Setup(b => b.Update(It.IsAny<UserModel>())); da.Setup(b => b.Delete(It.IsAny<UserModel>())); da.Setup(b => b.NextId()).Returns(43); return da.Object; } internal static IExampleBusinessService MockExampleBusinessLogic() { var buslog = new Mock<IExampleBusinessService>(); buslog.Setup(b => b.SelectAll()).Returns(new[] { TestModel }); buslog.Setup(b => b.SeledtById(It.IsAny<int>())) .Returns((int id) => { if (id == 42) { return TestModel; } else { return NullModel; } }); buslog.Setup(b => b.SelectByEmail(It.IsAny<string>())) .Returns((string email) => { if (email == "unit@test.cs") { return TestModel; } else { return NullModel; } }); buslog.Setup(b => b.Insert(It.IsAny<UserModel>())) .Returns((UserModel newModel) => { if (newModel.Equals(TestModel)) { return (true, null, newModel); } else { return (false, "test error message", null); } }); buslog.Setup(b => b.Update(It.IsNotNull<UserModel>())) .Returns((UserModel newModel) => { if (newModel.Equals(TestModel)) { return (true, null); } else { return (false, "test error message"); } }); buslog.Setup(b => b.Delete(It.IsNotNull<UserModel>())).Returns((true, null)); var mock = buslog.Object; return mock; } internal static IAppSettings MockIAppSettings(string logLevel = "debug") { var settings = new Mock<IAppSettings>(); settings.SetupGet(m => m["LOG_LEVEL"]).Returns(logLevel); settings.SetupGet(m => m["AZURE_SVC_BUS_URI"]).Returns("sb://mcg-templates.servicebus.windows.net/"); settings.SetupGet(m => m["AZURE_SHARED_ACCESS_KEY_NAME"]).Returns("RootManageSharedAccessKey"); settings.SetupGet(m => m["AZURE_SHARED_ACCESS_KEY_VALUE"]).Returns("wYBGR0iaFwT5ESrHR34Z57JgV0hm2cs8lqMGIC1B"); settings.SetupGet(m => m["AZURE_PUBLISH_QUEUE"]).Returns("example.request"); settings.SetupGet(m => m["AZURE_DEFAULT_CONSUMER_MAX_CONCURRENT_CALLS"]).Returns("1"); settings.SetupGet(m => m["AZURE_DEFAULT_CONSUMER_AUTO_COMPLETE"]).Returns("false"); settings.SetupGet(m => m["OPS_PORT"]).Returns("1234"); return settings.Object; } internal static IDictionary<string, string> TestConfigValues() => new Dictionary<string, string>() { { "CORS_ALLOWED_URLS", "*"}, { "ASPNETCORE_ENVIRONMENT", "Development" }, { "ELASTIC_SEARCH_URI", "http://test/uri" }, { "JAEGER_AGENT_PORT", "localhost" }, { "JAEGER_SAMPLER_TYPE" , "6831"}, { "JAEGER_SERVICE_NAME", "Mcg.Webservice" }, { "LOG_LEVEL","verbose" }, { "MEANING_OF_LIFE","42" }, }; internal static DefaultHttpContext TestContext() { DefaultHttpContext context = new DefaultHttpContext(); context.Request.Body = new MemoryStream(); context.Request.Method = "GET"; context.Request.Path = "/this/is/a/path"; context.Request.PathBase = new PathString("/test"); context.Request.Scheme = "http"; context.Request.Host = new HostString("www.unittests.fake"); context.Response.Body = new MemoryStream(); return context; } } }
34.342857
137
0.47188
[ "MIT" ]
MCGHealth/mcg.webservice.template.datatdog
template/template.unittests/Helpers.cs
6,012
C#
using System.IO; using System.Runtime.Serialization; namespace BroadcastMessaging { public abstract class Persistable { public abstract void Save(BinaryWriter writer); public abstract void Load(BinaryReader reader); } }
21.166667
55
0.712598
[ "MIT" ]
mtaulty/HoloSharingUDPAzure
MessagingLibrary/Shared/SharedCode/Persistable.cs
256
C#
#nullable enable using System; using System.Collections.Generic; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class T01_NullableRefTypes { private string field_string; private string? field_nullable_string; private dynamic? field_nullable_dynamic; private Dictionary<string?, string> field_generic; private Dictionary<int, string?[]> field_generic2; private Dictionary<int?, string?[]> field_generic3; private KeyValuePair<string?, string> field_generic_value_type; private KeyValuePair<string?, string>? field_generic_nullable_value_type; private (string, string?, string) field_tuple; private string[]?[] field_array; private Dictionary<(string, string?), (int, string[]?, string?[])> field_complex; private dynamic[][,]?[,,][,,,] field_complex_nested_array; public (string A, dynamic? B) PropertyNamedTuple { get { throw new NotImplementedException(); } } public (string A, dynamic? B) this[(dynamic? C, string D) weirdIndexer] { get { throw new NotImplementedException(); } } public int GetLength1(string[] arr) { return field_string.Length + arr.Length; } public int GetLength2(string[]? arr) { return field_nullable_string.Length + arr.Length; } public int? GetLength3(string[]? arr) { return field_nullable_string?.Length + arr?.Length; } public void GenericNullable<T1, T2>((T1?, T1, T2, T2?, T1, T1?) x) where T1 : class where T2 : struct { } public T ByRef<T>(ref T t) { return t; } public void CallByRef(ref string a, ref string? b) { ByRef(ref a).ToString(); ByRef(ref b).ToString(); } public void Constraints<UC, C, CN, NN, S, SN, D, DN, NND>() where C : class where CN : class? where NN : notnull where S : struct where D : IDisposable where DN : IDisposable? where NND : notnull, IDisposable { } } public class T02_EverythingIsNullableInHere { private string? field1; private object? field2; // value types are irrelevant for the nullability attributes: private int field3; private int? field4; public string? Property { get; set; } public event EventHandler? Event; public static int? NullConditionalOperator(T02_EverythingIsNullableInHere? x) { // This code throws if `x != null && x.field1 == null`. // But we can't decompile it to the warning-free "x?.field1!.Length", // because of https://github.com/dotnet/roslyn/issues/43659 return x?.field1.Length; } } public class T03_EverythingIsNotNullableInHere { private string field1; private object field2; // value types are irrelevant for the nullability attributes: private int field3; private int? field4; public string Property { get; set; } public event EventHandler Event; } public class T04_Dictionary<TKey, TValue> where TKey : notnull { private struct Entry { public TKey key; public TValue value; } private int[]? _buckets; private Entry[]? _entries; private IEqualityComparer<TKey>? _comparer; } }
26.104348
210
0.706862
[ "MIT" ]
derek221028/ILSPY
ICSharpCode.Decompiler.Tests/TestCases/Pretty/NullableRefTypes.cs
3,004
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Radilovsoft.Rest.Data.Core.Contract { public interface IAsyncHelpers { Task<T> SingleOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<T> SingleAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<T> FirstOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<T> FirstAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<T[]> ToArrayAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<List<T>> ToListAsync<T>(IQueryable<T> queryable, CancellationToken token = default); Task<Dictionary<TKey, T>> ToDictionaryAsync<T, TKey>(IQueryable<T> queryable, Func<T, TKey> keySelector, CancellationToken token = default); Task<Dictionary<TKey, TElement>> ToDictionaryAsync<T, TKey, TElement>(IQueryable<T> queryable, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, CancellationToken token = default); Task<int> CountAsync<T>(IQueryable<T> queryableForCount, CancellationToken token = default); Task<long> LongCountAsync<T>(IQueryable<T> queryable, CancellationToken token = default); } }
52.153846
200
0.733776
[ "MIT" ]
Nemo-Illusionist/REST-ASP.NET
Core/Data/Radilovsoft.Rest.Data.Core/Contract/IAsyncHelpers.cs
1,356
C#
using FavourAPI.Data.Dtos.Favour; using FavourAPI.Dtos; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace FavourAPI.Services.Contracts { public interface IOfferingService { Task<OfferingDto> AddOffering(string Guid, OfferingDto offering); Task<OfferingDto> GetById(string favourId); Task<List<OfferingDto>> GetAllActiveOfferings(); Task AddApplication(string providerId, string offeringId, ApplicationDto application); Task ConfirmApplication(string applicationId, List<PeriodDto> finalPeriodsDto); Task Reject(string applicationId); } }
26.48
94
0.749245
[ "MIT" ]
indeavr/favour-api
FavourAPI.Services/Contracts/IOfferingService.cs
664
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelectionMessage : BaseMessage { }
18.428571
45
0.813953
[ "MIT" ]
palpitatertot/UnityMessaging
Assets/MessageSystemExample/Scripts/SelectionMessage.cs
131
C#
using System; using DataPowerTools.Extensions; using DataPowerTools.Extensions.Objects; namespace DataPowerTools.DataReaderExtensibility.TransformingReaders { public static class DataTransformGroups { /// <summary> /// Applies no transformation. /// </summary> /// <param name="dataType"></param> /// <returns></returns> public static DataTransform None(Type dataType) { return DataTransforms.None; } //TODO: make these composible. I.e. DataTransformGroups.Default.Add(dataTranform2) public static DataTransform ConvertEnum(Type destEnumType) { return value => { try { // ReSharper disable once PossibleNullReferenceException // Because an enum and a nullable enum are both value types, it's actually not possible to reach the next line of code when the value variable is null var r = Enum.Parse(destEnumType, value.ToString(), true); return r; } catch (Exception exception) { throw new TypeConversionException( $"An error occurred while attempting to convert the value '{value}' to an enum of type '{destEnumType}' in a data transform group", exception); } }; } /// <summary> /// The default transform group uses a minimum set of robust transforms for transforming CSV and Excel data / dates. /// </summary> /// <param name="destinationType"></param> /// <returns></returns> public static DataTransform Default(Type destinationType) { if (destinationType.IsNullableGenericType()) { destinationType = destinationType.GetNonNullableType(); var destinationTypeConverter = DefaultValueTypeConvert(destinationType); return o => { o = DataTransforms.TransformNull(o); if (o == null) return null; o = destinationTypeConverter(o); return o; }; } return DefaultValueTypeConvert(destinationType); } /// <summary> /// Converts value types using a robust set of transforms. Does not handle nulls. /// </summary> /// <param name="destinationType"></param> /// <returns></returns> public static DataTransform DefaultValueTypeConvert(Type destinationType) { if (destinationType.IsEnum) return ConvertEnum(destinationType); if (destinationType == typeof(string)) return DataTransforms.None; if (destinationType == typeof(bool)) return DataTransforms.TransformBoolean; if (destinationType == typeof(decimal) || destinationType == typeof(double) || destinationType == typeof(float)) return DataTransforms.TransformDecimal; //o => Convert.ChangeType(DataTransforms.TransformDecimal(o), destinationType); if (destinationType == typeof(int)) return DataTransforms.TransformInt; if (destinationType == typeof(Guid)) return DataTransforms.TransformGuid; if (destinationType == typeof(byte[])) return DataTransforms.None; if (destinationType == typeof(DateTime)) return DataTransforms.TransformExcelDate; return DataTransforms.TransformStringIsNullOrWhiteSpaceAndTrim; } public static DataTransform TypeConvert(Type destinationType) { return o => Convert.ChangeType(o, destinationType); } /// <summary> /// Uses some checking and MS default converters for C# types using .ConvertType /// </summary> /// <param name="destinationType"></param> /// <returns></returns> public static DataTransform DefaultConvert(Type destinationType) { return o => o.ConvertTo(destinationType); } } }
36.991379
227
0.571429
[ "MIT" ]
nh43de/DataPowerTools
src/DataPowerTools/DataReaderExtensibility/Transformations/DataTransformGroups.cs
4,293
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; using System.IO; using ImageMagick; using Xunit; #if Q8 using QuantumType = System.Byte; #elif Q16 using QuantumType = System.UInt16; #elif Q16HDRI using QuantumType = System.Single; #else #error Not implemented! #endif namespace Magick.NET.Tests { public partial class MagickImageTests { public partial class TheReadPixelsMethod { public class WithByteArray { [Fact] public void ShouldThrowExceptionWhenArrayIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("data", () => { image.ReadPixels((byte[])null, settings); }); } } [Fact] public void ShouldThrowExceptionWhenArrayIsEmpty() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("data", () => { image.ReadPixels(Array.Empty<byte>(), settings); }); Assert.Contains("Value cannot be empty.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new byte[] { 215 }, null); }); } } [Fact] public void ShouldThrowExceptionWhenMappingIsNull() { var settings = new PixelReadSettings { Mapping = null, StorageType = StorageType.Char, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new byte[] { 215 }, settings); }); Assert.Contains("Pixel storage mapping should be defined.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenMappingIsEmpty() { var settings = new PixelReadSettings { Mapping = string.Empty, StorageType = StorageType.Char, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new byte[] { 215 }, settings); }); Assert.Contains("Pixel storage mapping should be defined.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenStorageTypeIsUndefined() { var settings = new PixelReadSettings { Mapping = "R", StorageType = StorageType.Undefined, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new byte[] { 215 }, settings); }); Assert.Contains("Storage type should not be undefined.", exception.Message); } } [Fact] public void ShouldReadByteArray() { var data = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xf0, 0x3f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xf0, 0x3f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var settings = new PixelReadSettings(2, 1, StorageType.Double, PixelMapping.RGBA); using (var image = new MagickImage()) { image.ReadPixels(data, settings); Assert.Equal(2, image.Width); Assert.Equal(1, image.Height); using (var pixels = image.GetPixels()) { var pixel = pixels.GetPixel(0, 0); Assert.Equal(4, pixel.Channels); Assert.Equal(0, pixel.GetChannel(0)); Assert.Equal(0, pixel.GetChannel(1)); Assert.Equal(0, pixel.GetChannel(2)); Assert.Equal(Quantum.Max, pixel.GetChannel(3)); pixel = pixels.GetPixel(1, 0); Assert.Equal(4, pixel.Channels); Assert.Equal(0, pixel.GetChannel(0)); Assert.Equal(Quantum.Max, pixel.GetChannel(1)); Assert.Equal(0, pixel.GetChannel(2)); Assert.Equal(0, pixel.GetChannel(3)); } } } } public class WithByteArrayAndOffset { [Fact] public void ShouldThrowExceptionWhenArrayIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("data", () => { image.ReadPixels((byte[])null, 0, 0, settings); }); } } [Fact] public void ShouldThrowExceptionWhenArrayIsEmpty() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("data", () => { image.ReadPixels(Array.Empty<byte>(), 0, 0, settings); }); Assert.Contains("Value cannot be empty.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new byte[] { 215 }, null); }); } } [Fact] public void ShouldThrowExceptionWhenOffsetIsNegative() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("offset", () => { image.ReadPixels(new byte[] { 215 }, -1, 0, settings); }); Assert.Contains("The offset should be positive.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsZero() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new byte[] { 215 }, 0, 0, settings); }); Assert.Contains("The number of bytes should be at least 1.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsNegative() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new byte[] { 215 }, 0, -1, settings); }); Assert.Contains("The number of bytes should be at least 1.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsTooLow() { var settings = new PixelReadSettings(1, 1, StorageType.Char, PixelMapping.RGB); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new byte[] { 215 }, settings); }); Assert.Contains("The count is 1 but should be at least 3.", exception.Message); } } } #if !Q8 public class WithQuantumArray { [Fact] public void ShouldThrowExceptionWhenArrayIsNull() { var settings = new PixelReadSettings { StorageType = StorageType.Quantum, }; using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("data", () => { image.ReadPixels((QuantumType[])null, settings); }); } } [Fact] public void ShouldThrowExceptionWhenArrayIsEmpty() { var settings = new PixelReadSettings { StorageType = StorageType.Quantum, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("data", () => { image.ReadPixels(Array.Empty<QuantumType>(), settings); }); Assert.Contains("Value cannot be empty.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new QuantumType[] { 215 }, null); }); } } [Fact] public void ShouldThrowExceptionWhenMappingIsNull() { var settings = new PixelReadSettings { Mapping = null, StorageType = StorageType.Quantum, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new QuantumType[] { 215 }, settings); }); Assert.Contains("Pixel storage mapping should be defined.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenMappingIsEmpty() { var settings = new PixelReadSettings { Mapping = string.Empty, StorageType = StorageType.Quantum, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new QuantumType[] { 215 }, settings); }); Assert.Contains("Pixel storage mapping should be defined.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenStorageTypeIsInvalid() { var settings = new PixelReadSettings { Mapping = "R", StorageType = StorageType.Char, }; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(new QuantumType[] { 215 }, settings); }); Assert.Contains("Storage type should be Quantum.", exception.Message); } } [Fact] public void ShouldReadQuantumArray() { var data = new QuantumType[] { 0, 0, 0, Quantum.Max, 0, Quantum.Max, 0, 0, }; var settings = new PixelReadSettings(2, 1, StorageType.Quantum, PixelMapping.RGBA); using (var image = new MagickImage()) { image.ReadPixels(data, settings); Assert.Equal(2, image.Width); Assert.Equal(1, image.Height); using (var pixels = image.GetPixels()) { var pixel = pixels.GetPixel(0, 0); Assert.Equal(4, pixel.Channels); Assert.Equal(0, pixel.GetChannel(0)); Assert.Equal(0, pixel.GetChannel(1)); Assert.Equal(0, pixel.GetChannel(2)); Assert.Equal(Quantum.Max, pixel.GetChannel(3)); pixel = pixels.GetPixel(1, 0); Assert.Equal(4, pixel.Channels); Assert.Equal(0, pixel.GetChannel(0)); Assert.Equal(Quantum.Max, pixel.GetChannel(1)); Assert.Equal(0, pixel.GetChannel(2)); Assert.Equal(0, pixel.GetChannel(3)); } } } } public class WithQuantumArrayAndOffset { [Fact] public void ShouldThrowExceptionWhenArrayIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("data", () => { image.ReadPixels((QuantumType[])null, 0, 0, settings); }); } } [Fact] public void ShouldThrowExceptionWhenArrayIsEmpty() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("data", () => { image.ReadPixels(Array.Empty<QuantumType>(), 0, 0, settings); }); Assert.Contains("Value cannot be empty.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new byte[] { 215 }, 0, 1, null); }); } } [Fact] public void ShouldThrowExceptionWhenOffsetIsNegative() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("offset", () => { image.ReadPixels(new QuantumType[] { 215 }, -1, 0, settings); }); Assert.Contains("The offset should be positive.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsZero() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new QuantumType[] { 215 }, 0, 0, settings); }); Assert.Contains("The number of items should be at least 1.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsNegative() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new QuantumType[] { 215 }, 0, -1, settings); }); Assert.Contains("The number of items should be at least 1.", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenCountIsTooLow() { var settings = new PixelReadSettings(1, 1, StorageType.Quantum, PixelMapping.RGB); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("count", () => { image.ReadPixels(new QuantumType[] { 215 }, settings); }); Assert.Contains("The count is 1 but should be at least 3.", exception.Message); } } } #endif public class WithFileInfo { [Fact] public void ShouldThrowExceptionWhenFileInfoIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("file", () => { image.ReadPixels((FileInfo)null, settings); }); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new FileInfo(Files.CirclePNG), null); }); } } [Fact] public void ShouldReadFileInfo() { var settings = new PixelReadSettings(1, 1, StorageType.Float, "R"); var bytes = BitConverter.GetBytes(1.0F); using (var temporyFile = new TemporaryFile(bytes)) { using (var image = new MagickImage()) { image.ReadPixels(temporyFile.FileInfo, settings); Assert.Equal(1, image.Width); Assert.Equal(1, image.Height); ColorAssert.Equal(MagickColors.White, image, 0, 0); } } } } public class WithFileName { [Fact] public void ShouldThrowExceptionWhenFileNameIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("fileName", () => { image.ReadPixels((string)null, settings); }); } } [Fact] public void ShouldThrowExceptionWhenFileNameIsEmpty() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentException>("fileName", () => { image.ReadPixels(string.Empty, settings); }); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(Files.CirclePNG, null); }); } } [Fact] public void ShouldThrowExceptionWhenMappingIsNull() { var settings = new PixelReadSettings(1, 1, StorageType.Char, null); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(Files.CirclePNG, settings); }); Assert.Contains("mapping", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenMappingIsEmpty() { var settings = new PixelReadSettings(1, 1, StorageType.Char, string.Empty); using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentException>("settings", () => { image.ReadPixels(Files.CirclePNG, settings); }); Assert.Contains("mapping", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenWidthIsNull() { var settings = new PixelReadSettings(1, 1, StorageType.Char, "RGBA"); settings.ReadSettings.Width = null; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(Files.CirclePNG, settings); }); Assert.Contains("Width", exception.Message); } } [Fact] public void ShouldThrowExceptionWhenHeightIsNull() { var settings = new PixelReadSettings(1, 1, StorageType.Char, "RGBA"); settings.ReadSettings.Height = null; using (var image = new MagickImage()) { var exception = Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(Files.CirclePNG, settings); }); Assert.Contains("Height", exception.Message); } } [Fact] public void ShouldReadFileName() { var settings = new PixelReadSettings(1, 1, StorageType.Short, "R"); var bytes = BitConverter.GetBytes(ushort.MaxValue); using (var temporyFile = new TemporaryFile(bytes)) { var fileName = temporyFile.FullName; using (var image = new MagickImage()) { image.ReadPixels(fileName, settings); Assert.Equal(1, image.Width); Assert.Equal(1, image.Height); ColorAssert.Equal(MagickColors.White, image, 0, 0); } } } } public class WithStream { [Fact] public void ShouldThrowExceptionWhenStreamIsNull() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("stream", () => { image.ReadPixels((Stream)null, settings); }); } } [Fact] public void ShouldThrowExceptionWhenStreamIsEmpty() { var settings = new PixelReadSettings(); using (var image = new MagickImage()) { Assert.Throws<ArgumentException>("stream", () => { image.ReadPixels(new MemoryStream(), settings); }); } } [Fact] public void ShouldThrowExceptionWhenSettingsIsNull() { using (var image = new MagickImage()) { Assert.Throws<ArgumentNullException>("settings", () => { image.ReadPixels(new MemoryStream(new byte[] { 215 }), null); }); } } [Fact] public void ShouldReadStream() { var settings = new PixelReadSettings(1, 1, StorageType.Int64, "R"); var bytes = BitConverter.GetBytes(ulong.MaxValue); using (var memoryStream = new MemoryStream(bytes)) { using (var image = new MagickImage()) { image.ReadPixels(memoryStream, settings); Assert.Equal(1, image.Width); Assert.Equal(1, image.Height); ColorAssert.Equal(MagickColors.White, image, 0, 0); } } } } } } }
38.011734
104
0.394409
[ "Apache-2.0" ]
jianyuyanyu/Magick.NET
tests/Magick.NET.Tests/MagickImageTests/TheReadPixelsMethod.cs
29,157
C#
using System; using UnityEngine; namespace RFG { [CreateAssetMenu(fileName = "New Weapon Fired State", menuName = "RFG/Platformer/Items/Equipable/Weapon/States/Fired")] public class WeaponFiredState : WeaponState { public override Type Execute(Weapon weapon) { return typeof(WeaponIdleState); } } }
24.142857
122
0.695266
[ "Apache-2.0" ]
retro-fall-games/PermitDenied
Assets/RFG/Platformer/Items/Equipables/Weapon/States/WeaponFiredState.cs
338
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.IO; using Microsoft.VisualStudio.ProjectSystem.Build; using Microsoft.VisualStudio.ProjectSystem.Properties; using Microsoft.VisualStudio.Telemetry; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.ProjectSystem.UpToDate { [AppliesTo(ProjectCapability.DotNet + "+ !" + ProjectCapabilities.SharedAssetsProject)] [Export(typeof(IBuildUpToDateCheckProvider))] [Export(ExportContractNames.Scopes.ConfiguredProject, typeof(IProjectDynamicLoadComponent))] [ExportMetadata("BeforeDrainCriticalTasks", true)] internal sealed partial class BuildUpToDateCheck : OnceInitializedOnceDisposedUnderLockAsync, IBuildUpToDateCheckProvider, IProjectDynamicLoadComponent { private const string CopyToOutputDirectory = "CopyToOutputDirectory"; private const string PreserveNewest = "PreserveNewest"; private const string Always = "Always"; private const string Link = "Link"; private const string DefaultSetName = ""; private static readonly StringComparer s_setNameComparer = StringComparers.ItemNames; private static ImmutableHashSet<string> ReferenceSchemas => ImmutableStringHashSet.EmptyOrdinal .Add(ResolvedAnalyzerReference.SchemaName) .Add(ResolvedCompilationReference.SchemaName); private static ImmutableHashSet<string> UpToDateSchemas => ImmutableStringHashSet.EmptyOrdinal .Add(CopyUpToDateMarker.SchemaName) .Add(UpToDateCheckInput.SchemaName) .Add(UpToDateCheckOutput.SchemaName) .Add(UpToDateCheckBuilt.SchemaName); private static ImmutableHashSet<string> ProjectPropertiesSchemas => ImmutableStringHashSet.EmptyOrdinal .Add(ConfigurationGeneral.SchemaName) .Union(ReferenceSchemas) .Union(UpToDateSchemas); private static ImmutableHashSet<string> NonCompilationItemTypes => ImmutableHashSet<string>.Empty .WithComparer(StringComparers.ItemTypes) .Add(None.SchemaName) .Add(Content.SchemaName); private readonly IProjectSystemOptions _projectSystemOptions; private readonly ConfiguredProject _configuredProject; private readonly IProjectAsynchronousTasksService _tasksService; private readonly IProjectItemSchemaService _projectItemSchemaService; private readonly ITelemetryService _telemetryService; private readonly IFileSystem _fileSystem; private readonly object _stateLock = new object(); private State _state = State.Empty; private IDisposable? _link; [ImportingConstructor] public BuildUpToDateCheck( IProjectSystemOptions projectSystemOptions, ConfiguredProject configuredProject, [Import(ExportContractNames.Scopes.ConfiguredProject)] IProjectAsynchronousTasksService tasksService, IProjectItemSchemaService projectItemSchemaService, ITelemetryService telemetryService, IProjectThreadingService threadingService, IFileSystem fileSystem) : base(threadingService.JoinableTaskContext) { _projectSystemOptions = projectSystemOptions; _configuredProject = configuredProject; _tasksService = tasksService; _projectItemSchemaService = projectItemSchemaService; _telemetryService = telemetryService; _fileSystem = fileSystem; } public Task LoadAsync() { return InitializeAsync(); } public Task UnloadAsync() { return ExecuteUnderLockAsync(_ => { lock (_stateLock) { _link?.Dispose(); _link = null; _state = State.Empty; } return Task.CompletedTask; }); } protected override Task InitializeCoreAsync(CancellationToken cancellationToken) { Assumes.Present(_configuredProject.Services.ProjectSubscription); _link = ProjectDataSources.SyncLinkTo( _configuredProject.Services.ProjectSubscription.JointRuleSource.SourceBlock.SyncLinkOptions(DataflowOption.WithRuleNames(ProjectPropertiesSchemas)), _configuredProject.Services.ProjectSubscription.SourceItemsRuleSource.SourceBlock.SyncLinkOptions(), _configuredProject.Services.ProjectSubscription.ProjectSource.SourceBlock.SyncLinkOptions(), _projectItemSchemaService.SourceBlock.SyncLinkOptions(), _configuredProject.Services.ProjectSubscription.ProjectCatalogSource.SourceBlock.SyncLinkOptions(), target: DataflowBlockSlim.CreateActionBlock<IProjectVersionedValue<ValueTuple<IProjectSubscriptionUpdate, IProjectSubscriptionUpdate, IProjectSnapshot, IProjectItemSchema, IProjectCatalogSnapshot>>>(OnChanged), linkOptions: DataflowOption.PropagateCompletion); return Task.CompletedTask; } protected override Task DisposeCoreUnderLockAsync(bool initialized) { _link?.Dispose(); return Task.CompletedTask; } internal void OnChanged(IProjectVersionedValue<ValueTuple<IProjectSubscriptionUpdate, IProjectSubscriptionUpdate, IProjectSnapshot, IProjectItemSchema, IProjectCatalogSnapshot>> e) { lock (_stateLock) { if (_link == null) { // We've been unloaded, so don't update the state (which will be empty) return; } var snapshot = e.Value.Item3 as IProjectSnapshot2; Assumes.NotNull(snapshot); _state = _state.Update( jointRuleUpdate: e.Value.Item1, sourceItemsUpdate: e.Value.Item2, projectSnapshot: snapshot, projectItemSchema: e.Value.Item4, projectCatalogSnapshot: e.Value.Item5, configuredProjectVersion: e.DataSourceVersions[ProjectDataSources.ConfiguredProjectVersion]); } } private bool CheckGlobalConditions(Log log, State state) { if (!_tasksService.IsTaskQueueEmpty(ProjectCriticalOperation.Build)) { return log.Fail("CriticalTasks", "Critical build tasks are running, not up to date."); } if (state.LastVersionSeen == null || _configuredProject.ProjectVersion.CompareTo(state.LastVersionSeen) > 0) { return log.Fail("ProjectInfoOutOfDate", "Project information is older than current project version, not up to date."); } if (state.IsDisabled) { return log.Fail("Disabled", "The 'DisableFastUpToDateCheck' property is true, not up to date."); } string copyAlwaysItemPath = state.ItemsByItemType.SelectMany(kvp => kvp.Value).FirstOrDefault(item => item.copyType == CopyType.CopyAlways).path; if (copyAlwaysItemPath != null) { return log.Fail("CopyAlwaysItemExists", "Item '{0}' has CopyToOutputDirectory set to 'Always', not up to date.", _configuredProject.UnconfiguredProject.MakeRooted(copyAlwaysItemPath)); } return true; } private bool CheckInputsAndOutputs(Log log, in TimestampCache timestampCache, State state) { // UpToDateCheckInput/Output/Built items have optional 'Set' metadata that determine whether they // are treated separately or not. If omitted, such inputs/outputs are included in the default set, // which also includes other items such as project files, compilation items, analyzer references, etc. // First, validate the relationship between inputs and outputs within the default set. if (!CheckInputsAndOutputs(CollectDefaultInputs(), CollectDefaultOutputs(), timestampCache, DefaultSetName)) { return false; } // Second, validate the relationships between inputs and outputs in specific sets, if any. foreach (string setName in state.SetNames) { log.Verbose("Comparing timestamps of inputs and outputs in set '{0}':", setName); if (!CheckInputsAndOutputs(CollectSetInputs(setName), CollectSetOutputs(setName), timestampCache, setName)) { return false; } } // Validation passed return true; bool CheckInputsAndOutputs(IEnumerable<(string Path, bool IsRequired)> inputs, IEnumerable<string> outputs, in TimestampCache timestampCache, string setName) { // We assume there are fewer outputs than inputs, so perform a full scan of outputs to find the earliest. // This increases the chance that we may return sooner in the case we are not up to date. DateTime earliestOutputTime = DateTime.MaxValue; string? earliestOutputPath = null; bool hasOutput = false; bool hasInput = false; foreach (string output in outputs) { DateTime? outputTime = timestampCache.GetTimestampUtc(output); if (outputTime == null) { return log.Fail("Outputs", "Output '{0}' does not exist, not up to date.", output); } if (outputTime < earliestOutputTime) { earliestOutputTime = outputTime.Value; earliestOutputPath = output; } hasOutput = true; } if (!hasOutput) { log.Info(setName == DefaultSetName ? "No build outputs defined." : "No build outputs defined in set '{0}'.", setName); return true; } Assumes.NotNull(earliestOutputPath); if (earliestOutputTime < state.LastItemsChangedAtUtc) { return log.Fail("Outputs", "The set of project items was changed more recently ({0}) than the earliest output '{1}' ({2}), not up to date.", state.LastItemsChangedAtUtc, earliestOutputPath, earliestOutputTime); } foreach ((string input, bool isRequired) in inputs) { DateTime? inputTime = timestampCache.GetTimestampUtc(input); if (inputTime == null) { if (isRequired) { return log.Fail("Outputs", "Input '{0}' does not exist and is required, not up to date.", input); } else { log.Verbose("Input '{0}' does not exist, but is not required.", input); } } if (inputTime > earliestOutputTime) { return log.Fail("Outputs", "Input '{0}' is newer ({1}) than earliest output '{2}' ({3}), not up to date.", input, inputTime.Value, earliestOutputPath, earliestOutputTime); } if (inputTime > _state.LastCheckedAtUtc) { return log.Fail("Outputs", "Input '{0}' ({1}) has been modified since the last up-to-date check ({2}), not up to date.", input, inputTime.Value, state.LastCheckedAtUtc); } hasInput = true; } if (!hasInput) { log.Info(setName == DefaultSetName ? "No inputs defined." : "No inputs defined in set '{0}'.", setName); } else if (setName == DefaultSetName) { log.Info("No inputs are newer than earliest output '{0}' ({1}).", earliestOutputPath, earliestOutputTime); } else { log.Info("In set '{0}', no inputs are newer than earliest output '{1}' ({2}).", setName, earliestOutputPath, earliestOutputTime); } return true; } IEnumerable<(string Path, bool IsRequired)> CollectDefaultInputs() { if (state.MSBuildProjectFullPath != null) { log.Verbose("Adding project file inputs:"); log.Verbose(" '{0}'", state.MSBuildProjectFullPath); yield return (Path: state.MSBuildProjectFullPath, IsRequired: true); } if (state.NewestImportInput != null) { log.Verbose("Adding newest import input:"); log.Verbose(" '{0}'", state.NewestImportInput); yield return (Path: state.NewestImportInput, IsRequired: true); } foreach ((string itemType, ImmutableHashSet<(string path, string? link, CopyType copyType)> changes) in state.ItemsByItemType) { if (!NonCompilationItemTypes.Contains(itemType)) { log.Verbose("Adding {0} inputs:", itemType); foreach (string input in changes.Select(item => _configuredProject.UnconfiguredProject.MakeRooted(item.path))) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: true); } } } if (state.ResolvedAnalyzerReferencePaths.Count != 0) { log.Verbose("Adding " + ResolvedAnalyzerReference.SchemaName + " inputs:"); foreach (string input in state.ResolvedAnalyzerReferencePaths) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: true); } } if (state.ResolvedCompilationReferencePaths.Count != 0) { log.Verbose("Adding " + ResolvedCompilationReference.SchemaName + " inputs:"); foreach (string input in state.ResolvedCompilationReferencePaths) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: true); } } if (state.UpToDateCheckInputItemsBySetName.TryGetValue(DefaultSetName, out ImmutableHashSet<string> upToDateCheckInputItems)) { log.Verbose("Adding " + UpToDateCheckInput.SchemaName + " inputs:"); foreach (string input in upToDateCheckInputItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: true); } } if (state.AdditionalDependentFileTimes.Count != 0) { log.Verbose("Adding " + nameof(state.AdditionalDependentFileTimes) + " inputs:"); foreach ((string input, DateTime _) in state.AdditionalDependentFileTimes) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: false); } } } IEnumerable<string> CollectDefaultOutputs() { if (state.UpToDateCheckOutputItemsBySetName.TryGetValue(DefaultSetName, out ImmutableHashSet<string> upToDateCheckOutputItems)) { log.Verbose("Adding " + UpToDateCheckOutput.SchemaName + " outputs:"); foreach (string output in upToDateCheckOutputItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", output); yield return output; } } if (state.UpToDateCheckBuiltItemsBySetName.TryGetValue(DefaultSetName, out ImmutableHashSet<string> upToDateCheckBuiltItems)) { log.Verbose("Adding " + UpToDateCheckBuilt.SchemaName + " outputs:"); foreach (string output in upToDateCheckBuiltItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", output); yield return output; } } } IEnumerable<(string Path, bool IsRequired)> CollectSetInputs(string setName) { if (state.UpToDateCheckInputItemsBySetName.TryGetValue(setName, out ImmutableHashSet<string> upToDateCheckInputItems)) { log.Verbose("Adding " + UpToDateCheckInput.SchemaName + " inputs in set '{0}':", setName); foreach (string input in upToDateCheckInputItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", input); yield return (Path: input, IsRequired: true); } } } IEnumerable<string> CollectSetOutputs(string setName) { if (state.UpToDateCheckOutputItemsBySetName.TryGetValue(setName, out ImmutableHashSet<string> upToDateCheckOutputItems)) { log.Verbose("Adding " + UpToDateCheckOutput.SchemaName + " outputs in set '{0}':", setName); foreach (string output in upToDateCheckOutputItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", output); yield return output; } } if (state.UpToDateCheckBuiltItemsBySetName.TryGetValue(setName, out ImmutableHashSet<string> upToDateCheckBuiltItems)) { log.Verbose("Adding " + UpToDateCheckBuilt.SchemaName + " outputs in set '{0}':", setName); foreach (string output in upToDateCheckBuiltItems.Select(_configuredProject.UnconfiguredProject.MakeRooted)) { log.Verbose(" '{0}'", output); yield return output; } } } } private bool CheckMarkers(Log log, in TimestampCache timestampCache, State state) { // Reference assembly copy markers are strange. The property is always going to be present on // references to SDK-based projects, regardless of whether or not those referenced projects // will actually produce a marker. And an item always will be present in an SDK-based project, // regardless of whether or not the project produces a marker. So, basically, we only check // here if the project actually produced a marker and we only check it against references that // actually produced a marker. if (string.IsNullOrWhiteSpace(state.CopyUpToDateMarkerItem) || !state.CopyReferenceInputs.Any()) { return true; } string markerFile = _configuredProject.UnconfiguredProject.MakeRooted(state.CopyUpToDateMarkerItem); log.Verbose("Adding input reference copy markers:"); foreach (string referenceMarkerFile in state.CopyReferenceInputs) { log.Verbose(" '{0}'", referenceMarkerFile); } log.Verbose("Adding output reference copy marker:"); log.Verbose(" '{0}'", markerFile); if (timestampCache.TryGetLatestInput(state.CopyReferenceInputs, out string? latestInputMarkerPath, out DateTime latestInputMarkerTime)) { log.Info("Latest write timestamp on input marker is {0} on '{1}'.", latestInputMarkerTime, latestInputMarkerPath); } else { log.Info("No input markers exist, skipping marker check."); return true; } DateTime? outputMarkerTime = timestampCache.GetTimestampUtc(markerFile); if (outputMarkerTime != null) { log.Info("Write timestamp on output marker is {0} on '{1}'.", outputMarkerTime, markerFile); } else { log.Info("Output marker '{0}' does not exist, skipping marker check.", markerFile); return true; } if (outputMarkerTime < latestInputMarkerTime) { return log.Fail("Marker", "Input marker is newer than output marker, not up to date."); } return true; } private bool CheckCopiedOutputFiles(Log log, in TimestampCache timestampCache, State state) { foreach ((string destinationRelative, string sourceRelative) in state.CopiedOutputFiles) { string source = _configuredProject.UnconfiguredProject.MakeRooted(sourceRelative); string destination = _configuredProject.UnconfiguredProject.MakeRooted(destinationRelative); log.Info("Checking copied output (" + UpToDateCheckBuilt.SchemaName + " with " + UpToDateCheckBuilt.OriginalProperty + " property) file '{0}':", source); DateTime? sourceTime = timestampCache.GetTimestampUtc(source); if (sourceTime != null) { log.Info(" Source {0}: '{1}'.", sourceTime, source); } else { return log.Fail("CopyOutput", "Source '{0}' does not exist, not up to date.", source); } DateTime? destinationTime = timestampCache.GetTimestampUtc(destination); if (destinationTime != null) { log.Info(" Destination {0}: '{1}'.", destinationTime, destination); } else { return log.Fail("CopyOutput", "Destination '{0}' does not exist, not up to date.", destination); } if (destinationTime < sourceTime) { return log.Fail("CopyOutput", "Source is newer than build output destination, not up to date."); } } return true; } private bool CheckCopyToOutputDirectoryFiles(Log log, in TimestampCache timestampCache, State state) { IEnumerable<(string path, string? link, CopyType copyType)> items = state.ItemsByItemType.SelectMany(kvp => kvp.Value).Where(item => item.copyType == CopyType.CopyIfNewer); string outputFullPath = Path.Combine(state.MSBuildProjectDirectory, state.OutputRelativeOrFullPath); foreach ((string path, string? link, _) in items) { string rootedPath = _configuredProject.UnconfiguredProject.MakeRooted(path); string filename = Strings.IsNullOrEmpty(link) ? rootedPath : link; if (string.IsNullOrEmpty(filename)) { continue; } filename = _configuredProject.UnconfiguredProject.MakeRelative(filename); log.Info("Checking PreserveNewest file '{0}':", rootedPath); DateTime? itemTime = timestampCache.GetTimestampUtc(rootedPath); if (itemTime != null) { log.Info(" Source {0}: '{1}'.", itemTime, rootedPath); } else { return log.Fail("CopyToOutputDirectory", "Source '{0}' does not exist, not up to date.", rootedPath); } string destination = Path.Combine(outputFullPath, filename); DateTime? destinationTime = timestampCache.GetTimestampUtc(destination); if (destinationTime != null) { log.Info(" Destination {0}: '{1}'.", destinationTime, destination); } else { return log.Fail("CopyToOutputDirectory", "Destination '{0}' does not exist, not up to date.", destination); } if (destinationTime < itemTime) { return log.Fail("CopyToOutputDirectory", "PreserveNewest source is newer than destination, not up to date."); } } return true; } public Task<bool> IsUpToDateAsync(BuildAction buildAction, TextWriter logWriter, CancellationToken cancellationToken = default) { if (buildAction != BuildAction.Build) { return TaskResult.False; } cancellationToken.ThrowIfCancellationRequested(); return ExecuteUnderLockAsync(IsUpToDateInternalAsync, cancellationToken); async Task<bool> IsUpToDateInternalAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); var sw = Stopwatch.StartNew(); await InitializeAsync(token); LogLevel requestedLogLevel = await _projectSystemOptions.GetFastUpToDateLoggingLevelAsync(token); var logger = new Log(logWriter, requestedLogLevel, _configuredProject.UnconfiguredProject.FullPath ?? "", _telemetryService); try { State state = _state; if (!CheckGlobalConditions(logger, state)) { return false; } // Short-lived cache of timestamp by path var timestampCache = new TimestampCache(_fileSystem); if (!CheckInputsAndOutputs(logger, timestampCache, state) || !CheckMarkers(logger, timestampCache, state) || !CheckCopyToOutputDirectoryFiles(logger, timestampCache, state) || !CheckCopiedOutputFiles(logger, timestampCache, state)) { return false; } logger.UpToDate(); return true; } finally { lock (_stateLock) { _state = _state.WithLastCheckedAtUtc(DateTime.UtcNow); } logger.Verbose("Up to date check completed in {0:N1} ms", sw.Elapsed.TotalMilliseconds); } } } public Task<bool> IsUpToDateCheckEnabledAsync(CancellationToken cancellationToken = default) { return _projectSystemOptions.GetIsFastUpToDateCheckEnabledAsync(cancellationToken); } internal readonly struct TestAccessor { private readonly BuildUpToDateCheck _check; public TestAccessor(BuildUpToDateCheck check) { _check = check; } public State State => _check._state; public void SetLastCheckedAtUtc(DateTime lastCheckedAtUtc) { _check._state = _check._state.WithLastCheckedAtUtc(lastCheckedAtUtc); } public void SetLastItemsChangedAtUtc(DateTime lastItemsChangedAtUtc) { _check._state = _check._state.WithLastItemsChangedAtUtc(lastItemsChangedAtUtc); } } /// <summary>For unit testing only.</summary> internal TestAccessor TestAccess => new TestAccessor(this); } }
44.645551
231
0.557095
[ "Apache-2.0" ]
am11/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/UpToDate/BuildUpToDateCheck.cs
28,940
C#
using System; using System.Runtime.InteropServices; /* * Copyright (c) 2021 All Rights Reserved. * Description:Finalizer * Author: Chance_写代码的厨子 * Create Time:2021-08-27 10:24:50 */ namespace CookPopularCSharpToolkit.Communal { /// <summary> /// 终结器(以前称为析构函数) /// </summary> /// <remarks> /// 用于在垃圾回收器收集类实例时执行任何必要的最终清理操作。 /// 在大多数情况下,通过使用 System.Runtime.InteropServices.SafeHandle 或派生类包装任何非托管句柄,可以免去编写终结器的过程。 /// </remarks> public class Finalizer : IDisposable { private bool disposedValue; private IntPtr buffer; //Unmanaged memory buffer private SafeHandle resource; //Disposable handle to a resource public Finalizer() { //this.buffer = //Allocates memory //this.resource = //Allocates the resource } public void RunNativeMethod() { if (disposedValue) throw new ObjectDisposedException("ObjectName is disposed"); // TODO } // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器 ~Finalizer() { // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 Dispose(disposing: false); } public void Dispose() { // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 Dispose(disposing: true); GC.SuppressFinalize(this); //GC.WaitForPendingFinalizers(); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象) if (resource != null) resource.Dispose(); } // TODO: 释放未托管的资源(未托管的对象)并替代终结器 // TODO: 将大型字段设置为 null disposedValue = true; } } } }
25.236842
90
0.540667
[ "Apache-2.0" ]
Muzsor/CookPopularControl
CookPopularCSharpToolkit/Communal/Disposes/Finalizer.cs
2,304
C#
using DG.Tweening; using System.Collections; using UnityEngine; namespace MagiCloud.KGUI { public class KGUI_TurnPage : MonoBehaviour { public RectTransform content; public KGUI_Backpack kGUI_Backpack; public KGUI_Button buttonNext; public KGUI_Button buttonPre; private float min = 0; private float max; private bool isPreComplete = true; private bool isNextComplete = true; private int cellsNum; void Start() { kGUI_Backpack.action.AddListener(OnReset); StartCoroutine(EndAction()); } private void OnDestroy() { kGUI_Backpack.action.RemoveListener(OnReset); } void Update() { } IEnumerator EndAction() { yield return new WaitForEndOfFrame(); OnReset(); } void OnReset() { cellsNum = content.GetComponentsInChildren<KGUI_BackpackItem>().Length; max = Mathf.Ceil(cellsNum / 4 - 1) * 480; content.localPosition = Vector3.zero; if (cellsNum <= 4) { buttonPre.IsEnable = false; buttonNext.IsEnable = false; buttonPre.gameObject.SetActive(false); buttonNext.gameObject.SetActive(false); } else { buttonPre.IsEnable = false; buttonNext.IsEnable = true; buttonNext.gameObject.SetActive(true); buttonPre.gameObject.SetActive(true); } } public void MovePrePage() { if (content.localPosition.x < min) { if (isPreComplete == true && isNextComplete == true) { isPreComplete = false; content.DOLocalMoveX(480, 1).SetRelative().OnComplete(() => { isPreComplete = true; if (content.localPosition.x >= min) { buttonPre.IsEnable = false; buttonNext.IsEnable = true; } else { buttonPre.IsEnable = true; buttonNext.IsEnable = true; } }); } } } public void MoveNextPage() { if (content.localPosition.x >= -max) { if (isPreComplete == true && isNextComplete == true) { isNextComplete = false; content.DOLocalMoveX(-480, 1).SetRelative().OnComplete(() => { isNextComplete = true; if (content.localPosition.x <= -max) { buttonNext.IsEnable = false; buttonPre.IsEnable = true; } else { buttonNext.IsEnable = true; buttonPre.IsEnable = true; } }); } } } } }
27.560976
83
0.428614
[ "MIT" ]
LiiiiiWr/MagiCloudSDK
Assets/MagiCloud/Expansion/KGUI/Scripts/Backpack/KGUI_TurnPage.cs
3,392
C#
//----------------------------------------------------------------------------- // (c) 2020 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using BookGen.Gui.Mvvm; using BookGen.Gui.XmlEntities; using System; using System.IO; using System.Xml.Serialization; using Terminal.Gui; namespace BookGen.Gui { public sealed class ConsoleUi: IView, IDisposable { private Window? _window; private Binder? _binder; public void Run(Stream view, ViewModelBase model) { #pragma warning disable S2696 // Instance members should not write to "static" fields Application.UseSystemConsole = false; #pragma warning restore S2696 // Instance members should not write to "static" fields _binder = new Binder(model); XWindow? deserialized = DeserializeXmlView(view); if (deserialized != null) { _window = new UiPage(deserialized, _binder); model.InjectView(this); ResumeUi(); } else { throw new InvalidOperationException("View load error"); } } public event Func<string, (Stream view, ViewModelBase model)>? OnNavigaton; public void SwitchToView(string name) { if (OnNavigaton!= null) { (Stream view, ViewModelBase model)? result = OnNavigaton?.Invoke(name); if (_window != null) { _window.Dispose(); _binder = null; _window = null; } if (result != null) { Run(result.Value.view, result.Value.model); } } } public void SuspendUi() { if (Application.Top?.Running == true) { Application.RequestStop(); Application.Driver.End(); Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); } } public void ResumeUi() { Application.Init(); if (_window != null) { _window.ColorScheme = new ColorScheme { Focus = Terminal.Gui.Attribute.Make(Color.Gray, Color.Blue), HotFocus = Terminal.Gui.Attribute.Make(Color.Gray, Color.Black), HotNormal = Terminal.Gui.Attribute.Make(Color.Gray, Color.Black), Normal = Terminal.Gui.Attribute.Make(Color.Gray, Color.Black), }; Application.Top.Add(_window); } Application.Run(); } public void ExitApp() { SuspendUi(); Dispose(); Environment.Exit(0); } public void UpdateBindingsToModel() { _binder?.UpdateToModel(); } public void UpdateViewFromModel() { _binder?.UpdateFromModel(); } private XWindow? DeserializeXmlView(Stream view) { XmlSerializer xs = new XmlSerializer(typeof(XWindow)); return xs.Deserialize(view) as XWindow; } public void Dispose() { if (_window != null) { _window.Dispose(); _window = null; } } } }
29.278689
87
0.482643
[ "MIT" ]
webmaster442/BookGen
BookGen.Gui/ConsoleUi.cs
3,575
C#
using System.Collections.Generic; namespace SharedLibraryCore.Formatting { public enum ColorCodes { Black, Red, Green, Yellow, Blue, Cyan, Purple, Pink, White, Map, Grey, Wildcard, Accent } public class ColorCodeMapping : Dictionary<string, string> { } }
15.153846
62
0.5
[ "MIT" ]
LelieL91/IW4M-Admin
SharedLibraryCore/Formatting/ColorCodes.cs
396
C#
using System; class ZeroSubset { static void Main() { Console.Write("Write a first number: "); int firstNum = Int32.Parse(Console.ReadLine()); Console.Write("Write a second number: "); int secondNum = Int32.Parse(Console.ReadLine()); Console.Write("Write a third number: "); int thirdNum = Int32.Parse(Console.ReadLine()); Console.Write("Write a fourt number: "); int fourthNum = Int32.Parse(Console.ReadLine()); Console.Write("Write a fift number: "); int fiftNum = Int32.Parse(Console.ReadLine()); bool hasSubset = false; if (firstNum + secondNum == 0) { Console.WriteLine("{0} + {1} = 0", firstNum, secondNum); hasSubset = true; } if (firstNum + thirdNum == 0) { Console.WriteLine("{0} + {1} = 0", firstNum, thirdNum); hasSubset = true; } if (firstNum + fourthNum == 0) { Console.WriteLine("{0} + {1} = 0", firstNum, fourthNum); hasSubset = true; } if (firstNum + fiftNum == 0) { Console.WriteLine("{0} + {1} = 0", firstNum, fiftNum); hasSubset = true; } if (firstNum + secondNum + thirdNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, secondNum, thirdNum); hasSubset = true; } if (firstNum + secondNum + fourthNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, secondNum, fourthNum); hasSubset = true; } if (firstNum + secondNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, secondNum, fiftNum); hasSubset = true; } if (firstNum + thirdNum + fourthNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, thirdNum, fourthNum); hasSubset = true; } if (firstNum + thirdNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, thirdNum, fiftNum); hasSubset = true; } if (firstNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", firstNum, fourthNum, fiftNum); hasSubset = true; } if (firstNum + secondNum + thirdNum + fourthNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} = 0", firstNum, secondNum, thirdNum, fourthNum); hasSubset = true; } if (firstNum + secondNum + thirdNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} = 0", firstNum, secondNum, thirdNum, fiftNum); hasSubset = true; } if (firstNum + secondNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} = 0", firstNum, secondNum, fourthNum, fiftNum); hasSubset = true; } if (firstNum + thirdNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} = 0", firstNum, thirdNum, fourthNum, fiftNum); hasSubset = true; } if (firstNum + secondNum + thirdNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} + {4} = 0", firstNum, secondNum, thirdNum, fourthNum, fiftNum); hasSubset = true; } if (secondNum + thirdNum == 0) { Console.WriteLine("{0} + {1} = 0", secondNum, thirdNum); hasSubset = true; } if (secondNum + fourthNum == 0) { Console.WriteLine("{0} + {1} = 0", secondNum, fourthNum); hasSubset = true; } if (secondNum + fiftNum == 0) { Console.WriteLine("{0} + {1} = 0", secondNum, fiftNum); hasSubset = true; } if (secondNum + thirdNum + fourthNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", secondNum, thirdNum, fourthNum); hasSubset = true; } if (secondNum + thirdNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", secondNum, thirdNum, fiftNum); hasSubset = true; } if (secondNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", secondNum, fourthNum, fiftNum); hasSubset = true; } if (secondNum + thirdNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} + {3} = 0", secondNum, thirdNum, fourthNum, fiftNum); hasSubset = true; } if (thirdNum + fourthNum == 0) { Console.WriteLine("{0} + {1} = 0", thirdNum, fourthNum); hasSubset = true; } if (thirdNum + fiftNum == 0) { Console.WriteLine("{0} + {1} = 0", thirdNum, fiftNum); hasSubset = true; } if (thirdNum + fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} + {2} = 0", thirdNum, fourthNum, fiftNum); hasSubset = true; } if (fourthNum + fiftNum == 0) { Console.WriteLine("{0} + {1} = 0", fourthNum, fiftNum); hasSubset = true; } if (!hasSubset) { Console.WriteLine("No zero subset."); } } }
35.045161
116
0.476068
[ "MIT" ]
glifada/High-Quality-Code-Homeworks
C#-Part1/05. ConditionalStatements/12-ZeroSubset/ZeroSubset.cs
5,434
C#
/* * PA Engine API * * Allow clients to fetch Analytics through APIs. * * The version of the OpenAPI document: 3 * Contact: analytics.api.support@factset.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; using RestSharp.Deserializers; using RestSharpMethod = RestSharp.Method; using Polly; namespace FactSet.SDK.PAEngine.Client { /// <summary> /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// </summary> internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; public CustomJsonCodec(IReadableConfiguration configuration) { _configuration = configuration; } public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) { _serializerSettings = serializerSettings; _configuration = configuration; } /// <summary> /// Serialize the object into a JSON string. /// </summary> /// <param name="obj">Object to be serialized.</param> /// <returns>A JSON string.</returns> public string Serialize(object obj) { if (obj != null && obj is FactSet.SDK.PAEngine.Model.AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema return ((FactSet.SDK.PAEngine.Model.AbstractOpenAPISchema)obj).ToJson(); } else { return JsonConvert.SerializeObject(obj, _serializerSettings); } } public T Deserialize<T>(IRestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> internal object Deserialize(IRestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { return response.RawBytes; } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { var bytes = response.RawBytes; if (response.Headers != null) { var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in response.Headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(bytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } public string RootElement { get; set; } public string Namespace { get; set; } public string DateFormat { get; set; } public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } } /// <summary> /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), /// encapsulating general REST accessor use cases. /// </summary> public partial class ApiClient : ISynchronousClient, IAsynchronousClient { private readonly string _baseUrl; /// <summary> /// Specifies the settings on a <see cref="JsonSerializer" /> object. /// These settings can be adjusted to accommodate custom serialization rules. /// </summary> public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// </summary> public ApiClient() { _baseUrl = FactSet.SDK.PAEngine.Client.GlobalConfiguration.Instance.BasePath; } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> /// </summary> /// <param name="basePath">The target service's base path in URL format.</param> /// <exception cref="ArgumentException"></exception> public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); _baseUrl = basePath; } /// <summary> /// Constructs the RestSharp version of an http method /// </summary> /// <param name="method">Swagger Client Custom HttpMethod</param> /// <returns>RestSharp's HttpMethod instance.</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> private RestSharpMethod Method(HttpMethod method) { RestSharpMethod other; switch (method) { case HttpMethod.Get: other = RestSharpMethod.GET; break; case HttpMethod.Post: other = RestSharpMethod.POST; break; case HttpMethod.Put: other = RestSharpMethod.PUT; break; case HttpMethod.Delete: other = RestSharpMethod.DELETE; break; case HttpMethod.Head: other = RestSharpMethod.HEAD; break; case HttpMethod.Options: other = RestSharpMethod.OPTIONS; break; case HttpMethod.Patch: other = RestSharpMethod.PATCH; break; default: throw new ArgumentOutOfRangeException("method", method, null); } return other; } /// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, string path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) throw new ArgumentNullException("path"); if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.Data is Stream stream) { var contentType = "application/octet-stream"; if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; contentType = contentTypes[0]; } var bytes = ClientUtils.ReadAsBytes(stream); request.AddParameter(contentType, bytes, ParameterType.RequestBody); } else { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); else request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return request; } private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) { T result = response.Data; string rawContent = response.Content; var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(StringComparer.OrdinalIgnoreCase), result, rawContent) { ErrorText = response.ErrorMessage, Cookies = new List<Cookie>() }; if (response.Headers != null) { foreach (var responseHeader in response.Headers) { transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); } } if (response.Cookies != null) { foreach (var responseCookies in response.Cookies) { transformed.Cookies.Add( new Cookie( responseCookies.Name, responseCookies.Value, responseCookies.Path, responseCookies.Domain) ); } } return transformed; } private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration, RequestOptions requestOptions) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = client.Execute<T>(req); } // check if we already have an ApiException, e.g. something went wrong during deserialization if (response.ErrorException is ApiException) { throw response.ErrorException; } DeserializeResponseWithResponseTypeDictionary(configuration, requestOptions, response); InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, RequestOptions requestOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false); } // check if we alrady have an ApiException, e.g. something went wrong during deserialization if (response.ErrorException is ApiException) { throw response.ErrorException; } DeserializeResponseWithResponseTypeDictionary(configuration, requestOptions, response); InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } private void DeserializeResponseWithResponseTypeDictionary<T>(IReadableConfiguration configuration, RequestOptions requestOptions, IRestResponse<T> response) { if (requestOptions.ResponseTypeDictionary.ContainsKey(response.StatusCode)) { var type = requestOptions.ResponseTypeDictionary[response.StatusCode]; var jsonSerializer = new CustomJsonCodec(SerializerSettings, configuration); if (!response.IsSuccessful) { Multimap<string, string> responseHeaders = new Multimap<string, string>(); foreach (var header in response.Headers) { responseHeaders.Add(header.Name, header.Value?.ToString()); } throw new ApiException((int) response.StatusCode, "error", response.ToString(), responseHeaders); } if (typeof(T).Name == "Stream") // for binary response { response.Data = (T) (object) new MemoryStream(response.RawBytes); } else { response.Data = (T) jsonSerializer.Deserialize(response, type); } } } #region IAsynchronousClient /// <summary> /// Make a HTTP GET request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP POST request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP PUT request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP DELETE request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP HEAD request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP OPTION request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, options, cancellationToken); } /// <summary> /// Make a HTTP PATCH request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, options, cancellationToken); } #endregion IAsynchronousClient #region ISynchronousClient /// <summary> /// Make a HTTP GET request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config, options); } /// <summary> /// Make a HTTP POST request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config, options); } /// <summary> /// Make a HTTP PUT request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config, options); } /// <summary> /// Make a HTTP DELETE request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config, options); } /// <summary> /// Make a HTTP HEAD request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config, options); } /// <summary> /// Make a HTTP OPTION request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config, options); } /// <summary> /// Make a HTTP PATCH request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config, options); } #endregion ISynchronousClient } }
45.438695
241
0.580913
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/PAEngine/v3/src/FactSet.SDK.PAEngine/Client/ApiClient.cs
40,395
C#
using System.Collections.Generic; using Dnn.PersonaBar.Pages.Components.Dto; using Dnn.PersonaBar.Pages.Services.Dto; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Portals; namespace Dnn.PersonaBar.Pages.Components { public interface IPagesController { bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, out string errorMessage); IEnumerable<TabInfo> GetPageList(PortalSettings portalSettings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false); IEnumerable<TabInfo> GetPageList(PortalSettings portalSettings, bool? deleted, string tabName, string tabTitle, string tabPath, string tabSkin, bool? visible, int parentId, out int total, string searchKey = "", int pageIndex = -1, int pageSize = 10, bool includeSubpages = false); IEnumerable<TabInfo> SearchPages(out int totalRecords, string searchKey = "", string pageType = "", string tags = "", string publishStatus = "", string publishDateStart = "", string publishDateEnd = "", int workflowId = -1, int pageIndex = -1, int pageSize = -1); List<int> GetPageHierarchy(int pageId); TabInfo MovePage(PageMoveRequest request); void DeletePage(PageItem page, PortalSettings portalSettings = null); void DeletePage(PageItem page, bool hardDelete, PortalSettings portalSettings = null); void EditModeForPage(int pageId, int userId); TabInfo SavePageDetails(PortalSettings portalSettings, PageSettings pageSettings); IEnumerable<ModuleInfo> GetModules(int pageId); PageSettings GetDefaultSettings(int pageId = 0); void DeleteTabModule(int pageId, int moduleId); /// <summary> /// Returns a clean tab relative url based on Advanced Management Url settings /// </summary> /// <param name="url">Url not cleaned, this could containes blank space or invalid characters</param> /// <returns>Cleaned Url</returns> string CleanTabUrl(string url); /// <summary> /// Copy the given theme to all descendant pages /// </summary> /// <param name="pageId">page identifier</param> /// <param name="theme">Theme</param> void CopyThemeToDescendantPages(int pageId, Theme theme); /// <summary> /// Copy the current page permissions to all descendant pages /// </summary> /// <param name="pageId">page identifier</param> void CopyPermissionsToDescendantPages(int pageId); IEnumerable<Url> GetPageUrls(int tabId); PageSettings GetPageSettings(int pageId, PortalSettings portalSettings = null); PageUrlResult CreateCustomUrl(SeoUrl dto); PageUrlResult UpdateCustomUrl(SeoUrl dto); PageUrlResult DeleteCustomUrl(UrlIdDto dto); PagePermissions GetPermissionsData(int pageId); } }
44.147059
200
0.693205
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
Dnn.AdminExperience/Extensions/Content/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs
3,004
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoMapperDemo.Models { public class CustomerDto { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Company { get; set; } } }
21.6875
45
0.651297
[ "Apache-2.0" ]
miggymail/AutoMapperAspNetCoreDemo
AutoMapperDemo/Models/CustomerDto.cs
349
C#
using Microsoft.AspNetCore.Mvc; using SpeedTestApi.Models; using SpeedTestApi.Services; using System.Threading.Tasks; namespace SpeedTestApi.Controllers { [Route("[controller]")] [ApiController] public class SpeedTestController : ControllerBase { private readonly ISpeedTestEvents _eventHub; public SpeedTestController(ISpeedTestEvents eventHub) { _eventHub = eventHub; } // GET speedtest/ping [Route("ping")] [HttpGet] public ActionResult<string> Ping() { return Ok("PONG"); } // POST speedtest/ [HttpPost] public async Task<ActionResult<string>> UploadSpeedTest([FromBody] TestResult speedTest) { await _eventHub.PublishSpeedTest(speedTest); var speedTestData = $"Got a TestResult from { speedTest.User } with download { speedTest.Data.Speeds.Download } Mbps."; return Ok(speedTestData); } } }
25.717949
131
0.626122
[ "MIT" ]
martitv/az-speedtest-api
SpeedTestApi/Controllers/SpeedTestController.cs
1,005
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; namespace UE4.UMG { ///<summary>EDesign Preview Size Mode</summary> public enum EDesignPreviewSizeMode { FillScreen = 0x00000000, Custom = 0x00000001, CustomOnScreen = 0x00000002, Desired = 0x00000003, DesiredOnScreen = 0x00000004, EDesignPreviewSizeMode_MAX = 0x00000005 } }
27.521739
59
0.71248
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/UMG/EDesignPreviewSizeMode.cs
633
C#
using System; namespace ServicePrincipleApp.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.083333
71
0.646288
[ "MIT" ]
PacktPublishing/Exam-Ref-AZ-304-Microsoft-Azure-Architect-Design-Certification-and-Beyond
ch6/ServicePrincipleApp/Models/ErrorViewModel.cs
229
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// ListThingTypes Request Marshaller /// </summary> public class ListThingTypesRequestMarshaller : IMarshaller<IRequest, ListThingTypesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListThingTypesRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListThingTypesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-05-28"; request.HttpMethod = "GET"; if (publicRequest.IsSetMaxResults()) request.Parameters.Add("maxResults", StringUtils.FromInt(publicRequest.MaxResults)); if (publicRequest.IsSetNextToken()) request.Parameters.Add("nextToken", StringUtils.FromString(publicRequest.NextToken)); if (publicRequest.IsSetThingTypeName()) request.Parameters.Add("thingTypeName", StringUtils.FromString(publicRequest.ThingTypeName)); request.ResourcePath = "/thing-types"; request.UseQueryString = true; return request; } private static ListThingTypesRequestMarshaller _instance = new ListThingTypesRequestMarshaller(); internal static ListThingTypesRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListThingTypesRequestMarshaller Instance { get { return _instance; } } } }
34.617021
143
0.64536
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/ListThingTypesRequestMarshaller.cs
3,254
C#
using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Maui; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Graphics; namespace Controls.Sample.Tests { public class MockPlatformServices : IPlatformServices { public string GetHash(string input) => string.Empty; public string GetMD5Hash(string input) => string.Empty; public double GetNamedSize(NamedSize size, Type targetElement, bool useOldSizes) => 0; public Color GetNamedColor(string name) => Colors.Transparent; public void OpenUriAction(Uri uri) { } public bool IsInvokeRequired { get; } = false; public OSAppTheme RequestedTheme { get; } = OSAppTheme.Unspecified; public string RuntimePlatform { get; set; } = string.Empty; public void BeginInvokeOnMainThread(Action action) => action(); public void StartTimer(TimeSpan interval, Func<bool> callback) { } public Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken) => Task.FromResult<Stream>(new MemoryStream()); public Assembly[] GetAssemblies() => Array.Empty<Assembly>(); public IIsolatedStorageFile? GetUserStoreForApplication() => null; public void QuitApplication() { } public SizeRequest GetNativeSize(VisualElement view, double widthConstraint, double heightConstraint) => default; } }
29.730769
121
0.691462
[ "MIT" ]
Kahbazi/maui
src/Controls/samples/Controls.Sample.Tests/MockPlatformServices.cs
1,548
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Abstractions.Serialization; using Abstractions.DB; using Abstractions.Models; namespace DB { /// <summary> /// Unit of work for ProcessingData logic. /// </summary> public class ProcessingDataUnitOfWork : UnitOfWork<OutboxContext>, IProcessingDataUnitOfWork { /// <summary> /// Creates <see cref="ProcessingDataUnitOfWork"/>. /// </summary> /// <param name="context">Databaes contex.</param> /// <param name="logger">Logger.</param> /// <param name="serializer">Serializer.</param> public ProcessingDataUnitOfWork( OutboxContext context, ILogger<ProcessingDataUnitOfWork> logger, ISerializer<IProcessingData> serializer) : base(context, System.Data.IsolationLevel.Serializable, logger) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); } /// <inheritdoc/> public async Task ProcessDataAsync(IProcessingData data, CancellationToken cancellationToken = default) { if (data is null) { throw new ArgumentNullException(nameof(data)); } ThrowIfDisposed(); _logger.LogInformation("Starting process {@data}.", data); var item = await _context.ProcessingData.SingleOrDefaultAsync(x => x.Id == data.Id, cancellationToken).ConfigureAwait(false); if (item is not null) { _logger.LogInformation("Updating exists data from {oldValue} => {newValue}.", item.Value, data.Value); item.Value = data.Value; } else { _logger.LogInformation("Creating new data item."); _context.ProcessingData.Add(new ProcessingData { Id = data.Id, Value = data.Value }); } _context.OutboxMessages.Add(new OutboxMessage() { MessageType = OutboxMessageType.ProcessingDataMessage, OccurredOn = DateTime.UtcNow, Body = _serializer.Serialize(data) }); } private readonly ISerializer<IProcessingData> _serializer; } }
33.013889
137
0.583929
[ "MIT" ]
ntulenev/SimpleTransactionalOutbox
src/DB/ProcessingDataUnitOfWork.cs
2,379
C#
// https://docs.microsoft.com/en-us/visualstudio/modeling/t4-include-directive?view=vs-2017 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Runtime.CompilerServices; using Microsoft.Bot.Solutions.Dialogs; namespace ToDoSkill.Dialogs.MarkToDo.Resources { /// <summary> /// Contains bot responses. /// </summary> public static class MarkToDoResponses { private static readonly ResponseManager _responseManager; static MarkToDoResponses() { var dir = Path.GetDirectoryName(typeof(MarkToDoResponses).Assembly.Location); var resDir = Path.Combine(dir, @"Dialogs\MarkToDo\Resources"); _responseManager = new ResponseManager(resDir, "MarkToDoResponses"); } // Generated accessors public static BotResponse AfterTaskCompleted => GetBotResponse(); public static BotResponse AfterAllTasksCompleted => GetBotResponse(); public static BotResponse ListTypePrompt => GetBotResponse(); public static BotResponse AskTaskIndex => GetBotResponse(); public static BotResponse CompleteAnotherTaskPrompt => GetBotResponse(); private static BotResponse GetBotResponse([CallerMemberName] string propertyName = null) { return _responseManager.GetBotResponse(propertyName); } } }
35.425
96
0.704305
[ "MIT" ]
AllcryptoquickDevelopment/AI
solutions/Virtual-Assistant/src/csharp/skills/todoskill/todoskill/Dialogs/MarkToDo/Resources/MarkToDoResponses.cs
1,419
C#
using System; namespace _05_Birthday_Party { class Program { static void Main(string[] args) { double rent = double.Parse(Console.ReadLine()); double cakePrice = rent * 0.20; double drinks = cakePrice - (cakePrice * 0.45); double animatorPrice = rent / 3; double budget = rent + cakePrice + drinks + animatorPrice; Console.WriteLine(budget); } } }
25.444444
70
0.556769
[ "MIT" ]
NeSh74/Programing-Basic-CSharp-October-2020
02_First Steps In Coding - Exercise/05_Birthday_Party/Program.cs
460
C#
using System.Collections.Generic; using UnityEngine; public class WeightedRandom { private float[] weights; private float[] additiveWeights; private readonly int count; private bool calculatedAdditiveWeights; public WeightedRandom(params float[] weights) { count = weights.Length; this.weights = new float[count]; for (var i = 0; i < count; i++) { this.weights[i] = weights[i]; } calculatedAdditiveWeights = false; } public void NormalizeWeights() { var weightSum = 0f; for (var i = 0; i < count; i++) { weightSum += weights[i]; } var multiplier = 1f / weightSum; for (var i = 0; i < count; i++) { weights[i] *= multiplier; } if(calculatedAdditiveWeights) CalculateAdditiveWeights(); } public void CalculateAdditiveWeights() { additiveWeights = new float[count]; additiveWeights[0] = weights[0]; for (var i = 1; i < count; i++) { additiveWeights[i] = additiveWeights[i - 1] + weights[i]; } calculatedAdditiveWeights = true; } public int Value() { float[] array = weights; if (calculatedAdditiveWeights) array = additiveWeights; var randomValue = Rand.Value; for (var i = 0; i < count-1; i++) { if (randomValue < array[i]) return i; } return count - 1; } }
27.166667
69
0.563054
[ "MIT" ]
TeodorVecerdi/saxion_procedural_art
Assets/Procedural Art/Scripts/Misc/WeightedRandom.cs
1,467
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.iservice.ccm.ols.chatrecord.query /// </summary> public class AlipayIserviceCcmOlsChatrecordQueryRequest : IAlipayRequest<AlipayIserviceCcmOlsChatrecordQueryResponse> { /// <summary> /// 查询某通在线服务的聊天记录 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.iservice.ccm.ols.chatrecord.query"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.724638
121
0.542456
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayIserviceCcmOlsChatrecordQueryRequest.cs
3,302
C#
// Copyright(c) 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Collections.Generic; using System.Linq; namespace GoogleHomeAspNetCoreDemoServer.Dialogflow.Intents.Vision { /// <summary> /// Base class for Vision API related intent handlers. /// </summary> public abstract class BaseVisionHandler : BaseHandler { /// <summary> /// Initializes class with the conversation. /// </summary> /// <param name="conversation">Conversation</param> public BaseVisionHandler(Conversation conversation) : base(conversation) { } /// <summary> /// Helper method to convert a list into a comma separated string. /// </summary> /// <param name="col">List to process</param> /// <param name="nonEmptyPrefix">The prefix to add when the list is not empty</param> /// <param name="onEmpty">The string to return when the list is empty.</param> /// <returns></returns> protected static string CombineList(IReadOnlyList<string> col, string nonEmptyPrefix, string onEmpty) { if (col == null || col.Count == 0) return onEmpty; if (col.Count == 1) return $"{nonEmptyPrefix} {col[0]}"; return $"{nonEmptyPrefix} {string.Join(", ", col.Take(col.Count - 1))}, and {col.Last()}"; } } }
38.673469
109
0.651715
[ "ECL-2.0", "Apache-2.0" ]
AdrianaDJ/dotnet-docs-samples
applications/googlehome-meets-dotnetcontainers/GoogleHomeAspNetCoreDemoServer/Dialogflow/Intents/Vision/BaseVisionHandler.cs
1,897
C#
using System; using System.Reflection; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.SlashCommands; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MomentumDiscordBot.Models; using MomentumDiscordBot.Utilities; using Serilog; using ILogger = Serilog.ILogger; namespace MomentumDiscordBot { public class Bot { private readonly Configuration _config; private readonly DiscordShardedClient _discordClient; private readonly ILogger _logger; public Bot(Configuration config, ILogger logger) { _config = config; _logger = logger; var logFactory = new LoggerFactory().AddSerilog(logger); _discordClient = new DiscordShardedClient(new DiscordConfiguration { Token = _config.BotToken, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.None, LoggerFactory = logFactory, MessageCacheSize = 512, Intents = DiscordIntents.All }); var slash = _discordClient.UseSlashCommandsAsync(new SlashCommandsConfiguration { Services = new ServiceCollection().AddSingleton<Random>().BuildServiceProvider() }); var services = BuildServiceProvider(); services.InitializeMicroservices(Assembly.GetEntryAssembly()); } private IServiceProvider BuildServiceProvider() => new ServiceCollection() .AddSingleton(_config) .AddSingleton(_logger) .AddSingleton(_discordClient) .InjectMicroservices(Assembly.GetEntryAssembly()) .BuildServiceProvider(); public async Task StartAsync() => await _discordClient.StartAsync(); } }
32.576271
96
0.633715
[ "MIT" ]
vDokkaebi/discord-bot
MomentumDiscordBot/Bot.cs
1,924
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Zoo.Web { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.518519
70
0.641509
[ "MIT" ]
MomchilAngelovv/ZooTask
Zoo/Zoo.Web/Program.cs
689
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 Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.imm.Model.V20170906 { public class ListTagSetsResponse : AcsResponse { private string requestId; private string nextMarker; private List<ListTagSets_SetsItem> sets; public string RequestId { get { return requestId; } set { requestId = value; } } public string NextMarker { get { return nextMarker; } set { nextMarker = value; } } public List<ListTagSets_SetsItem> Sets { get { return sets; } set { sets = value; } } public class ListTagSets_SetsItem { private string setId; private string status; private long? photos; private string createTime; private string modifyTime; public string SetId { get { return setId; } set { setId = value; } } public string Status { get { return status; } set { status = value; } } public long? Photos { get { return photos; } set { photos = value; } } public string CreateTime { get { return createTime; } set { createTime = value; } } public string ModifyTime { get { return modifyTime; } set { modifyTime = value; } } } } }
16.300699
63
0.587302
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/ListTagSetsResponse.cs
2,331
C#
using System; using System.Collections.Generic; using System.Text; namespace P01.Stream_Progress { public class StreamProgressInfo { private IStreamble stream; // If we want to stream a music file, we can't public StreamProgressInfo(IStreamble stream) { this.stream = stream; } public int CalculateCurrentPercent() { return (this.stream.BytesSent * 100) / this.stream.Length; } } }
21.130435
70
0.613169
[ "MIT" ]
Alexxx2207/CSharpOOP
SOLID/P01.Stream_Progress/StreamProgressInfo.cs
488
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Pinpoint.Model { /// <summary> /// Custom attibute dimension /// </summary> public partial class AttributeDimension { private AttributeType _attributeType; private List<string> _values = new List<string>(); /// <summary> /// Gets and sets the property AttributeType. The type of dimension:INCLUSIVE – Endpoints /// that match the criteria are included in the segment.EXCLUSIVE – Endpoints that match /// the criteria are excluded from the segment. /// </summary> public AttributeType AttributeType { get { return this._attributeType; } set { this._attributeType = value; } } // Check to see if AttributeType property is set internal bool IsSetAttributeType() { return this._attributeType != null; } /// <summary> /// Gets and sets the property Values. The criteria values for the segment dimension. /// Endpoints with matching attribute values are included or excluded from the segment, /// depending on the setting for Type. /// </summary> public List<string> Values { get { return this._values; } set { this._values = value; } } // Check to see if Values property is set internal bool IsSetValues() { return this._values != null && this._values.Count > 0; } } }
32.383562
106
0.646362
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/AttributeDimension.cs
2,368
C#
using System.Windows.Forms; using RaynMaker.Modules.Import.Documents; namespace RaynMaker.Modules.Import.Design { public class HtmlMarkupAutomationProvider { public static void SimulateClickOn( HtmlDocument document, string clickedElementId ) { document.Body.SetAttribute( "rym_clicked_on", clickedElementId ); document.GetElementById( clickedElementId ).InvokeMember( "Click" ); document.Body.SetAttribute( "rym_clicked_on", string.Empty ); } public static HtmlElement GetClickedElement( HtmlDocument document ) { var id = document.Body.GetAttribute( "rym_clicked_on" ); if ( string.IsNullOrEmpty( id ) ) { return null; } return document.GetElementById( id ); } public static bool IsMarked( IHtmlElement element ) { return HtmlElementMarker.IsMarked( element ); } } }
29.911765
93
0.602753
[ "BSD-3-Clause" ]
Tball40/RaynMaker
src/RaynMaker.Modules.Import/Design/HtmlMarkupAutomationProvider.cs
1,019
C#
public class Program { static int TheBomb = 90; public static void Method1(ref int i, ref string str) { System.Console.WriteLine(i); System.Console.WriteLine(str); i += 32; str = "Test2"; } public static void Main() { int i = 8; string str = "Test1"; System.Console.WriteLine(i); System.Console.WriteLine(str); Method1(ref i, ref str); System.Console.WriteLine(i); System.Console.WriteLine(str); System.Console.WriteLine(TheBomb); Method1(ref TheBomb, ref str); System.Console.WriteLine(TheBomb); } }
21.566667
57
0.57187
[ "MIT" ]
FrankLIKE/SharpNative
Tests/Basics/CallByReferenceTest.cs
649
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsVarARequest. /// </summary> public partial class WorkbookFunctionsVarARequest : BaseRequest, IWorkbookFunctionsVarARequest { /// <summary> /// Constructs a new WorkbookFunctionsVarARequest. /// </summary> public WorkbookFunctionsVarARequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsVarARequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsVarARequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsVarARequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsVarARequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
34.609195
153
0.577881
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsVarARequest.cs
3,011
C#
using MatterHackers.VectorMath; //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System.Collections.Generic; namespace MatterHackers.Agg.VertexSource { //------------------------------------------------------------null_markers public struct null_markers : IMarkers { public void remove_all() { } public void add_vertex(double x, double y, ShapePath.FlagsAndCommand unknown) { } public void prepare_src() { } public void rewind(int unknown) { } public ShapePath.FlagsAndCommand vertex(ref double x, ref double y) { return ShapePath.FlagsAndCommand.CommandStop; } }; //------------------------------------------------------conv_adaptor_vcgen public class VertexSourceAdapter : IVertexSourceProxy { private IGenerator generator; private IMarkers markers; private status m_status; private ShapePath.FlagsAndCommand m_last_cmd; private double m_start_x; private double m_start_y; public IVertexSource VertexSource { get; set; } private enum status { initial, accumulate, generate }; public VertexSourceAdapter(IVertexSource vertexSource, IGenerator generator) { markers = new null_markers(); this.VertexSource = vertexSource; this.generator = generator; m_status = status.initial; } public VertexSourceAdapter(IVertexSource vertexSource, IGenerator generator, IMarkers markers) : this(vertexSource, generator) { this.markers = markers; } private void Attach(IVertexSource vertexSource) { this.VertexSource = vertexSource; } protected IGenerator GetGenerator() { return generator; } private IMarkers GetMarkers() { return markers; } public IEnumerable<VertexData> Vertices() { rewind(0); ShapePath.FlagsAndCommand command = ShapePath.FlagsAndCommand.CommandStop; do { double x; double y; command = vertex(out x, out y); yield return new VertexData(command, new Vector2(x, y)); } while (command != ShapePath.FlagsAndCommand.CommandStop); } public void rewind(int path_id) { VertexSource.rewind(path_id); m_status = status.initial; } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { x = 0; y = 0; ShapePath.FlagsAndCommand command = ShapePath.FlagsAndCommand.CommandStop; bool done = false; while (!done) { switch (m_status) { case status.initial: markers.remove_all(); m_last_cmd = VertexSource.vertex(out m_start_x, out m_start_y); m_status = status.accumulate; goto case status.accumulate; case status.accumulate: if (ShapePath.is_stop(m_last_cmd)) { return ShapePath.FlagsAndCommand.CommandStop; } generator.RemoveAll(); generator.AddVertex(m_start_x, m_start_y, ShapePath.FlagsAndCommand.CommandMoveTo); markers.add_vertex(m_start_x, m_start_y, ShapePath.FlagsAndCommand.CommandMoveTo); for (; ; ) { command = VertexSource.vertex(out x, out y); //DebugFile.Print("x=" + x.ToString() + " y=" + y.ToString() + "\n"); if (ShapePath.is_vertex(command)) { m_last_cmd = command; if (ShapePath.is_move_to(command)) { m_start_x = x; m_start_y = y; break; } generator.AddVertex(x, y, command); markers.add_vertex(x, y, ShapePath.FlagsAndCommand.CommandLineTo); } else { if (ShapePath.is_stop(command)) { m_last_cmd = ShapePath.FlagsAndCommand.CommandStop; break; } if (ShapePath.is_end_poly(command)) { generator.AddVertex(x, y, command); break; } } } generator.Rewind(0); m_status = status.generate; goto case status.generate; case status.generate: command = generator.Vertex(ref x, ref y); //DebugFile.Print("x=" + x.ToString() + " y=" + y.ToString() + "\n"); if (ShapePath.is_stop(command)) { m_status = status.accumulate; break; } done = true; break; } } return command; } } }
25.5
96
0.60866
[ "BSD-2-Clause" ]
Frank-Buss/utest
Assets/agg/VertexSource/VertexSourceAdapter.cs
4,896
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using Remotion.Linq.Parsing.ExpressionVisitors.Transformation; namespace Couchbase.Linq.QueryGeneration.ExpressionTransformers { /// <summary> /// Recognizes == and != comparisons between a enumeration property and an enumeration constant. /// By default, LINQ does this comparison using the base type of the enumeration, converting the /// enumeration property to the base type and comparing to the raw number. This converts the /// comparison to be directly between two values of the enumeration type. This allows /// <see cref="N1QlExpressionTreeVisitor"/> to handle different serialization approaches for the /// enumeration constant. /// </summary> internal class EnumComparisonExpressionTransformer : IExpressionTransformer<BinaryExpression> { public ExpressionType[] SupportedExpressionTypes { get { return new[] { ExpressionType.Equal, ExpressionType.NotEqual }; } } public Expression Transform(BinaryExpression expression) { Expression newExpression = null; if (IsEnumConversion(expression.Left) && (expression.Right.NodeType == ExpressionType.Constant)) { newExpression = MakeEnumComparisonExpression( ((UnaryExpression) expression.Left).Operand, ((ConstantExpression)expression.Right).Value, expression.NodeType); } else if (IsEnumConversion(expression.Right) && (expression.Left.NodeType == ExpressionType.Constant)) { newExpression = MakeEnumComparisonExpression( ((UnaryExpression)expression.Right).Operand, ((ConstantExpression)expression.Left).Value, expression.NodeType); } return newExpression ?? expression; } private bool IsEnumConversion(Expression expression) { if (expression.NodeType != ExpressionType.Convert) { return false; } var convertExpression = (UnaryExpression) expression; var type = convertExpression.Operand.Type; // If type is Nullable<T>, extract the inner type to see if it is an enumeration if (type.GetTypeInfo().IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))) { type = type.GetGenericArguments()[0]; } return type.GetTypeInfo().IsEnum; } private BinaryExpression MakeEnumComparisonExpression(Expression operand, object enumValue, ExpressionType comparisonType) { var isNullable = false; var enumType = operand.Type; // If type is Nullable<T>, the inner type is the enumeration type if (enumType.GetTypeInfo().IsGenericType && (enumType.GetGenericTypeDefinition() == typeof (Nullable<>))) { enumType = enumType.GetGenericArguments()[0]; isNullable = true; } string name = null; if (enumValue != null) { // enumValue == null if this is a Nullable type and it doesn't have a value name = Enum.GetName(enumType, enumValue); if (name == null) { // Don't bother converting for undefined enumeration values, we'll use the original expression instead return null; } } Expression comparisonValue; if (name != null) { comparisonValue = Expression.Constant(enumType.GetTypeInfo().GetField(name).GetValue(null)); if (isNullable) { comparisonValue = Expression.Convert(comparisonValue, typeof(Nullable<>).MakeGenericType(enumType)); } } else { comparisonValue = Expression.Constant(null); } return Expression.MakeBinary(comparisonType, operand, comparisonValue); } } }
36.365854
122
0.581265
[ "Apache-2.0" ]
RossMerr/CouchbaseNetLinq
Src/src/Couchbase.Linq/QueryGeneration/ExpressionTransformers/EnumComparisonExpressionTransformer.cs
4,475
C#
namespace RememBeer.Data.Migrations { using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { this.CreateTable( "dbo.BeerReviews", c => new { Id = c.Int(nullable: false, identity: true), BeerId = c.Int(nullable: false), UserId = c.String(nullable: false, maxLength: 128), Overall = c.Int(nullable: false), Look = c.Int(nullable: false), Smell = c.Int(nullable: false), Taste = c.Int(nullable: false), Description = c.String(nullable: false), CreatedAt = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"), ModifiedAt = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"), IsPublic = c.Boolean(nullable: false, defaultValue: true), IsDeleted = c.Boolean(nullable: false, defaultValue: false), Place = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Beers", t => t.BeerId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.BeerId) .Index(t => t.UserId); this.CreateTable( "dbo.Beers", c => new { Id = c.Int(nullable: false, identity: true), BeerTypeId = c.Int(nullable: false), Name = c.String(nullable: false), BreweryId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.BeerTypes", t => t.BeerTypeId, cascadeDelete: true) .ForeignKey("dbo.Breweries", t => t.BreweryId, cascadeDelete: true) .Index(t => t.BeerTypeId) .Index(t => t.BreweryId); this.CreateTable( "dbo.BeerTypes", c => new { Id = c.Int(nullable: false, identity: true), Type = c.String(nullable: false), }) .PrimaryKey(t => t.Id); this.CreateTable( "dbo.Breweries", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Description = c.String(nullable: false), Country = c.String(nullable: false), }) .PrimaryKey(t => t.Id); this.CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); this.CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); this.CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); this.CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); this.CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { this.DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); this.DropForeignKey("dbo.BeerReviews", "UserId", "dbo.AspNetUsers"); this.DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); this.DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); this.DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); this.DropForeignKey("dbo.BeerReviews", "BeerId", "dbo.Beers"); this.DropForeignKey("dbo.Beers", "BreweryId", "dbo.Breweries"); this.DropForeignKey("dbo.Beers", "BeerTypeId", "dbo.BeerTypes"); this.DropIndex("dbo.AspNetRoles", "RoleNameIndex"); this.DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); this.DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); this.DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); this.DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); this.DropIndex("dbo.AspNetUsers", "UserNameIndex"); this.DropIndex("dbo.Beers", new[] { "BreweryId" }); this.DropIndex("dbo.Beers", new[] { "BeerTypeId" }); this.DropIndex("dbo.BeerReviews", new[] { "UserId" }); this.DropIndex("dbo.BeerReviews", new[] { "BeerId" }); this.DropTable("dbo.AspNetRoles"); this.DropTable("dbo.AspNetUserRoles"); this.DropTable("dbo.AspNetUserLogins"); this.DropTable("dbo.AspNetUserClaims"); this.DropTable("dbo.AspNetUsers"); this.DropTable("dbo.Breweries"); this.DropTable("dbo.BeerTypes"); this.DropTable("dbo.Beers"); this.DropTable("dbo.BeerReviews"); } } }
52.513966
109
0.396064
[ "MIT" ]
J0hnyBG/RememBeerMe
src/RememBeer.Data/Migrations/201702081137574_Initial.cs
9,400
C#
//----------------------------------------------------------------------------- // Filename: DtlsSrtpServer.cs // // Description: This class represents the DTLS SRTP server connection handler. // // Derived From: // https://github.com/RestComm/media-core/blob/master/rtp/src/main/java/org/restcomm/media/core/rtp/crypto/DtlsSrtpServer.java // // Author(s): // Rafael Soares (raf.csoares@kyubinteractive.com) // // History: // 01 Jul 2020 Rafael Soares Created. // // License: // BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. // Original Source: AGPL-3.0 License //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Tls; using Org.BouncyCastle.Utilities; using SIPSorcery.Sys; namespace SIPSorcery.Net { public enum AlertLevelsEnum : byte { Warning = 1, Fatal = 2 } public enum AlertTypesEnum : byte { close_notify = 0, unexpected_message = 10, bad_record_mac = 20, decryption_failed = 21, record_overflow = 22, decompression_failure = 30, handshake_failure = 40, no_certificate = 41, bad_certificate = 42, unsupported_certificate = 43, certificate_revoked = 44, certificate_expired = 45, certificate_unknown = 46, illegal_parameter = 47, unknown_ca = 48, access_denied = 49, decode_error = 50, decrypt_error = 51, export_restriction = 60, protocol_version = 70, insufficient_security = 71, internal_error = 80, inappropriate_fallback = 86, user_canceled = 90, no_renegotiation = 100, unsupported_extension = 110, certificate_unobtainable = 111, unrecognized_name = 112, bad_certificate_status_response = 113, bad_certificate_hash_value = 114, unknown_psk_identity = 115, unknown = 255 } public interface IDtlsSrtpPeer { event Action<AlertLevelsEnum, AlertTypesEnum, string> OnAlert; SrtpPolicy GetSrtpPolicy(); SrtpPolicy GetSrtcpPolicy(); byte[] GetSrtpMasterServerKey(); byte[] GetSrtpMasterServerSalt(); byte[] GetSrtpMasterClientKey(); byte[] GetSrtpMasterClientSalt(); bool IsClient(); Certificate GetRemoteCertificate(); } public class DtlsSrtpServer : DefaultTlsServer, IDtlsSrtpPeer { private static readonly ILogger logger = Log.Logger; Certificate mCertificateChain = null; AsymmetricKeyParameter mPrivateKey = null; private RTCDtlsFingerprint mFingerPrint; //private AlgorithmCertificate algorithmCertificate; public Certificate ClientCertificate { get; private set; } // the server response to the client handshake request // http://tools.ietf.org/html/rfc5764#section-4.1.1 private UseSrtpData serverSrtpData; // Asymmetric shared keys derived from the DTLS handshake and used for the SRTP encryption/ private byte[] srtpMasterClientKey; private byte[] srtpMasterServerKey; private byte[] srtpMasterClientSalt; private byte[] srtpMasterServerSalt; byte[] masterSecret = null; // Policies private SrtpPolicy srtpPolicy; private SrtpPolicy srtcpPolicy; private int[] cipherSuites; /// <summary> /// Parameters: /// - alert level, /// - alert type, /// - alert description. /// </summary> public event Action<AlertLevelsEnum, AlertTypesEnum, string> OnAlert; public DtlsSrtpServer() : this((Certificate)null, null) { } public DtlsSrtpServer(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) : this(DtlsUtils.LoadCertificateChain(certificate), DtlsUtils.LoadPrivateKeyResource(certificate)) { } public DtlsSrtpServer(string certificatePath, string keyPath) : this(new string[] { certificatePath }, keyPath) { } public DtlsSrtpServer(string[] certificatesPath, string keyPath) : this(DtlsUtils.LoadCertificateChain(certificatesPath), DtlsUtils.LoadPrivateKeyResource(keyPath)) { } public DtlsSrtpServer(Certificate certificateChain, AsymmetricKeyParameter privateKey) { if (certificateChain == null && privateKey == null) { (certificateChain, privateKey) = DtlsUtils.CreateSelfSignedTlsCert(); } this.cipherSuites = base.GetCipherSuites(); this.mPrivateKey = privateKey; mCertificateChain = certificateChain; //Generate FingerPrint var certificate = mCertificateChain.GetCertificateAt(0); this.mFingerPrint = certificate != null ? DtlsUtils.Fingerprint(certificate) : null; } public RTCDtlsFingerprint Fingerprint { get { return mFingerPrint; } } public AsymmetricKeyParameter PrivateKey { get { return mPrivateKey; } } public Certificate CertificateChain { get { return mCertificateChain; } } protected override ProtocolVersion MaximumVersion { get { return ProtocolVersion.DTLSv12; } } protected override ProtocolVersion MinimumVersion { get { return ProtocolVersion.DTLSv10; } } public override int GetSelectedCipherSuite() { /* * TODO RFC 5246 7.4.3. In order to negotiate correctly, the server MUST check any candidate cipher suites against the * "signature_algorithms" extension before selecting them. This is somewhat inelegant but is a compromise designed to * minimize changes to the original cipher suite design. */ /* * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these extensions MUST use the client's * enumerated capabilities to guide its selection of an appropriate cipher suite. One of the proposed ECC cipher suites * must be negotiated only if the server can successfully complete the handshake while using the curves and point * formats supported by the client [...]. */ bool eccCipherSuitesEnabled = SupportsClientEccCapabilities(this.mNamedCurves, this.mClientECPointFormats); int[] cipherSuites = GetCipherSuites(); for (int i = 0; i < cipherSuites.Length; ++i) { int cipherSuite = cipherSuites[i]; if (Arrays.Contains(this.mOfferedCipherSuites, cipherSuite) && (eccCipherSuitesEnabled || !TlsEccUtilities.IsEccCipherSuite(cipherSuite)) && TlsUtilities.IsValidCipherSuiteForVersion(cipherSuite, mServerVersion)) { return this.mSelectedCipherSuite = cipherSuite; } } throw new TlsFatalAlert(AlertDescription.handshake_failure); } public override CertificateRequest GetCertificateRequest() { List<SignatureAndHashAlgorithm> serverSigAlgs = new List<SignatureAndHashAlgorithm>(); if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mServerVersion)) { byte[] hashAlgorithms = new byte[] { HashAlgorithm.sha512, HashAlgorithm.sha384, HashAlgorithm.sha256, HashAlgorithm.sha224, HashAlgorithm.sha1 }; byte[] signatureAlgorithms = new byte[] { SignatureAlgorithm.rsa, SignatureAlgorithm.ecdsa }; serverSigAlgs = new List<SignatureAndHashAlgorithm>(); for (int i = 0; i < hashAlgorithms.Length; ++i) { for (int j = 0; j < signatureAlgorithms.Length; ++j) { serverSigAlgs.Add(new SignatureAndHashAlgorithm(hashAlgorithms[i], signatureAlgorithms[j])); } } } return new CertificateRequest(new byte[] { ClientCertificateType.rsa_sign }, serverSigAlgs, null); } public override void NotifyClientCertificate(Certificate clientCertificate) { ClientCertificate = clientCertificate; } public override IDictionary GetServerExtensions() { Hashtable serverExtensions = (Hashtable)base.GetServerExtensions(); if (TlsSRTPUtils.GetUseSrtpExtension(serverExtensions) == null) { if (serverExtensions == null) { serverExtensions = new Hashtable(); } TlsSRTPUtils.AddUseSrtpExtension(serverExtensions, serverSrtpData); } return serverExtensions; } public override void ProcessClientExtensions(IDictionary clientExtensions) { base.ProcessClientExtensions(clientExtensions); // set to some reasonable default value int chosenProfile = SrtpProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80; UseSrtpData clientSrtpData = TlsSRTPUtils.GetUseSrtpExtension(clientExtensions); foreach (int profile in clientSrtpData.ProtectionProfiles) { switch (profile) { case SrtpProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_32: case SrtpProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80: case SrtpProtectionProfile.SRTP_NULL_HMAC_SHA1_32: case SrtpProtectionProfile.SRTP_NULL_HMAC_SHA1_80: chosenProfile = profile; break; } } // server chooses a mutually supported SRTP protection profile // http://tools.ietf.org/html/draft-ietf-avt-dtls-srtp-07#section-4.1.2 int[] protectionProfiles = { chosenProfile }; // server agrees to use the MKI offered by the client serverSrtpData = new UseSrtpData(protectionProfiles, clientSrtpData.Mki); } public SrtpPolicy GetSrtpPolicy() { return srtpPolicy; } public SrtpPolicy GetSrtcpPolicy() { return srtcpPolicy; } public byte[] GetSrtpMasterServerKey() { return srtpMasterServerKey; } public byte[] GetSrtpMasterServerSalt() { return srtpMasterServerSalt; } public byte[] GetSrtpMasterClientKey() { return srtpMasterClientKey; } public byte[] GetSrtpMasterClientSalt() { return srtpMasterClientSalt; } public override void NotifyHandshakeComplete() { //Copy master Secret (will be inaccessible after this call) masterSecret = new byte[mContext.SecurityParameters.MasterSecret != null ? mContext.SecurityParameters.MasterSecret.Length : 0]; Buffer.BlockCopy(mContext.SecurityParameters.MasterSecret, 0, masterSecret, 0, masterSecret.Length); //Prepare Srtp Keys (we must to it here because master key will be cleared after that) PrepareSrtpSharedSecret(); } public bool IsClient() { return false; } protected override TlsSignerCredentials GetECDsaSignerCredentials() { return DtlsUtils.LoadSignerCredentials(mContext, mCertificateChain, mPrivateKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)); } protected override TlsEncryptionCredentials GetRsaEncryptionCredentials() { return DtlsUtils.LoadEncryptionCredentials(mContext, mCertificateChain, mPrivateKey); } protected override TlsSignerCredentials GetRsaSignerCredentials() { /* * TODO Note that this code fails to provide default value for the client supported * algorithms if it wasn't sent. */ SignatureAndHashAlgorithm signatureAndHashAlgorithm = null; IList sigAlgs = mSupportedSignatureAlgorithms; if (sigAlgs != null) { foreach (var sigAlgUncasted in sigAlgs) { SignatureAndHashAlgorithm sigAlg = sigAlgUncasted as SignatureAndHashAlgorithm; if (sigAlg != null && sigAlg.Signature == SignatureAlgorithm.rsa) { signatureAndHashAlgorithm = sigAlg; break; } } if (signatureAndHashAlgorithm == null) { return null; } } return DtlsUtils.LoadSignerCredentials(mContext, mCertificateChain, mPrivateKey, signatureAndHashAlgorithm); } protected virtual void PrepareSrtpSharedSecret() { //Set master secret back to security parameters (only works in old bouncy castle versions) //mContext.SecurityParameters.masterSecret = masterSecret; SrtpParameters srtpParams = SrtpParameters.GetSrtpParametersForProfile(serverSrtpData.ProtectionProfiles[0]); int keyLen = srtpParams.GetCipherKeyLength(); int saltLen = srtpParams.GetCipherSaltLength(); srtpPolicy = srtpParams.GetSrtpPolicy(); srtcpPolicy = srtpParams.GetSrtcpPolicy(); srtpMasterClientKey = new byte[keyLen]; srtpMasterServerKey = new byte[keyLen]; srtpMasterClientSalt = new byte[saltLen]; srtpMasterServerSalt = new byte[saltLen]; // 2* (key + salt length) / 8. From http://tools.ietf.org/html/rfc5764#section-4-2 // No need to divide by 8 here since lengths are already in bits byte[] sharedSecret = GetKeyingMaterial(2 * (keyLen + saltLen)); /* * * See: http://tools.ietf.org/html/rfc5764#section-4.2 * * sharedSecret is an equivalent of : * * struct { * client_write_SRTP_master_key[SRTPSecurityParams.master_key_len]; * server_write_SRTP_master_key[SRTPSecurityParams.master_key_len]; * client_write_SRTP_master_salt[SRTPSecurityParams.master_salt_len]; * server_write_SRTP_master_salt[SRTPSecurityParams.master_salt_len]; * } ; * * Here, client = local configuration, server = remote. * NOTE [ivelin]: 'local' makes sense if this code is used from a DTLS SRTP client. * Here we run as a server, so 'local' referring to the client is actually confusing. * * l(k) = KEY length * s(k) = salt length * * So we have the following repartition : * l(k) 2*l(k)+s(k) * 2*l(k) 2*(l(k)+s(k)) * +------------------------+------------------------+---------------+-------------------+ * + local key | remote key | local salt | remote salt | * +------------------------+------------------------+---------------+-------------------+ */ Buffer.BlockCopy(sharedSecret, 0, srtpMasterClientKey, 0, keyLen); Buffer.BlockCopy(sharedSecret, keyLen, srtpMasterServerKey, 0, keyLen); Buffer.BlockCopy(sharedSecret, 2 * keyLen, srtpMasterClientSalt, 0, saltLen); Buffer.BlockCopy(sharedSecret, (2 * keyLen + saltLen), srtpMasterServerSalt, 0, saltLen); } protected byte[] GetKeyingMaterial(int length) { return mContext.ExportKeyingMaterial(ExporterLabel.dtls_srtp, null, length); } protected override int[] GetCipherSuites() { int[] cipherSuites = new int[this.cipherSuites.Length]; for (int i = 0; i < this.cipherSuites.Length; i++) { cipherSuites[i] = this.cipherSuites[i]; } return cipherSuites; } public Certificate GetRemoteCertificate() { return ClientCertificate; } public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) { string description = null; if (message != null) { description += message; } if (cause != null) { description += cause; } if (alertDescription == AlertTypesEnum.close_notify.GetHashCode()) { logger.LogDebug($"DTLS server raised close notify: {AlertLevel.GetText(alertLevel)}, {AlertDescription.GetText(alertDescription)}, {description}."); } else { logger.LogWarning($"DTLS server raised unexpected alert: {AlertLevel.GetText(alertLevel)}, {AlertDescription.GetText(alertDescription)}, {description}."); } } public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) { string description = AlertDescription.GetText(alertDescription); AlertLevelsEnum level = AlertLevelsEnum.Warning; AlertTypesEnum alertType = AlertTypesEnum.unknown; if (Enum.IsDefined(typeof(AlertLevelsEnum), alertLevel)) { level = (AlertLevelsEnum)alertLevel; } if (Enum.IsDefined(typeof(AlertTypesEnum), alertDescription)) { alertType = (AlertTypesEnum)alertDescription; } if (alertType == AlertTypesEnum.close_notify) { logger.LogDebug($"DTLS server received close notification: {AlertLevel.GetText(alertLevel)}, {description}."); } else { logger.LogWarning($"DTLS server received unexpected alert: {AlertLevel.GetText(alertLevel)}, {description}."); } OnAlert?.Invoke(level, alertType, description); } /// <summary> /// This override prevents a TLS fault from being generated if a "Client Hello" is received that /// does not support TLS renegotiation (https://tools.ietf.org/html/rfc5746). /// This override is required to be able to complete a DTLS handshake with the Pion WebRTC library, /// see https://github.com/pion/dtls/issues/274. /// </summary> public override void NotifySecureRenegotiation(bool secureRenegotiation) { if (!secureRenegotiation) { logger.LogWarning($"DTLS server received a client handshake without renegotiation support."); } } } }
37.998084
204
0.579027
[ "Apache-2.0" ]
ArcaneDevs/sipsorcery
src/net/DtlsSrtp/DtlsSrtpServer.cs
19,837
C#
using System.Reflection; namespace Uncontainer { /// <summary> /// Represents a type that determines the constructor that will be used to instantiate a particular service implementation. /// </summary> public interface IConstructorResolver { /// <summary> /// Determines which constructor implementation should be used from a given <see cref="IDependencyContainer"/> instance. /// </summary> /// <param name="targetType">The target type that contains list of constructors to be resolved.</param> /// <param name="container">The dependency container that holds the current set of dependencies.</param> /// <returns>An implementation that can instantiate the object associated with the constructor.</returns> IImplementation<ConstructorInfo> ResolveFrom(System.Type targetType, IDependencyContainer container); } }
48.631579
129
0.690476
[ "MIT" ]
philiplaureano/Uncontainer
Uncontainer/IConstructorResolver.cs
926
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class AutomationAccountOperationsExtensions { /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update automation /// account. /// </param> /// <returns> /// The response model for the create or update account operation. /// </returns> public static AutomationAccountCreateOrUpdateResponse CreateOrUpdate(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update automation /// account. /// </param> /// <returns> /// The response model for the create or update account operation. /// </returns> public static Task<AutomationAccountCreateOrUpdateResponse> CreateOrUpdateAsync(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccountName'> /// Required. Automation account name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccountName) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).DeleteAsync(resourceGroupName, automationAccountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccountName'> /// Required. Automation account name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccountName) { return operations.DeleteAsync(resourceGroupName, automationAccountName, CancellationToken.None); } /// <summary> /// Retrieve the account by account name. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the get account operation. /// </returns> public static AutomationAccountGetResponse Get(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).GetAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the account by account name. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the get account operation. /// </returns> public static Task<AutomationAccountGetResponse> GetAsync(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccount) { return operations.GetAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve a list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static AutomationAccountListResponse List(this IAutomationAccountOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static Task<AutomationAccountListResponse> ListAsync(this IAutomationAccountOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Retrieve next list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static AutomationAccountListResponse ListNext(this IAutomationAccountOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static Task<AutomationAccountListResponse> ListNextAsync(this IAutomationAccountOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch automation account. /// </param> /// <returns> /// The response model for the create account operation. /// </returns> public static AutomationAccountPatchResponse Patch(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountPatchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).PatchAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch automation account. /// </param> /// <returns> /// The response model for the create account operation. /// </returns> public static Task<AutomationAccountPatchResponse> PatchAsync(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountPatchParameters parameters) { return operations.PatchAsync(resourceGroupName, parameters, CancellationToken.None); } } }
43.415902
213
0.62323
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ResourceManagement/Automation/AutomationManagement/Generated/AutomationAccountOperationsExtensions.cs
14,197
C#
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Copyright (C) LibreHardwareMonitor and Contributors. // Partial Copyright (C) Michael Möller <mmoeller@openhardwaremonitor.org> and Contributors. // All Rights Reserved. namespace LibreHardwareMonitor.Hardware { public delegate void SensorEventHandler(ISensor sensor); public enum HardwareType { Motherboard, SuperIO, Cpu, Memory, GpuNvidia, GpuAmd, Storage, Network, Cooler } public interface IHardware : IElement { HardwareType HardwareType { get; } Identifier Identifier { get; } string Name { get; set; } IHardware Parent { get; } ISensor[] Sensors { get; } IHardware[] SubHardware { get; } string GetReport(); void Update(); event SensorEventHandler SensorAdded; event SensorEventHandler SensorRemoved; } }
23.553191
110
0.63505
[ "MPL-2.0" ]
Biztactix/LibreHardwareMonitor
LibreHardwareMonitorLib/Hardware/IHardware.cs
1,110
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Shared.Construction { [Serializable] [DataDefinition] public sealed class ConstructionGraphNode { [DataField("actions", serverOnly: true)] private IGraphAction[] _actions = Array.Empty<IGraphAction>(); [DataField("edges")] private ConstructionGraphEdge[] _edges = Array.Empty<ConstructionGraphEdge>(); [ViewVariables] [DataField("node", required: true)] public string Name { get; private set; } = default!; [ViewVariables] public IReadOnlyList<ConstructionGraphEdge> Edges => _edges; [ViewVariables] public IReadOnlyList<IGraphAction> Actions => _actions; [ViewVariables] [DataField("entity")] public string? Entity { get; private set; } public ConstructionGraphEdge? GetEdge(string target) { foreach (var edge in _edges) { if (edge.Target == target) return edge; } return null; } public int? GetEdgeIndex(string target) { for (var i = 0; i < _edges.Length; i++) { var edge = _edges[i]; if (edge.Target == target) return i; } return null; } public bool TryGetEdge(string target, [NotNullWhen(true)] out ConstructionGraphEdge? edge) { return (edge = GetEdge(target)) != null; } } }
27.209677
98
0.577949
[ "MIT" ]
Alainx277/space-station-14
Content.Shared/Construction/ConstructionGraphNode.cs
1,689
C#
using Catalog.Entities; namespace Catalog.Repositories { public interface IProductRepository { Task<IEnumerable<Product>> GetProducts(); Task<Product> GetProduct(string id); Task<IEnumerable<Product>> GetProductByName(string name); Task<IEnumerable<Product>> GetProductByCategory(string categoryName); Task CreateProduct(Product product); Task<bool> UpdateProduct(Product product); Task<bool> DeleteProduct(string id); } }
30.8125
77
0.701826
[ "MIT" ]
AgileMark/MobilePhoneSales
src/services/Catalog/Catalog/Repositories/IProductRepository.cs
495
C#
using System; using NetOffice; namespace NetOffice.WordApi.Enums { /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836958.aspx </remarks> [SupportByVersionAttribute("Word", 12,14,15)] [EntityTypeAttribute(EntityType.IsEnum)] public enum WdStyleSort { /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("Word", 12,14,15)] wdStyleSortByName = 0, /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("Word", 12,14,15)] wdStyleSortRecommended = 1, /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> /// <remarks>2</remarks> [SupportByVersionAttribute("Word", 12,14,15)] wdStyleSortByFont = 2, /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> /// <remarks>3</remarks> [SupportByVersionAttribute("Word", 12,14,15)] wdStyleSortByBasedOn = 3, /// <summary> /// SupportByVersion Word 12, 14, 15 /// </summary> /// <remarks>4</remarks> [SupportByVersionAttribute("Word", 12,14,15)] wdStyleSortByType = 4 } }
27.666667
120
0.620482
[ "MIT" ]
NetOffice/NetOffice
Source/Word/Enums/WdStyleSort.cs
1,328
C#
using System.ComponentModel; namespace Imprint.IO.Runtime { public class ViewModelBase : IViewModelBase { #region Fields private PropertyChangedEventHandler _propertyChanged; private string _name; #endregion #region ** IViewModelBase public event PropertyChangedEventHandler PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } } public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } protected virtual void OnPropertyChanged(string name) { var handler = _propertyChanged; if (handler == null) return; handler(this, new PropertyChangedEventArgs(name)); } public virtual void Dispose() { } #endregion } }
14.811321
58
0.677707
[ "MIT" ]
VallarasuS/Imprint
Imprint.IO.Runtime/Types/ViewModelBase.cs
787
C#
using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using JetBrains.Annotations; using Rsdn.JanusNG.Services; using Rsdn.JanusNG.Services.Connection; namespace Rsdn.JanusNG.Main.ViewModel { [UsedImplicitly] public partial class MainViewModel : INotifyPropertyChanged { private const string _curSelectionVar = "MainForm.CurrentSelectionIDs"; private readonly ApiConnectionService _api; private readonly VarsService _varsService; public MainViewModel(ApiConnectionService api, VarsService varsService, AccountsService accountsService) { _api = api; _varsService = varsService; InitCommands(); Accounts = accountsService .GetAccounts() .Select(a => new AccountViewModel( a, new Command(() => { api.UseStoredAccount(a.ID); CurrentAccount = a; }))) .ToArray(); CurrentAccount = accountsService.GetCurrentAccount(); } public async Task Init() { await LoadForumsAsync(); var selectedIDs = FullMsgID.TryParse(_varsService.GetVar(_curSelectionVar)); if (selectedIDs != null) { var forum = Forums.SelectMany(fg => fg.Forums).FirstOrDefault(f => f.ID == selectedIDs.ForumID); SelectedForum = forum; if (selectedIDs.MessageID.HasValue) { await LoadTopicsAsync(selectedIDs.ForumID); var topic = Topics.FirstOrDefault(t => t.Message.ID == selectedIDs.TopicID.GetValueOrDefault(selectedIDs.MessageID.Value)); if (topic != null) { await LoadRepliesAsync(topic); MessageNode FindMessage(int id, MessageNode m) => m.Message.ID == id ? m : m.Children.Select(mc => FindMessage(id, mc)).FirstOrDefault(mc => mc != null); Message = FindMessage(selectedIDs.MessageID.Value, topic); } } } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
29.657143
110
0.721098
[ "MIT" ]
andrewvk/JanusNG
JanusNG/Main/ViewModel/MainViewModel.cs
2,078
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; #nullable disable namespace Microsoft.Build.Tasks { /// <summary> /// Base class for task that determines the appropriate manifest resource name to /// assign to a given resx or other resource. /// </summary> public abstract class CreateManifestResourceName : TaskExtension { #region Properties internal const string resxFileExtension = ".resx"; internal const string restextFileExtension = ".restext"; internal const string resourcesFileExtension = ".resources"; private ITaskItem[] _resourceFiles; [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Shipped this way in Dev11 Beta (go-live)")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Taskitem", Justification = "Shipped this way in Dev11 Beta (go-live)")] protected Dictionary<string, ITaskItem> itemSpecToTaskitem = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Should the culture name be prepended to the manifest resource name as a directory? /// This is true by default. /// </summary> public bool PrependCultureAsDirectory { get; set; } = true; public bool UseDependentUponConvention { get; set; } protected abstract string SourceFileExtension { get; } /// <summary> /// The possibly dependent resource files. /// </summary> [Required] public ITaskItem[] ResourceFiles { get { ErrorUtilities.VerifyThrowArgumentNull(_resourceFiles, nameof(ResourceFiles)); return _resourceFiles; } set => _resourceFiles = value; } /// <summary> /// Rootnamespace to use for naming. /// </summary> public string RootNamespace { get; set; } = null; /// <summary> /// The resulting manifest names. /// </summary> /// <value></value> [Output] public ITaskItem[] ManifestResourceNames { get; private set; } /// <summary> /// The initial list of resource names, with additional metadata for manifest resource names /// </summary> [Output] public ITaskItem[] ResourceFilesWithManifestResourceNames { get; set; } #endregion /// <summary> /// Method in the derived class that composes the manifest name. /// </summary> /// <param name="fileName">The file name of the dependent (usually a .resx)</param> /// <param name="linkFileName">The name of the file specified by the Link attribute.</param> /// <param name="rootNamespaceName">The root namespace (usually from the project file). May be null</param> /// <param name="dependentUponFileName">The file name of the parent of this dependency. May be null</param> /// <param name="binaryStream">File contents binary stream, may be null</param> /// <returns>Returns the manifest name</returns> protected abstract string CreateManifestName ( string fileName, string linkFileName, string rootNamespaceName, string dependentUponFileName, Stream binaryStream ); /// <summary> /// The derived class chooses whether this is a valid source file to work against. /// Usually, this is just a matter of looking at the file's extension. /// </summary> /// <param name="fileName">Name of the candidate source file.</param> /// <returns>True, if this is a validate source file.</returns> protected abstract bool IsSourceFile(string fileName); /// <summary> /// Given a file path, return a stream on top of that path. /// </summary> /// <param name="path">Path to the file</param> /// <param name="mode">File mode</param> /// <param name="access">Access type</param> /// <returns>The FileStream</returns> private static Stream CreateFileStreamOverNewFileStream(string path, FileMode mode, FileAccess access) { return new FileStream(path, mode, access); } #region ITask Members /// <summary> /// Execute the task with delegate handlers. /// </summary> /// <param name="createFileStream">CreateFileStream delegate</param> /// <returns>True if task succeeded.</returns> internal bool Execute ( CreateFileStream createFileStream ) { ManifestResourceNames = new ITaskItem[ResourceFiles.Length]; ResourceFilesWithManifestResourceNames = new ITaskItem[ResourceFiles.Length]; bool success = true; int i = 0; // If Rootnamespace was null, then it wasn't set from the project resourceFile. // Empty namespaces are allowed. if (RootNamespace != null) { Log.LogMessageFromResources(MessageImportance.Low, "CreateManifestResourceName.RootNamespace", RootNamespace); } else { Log.LogMessageFromResources(MessageImportance.Low, "CreateManifestResourceName.NoRootNamespace"); } foreach (ITaskItem resourceFile in ResourceFiles) { try { string fileName = resourceFile.ItemSpec; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); string dependentUpon = resourceFile.GetMetadata(ItemMetadataNames.dependentUpon); string fileType = resourceFile.GetMetadata("Type"); // If it has "type" metadata and the value is "Resx" // This value can be specified by the user, if not it will have been automatically assigned by the SplitResourcesByCulture target. bool isResxFile = (!string.IsNullOrEmpty(fileType) && fileType == "Resx"); // If not, fall back onto the extension. if (string.IsNullOrEmpty(fileType)) { isResxFile = Path.GetExtension(fileName) == resxFileExtension; } // If opted into convention and no DependentUpon metadata and is a resx file, reference "<filename>.<ext>" (.cs or .vb) if it exists. if (isResxFile && UseDependentUponConvention && string.IsNullOrEmpty(dependentUpon)) { // Assume that by convention the expected file name is "<filename>.<ext>" string conventionDependentUpon = Path.ChangeExtension(Path.GetFileName(fileName), SourceFileExtension); // Verify that the file name didn't have a culture associated with it. Ex: "<filename>.<culture>.resx" If we don't strip the culture we look for TestComponent.de.cs, which we don't want. if (resourceFile.GetMetadata("WithCulture") == "true") { string culture = resourceFile.GetMetadata("Culture"); if (!string.IsNullOrEmpty(culture)) { int indexJustBeforeCulture = fileNameWithoutExtension.Length - culture.Length - 1; // Strip the culture from the name, append the appropriate extension, now we have "<filename>.<ext>", this is the file resourceFile is dependent upon conventionDependentUpon = fileNameWithoutExtension.Substring(0, indexJustBeforeCulture) + SourceFileExtension; } } if (File.Exists(Path.Combine(Path.GetDirectoryName(fileName), conventionDependentUpon))) { dependentUpon = conventionDependentUpon; } } // Pre-log some information. bool isDependentOnSourceFile = !string.IsNullOrEmpty(dependentUpon) && IsSourceFile(dependentUpon); if (isDependentOnSourceFile) { Log.LogMessageFromResources(MessageImportance.Low, "CreateManifestResourceName.DependsUpon", fileName, dependentUpon); } else { Log.LogMessageFromResources(MessageImportance.Low, "CreateManifestResourceName.DependsUponNothing", fileName); } // Create the manifest name. Stream binaryStream = null; string manifestName; if (isDependentOnSourceFile) { string pathToDependent = Path.Combine(Path.GetDirectoryName(fileName), dependentUpon); binaryStream = createFileStream(pathToDependent, FileMode.Open, FileAccess.Read); } // Put the task item into a dictionary so we can access it from a derived class quickly. itemSpecToTaskitem[resourceFile.ItemSpec] = resourceFile; // This "using" statement ensures that the "binaryStream" will be disposed once // we're done with it. using (binaryStream) { manifestName = CreateManifestName ( fileName, resourceFile.GetMetadata(ItemMetadataNames.targetPath), RootNamespace, isDependentOnSourceFile ? dependentUpon : null, binaryStream ); } // Emit an item with our manifest name. ManifestResourceNames[i] = new TaskItem(resourceFile) { ItemSpec = manifestName }; // Emit a new item preserving the itemSpec of the resourceFile, but with new metadata for manifest resource name ResourceFilesWithManifestResourceNames[i] = new TaskItem(resourceFile); ResourceFilesWithManifestResourceNames[i].SetMetadata("ManifestResourceName", manifestName); // Add a LogicalName metadata to Non-Resx resources // LogicalName isn't used for Resx resources because the ManifestResourceName metadata determines the filename of the // .resources file which then is used as the embedded resource manifest name if (string.IsNullOrEmpty(ResourceFilesWithManifestResourceNames[i].GetMetadata("LogicalName")) && string.Equals(ResourceFilesWithManifestResourceNames[i].GetMetadata("Type"), "Non-Resx", StringComparison.OrdinalIgnoreCase)) { ResourceFilesWithManifestResourceNames[i].SetMetadata("LogicalName", manifestName); } // Post-logging Log.LogMessageFromResources(MessageImportance.Low, "CreateManifestResourceName.AssignedName", fileName, manifestName); } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { Log.LogErrorWithCodeFromResources("CreateManifestResourceName.Error", resourceFile.ItemSpec, e.Message); success = false; } ++i; } return success; } /// <summary> /// Do the task's work. /// </summary> /// <returns>True if succeeded.</returns> public override bool Execute() { return Execute(CreateFileStreamOverNewFileStream); } #endregion #region Helper methods /// <summary> /// Is the character a valid first Everett identifier character? /// </summary> private static bool IsValidEverettIdFirstChar(char c) { return char.IsLetter(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.ConnectorPunctuation; } /// <summary> /// Is the character a valid Everett identifier character? /// </summary> private static bool IsValidEverettIdChar(char c) { UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(c); return char.IsLetterOrDigit(c) || cat == UnicodeCategory.ConnectorPunctuation || cat == UnicodeCategory.NonSpacingMark || cat == UnicodeCategory.SpacingCombiningMark || cat == UnicodeCategory.EnclosingMark; } /// <summary> /// Make a folder subname into an Everett-compatible identifier /// </summary> private static void MakeValidEverettSubFolderIdentifier(StringBuilder builder, string subName) { ErrorUtilities.VerifyThrowArgumentNull(subName, nameof(subName)); if (string.IsNullOrEmpty(subName)) { return; } // the first character has stronger restrictions than the rest if (IsValidEverettIdFirstChar(subName[0])) { builder.Append(subName[0]); } else { builder.Append('_'); if (IsValidEverettIdChar(subName[0])) { // if it is a valid subsequent character, prepend an underscore to it builder.Append(subName[0]); } } // process the rest of the subname for (int i = 1; i < subName.Length; i++) { if (!IsValidEverettIdChar(subName[i])) { builder.Append('_'); } else { builder.Append(subName[i]); } } } /// <summary> /// Make a folder name into an Everett-compatible identifier /// </summary> internal static void MakeValidEverettFolderIdentifier(StringBuilder builder, string name) { ErrorUtilities.VerifyThrowArgumentNull(name, nameof(name)); if (string.IsNullOrEmpty(name)) { return; } // store the original length for use later int length = builder.Length; // split folder name into subnames separated by '.', if any string[] subNames = name.Split(MSBuildConstants.DotChar); // convert each subname separately MakeValidEverettSubFolderIdentifier(builder, subNames[0]); for (int i = 1; i < subNames.Length; i++) { builder.Append('.'); MakeValidEverettSubFolderIdentifier(builder, subNames[i]); } // folder name cannot be a single underscore - add another underscore to it if ((builder.Length - length) == 1 && builder[length] == '_') { builder.Append('_'); } } /// <summary> /// This method is provided for compatibility with Everett which used to convert parts of resource names into /// valid identifiers /// </summary> public static string MakeValidEverettIdentifier(string name) { ErrorUtilities.VerifyThrowArgumentNull(name, nameof(name)); if (string.IsNullOrEmpty(name)) { return name; } var everettId = new StringBuilder(name.Length); // split the name into folder names string[] subNames = name.Split(MSBuildConstants.ForwardSlashBackslash); // convert every folder name MakeValidEverettFolderIdentifier(everettId, subNames[0]); for (int i = 1; i < subNames.Length; i++) { everettId.Append('.'); MakeValidEverettFolderIdentifier(everettId, subNames[i]); } return everettId.ToString(); } #endregion } }
42.448363
210
0.573107
[ "MIT" ]
AlexanderSemenyak/msbuild
src/Tasks/CreateManifestResourceName.cs
16,854
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.IO; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Formatters.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Mvc.Infrastructure { internal sealed class SystemTextJsonResultExecutor : IActionResultExecutor<JsonResult> { private static readonly string DefaultContentType = new MediaTypeHeaderValue("application/json") { Encoding = Encoding.UTF8 }.ToString(); private readonly JsonOptions _options; private readonly ILogger<SystemTextJsonResultExecutor> _logger; public SystemTextJsonResultExecutor( IOptions<JsonOptions> options, ILogger<SystemTextJsonResultExecutor> logger) { _options = options.Value; _logger = logger; } public async Task ExecuteAsync(ActionContext context, JsonResult result) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } var jsonSerializerOptions = GetSerializerOptions(result); var response = context.HttpContext.Response; ResponseContentTypeHelper.ResolveContentTypeAndEncoding( result.ContentType, response.ContentType, DefaultContentType, out var resolvedContentType, out var resolvedContentTypeEncoding); response.ContentType = resolvedContentType; if (result.StatusCode != null) { response.StatusCode = result.StatusCode.Value; } Log.JsonResultExecuting(_logger, result.Value); // Keep this code in sync with SystemTextJsonOutputFormatter var writeStream = GetWriteStream(context.HttpContext, resolvedContentTypeEncoding); try { var type = result.Value?.GetType() ?? typeof(object); await JsonSerializer.WriteAsync(writeStream, result.Value, type, jsonSerializerOptions); await writeStream.FlushAsync(); } finally { if (writeStream is TranscodingWriteStream transcoding) { await transcoding.DisposeAsync(); } } } private Stream GetWriteStream(HttpContext httpContext, Encoding selectedEncoding) { if (selectedEncoding.CodePage == Encoding.UTF8.CodePage) { // JsonSerializer does not write a BOM. Therefore we do not have to handle it // in any special way. return httpContext.Response.Body; } return new TranscodingWriteStream(httpContext.Response.Body, selectedEncoding); } private JsonSerializerOptions GetSerializerOptions(JsonResult result) { var serializerSettings = result.SerializerSettings; if (serializerSettings == null) { return _options.JsonSerializerOptions; } else { if (!(serializerSettings is JsonSerializerOptions settingsFromResult)) { throw new InvalidOperationException(Resources.FormatProperty_MustBeInstanceOfType( nameof(JsonResult), nameof(JsonResult.SerializerSettings), typeof(JsonSerializerOptions))); } return settingsFromResult; } } private static class Log { private static readonly Action<ILogger, string, Exception> _jsonResultExecuting = LoggerMessage.Define<string>( LogLevel.Information, new EventId(1, "JsonResultExecuting"), "Executing JsonResult, writing value of type '{Type}'."); public static void JsonResultExecuting(ILogger logger, object value) { var type = value == null ? "null" : value.GetType().FullName; _jsonResultExecuting(logger, type, null); } } } }
35.320896
123
0.602366
[ "Apache-2.0" ]
NickDarvey/AspNetCore
src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs
4,735
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the clouddirectory-2017-01-11.normal.json service model. */ using Amazon.Runtime; namespace Amazon.CloudDirectory.Model { /// <summary> /// Paginator for the LookupPolicy operation ///</summary> public interface ILookupPolicyPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<LookupPolicyResponse> Responses { get; } } } #endif
32.857143
113
0.683478
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CloudDirectory/Generated/Model/_bcl45+netstandard/ILookupPolicyPaginator.cs
1,150
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Confluent.Kafka; using ClassLibrary1; namespace ComsumerApp1 { /// <summary> /// サブスクライバーの生成処理の基本実装。 /// </summary> public abstract class MessageSubscriberFactoryBase { /// <summary> /// インスタンスを生成します。 /// </summary> /// <param name="subscriberSetting">サブスクライバーの動作設定</param> /// <param name="logger">ロガー</param> protected MessageSubscriberFactoryBase(MessageSubscriberSetting subscriberSetting, ILogger logger) { SubscriberSetting = subscriberSetting; Logger = logger; } /// <summary> /// サブスクライバーの動作設定を取得します。 /// </summary> private MessageSubscriberSetting SubscriberSetting { get; } /// <summary> /// ロガーを取得します。 /// </summary> private ILogger Logger { get; } /// <summary> /// サブスクライバーを生成します。 /// </summary> /// <typeparam name="TKey">キーの型</typeparam> /// <typeparam name="TMessage">メッセージの型</typeparam> /// <returns>サブスクライバー</returns> public MessageSubscriber<TKey, TMessage> CreateSubscriber<TKey, TMessage>(string topic) { return new MessageSubscriber<TKey, TMessage>( GetDeserializer<TKey>() , GetDeserializer<TMessage>() , SubscriberSetting , topic , Logger ); } /// <summary> /// シリアライザを取得します。 /// </summary> /// <typeparam name="T">シリアライズ対象オブジェクトの型</typeparam> /// <returns>シリアライザ</returns> protected abstract IDeserializer<T> GetDeserializer<T>(); } }
27.41791
106
0.576483
[ "MIT" ]
mxProject/Misc
source/KafkaPubSub/ComsumerApp1/MessageSubscriberFactoryBase.cs
2,133
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: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using XenAPI; using XenAdmin.Network; using XenAdmin.Core; using XenAdmin.Commands; namespace XenAdmin.Controls { public partial class LoggedInLabel : UserControl { private IXenConnection connection; public IXenConnection Connection { get { return connection; } set { // Check if we need to bother updating if (value == connection) return; // if the old value was not null then we need to deregister the event handlers if (connection != null) { connection.ConnectionStateChanged -= new EventHandler<EventArgs>(connection_ConnectionStateChanged); connection.CachePopulated -= new EventHandler<EventArgs>(connection_CachePopulated); } // Now set to the new value, if it's not null then we set the labels and tooltip relevant to the new connection connection = value; if (connection != null) { // If the current connection disconnects we need to clear the labels connection.ConnectionStateChanged += new EventHandler<EventArgs>(connection_ConnectionStateChanged); // if the cache isn't populated yet we can clear the lables and update later off this event handler connection.CachePopulated += new EventHandler<EventArgs>(connection_CachePopulated); if (connection.CacheIsPopulated) { setLabelText(); return; } } // clear labels labelUsername.Text = ""; labelLoggedInAs.Visible = false; } } /// <summary> /// Used to clear the labels on a disconnect /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void connection_ConnectionStateChanged(object sender, EventArgs e) { Program.Invoke(Program.MainWindow, delegate { setLabelText(); }); } void connection_CachePopulated(object sender, EventArgs e) { Program.Invoke(Program.MainWindow, delegate { setLabelText(); }); } private void setLabelText() { // If we are connecting we should actually only update when the cache is populated. if (connection == null || connection.Session == null || !connection.IsConnected || !connection.CacheIsPopulated) { labelUsername.Text = ""; labelLoggedInAs.Visible = false; return; } labelLoggedInAs.Visible = true; // get the logged in username from the session to update the logged in label if (connection.Session.IsLocalSuperuser || XenAdmin.Core.Helpers.GetMaster(connection).external_auth_type != Auth.AUTH_TYPE_AD) { labelUsername.Text = connection.Session.UserFriendlyName; } else { labelUsername.Text = string.Format("{0} ({1})", connection.Session.UserFriendlyName, connection.Session.FriendlySingleRoleDescription); ; } } public LoggedInLabel() { InitializeComponent(); } /// <summary> /// Sets all the labels on the control to use this text color /// </summary> /// <param name="c"></param> public void SetTextColor(Color c) { labelLoggedInAs.ForeColor = c; labelUsername.ForeColor = c; } } }
38.067114
140
0.576869
[ "BSD-2-Clause" ]
cheng-z/xenadmin
XenAdmin/Controls/AD/LoggedInLabel.cs
5,674
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HostelAllocationOptimization { public class HostelAllocationDTO { public int NumDays { get; set; } public int NumRooms { get; set; } public int[] GroupsSizes { get; set; } public int[] RoomCapacity { get; set; } public List<Tuple<int, int>> GroupsDemands { get; set; } public List<Tuple<int, int>> InitialAllocation { get; set; } public HostelAllocationDTO() { } } }
24.434783
68
0.629893
[ "MIT" ]
alanwjunior/HostelAllocation
HostelAllocationOptimization/Model/HostelAllocationDTO.cs
564
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.CloudTrail.Inputs { public sealed class TrailAdvancedEventSelectorFieldSelectorArgs : Pulumi.ResourceArgs { [Input("endsWiths")] private InputList<string>? _endsWiths; /// <summary> /// A list of values that includes events that match the last few characters of the event record field specified as the value of `field`. /// </summary> public InputList<string> EndsWiths { get => _endsWiths ?? (_endsWiths = new InputList<string>()); set => _endsWiths = value; } [Input("equals")] private InputList<string>? _equals; /// <summary> /// A list of values that includes events that match the exact value of the event record field specified as the value of `field`. This is the only valid operator that you can use with the `readOnly`, `eventCategory`, and `resources.type` fields. /// </summary> public InputList<string> Equals { get => _equals ?? (_equals = new InputList<string>()); set => _equals = value; } /// <summary> /// Specifies a field in an event record on which to filter events to be logged. You can specify only the following values: `readOnly`, `eventSource`, `eventName`, `eventCategory`, `resources.type`, `resources.ARN`. /// </summary> [Input("field", required: true)] public Input<string> Field { get; set; } = null!; [Input("notEndsWiths")] private InputList<string>? _notEndsWiths; /// <summary> /// A list of values that excludes events that match the last few characters of the event record field specified as the value of `field`. /// </summary> public InputList<string> NotEndsWiths { get => _notEndsWiths ?? (_notEndsWiths = new InputList<string>()); set => _notEndsWiths = value; } [Input("notEquals")] private InputList<string>? _notEquals; /// <summary> /// A list of values that excludes events that match the exact value of the event record field specified as the value of `field`. /// </summary> public InputList<string> NotEquals { get => _notEquals ?? (_notEquals = new InputList<string>()); set => _notEquals = value; } [Input("notStartsWiths")] private InputList<string>? _notStartsWiths; /// <summary> /// A list of values that excludes events that match the first few characters of the event record field specified as the value of `field`. /// </summary> public InputList<string> NotStartsWiths { get => _notStartsWiths ?? (_notStartsWiths = new InputList<string>()); set => _notStartsWiths = value; } [Input("startsWiths")] private InputList<string>? _startsWiths; /// <summary> /// A list of values that includes events that match the first few characters of the event record field specified as the value of `field`. /// </summary> public InputList<string> StartsWiths { get => _startsWiths ?? (_startsWiths = new InputList<string>()); set => _startsWiths = value; } public TrailAdvancedEventSelectorFieldSelectorArgs() { } } }
37.94898
253
0.613875
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/CloudTrail/Inputs/TrailAdvancedEventSelectorFieldSelectorArgs.cs
3,719
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public string firstlevel; public GameObject optionsScreen; public void StartGame() { SceneManager.LoadScene(firstlevel); } public void OpenOptions() { optionsScreen.SetActive(true); } public void CloseOptions() { optionsScreen.SetActive(false); } public void QuitGame() { Application.Quit(); } }
17.935484
44
0.647482
[ "MIT" ]
EricWRogers/ChallengerDeep
Assets/Scripts/UI/HUD/Example/Scripts/MainMenu.cs
558
C#
namespace RelationalGit { public class AbandonedFile { public string FilePath { get; set; } public int TotalLinesInPeriod { get; set; } public int AbandonedLinesInPeriod { get; set; } public int SavedLines => TotalLinesInPeriod - AbandonedLinesInPeriod; } }
21.857143
77
0.656863
[ "MIT" ]
CESEL/RelationalGit
src/RelationalGit.CommandLine/Commands/Models/AbandonedFile.cs
308
C#
using System; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Entries.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class AboutPage : ContentPage { public AboutPage() { InitializeComponent(); } } }
24
81
0.678241
[ "MIT" ]
taublast/droidentrybug
Entries/Views/AboutPage.xaml.cs
434
C#
/* * Assembly API * * Assembly (formely PromisePay) is a powerful payments engine custom-built for platforms and marketplaces. * * The version of the OpenAPI document: 2.0 * Contact: support@assemblypayments.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; namespace AssemblyPay.Sdk.Test.Model { /// <summary> /// Class for testing Charge /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class ChargeTests : IDisposable { // TODO uncomment below to declare an instance variable for Charge //private Charge instance; public ChargeTests() { // TODO uncomment below to create an instance of Charge //instance = new Charge(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of Charge /// </summary> [Fact] public void ChargeInstanceTest() { // TODO uncomment below to test "IsType" Charge //Assert.IsType<Charge>(instance); } /// <summary> /// Test the property 'Id' /// </summary> [Fact] public void IdTest() { // TODO unit test for the property 'Id' } /// <summary> /// Test the property 'Name' /// </summary> [Fact] public void NameTest() { // TODO unit test for the property 'Name' } /// <summary> /// Test the property 'CustomDescriptor' /// </summary> [Fact] public void CustomDescriptorTest() { // TODO unit test for the property 'CustomDescriptor' } /// <summary> /// Test the property 'CustomData' /// </summary> [Fact] public void CustomDataTest() { // TODO unit test for the property 'CustomData' } /// <summary> /// Test the property 'CreatedAt' /// </summary> [Fact] public void CreatedAtTest() { // TODO unit test for the property 'CreatedAt' } /// <summary> /// Test the property 'UpdatedAt' /// </summary> [Fact] public void UpdatedAtTest() { // TODO unit test for the property 'UpdatedAt' } /// <summary> /// Test the property 'State' /// </summary> [Fact] public void StateTest() { // TODO unit test for the property 'State' } /// <summary> /// Test the property 'BuyerFees' /// </summary> [Fact] public void BuyerFeesTest() { // TODO unit test for the property 'BuyerFees' } /// <summary> /// Test the property 'SellerFees' /// </summary> [Fact] public void SellerFeesTest() { // TODO unit test for the property 'SellerFees' } /// <summary> /// Test the property 'CreditCardFee' /// </summary> [Fact] public void CreditCardFeeTest() { // TODO unit test for the property 'CreditCardFee' } /// <summary> /// Test the property 'Status' /// </summary> [Fact] public void StatusTest() { // TODO unit test for the property 'Status' } /// <summary> /// Test the property 'Amount' /// </summary> [Fact] public void AmountTest() { // TODO unit test for the property 'Amount' } /// <summary> /// Test the property 'DynamicDescriptor' /// </summary> [Fact] public void DynamicDescriptorTest() { // TODO unit test for the property 'DynamicDescriptor' } /// <summary> /// Test the property 'AccountId' /// </summary> [Fact] public void AccountIdTest() { // TODO unit test for the property 'AccountId' } /// <summary> /// Test the property 'AccountType' /// </summary> [Fact] public void AccountTypeTest() { // TODO unit test for the property 'AccountType' } /// <summary> /// Test the property 'PromisepayFee' /// </summary> [Fact] public void PromisepayFeeTest() { // TODO unit test for the property 'PromisepayFee' } /// <summary> /// Test the property 'Currency' /// </summary> [Fact] public void CurrencyTest() { // TODO unit test for the property 'Currency' } /// <summary> /// Test the property 'PaymentMethod' /// </summary> [Fact] public void PaymentMethodTest() { // TODO unit test for the property 'PaymentMethod' } /// <summary> /// Test the property 'BuyerName' /// </summary> [Fact] public void BuyerNameTest() { // TODO unit test for the property 'BuyerName' } /// <summary> /// Test the property 'BuyerEmail' /// </summary> [Fact] public void BuyerEmailTest() { // TODO unit test for the property 'BuyerEmail' } /// <summary> /// Test the property 'BuyerZip' /// </summary> [Fact] public void BuyerZipTest() { // TODO unit test for the property 'BuyerZip' } /// <summary> /// Test the property 'BuyerCountry' /// </summary> [Fact] public void BuyerCountryTest() { // TODO unit test for the property 'BuyerCountry' } /// <summary> /// Test the property 'SellerName' /// </summary> [Fact] public void SellerNameTest() { // TODO unit test for the property 'SellerName' } /// <summary> /// Test the property 'SellerEmail' /// </summary> [Fact] public void SellerEmailTest() { // TODO unit test for the property 'SellerEmail' } /// <summary> /// Test the property 'SellerZip' /// </summary> [Fact] public void SellerZipTest() { // TODO unit test for the property 'SellerZip' } /// <summary> /// Test the property 'SellerCountry' /// </summary> [Fact] public void SellerCountryTest() { // TODO unit test for the property 'SellerCountry' } /// <summary> /// Test the property 'Related' /// </summary> [Fact] public void RelatedTest() { // TODO unit test for the property 'Related' } /// <summary> /// Test the property 'Links' /// </summary> [Fact] public void LinksTest() { // TODO unit test for the property 'Links' } } }
26.567857
107
0.488641
[ "MIT" ]
tahirahmed76/AssemblyPay.Sdk
Org.OpenAPITools.Test/Model/ChargeTests.cs
7,439
C#
using System.Threading; using System.Threading.Tasks; using Lion.AbpPro.DataDictionaryManagement.DataDictionaries.Dtos; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace Lion.AbpPro.DataDictionaryManagement.DataDictionaries { public interface IDataDictionaryAppService : IApplicationService { /// <summary> /// 分页查询字典项 /// </summary> /// <param name="input"></param> /// <returns></returns> Task<PagedResultDto<PagingDataDictionaryOutput>> GetPagingListAsync( PagingDataDictionaryInput input); /// <summary> /// 分页查询字典项明细 /// </summary> /// <param name="input"></param> /// <returns></returns> Task<PagedResultDto<PagingDataDictionaryDetailOutput>> GetPagingDetailListAsync( PagingDataDictionaryDetailInput input); /// <summary> /// 创建字典类型 /// </summary> /// <returns></returns> Task CreateAsync(CreateDataDictinaryInput input); /// <summary> /// 新增字典明细 /// </summary> Task CreateDetailAsync(CreateDataDictinaryDetailInput input); /// <summary> /// 设置字典明细状态 /// </summary> Task SetStatus(SetDataDictinaryDetailInput input); Task UpdateDetailAsync(UpdateDetailInput input); /// <summary> /// 删除数据字典明细项 /// </summary> /// <param name="input"></param> /// <returns></returns> Task DeleteAsync(DeleteDataDictionaryDetailInput input); } }
30.038462
88
0.616517
[ "MIT" ]
tangjian826454/abp-vnext-pro
aspnet-core/modules/DataDictionaryManagement/src/Lion.AbpPro.DataDictionaryManagement.Application.Contracts/DataDictionaries/IDataDictionaryAppService.cs
1,652
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.CosmosDB { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// DatabaseAccountRegionOperations operations. /// </summary> internal partial class DatabaseAccountRegionOperations : IServiceOperations<CosmosDBManagementClient>, IDatabaseAccountRegionOperations { /// <summary> /// Initializes a new instance of the DatabaseAccountRegionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DatabaseAccountRegionOperations(CosmosDBManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the CosmosDBManagementClient /// </summary> public CosmosDBManagementClient Client { get; private set; } /// <summary> /// Retrieves the metrics determined by the given filter for the given database /// account and region. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='accountName'> /// Cosmos DB database account name. /// </param> /// <param name='region'> /// Cosmos DB region, with spaces between words and each word capitalized. /// </param> /// <param name='filter'> /// An OData filter expression that describes a subset of metrics to return. /// The parameters that can be filtered are name.value (name of the metric, can /// have an or of multiple names), startTime, endTime, and timeGrain. The /// supported operator is eq. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Metric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string accountName, string region, string filter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "accountName", 50); } if (accountName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*")) { throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*"); } } if (region == null) { throw new ValidationException(ValidationRules.CannotBeNull, "region"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ApiVersion != null) { if (Client.ApiVersion.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1); } } if (filter == null) { throw new ValidationException(ValidationRules.CannotBeNull, "filter"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("region", region); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/metrics").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{region}", System.Uri.EscapeDataString(region)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Metric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Metric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.2125
300
0.560008
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/DatabaseAccountRegionOperations.cs
14,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.Circles_Intersection { class Program { static void Main(string[] args) { } } }
15.4375
39
0.659919
[ "MIT" ]
AlexanderStanev/SoftUni
TechModule/ObjectsClassesExercises/03. Circles Intersection/Program.cs
249
C#
using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading.Tasks; using StackExchange.Redis; namespace TranscendenceChat.WorkerRole.SocketServer.Infrastructure.Persistence.Redis { public static class RedisExtensions { public static T Get<T>(this IDatabase cache, string key) { return Deserialize<T>(cache.StringGet(key)); } public static void Set(this IDatabase cache, string key, object value) { cache.StringSet(key, Serialize(value)); } public static async Task<T> GetAsync<T>(this ITransaction cache, string key) { return Deserialize<T>(await cache.StringGetAsync(key).ConfigureAwait(false)); } public static Task<bool> SetAsync(this ITransaction cache, string key, object value) { return cache.StringSetAsync(key, Serialize(value)); } /* TODO: BinaryFormatter or Protobuf? */ public static byte[] Serialize(object o) { if (o == null) { return null; } BinaryFormatter binaryFormatter = new BinaryFormatter(); using (MemoryStream memoryStream = new MemoryStream()) { binaryFormatter.Serialize(memoryStream, o); byte[] objectDataAsStream = memoryStream.ToArray(); return objectDataAsStream; } } public static T Deserialize<T>(byte[] stream) { if (stream == null) { return default(T); } BinaryFormatter binaryFormatter = new BinaryFormatter(); using (MemoryStream memoryStream = new MemoryStream(stream)) { T result = (T)binaryFormatter.Deserialize(memoryStream); return result; } } } }
30.375
92
0.570988
[ "MIT" ]
tamifist/Transcendence
TranscendenceChatWorkerRole/TranscendenceChat.WorkerRole.SocketServer/Infrastructure/Persistence/Redis/RedisExtensions.cs
1,946
C#
using Toe.Scripting; namespace SpirVGraph.NodeFactories { public class OpEmitStreamVertexNodeFactory : AbstractNodeFactory { public static readonly OpEmitStreamVertexNodeFactory Instance = new OpEmitStreamVertexNodeFactory(); public OpEmitStreamVertexNodeFactory():base(new ScriptNode() { Name = "EmitStreamVertex", Category = NodeCategory.Function, Type = "OpEmitStreamVertex", InputPins = { new PinWithConnection("Stream",null), }, OutputPins = { } }, NodeFactoryVisibility.Visible) { } } }
27.12
108
0.584071
[ "MIT" ]
gleblebedev/SpirVisualEditor
src/SpirVGraph/NodeFactories/OpEmitStreamVertexNodeFactory.cs
678
C#
using System.Linq; using System.Threading.Tasks; namespace eKart.Api.Data { public static class DbInitializer { public static async Task InitializeAsync(eKartContext context) { await context.Database.EnsureCreatedAsync(); if (context.Products.Any()) { return; } var products = new Product[] { new Product{Name="Apple"}, new Product{Name="Banana"}, new Product{Name="Orange"}, new Product{Name="Grape"}, new Product{Name="Plum"}, new Product{Name="Lime"}, new Product{Name="Kiwi"} }; context.Products.AddRange(products); await context.SaveChangesAsync(); } } }
26.09375
70
0.505389
[ "MIT" ]
subhendu-de/eKart
eKart.api/Data/DbInitializer.cs
835
C#
using System.Collections.Generic; using PizzaBox.Domain.Abstracts; using PizzaBox.Domain.Models; namespace PizzaBox.Data { public interface IRepository { void AddPizza(CustomPizza pizza); CustomPizza GetPizzaByIndex(int Id); void UpdatePizza(CustomPizza pizza); void DeletePizza(int Id); List<MCustomer> GetUserAndPass(); List<MCustomer> GetCustomers(); public List<MOrder> GetAllOrders(); void AddCustomer(MCustomer customer); void AddOrder(MOrder order); void AddToppings(Toppings toppings); List<Store> GetStores(); Store GetStoreByIndex(int Id); List<MCrust> GetPizzaCrusts(); MCrust GetCrustByIndex(int Id); List<Size> GetSizes(); Size GetSizeByIndex(int Id); List<Toppings> GetToppings(); Toppings GetToppingByIndex(int Id); int GetOrderCount(); int GetPizzaCount(); int GetPizzaToppingCount(); public List<CustomPizza> GetPizzasOrders(); public MCustomer GetCustomerById(int Id); MOrder GetOrderById(int id); void UpdateOrder(MOrder order); void DeleteOrder(int Id); void UpdateCrust(MCrust crust); void DeleteCrust(int Id); void DeleteCustomer(int Id); void AddCrust(MCrust crust); void UpdateCustomer(MCustomer customer); void AddSize(Size size); void AddTopList(Toppings toppings); List<Toppings> GetPizzaToppings(); List<Toppings> GetPizzaToppingsById(int PizzaId); void UpdatePizzaTopping(Toppings toppings); Toppings GetPizzaToppingById(int toppingId); void DeletePizzaToppingById(int toppingId); void DeleteToppingById(int toppingId); void UpdateTopping(Toppings toppings); void UpdateSize(Size size); void DeleteSize(int Id); List<CustomPizza> GetPizzaOrdersById(int Id); CustomPizza GetPizzaOrderById(int Id); //bool AddOrderToDb(MOrder order); } }
20.509804
57
0.645793
[ "MIT" ]
210329-UTA-SH-UiPath/p1_eduardo_reyes
PizzaBoxAPI/PizzaBox.Domain/Abstracts/IRepository.cs
2,092
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using OpenConfigurator.Core.XmlDAL; namespace OpenConfigurator.Core.XmlDAL.ModelFile.DataEntities { [DataContract] internal class CompositionRule : iDataEntity { [DataMember(Order = 0)] public string Identifier { get; set; } [DataMember(Order = 1)] public int CompositionRuleType { get; set; } [DataMember(Order = 2)] public string FirstFeatureIdentifier { get; set; } [DataMember(Order = 3)] public string SecondFeatureIdentifier { get; set; } [DataMember(Order = 4)] public string Name { get; set; } [DataMember(Order = 5)] public string Description { get; set; } } }
20.692308
61
0.51487
[ "MIT" ]
rmitache/OpenConfigurator
XmlDAL/ModelFile/DataEntities/CompositionRule.cs
1,078
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the fms-2018-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.FMS.Model { /// <summary> /// The definition of the Network Firewall firewall policy. /// </summary> public partial class NetworkFirewallPolicyDescription { private List<StatefulRuleGroup> _statefulRuleGroups = new List<StatefulRuleGroup>(); private List<string> _statelessCustomActions = new List<string>(); private List<string> _statelessDefaultActions = new List<string>(); private List<string> _statelessFragmentDefaultActions = new List<string>(); private List<StatelessRuleGroup> _statelessRuleGroups = new List<StatelessRuleGroup>(); /// <summary> /// Gets and sets the property StatefulRuleGroups. /// <para> /// The stateful rule groups that are used in the Network Firewall firewall policy. /// </para> /// </summary> public List<StatefulRuleGroup> StatefulRuleGroups { get { return this._statefulRuleGroups; } set { this._statefulRuleGroups = value; } } // Check to see if StatefulRuleGroups property is set internal bool IsSetStatefulRuleGroups() { return this._statefulRuleGroups != null && this._statefulRuleGroups.Count > 0; } /// <summary> /// Gets and sets the property StatelessCustomActions. /// <para> /// Names of custom actions that are available for use in the stateless default actions /// settings. /// </para> /// </summary> public List<string> StatelessCustomActions { get { return this._statelessCustomActions; } set { this._statelessCustomActions = value; } } // Check to see if StatelessCustomActions property is set internal bool IsSetStatelessCustomActions() { return this._statelessCustomActions != null && this._statelessCustomActions.Count > 0; } /// <summary> /// Gets and sets the property StatelessDefaultActions. /// <para> /// The actions to take on packets that don't match any of the stateless rule groups. /// /// </para> /// </summary> public List<string> StatelessDefaultActions { get { return this._statelessDefaultActions; } set { this._statelessDefaultActions = value; } } // Check to see if StatelessDefaultActions property is set internal bool IsSetStatelessDefaultActions() { return this._statelessDefaultActions != null && this._statelessDefaultActions.Count > 0; } /// <summary> /// Gets and sets the property StatelessFragmentDefaultActions. /// <para> /// The actions to take on packet fragments that don't match any of the stateless rule /// groups. /// </para> /// </summary> public List<string> StatelessFragmentDefaultActions { get { return this._statelessFragmentDefaultActions; } set { this._statelessFragmentDefaultActions = value; } } // Check to see if StatelessFragmentDefaultActions property is set internal bool IsSetStatelessFragmentDefaultActions() { return this._statelessFragmentDefaultActions != null && this._statelessFragmentDefaultActions.Count > 0; } /// <summary> /// Gets and sets the property StatelessRuleGroups. /// <para> /// The stateless rule groups that are used in the Network Firewall firewall policy. /// </para> /// </summary> public List<StatelessRuleGroup> StatelessRuleGroups { get { return this._statelessRuleGroups; } set { this._statelessRuleGroups = value; } } // Check to see if StatelessRuleGroups property is set internal bool IsSetStatelessRuleGroups() { return this._statelessRuleGroups != null && this._statelessRuleGroups.Count > 0; } } }
36.382353
117
0.636823
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/FMS/Generated/Model/NetworkFirewallPolicyDescription.cs
4,948
C#
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:42 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.ux.ajax { #region DataSimlet /// <inheritdocs /> /// <summary> /// <p>This base class is used to handle data preparation (e.g., sorting, filtering and /// group summary).</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class DataSimlet : Ext.Base { public DataSimlet(DataSimletConfig config){} public DataSimlet(){} public DataSimlet(params object[] args){} } #endregion #region DataSimletConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class DataSimletConfig : Ext.BaseConfig { public DataSimletConfig(params object[] args){} } #endregion #region DataSimletEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class DataSimletEvents : Ext.BaseEvents { public DataSimletEvents(params object[] args){} } #endregion }
31.4
91
0.604299
[ "MIT" ]
SharpKit/SharpKit-SDK
Defs/ExtJs/Ext.ux.ajax.DataSimlet.cs
1,256
C#
#pragma checksum "..\..\NewPassenger.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "9FAD92B774025E71CBB29C27E1A5857F" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Airline_Reservation_System { /// <summary> /// NewPassenger /// </summary> public partial class NewPassenger : System.Windows.Window, System.Windows.Markup.IComponentConnector { #line 20 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox lname; #line default #line hidden #line 21 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox fname; #line default #line hidden #line 24 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox agetxt; #line default #line hidden #line 25 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.RadioButton maletxt; #line default #line hidden #line 26 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.RadioButton femaleTxt; #line default #line hidden #line 27 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ComboBox nationalityBox; #line default #line hidden #line 29 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox emailTxt; #line default #line hidden #line 31 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox contact_txt; #line default #line hidden #line 32 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox tel_txt; #line default #line hidden #line 34 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox setPasstxt; #line default #line hidden #line 36 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox addTXT; #line default #line hidden #line 38 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox passporttxt; #line default #line hidden #line 39 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button back_new; #line default #line hidden #line 40 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button Submiit; #line default #line hidden #line 41 "..\..\NewPassenger.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button cancel_NP; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Airline_Reservation_System;component/newpassenger.xaml", System.UriKind.Relative); #line 1 "..\..\NewPassenger.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.lname = ((System.Windows.Controls.TextBox)(target)); return; case 2: this.fname = ((System.Windows.Controls.TextBox)(target)); return; case 3: this.agetxt = ((System.Windows.Controls.TextBox)(target)); return; case 4: this.maletxt = ((System.Windows.Controls.RadioButton)(target)); return; case 5: this.femaleTxt = ((System.Windows.Controls.RadioButton)(target)); return; case 6: this.nationalityBox = ((System.Windows.Controls.ComboBox)(target)); return; case 7: this.emailTxt = ((System.Windows.Controls.TextBox)(target)); return; case 8: this.contact_txt = ((System.Windows.Controls.TextBox)(target)); return; case 9: this.tel_txt = ((System.Windows.Controls.TextBox)(target)); return; case 10: this.setPasstxt = ((System.Windows.Controls.TextBox)(target)); return; case 11: this.addTXT = ((System.Windows.Controls.TextBox)(target)); return; case 12: this.passporttxt = ((System.Windows.Controls.TextBox)(target)); return; case 13: this.back_new = ((System.Windows.Controls.Button)(target)); #line 39 "..\..\NewPassenger.xaml" this.back_new.Click += new System.Windows.RoutedEventHandler(this.Back_new_P); #line default #line hidden return; case 14: this.Submiit = ((System.Windows.Controls.Button)(target)); #line 40 "..\..\NewPassenger.xaml" this.Submiit.Click += new System.Windows.RoutedEventHandler(this.Submiit_Click); #line default #line hidden return; case 15: this.cancel_NP = ((System.Windows.Controls.Button)(target)); #line 41 "..\..\NewPassenger.xaml" this.cancel_NP.Click += new System.Windows.RoutedEventHandler(this.Cancel_NP); #line default #line hidden return; } this._contentLoaded = true; } } }
37.83908
141
0.613609
[ "MIT" ]
MTayabShafique/Airline-Ticket-Reservation-System
Passengers Activity/Airline_Reservation_System/Airline_Reservation_System/obj/Debug/NewPassenger.g.cs
9,878
C#
 namespace Standard { using System; using System.Diagnostics.CodeAnalysis; /// <summary> /// DoubleUtil uses fixed eps to provide fuzzy comparison functionality for doubles. /// Note that FP noise is a big problem and using any of these compare /// methods is not a complete solution, but rather the way to reduce /// the probability of repeating unnecessary work. /// </summary> internal static class DoubleUtilities { /// <summary> /// Epsilon - more or less random, more or less small number. /// </summary> private const double Epsilon = 0.00000153; /// <summary> /// AreClose returns whether or not two doubles are "close". That is, whether or /// not they are within epsilon of each other. /// There are plenty of ways for this to return false even for numbers which /// are theoretically identical, so no code calling this should fail to work if this /// returns false. /// </summary> /// <param name="value1">The first double to compare.</param> /// <param name="value2">The second double to compare.</param> /// <returns>The result of the AreClose comparision.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool AreClose(double value1, double value2) { if (value1 == value2) { return true; } double delta = value1 - value2; return (delta < Epsilon) && (delta > -Epsilon); } /// <summary> /// LessThan returns whether or not the first double is less than the second double. /// That is, whether or not the first is strictly less than *and* not within epsilon of /// the other number. /// There are plenty of ways for this to return false even for numbers which /// are theoretically identical, so no code calling this should fail to work if this /// returns false. /// </summary> /// <param name="value1">The first double to compare.</param> /// <param name="value2">The second double to compare.</param> /// <returns>The result of the LessThan comparision.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool LessThan(double value1, double value2) { return (value1 < value2) && !AreClose(value1, value2); } /// <summary> /// GreaterThan returns whether or not the first double is greater than the second double. /// That is, whether or not the first is strictly greater than *and* not within epsilon of /// the other number. /// There are plenty of ways for this to return false even for numbers which /// are theoretically identical, so no code calling this should fail to work if this /// returns false. /// </summary> /// <param name="value1">The first double to compare.</param> /// <param name="value2">The second double to compare.</param> /// <returns>The result of the GreaterThan comparision.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool GreaterThan(double value1, double value2) { return (value1 > value2) && !AreClose(value1, value2); } /// <summary> /// LessThanOrClose returns whether or not the first double is less than or close to /// the second double. That is, whether or not the first is strictly less than or within /// epsilon of the other number. /// There are plenty of ways for this to return false even for numbers which /// are theoretically identical, so no code calling this should fail to work if this /// returns false. /// </summary> /// <param name="value1">The first double to compare.</param> /// <param name="value2">The second double to compare.</param> /// <returns>The result of the LessThanOrClose comparision.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool LessThanOrClose(double value1, double value2) { return (value1 < value2) || AreClose(value1, value2); } /// <summary> /// GreaterThanOrClose returns whether or not the first double is greater than or close to /// the second double. That is, whether or not the first is strictly greater than or within /// epsilon of the other number. /// There are plenty of ways for this to return false even for numbers which /// are theoretically identical, so no code calling this should fail to work if this /// returns false. /// </summary> /// <param name="value1">The first double to compare.</param> /// <param name="value2">The second double to compare.</param> /// <returns>The result of the GreaterThanOrClose comparision.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool GreaterThanOrClose(double value1, double value2) { return (value1 > value2) || AreClose(value1, value2); } /// <summary> /// Test to see if a double is a finite number (is not NaN or Infinity). /// </summary> /// <param name='value'>The value to test.</param> /// <returns>Whether or not the value is a finite number.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsFinite(double value) { return !double.IsNaN(value) && !double.IsInfinity(value); } /// <summary> /// Test to see if a double a valid size value (is finite and > 0). /// </summary> /// <param name='value'>The value to test.</param> /// <returns>Whether or not the value is a valid size value.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsValidSize(double value) { return IsFinite(value) && GreaterThanOrClose(value, 0); } } }
48.827068
101
0.611334
[ "Unlicense" ]
JeremyDurnell/ChromeTabs
Version2.0/AvalonDock/AvalonDock/Controls/Shell/Standard/DoubleUtil.cs
6,496
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Threading.Tasks; namespace RsCode { public sealed class VerifyCodeHelper { #region 单例模式 //创建私有化静态obj锁 private static readonly object _ObjLock = new object(); //创建私有静态字段,接收类的实例化对象 private static VerifyCodeHelper _VerifyCodeHelper = null; //构造函数私有化 private VerifyCodeHelper() { } //创建单利对象资源并返回 public static VerifyCodeHelper GetSingleObj() { if (_VerifyCodeHelper == null) { lock (_ObjLock) { if (_VerifyCodeHelper == null) _VerifyCodeHelper = new VerifyCodeHelper(); } } return _VerifyCodeHelper; } #endregion #region 生产验证码 public enum VerifyCodeType { NumberVerifyCode, AbcVerifyCode, MixVerifyCode }; /// <summary> /// 1.数字验证码 /// </summary> /// <param name="length"></param> /// <returns></returns> private string CreateNumberVerifyCode(int length) { int[] randMembers = new int[length]; int[] validateNums = new int[length]; string validateNumberStr = ""; //生成起始序列值 int seekSeek = unchecked((int)DateTime.Now.Ticks); Random seekRand = new Random(seekSeek); int beginSeek = seekRand.Next(0, Int32.MaxValue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginSeek += 10000; seeks[i] = beginSeek; } //生成随机数字 for (int i = 0; i < length; i++) { Random rand = new Random(seeks[i]); int pownum = 1 * (int)Math.Pow(10, length); randMembers[i] = rand.Next(pownum, Int32.MaxValue); } //抽取随机数字 for (int i = 0; i < length; i++) { string numStr = randMembers[i].ToString(); int numLength = numStr.Length; Random rand = new Random(); int numPosition = rand.Next(0, numLength - 1); validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); } //生成验证码 for (int i = 0; i < length; i++) { validateNumberStr += validateNums[i].ToString(); } return validateNumberStr; } /// <summary> /// 2.字母验证码 /// </summary> /// <param name="length">字符长度</param> /// <returns>验证码字符</returns> private string CreateAbcVerifyCode(int length) { char[] verification = new char[length]; char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; Random random = new Random(); for (int i = 0; i < length; i++) { verification[i] = dictionary[random.Next(dictionary.Length - 1)]; } return new string(verification); } /// <summary> /// 3.混合验证码 /// </summary> /// <param name="length">字符长度</param> /// <returns>验证码字符</returns> private string CreateMixVerifyCode(int length) { char[] verification = new char[length]; char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; Random random = new Random(); for (int i = 0; i < length; i++) { verification[i] = dictionary[random.Next(dictionary.Length - 1)]; } return new string(verification); } /// <summary> /// 产生验证码(随机产生4-6位) /// </summary> /// <param name="type">验证码类型:数字,字符,符合</param> /// <returns></returns> public async Task<string> CreateVerifyCodeAsync(VerifyCodeType type) { string verifyCode = string.Empty; Random random = new Random(); int length = random.Next(4, 6); switch (type) { case VerifyCodeType.NumberVerifyCode: verifyCode =await Task.Run(()=> GetSingleObj().CreateNumberVerifyCode(length)); break; case VerifyCodeType.AbcVerifyCode: verifyCode =await Task.Run(()=> GetSingleObj().CreateAbcVerifyCode(length)); break; case VerifyCodeType.MixVerifyCode: verifyCode =await Task.Run(()=> GetSingleObj().CreateMixVerifyCode(length)); break; } return verifyCode; } #endregion #region 验证码图片 /// <summary> /// 验证码图片 => Bitmap /// </summary> /// <param name="verifyCode">验证码</param> /// <param name="width">宽</param> /// <param name="height">高</param> /// <returns>Bitmap</returns> public Bitmap CreateBitmapByImgVerifyCode(string verifyCode, int width, int height) { Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic)); Brush brush; Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); SizeF totalSizeF = g.MeasureString(verifyCode, font); SizeF curCharSizeF; PointF startPointF = new PointF(0, (height - totalSizeF.Height) / 2); Random random = new Random(); //随机数产生器 g.Clear(Color.White); //清空图片背景色 for (int i = 0; i < verifyCode.Length; i++) { brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255))); g.DrawString(verifyCode[i].ToString(), font, brush, startPointF); curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font); startPointF.X += curCharSizeF.Width; } //画图片的干扰线 for (int i = 0; i < 10; i++) { int x1 = random.Next(bitmap.Width); int x2 = random.Next(bitmap.Width); int y1 = random.Next(bitmap.Height); int y2 = random.Next(bitmap.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(bitmap.Width); int y = random.Next(bitmap.Height); bitmap.SetPixel(x, y, Color.FromArgb(random.Next())); } g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); //画图片的边框线 g.Dispose(); return bitmap; } /// <summary> /// 验证码图片 => byte[] /// </summary> /// <param name="verifyCode">验证码</param> /// <param name="width">宽</param> /// <param name="height">高</param> /// <returns>byte[]</returns> public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height) { Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic)); Brush brush; Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); SizeF totalSizeF = g.MeasureString(verifyCode, font); SizeF curCharSizeF; PointF startPointF = new PointF(0, (height - totalSizeF.Height) / 2); Random random = new Random(); //随机数产生器 g.Clear(Color.White); //清空图片背景色 for (int i = 0; i < verifyCode.Length; i++) { brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255))); g.DrawString(verifyCode[i].ToString(), font, brush, startPointF); curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font); startPointF.X += curCharSizeF.Width; } //画图片的干扰线 for (int i = 0; i < 10; i++) { int x1 = random.Next(bitmap.Width); int x2 = random.Next(bitmap.Width); int y1 = random.Next(bitmap.Height); int y2 = random.Next(bitmap.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(bitmap.Width); int y = random.Next(bitmap.Height); bitmap.SetPixel(x, y, Color.FromArgb(random.Next())); } g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); //画图片的边框线 g.Dispose(); //保存图片数据 MemoryStream stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Jpeg); //输出图片流 return stream.ToArray(); } #endregion } }
39.240157
222
0.485402
[ "MIT" ]
kuiyu/RsCode
src/RsCode/Helper/VerifyCodeHelper.cs
10,457
C#
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. namespace Intel.RealSense { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; /// <summary> /// Base class for multiple frame extensions /// </summary> public class Frame : Base.PooledObject { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static readonly Base.Deleter FrameReleaser = NativeMethods.rs2_release_frame; internal override void Initialize() { } internal Frame(IntPtr ptr) : base(ptr, FrameReleaser) { } /// <summary> /// Create a frame from a native pointer /// </summary> /// <param name="ptr">Native <c>rs2_frame*</c> pointer</param> /// <returns>a new <see cref="Frame"/></returns> public static Frame Create(IntPtr ptr) { return Create<Frame>(ptr); } /// <summary> /// Create a frame from a native pointer /// </summary> /// <typeparam name="T"><see cref="Frame"/> type or subclass</typeparam> /// <param name="ptr">Native <c>rs2_frame*</c> pointer</param> /// <returns>a new <typeparamref name="T"/></returns> public static T Create<T>(IntPtr ptr) where T : Frame { return ObjectPool.Get<T>(ptr); } /// <summary>Returns a strongly-typed clone</summary> /// <typeparam name="T"><see cref="Frame"/> type or subclass</typeparam> /// <param name="other"><see cref="Frame"/> to clone</param> /// <returns>an instance of <typeparamref name="T"/></returns> public static T Create<T>(Frame other) where T : Frame { object error; NativeMethods.rs2_frame_add_ref(other.Handle, out error); return ObjectPool.Get<T>(other.Handle); } /// <summary>Test if the given frame can be extended to the requested extension</summary> /// <param name="extension">The extension to which the frame should be tested if it is extendable</param> /// <returns><see langword="true"/> iff the frame can be extended to the given extension</returns> public bool Is(Extension extension) { object error; return NativeMethods.rs2_is_frame_extendable_to(Handle, extension, out error) != 0; } /// <summary>Returns a strongly-typed clone</summary> /// <typeparam name="T"><see cref="Frame"/> type or subclass</typeparam> /// <returns>an instance of <typeparamref name="T"/></returns> public T As<T>() where T : Frame { return Create<T>(this); } /// <summary>Returns a strongly-typed clone, <see langword="this"/> is disposed</summary> /// <typeparam name="T"><see cref="Frame"/> type or subclass</typeparam> /// <returns>an instance of <typeparamref name="T"/></returns> public T Cast<T>() where T : Frame { using (this) { return Create<T>(this); } } /// <summary> /// Add a reference to this frame and return a clone, does not copy data /// </summary> /// <returns>A clone of this frame</returns> public Frame Clone() { object error; NativeMethods.rs2_frame_add_ref(Handle, out error); return Create(Handle); } /// <summary>communicate to the library you intend to keep the frame alive for a while /// <para> /// this will remove the frame from the regular count of the frame pool /// </para> /// </summary> /// <remarks> /// once this function is called, the SDK can no longer guarantee 0-allocations during frame cycling /// </remarks> public void Keep() { NativeMethods.rs2_keep_frame(Handle); } /// <summary> /// Gets a value indicating whether frame is a composite frame /// <para>Shorthand for <c>Is(<see cref="Extension.CompositeFrame"/>)</c></para> /// </summary> /// <seealso cref="Is(Extension)"/> /// <value><see langword="true"/> if frame is a composite frame and false otherwise</value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsComposite { get { return Is(Extension.CompositeFrame); } } /// <summary>Gets the size of the frame data</summary> /// <value>The size of the frame data</value> public int DataSize { get { object error; return NativeMethods.rs2_get_frame_data_size(Handle, out error); } } /// <summary>Gets a pointer to the frame data</summary> /// <value>pointer to the start of the frame data</value> public IntPtr Data { get { object error; return NativeMethods.rs2_get_frame_data(Handle, out error); } } /// <summary> /// Returns the stream profile that was used to start the stream of this frame /// </summary> /// <typeparam name="T">StreamProfile or subclass type</typeparam> /// <returns>the stream profile that was used to start the stream of this frame</returns> public T GetProfile<T>() where T : StreamProfile { object error; var ptr = NativeMethods.rs2_get_frame_stream_profile(Handle, out error); return StreamProfile.Create<T>(ptr); } /// <summary> /// Gets the stream profile that was used to start the stream of this frame /// </summary> /// <see cref="GetProfile{T}"/> public StreamProfile Profile => GetProfile<StreamProfile>(); /// <summary>Gets the frame number of the frame</summary> /// <value>the frame nubmer of the frame</value> public ulong Number { get { object error; return NativeMethods.rs2_get_frame_number(Handle, out error); } } /// <summary>Gets timestamp from frame handle in milliseconds</summary> /// <value>the timestamp of the frame in milliseconds</value> public double Timestamp { get { object error; return NativeMethods.rs2_get_frame_timestamp(Handle, out error); } } /// <summary>Gets the sensor owning the frame</summary> /// <value>the pointer to the sensor owning the frame</value> public IntPtr Sensor { get { object error; return NativeMethods.rs2_get_frame_sensor(Handle, out error); } } /// <summary>Gets the timestamp domain from frame handle. timestamps can only be comparable if they are in common domain</summary> /// <remarks> /// (for example, depth timestamp might come from system time while color timestamp might come from the device) /// this method is used to check if two timestamp values are comparable (generated from the same clock) /// </remarks> /// <value>the timestamp domain of the frame (camera / microcontroller / system time)</value> public TimestampDomain TimestampDomain { get { object error; return NativeMethods.rs2_get_frame_timestamp_domain(Handle, out error); } } public long this[FrameMetadataValue frame_metadata] { get { return GetFrameMetadata(frame_metadata); } } /// <summary>retrieve metadata from frame handle</summary> /// <param name="frame_metadata">the <see cref="FrameMetadataValue">FrameMetadataValue</see> whose latest frame we are interested in</param> /// <returns>the metadata value</returns> public long GetFrameMetadata(FrameMetadataValue frame_metadata) { object error; return NativeMethods.rs2_get_frame_metadata(Handle, frame_metadata, out error); } /// <summary>determine device metadata</summary> /// <param name="frame_metadata">the metadata to check for support</param> /// <returns>true if device has this metadata</returns> public bool SupportsFrameMetaData(FrameMetadataValue frame_metadata) { object error; return NativeMethods.rs2_supports_frame_metadata(Handle, frame_metadata, out error) != 0; } #if DEBUGGER_METADATA private static readonly FrameMetadataValue[] MetadataValues = Enum.GetValues(typeof(FrameMetadataValue)) as FrameMetadataValue[]; public ICollection<KeyValuePair<FrameMetadataValue, long>> MetaData { get { return MetadataValues .Where(m => SupportsFrameMetaData(m)) .Select(m => new KeyValuePair<FrameMetadataValue, long>(m, GetFrameMetadata(m))) .ToArray(); } } #endif } }
36.427481
148
0.571982
[ "Apache-2.0" ]
BenDavisson/librealsense
wrappers/csharp/Intel.RealSense/Frames/Frame.cs
9,546
C#
using Microsoft.AspNetCore.Components; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace TrabalhoLeituraCepBootstrap.Pages { public class IndexBase:ComponentBase { [Inject] public HttpClient HttpClient { get; set; } public string CepInput { get; set; } public DadosCep DadosCep { get; set; } public async Task BuscaCep() { var resultado = await HttpClient.GetAsync($"http://cep.republicavirtual.com.br/web_cep.php?cep={CepInput}&formato=json"); DadosCep = JsonSerializer.Deserialize<DadosCep>(await resultado.Content.ReadAsStringAsync()); } } }
26.192308
133
0.674009
[ "MIT" ]
KatharinaPedrosa/BuscadorCep
TrabalhoLeituraCepBootstrap/Pages/IndexBase.cs
683
C#
using Newtonsoft.Json.Linq; using Xunit; using Yaapii.Atoms.IO; namespace Yaapii.JSON.Test { public sealed class JSONPatchedTests { [Fact] public void Patches2() { var unpatched = new JSONOf( new ResourceOf( "Datum/data.json", typeof(JSONTests) ) ); var patched = new JSONPatched( unpatched, $"$.addresses[0].name", "Quick Stop" ); Assert.Equal( "Quick Stop", patched.Value($"$.addresses[0].name") ); } [Fact] public void WorksOnMultipleLevels() { Assert.Equal( "success", new JSONPatched( new JSONOf( new JObject( new JProperty("object", new JObject( new JProperty("value", "empty") ) ) ) ), "object.value", "success" ).Value("object.value") ); } } }
24.836364
67
0.338946
[ "MIT" ]
icarus-consulting/Yaapii.JSON
tests/Test.Yaapii.JSON/JSONPatchedTests.cs
1,366
C#
namespace SIS.MvcFramework { public class ErrorViewModel { public string Error { get; set; } } }
16.714286
41
0.615385
[ "MIT" ]
radrex/SoftuniCourses
C# Web Developer/C# Web/C# Web Basics/Softuni Information Services/SIS/SIS.MvcFramework/ErrorViewModel.cs
119
C#
using System; using System.Reflection; using AutoFixture.Kernel; namespace AutoFixture { /// <summary> /// Creates random <see cref="DateTime"/> specimens. /// </summary> /// <remarks> /// The generated <see cref="DateTime"/> values will be within /// a range of ± two years from today's date, /// unless a different range has been specified in the constructor. /// </remarks> public class RandomDateTimeSequenceGenerator : ISpecimenBuilder { private readonly RandomNumericSequenceGenerator randomizer; /// <summary> /// Initializes a new instance of the <see cref="RandomDateTimeSequenceGenerator"/> class. /// </summary> public RandomDateTimeSequenceGenerator() : this(DateTime.Today.AddYears(-2), DateTime.Today.AddYears(2)) { } /// <summary> /// Initializes a new instance of the <see cref="RandomDateTimeSequenceGenerator"/> class /// for a specific range of dates. /// </summary> /// <param name="minDate">The lower bound of the date range.</param> /// <param name="maxDate">The upper bound of the date range.</param> /// <exception cref="ArgumentException"> /// <paramref name="minDate"/> is greater than <paramref name="maxDate"/>. /// </exception> public RandomDateTimeSequenceGenerator(DateTime minDate, DateTime maxDate) { if (minDate >= maxDate) { throw new ArgumentException("The 'minDate' argument must be less than the 'maxDate'."); } this.randomizer = new RandomNumericSequenceGenerator(minDate.Ticks, maxDate.Ticks); } /// <summary> /// Creates a new <see cref="DateTime"/> specimen based on a request. /// </summary> /// <param name="request">The request that describes what to create.</param> /// <param name="context">Not used.</param> /// <returns> /// A new <see cref="DateTime"/> specimen, if <paramref name="request"/> is a request for a /// <see cref="DateTime"/> value; otherwise, a <see cref="NoSpecimen"/> instance. /// </returns> public object Create(object request, ISpecimenContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); return IsNotDateTimeRequest(request) ? new NoSpecimen() : this.CreateRandomDate(context); } private static bool IsNotDateTimeRequest(object request) { return !typeof(DateTime).GetTypeInfo().IsAssignableFrom(request as Type); } private object CreateRandomDate(ISpecimenContext context) { return new DateTime(this.GetRandomNumberOfTicks(context)); } private long GetRandomNumberOfTicks(ISpecimenContext context) { return (long)this.randomizer.Create(typeof(long), context); } } }
37.8625
103
0.607791
[ "MIT" ]
AutoFixture/AutoFixture
Src/AutoFixture/RandomDateTimeSequenceGenerator.cs
3,032
C#
using UnityEngine; using UnityEngine.UI; using MLAgents; using MLAgents.Sensors; using MLAgents.SideChannels; public class TennisAgent : Agent { [Header("Specific to Tennis")] public GameObject ball; public bool invertX; public int score; public GameObject myArea; public float angle; public float scale; Text m_TextComponent; Rigidbody m_AgentRb; Rigidbody m_BallRb; float m_InvertMult; EnvironmentParameters m_ResetParams; // Looks for the scoreboard based on the name of the gameObjects. // Do not modify the names of the Score GameObjects const string k_CanvasName = "Canvas"; const string k_ScoreBoardAName = "ScoreA"; const string k_ScoreBoardBName = "ScoreB"; public override void Initialize() { m_AgentRb = GetComponent<Rigidbody>(); m_BallRb = ball.GetComponent<Rigidbody>(); var canvas = GameObject.Find(k_CanvasName); GameObject scoreBoard; m_ResetParams = Academy.Instance.EnvironmentParameters; if (invertX) { scoreBoard = canvas.transform.Find(k_ScoreBoardBName).gameObject; } else { scoreBoard = canvas.transform.Find(k_ScoreBoardAName).gameObject; } m_TextComponent = scoreBoard.GetComponent<Text>(); SetResetParameters(); } public override void CollectObservations(VectorSensor sensor) { sensor.AddObservation(m_InvertMult * (transform.position.x - myArea.transform.position.x)); sensor.AddObservation(transform.position.y - myArea.transform.position.y); sensor.AddObservation(m_InvertMult * m_AgentRb.velocity.x); sensor.AddObservation(m_AgentRb.velocity.y); sensor.AddObservation(m_InvertMult * (ball.transform.position.x - myArea.transform.position.x)); sensor.AddObservation(ball.transform.position.y - myArea.transform.position.y); sensor.AddObservation(m_InvertMult * m_BallRb.velocity.x); sensor.AddObservation(m_BallRb.velocity.y); sensor.AddObservation(m_InvertMult * gameObject.transform.rotation.z); } public override void OnActionReceived(float[] vectorAction) { var moveX = Mathf.Clamp(vectorAction[0], -1f, 1f) * m_InvertMult; var moveY = Mathf.Clamp(vectorAction[1], -1f, 1f); var rotate = Mathf.Clamp(vectorAction[2], -1f, 1f) * m_InvertMult; if (moveY > 0.5 && transform.position.y - transform.parent.transform.position.y < -1.5f) { m_AgentRb.velocity = new Vector3(m_AgentRb.velocity.x, 7f, 0f); } m_AgentRb.velocity = new Vector3(moveX * 30f, m_AgentRb.velocity.y, 0f); m_AgentRb.transform.rotation = Quaternion.Euler(0f, -180f, 55f * rotate + m_InvertMult * 90f); if (invertX && transform.position.x - transform.parent.transform.position.x < -m_InvertMult || !invertX && transform.position.x - transform.parent.transform.position.x > -m_InvertMult) { transform.position = new Vector3(-m_InvertMult + transform.parent.transform.position.x, transform.position.y, transform.position.z); } m_TextComponent.text = score.ToString(); } public override void Heuristic(float[] actionsOut) { actionsOut[0] = Input.GetAxis("Horizontal"); // Racket Movement actionsOut[1] = Input.GetKey(KeyCode.Space) ? 1f : 0f; // Racket Jumping actionsOut[2] = Input.GetAxis("Vertical"); // Racket Rotation } public override void OnEpisodeBegin() { m_InvertMult = invertX ? -1f : 1f; transform.position = new Vector3(-m_InvertMult * Random.Range(6f, 8f), -1.5f, -1.8f) + transform.parent.transform.position; m_AgentRb.velocity = new Vector3(0f, 0f, 0f); SetResetParameters(); } public void SetRacket() { angle = m_ResetParams.GetWithDefault("angle", 55); gameObject.transform.eulerAngles = new Vector3( gameObject.transform.eulerAngles.x, gameObject.transform.eulerAngles.y, m_InvertMult * angle ); } public void SetBall() { scale = m_ResetParams.GetWithDefault("scale", .5f); ball.transform.localScale = new Vector3(scale, scale, scale); } public void SetResetParameters() { SetRacket(); SetBall(); } }
34.515625
131
0.6555
[ "Apache-2.0" ]
Oningyo/ml-agents
Project/Assets/ML-Agents/Examples/Tennis/Scripts/TennisAgent.cs
4,418
C#
// Copyright Epic Games, Inc. All Rights Reserved. // This file is automatically generated. Changes to this file may be overwritten. namespace Epic.OnlineServices.P2P { /// <summary> /// Structure containing information about who would like to close connections, and by what socket ID /// </summary> public class CloseConnectionsOptions { /// <summary> /// The Product User ID of the local user who would like to close all connections that use a particular socket ID /// </summary> public ProductUserId LocalUserId { get; set; } /// <summary> /// The socket ID of the connections to close /// </summary> public SocketId SocketId { get; set; } } [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 8)] internal struct CloseConnectionsOptionsInternal : ISettable, System.IDisposable { private int m_ApiVersion; private System.IntPtr m_LocalUserId; private System.IntPtr m_SocketId; public ProductUserId LocalUserId { set { Helper.TryMarshalSet(ref m_LocalUserId, value); } } public SocketId SocketId { set { Helper.TryMarshalSet<SocketIdInternal, SocketId>(ref m_SocketId, value); } } public void Set(CloseConnectionsOptions other) { if (other != null) { m_ApiVersion = P2PInterface.CloseconnectionsApiLatest; LocalUserId = other.LocalUserId; SocketId = other.SocketId; } } public void Set(object other) { Set(other as CloseConnectionsOptions); } public void Dispose() { Helper.TryMarshalDispose(ref m_LocalUserId); Helper.TryMarshalDispose(ref m_SocketId); } } }
24.863636
115
0.720293
[ "MIT" ]
CreepyAnt/EpicOnlineTransport
Mirror/Runtime/Transport/EpicOnlineTransport/EOSSDK/Generated/P2P/CloseConnectionsOptions.cs
1,641
C#
using Microsoft.AspNetCore.Mvc; using RobustErrorHandler.AspNetCore; using RobustErrorHandler.AspNetCore.Sample.DTO; using RobustErrorHandler.AspNetCore.ShapeDomain; using RobustErrorHandler.Core; namespace RobustErrorHandler.AspNetCore.Sample.Controllers { [ApiController] [Route("[controller]")] public class RobustErrorHandlerControllercs : ControllerBase { [HttpPost] [Route("/Calculate/{type}/Perimeter")] public ActionResult<bool> GetShapePeremeter(ShapeType type, [FromBody]ShapeDTO shapeData) { switch (type) { case ShapeType.Rectangle: { return ShapeDomain.Rectangle.Create(shapeData.Sides) .Map((data) => { return true; }).ToActionResult(); } default: { break; } } return false; } } }
29.243243
97
0.512015
[ "MIT" ]
arvylagunamayor/RobustErrorHandler.AspNetCore
sample/RobustErrorHandler.AspNetCore.Sample/Controllers/RobustErrorHandlerControllercs.cs
1,084
C#
using DbConnector.Core.Extensions; using DbConnector.Tests.Entities; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace DbConnector.Tests { public class ReadCustomTests : TestBase { [Fact] public void ReadTo() { var result = _dbConnector.ReadTo<IEnumerable<Currency>>( (cmdActions) => { cmdActions.Enqueue((cmd) => cmd.CommandText = "SELECT TOP(3) * FROM [Sales].[Currency]"); }, (d, e, odr) => { return e.IsBuffered ? odr.ToList<Currency>(e.Token, e.JobCommand) : odr.ToEnumerable<Currency>(e.Token, e.JobCommand); } ).Execute(); Assert.Equal(3, result.Count()); var values = (result as List<Currency>); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void ReadTo_Deferred() { var result = _dbConnector.ReadTo<IEnumerable<Currency>>( (cmdActions) => { cmdActions.Enqueue((cmd) => cmd.CommandText = "SELECT TOP(3) * FROM [Sales].[Currency]"); }, (d, e, odr) => { return e.IsBuffered ? odr.ToList<Currency>(e.Token, e.JobCommand) : odr.ToEnumerable<Currency>(e.Token, e.JobCommand); } ).WithBuffering(false).Execute(); Assert.Equal(3, result.Count()); var values = result.ToList(); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void Build() { var result = _dbConnector.Build<IEnumerable<Currency>>( (cmdActions) => { cmdActions.Enqueue((cmd) => cmd.CommandText = "SELECT TOP(3) * FROM [Sales].[Currency]"); }, (d, e) => { using (var odr = e.Command.ExecuteReader(e.JobCommand.CommandBehavior ?? (CommandBehavior.SequentialAccess | CommandBehavior.Default))) { return odr.ToList<Currency>(e.Token, e.JobCommand); } } ).Execute(); Assert.Equal(3, result.Count()); var values = (result as List<Currency>); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void ReadTo_Simple() { var result = _dbConnector.ReadTo<IEnumerable<Currency>>("SELECT TOP(3) * FROM [Sales].[Currency]", null, (d, e, odr) => { return e.IsBuffered ? odr.ToList<Currency>(e.Token, e.JobCommand) : odr.ToEnumerable<Currency>(e.Token, e.JobCommand); }).Execute(); Assert.Equal(3, result.Count()); var values = (result as List<Currency>); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void ReadTo_Simple_Deferred() { var result = _dbConnector.ReadTo<IEnumerable<Currency>>("SELECT TOP(3) * FROM [Sales].[Currency]", null, (d, e, odr) => { return e.IsBuffered ? odr.ToList<Currency>(e.Token, e.JobCommand) : odr.ToEnumerable<Currency>(e.Token, e.JobCommand); }).WithBuffering(false).Execute(); Assert.Equal(3, result.Count()); var values = result.ToList(); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void Build_Simple() { var result = _dbConnector.Build<IEnumerable<Currency>>("SELECT TOP(3) * FROM [Sales].[Currency]", null, (d, e) => { using (var odr = e.Command.ExecuteReader(e.JobCommand.CommandBehavior ?? (CommandBehavior.SequentialAccess | CommandBehavior.Default))) { return odr.ToList<Currency>(e.Token, e.JobCommand); } }).Execute(); Assert.Equal(3, result.Count()); var values = (result as List<Currency>); Assert.Equal("AED", values[0].CurrencyCode); Assert.Equal("AFA", values[1].CurrencyCode); Assert.Equal("ALL", values[2].CurrencyCode); } [Fact] public void Read_Custom_Connection() { using (var conn = new SqlConnection(TestBase.ConnectionString)) { conn.Open(); var x = _dbConnector.Read<Currency>("SELECT TOP(1) * FROM [Sales].[Currency]").Execute(conn); var y = _dbConnector.Read<Currency>("SELECT TOP(3) * FROM [Sales].[Currency]").Execute(conn); var z = _dbConnector.Read<Currency>("SELECT TOP(2) * FROM [Sales].[Currency]").Execute(conn); Assert.Single(x); Assert.Equal(3, y.Count()); Assert.Equal(2, z.Count()); } } [Fact] public void Read_Custom_Transaction() { using (var conn = new SqlConnection(TestBase.ConnectionString)) { conn.Open(); using (var transaction = conn.BeginTransaction()) { var x = _dbConnector.Read<Currency>("SELECT TOP(1) * FROM [Sales].[Currency]").Execute(transaction); var y = _dbConnector.Read<Currency>("SELECT TOP(3) * FROM [Sales].[Currency]").Execute(transaction); var z = _dbConnector.Read<Currency>("SELECT TOP(2) * FROM [Sales].[Currency]").Execute(transaction); Assert.Single(x); Assert.Equal(3, y.Count()); Assert.Equal(2, z.Count()); transaction.Commit(); } } } } }
33.65641
151
0.523541
[ "Apache-2.0" ]
SavantBuffer/DbConnector
DbConnector.Tests/ReadCustomTests.cs
6,563
C#
using IdentityServer4.Models; using IdentityServer4.Services; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using static IdentityServer4.IdentityServerConstants; namespace IdentityServerCustomClaims { public class CustomProfileService : IProfileService { public Task GetProfileDataAsync(ProfileDataRequestContext context) { var claims = new List<Claim> { new Claim("CustomClaim", "My custom claim value"), }; if(context.Caller == ProfileDataCallers.UserInfoEndpoint) { context.IssuedClaims.AddRange(claims); } return Task.FromResult(0); } public Task IsActiveAsync(IsActiveContext context) { return Task.FromResult(0); } } }
26.371429
74
0.625135
[ "Apache-2.0" ]
Mallekoppie/IdentityServer
IdentityServerCustomClaims/CustomProfileService.cs
925
C#
using System.Collections; using System.Collections.Generic; using FairyAnalyzer.Package; using UnityEngine; using UnityEditor; using System.IO; public class Menu { [MenuItem("工具/打开GUI项目")] public static void Process() { var argPath = Path.Combine("UIProject/UIProject", "FairyGUI-Examples.fairy"); var guiBat = Path.Combine("UIProject/UIProject", "FairyGUI-Editor"); var exePath = Path.Combine(guiBat, "FairyGUI-Editor.exe"); argPath = Path.Combine(Directory.GetCurrentDirectory(), argPath); exePath = Path.Combine(Directory.GetCurrentDirectory(), exePath); System.Diagnostics.Process.Start(exePath, argPath); } [MenuItem("工具/解析")] public static void Parse() { var packagePath = string.Format("{0}/../UIProject/UIProject", Application.dataPath); var outputPath = string.Format("{0}/../Output", packagePath); PackageLoader.Load(packagePath, outputPath); } }
32.129032
93
0.661647
[ "MIT" ]
Minamiyama/FairyGUI-unity
Examples.Unity5/Assets/FairyAnalyzer/Editor/Analyzer/Menu.cs
1,018
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("kcdnug.Mobile.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("kcdnug.Mobile.UWP")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
36.241379
84
0.740247
[ "MIT" ]
AlienArc/kcdnug
src/kcdnug.Mobile.UWP/Properties/AssemblyInfo.cs
1,054
C#
using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using SampleAutofacFunction.Services; using SampleAutofacFunction.Settings; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace SampleAutofacFunction.Functions { public class Function2 : IDisposable { private readonly IService1 _service1; private readonly MySettings _settings; private readonly ILogger _logger; private readonly TelemetryClient _client; private readonly Guid _id = Guid.NewGuid(); public Function2(IService1 service1, MySettings settings, ILogger logger, TelemetryClient client) { _service1 = service1; _settings = settings; _logger = logger; _client = client; _logger.LogWarning($"Creating {this}"); } public void Dispose() { _logger.LogWarning($"Disposing {this}"); } [FunctionName(nameof(Function2))] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req) { _logger.LogInformation("C# HTTP trigger function processed a request."); string value = _service1.ToString(); string responseMessage = @$" This HTTP triggered function executed successfully. Injected Service Value: {value} MySettings Value1: {_settings.Value1} MySettings Value2: {_settings.Value2} UrlRequested: {req.Path} "; _client.TrackEvent("HTTP Function Event", new Dictionary<string, string>() { { "Injected Service Value", value }, { "MySettings Value1", _settings.Value1 }, { "MySettings Value2", _settings.Value2 }, { "UrlRequested", req.Path} }); await Task.Delay(1000); _logger.LogInformation(responseMessage); return new OkObjectResult(responseMessage); } public override string ToString() { return $"{_id} ({nameof(Function2)})"; } } }
31.205479
105
0.643986
[ "MIT" ]
junalmeida/autofac-azurefunctions
SampleAutofacFunction/Functions/Function2.cs
2,278
C#
namespace RabbitMQEventbus.IntegrationEvents.Events; public record NewPulseDataPosted : Event { public string DeviceId { get; private init; } public uint Pulse { get; private init; } public uint Systolic { get; private init; } public uint Diastolic { get; private init; } public DateTime Time { get; private init; } public NewPulseDataPosted(string deviceId, uint pulse, uint systolic, uint diastolic) { DeviceId = deviceId; Pulse = pulse; Systolic = systolic; Diastolic = diastolic; Time = DateTime.UtcNow; } }
28
89
0.668367
[ "MIT" ]
AbeneAb/MembershipManagement
src/EventBus/RabbitMQEventbus/IntegrationEvents/Events/NewPulseDataPosted.cs
590
C#
using LibPDBinding.Managed.Data; using LibPDBinding.Managed.Utils; using LibPDBinding.Native; namespace LibPDBinding.Managed { /// <summary> /// Array in Pd. /// </summary> public sealed class PdArray { readonly string _name; /// <summary> /// Gets the name of the array in Pd. /// </summary> /// <value>The name.</value> public string Name { get { return _name; } } internal PdArray (string name) { _name = name; } /// <summary> /// Gets the size of the Pd array. /// </summary> /// <value>The size.</value> public int Size { get { return Audio.arraysize (_name); } } /// <summary> /// Read values from the array. /// </summary> /// <param name="start">Start position for reading.</param> /// <param name="length">Number of values to be read.</param> public float[] Read (int start, int length) { float[] arrayContent = new float [length]; int status = Audio.read_array (arrayContent, _name, start, length); if (status != 0) { throw new PdProcessException (status, "read_array"); } return arrayContent; } /// <summary> /// Writes values to the array. /// </summary> /// <param name="newContent">New content to be written.</param> /// <param name="start">Start position for writing.</param> /// <param name="length">Number of values to be written.</param> public void Write (float[] newContent, int start, int length) { int status = Audio.write_array (_name, start, newContent, length); if (status != 0) { throw new PdProcessException (status, "write_array"); } } /// <summary> /// Resizes the Pd array. /// /// NB: This is an expensive method, use sparingly. /// </summary> /// <param name="length">The new size of the array.</param> public void Resize (int length) { MessageInvocation.SendMessage (_name, "resize", new Float (length)); } } }
25.445946
71
0.635688
[ "MIT" ]
Tiltification/sonic-tilt
android/PdCore/src/main/jni/libpd/csharp/Managed/PdArray.cs
1,885
C#
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using Xamarin.Forms; using Xamarin.Forms.Internals; using EssentialUIKit.Models.Navigation; using System.Runtime.Serialization; namespace EssentialUIKit.ViewModels.Navigation { /// <summary> /// ViewModel for album page. /// </summary> [Preserve(AllMembers = true)] [DataContract] public class AlbumViewModel : INotifyPropertyChanged { #region Fields private ObservableCollection<Album> albumInfo; private Command addCommand; private Command viewAllCommand; private Command imageTapCommand; #endregion #region Properties /// <summary> /// Gets or sets the value for the album info. /// </summary> [DataMember(Name = "albumInfos")] public ObservableCollection<Album> AlbumInfo { get { return this.albumInfo; } set { if (this.albumInfo == value) { return; } this.albumInfo = value; this.NotifyPropertyChanged(); } } #endregion #region Constructor public AlbumViewModel() { } #endregion #region Event /// <summary> /// The declaration of the property changed event. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Command /// <summary> /// Gets or sets the command that is executed when the Add button is clicked. /// </summary> public Command AddCommand { get { return this.addCommand ?? (this.addCommand = new Command(this.AddButtonClicked)); } } /// <summary> /// Gets or sets the command that is executed when the View all button is clicked. /// </summary> public Command ViewAllCommand { get { return this.viewAllCommand ?? (this.viewAllCommand = new Command(this.ViewAllButtonClicked)); } } /// <summary> /// Gets or sets the image tap command. /// </summary> public Command ImageTapCommand { get { return this.imageTapCommand ?? (this.imageTapCommand = new Command(this.OnImageTapped)); } } #endregion #region Methods /// <summary> /// The PropertyChanged event occurs when changing the value of property. /// </summary> /// <param name="propertyName">Property name</param> public void NotifyPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Invoked when the Add button is clicked. /// </summary> /// <param name="obj">The object</param> private void AddButtonClicked(object obj) { // Do something } /// <summary> /// Invoked when the View all button is clicked. /// </summary> /// <param name="obj">The object</param> private void ViewAllButtonClicked(object obj) { // Do something } /// <summary> /// Invoked when the album image is clicked. /// </summary> /// <param name="obj">The Object</param> private void OnImageTapped(object obj) { // Do Something } #endregion } }
25.763889
113
0.555526
[ "MIT" ]
Humphryshikunzi/essential-ui-kit-for-xamarin.forms
EssentialUIKit/ViewModels/Navigation/AlbumViewModel.cs
3,712
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Runtime.CompilerServices; using BepuPhysics.Collidables; using BepuPhysics.CollisionDetection; using BepuPhysics.Constraints; using BepuUtilities; using BepuUtilities.Collections; using BepuUtilities.Memory; namespace BepuPhysics { public struct DefaultPoseIntegratorCallbacks : IPoseIntegratorCallbacks { public Vector3 Gravity; public float LinearDamping; public float AngularDamping; Vector3 gravityDt; float linearDampingDt; float angularDampingDt; private float _dt; private QuickDictionary<int, float, IntComparer> _angularDampingDictionary; private QuickDictionary<int, float, IntComparer> _linearDampingDictionary; public struct IntComparer : IEqualityComparerRef<int> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(ref int a, ref int b) { return a == b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Hash(ref int item) { return item; } } public void CustomAngularDamping(int bodyIndex, float angularDamping, IUnmanagedMemoryPool pool) { if (angularDamping == AngularDamping) { _angularDampingDictionary.FastRemove(bodyIndex); return; } _angularDampingDictionary.Add(bodyIndex, angularDamping, pool); } public void CustomLinearDamping(int bodyIndex, float linearDamping, IUnmanagedMemoryPool pool) { if (linearDamping == LinearDamping) { _linearDampingDictionary.FastRemove(bodyIndex); return; } _linearDampingDictionary.Add(bodyIndex, linearDamping, pool); } public AngularIntegrationMode AngularIntegrationMode => AngularIntegrationMode.Nonconserving; public DefaultPoseIntegratorCallbacks(IUnmanagedMemoryPool pool, Vector3? gravity = null, float linearDamping = .03f, float angularDamping = .03f) : this() { Gravity = gravity ?? new Vector3(0, -9.81f, 0); LinearDamping = linearDamping; AngularDamping = angularDamping; _angularDampingDictionary = new QuickDictionary<int, float, IntComparer>(1, pool); _linearDampingDictionary = new QuickDictionary<int, float, IntComparer>(1, pool); _linearDampingDictionary.Add(-1, LinearDamping, pool); _angularDampingDictionary.Add(-1, AngularDamping, pool); } public void PrepareForIntegration(float dt) { _dt = dt; //No reason to recalculate gravity * dt for every body; just cache it ahead of time. gravityDt = Gravity * dt; //Since this doesn't use per-body damping, we can precalculate everything. linearDampingDt = (float)Math.Pow(MathHelper.Clamp(1 - LinearDamping, 0, 1), dt); angularDampingDt = (float)Math.Pow(MathHelper.Clamp(1 - AngularDamping, 0, 1), dt); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia localInertia, int workerIndex, ref BodyVelocity velocity) { //Note that we avoid accelerating kinematics. Kinematics are any body with an inverse mass of zero (so a mass of ~infinity). No force can move them. if (localInertia.InverseMass > 0) { // ref var handle = ref Simulation.Bodies.ActiveSet.IndexToHandle[0]; // ref var index = ref Unsafe.Add(ref handle, bodyIndex); if (_linearDampingDictionary.TryGetValue(bodyIndex, out var linearDamping)) { linearDamping = (float)Math.Pow(MathHelper.Clamp(1 - linearDamping, 0, 1), _dt); velocity.Linear = (velocity.Linear + gravityDt) * linearDamping; } else { velocity.Linear = (velocity.Linear + gravityDt) * linearDampingDt; } if (_angularDampingDictionary.TryGetValue(bodyIndex, out var angularDamping)) { angularDamping = (float)Math.Pow(MathHelper.Clamp(1 - angularDamping, 0, 1), _dt); velocity.Angular = velocity.Angular * angularDamping; } else { velocity.Angular = velocity.Angular * angularDampingDt; } } //Implementation sidenote: Why aren't kinematics all bundled together separately from dynamics to avoid this per-body condition? //Because kinematics can have a velocity- that is what distinguishes them from a static object. The solver must read velocities of all bodies involved in a constraint. //Under ideal conditions, those bodies will be near in memory to increase the chances of a cache hit. If kinematics are separately bundled, the the number of cache //misses necessarily increases. Slowing down the solver in order to speed up the pose integrator is a really, really bad trade, especially when the benefit is a few ALU ops. //Note that you CAN technically modify the pose in IntegrateVelocity. The PoseIntegrator has already integrated the previous velocity into the position, but you can modify it again //if you really wanted to. //This is also a handy spot to implement things like position dependent gravity or per-body damping. } public void Dispose(IUnmanagedMemoryPool pool) { _angularDampingDictionary.Dispose(pool); _linearDampingDictionary.Dispose(pool); } } public unsafe struct DefaultNarrowPhaseCallbacks : INarrowPhaseCallbacks { public SpringSettings ContactSpringiness; public void Initialize(Simulation simulation) { //Use a default if the springiness value wasn't initialized. if (ContactSpringiness.AngularFrequency == 0 && ContactSpringiness.TwiceDampingRatio == 0) ContactSpringiness = new SpringSettings(30, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowContactGeneration(int workerIndex, CollidableReference a, CollidableReference b) { return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB) { return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] void ConfigureMaterial(out PairMaterialProperties pairMaterial) { pairMaterial.FrictionCoefficient = 4; pairMaterial.MaximumRecoveryVelocity = 2f; pairMaterial.SpringSettings = ContactSpringiness; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ConfigureContactManifold(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB, ref ConvexContactManifold manifold) { return true; } public void Dispose() { } public bool ConfigureContactManifold<TManifold>(int workerIndex, CollidablePair pair, ref TManifold manifold, out PairMaterialProperties pairMaterial) where TManifold : struct, IContactManifold<TManifold> { ConfigureMaterial(out pairMaterial); return true; } } }
43.216667
212
0.645584
[ "Apache-2.0" ]
FEETB24/bepuphysics2
BepuPhysics/DefaultCallbacks.cs
7,781
C#
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.38Release // Tag = production/akw/20.38.00-0-geccbce3 //////////////////////////////////////////////////////////////////////////////// #endregion namespace Dynastream.Fit { /// <summary> /// Implements the profile TurnType type as an enum /// </summary> public enum TurnType : byte { ArrivingIdx = 0, ArrivingLeftIdx = 1, ArrivingRightIdx = 2, ArrivingViaIdx = 3, ArrivingViaLeftIdx = 4, ArrivingViaRightIdx = 5, BearKeepLeftIdx = 6, BearKeepRightIdx = 7, ContinueIdx = 8, ExitLeftIdx = 9, ExitRightIdx = 10, FerryIdx = 11, Roundabout45Idx = 12, Roundabout90Idx = 13, Roundabout135Idx = 14, Roundabout180Idx = 15, Roundabout225Idx = 16, Roundabout270Idx = 17, Roundabout315Idx = 18, Roundabout360Idx = 19, RoundaboutNeg45Idx = 20, RoundaboutNeg90Idx = 21, RoundaboutNeg135Idx = 22, RoundaboutNeg180Idx = 23, RoundaboutNeg225Idx = 24, RoundaboutNeg270Idx = 25, RoundaboutNeg315Idx = 26, RoundaboutNeg360Idx = 27, RoundaboutGenericIdx = 28, RoundaboutNegGenericIdx = 29, SharpTurnLeftIdx = 30, SharpTurnRightIdx = 31, TurnLeftIdx = 32, TurnRightIdx = 33, UturnLeftIdx = 34, UturnRightIdx = 35, IconInvIdx = 36, IconIdxCnt = 37, Invalid = 0xFF } }
32.732394
83
0.57315
[ "MIT" ]
wpbest/CodeTest
FitSDKRelease_20.38.00/cs/Dynastream/Fit/Profile/Types/TurnType.cs
2,324
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (https://www.specflow.org/). // SpecFlow Version:3.9.0.0 // SpecFlow Generator Version:3.9.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Sfa.Tl.ResultsAndCertificationAutomation.Tests.Features.AssessmentEntries { using TechTalk.SpecFlow; using System; using System.Linq; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "3.9.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("1917_AssessmentEntryUploadSuccessful")] public partial class _1917_AssessmentEntryUploadSuccessfulFeature { private TechTalk.SpecFlow.ITestRunner testRunner; private string[] _featureTags = ((string[])(null)); #line 1 "1917_AssessmentEntryUploadSuccessful.feature" #line hidden [NUnit.Framework.OneTimeSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Tests/Features/AssessmentEntries", "1917_AssessmentEntryUploadSuccessful", "\tAs a Registrations Editor\r\n\tI need to see that my upload file has been successfu" + "l\r\n\tSo that I can ensure my data has been uploaded", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.OneTimeTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void TestTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("1917_Assessment upload Success")] [NUnit.Framework.IgnoreAttribute("Ignored scenario")] [NUnit.Framework.CategoryAttribute("RegressionTest")] [NUnit.Framework.CategoryAttribute("AssessmentEntriesUpload")] public virtual void _1917_AssessmentUploadSuccess() { string[] tagsOfScenario = new string[] { "Ignore", "RegressionTest", "AssessmentEntriesUpload"}; System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("1917_Assessment upload Success", null, tagsOfScenario, argumentsOfScenario, this._featureTags); #line 7 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 8 testRunner.Given("I have logged in as a \"RegistrationEditor\" user", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line hidden #line 9 testRunner.And("I am on Registrations upload page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 10 testRunner.And("I have a Academic Year in \"RegistrationsDataForAssessments.csv\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 11 testRunner.And("I upload \"RegistrationsDataForAssessments.csv\" file", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 12 testRunner.And("I navigated Home page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 13 testRunner.And("I am on Assessment entries upload page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 14 testRunner.And("I have a active Assessment Series in \"AssessmentEntrySuccessfulData.csv\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 15 testRunner.When("I upload \"AssessmentEntrySuccessfulData.csv\" file", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 16 testRunner.And("I click on \"Upload\" button", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 17 testRunner.Then("I should see Upload success page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } } } #pragma warning restore #endregion
43.129252
302
0.642587
[ "MIT" ]
SkillsFundingAgency/tl-results-and-certification-automation-suite
src/Sfa.Tl.ResultsAndCertificationAutomation/Tests/Features/AssessmentEntries/1917_AssessmentEntryUploadSuccessful.feature.cs
6,342
C#
using Nethereum.ABI.FunctionEncoding; using Nethereum.ABI.Model; using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.JsonRpc.Client; using Newtonsoft.Json.Linq; using System.Collections.Generic; namespace Nethereum.Contracts { public static class ErrorExtensions { private static FunctionCallDecoder _functionCallDecoder = new FunctionCallDecoder(); public static bool IsExceptionEncodedDataForError<TError>(this string data) { var errorABI = ABITypedRegistry.GetError<TError>(); return errorABI.IsExceptionEncodedDataForError(data); } public static bool IsExceptionEncodedDataForError(this string data, string signature) { return _functionCallDecoder.IsDataForFunction(signature, data); } public static bool IsErrorABIForErrorType<TError>(this ErrorABI errorABI) { var errorTypeABI = ABITypedRegistry.GetError<TError>(); return errorTypeABI.Sha3Signature.ToLowerInvariant() == errorABI.Sha3Signature.ToLowerInvariant(); } public static TError DecodeExceptionEncodedData<TError>(this string data) where TError : class, new() { var errorABI = ABITypedRegistry.GetError<TError>(); if (errorABI.IsExceptionEncodedDataForError(data)) { return _functionCallDecoder.DecodeFunctionCustomError(new TError(), errorABI.Sha3Signature, data); } return null; } public static List<ParameterOutput> DecodeExceptionEncodedDataToDefault(this ErrorABI errorABI, string data) { return _functionCallDecoder.DecodeFunctionInput(errorABI.Sha3Signature, data, errorABI.InputParameters); } public static bool IsExceptionEncodedDataForError(this ErrorABI errorABI, string data) { return data.IsExceptionEncodedDataForError(errorABI.Sha3Signature); } public static bool IsExceptionForError(this ErrorABI errorABI, RpcResponseException exception) { if (exception.RpcError.Data == null) return false; var encodedData = exception.RpcError.Data.ToString(); if (!encodedData.IsHex()) return false; return encodedData.IsExceptionEncodedDataForError(errorABI.Sha3Signature); } } }
39.633333
116
0.688394
[ "MIT" ]
CryptoProject0417/P2E-UnityGameExample
Assets/MoralisWeb3ApiSdk/Nethereum/Nethereum.Contracts/Extensions/ErrorExtensions.cs
2,380
C#
//~ Generated by SearchStubs/SearchRowBasic using System; using System.Collections.Generic; namespace SuiteTalk { partial class EmployeeSearchRowBasic { // TODO: Make this Lazy and Weak referenced so that it can be garbaged collected private static readonly Lazy<ColumnFactory> columnFactoryLoader = new Lazy<ColumnFactory>(() => new ColumnFactory()); public override void SetColumns(string[] columnNames) { var factory = columnFactoryLoader.Value; for (int i = 0; i < columnNames.Length; i++) { factory.BuildColumn(this, columnNames[i]); } } class ColumnFactory: ColumnFactory<EmployeeSearchRowBasic> { protected override Dictionary<string, Action<EmployeeSearchRowBasic>> InitializeColumnBuilders() { return new Dictionary<string, Action<EmployeeSearchRowBasic>> { { "accountNumber", r => r.@accountNumber = new [] { new SearchColumnStringField { customLabel = "accountNumber" } } }, { "address", r => r.@address = new [] { new SearchColumnStringField { customLabel = "address" } } }, { "address1", r => r.@address1 = new [] { new SearchColumnStringField { customLabel = "address1" } } }, { "address2", r => r.@address2 = new [] { new SearchColumnStringField { customLabel = "address2" } } }, { "address3", r => r.@address3 = new [] { new SearchColumnStringField { customLabel = "address3" } } }, { "addressee", r => r.@addressee = new [] { new SearchColumnStringField { customLabel = "addressee" } } }, { "addressInternalId", r => r.@addressInternalId = new [] { new SearchColumnStringField { customLabel = "addressInternalId" } } }, { "addressLabel", r => r.@addressLabel = new [] { new SearchColumnStringField { customLabel = "addressLabel" } } }, { "addressPhone", r => r.@addressPhone = new [] { new SearchColumnStringField { customLabel = "addressPhone" } } }, { "alienNumber", r => r.@alienNumber = new [] { new SearchColumnStringField { customLabel = "alienNumber" } } }, { "allocation", r => r.@allocation = new [] { new SearchColumnDoubleField { customLabel = "allocation" } } }, { "altEmail", r => r.@altEmail = new [] { new SearchColumnStringField { customLabel = "altEmail" } } }, { "altName", r => r.@altName = new [] { new SearchColumnStringField { customLabel = "altName" } } }, { "altPhone", r => r.@altPhone = new [] { new SearchColumnStringField { customLabel = "altPhone" } } }, { "approvalLimit", r => r.@approvalLimit = new [] { new SearchColumnDoubleField { customLabel = "approvalLimit" } } }, { "approver", r => r.@approver = new [] { new SearchColumnSelectField { customLabel = "approver" } } }, { "attention", r => r.@attention = new [] { new SearchColumnStringField { customLabel = "attention" } } }, { "authWorkDate", r => r.@authWorkDate = new [] { new SearchColumnDateField { customLabel = "authWorkDate" } } }, { "baseWage", r => r.@baseWage = new [] { new SearchColumnDoubleField { customLabel = "baseWage" } } }, // NOTE: 'baseWageType' is unsupported as it's of type SearchEnumMultiSelectField, // which is not a SearchColumnField type. { "billAddress", r => r.@billAddress = new [] { new SearchColumnStringField { customLabel = "billAddress" } } }, { "billAddress1", r => r.@billAddress1 = new [] { new SearchColumnStringField { customLabel = "billAddress1" } } }, { "billAddress2", r => r.@billAddress2 = new [] { new SearchColumnStringField { customLabel = "billAddress2" } } }, { "billAddress3", r => r.@billAddress3 = new [] { new SearchColumnStringField { customLabel = "billAddress3" } } }, { "billAddressee", r => r.@billAddressee = new [] { new SearchColumnStringField { customLabel = "billAddressee" } } }, { "billAttention", r => r.@billAttention = new [] { new SearchColumnStringField { customLabel = "billAttention" } } }, { "billCity", r => r.@billCity = new [] { new SearchColumnStringField { customLabel = "billCity" } } }, { "billCountry", r => r.@billCountry = new [] { new SearchColumnEnumSelectField { customLabel = "billCountry" } } }, { "billCountryCode", r => r.@billCountryCode = new [] { new SearchColumnStringField { customLabel = "billCountryCode" } } }, { "billingClass", r => r.@billingClass = new [] { new SearchColumnSelectField { customLabel = "billingClass" } } }, { "billPhone", r => r.@billPhone = new [] { new SearchColumnStringField { customLabel = "billPhone" } } }, { "billState", r => r.@billState = new [] { new SearchColumnStringField { customLabel = "billState" } } }, { "billZipCode", r => r.@billZipCode = new [] { new SearchColumnStringField { customLabel = "billZipCode" } } }, { "birthDate", r => r.@birthDate = new [] { new SearchColumnDateField { customLabel = "birthDate" } } }, { "birthDay", r => r.@birthDay = new [] { new SearchColumnDateField { customLabel = "birthDay" } } }, { "bonusTarget", r => r.@bonusTarget = new [] { new SearchColumnDoubleField { customLabel = "bonusTarget" } } }, { "bonusTargetComment", r => r.@bonusTargetComment = new [] { new SearchColumnStringField { customLabel = "bonusTargetComment" } } }, { "bonusTargetPayFrequency", r => r.@bonusTargetPayFrequency = new [] { new SearchColumnEnumSelectField { customLabel = "bonusTargetPayFrequency" } } }, { "bonusTargetType", r => r.@bonusTargetType = new [] { new SearchColumnEnumSelectField { customLabel = "bonusTargetType" } } }, { "city", r => r.@city = new [] { new SearchColumnStringField { customLabel = "city" } } }, { "class", r => r.@class = new [] { new SearchColumnSelectField { customLabel = "class" } } }, { "comments", r => r.@comments = new [] { new SearchColumnStringField { customLabel = "comments" } } }, { "compensationCurrency", r => r.@compensationCurrency = new [] { new SearchColumnEnumSelectField { customLabel = "compensationCurrency" } } }, { "concurrentWebServicesUser", r => r.@concurrentWebServicesUser = new [] { new SearchColumnBooleanField { customLabel = "concurrentWebServicesUser" } } }, { "corporateCardProfile", r => r.@corporateCardProfile = new [] { new SearchColumnSelectField { customLabel = "corporateCardProfile" } } }, { "country", r => r.@country = new [] { new SearchColumnEnumSelectField { customLabel = "country" } } }, { "countryCode", r => r.@countryCode = new [] { new SearchColumnStringField { customLabel = "countryCode" } } }, { "dateCreated", r => r.@dateCreated = new [] { new SearchColumnDateField { customLabel = "dateCreated" } } }, { "defaultAcctCorpCardExp", r => r.@defaultAcctCorpCardExp = new [] { new SearchColumnSelectField { customLabel = "defaultAcctCorpCardExp" } } }, { "defaultExpenseReportCurrency", r => r.@defaultExpenseReportCurrency = new [] { new SearchColumnSelectField { customLabel = "defaultExpenseReportCurrency" } } }, { "defaultTaxReg", r => r.@defaultTaxReg = new [] { new SearchColumnStringField { customLabel = "defaultTaxReg" } } }, { "department", r => r.@department = new [] { new SearchColumnSelectField { customLabel = "department" } } }, { "eligibleForCommission", r => r.@eligibleForCommission = new [] { new SearchColumnBooleanField { customLabel = "eligibleForCommission" } } }, { "email", r => r.@email = new [] { new SearchColumnStringField { customLabel = "email" } } }, { "embossedName", r => r.@embossedName = new [] { new SearchColumnStringField { customLabel = "embossedName" } } }, { "employeeStatus", r => r.@employeeStatus = new [] { new SearchColumnSelectField { customLabel = "employeeStatus" } } }, { "employeeType", r => r.@employeeType = new [] { new SearchColumnSelectField { customLabel = "employeeType" } } }, { "entityId", r => r.@entityId = new [] { new SearchColumnStringField { customLabel = "entityId" } } }, { "entityNumber", r => r.@entityNumber = new [] { new SearchColumnLongField { customLabel = "entityNumber" } } }, { "ethnicity", r => r.@ethnicity = new [] { new SearchColumnSelectField { customLabel = "ethnicity" } } }, { "expenseLimit", r => r.@expenseLimit = new [] { new SearchColumnDoubleField { customLabel = "expenseLimit" } } }, { "expenseReportCurrency", r => r.@expenseReportCurrency = new [] { new SearchColumnSelectField { customLabel = "expenseReportCurrency" } } }, { "expiration", r => r.@expiration = new [] { new SearchColumnDateField { customLabel = "expiration" } } }, { "externalId", r => r.@externalId = new [] { new SearchColumnSelectField { customLabel = "externalId" } } }, { "fax", r => r.@fax = new [] { new SearchColumnStringField { customLabel = "fax" } } }, { "firstName", r => r.@firstName = new [] { new SearchColumnStringField { customLabel = "firstName" } } }, { "gender", r => r.@gender = new [] { new SearchColumnEnumSelectField { customLabel = "gender" } } }, { "giveAccess", r => r.@giveAccess = new [] { new SearchColumnBooleanField { customLabel = "giveAccess" } } }, { "globalSubscriptionStatus", r => r.@globalSubscriptionStatus = new [] { new SearchColumnEnumSelectField { customLabel = "globalSubscriptionStatus" } } }, { "hireDate", r => r.@hireDate = new [] { new SearchColumnDateField { customLabel = "hireDate" } } }, { "homePhone", r => r.@homePhone = new [] { new SearchColumnStringField { customLabel = "homePhone" } } }, { "i9Verified", r => r.@i9Verified = new [] { new SearchColumnBooleanField { customLabel = "i9Verified" } } }, { "image", r => r.@image = new [] { new SearchColumnSelectField { customLabel = "image" } } }, { "internalId", r => r.@internalId = new [] { new SearchColumnSelectField { customLabel = "internalId" } } }, { "isDefaultBilling", r => r.@isDefaultBilling = new [] { new SearchColumnBooleanField { customLabel = "isDefaultBilling" } } }, { "isDefaultShipping", r => r.@isDefaultShipping = new [] { new SearchColumnBooleanField { customLabel = "isDefaultShipping" } } }, { "isInactive", r => r.@isInactive = new [] { new SearchColumnBooleanField { customLabel = "isInactive" } } }, { "isJobManager", r => r.@isJobManager = new [] { new SearchColumnBooleanField { customLabel = "isJobManager" } } }, { "isJobResource", r => r.@isJobResource = new [] { new SearchColumnBooleanField { customLabel = "isJobResource" } } }, { "isSalesRep", r => r.@isSalesRep = new [] { new SearchColumnBooleanField { customLabel = "isSalesRep" } } }, { "isSupportRep", r => r.@isSupportRep = new [] { new SearchColumnBooleanField { customLabel = "isSupportRep" } } }, { "isTemplate", r => r.@isTemplate = new [] { new SearchColumnBooleanField { customLabel = "isTemplate" } } }, { "job", r => r.@job = new [] { new SearchColumnSelectField { customLabel = "job" } } }, { "laborCost", r => r.@laborCost = new [] { new SearchColumnDoubleField { customLabel = "laborCost" } } }, { "language", r => r.@language = new [] { new SearchColumnEnumSelectField { customLabel = "language" } } }, { "lastModifiedDate", r => r.@lastModifiedDate = new [] { new SearchColumnDateField { customLabel = "lastModifiedDate" } } }, { "lastName", r => r.@lastName = new [] { new SearchColumnStringField { customLabel = "lastName" } } }, { "lastPaidDate", r => r.@lastPaidDate = new [] { new SearchColumnDateField { customLabel = "lastPaidDate" } } }, { "lastReviewDate", r => r.@lastReviewDate = new [] { new SearchColumnDateField { customLabel = "lastReviewDate" } } }, { "level", r => r.@level = new [] { new SearchColumnEnumSelectField { customLabel = "level" } } }, { "location", r => r.@location = new [] { new SearchColumnSelectField { customLabel = "location" } } }, { "maritalStatus", r => r.@maritalStatus = new [] { new SearchColumnSelectField { customLabel = "maritalStatus" } } }, { "middleName", r => r.@middleName = new [] { new SearchColumnStringField { customLabel = "middleName" } } }, { "mobilePhone", r => r.@mobilePhone = new [] { new SearchColumnStringField { customLabel = "mobilePhone" } } }, { "nextReviewDate", r => r.@nextReviewDate = new [] { new SearchColumnDateField { customLabel = "nextReviewDate" } } }, { "offlineAccess", r => r.@offlineAccess = new [] { new SearchColumnBooleanField { customLabel = "offlineAccess" } } }, { "payFrequency", r => r.@payFrequency = new [] { new SearchColumnEnumSelectField { customLabel = "payFrequency" } } }, { "permChangeDate", r => r.@permChangeDate = new [] { new SearchColumnDateField { customLabel = "permChangeDate" } } }, { "permChangeLevel", r => r.@permChangeLevel = new [] { new SearchColumnStringField { customLabel = "permChangeLevel" } } }, { "permission", r => r.@permission = new [] { new SearchColumnEnumSelectField { customLabel = "permission" } } }, { "permissionChange", r => r.@permissionChange = new [] { new SearchColumnEnumSelectField { customLabel = "permissionChange" } } }, { "phone", r => r.@phone = new [] { new SearchColumnStringField { customLabel = "phone" } } }, { "phoneticName", r => r.@phoneticName = new [] { new SearchColumnStringField { customLabel = "phoneticName" } } }, { "positionTitle", r => r.@positionTitle = new [] { new SearchColumnStringField { customLabel = "positionTitle" } } }, { "primaryEarningAmount", r => r.@primaryEarningAmount = new [] { new SearchColumnDoubleField { customLabel = "primaryEarningAmount" } } }, { "primaryEarningItem", r => r.@primaryEarningItem = new [] { new SearchColumnStringField { customLabel = "primaryEarningItem" } } }, { "primaryEarningType", r => r.@primaryEarningType = new [] { new SearchColumnStringField { customLabel = "primaryEarningType" } } }, { "purchaseOrderApprovalLimit", r => r.@purchaseOrderApprovalLimit = new [] { new SearchColumnDoubleField { customLabel = "purchaseOrderApprovalLimit" } } }, { "purchaseOrderApprover", r => r.@purchaseOrderApprover = new [] { new SearchColumnSelectField { customLabel = "purchaseOrderApprover" } } }, { "purchaseOrderLimit", r => r.@purchaseOrderLimit = new [] { new SearchColumnDoubleField { customLabel = "purchaseOrderLimit" } } }, { "releaseDate", r => r.@releaseDate = new [] { new SearchColumnDateField { customLabel = "releaseDate" } } }, { "residentStatus", r => r.@residentStatus = new [] { new SearchColumnSelectField { customLabel = "residentStatus" } } }, { "role", r => r.@role = new [] { new SearchColumnSelectField { customLabel = "role" } } }, { "roleChange", r => r.@roleChange = new [] { new SearchColumnStringField { customLabel = "roleChange" } } }, { "roleChangeAction", r => r.@roleChangeAction = new [] { new SearchColumnStringField { customLabel = "roleChangeAction" } } }, { "roleChangeDate", r => r.@roleChangeDate = new [] { new SearchColumnDateField { customLabel = "roleChangeDate" } } }, { "salesRole", r => r.@salesRole = new [] { new SearchColumnSelectField { customLabel = "salesRole" } } }, { "salutation", r => r.@salutation = new [] { new SearchColumnStringField { customLabel = "salutation" } } }, { "shipAddress1", r => r.@shipAddress1 = new [] { new SearchColumnStringField { customLabel = "shipAddress1" } } }, { "shipAddress2", r => r.@shipAddress2 = new [] { new SearchColumnStringField { customLabel = "shipAddress2" } } }, { "shipAddress3", r => r.@shipAddress3 = new [] { new SearchColumnStringField { customLabel = "shipAddress3" } } }, { "shipAddressee", r => r.@shipAddressee = new [] { new SearchColumnStringField { customLabel = "shipAddressee" } } }, { "shipAttention", r => r.@shipAttention = new [] { new SearchColumnStringField { customLabel = "shipAttention" } } }, { "shipCity", r => r.@shipCity = new [] { new SearchColumnStringField { customLabel = "shipCity" } } }, { "shipCountry", r => r.@shipCountry = new [] { new SearchColumnEnumSelectField { customLabel = "shipCountry" } } }, { "shipCountryCode", r => r.@shipCountryCode = new [] { new SearchColumnStringField { customLabel = "shipCountryCode" } } }, { "shipPhone", r => r.@shipPhone = new [] { new SearchColumnStringField { customLabel = "shipPhone" } } }, { "shipState", r => r.@shipState = new [] { new SearchColumnStringField { customLabel = "shipState" } } }, { "shipZip", r => r.@shipZip = new [] { new SearchColumnStringField { customLabel = "shipZip" } } }, { "socialSecurityNumber", r => r.@socialSecurityNumber = new [] { new SearchColumnStringField { customLabel = "socialSecurityNumber" } } }, { "startDateTimeOffCalc", r => r.@startDateTimeOffCalc = new [] { new SearchColumnDateField { customLabel = "startDateTimeOffCalc" } } }, { "state", r => r.@state = new [] { new SearchColumnEnumSelectField { customLabel = "state" } } }, { "subscription", r => r.@subscription = new [] { new SearchColumnSelectField { customLabel = "subscription" } } }, { "subscriptionDate", r => r.@subscriptionDate = new [] { new SearchColumnDateField { customLabel = "subscriptionDate" } } }, { "subscriptionStatus", r => r.@subscriptionStatus = new [] { new SearchColumnBooleanField { customLabel = "subscriptionStatus" } } }, { "subsidiary", r => r.@subsidiary = new [] { new SearchColumnSelectField { customLabel = "subsidiary" } } }, { "supervisor", r => r.@supervisor = new [] { new SearchColumnSelectField { customLabel = "supervisor" } } }, { "targetUtilization", r => r.@targetUtilization = new [] { new SearchColumnDoubleField { customLabel = "targetUtilization" } } }, { "terminationCategory", r => r.@terminationCategory = new [] { new SearchColumnEnumSelectField { customLabel = "terminationCategory" } } }, { "terminationDetails", r => r.@terminationDetails = new [] { new SearchColumnStringField { customLabel = "terminationDetails" } } }, { "terminationReason", r => r.@terminationReason = new [] { new SearchColumnSelectField { customLabel = "terminationReason" } } }, { "terminationRegretted", r => r.@terminationRegretted = new [] { new SearchColumnEnumSelectField { customLabel = "terminationRegretted" } } }, { "timeApprover", r => r.@timeApprover = new [] { new SearchColumnSelectField { customLabel = "timeApprover" } } }, { "timeOffPlan", r => r.@timeOffPlan = new [] { new SearchColumnStringField { customLabel = "timeOffPlan" } } }, { "title", r => r.@title = new [] { new SearchColumnStringField { customLabel = "title" } } }, { "usePerquest", r => r.@usePerquest = new [] { new SearchColumnBooleanField { customLabel = "usePerquest" } } }, { "useTimeData", r => r.@useTimeData = new [] { new SearchColumnBooleanField { customLabel = "useTimeData" } } }, { "visaExpDate", r => r.@visaExpDate = new [] { new SearchColumnDateField { customLabel = "visaExpDate" } } }, { "visaType", r => r.@visaType = new [] { new SearchColumnSelectField { customLabel = "visaType" } } }, { "workCalendar", r => r.@workCalendar = new [] { new SearchColumnStringField { customLabel = "workCalendar" } } }, { "workplace", r => r.@workplace = new [] { new SearchColumnSelectField { customLabel = "workplace" } } }, { "zipCode", r => r.@zipCode = new [] { new SearchColumnStringField { customLabel = "zipCode" } } }, }; } } } }
117.535135
183
0.576849
[ "Apache-2.0" ]
cloudextend/contrib-netsuite-servicemgr
Celigo.SuiteTalk/src/SuiteTalk/Generated/EmployeeSearchRowBasic.gen.cs
21,744
C#
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MudBlazor.Examples.Data; using MudBlazor.Examples.Data.Models; namespace Server.Controllers { [Route("wasm/webapi/[controller]")] [Route("webapi/[controller]")] [ApiController] public class PeriodicTableController : ControllerBase { private IPeriodicTableService _periodicTableService; public PeriodicTableController(IPeriodicTableService periodicTableService) { _periodicTableService = periodicTableService; } [HttpGet("{search}")] public async Task<IEnumerable<Element>> Get(string search) { return await _periodicTableService.GetElements(search); } [HttpGet] public async Task<IEnumerable<Element>> Get() { return await _periodicTableService.GetElements(); } } }
27.323529
82
0.675996
[ "MIT" ]
BananaRush/MudBlazor
src/MudBlazor.Docs.Server/Controllers/PeriodicTableController.cs
931
C#
using System.ComponentModel.DataAnnotations; namespace HowIMeter.Cli { enum ApplicationErrorKind { NoError = 0, GeneralError = -1, [Display(Description = "Invalid arguments")] InvalidCliArgument = -2, [Display(Description = "The provided uri is invalid")] InvalidUri } }
22.2
62
0.630631
[ "MIT" ]
jaenyph/howimeter
HowIMeter.Cli/ApplicationErrorKind.cs
335
C#
using strange.extensions.context.impl; namespace Server.Contexts { public class AppServerRoot : ContextView { private void Awake() { context = new AppServerContext(this); } } }
18.833333
49
0.606195
[ "MIT" ]
gellios3/Simple-Battle-Cards-Server
Assets/Scripts/Server/Contexts/AppServerRoot.cs
228
C#