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
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.CustomerInsights.V20170101 { public static class GetKpi { public static Task<GetKpiResult> InvokeAsync(GetKpiArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetKpiResult>("azure-nextgen:customerinsights/v20170101:getKpi", args ?? new GetKpiArgs(), options.WithVersion()); } public sealed class GetKpiArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the hub. /// </summary> [Input("hubName", required: true)] public string HubName { get; set; } = null!; /// <summary> /// The name of the KPI. /// </summary> [Input("kpiName", required: true)] public string KpiName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetKpiArgs() { } } [OutputType] public sealed class GetKpiResult { /// <summary> /// The aliases. /// </summary> public readonly ImmutableArray<Outputs.KpiAliasResponse> Aliases; /// <summary> /// The calculation window. /// </summary> public readonly string CalculationWindow; /// <summary> /// Name of calculation window field. /// </summary> public readonly string? CalculationWindowFieldName; /// <summary> /// Localized description for the KPI. /// </summary> public readonly ImmutableDictionary<string, string>? Description; /// <summary> /// Localized display name for the KPI. /// </summary> public readonly ImmutableDictionary<string, string>? DisplayName; /// <summary> /// The mapping entity type. /// </summary> public readonly string EntityType; /// <summary> /// The mapping entity name. /// </summary> public readonly string EntityTypeName; /// <summary> /// The computation expression for the KPI. /// </summary> public readonly string Expression; /// <summary> /// The KPI extracts. /// </summary> public readonly ImmutableArray<Outputs.KpiExtractResponse> Extracts; /// <summary> /// The filter expression for the KPI. /// </summary> public readonly string? Filter; /// <summary> /// The computation function for the KPI. /// </summary> public readonly string Function; /// <summary> /// the group by properties for the KPI. /// </summary> public readonly ImmutableArray<string> GroupBy; /// <summary> /// The KPI GroupByMetadata. /// </summary> public readonly ImmutableArray<Outputs.KpiGroupByMetadataResponse> GroupByMetadata; /// <summary> /// The KPI name. /// </summary> public readonly string KpiName; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The participant profiles. /// </summary> public readonly ImmutableArray<Outputs.KpiParticipantProfilesMetadataResponse> ParticipantProfilesMetadata; /// <summary> /// Provisioning state. /// </summary> public readonly string ProvisioningState; /// <summary> /// The hub name. /// </summary> public readonly string TenantId; /// <summary> /// The KPI thresholds. /// </summary> public readonly Outputs.KpiThresholdsResponse? ThresHolds; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// The unit of measurement for the KPI. /// </summary> public readonly string? Unit; [OutputConstructor] private GetKpiResult( ImmutableArray<Outputs.KpiAliasResponse> aliases, string calculationWindow, string? calculationWindowFieldName, ImmutableDictionary<string, string>? description, ImmutableDictionary<string, string>? displayName, string entityType, string entityTypeName, string expression, ImmutableArray<Outputs.KpiExtractResponse> extracts, string? filter, string function, ImmutableArray<string> groupBy, ImmutableArray<Outputs.KpiGroupByMetadataResponse> groupByMetadata, string kpiName, string name, ImmutableArray<Outputs.KpiParticipantProfilesMetadataResponse> participantProfilesMetadata, string provisioningState, string tenantId, Outputs.KpiThresholdsResponse? thresHolds, string type, string? unit) { Aliases = aliases; CalculationWindow = calculationWindow; CalculationWindowFieldName = calculationWindowFieldName; Description = description; DisplayName = displayName; EntityType = entityType; EntityTypeName = entityTypeName; Expression = expression; Extracts = extracts; Filter = filter; Function = function; GroupBy = groupBy; GroupByMetadata = groupByMetadata; KpiName = kpiName; Name = name; ParticipantProfilesMetadata = participantProfilesMetadata; ProvisioningState = provisioningState; TenantId = tenantId; ThresHolds = thresHolds; Type = type; Unit = unit; } } }
30.930348
168
0.579701
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/CustomerInsights/V20170101/GetKpi.cs
6,217
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin { public class BlockLocator : IBitcoinSerializable { public BlockLocator() { } public BlockLocator(List<uint256> hashes) { vHave = hashes; } List<uint256> vHave = new List<uint256>(); public List<uint256> Blocks { get { return vHave; } } #region IBitcoinSerializable Members public void ReadWrite(BitcoinStream stream) { stream.ReadWrite(ref vHave); } #endregion } }
15.358974
50
0.649416
[ "MIT" ]
dthorpe/NBitcoin
NBitcoin/BlockLocator.cs
601
C#
using System; using System.Threading.Tasks; using DatingApp.API.Models; using Microsoft.EntityFrameworkCore; namespace DatingApp.API.Data { public class AuthRepository : IAuthRepository { private readonly DataContext _context; public AuthRepository(DataContext context) { this._context = context; } public async Task<User> Login(string username, string password) { var user = await this._context.Users.FirstOrDefaultAsync(x => x.Username == username); if (user == null) { return null; } if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) { return null; } return user; } private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) { passwordSalt = hmac.Key; var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != passwordHash[i]) { return false; } } return true; } } public async Task<User> Register(User user, string password) { byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await this._context.Users.AddAsync(user); await this._context.SaveChangesAsync(); return user; } private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } } public async Task<bool> UserExists(string username) { if (await this._context.Users.AnyAsync((x => x.Username == username))) { return true; } return false; } } }
29.576471
106
0.542562
[ "MIT" ]
julianobrasil-experimental/udemy-dotnetcore
DatingApp-API/Data/AuthRepository.cs
2,514
C#
using MbDotNet.Models.Responses; using MbDotNet.Models.Responses.Fields; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MbDotNet.Tests.Models.Responses { [TestClass] public class ProxyResponseTests { private class TestResponseFields : ResponseFields { } [TestMethod] public void TestResponse_Constructor_SetsFields() { var expectedFields = new TestResponseFields(); var response = new ProxyResponse<TestResponseFields>(expectedFields); Assert.AreSame(expectedFields, response.Fields); } } }
28.571429
81
0.7
[ "MIT" ]
putnap/MbDotNet
MbDotNet.Tests/Models/Responses/ProxyResponseTests.cs
600
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Feats.Common.Tests; using Feats.Common.Tests.Commands; using Feats.CQRS.Commands; using Feats.Management.Features; using Feats.Management.Features.Commands; using Microsoft.AspNetCore.Mvc; using NUnit.Framework; namespace Feats.Management.Tests.Features { public class AssignIsInListStrategyToFeatureControllerTests : TestBase { [Test] public async Task GivenRequest_WhenProcessingTheCommandIsSuccessful_ThenWeReturnOk() { var request = this .GivenRequest(); var handler = this .GivenCommandHandler<AssignIsInListStrategyToFeatureCommand>() .WithHandling(); await this .GivenController(handler.Object) .WhenProcessingCommand(request) .ThenWeReturnOK(); } [Test] public async Task GivenRequest_WhenProcessingTheCommandItThrows_ThenThrow() { var request = this .GivenRequest(); var handler = this .GivenCommandHandler<AssignIsInListStrategyToFeatureCommand>() .WithException<AssignIsInListStrategyToFeatureCommand, TestException>(); await this .GivenController(handler.Object) .WhenProcessingCommand(request) .ThenExceptionIsThrown<TestException, IActionResult>(); } } public static class AssignIsInListStrategyToFeatureControllerTestsExtensions { public static AssignIsInListStrategyToFeatureRequest GivenRequest( this AssignIsInListStrategyToFeatureControllerTests tests) { return new AssignIsInListStrategyToFeatureRequest { AssignedBy = "bob", Name = "Ross", Path = "🦄.🖼", Items = new List<string> { "😜" }, }; } public static AssignIsInListStrategyToFeatureController GivenController( this AssignIsInListStrategyToFeatureControllerTests tests, IHandleCommand<AssignIsInListStrategyToFeatureCommand> handler) { return new AssignIsInListStrategyToFeatureController(handler); } public static Func<Task<IActionResult>> WhenProcessingCommand( this AssignIsInListStrategyToFeatureController controller, AssignIsInListStrategyToFeatureRequest request) { return () => controller.Post(request); } } }
34.68
92
0.640907
[ "MIT" ]
dotnet-feats/feats
tests/Feats.Management.Tests/Features/AssignIsInListStrategyToFeatureControllerTests.cs
2,610
C#
using System; namespace LoggingKata { public interface ILog { void LogFatal(string log, Exception exception = null); void LogError(string log, Exception exception = null); void LogWarning(string log); void LogInfo(string log); void LogDebug(string log); } }
23.923077
62
0.643087
[ "MIT" ]
CruzSanchez/TacoBell-Distance-Finder
LoggingKata/ILog.cs
313
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: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IActiveDirectoryWindowsAutopilotDeploymentProfileRequest. /// </summary> public partial interface IActiveDirectoryWindowsAutopilotDeploymentProfileRequest : IBaseRequest { /// <summary> /// Creates the specified ActiveDirectoryWindowsAutopilotDeploymentProfile using POST. /// </summary> /// <param name="activeDirectoryWindowsAutopilotDeploymentProfileToCreate">The ActiveDirectoryWindowsAutopilotDeploymentProfile to create.</param> /// <returns>The created ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> CreateAsync(ActiveDirectoryWindowsAutopilotDeploymentProfile activeDirectoryWindowsAutopilotDeploymentProfileToCreate); /// <summary> /// Creates the specified ActiveDirectoryWindowsAutopilotDeploymentProfile using POST. /// </summary> /// <param name="activeDirectoryWindowsAutopilotDeploymentProfileToCreate">The ActiveDirectoryWindowsAutopilotDeploymentProfile to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> CreateAsync(ActiveDirectoryWindowsAutopilotDeploymentProfile activeDirectoryWindowsAutopilotDeploymentProfileToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified ActiveDirectoryWindowsAutopilotDeploymentProfile. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified ActiveDirectoryWindowsAutopilotDeploymentProfile. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified ActiveDirectoryWindowsAutopilotDeploymentProfile. /// </summary> /// <returns>The ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> GetAsync(); /// <summary> /// Gets the specified ActiveDirectoryWindowsAutopilotDeploymentProfile. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified ActiveDirectoryWindowsAutopilotDeploymentProfile using PATCH. /// </summary> /// <param name="activeDirectoryWindowsAutopilotDeploymentProfileToUpdate">The ActiveDirectoryWindowsAutopilotDeploymentProfile to update.</param> /// <returns>The updated ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> UpdateAsync(ActiveDirectoryWindowsAutopilotDeploymentProfile activeDirectoryWindowsAutopilotDeploymentProfileToUpdate); /// <summary> /// Updates the specified ActiveDirectoryWindowsAutopilotDeploymentProfile using PATCH. /// </summary> /// <param name="activeDirectoryWindowsAutopilotDeploymentProfileToUpdate">The ActiveDirectoryWindowsAutopilotDeploymentProfile to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated ActiveDirectoryWindowsAutopilotDeploymentProfile.</returns> System.Threading.Tasks.Task<ActiveDirectoryWindowsAutopilotDeploymentProfile> UpdateAsync(ActiveDirectoryWindowsAutopilotDeploymentProfile activeDirectoryWindowsAutopilotDeploymentProfileToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IActiveDirectoryWindowsAutopilotDeploymentProfileRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IActiveDirectoryWindowsAutopilotDeploymentProfileRequest Expand(Expression<Func<ActiveDirectoryWindowsAutopilotDeploymentProfile, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IActiveDirectoryWindowsAutopilotDeploymentProfileRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IActiveDirectoryWindowsAutopilotDeploymentProfileRequest Select(Expression<Func<ActiveDirectoryWindowsAutopilotDeploymentProfile, object>> selectExpression); } }
60.740741
242
0.720884
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IActiveDirectoryWindowsAutopilotDeploymentProfileRequest.cs
6,560
C#
/* * _____ ______ * /_ / ____ ____ ____ _________ / __/ /_ * / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/ * / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_ * /____/\____/_/ /_/\__ /____/\____/_/ \__/ * /____/ * * Authors: * 钟峰(Popeye Zhong) <zongsoft@qq.com> * * Copyright (C) 2015-2017 Zongsoft Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Zongsoft.Data; namespace Zongsoft.Community.Models { /// <summary> /// 表示论坛的业务实体类。 /// </summary> public abstract class Forum { #region 公共属性 /// <summary> /// 获取或设置站点编号,主键。 /// </summary> public abstract uint SiteId { get; set; } /// <summary> /// 获取或设置论坛编号,主键。 /// </summary> public abstract ushort ForumId { get; set; } /// <summary> /// 获取或设置论坛所属的组号。 /// </summary> public abstract ushort GroupId { get; set; } /// <summary> /// 获取或设置论坛所属的 <see cref="ForumGroup"/> 分组对象。 /// </summary> public abstract ForumGroup Group { get; set; } /// <summary> /// 获取或设置论坛所在分组中的排列序号。 /// </summary> public abstract ushort SortOrder { get; set; } /// <summary> /// 获取或设置论坛的名称(标题)。 /// </summary> public abstract string Name { get; set; } /// <summary> /// 获取或设置论坛的描述文本。 /// </summary> public abstract string Description { get; set; } /// <summary> /// 获取或设置论坛的封面图片路径。 /// </summary> public abstract string CoverPicturePath { get; set; } /// <summary> /// 获取论坛封面图片的外部访问地址。 /// </summary> public string CoverPictureUrl { get => Zongsoft.IO.FileSystem.GetUrl(this.CoverPicturePath); } /// <summary> /// 获取或设置一个值,表示论坛是否为热门版块。 /// </summary> public abstract bool IsPopular { get; set; } /// <summary> /// 获取或设置一个值,表示发帖是否需要审核。 /// </summary> public abstract bool Approvable { get; set; } /// <summary> /// 获取或设置论坛的可见性。 /// </summary> public abstract Visibility Visibility { get; set; } /// <summary> /// 获取或设置论坛的可访问性。 /// </summary> public abstract Accessibility Accessibility { get; set; } /// <summary> /// 获取或设置论坛中的累计帖子总数。 /// </summary> public abstract uint TotalPosts { get; set; } /// <summary> /// 获取或设置论坛中的累积主题总数。 /// </summary> public abstract uint TotalThreads { get; set; } /// <summary> /// 获取或设置论坛中最新主题的编号。 /// </summary> public abstract ulong? MostRecentThreadId { get; set; } /// <summary> /// 获取或设置论坛中最新发布的主题对象。 /// </summary> public abstract Thread MostRecentThread { get; set; } /// <summary> /// 获取或设置论坛中最新主题的标题。 /// </summary> public abstract string MostRecentThreadTitle { get; set; } /// <summary> /// 获取或设置论坛中最新主题的作者编号。 /// </summary> public abstract uint? MostRecentThreadAuthorId { get; set; } /// <summary> /// 获取或设置论坛中最新主题的作者名称。 /// </summary> public abstract string MostRecentThreadAuthorName { get; set; } /// <summary> /// 获取或设置论坛中最新主题的作者头像。 /// </summary> public abstract string MostRecentThreadAuthorAvatar { get; set; } /// <summary> /// 获取或设置论坛中最新主题的发布时间。 /// </summary> public abstract DateTime? MostRecentThreadTime { get; set; } /// <summary> /// 获取或设置论坛中最近回帖编号。 /// </summary> public abstract ulong? MostRecentPostId { get; set; } /// <summary> /// 获取或设置论坛中最近的回帖对象。 /// </summary> public abstract Post MostRecentPost { get; set; } /// <summary> /// 获取或设置论坛中最近回帖的作者编号。 /// </summary> public abstract uint? MostRecentPostAuthorId { get; set; } /// <summary> /// 获取或设置论坛中最近回帖的作者名称。 /// </summary> public abstract string MostRecentPostAuthorName { get; set; } /// <summary> /// 获取或设置论坛中最近回帖的作者头像。 /// </summary> public abstract string MostRecentPostAuthorAvatar { get; set; } /// <summary> /// 获取或设置论坛中最近回帖的时间。 /// </summary> public abstract DateTime? MostRecentPostTime { get; set; } /// <summary> /// 获取或设置论坛创建人编号。 /// </summary> public abstract uint CreatorId { get; set; } /// <summary> /// 获取或设置论坛的创建时间。 /// </summary> public abstract DateTime CreatedTime { get; set; } #endregion #region 集合属性 /// <summary> /// 获取或设置论坛成员集。 /// </summary> public abstract IEnumerable<ForumUser> Users { get; set; } /// <summary> /// 获取或设置论坛的版主集。 /// </summary> public abstract IEnumerable<UserProfile> Moderators { get; set; } #endregion #region 嵌套结构 /// <summary> /// 表示论坛用户的业务实体结构。 /// </summary> public struct ForumUser : IEquatable<ForumUser> { #region 公共字段 /// <summary>站点编号</summary> public uint SiteId; /// <summary>论坛编号</summary> public ushort ForumId; /// <summary>用户编号</summary> public uint UserId; /// <summary>权限定义</summary> public Permission Permission; /// <summary>是否为版主</summary> public bool IsModerator; /// <summary>论坛对象</summary> public Forum Forum; /// <summary>用户对象</summary> public UserProfile User; #endregion #region 构造函数 private ForumUser(uint userId) { this.SiteId = 0; this.ForumId = 0; this.UserId = userId; this.Permission = Permission.None; this.IsModerator = true; this.Forum = null; this.User = null; } private ForumUser(uint siteId, ushort forumId, uint userId) { this.SiteId = siteId; this.ForumId = forumId; this.UserId = userId; this.Permission = Permission.None; this.IsModerator = true; this.Forum = null; this.User = null; } public ForumUser(uint userId, Permission permission) { this.SiteId = 0; this.ForumId = 0; this.UserId = userId; this.Permission = permission; this.IsModerator = false; this.Forum = null; this.User = null; } public ForumUser(uint siteId, ushort forumId, uint userId, Permission permission) { this.SiteId = siteId; this.ForumId = forumId; this.UserId = userId; this.Permission = permission; this.IsModerator = false; this.Forum = null; this.User = null; } #endregion #region 静态方法 /// <summary> /// 构建一个指定用户编号的版主。 /// </summary> /// <param name="userId">指定的版主的用户编号。</param> /// <returns>返回构建成功的论坛用户成员。</returns> public static ForumUser Moderator(uint userId) { return new ForumUser(userId); } /// <summary> /// 构建一个指定论坛的版主。 /// </summary> /// <param name="siteId">指定的站点编号。</param> /// <param name="forumId">指定的论坛编号。</param> /// <param name="userId">指定的版主的用户编号。</param> /// <returns>返回构建成功的论坛用户成员。</returns> public static ForumUser Moderator(uint siteId, ushort forumId, uint userId) { return new ForumUser(siteId, forumId, userId); } #endregion #region 重写方法 public bool Equals(ForumUser other) { return this.SiteId == other.SiteId && this.ForumId == other.ForumId && this.UserId == other.UserId; } public override bool Equals(object obj) { if(obj == null || obj.GetType() != typeof(ForumUser)) return false; return this.Equals((ForumUser)obj); } public override int GetHashCode() { return (int)(this.SiteId ^ this.ForumId ^ this.UserId); } public override string ToString() { return this.SiteId.ToString() + "." + this.ForumId.ToString() + "-" + this.UserId.ToString() + ":" + ( this.IsModerator ? "Moderator" : this.Permission.ToString() ); } #endregion } #endregion } /// <summary> /// 表示论坛查询条件的实体类。 /// </summary> public abstract class ForumConditional : ConditionalBase { #region 公共属性 public abstract string Name { get; set; } public abstract Visibility? Visiblity { get; set; } public abstract Accessibility? Accessibility { get; set; } public abstract bool? IsPopular { get; set; } public abstract Range<DateTime> CreatedTime { get; set; } #endregion } }
18.524946
84
0.608431
[ "Apache-2.0" ]
Zongsoft/Zongsoft.Community
src/Models/Forum.cs
9,926
C#
namespace Octokit.Webhooks.Models.IssuesEvent { using System.Text.Json.Serialization; using JetBrains.Annotations; [PublicAPI] public sealed record ChangesTitle { [JsonPropertyName("from")] public string From { get; init; } = null!; } }
21.461538
50
0.659498
[ "MIT" ]
JamieMagee/JamieMagee.Octokit.Webhooks
src/Octokit.Webhooks/Models/IssuesEvent/ChangesTitle.cs
281
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 OcelotApiGw { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile($"ocelot.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging((hostingContext, loggingbuilder) => { loggingbuilder.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); loggingbuilder.AddConsole(); loggingbuilder.AddDebug(); }); } }
32.25
115
0.635659
[ "MIT" ]
Jefferson-web/EcommerceMicroservices
src/ApiGateways/OcelotApiGw/Program.cs
1,161
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class GregorianCalendarGetDayOfWeek { public static IEnumerable<object[]> GetDayOfWeek_TestData() { yield return new object[] { new DateTime(2007, 1, 1) }; yield return new object[] { new DateTime(2006, 2, 28) }; yield return new object[] { new DateTime(2006, 3, 1) }; yield return new object[] { new DateTime(2006, 8, 31) }; yield return new object[] { new DateTime(2008, 2, 29) }; yield return new object[] { new DateTime(2006, 12, 30) }; yield return new object[] { new DateTime(2006, 12, 31) }; yield return new object[] { DateTime.MaxValue }; yield return new object[] { DateTime.MinValue }; yield return new object[] { new DateTime(2000, 2, 29) }; } [Theory] [MemberData(nameof(GetDayOfWeek_TestData))] public void GetDayOfWeek(DateTime time) { Assert.Equal(time.DayOfWeek, new GregorianCalendar().GetDayOfWeek(time)); } } }
38.545455
85
0.613208
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Globalization.Calendars/tests/GregorianCalendar/GregorianCalendarGetDayOfWeek.cs
1,272
C#
using System.Threading; using System.Threading.Tasks; using SmartHead.Essentials.Abstractions.Cqrs; namespace SmartHead.Essentials.Abstractions.MediatR { public interface IEventStore { Task SaveAsync<T>(T @event, CancellationToken ct = default) where T : Event; } }
24
84
0.746528
[ "Apache-2.0" ]
neonbones/SmartHead.Essentials
src/SmartHead.Essentials.Abstractions/MediatR/IEventStore.cs
290
C#
namespace CoreWCF.Description { internal interface IContractResolver { ContractDescription ResolveContract(string contractName); } }
21.857143
65
0.738562
[ "MIT" ]
0x53A/CoreWCF
src/CoreWCF.Primitives/src/CoreWCF/Description/IContractResolver.cs
155
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Windows; namespace Careful.Module.Core.Regions.Behaviors { public class DelayedRegionCreationBehavior { private readonly RegionAdapterMappings regionAdapterMappings; private WeakReference elementWeakReference; private bool regionCreated; private static ICollection<DelayedRegionCreationBehavior> _instanceTracker = new Collection<DelayedRegionCreationBehavior>(); private object _trackerLock = new object(); /// <summary> /// Initializes a new instance of the <see cref="DelayedRegionCreationBehavior"/> class. /// </summary> /// <param name="regionAdapterMappings"> /// The region adapter mappings, that are used to find the correct adapter for /// a given controltype. The controltype is determined by the <see name="TargetElement"/> value. /// </param> public DelayedRegionCreationBehavior(RegionAdapterMappings regionAdapterMappings) { this.regionAdapterMappings = regionAdapterMappings; this.RegionManagerAccessor = new DefaultRegionManagerAccessor(); } /// <summary> /// Sets a class that interfaces between the <see cref="RegionManager"/> 's static properties/events and this behavior, /// so this behavior can be tested in isolation. /// </summary> /// <value>The region manager accessor.</value> public IRegionManagerAccessor RegionManagerAccessor { get; set; } /// <summary> /// The element that will host the Region. /// </summary> /// <value>The target element.</value> public DependencyObject TargetElement { get { return this.elementWeakReference != null ? this.elementWeakReference.Target as DependencyObject : null; } set { this.elementWeakReference = new WeakReference(value); } } /// <summary> /// Start monitoring the <see cref="RegionManager"/> and the <see cref="TargetElement"/> to detect when the <see cref="TargetElement"/> becomes /// part of the Visual Tree. When that happens, the Region will be created and the behavior will <see cref="Detach"/>. /// </summary> public void Attach() { this.RegionManagerAccessor.UpdatingRegions += this.OnUpdatingRegions; this.WireUpTargetElement(); } /// <summary> /// Stop monitoring the <see cref="RegionManager"/> and the <see cref="TargetElement"/>, so that this behavior can be garbage collected. /// </summary> public void Detach() { this.RegionManagerAccessor.UpdatingRegions -= this.OnUpdatingRegions; this.UnWireTargetElement(); } /// <summary> /// Called when the <see cref="RegionManager"/> is updating it's <see cref="RegionManager.Regions"/> collection. /// </summary> /// <remarks> /// This method has to be public, because it has to be callable using weak references in silverlight and other partial trust environments. /// </remarks> /// <param name="sender">The <see cref="RegionManager"/>. </param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "This has to be public in order to work with weak references in partial trust or Silverlight environments.")] public void OnUpdatingRegions(object sender, EventArgs e) { this.TryCreateRegion(); } private void TryCreateRegion() { DependencyObject targetElement = this.TargetElement; if (targetElement == null) { this.Detach(); return; } if (targetElement.CheckAccess()) { this.Detach(); if (!this.regionCreated) { string regionName = this.RegionManagerAccessor.GetRegionName(targetElement); CreateRegion(targetElement, regionName); this.regionCreated = true; } } } /// <summary> /// Method that will create the region, by calling the right <see cref="IRegionAdapter"/>. /// </summary> /// <param name="targetElement">The target element that will host the <see cref="IRegion"/>.</param> /// <param name="regionName">Name of the region.</param> /// <returns>The created <see cref="IRegion"/></returns> protected virtual IRegion CreateRegion(DependencyObject targetElement, string regionName) { if (targetElement == null) throw new ArgumentNullException(nameof(targetElement)); try { // Build the region IRegionAdapter regionAdapter = this.regionAdapterMappings.GetMapping(targetElement.GetType()); IRegion region = regionAdapter.Initialize(targetElement, regionName); return region; } catch (Exception ex) { throw new RegionCreationException(string.Format(CultureInfo.CurrentCulture, "region created exception", regionName, ex), ex); } } private void ElementLoaded(object sender, RoutedEventArgs e) { this.UnWireTargetElement(); this.TryCreateRegion(); } private void WireUpTargetElement() { FrameworkElement element = this.TargetElement as FrameworkElement; if (element != null) { element.Loaded += this.ElementLoaded; return; } #if !HAS_WINUI FrameworkContentElement fcElement = this.TargetElement as FrameworkContentElement; if (fcElement != null) { fcElement.Loaded += this.ElementLoaded; return; } #endif //if the element is a dependency object, and not a FrameworkElement, nothing is holding onto the reference after the DelayedRegionCreationBehavior //is instantiated inside RegionManager.CreateRegion(DependencyObject element). If the GC runs before RegionManager.UpdateRegions is called, the region will //never get registered because it is gone from the updatingRegionsListeners list inside RegionManager. So we need to hold on to it. This should be rare. DependencyObject depObj = this.TargetElement as DependencyObject; if (depObj != null) { Track(); return; } } private void UnWireTargetElement() { FrameworkElement element = this.TargetElement as FrameworkElement; if (element != null) { element.Loaded -= this.ElementLoaded; return; } #if !HAS_WINUI FrameworkContentElement fcElement = this.TargetElement as FrameworkContentElement; if (fcElement != null) { fcElement.Loaded -= this.ElementLoaded; return; } #endif DependencyObject depObj = this.TargetElement as DependencyObject; if (depObj != null) { Untrack(); return; } } /// <summary> /// Add the instance of this class to <see cref="_instanceTracker"/> to keep it alive /// </summary> private void Track() { lock(_trackerLock) { if (!_instanceTracker.Contains(this)) { _instanceTracker.Add(this); } } } /// <summary> /// Remove the instance of this class from <see cref="_instanceTracker"/> /// so it can eventually be garbage collected /// </summary> private void Untrack() { lock(_trackerLock) { _instanceTracker.Remove(this); } } } }
38.856481
241
0.59085
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
daixin10310/CarefulDemo
MVVMCareful/Careful.Module.Core/Regions/Behaviors/DelayedRegionCreationBehavior.cs
8,393
C#
using System; namespace SQLib { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class SqlColumnAttribute : Attribute { public string Name { get; set; } public SqlColumnAttribute(string name) { Name = name; } } }
20.375
95
0.625767
[ "MIT" ]
zmjack/SQLib
SQLib/SqlColumnAttribute.cs
328
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using FluentValidation; using MediatR; using Microsoft.AspNetCore.Mvc; using Miru; using Miru.Databases.EntityFramework; using Miru.Domain; using Miru.Mvc; using Miru.Validation; using Supportreon.Database; using Supportreon.Domain; namespace Supportreon.Features.Projects { public class ProjectEdit { public class Query : IRequest<Command> { public long Id { get; set; } } public class Command : IRequest<Result> { public long Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal MinimumDonation { get; set; } public long CategoryId { get; set; } public decimal? Goal { get; set; } public DateTime? EndDate { get; set; } public IEnumerable<ILookupable> Categories { get; set; } } public class Result { public long Id { get; set; } } public class Handler : IRequestHandler<Query, Command>, IRequestHandler<Command, Result> { private readonly SupportreonDbContext _db; public Handler(SupportreonDbContext db) { _db = db; } public async Task<Command> Handle(Query request, CancellationToken ct) { var project = await _db.Projects.ByIdOrFailAsync(request.Id, ct); var categories = await _db.Categories.ToLookupableAsync(ct); return new Command { Id = project.Id, Name = project.Name, Description = project.Description, Goal = project.Goal, CategoryId = project.CategoryId, EndDate = project.EndDate, MinimumDonation = project.MinimumDonation, Categories = categories }; } public async Task<Result> Handle(Command request, CancellationToken ct) { var project = await _db.Projects.ByIdAsync(request.Id) ?? new Project(); project.Name = request.Name; project.Description = request.Description; project.MinimumDonation = request.MinimumDonation; project.CategoryId = request.CategoryId; project.Goal = request.Goal; project.EndDate = request.EndDate; await _db.SaveOrUpdate(project, ct); return new Result { Id = project.Id }; } } public class Validator : AbstractValidator<Command> { public Validator(SupportreonDbContext db) { RuleFor(m => m.Name) .NotEmpty() .MaximumLength(64) .UniqueAsync(async (cmd, ct) => await db.Projects.UniqueAsync(cmd.Id, m => m.Name == cmd.Name, ct)); RuleFor(m => m.Description).NotEmpty().MaximumLength(1000); RuleFor(m => m.MinimumDonation).NotEmpty().GreaterThanOrEqualTo(Donation.Minimum); RuleFor(m => m.CategoryId).NotEmpty(); } } public class ProjectsController : MiruController { [Route("/Projects/{id:long}/Edit")] public async Task<Command> Edit(Query query) => await Send(query); [HttpPost, Route("/Projects/Save")] public async Task<Result> Save(Command command) => await Send(command); } } }
33.094017
98
0.530217
[ "MIT" ]
joaofx/Supportreon
src/Supportreon/Features/Projects/ProjectEdit.cs
3,872
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NPH.Models; using NPH.Services.Implementation; using NPH.Services.Interface; using System; using System.Collections.Generic; using System.Text; using FluentAssertions; namespace NPH.Services.Tests { [TestClass()] public class WeatherAnalysisTests { private Mock<IWeatherStack> mock; private Mock<WeatherResult> mockWeather; private Mock<WeatherCurrent> mockWeatherCurrent; [TestInitialize] public void Init() { mock = new Mock<IWeatherStack>(); mockWeather = new Mock<WeatherResult>(); mockWeatherCurrent = new Mock<WeatherCurrent>(); } [TestMethod()] public void Can_GoOuside_Test() { mockWeatherCurrent.SetupGet<int>(p => p.WeatherCode).Returns(262); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = true; var actual = weatherAnalysis.GoOuside(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void Cant_GoOuside_Test() { mockWeatherCurrent.SetupGet<int>(p => p.WeatherCode).Returns(264); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = false; var actual = weatherAnalysis.GoOuside(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected, "cannot go outside when raining"); } [TestMethod()] public void GoOuside_Error_Test() { mockWeather.Setup(p => p.Success).Returns(false); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = false; var actual = weatherAnalysis.GoOuside(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void Need_WearSunscreen_Test() { mockWeatherCurrent.SetupGet<float>(p => p.UvIndex).Returns(4); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = true; var actual = weatherAnalysis.WearSunscreen(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void NoNeed_WearSunscreen_Test() { mockWeatherCurrent.SetupGet<float>(p => p.UvIndex).Returns(2); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = false; var actual = weatherAnalysis.WearSunscreen(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void Can_WearSunscreen_Test() { mockWeatherCurrent.SetupGet<int>(p => p.WeatherCode).Returns(262); mockWeatherCurrent.SetupGet<float>(p => p.WindSpeed).Returns(16); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = true; var actual = weatherAnalysis.FlyKite(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void Cant_WearSunscreen_Raining_Test() { mockWeatherCurrent.SetupGet<int>(p => p.WeatherCode).Returns(265); mockWeatherCurrent.SetupGet<float>(p => p.WindSpeed).Returns(16); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = false; var actual = weatherAnalysis.FlyKite(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } [TestMethod()] public void Cant_WearSunscreen_NoWind_Test() { mockWeatherCurrent.SetupGet<int>(p => p.WeatherCode).Returns(262); mockWeatherCurrent.SetupGet<float>(p => p.WindSpeed).Returns(14); mockWeather.SetupGet(p => p.Current).Returns(mockWeatherCurrent.Object); mock.Setup(p => p.GetWeatherInformation("", 0)).Returns(mockWeather.Object); IWeatherAnalysis weatherAnalysis = new WeatherAnalysis(); var expected = false; var actual = weatherAnalysis.FlyKite(mock.Object.GetWeatherInformation("", 0)); actual.Should().Be(expected); } } }
40.518248
97
0.628716
[ "Apache-2.0" ]
nguyenphanhuynh/fpttest
NPH.ServicesTests/WeatherAnalysisTests.cs
5,553
C#
namespace IotTelemetrySimulator.Test { using System; using System.Collections.Generic; using System.Text; using Moq; using Xunit; public class PayloadGeneratorTest { private byte[] GetBytes(string v) => Encoding.UTF8.GetBytes(v); [Fact] public void When_Getting_Payload_Should_Distribute_Correctly() { var randomizer = new Mock<IRandomizer>(); var target = new PayloadGenerator( new[] { new FixPayload(30, this.GetBytes("30")), new FixPayload(55, this.GetBytes("55")), new FixPayload(15, this.GetBytes("15")) }, randomizer.Object); var t = new (int distribution, string expectedPayload)[] { (1, "55"), (55, "55"), (56, "30"), (85, "30"), (86, "15"), (100, "15"), }; foreach (var tt in t) { randomizer.Setup(x => x.Next(It.IsAny<int>(), It.IsAny<int>())).Returns(tt.distribution); var (p, v) = target.Generate(null, null); Assert.Equal(tt.expectedPayload, Encoding.UTF8.GetString(p)); } } [Fact] public void Sequence_Generator() { var telemetryTemplate = new TelemetryTemplate("{\"val\":\"$.Value\"}", new[] { "Value", "Counter" }); var telemetryVariables = new[] { new TelemetryVariable { Name = "Value", Sequence = true, Values = new object[] { "$.Counter", "true", "false", "$.Counter" }, }, new TelemetryVariable { Name = "Counter", Step = 1, Min = 1 } }; var telemetryValues = new TelemetryValues(telemetryVariables); var payload = new TemplatedPayload(100, telemetryTemplate, telemetryValues); var target = new PayloadGenerator(new[] { payload }, new DefaultRandomizer()); var expectedValues = new[] { "{\"val\":\"1\"}", "{\"val\":\"true\"}", "{\"val\":\"false\"}", "{\"val\":\"2\"}", "{\"val\":\"3\"}", "{\"val\":\"true\"}", "{\"val\":\"false\"}", "{\"val\":\"4\"}", }; var variables = new Dictionary<string, object> { { Constants.DeviceIdValueName, "mydevice" }, }; byte[] result; foreach (var expectedValue in expectedValues) { (result, variables) = target.Generate(null, variables); Assert.NotEmpty(variables); Assert.Equal(expectedValue, Encoding.UTF8.GetString(result)); } } [Fact] public void Sequence_With_Exchanging_Counters_Generator() { var telemetryTemplate = new TelemetryTemplate("{\"val1\":\"$.Value1\",\"val2\":\"$.Value2\"}", new[] { "Value1", "Value2", "Counter1", "Counter2" }); var telemetryVariables = new[] { new TelemetryVariable { Name = "Value1", Sequence = true, Values = new object[] { "$.Counter1", "$.Counter2" }, }, new TelemetryVariable { Name = "Value2", Sequence = true, Values = new object[] { "$.Counter2", "$.Counter1" }, }, new TelemetryVariable { Name = "Counter1", Step = 1, Min = 1 }, new TelemetryVariable { Name = "Counter2", Step = 1, Min = 1_001 } }; var telemetryValues = new TelemetryValues(telemetryVariables); var payload = new TemplatedPayload(100, telemetryTemplate, telemetryValues); var target = new PayloadGenerator(new[] { payload }, new DefaultRandomizer()); var expectedValues = new[] { "{\"val1\":\"1\",\"val2\":\"1001\"}", "{\"val1\":\"1002\",\"val2\":\"2\"}", "{\"val1\":\"3\",\"val2\":\"1003\"}", "{\"val1\":\"1004\",\"val2\":\"4\"}", }; var variables = new Dictionary<string, object> { { Constants.DeviceIdValueName, "mydevice" }, }; byte[] result; foreach (var expectedValue in expectedValues) { (result, variables) = target.Generate(null, variables); Assert.NotEmpty(variables); Assert.Equal(expectedValue, Encoding.UTF8.GetString(result)); } } [Fact] public void Sequence_With_Mixed_Counters_Generator() { var telemetryTemplate = new TelemetryTemplate("{\"val1\":\"$.Value1\",\"val2\":\"$.Value2\",\"counter_3\":\"$.Counter3\"}", new[] { "Value1", "Value2", "Counter1", "Counter2", "Counter3" }); var telemetryVariables = new[] { new TelemetryVariable { Name = "Value1", Sequence = true, Values = new object[] { "$.Counter1", "$.Counter2" }, }, new TelemetryVariable { Name = "Value2", Sequence = true, Values = new object[] { "$.Counter2", "$.Counter1" }, }, new TelemetryVariable { Name = "Counter1", Step = 1, Min = 1 }, new TelemetryVariable { Name = "Counter2", Step = 1, Min = 1_001 }, new TelemetryVariable { Name = "Counter3", Step = 1, Min = 1_000_001 } }; var telemetryValues = new TelemetryValues(telemetryVariables); var payload = new TemplatedPayload(100, telemetryTemplate, telemetryValues); var target = new PayloadGenerator(new[] { payload }, new DefaultRandomizer()); var expectedValues = new[] { "{\"val1\":\"1\",\"val2\":\"1001\",\"counter_3\":\"1000001\"}", "{\"val1\":\"1002\",\"val2\":\"2\",\"counter_3\":\"1000002\"}", "{\"val1\":\"3\",\"val2\":\"1003\",\"counter_3\":\"1000003\"}", "{\"val1\":\"1004\",\"val2\":\"4\",\"counter_3\":\"1000004\"}", }; var variables = new Dictionary<string, object> { { Constants.DeviceIdValueName, "mydevice" }, }; byte[] result; foreach (var expectedValue in expectedValues) { (result, variables) = target.Generate(null, variables); Assert.NotEmpty(variables); Assert.Equal(expectedValue, Encoding.UTF8.GetString(result)); } } [Fact] public void Sequence_As_Array_Attribute() { var telemetryTemplate = new TelemetryTemplate("{\"val1\":\"$.Value1\",\"array_var\":$.ArrayValue,\"array_fix\":[\"FixCategory\"]}", new[] { "Value1", "Counter1", "Counter2", "ArrayValue" }); var telemetryVariables = new[] { new TelemetryVariable { Name = "Value1", Sequence = true, Values = new object[] { "$.Counter1", "$.Counter2" }, }, new TelemetryVariable { Name = "Counter1", Step = 1, Min = 1 }, new TelemetryVariable { Name = "Counter2", Step = 1, Min = 1_001 }, new TelemetryVariable { Name = "ArrayValue", Sequence = true, Values = new object[] { "[\"MyCategory\"]", "[]" } } }; var telemetryValues = new TelemetryValues(telemetryVariables); var payload = new TemplatedPayload(100, telemetryTemplate, telemetryValues); var target = new PayloadGenerator(new[] { payload }, new DefaultRandomizer()); var expectedValues = new[] { "{\"val1\":\"1\",\"array_var\":[\"MyCategory\"],\"array_fix\":[\"FixCategory\"]}", "{\"val1\":\"1001\",\"array_var\":[],\"array_fix\":[\"FixCategory\"]}", "{\"val1\":\"2\",\"array_var\":[\"MyCategory\"],\"array_fix\":[\"FixCategory\"]}", "{\"val1\":\"1002\",\"array_var\":[],\"array_fix\":[\"FixCategory\"]}", }; var variables = new Dictionary<string, object> { { Constants.DeviceIdValueName, "mydevice" }, }; byte[] result; foreach (var expectedValue in expectedValues) { (result, variables) = target.Generate(null, variables); Assert.NotEmpty(variables); Assert.Equal(expectedValue, Encoding.UTF8.GetString(result)); } } } }
34.309278
202
0.427784
[ "MIT" ]
LauraDamianTNA/Iot-Telemetry-Simulator
test/IotTelemetrySimulator.Test/PayloadGeneratorTest.cs
9,986
C#
using System; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Collections.Generic; using System.Linq; namespace filemon.Util{ public class HttpUtil{ public static async Task<string> Post(byte[] data, Dictionary<string , string> json , string url) { HttpContent bytesContent = new ByteArrayContent(data); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { for (int i = 0; i < json.Count; i++) { HttpContent stringContent = new StringContent(json.ElementAt(i).Key); formData.Add(stringContent, json.ElementAt(i).Key, json.ElementAt(i).Value); } formData.Add(bytesContent , "File" ); var response = await client.PostAsync(url, formData); if (!response.IsSuccessStatusCode) { return null; } return await response.Content.ReadAsStringAsync(); } } public async Task UploadAsync() { // Google Cloud Platform project ID. const string projectId = "project-id-goes-here"; // The name for the new bucket. const string bucketName = projectId + "-test-bucket"; // Path to the file to upload const string filePath = @"C:\path\to\image.jpg"; var newObject = new Google.Apis.Storage.v1.Data.Object { Bucket = bucketName, Name = System.IO.Path.GetFileNameWithoutExtension(filePath), ContentType = "image/jpeg" }; // read the JSON credential file saved when you created the service account var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromJson(System.IO.File.ReadAllText( @"c:\path\to\service-account-credentials.json")); // Instantiates a client. using (var storageClient = Google.Cloud.Storage.V1.StorageClient.Create(credential)) { try { // Creates the new bucket. Only required the first time. // You can also create buckets through the GCP cloud console web interface //storageClient.CreateBucket(projectId, bucketName); // Open the image file filestream using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { // set minimum chunksize just to see progress updating var uploadObjectOptions = new Google.Cloud.Storage.V1.UploadObjectOptions { ChunkSize = Google.Cloud.Storage.V1.UploadObjectOptions.MinimumChunkSize }; await storageClient.UploadObjectAsync( newObject, fileStream, uploadObjectOptions) .ConfigureAwait(false); } } catch (Google.GoogleApiException e) when (e.Error.Code == 409) { } catch (Exception e) { } } } } }
34.050505
105
0.544349
[ "MIT" ]
bahram-ghahari/Detekt
Monitor/Util/HttpUtil.cs
3,371
C#
using System; using System.Collections.Generic; using System.Linq; using Rhino.Mocks; using Rhino.Mocks.Interfaces; using Xunit; namespace StakHappy.Core.UnitTest.Logic.UserServiceLogic { [Collection("Logic")] public class GetListFixture : TestBase { [Fact] public void Successful() { // data var id = Guid.NewGuid(); System.Linq.Expressions.Expression<Func<Core.Data.Model.UserService, bool>> expr = u => u.Id == id; var services = new List<Core.Data.Model.UserService>(); // mocks var userServicePersistor = Mocks.StrictMock<Core.Data.Persistor.UserService>(); var bll = Mocks.StrictMock<Core.Logic.UserServiceLogic>(userServicePersistor); bll.Expect(b => b.GetList(expr)).CallOriginalMethod(OriginalCallOptions.NoExpectation); userServicePersistor.Expect(d => d.Get(expr)).Return(services.AsQueryable()); // record Mocks.ReplayAll(); var results = bll.GetList(expr); Assert.Equal(services, results); } } }
30.297297
112
0.626227
[ "MIT" ]
aarce77/StakeHappy-Core
StakHappy.Core.UnitTest/Logic/UserServiceLogic/GetListFixture.cs
1,123
C#
namespace Alex.Utils.Commands { public class AskServerProperty : CommandProperty { /// <inheritdoc /> public AskServerProperty(string name, bool required = true, string typeIdentifier = "Unknown") : base(name, required, typeIdentifier) { } } }
31.25
139
0.74
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
codingwatching/Alex
src/Alex/Utils/Commands/AskServerProperty.cs
250
C#
using System; using Http.quoted_string; using Http.token; using JetBrains.Annotations; using Txt.ABNF; using Txt.Core; namespace Http.chunk_ext_val { public sealed class ChunkExtensionValueLexerFactory : RuleLexerFactory<ChunkExtensionValue> { static ChunkExtensionValueLexerFactory() { Default = new ChunkExtensionValueLexerFactory( TokenLexerFactory.Default.Singleton(), QuotedStringLexerFactory.Default.Singleton()); } public ChunkExtensionValueLexerFactory( [NotNull] ILexerFactory<Token> token, [NotNull] ILexerFactory<QuotedString> quotedString) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (quotedString == null) { throw new ArgumentNullException(nameof(quotedString)); } Token = token; QuotedString = quotedString; } [NotNull] public static ChunkExtensionValueLexerFactory Default { get; } [NotNull] public ILexerFactory<QuotedString> QuotedString { get; set; } [NotNull] public ILexerFactory<Token> Token { get; set; } public override ILexer<ChunkExtensionValue> Create() { var innerLexer = Alternation.Create( Token.Create(), QuotedString.Create()); return new ChunkExtensionValueLexer(innerLexer); } } }
29
95
0.59987
[ "MIT" ]
StevenLiekens/HTTPortable
src/Http/chunk_ext_val/ChunkExtensionValueLexerFactory.cs
1,539
C#
#region License //------------------------------------------------------------------------------ // Copyright (c) Dmitrii Evdokimov // Source https://github.com/diev/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //------------------------------------------------------------------------------ #endregion namespace JZDO_Exch { public sealed class SftpSettings { public string Host { get; set; } = "10.**.**.**"; public int Port { get; set; } = 22; public string User { get; set; } = "zdo"; public string Pass { get; set; } = "****"; public string RemoteIn { get; set; } = "zdo/files/doc/in/cs/unknown"; public string RemoteOut { get; set; } = "zdo/files/doc/out/cs/unknown"; public string TestRemoteIn { get; set; } = "zdo/files/doc/in/cs/test"; public string TestRemoteOut { get; set; } = "zdo/files/doc/out/cs/test"; public string LocalIn { get; set; } = @"ZDO\IN"; public string LocalOut { get; set; } = @"ZDO\OUT"; public string StoreIn { get; set; } = @"ZDO\ARCHIVE\IN"; public string StoreOut { get; set; } = @"ZDO\ARCHIVE\OUT"; } }
40.414634
80
0.581171
[ "Apache-2.0" ]
diev/JZDO-Exch
JZDO-Exch/SftpSettings.cs
1,659
C#
namespace SRF.UI.Layout { using System.Collections.Generic; using Internal; using UnityEngine; using UnityEngine.UI; /// <summary> /// Layout Group controller that arranges children in rows, fitting as many on a line until total width exceeds parent /// bounds /// </summary> [AddComponentMenu(ComponentMenuPaths.FlowLayoutGroup)] public class FlowLayoutGroup : LayoutGroup { /// <summary> /// Holds the rects that will make up the current row being processed /// </summary> private readonly IList<RectTransform> _rowList = new List<RectTransform>(); private float _layoutHeight; public bool ChildForceExpandHeight = false; public bool ChildForceExpandWidth = false; public float Spacing = 0f; protected bool IsCenterAlign { get { return childAlignment == TextAnchor.LowerCenter || childAlignment == TextAnchor.MiddleCenter || childAlignment == TextAnchor.UpperCenter; } } protected bool IsRightAlign { get { return childAlignment == TextAnchor.LowerRight || childAlignment == TextAnchor.MiddleRight || childAlignment == TextAnchor.UpperRight; } } protected bool IsMiddleAlign { get { return childAlignment == TextAnchor.MiddleLeft || childAlignment == TextAnchor.MiddleRight || childAlignment == TextAnchor.MiddleCenter; } } protected bool IsLowerAlign { get { return childAlignment == TextAnchor.LowerLeft || childAlignment == TextAnchor.LowerRight || childAlignment == TextAnchor.LowerCenter; } } public override void CalculateLayoutInputHorizontal() { base.CalculateLayoutInputHorizontal(); var minWidth = GetGreatestMinimumChildWidth() + padding.left + padding.right; SetLayoutInputForAxis(minWidth, -1, -1, 0); } public override void SetLayoutHorizontal() { SetLayout(rectTransform.rect.width, 0, false); } public override void SetLayoutVertical() { SetLayout(rectTransform.rect.width, 1, false); } public override void CalculateLayoutInputVertical() { _layoutHeight = SetLayout(rectTransform.rect.width, 1, true); } /// <summary> /// Main layout method /// </summary> /// <param name="width">Width to calculate the layout with</param> /// <param name="axis">0 for horizontal axis, 1 for vertical</param> /// <param name="layoutInput">If true, sets the layout input for the axis. If false, sets child position for axis</param> public float SetLayout(float width, int axis, bool layoutInput) { var groupHeight = rectTransform.rect.height; // Width that is available after padding is subtracted var workingWidth = rectTransform.rect.width - padding.left - padding.right; // Accumulates the total height of the rows, including spacing and padding. var yOffset = IsLowerAlign ? padding.bottom : (float)padding.top; var currentRowWidth = 0f; var currentRowHeight = 0f; for (var i = 0; i < rectChildren.Count; i++) { // LowerAlign works from back to front var index = IsLowerAlign ? rectChildren.Count - 1 - i : i; var child = rectChildren[index]; var childWidth = LayoutUtility.GetPreferredSize(child, 0); var childHeight = LayoutUtility.GetPreferredSize(child, 1); // Max child width is layout group with - padding childWidth = Mathf.Min(childWidth, workingWidth); // Apply spacing if not the first element in a row if (_rowList.Count > 0) { currentRowWidth += Spacing; } // If adding this element would exceed the bounds of the row, // go to a new line after processing the current row if (currentRowWidth + childWidth > workingWidth) { // Undo spacing addition if we're moving to a new line (Spacing is not applied on edges) currentRowWidth -= Spacing; // Process current row elements positioning if (!layoutInput) { var h = CalculateRowVerticalOffset(groupHeight, yOffset, currentRowHeight); LayoutRow(_rowList, currentRowWidth, currentRowHeight, workingWidth, padding.left, h, axis); } // Clear existing row _rowList.Clear(); // Add the current row height to total height accumulator, and reset to 0 for the next row yOffset += currentRowHeight; yOffset += Spacing; currentRowHeight = 0; currentRowWidth = 0; } currentRowWidth += childWidth; _rowList.Add(child); // We need the largest element height to determine the starting position of the next line if (childHeight > currentRowHeight) { currentRowHeight = childHeight; } } if (!layoutInput) { var h = CalculateRowVerticalOffset(groupHeight, yOffset, currentRowHeight); // Layout the final row LayoutRow(_rowList, currentRowWidth, currentRowHeight, workingWidth, padding.left, h, axis); } _rowList.Clear(); // Add the last rows height to the height accumulator yOffset += currentRowHeight; yOffset += IsLowerAlign ? padding.top : padding.bottom; if (layoutInput) { if (axis == 1) { SetLayoutInputForAxis(yOffset, yOffset, -1, axis); } } return yOffset; } private float CalculateRowVerticalOffset(float groupHeight, float yOffset, float currentRowHeight) { float h; if (IsLowerAlign) { h = groupHeight - yOffset - currentRowHeight; } else if (IsMiddleAlign) { h = groupHeight * 0.5f - _layoutHeight * 0.5f + yOffset; } else { h = yOffset; } return h; } protected void LayoutRow(IList<RectTransform> contents, float rowWidth, float rowHeight, float maxWidth, float xOffset, float yOffset, int axis) { var xPos = xOffset; if (!ChildForceExpandWidth && IsCenterAlign) { xPos += (maxWidth - rowWidth) * 0.5f; } else if (!ChildForceExpandWidth && IsRightAlign) { xPos += (maxWidth - rowWidth); } var extraWidth = 0f; if (ChildForceExpandWidth) { var flexibleChildCount = 0; for (var i = 0; i < _rowList.Count; i++) { if (LayoutUtility.GetFlexibleWidth(_rowList[i]) > 0f) { flexibleChildCount++; } } if (flexibleChildCount > 0) { extraWidth = (maxWidth - rowWidth) / flexibleChildCount; } } for (var j = 0; j < _rowList.Count; j++) { var index = IsLowerAlign ? _rowList.Count - 1 - j : j; var rowChild = _rowList[index]; var rowChildWidth = LayoutUtility.GetPreferredSize(rowChild, 0); if (LayoutUtility.GetFlexibleWidth(rowChild) > 0f) { rowChildWidth += extraWidth; } var rowChildHeight = LayoutUtility.GetPreferredSize(rowChild, 1); if (ChildForceExpandHeight) { rowChildHeight = rowHeight; } rowChildWidth = Mathf.Min(rowChildWidth, maxWidth); var yPos = yOffset; if (IsMiddleAlign) { yPos += (rowHeight - rowChildHeight) * 0.5f; } else if (IsLowerAlign) { yPos += (rowHeight - rowChildHeight); } if (axis == 0) { #if UNITY_2019_1 SetChildAlongAxis(rowChild, 0, 1f, xPos, rowChildWidth); #else SetChildAlongAxis(rowChild, 0, xPos, rowChildWidth); #endif } else { #if UNITY_2019_1 SetChildAlongAxis(rowChild, 1, 1f, yPos, rowChildHeight); #else SetChildAlongAxis(rowChild, 1, yPos, rowChildHeight); #endif } xPos += rowChildWidth + Spacing; } } public float GetGreatestMinimumChildWidth() { var max = 0f; for (var i = 0; i < rectChildren.Count; i++) { var w = LayoutUtility.GetMinWidth(rectChildren[i]); max = Mathf.Max(w, max); } return max; } } }
32.491803
129
0.51221
[ "Apache-2.0" ]
Game-Bubble/Run-Transformer
Assets/StompyRobot/SRF/Scripts/UI/Layout/FlowLayoutGroup.cs
9,912
C#
using Locust.ServiceModel; namespace Locust.Modules.Setting.Strategies { public partial class AppSettingGetByPKRequest : IBaseServiceRequest { } }
17.666667
68
0.773585
[ "MIT" ]
mansoor-omrani/Locust.NET
Modules/Locust.Modules.Setting/Service/AppSetting/GetByPK/Request.cs
159
C#
using System; using System.Net.Http.Headers; using Common.Logging; using Nethereum.BlockchainProcessing.Services; using Nethereum.Contracts; using Nethereum.Contracts.Services; using Nethereum.JsonRpc.Client; using Nethereum.RPC; using Nethereum.RPC.Accounts; using Nethereum.RPC.TransactionManagers; #if !LITE using Nethereum.Signer; #endif using Nethereum.Util; namespace Nethereum.Web3 { public class Web3 : IWeb3 { private static readonly AddressUtil AddressUtil = new AddressUtil(); private static readonly Sha3Keccack Sha3Keccack = new Sha3Keccack(); public Web3(IClient client) { Client = client; InitialiseInnerServices(); InitialiseDefaultGasAndGasPrice(); } public Web3(IAccount account, IClient client) : this(client) { TransactionManager = account.TransactionManager; TransactionManager.Client = Client; } public Web3(string url = @"http://localhost:8545/", ILog log = null, AuthenticationHeaderValue authenticationHeader = null) { InitialiseDefaultRpcClient(url, log, authenticationHeader); InitialiseInnerServices(); InitialiseDefaultGasAndGasPrice(); } public Web3(IAccount account, string url = @"http://localhost:8545/", ILog log = null, AuthenticationHeaderValue authenticationHeader = null) : this(url, log, authenticationHeader) { TransactionManager = account.TransactionManager; TransactionManager.Client = Client; } public ITransactionManager TransactionManager { get => Eth.TransactionManager; set => Eth.TransactionManager = value; } public static UnitConversion Convert { get; } = new UnitConversion(); public IClient Client { get; private set; } public IEthApiContractService Eth { get; private set; } public IShhApiService Shh { get; private set; } public INetApiService Net { get; private set; } public IPersonalApiService Personal { get; private set; } public IBlockchainProcessingService Processing { get; private set; } public FeeSuggestionService FeeSuggestion { get; private set; } private void InitialiseDefaultGasAndGasPrice() { #if !LITE TransactionManager.DefaultGas = LegacyTransaction.DEFAULT_GAS_LIMIT; TransactionManager.DefaultGasPrice = LegacyTransaction.DEFAULT_GAS_PRICE; #endif } #if !LITE public static string GetAddressFromPrivateKey(string privateKey) { return EthECKey.GetPublicAddress(privateKey); } #endif public static bool IsChecksumAddress(string address) { return AddressUtil.IsChecksumAddress(address); } public static string Sha3(string value) { return Sha3Keccack.CalculateHash(value); } public static string ToChecksumAddress(string address) { return AddressUtil.ConvertToChecksumAddress(address); } public static string ToValid20ByteAddress(string address) { return AddressUtil.ConvertToValid20ByteAddress(address); } protected virtual void InitialiseInnerServices() { Eth = new EthApiContractService(Client); Processing = new BlockchainProcessingService(Eth); Shh = new ShhApiService(Client); Net = new NetApiService(Client); Personal = new PersonalApiService(Client); FeeSuggestion = new FeeSuggestionService(Client); } private void InitialiseDefaultRpcClient(string url, ILog log, AuthenticationHeaderValue authenticationHeader) { Client = new RpcClient(new Uri(url), authenticationHeader, null, null, log); } } }
32.725
188
0.658009
[ "MIT" ]
GitHubPang/Nethereum
src/Nethereum.Web3/Web3.cs
3,929
C#
#region using System.Collections.Generic; #endregion namespace FluentInterpreter.Tests.Models { public class User { public int Id { get; set; } public string Username { get; set; } public Profile? Profile { get; set; } public int Age { get; set; } public ICollection<Note> Notes { get; set; } } }
19.526316
53
0.579515
[ "MIT" ]
TonyTroeff/FluentInterpreter
FluentInterpreter/FluentInterpreter.Tests/Models/User.cs
371
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace k8s.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// ObjectFieldSelector selects an APIVersioned field of an object. /// </summary> public partial class V1ObjectFieldSelector { /// <summary> /// Initializes a new instance of the V1ObjectFieldSelector class. /// </summary> public V1ObjectFieldSelector() { CustomInit(); } /// <summary> /// Initializes a new instance of the V1ObjectFieldSelector class. /// </summary> /// <param name="fieldPath">Path of the field to select in the /// specified API version.</param> /// <param name="apiVersion">Version of the schema the FieldPath is /// written in terms of, defaults to "v1".</param> public V1ObjectFieldSelector(string fieldPath, string apiVersion = default(string)) { ApiVersion = apiVersion; FieldPath = fieldPath; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets version of the schema the FieldPath is written in /// terms of, defaults to "v1". /// </summary> [JsonProperty(PropertyName = "apiVersion")] public string ApiVersion { get; set; } /// <summary> /// Gets or sets path of the field to select in the specified API /// version. /// </summary> [JsonProperty(PropertyName = "fieldPath")] public string FieldPath { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (FieldPath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "FieldPath"); } } } }
31.364865
91
0.577337
[ "MIT" ]
pdeligia/nekara-artifact
TSVD/kubernetes-client/src/KubernetesClient/generated/Models/V1ObjectFieldSelector.cs
2,321
C#
using Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { /// <summary> /// Special TextBox that accepts all keys and shows Keys representations if IsCommandInput is /// set to True. Bahves like common TextBox otherwise /// </summary> public class KeyboardCommandTextBox : TextBox { #region Private Fields private List<int> _pressedButtons = new List<int>(); #endregion #region Public Properties /// <summary> /// Gets or sets value indicating if command input is enabled /// </summary> public bool IsCommandInput { get; set; } #endregion #region Constructor /// <summary> /// Setup all needed event handlers /// </summary> public KeyboardCommandTextBox() : base() { KeyDown += eventHandler_KeyDown; KeyUp += eventHandler_KeyUp; KeyPress += eventHandler_KeyPress; } #endregion #region Protected Methods protected override bool IsInputKey(Keys keyData) { if (IsCommandInput) { return true; } else { return base.IsInputKey(keyData); } } #endregion #region Private Event Handlers private void eventHandler_KeyDown(object sender, KeyEventArgs e) { //if it's not a command input - do nothing if (!IsCommandInput) return; if (!_pressedButtons.Contains(e.KeyValue)) { //if it's a multi-key command - print "-" if (e.Alt && e.KeyValue != (int)Keys.Menu || e.Control && e.KeyValue != (int)Keys.ControlKey || e.Shift && e.KeyValue != (int)Keys.ShiftKey) { Text += "-"; } else { if (Text.Length > 0) Text += ","; } //add string representation for key Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); //place caret to the end SelectionStart = Text.Length; _pressedButtons.Add(e.KeyValue); } e.Handled = true; } private void eventHandler_KeyUp(object sender, KeyEventArgs e) { if (IsCommandInput) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } } private void eventHandler_KeyPress(object sender, KeyPressEventArgs e) { if (IsCommandInput) { e.Handled = true; } } #endregion } }
25.533898
98
0.505808
[ "MIT" ]
StanislavUshakov/ArduinoWindowsRemoteControl
ArduinoWindowsRemoteControl/UI/KeyboardCommandTextBox.cs
3,015
C#
namespace Datafication.Models.Dtos { public class ImageDetailsDto { public int Id { get; set; } public string Url { get; set; } public IceCreamDto IceCream { get; set; } } }
23.222222
49
0.602871
[ "MIT" ]
eggertmar1/T-514-VEFT
Small_assignment3/template/Datafication.Models/Dtos/ImageDetailsDto.cs
209
C#
// ///----------------------------------------------------------------- // /// Class: IConnectionHeaders // /// Description: <Description> // /// Author: Dimitri Renke Date: 19.12.2016 // /// Notes: <Notes> // /// Revision History: // /// Name: Date: Description: // ///----------------------------------------------------------------- using System.Collections.Generic; using LibDataService.DataModels.Container; namespace LibDataService.ConnectionService { /// <summary> /// Interface to add static or dynamic Headers /// </summary> public interface IConnectionHeaders { bool HasHeader { get; } List<KeyValuePair<string, string>> Headers { get; } bool HasDynamicHeader(IDataContainer dataIn); List<KeyValuePair<string, string>> GetDynamicHeaders(IDataContainer dataIn); } }
31.571429
78
0.529412
[ "MIT" ]
MarianHristov92/Service-Prototype
LibDataService/ConnectionService/Interface/IConnectionHeaders.cs
886
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d11.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.Versioning; namespace TerraFX.Interop.DirectX; /// <include file='D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.xml' path='doc/member[@name="D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT"]/*' /> [SupportedOSPlatform("windows8.0")] public partial struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT { /// <include file='D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.xml' path='doc/member[@name="D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.Input"]/*' /> public D3D11_AUTHENTICATED_QUERY_INPUT Input; /// <include file='D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.xml' path='doc/member[@name="D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.EncryptionGuidIndex"]/*' /> public uint EncryptionGuidIndex; }
57
203
0.822807
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d11/D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT.cs
1,142
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using Grasshopper.Kernel; using Grasshopper.Kernel.Data; using Grasshopper.Kernel.Types; using Rhino.Geometry; using static Impala.Generic; using static Impala.Generated; using static Impala.Errors; namespace Impala { /// <summary> /// Divide a curve into segments of a set length. /// </summary> public class ParDivideLength : GH_Component { /// <summary> /// Initializes a new instance of the ParDivideLength Component. /// </summary> public ParDivideLength() : base("ParDivideLength", "ParDivLen", "Divide a curve into segments with a preset length.", "Impala", "Physical") { var nerror = new Error<(GH_Curve, GH_Number, GH_Point, GH_Vector)>(NullCheck, NullHandle, this); var terror = new Error<(GH_Curve, GH_Number, GH_Point, GH_Vector)>(TolValidCheck, TolValidHandle, this); CheckError = new ErrorChecker<(GH_Curve, GH_Number, GH_Point, GH_Vector)>(nerror,terror); } private static ErrorChecker<(GH_Curve, GH_Number, GH_Point, GH_Vector)> CheckError; private static Func<(GH_Curve, GH_Number, GH_Point, GH_Vector), bool> NullCheck = a => (a.Item1 != null && a.Item2 != null && a.Item3 != null && a.Item4 != null); /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_InputParamManager pManager) { pManager.AddCurveParameter("Curve", "C", "Curve to divide", GH_ParamAccess.tree); pManager.AddNumberParameter("Length", "L", "Length of segments", GH_ParamAccess.tree); } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_OutputParamManager pManager) { pManager.AddPointParameter("Points", "P", "Division Points", GH_ParamAccess.tree); pManager.AddVectorParameter("Tangents", "T", "Tangents at divisions", GH_ParamAccess.tree); pManager.AddNumberParameter("Parameters", "t", "Parameters at divisions", GH_ParamAccess.tree); } /// <summary> /// Solve method - Divide a curve into segments of a set length. /// </summary> public static (GH_Point[],GH_Vector[],GH_Number[]) DivCurve(GH_Curve gcrv, GH_Number gnum, GH_Point start, GH_Vector stan) { var crv = (Curve)gcrv.Value.Duplicate(); var divLen = gnum.Value; double curveLen = crv.GetLength(); var divisions = Convert.ToInt32(Math.Floor(curveLen / divLen)) + 1; var pointArray = new GH_Point[divisions]; var vectorArray = new GH_Vector[divisions]; var paramArray = new GH_Number[divisions]; if (divisions > 1) { double[] parArray = crv.DivideByLength(divLen, true, out Point3d[] tempPts); if (tempPts != null) { for (int i = 0; i < tempPts.Count(); i++) { pointArray[i] = tempPts[i] != null ? new GH_Point(tempPts[i]) : null; } if (parArray != null) //shouldn't be necessary, but there's race conditions around here. { //Todo: we should really have a recompute here. for (int i = 0; i < parArray.Count(); i++) { paramArray[i] = new GH_Number(parArray[i]); vectorArray[i] = new GH_Vector(crv.TangentAt(parArray[i])); } } } else { return (new GH_Point[] { null }, new GH_Vector[] { null }, new GH_Number[] { null }); } } else { pointArray = new GH_Point[] { start }; vectorArray = new GH_Vector[] { stan }; paramArray = new GH_Number[] { new GH_Number(0.0) }; } return (pointArray, vectorArray, paramArray); } /// <summary> /// Error Checking /// </summary> private static Func<GH_Curve, bool> CurveValidCheck => x => x.Value.IsValid && x.Value.GetLength() > Rhino.RhinoMath.ZeroTolerance; private static Func<(GH_Curve, GH_Number, GH_Point, GH_Vector), bool> TolValidCheck => x => x.Item2.Value > Rhino.RhinoMath.ZeroTolerance; private static Action<GH_Component> CurveValidHandle => comp => comp.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Invalid Curve."); private static Action<GH_Component> TolValidHandle => comp => comp.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Invalid Division Length."); private static Func<GH_Curve, bool> CurveNull => c => c != null; /// <summary> /// Loop through data structure - checks curve nulls and creates start points/tangent structures before loop /// </summary> protected override void SolveInstance(IGH_DataAccess DA) { if (!DA.GetDataTree(0, out GH_Structure<GH_Curve> curveTree)) return; if (!DA.GetDataTree(1, out GH_Structure<GH_Number> lenTree)) return; //Check the curve errors sequentially to avoid race condition var crvnull = new Error<GH_Curve>(CurveNull, NullHandle, this); var crvvalid = new Error<GH_Curve>(CurveValidCheck, CurveValidHandle, this); var curveValidError = new ErrorChecker<GH_Curve>(crvnull, crvvalid); //These must be done with a sequential mapping, as there exists a race condition within the native //OpenNURBS methods for handling curves w/r/t extracting values at parameters. var startpts = MapStructure(curveTree, c => new GH_Point(c.Value.PointAtStart), curveValidError); var starttans = MapStructure(curveTree, c => new GH_Vector(c.Value.TangentAtStart), curveValidError); //Curve errors are pre-checked and already nulled out here var (points, tangents, divparams) = Zip4xGraft3(curveTree, lenTree, startpts, starttans, DivCurve, CheckError); DA.SetDataTree(0, points); DA.SetDataTree(1, tangents); DA.SetDataTree(2, divparams); return; } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon { get { return Impala.Properties.Resources.__0007_DivLen; } } /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("FAA9B0F6-2478-42B1-A19E-B2D9E3879C55"); } } } }
44.018405
170
0.588293
[ "MIT" ]
dcascaval/Impala
Impala/Components/ParDivideLength.cs
7,177
C#
using Homuai.Domain.Repository.Code; using Moq; namespace Useful.ToTests.Builders.Repositories { public class CodeWriteOnlyRepositoryBuilder { private static CodeWriteOnlyRepositoryBuilder _instance; private readonly Mock<ICodeWriteOnlyRepository> _repository; private CodeWriteOnlyRepositoryBuilder() { if (_repository == null) _repository = new Mock<ICodeWriteOnlyRepository>(); } public static CodeWriteOnlyRepositoryBuilder Instance() { _instance = new CodeWriteOnlyRepositoryBuilder(); return _instance; } public ICodeWriteOnlyRepository Build() { return _repository.Object; } } }
26.034483
68
0.647682
[ "Unlicense" ]
welissonArley/Homuai
tests/Backend/Useful.ToTests/Builders/Repositories/CodeWriteOnlyRepositoryBuilder.cs
757
C#
// Copyright (c) Alexandre Beauchamp. All rights reserved. // Licensed under the MIT license. using Compendium.Database.Models; using Compendium.Tests.Tools.Fixtures; using FluentAssertions; using System; using Xunit; namespace Compendium.Database.Repositories { public class TreasureRepositoryTests : TestBuilder, IClassFixture<DataSourceFixture>, IDisposable { private readonly DataSourceFixture fixture; private readonly ITreasureRepository repository; public TreasureRepositoryTests(DataSourceFixture fixture) { this.fixture = fixture; this.repository = new TreasureRepository(this.fixture.DataSource); } public void Dispose() => this.fixture.DeleteAll<Treasure>(); [Fact] public void GetAll_ShouldReturnAllTreasures() { Treasure treasure = DefaultTreasure().WithName("Chest"); this.fixture.Insert(treasure); var treasures = this.repository.GetAll(); treasures.Should().HaveCount(1); treasures.Should().OnlyContain(t => t.Name == treasure.Name); } [Fact] public void GetById_ShouldReturnATreasure_WhenFoundById() { Treasure treasure = DefaultTreasure().WithName("Chest"); this.fixture.Insert(treasure); var foundTreasure = this.repository.GetById(treasure.Id)!; foundTreasure.Should().NotBeNull(); foundTreasure.Name.Should().Be(treasure.Name); } [Fact] public void GetById_ShouldReturnNull_WhenDoesNotFoundById() { var foundTreasure = this.repository.GetById(999); foundTreasure.Should().BeNull(); } [Fact] public void GetByName_ShouldReturnATreasure_WhenFoundById() { Treasure treasure = DefaultTreasure().WithName("Ore"); this.fixture.Insert(treasure); var foundTreasure = this.repository.GetByName("Ore")!; foundTreasure.Should().NotBeNull(); foundTreasure.Name.Should().Be(treasure.Name); } [Fact] public void GetByName_ShouldReturnNull_WhenDoesNotFoundByName() { var foundTreasure = this.repository.GetByName("Unknown"); foundTreasure.Should().BeNull(); } [Fact] public void FindAll_ShouldReturnAllTreasuresWhichContainsTheName() { Treasure treasure = DefaultTreasure() .WithName("Chest"); this.fixture.Insert(treasure); var treasures = this.repository.FindAll(new QueryTreasure("Chest", string.Empty, string.Empty)); treasures.Should().HaveCount(1); treasures.Should().OnlyContain(t => t.Name == treasure.Name); } [Fact] public void FindAll_ShouldReturnAllTreasures_WhenSearchingByAnEmptyName() { this.fixture.InsertRange(new Treasure[] { DefaultTreasure().WithName("Chest"), DefaultTreasure().WithName("Ore") }); var treasures = this.repository.FindAll(new QueryTreasure(string.Empty, string.Empty, string.Empty)); treasures.Should().HaveCount(2); } [Fact] public void FindAll_ShouldReturnAllTreasuresWhichContainsTheDrop() { Treasure treasure = DefaultTreasure() .WithName("Chest") .WithDrops(new[] { "Rupee" }); this.fixture.Insert(treasure); var treasures = this.repository.FindAll(new QueryTreasure(string.Empty, "Upe", string.Empty)); treasures.Should().HaveCount(1); treasures.Should().OnlyContain(t => t.Name == treasure.Name); } [Fact] public void FindAll_ShouldReturnAllTreasures_WhenSearchingByAnEmptyDrop() { this.fixture.InsertRange(new Treasure[] { DefaultTreasure().WithDrops(new[] { "Rupee" }), DefaultTreasure().WithDrops(new[] { "Ore" }) }); var treasures = this.repository.FindAll(new QueryTreasure(string.Empty, string.Empty, string.Empty)); treasures.Should().HaveCount(2); } [Fact] public void FindAll_ShouldReturnAllTreasuresWhichContainsTheLocation() { Treasure treasure = DefaultTreasure() .WithName("Chest") .WithLocations(new[] { "Hyrule" }); this.fixture.Insert(treasure); var treasures = this.repository.FindAll(new QueryTreasure(string.Empty, string.Empty, "Yru")); treasures.Should().HaveCount(1); treasures.Should().OnlyContain(t => t.Name == treasure.Name); } [Fact] public void FindAll_ShouldReturnAllTreasures_WhenSearchingByAnEmptyLocation() { this.fixture.InsertRange(new Treasure[] { DefaultTreasure().WithLocations(new[] { "Hyrule" }), DefaultTreasure().WithLocations(new[] { "Kakariko" }) }); var treasures = this.repository.FindAll(new QueryTreasure(string.Empty, string.Empty, string.Empty)); treasures.Should().HaveCount(2); } } }
32.272727
113
0.60338
[ "MIT" ]
abeauchamp96/Compendium
Compendium.Database.Tests/Repositories/TreasureRepositoryTests.cs
5,327
C#
using System; using UnityEngine.Rendering; using UnityEngine.Serialization; namespace UnityEngine.XR.ARFoundation { /// <summary> /// Add this component to a <c>Camera</c> to copy the color camera's texture onto the background. /// </summary> /// <remarks> /// This is the component-ized version of <c>UnityEngine.XR.ARBackgroundRenderer</c>. /// </remarks> [DisallowMultipleComponent] [RequireComponent(typeof(Camera))] [RequireComponent(typeof(ARCameraManager))] [HelpURL("https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@1.5/api/UnityEngine.XR.ARFoundation.ARCameraBackground.html")] public sealed class ARCameraBackground : MonoBehaviour { [SerializeField, FormerlySerializedAs("m_OverrideMaterial")] bool m_UseCustomMaterial; /// <summary> /// When <c>false</c>, a material is generated automatically from the shader included in the platform-specific package. /// When <c>true</c>, <see cref="customMaterial"/> is used instead, overriding the automatically generated one. /// This is not necessary for most AR experiences. /// </summary> public bool useCustomMaterial { get { return m_UseCustomMaterial; } set { m_UseCustomMaterial = value; UpdateMaterial(); } } [SerializeField, FormerlySerializedAs("m_Material")] Material m_CustomMaterial; /// <summary> /// If <see cref="useCustomMaterial"/> is <c>true</c>, this <c>Material</c> will be used /// instead of the one included with the platform-specific AR package. /// </summary> public Material customMaterial { get { return m_CustomMaterial; } set { m_CustomMaterial = value; UpdateMaterial(); } } /// <summary> /// The current <c>Material</c> used for background rendering. /// </summary> public Material material { get { return m_BackgroundRenderer.backgroundMaterial; } private set { m_BackgroundRenderer.backgroundMaterial = value; } } [SerializeField] bool m_UseCustomRendererAsset; /// <summary> /// Whether to use a <see cref="ARBackgroundRendererAsset"/>. This can assist with /// usage of the light weight render pipeline. /// </summary> public bool useCustomRendererAsset { get { return m_UseCustomRendererAsset; } set { m_UseCustomRendererAsset = value; SetupBackgroundRenderer(); } } [SerializeField] ARBackgroundRendererAsset m_CustomRendererAsset; /// <summary> /// Get the custom <see cref="ARBackgroundRendererAsset "/> to use. This can /// assist with usage of the light weight render pipeline. /// </summary> public ARBackgroundRendererAsset customRendererAsset { get { return m_CustomRendererAsset; } set { m_CustomRendererAsset = value; SetupBackgroundRenderer(); } } ARFoundationBackgroundRenderer m_BackgroundRenderer { get; set; } Material CreateMaterialFromSubsystemShader() { if (m_CameraSetupThrewException) return null; // Try to create a material from the plugin's provided shader. if (String.IsNullOrEmpty(m_CameraManager.shaderName)) return null; var shader = Shader.Find(m_CameraManager.shaderName); if (shader == null) { // If an exception is thrown, then something is irrecoverably wrong. // Set this flag so we don't try to do this every frame. m_CameraSetupThrewException = true; throw new InvalidOperationException(string.Format( "Could not find shader named \"{0}\" required for video overlay on camera subsystem.", m_CameraManager.shaderName)); } return new Material(shader); } void OnCameraFrameReceived(ARCameraFrameEventArgs eventArgs) { UpdateMaterial(); var mat = material; var count = eventArgs.textures.Count; for (int i = 0; i < count; ++i) { mat.SetTexture( eventArgs.propertyNameIds[i], eventArgs.textures[i]); } mode = ARRenderMode.MaterialAsBackground; if (eventArgs.displayMatrix.HasValue) mat.SetMatrix(k_DisplayTransformId, eventArgs.displayMatrix.Value); if (eventArgs.projectionMatrix.HasValue) m_Camera.projectionMatrix = eventArgs.projectionMatrix.Value; } void SetupBackgroundRenderer() { if (useRenderPipeline) { if (m_LwrpBackgroundRenderer == null) { m_LwrpBackgroundRenderer = m_CustomRendererAsset.CreateARBackgroundRenderer(); m_CustomRendererAsset.CreateHelperComponents(gameObject); } m_BackgroundRenderer = m_LwrpBackgroundRenderer; } else { if (m_LegacyBackgroundRenderer == null) m_LegacyBackgroundRenderer = new ARFoundationBackgroundRenderer(); m_BackgroundRenderer = m_LegacyBackgroundRenderer; } m_BackgroundRenderer.mode = mode; m_BackgroundRenderer.camera = m_Camera; } void Awake() { m_Camera = GetComponent<Camera>(); m_CameraManager = GetComponent<ARCameraManager>(); SetupBackgroundRenderer(); } void OnEnable() { UpdateMaterial(); m_CameraManager.frameReceived += OnCameraFrameReceived; ARSession.stateChanged += OnSessionStateChanged; } void OnDisable() { mode = ARRenderMode.StandardBackground; m_CameraManager.frameReceived -= OnCameraFrameReceived; ARSession.stateChanged -= OnSessionStateChanged; m_CameraSetupThrewException = false; // We are no longer setting the projection matrix // so tell the camera to resume its normal projection // matrix calculations. m_Camera.ResetProjectionMatrix(); } void OnSessionStateChanged(ARSessionStateChangedEventArgs eventArgs) { // If the session goes away then return to using standard background mode if (eventArgs.state < ARSessionState.SessionInitializing && m_BackgroundRenderer != null) mode = ARRenderMode.StandardBackground; } void UpdateMaterial() { if (useRenderPipeline) { material = lwrpMaterial; } else { material = m_UseCustomMaterial ? m_CustomMaterial : subsystemMaterial; } } bool m_CameraSetupThrewException; Camera m_Camera; ARCameraManager m_CameraManager; Material m_SubsystemMaterial; private Material subsystemMaterial { get { if (m_SubsystemMaterial == null) m_SubsystemMaterial = CreateMaterialFromSubsystemShader(); return m_SubsystemMaterial; } } Material m_LwrpMaterial; Material lwrpMaterial { get { if (m_LwrpMaterial != null) return m_LwrpMaterial; if (m_UseCustomRendererAsset && m_CustomRendererAsset != null) { m_LwrpMaterial = m_CustomRendererAsset.CreateCustomMaterial(); } return m_LwrpMaterial; } } ARFoundationBackgroundRenderer m_LegacyBackgroundRenderer; ARFoundationBackgroundRenderer m_LwrpBackgroundRenderer; ARRenderMode m_Mode; ARRenderMode mode { get { return m_Mode; } set { m_Mode = value; if (m_LwrpBackgroundRenderer != null) m_LwrpBackgroundRenderer.mode = m_Mode; if (m_LegacyBackgroundRenderer != null) m_LegacyBackgroundRenderer.mode = m_Mode; } } bool useRenderPipeline { get { return m_UseCustomRendererAsset && (m_CustomRendererAsset != null) && (GraphicsSettings.renderPipelineAsset != null); } } const string k_DisplayTransformName = "_UnityDisplayTransform"; static readonly int k_DisplayTransformId = Shader.PropertyToID(k_DisplayTransformName); } }
31.860068
136
0.562828
[ "Apache-2.0" ]
CalibanDJ/MR_Project
ARPackages/com.unity.xr.arfoundation/Runtime/AR/ARCameraBackground.cs
9,337
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("XPlat.Samples.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XPlat.Samples.Android")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
34.806452
84
0.742354
[ "MIT" ]
wilsonvargas/XPlat-Windows-APIs
XPlat.Samples.Android/Properties/AssemblyInfo.cs
1,082
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using ReactiveUI; using Avalonia.ReactiveUI; using Bellow.Client.ViewModels; namespace Bellow.Client.Views { public class WelcomeView : ReactiveUserControl<WelcomeViewModel> { public WelcomeView() { InitializeComponent(); } private void InitializeComponent() { this.WhenActivated(disposables => { /* Handle view activation etc. */ }); AvaloniaXamlLoader.Load(this); } } }
21.6
85
0.644444
[ "MIT" ]
MikeCodesDotNET/Avalonia-Chat-Demo
Bellow/Bellow/Views/WelcomeView.axaml.cs
540
C#
using FlowScriptEngine; namespace FlowScriptEngineBasic.FlowSourceObjects.Array { [ToolTipText("Array_SortWithItem_Summary")] public partial class SortWithItemsFlowSourceObject : ArrayFlowSourceObjectBase { [ToolTipText("Array_Sort_Compare")] public event FlowEventHandler Compare; public override string Name { get { return "Array.Sort"; } } [ToolTipText("Array_SortWithItem_Items")] public object[] Items { private get; set; } [ToolTipText("Array_Sort_X")] public object X { get; private set; } [ToolTipText("Array_Sort_Y")] public object Y { get; private set; } [ToolTipText("Array_Sort_Result")] public int Result { private get; set; } public override void In(FlowScriptEngine.FlowEventArgs e) { SetArray(); if (Array != null) { SetValue(nameof(Items)); var comparer = new CallbackComparer((x, y) => { X = x; Y = y; FireEvent(Compare, true); ProcessChildEvent(); SetValue(nameof(Result)); return Result; }); System.Array.Sort(Array, Items, comparer); OnSuccess(); } else { OnFailed(); } } } }
24.058824
82
0.460269
[ "Apache-2.0" ]
KHCmaster/PPD
Win/FlowScriptEngineBasic/FlowSourceObjects/Array/SortWithItemsFlowSourceObject.cs
1,638
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 connect-2017-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Connect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Connect.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for HistoricalMetric Object /// </summary> public class HistoricalMetricUnmarshaller : IUnmarshaller<HistoricalMetric, XmlUnmarshallerContext>, IUnmarshaller<HistoricalMetric, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> HistoricalMetric IUnmarshaller<HistoricalMetric, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public HistoricalMetric Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; HistoricalMetric unmarshalledObject = new HistoricalMetric(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Statistic", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Statistic = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Threshold", targetDepth)) { var unmarshaller = ThresholdUnmarshaller.Instance; unmarshalledObject.Threshold = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Unit", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Unit = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static HistoricalMetricUnmarshaller _instance = new HistoricalMetricUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static HistoricalMetricUnmarshaller Instance { get { return _instance; } } } }
35.863636
161
0.612167
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Connect/Generated/Model/Internal/MarshallTransformations/HistoricalMetricUnmarshaller.cs
3,945
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GenericRepository.Models { public class User { public int Id { get; set; } public string Name { get; set; } } }
17.785714
40
0.666667
[ "MIT" ]
olkerr/YMS8518
GenericRepository/GenericRepository/Models/User.cs
251
C#
using LoggingCore; using LoggingCore.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DotNetCore_HandsOn3 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => options.Filters.Add(new HandleException())); //services.AddControllersWithViews(); services.AddSingleton<ILoggerManager, LoggerManager>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddLog4Net(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
33.095238
143
0.628777
[ "MIT" ]
sounakofficial/ADMDF
DotNetCore_HandsOn3/LoggingCore/Startup.cs
2,085
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("CubbicMesseges")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CubbicMesseges")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f984bf9e-73cb-4f1f-9956-35769a8d2a6d")] // 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")]
37.864865
84
0.745896
[ "MIT" ]
stoyantodorovbg/Programming-Fundamentals
ExamPreparation4/CubbicMesseges/Properties/AssemblyInfo.cs
1,404
C#
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace TagDetector { /// <summary> /// Summary description for Form2. /// </summary> public class Form2 : System.Windows.Forms.Form { private System.Windows.Forms.Button OpenPortButton; private System.Windows.Forms.TextBox ComPortTextBox; private System.Windows.Forms.Label label1; private Form1 m_form = new Form1(true); private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.Button CloseButton; private System.Windows.Forms.Label MsgLabel; private uint port = 0; public Form2() { InitializeComponent(); } public Form2(Form1 mForm) { InitializeComponent(); m_form = mForm; //ComPortTextBox.Text = mForm.port.ToString(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.OpenPortButton = new System.Windows.Forms.Button(); this.ComPortTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.CloseButton = new System.Windows.Forms.Button(); this.MsgLabel = new System.Windows.Forms.Label(); // // OpenPortButton // this.OpenPortButton.Location = new System.Drawing.Point(34, 66); this.OpenPortButton.Size = new System.Drawing.Size(108, 30); this.OpenPortButton.Text = "Open Port"; this.OpenPortButton.Click += new System.EventHandler(this.OpenPortButton_Click); // // ComPortTextBox // this.ComPortTextBox.Font = new System.Drawing.Font("Tahoma", 11.25F, System.Drawing.FontStyle.Regular); this.ComPortTextBox.Location = new System.Drawing.Point(106, 32); this.ComPortTextBox.Size = new System.Drawing.Size(34, 26); this.ComPortTextBox.Text = "4"; this.ComPortTextBox.GotFocus += new System.EventHandler(this.ComPortTextBox_GotFocus); // // label1 // this.label1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular); this.label1.Location = new System.Drawing.Point(30, 36); this.label1.Size = new System.Drawing.Size(74, 20); this.label1.Text = "Com. Port: "; this.label1.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // CloseButton // this.CloseButton.Location = new System.Drawing.Point(34, 100); this.CloseButton.Size = new System.Drawing.Size(108, 30); this.CloseButton.Text = "Close"; this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click); // // MsgLabel // this.MsgLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold); this.MsgLabel.ForeColor = System.Drawing.Color.Green; this.MsgLabel.Location = new System.Drawing.Point(8, 140); this.MsgLabel.Size = new System.Drawing.Size(158, 20); this.MsgLabel.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // Form2 // this.ClientSize = new System.Drawing.Size(172, 171); this.ControlBox = false; this.Controls.Add(this.MsgLabel); this.Controls.Add(this.CloseButton); this.Controls.Add(this.label1); this.Controls.Add(this.ComPortTextBox); this.Controls.Add(this.OpenPortButton); this.Location = new System.Drawing.Point(35, 45); this.MaximizeBox = false; this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Com. Port"; this.Load += new System.EventHandler(this.Form2_Load); } #endregion private void Form2_Load(object sender, System.EventArgs e) { ComPortTextBox.Text = m_form.GetPort().ToString(); port = m_form.GetPort(); } private void OpenPortButton_Click(object sender, System.EventArgs e) { int ret = 0; m_form.RSSIProgressBar.Value = 0; m_form.RSSITextBox.Text = ""; if (m_form.IsPortOpen()) { ret = m_form.api.rfClose(); if (ret < 0) { m_form.SetPort(false, port); m_form.DisplayMsg("Close failed ret=" + ret); return; } else m_form.DisplayMsg("Port Closed OK. ret=" + ret); } port = Convert.ToUInt32(ComPortTextBox.Text); ret = m_form.api.rfOpen(115200 , port); if (ret >= 0) { m_form.SetPort(true, port); m_form.WriteComPortNum(Convert.ToString(port)); m_form.DisplayMsg("Open port OK. ret=" + ret); m_form.PlaySound(1); m_form.ResetReader(0); MsgLabel.ForeColor = System.Drawing.Color.Green; MsgLabel.Text = "Port Opened Successfully"; } else { m_form.DisplayMsg("Open failed ret=" + ret); m_form.SetPort(false, port); m_form.PlaySound(1); MsgLabel.ForeColor = System.Drawing.Color.Red; MsgLabel.Text = "Open Port Failed"; } } private void ComPortTextBox_GotFocus(object sender, System.EventArgs e) { //inputPanel1.Enabled = true; } private void CloseButton_Click(object sender, System.EventArgs e) { Close(); } } }
30.32948
106
0.689156
[ "Apache-2.0" ]
konklone/tigerfid
api/c-sharp-dot-net-ce/example/Form2.cs
5,247
C#
#nullable enable using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using NotNullAttribute = Omnifactotum.Annotations.NotNullAttribute; //// ReSharper disable once CheckNamespace :: Namespace is intentionally named so in order to simplify usage of extension methods namespace System.Collections.Generic { /// <summary> /// Contains extension methods for the <see cref="IEqualityComparer{T}"/> interface. /// </summary> [SuppressMessage("ReSharper", "RedundantNullnessAttributeWithNullableReferenceTypes", Justification = "Multiple target frameworks.")] public static class OmnifactotumEqualityComparerExtensions { /// <summary> /// Gets a hash code of the specified value safely, that is, a <see langword="null"/> value does not cause an exception. /// </summary> /// <typeparam name="T"> /// The type of the value to get a hash code of. /// </typeparam> /// <param name="equalityComparer"> /// The equality comparer to use for getting a hash code of the value. /// </param> /// <param name="value"> /// The value to get a hash code of. Can be <see langword="null"/>. /// </param> /// <param name="nullValueHashCode"> /// The value to return if the <paramref name="value"/> parameter is <see langword="null"/>. /// </param> /// <returns> /// A hash code of the specified value obtained by calling <see cref="IEqualityComparer{T}.GetHashCode(T)"/> for this value /// if it is not <see langword="null"/>; otherwise, the value specified by the <paramref name="nullValueHashCode"/> /// parameter. /// </returns> [MethodImpl( MethodImplOptions.AggressiveInlining #if NET5_0_OR_GREATER | MethodImplOptions.AggressiveOptimization #endif )] public static int GetHashCodeSafely<T>([NotNull] this IEqualityComparer<T> equalityComparer, T value, int nullValueHashCode = 0) => equalityComparer is null ? throw new ArgumentNullException(nameof(equalityComparer)) : value is null ? nullValueHashCode : equalityComparer.GetHashCode(value); } }
47.22449
137
0.636128
[ "MIT" ]
HarinezumiSama/omnifactotum
src/Omnifactotum/ExtensionMethods/OmnifactotumEqualityComparerExtensions.cs
2,316
C#
using System; using System.Collections.Generic; namespace PersonPhoneExample.Models { public partial class Person { public Person() { Phone = new HashSet<Phone>(); } public long Id { get; set; } public string Name { get; set; } public short? Age { get; set; } public virtual ICollection<Phone> Phone { get; set; } } }
21.105263
61
0.571072
[ "MIT" ]
akitiainen/Database
PersonPhoneExample/PersonPhoneExample/Models/Person.cs
403
C#
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using AutoMapper; using CarsManager.Application.Common.Models; using CarsManager.Application.Vehicles.Commands.CreateVehicle; using CarsManager.Application.Vehicles.Commands.DeleteVehicle; using CarsManager.Application.Vehicles.Commands.UpdateBlockedStatus; using CarsManager.Application.Vehicles.Commands.UpdateMileage; using CarsManager.Application.Vehicles.Commands.UpdateVehicle; using CarsManager.Application.Vehicles.Queries.GetAllBasicVehicles; using CarsManager.Application.Vehicles.Queries.GetVehicle; using CarsManager.Application.Vehicles.Queries.GetVehicleExtended; using CarsManager.Application.Vehicles.Queries.GetVehiclesQuery; using CarsManager.Application.Vehicles.Queries.GetVehiclesSummary; using CarsManager.Application.Vehicles.Queries.GetVehiclesWithPagination; using CarsManager.Server.Utils; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Server; namespace CarsManager.Server.Controllers { public class VehiclesController : ApiControllerBase { private readonly IMapper mapper; private string imagesPath => Path.Combine(Startup.wwwRootFolder, Constants.IMAGES_FOLDER); public VehiclesController(IMapper mapper) { this.mapper = mapper; } [HttpGet] public async Task<ActionResult<VehiclesVm>> GetVehicles() => await Mediator.Send(new GetVehiclesQuery { Path = HttpContext.Request.GetAbsoluteUri(Constants.IMAGES_FOLDER) }); [HttpGet("pages")] public async Task<ActionResult<PaginatedList<ListedVehicleDto>>> GetVehiclesWithPagination([FromQuery] GetVehiclesWithPaginationQuery query) => await Mediator.Send(query); [HttpGet("basic")] public async Task<IList<ListedVehicleDto>> GetAllBasicVehicles() => await Mediator.Send(new GetAllBasicVehiclesQuery()); [HttpGet("{id}")] public async Task<ActionResult<VehicleVm>> Get(int id) => await Mediator.Send(new GetVehicleQuery { Id = id, Path = HttpContext.Request.GetAbsoluteUri(Constants.IMAGES_FOLDER) }); [HttpGet("{id}/extended")] public async Task<ActionResult<VehicleExtendedVm>> GetExtended(int id) => await Mediator.Send(new GetVehicleExtendedQuery { Id = id, PhotoPath = HttpContext.Request.GetAbsoluteUri(Constants.IMAGES_FOLDER) }); [HttpGet("summary")] public async Task<ActionResult<VehiclesSummaryDto>> GetSummary() => await Mediator.Send(new GetVehiclesSummaryQuery()); [HttpPost] public async Task<ActionResult<int>> Create(CreateVehicleDto dto) { var command = mapper.Map<CreateVehicleCommand>(dto); return await Mediator.Send(command); } [HttpPut("{id}")] public async Task<ActionResult> Update(int id, UpdateVehicleCommand command) { if (id != command.Id) return BadRequest(); await Mediator.Send(command); return NoContent(); } [HttpPatch("{id}")] public async Task<ActionResult>UpdateMileage(int id, UpdateMileageCommand command) { if (id != command.VehicleId) return BadRequest(); await Mediator.Send(command); return NoContent(); } [HttpPost("{id}/blocked")] public async Task<ActionResult> UpdateBlockedStatus(int id, UpdateBlockedStatusCommand command) { if (id != command.Id) return BadRequest(); await Mediator.Send(command); return NoContent(); } [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { await Mediator.Send(new DeleteVehicleCommand { Id = id, ImagePath = imagesPath }); return NoContent(); } } }
36.592593
149
0.68497
[ "MIT" ]
pkanev/CarsManager
src/Server/Controllers/VehiclesController.cs
3,954
C#
using System; namespace CosmosDB.Gremlin.Fluent.Functions { #pragma warning disable 1591 public static class EqFunction #pragma warning restore 1591 { /// <summary> /// Predicate testing that the incoming object is equal to the provided object /// </summary> /// <param name="builder"></param> /// <param name="parameter"></param> /// <returns></returns> public static GremlinQueryBuilder Eq(this GremlinQueryBuilder builder, IGremlinParameter parameter) { if (parameter == null) throw new ArgumentNullException(nameof(parameter)); builder.AddArgument(parameter as GremlinArgument); return builder.Add($"eq({parameter.QueryStringValue})"); } /// <summary> /// Predicate testing that the incoming object is equal to the provided object /// </summary> /// <param name="builder"></param> /// <param name="parameter"></param> /// <returns></returns> public static GremlinQueryBuilder Eq(this GremlinQueryBuilder builder, GremlinParameter parameter) { // for implicit conversion operators return builder.Eq((IGremlinParameter)parameter); } } }
35.916667
107
0.610209
[ "Apache-2.0" ]
AieatAssam/CosmosDB.Gremlin.Fluent
CosmosDB.Gremlin.Fluent/Functions/Eq.cs
1,293
C#
#region Copyright & License // Copyright © 2012 - 2020 François Chabot // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics.CodeAnalysis; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; namespace Be.Stateless.BizTalk.Unit.ServiceModel { public class SoapClient<TChannel> : ClientBase<TChannel> where TChannel : class { #region Operators [SuppressMessage("Usage", "CA2225:Operator overloads have named alternates")] public static implicit operator TChannel(SoapClient<TChannel> client) { return client?.Channel; } #endregion [SuppressMessage("Design", "CA1000:Do not declare static members on generic types")] public static TChannel For(ServiceEndpoint serviceEndpoint) { if (serviceEndpoint == null) throw new ArgumentNullException(nameof(serviceEndpoint)); return new SoapClient<TChannel>(serviceEndpoint.Binding, serviceEndpoint.Address); } private SoapClient(Binding binding, EndpointAddress address) : base(binding, address) { } } }
31.8
91
0.76478
[ "Apache-2.0" ]
emmanuelbenitez/Be.Stateless.BizTalk.ServiceModel
src/Be.Stateless.BizTalk.ServiceModel.Unit/Unit/ServiceModel/SoapClientOfT.cs
1,594
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace Aliyun.SDK.PDS.Client.Models { /** * */ public class ListSubdomainsResponse : TeaModel { /// <summary> /// 分页的 subdomain 数据 /// </summary> [NameInMap("items")] [Validation(Required=true)] public List<BaseSubdomainResponse> Items { get; set; } /// <summary> /// 分页游标,可以用作下次list的起点 /// </summary> [NameInMap("next_marker")] [Validation(Required=true)] public string NextMarker { get; set; } } }
20.59375
62
0.578149
[ "Apache-2.0" ]
18730298725/alibabacloud-pds-sdk
pds/csharp/core/Models/ListSubdomainsResponse.cs
697
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _30_05_2021_Database_Coursework { public class GlobalInformation_Access_Syncronized { MainFrame OriginFrame; public GlobalInformation_Access_Syncronized(MainFrame OriginFrame) { this.OriginFrame = OriginFrame; } public bool AddData(GlobalInformation info) { if (OriginFrame.GlobalInformation.Add(info)) { var GlobalTable = OriginFrame.FrameTables.TabPages[0].Controls.OfType<DataGridView>().First(); int rowNumber = GlobalTable.Rows.Add(); GlobalTable.Rows[rowNumber].Cells["Login"].Value = info.Login; GlobalTable.Rows[rowNumber].Cells["Age"].Value = info.Age; GlobalTable.Rows[rowNumber].Cells["PassedLevels"].Value = info.PassedLevels; GlobalTable.Rows[rowNumber].Cells["GameName"].Value = info.GameName; GlobalTable.Rows[rowNumber].Cells["Developer"].Value = info.Developer; GlobalTable.Rows[rowNumber].Cells["Contacts"].Value = info.Contacts; GlobalTable.Rows[rowNumber].Cells["FirstTimePlayed"].Value = info.FirstTimePlayed; GlobalTable.Rows[rowNumber].Cells["LastTimePlayed"].Value = info.LastTimePlayed; OriginFrame.GlobalInformationTree.NewElem(OriginFrame.GlobalInformation.FindElemInfo(info)); return true; } else { OriginFrame.ThrowError("Элемент уже находится в справочнике!"); } return false; } public bool RemoveData(GlobalInformation info) { DataGridView GlobalTable; if ( OriginFrame.GlobalInformationTree.DeleteElem(info) && OriginFrame.GlobalInformation.Remove(info) ) { GlobalTable = OriginFrame.FrameTables.TabPages[0].Controls.OfType<DataGridView>().First(); for (int rowNumber = 0; rowNumber < GlobalTable.Rows.Count; rowNumber++) { if ((string)GlobalTable.Rows[rowNumber].Cells["Login"].Value == info.Login && (int)GlobalTable.Rows[rowNumber].Cells["Age"].Value == info.Age && (int)GlobalTable.Rows[rowNumber].Cells["PassedLevels"].Value == info.PassedLevels && (string)GlobalTable.Rows[rowNumber].Cells["GameName"].Value == info.GameName && (string)GlobalTable.Rows[rowNumber].Cells["Developer"].Value == info.Developer && (string)GlobalTable.Rows[rowNumber].Cells["Contacts"].Value == info.Contacts && (string)GlobalTable.Rows[rowNumber].Cells["FirstTimePlayed"].Value == info.FirstTimePlayed && (string)GlobalTable.Rows[rowNumber].Cells["LastTimePlayed"].Value == info.LastTimePlayed) { GlobalTable.Rows.Remove(GlobalTable.Rows[rowNumber]); } } return true; } return false; } public void Clear() { var GlobalTable = OriginFrame.FrameTables.TabPages[0].Controls.OfType<DataGridView>().First(); while (GlobalTable.Rows.Count != 0) { GlobalTable.Rows.Remove(GlobalTable.Rows[0]); } OriginFrame.GlobalInformation.Clear(); OriginFrame.GlobalInformationTree.ClearTree(); } } }
42.488636
113
0.596684
[ "MIT" ]
StalkerRaftik/Database_Coursework
GlobalTable/GlobalInformation_Access_Syncronized.cs
3,772
C#
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Npoi.Mapper.Attributes; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace Npoi.Mapper { public enum StyleSources { Type, ExistingStyle } /// <summary> /// Map object properties with Excel columns for importing from and exporting to file. /// </summary> public class Mapper { #region Fields // Current working workbook. private IWorkbook _workbook; private Func<IColumnInfo, bool> _columnFilter; private Func<IColumnInfo, object, bool> _defaultTakeResolver; private Func<IColumnInfo, object, bool> _defaultPutResolver; private Action<ICell> _headerAction; #endregion #region Properties // Instance of helper class. private MapHelper Helper = new MapHelper(); // Stores formats for type rather than specific property. internal readonly Dictionary<Type, string> TypeFormats = new Dictionary<Type, string>(); // PropertyInfo map to ColumnAttribute private Dictionary<PropertyInfo, ColumnAttribute> Attributes { get; } = new Dictionary<PropertyInfo, ColumnAttribute>(); // Property name map to ColumnAttribute private Dictionary<string, ColumnAttribute> DynamicAttributes { get; } = new Dictionary<string, ColumnAttribute>(); /// <summary> /// Cache the tracked <see cref="ColumnInfo"/> objects by sheet name and target type. /// </summary> private Dictionary<string, Dictionary<Type, List<object>>> TrackedColumns { get; } = new Dictionary<string, Dictionary<Type, List<object>>>(); /// <summary> /// Sheet name map to tracked objects in dictionary with row number as key. /// </summary> public Dictionary<string, Dictionary<int, object>> Objects { get; } = new Dictionary<string, Dictionary<int, object>>(); /// <summary> /// The Excel workbook. /// </summary> public IWorkbook Workbook { get { return _workbook; } private set { if (value != _workbook) { Objects.Clear(); TrackedColumns.Clear(); Helper.ClearCache(); } _workbook = value; } } /// <summary> /// When map column, chars in this array will be removed from column header. /// </summary> public char[] IgnoredNameChars { get; set; } /// <summary> /// When map column, column name will be truncated from any of chars in this array. /// </summary> public char[] TruncateNameFrom { get; set; } /// <summary> /// Whether to track objects read from the Excel file. Default is true. /// If object tracking is enabled, the <see cref="Mapper"/> object keeps track of objects it yields through the Take() methods. /// You can then modify these objects and save them back to an Excel file without having to specify the list of objects to save. /// </summary> public bool TrackObjects { get; set; } = true; /// <summary> /// Whether to take the first row as column header. Default is true. /// </summary> public bool HasHeader { get; set; } = true; /// <summary> /// Gets or sets a zero-based index for the first row. It will be auto-detected if not set. /// If <see cref="HasHeader"/> is true (by default), this represents the header row index. /// </summary> public int FirstRowIndex { get; set; } = -1; /// <summary> /// Whether to apply (new) default styles or existing styles. Default is true. /// </summary> public StyleSources DefaultStyleSource { get; set; } = StyleSources.Type; #endregion #region Constructors /// <summary> /// Initialize a new instance of <see cref="Mapper"/> class. /// </summary> public Mapper() { } /// <summary> /// Initialize a new instance of <see cref="Mapper"/> class with stream to read workbook. /// </summary> /// <param name="stream">The input Excel(XLS, XLSX) file stream</param> public Mapper(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); using (stream) { Workbook = WorkbookFactory.Create(stream); } } /// <summary> /// Initialize a new instance of <see cref="Mapper"/> class with a workbook. /// </summary> /// <param name="workbook">The input IWorkbook object.</param> public Mapper(IWorkbook workbook) { if (workbook == null) throw new ArgumentNullException(nameof(workbook)); Workbook = workbook; } /// <summary> /// Initialize a new instance of <see cref="Mapper"/> class with file path to read workbook. /// </summary> /// <param name="filePath">The path of Excel file.</param> public Mapper(string filePath) : this(new FileStream(filePath, FileMode.Open)) { } #endregion #region Public Methods /// <summary> /// Use this to include and map columns for custom complex resolution. /// </summary> /// <param name="columnFilter">The function to determine whether or not to resolve an unmapped column.</param> /// <param name="tryTake">The function try to import from cell value to the target object.</param> /// <param name="tryPut">The function try to export source object to the cell.</param> /// <returns>The mapper object.</returns> public Mapper Map(Func<IColumnInfo, bool> columnFilter, Func<IColumnInfo, object, bool> tryTake = null, Func<IColumnInfo, object, bool> tryPut = null) { _columnFilter = columnFilter; _defaultPutResolver = tryPut; _defaultTakeResolver = tryTake; return this; } /// <summary> /// Map by a <see cref="ColumnAttribute"/> object. /// </summary> /// <param name="attribute">The <see cref="ColumnAttribute"/> object.</param> /// <returns>The mapper object.</returns> public Mapper Map(ColumnAttribute attribute) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); if (attribute.Property != null) { attribute.MergeTo(Attributes); } else if (attribute.PropertyName != null) { if (DynamicAttributes.ContainsKey(attribute.PropertyName)) { DynamicAttributes[attribute.PropertyName].MergeFrom(attribute); } else { // Ensures column name for the first time mapping. if (attribute.Name == null) { attribute.Name = attribute.PropertyName; } DynamicAttributes[attribute.PropertyName] = attribute; } } else { throw new InvalidOperationException("Either PropertyName or Property should be specified for a valid mapping!"); } return this; } /// <summary> /// Specify to use last non-blank value from above cell for a property. /// Typically to address the blank cell issue in merged cells. /// </summary> /// <typeparam name="T">The target object type.</typeparam> /// <param name="propertySelector">Property selector.</param> /// <returns>The mapper object.</returns> public Mapper UseLastNonBlankValue<T>(Expression<Func<T, object>> propertySelector) { var pi = MapHelper.GetPropertyInfoByExpression(propertySelector); if (pi == null) return this; new ColumnAttribute { Property = pi, UseLastNonBlankValue = true }.MergeTo(Attributes); return this; } /// <summary> /// Specify to ignore a property. Ignored property will not be mapped for import and export. /// </summary> /// <typeparam name="T">The target object type.</typeparam> /// <param name="propertySelector">Property selector.</param> /// <returns>The mapper object.</returns> public Mapper Ignore<T>(Expression<Func<T, object>> propertySelector) { var pi = MapHelper.GetPropertyInfoByExpression(propertySelector); if (pi == null) return this; new ColumnAttribute { Property = pi, Ignored = true }.MergeTo(Attributes); return this; } /* * Removed this method in v3 since this is rarely used but just increased internal complexity. * /// <summary> /// Specify the built-in format. /// </summary> /// <typeparam name="T">The target object type.</typeparam> /// <param name="builtinFormat">The built-in format, see https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html for possible values.</param> /// <param name="propertySelector">Property selector.</param> /// <returns>The mapper object.</returns> [Obsolete("Builtin format will not be supported in next major release!")] public Mapper Format<T>(short builtinFormat, Expression<Func<T, object>> propertySelector) { var pi = MapHelper.GetPropertyInfoByExpression(propertySelector); if (pi == null) return this; new ColumnAttribute { Property = pi, BuiltinFormat = builtinFormat }.MergeTo(Attributes); return this; } */ /// <summary> /// Specify the custom format. /// </summary> /// <typeparam name="T">The target object type.</typeparam> /// <param name="customFormat">The custom format, see https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 for the syntax.</param> /// <param name="propertySelector">Property selector.</param> /// <returns>The mapper object.</returns> public Mapper Format<T>(string customFormat, Expression<Func<T, object>> propertySelector) { var pi = MapHelper.GetPropertyInfoByExpression(propertySelector); if (pi == null) return this; new ColumnAttribute { Property = pi, CustomFormat = customFormat }.MergeTo(Attributes); return this; } /// <summary> /// Sets an action to configure header cells for export. /// </summary> /// <param name="headerAction">Action to configure header cell.</param> /// <returns>The mapper object.</returns> public Mapper ForHeader(Action<ICell> headerAction) { _headerAction = headerAction; return this; } /// <summary> /// Get objects of target type by converting rows in the sheet with specified index (zero based). /// </summary> /// <typeparam name="T">Target object type</typeparam> /// <param name="sheetIndex">The sheet index; default is 0.</param> /// <param name="maxErrorRows">The maximum error rows before stop reading; default is 10.</param> /// <param name="objectInitializer">Factory method to create a new target object.</param> /// <returns>Objects of target type</returns> public IEnumerable<RowInfo<T>> Take<T>(int sheetIndex = 0, int maxErrorRows = 10, Func<T> objectInitializer = null) where T : class { var sheet = Workbook.GetSheetAt(sheetIndex); return Take(sheet, maxErrorRows, objectInitializer); } /// <summary> /// Get objects of target type by converting rows in the sheet with specified name. /// </summary> /// <typeparam name="T">Target object type</typeparam> /// <param name="sheetName">The sheet name</param> /// <param name="maxErrorRows">The maximum error rows before stopping read; default is 10.</param> /// <param name="objectInitializer">Factory method to create a new target object.</param> /// <returns>Objects of target type</returns> public IEnumerable<RowInfo<T>> Take<T>(string sheetName, int maxErrorRows = 10, Func<T> objectInitializer = null) where T : class { var sheet = Workbook.GetSheet(sheetName); return Take(sheet, maxErrorRows, objectInitializer); } /// <summary> /// Put objects in the sheet with specified name. /// </summary> /// <typeparam name="T">Target object type</typeparam> /// <param name="objects">The objects to save.</param> /// <param name="sheetName">The sheet name</param> /// <param name="overwrite"><c>true</c> to overwrite existing rows; otherwise append.</param> public void Put<T>(IEnumerable<T> objects, string sheetName, bool overwrite = true) { if (Workbook == null) Workbook = new XSSFWorkbook(); var sheet = Workbook.GetSheet(sheetName) ?? Workbook.CreateSheet(sheetName); Put(sheet, objects, overwrite); } /// <summary> /// Put objects in the sheet with specified zero-based index. /// </summary> /// <typeparam name="T">Target object type</typeparam> /// <param name="objects">The objects to save.</param> /// <param name="sheetIndex">The sheet index, default is 0.</param> /// <param name="overwrite"><c>true</c> to overwrite existing rows; otherwise append.</param> public void Put<T>(IEnumerable<T> objects, int sheetIndex = 0, bool overwrite = true) { if (Workbook == null) Workbook = new XSSFWorkbook(); var sheet = Workbook.NumberOfSheets > sheetIndex ? Workbook.GetSheetAt(sheetIndex) : Workbook.CreateSheet(); Put(sheet, objects, overwrite); } /// <summary> /// Saves the current workbook to specified file. /// </summary> /// <param name="path">The path to the Excel file.</param> public void Save(string path) { if (Workbook == null) return; using (var fs = File.Open(path, FileMode.Create, FileAccess.Write)) Workbook.Write(fs); } /// <summary> /// Saves the current workbook to specified stream. /// </summary> /// <param name="stream">The stream to save the workbook.</param> public void Save(Stream stream) { Workbook?.Write(stream); } /// <summary> /// Saves the specified objects to the specified Excel file. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="path">The path to the Excel file.</param> /// <param name="objects">The objects to save.</param> /// <param name="sheetName">Name of the sheet.</param> /// <param name="overwrite">If file exists, pass <c>true</c> to overwrite existing file; <c>false</c> to merge.</param> /// <param name="xlsx">if <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(string path, IEnumerable<T> objects, string sheetName, bool overwrite = true, bool xlsx = true) { if (Workbook == null && !overwrite) LoadWorkbookFromFile(path); using (var fs = File.Open(path, FileMode.Create, FileAccess.Write)) Save(fs, objects, sheetName, overwrite, xlsx); } /// <summary> /// Saves the specified objects to the specified Excel file. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="path">The path to the Excel file.</param> /// <param name="objects">The objects to save.</param> /// <param name="sheetIndex">Index of the sheet.</param> /// <param name="overwrite">If file exists, pass <c>true</c> to overwrite existing file; <c>false</c> to merge.</param> /// <param name="xlsx">if <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(string path, IEnumerable<T> objects, int sheetIndex = 0, bool overwrite = true, bool xlsx = true) { if (Workbook == null && !overwrite) LoadWorkbookFromFile(path); using (var fs = File.Open(path, FileMode.Create, FileAccess.Write)) Save(fs, objects, sheetIndex, overwrite, xlsx); } /// <summary> /// Saves the specified objects to the specified stream. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="stream">The stream to write the objects to.</param> /// <param name="objects">The objects to save.</param> /// <param name="sheetName">Name of the sheet.</param> /// <param name="overwrite"><c>true</c> to overwrite existing content; <c>false</c> to merge.</param> /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(Stream stream, IEnumerable<T> objects, string sheetName, bool overwrite = true, bool xlsx = true) { if (Workbook == null) Workbook = xlsx ? new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook(); var sheet = Workbook.GetSheet(sheetName) ?? Workbook.CreateSheet(sheetName); Save(stream, sheet, objects, overwrite); } /// <summary> /// Saves the specified objects to the specified stream. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="stream">The stream to write the objects to.</param> /// <param name="objects">The objects to save.</param> /// <param name="sheetIndex">Index of the sheet.</param> /// <param name="overwrite"><c>true</c> to overwrite existing content; <c>false</c> to merge.</param> /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool overwrite = true, bool xlsx = true) { if (Workbook == null) Workbook = xlsx ? new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook(); var sheet = Workbook.NumberOfSheets > sheetIndex ? Workbook.GetSheetAt(sheetIndex) : Workbook.CreateSheet(); Save(stream, sheet, objects, overwrite); } /// <summary> /// Saves tracked objects to the specified Excel file. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="path">The path to the Excel file.</param> /// <param name="sheetName">Name of the sheet.</param> /// <param name="overwrite">If file exists, pass <c>true</c> to overwrite existing file; <c>false</c> to merge.</param> /// <param name="xlsx">if <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(string path, string sheetName, bool overwrite = true, bool xlsx = true) { if (Workbook == null && !overwrite) LoadWorkbookFromFile(path); using (var fs = File.Open(path, FileMode.Create, FileAccess.Write)) Save<T>(fs, sheetName, overwrite, xlsx); } /// <summary> /// Saves tracked objects to the specified Excel file. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="path">The path to the Excel file.</param> /// <param name="sheetIndex">Index of the sheet.</param> /// <param name="xlsx">if <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> /// <param name="overwrite">If file exists, pass <c>true</c> to overwrite existing file; <c>false</c> to merge.</param> public void Save<T>(string path, int sheetIndex = 0, bool overwrite = true, bool xlsx = true) { if (Workbook == null && !overwrite) LoadWorkbookFromFile(path); using (var fs = File.Open(path, FileMode.Create, FileAccess.Write)) Save<T>(fs, sheetIndex, overwrite, xlsx); } /// <summary> /// Saves tracked objects to the specified stream. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="stream">The stream to write the objects to.</param> /// <param name="sheetName">Name of the sheet.</param> /// <param name="overwrite"><c>true</c> to overwrite existing content; <c>false</c> to merge.</param> /// <param name="xlsx">if <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(Stream stream, string sheetName, bool overwrite = true, bool xlsx = true) { if (Workbook == null) Workbook = xlsx ? new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook(); var sheet = Workbook.GetSheet(sheetName) ?? Workbook.CreateSheet(sheetName); Save<T>(stream, sheet, overwrite); } /// <summary> /// Saves tracked objects to the specified stream. /// </summary> /// <typeparam name="T">The type of objects to save.</typeparam> /// <param name="stream">The stream to write the objects to.</param> /// <param name="sheetIndex">Index of the sheet.</param> /// <param name="overwrite"><c>true</c> to overwrite existing content; <c>false</c> to merge.</param> /// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param> public void Save<T>(Stream stream, int sheetIndex = 0, bool overwrite = true, bool xlsx = true) { if (Workbook == null) Workbook = xlsx ? new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook(); var sheet = Workbook.GetSheetAt(sheetIndex) ?? Workbook.CreateSheet(); Save<T>(stream, sheet, overwrite); } #endregion #region Private Methods #region Import private IEnumerable<RowInfo<T>> Take<T>(ISheet sheet, int maxErrorRows, Func<T> objectInitializer = null) where T : class { if (sheet == null || sheet.PhysicalNumberOfRows < 1) { yield break; } var firstRowIndex = GetFirstRowIndex(sheet); var firstRow = sheet.GetRow(firstRowIndex); var targetType = typeof(T); if (targetType == typeof(object)) // Dynamic type. { targetType = GetDynamicType(sheet); MapHelper.LoadDynamicAttributes(Attributes, DynamicAttributes, targetType); } // Scan object attributes. MapHelper.LoadAttributes(Attributes, targetType); // Read the first row to get column information. var columns = GetColumns(firstRow, targetType); // Detect column format based on the first non-null cell. Helper.LoadDataFormats(sheet, HasHeader ? firstRowIndex + 1 : firstRowIndex, columns, TypeFormats); if (TrackObjects) Objects[sheet.SheetName] = new Dictionary<int, object>(); // Loop rows in file. Generate one target object for each row. var errorCount = 0; var firstDataRowIndex = HasHeader ? firstRowIndex + 1 : firstRowIndex; foreach (IRow row in sheet) { if (maxErrorRows > 0 && errorCount >= maxErrorRows) break; if (row.RowNum < firstDataRowIndex) continue; var obj = objectInitializer == null ? Activator.CreateInstance(targetType) : objectInitializer(); var rowInfo = new RowInfo<T>(row.RowNum, obj as T, -1, string.Empty); LoadRowData(columns, row, obj, rowInfo); if (rowInfo.ErrorColumnIndex >= 0) { errorCount++; //rowInfo.Value = default(T); } if (TrackObjects) Objects[sheet.SheetName][row.RowNum] = rowInfo.Value; yield return rowInfo; } } private Type GetDynamicType(ISheet sheet) { var firstRowIndex = GetFirstRowIndex(sheet); var firstRow = sheet.GetRow(firstRowIndex); var names = new Dictionary<string, Type>(); foreach (var header in firstRow) { var column = GetColumnInfoByDynamicAttribute(header); var type = Helper.InferColumnDataType(sheet, HasHeader ? firstRowIndex : -1, header.ColumnIndex); if (column != null) { names[column.Attribute.PropertyName] = type ?? typeof(string); } else { var headerValue = GetHeaderValue(header); var tempColumn = new ColumnInfo(headerValue, header.ColumnIndex, null); if (_columnFilter != null && !_columnFilter(tempColumn)) { continue; } string propertyName; if (HasHeader && MapHelper.GetCellType(header) == CellType.String) { propertyName = MapHelper.GetVariableName(header.StringCellValue, IgnoredNameChars, TruncateNameFrom, header.ColumnIndex); } else { propertyName = MapHelper.GetVariableName(null, null, null, header.ColumnIndex); } names[propertyName] = type ?? typeof(string); DynamicAttributes[propertyName] = new ColumnAttribute((ushort)header.ColumnIndex) { PropertyName = propertyName }; } } return AnonymousTypeFactory.CreateType(names, true); } private List<ColumnInfo> GetColumns(IRow headerRow, Type type) { // // Column mapping priority: // Map<T> > ColumnAttribute > naming convention > column filter. // var sheetName = headerRow.Sheet.SheetName; var columns = new List<ColumnInfo>(); var columnsCache = new List<object>(); // Cached for export usage. // Prepare a list of ColumnInfo by the first row. foreach (ICell header in headerRow) { // Custom mappings via attributes. var column = GetColumnInfoByAttribute(header, type); // Naming convention. if (column == null && HasHeader && MapHelper.GetCellType(header) == CellType.String) { var s = header.StringCellValue; if (!string.IsNullOrWhiteSpace(s)) { column = GetColumnInfoByName(s.Trim(), header.ColumnIndex, type); } } // Column filter. if (column == null) { column = GetColumnInfoByFilter(header, _columnFilter); if (column != null) // Set default resolvers since the column is not mapped explicitly. { column.Attribute.TryPut = _defaultPutResolver; column.Attribute.TryTake = _defaultTakeResolver; } } if (column == null) continue; // No property was mapped to this column. if (header.CellStyle != null) column.HeaderFormat = header.CellStyle.DataFormat; columns.Add(column); columnsCache.Add(column); } var typeDict = TrackedColumns.ContainsKey(sheetName) ? TrackedColumns[sheetName] : TrackedColumns[sheetName] = new Dictionary<Type, List<object>>(); typeDict[type] = columnsCache; return columns; } private ColumnInfo GetColumnInfoByDynamicAttribute(ICell header) { var cellType = MapHelper.GetCellType(header); var index = header.ColumnIndex; foreach (var pair in DynamicAttributes) { var attribute = pair.Value; // If no header, cannot get a ColumnInfo by resolving header string. if (!HasHeader && attribute.Index < 0) continue; var headerValue = HasHeader ? GetHeaderValue(header) : null; var indexMatch = attribute.Index == index; var nameMatch = cellType == CellType.String && string.Equals(attribute.Name, header.StringCellValue); // Index takes precedence over Name. if (indexMatch || (attribute.Index < 0 && nameMatch)) { // Use a clone so no pollution to original attribute, // The origin might be used later again for multi-column/DefaultResolverType purpose. attribute = attribute.Clone(index); return new ColumnInfo(headerValue, attribute); } } return null; } private ColumnInfo GetColumnInfoByAttribute(ICell header, Type type) { var cellType = MapHelper.GetCellType(header); var index = header.ColumnIndex; foreach (var pair in Attributes) { var attribute = pair.Value; if (pair.Key.ReflectedType != type || attribute.Ignored == true) continue; // If no header, cannot get a ColumnInfo by resolving header string. if (!HasHeader && attribute.Index < 0) continue; var headerValue = HasHeader ? GetHeaderValue(header) : null; var indexMatch = attribute.Index == index; var nameMatch = cellType == CellType.String && string.Equals(attribute.Name?.Trim(), header.StringCellValue?.Trim()); // Index takes precedence over Name. if (indexMatch || (attribute.Index < 0 && nameMatch)) { // Use a clone so no pollution to original attribute, // The origin might be used later again for multi-column/DefaultResolverType purpose. attribute = attribute.Clone(index); return new ColumnInfo(headerValue, attribute); } } return null; } private ColumnInfo GetColumnInfoByName(string name, int index, Type type) { // First attempt: search by string (ignore case). var pi = type.GetProperty(name, MapHelper.BindingFlag); if (pi == null) { // Second attempt: search display name of DisplayAttribute if any. foreach (var propertyInfo in type.GetProperties(MapHelper.BindingFlag)) { var attributes = propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), false); if (attributes.Any(att => string.Equals(((DisplayAttribute)att).Name, name, StringComparison.CurrentCultureIgnoreCase))) { pi = propertyInfo; break; } } } if (pi == null) { // Third attempt: remove ignored chars and do the truncation. pi = type.GetProperty(MapHelper.GetRefinedName(name, IgnoredNameChars, TruncateNameFrom), MapHelper.BindingFlag); } if (pi == null) return null; ColumnAttribute attribute = null; if (Attributes.ContainsKey(pi)) { attribute = Attributes[pi].Clone(index); if (attribute.Ignored == true) return null; } return attribute == null ? new ColumnInfo(name, index, pi) : new ColumnInfo(name, attribute); } private static ColumnInfo GetColumnInfoByFilter(ICell header, Func<IColumnInfo, bool> columnFilter) { if (columnFilter == null) return null; var headerValue = GetHeaderValue(header); var column = new ColumnInfo(headerValue, header.ColumnIndex, null); return !columnFilter(column) ? null : column; } private static void LoadRowData(IEnumerable<ColumnInfo> columns, IRow row, object target, IRowInfo rowInfo) { var errorIndex = -1; string errorMessage = null; void ColumnFailed(IColumnInfo column, string message) { if (errorIndex >= 0) return; // Ensures the first error will not be overwritten. if (column.Attribute.IgnoreErrors == true) return; errorIndex = column.Attribute.Index; errorMessage = message; } foreach (var column in columns) { var index = column.Attribute.Index; if (index < 0) continue; try { var cell = row.GetCell(index); var propertyType = column.Attribute.PropertyUnderlyingType ?? column.Attribute.Property?.PropertyType; if (!MapHelper.TryGetCellValue(cell, propertyType, out object valueObj)) { ColumnFailed(column, "CellType is not supported yet!"); continue; } valueObj = column.RefreshAndGetValue(valueObj); if (column.Attribute.TryTake != null) { if (!column.Attribute.TryTake(column, target)) { ColumnFailed(column, "Returned failure by custom cell resolver!"); } } else if (propertyType != null) { // Change types between IConvertible objects, such as double, float, int and etc. if (MapHelper.TryConvertType(valueObj, column, out object result)) { column.Attribute.Property.SetValue(target, result, null); } else { ColumnFailed(column, "Cannot convert value to the property type!"); } //var value = Convert.ChangeType(valueObj, column.Attribute.PropertyUnderlyingType ?? propertyType); } } catch (Exception e) { ColumnFailed(column, e.ToString()); } } rowInfo.ErrorColumnIndex = errorIndex; rowInfo.ErrorMessage = errorMessage; } private static object GetHeaderValue(ICell header) { object value; var cellType = header.CellType; if (cellType == CellType.Formula) { cellType = header.CachedFormulaResultType; } switch (cellType) { case CellType.Numeric: value = header.NumericCellValue; break; case CellType.String: value = header.StringCellValue; break; default: value = null; break; } return value; } private void LoadWorkbookFromFile(string path) { Workbook = WorkbookFactory.Create(new FileStream(path, FileMode.Open)); } #endregion #region Export private void Put<T>(ISheet sheet, IEnumerable<T> objects, bool overwrite) { var sheetName = sheet.SheetName; var firstRowIndex = GetFirstRowIndex(sheet); var firstRow = sheet.GetRow(firstRowIndex); var objectArray = objects as T[] ?? objects.ToArray(); var type = MapHelper.GetConcreteType(objectArray); var columns = GetTrackedColumns(sheetName, type) ?? GetColumns(firstRow ?? PopulateFirstRow(sheet, null, type), type); firstRow = sheet.GetRow(firstRowIndex) ?? PopulateFirstRow(sheet, columns, type); var rowIndex = overwrite ? HasHeader ? firstRowIndex + 1 : firstRowIndex : sheet.GetRow(sheet.LastRowNum) != null ? sheet.LastRowNum + 1 : sheet.LastRowNum; // Write a IColumnInfo.CustomFormat to each column that does not already have one switch (DefaultStyleSource) { case StyleSources.Type: MapHelper.EnsureDefaultFormatsByType(columns, TypeFormats); break; case StyleSources.ExistingStyle: MapHelper.EnsureDefaultFormatsByExistingStyle(columns, sheet, firstRow); MapHelper.EnsureDefaultFormatsByType(columns, TypeFormats); // A column might not have any existing style break; default: throw new NotImplementedException($"Unsupported ColumnStyleSource value {DefaultStyleSource}"); } foreach (var o in objectArray) { var row = sheet.GetRow(rowIndex); if (overwrite && row != null) { //sheet.RemoveRow(row); //row = sheet.CreateRow(rowIndex); row.Cells.Clear(); } row = row ?? sheet.CreateRow(rowIndex); foreach (var column in columns) { var pi = column.Attribute.Property; var value = pi?.GetValue(o, null); var cell = row.GetCell(column.Attribute.Index, MissingCellPolicy.CREATE_NULL_AS_BLANK); column.CurrentValue = value; if (column.Attribute.TryPut == null || column.Attribute.TryPut(column, o)) { SetCell(cell, column.CurrentValue, column, setStyle: overwrite); } } rowIndex++; } // Remove not used rows if any. while (overwrite && rowIndex <= sheet.LastRowNum) { var row = sheet.GetRow(rowIndex); if (row != null) { //sheet.RemoveRow(row); row.Cells.Clear(); } rowIndex++; } // Injects custom action for headers. if (overwrite && HasHeader && _headerAction != null) { firstRow?.Cells.ForEach(c => _headerAction(c)); } } private void Save<T>(Stream stream, ISheet sheet, bool overwrite) { var sheetName = sheet.SheetName; var objects = Objects.ContainsKey(sheetName) ? Objects[sheetName] : new Dictionary<int, object>(); Put(sheet, objects.Values.OfType<T>(), overwrite); Workbook.Write(stream); } private void Save<T>(Stream stream, ISheet sheet, IEnumerable<T> objects, bool overwrite) { Put(sheet, objects, overwrite); Workbook.Write(stream); } private IRow PopulateFirstRow(ISheet sheet, List<ColumnInfo> columns, Type type) { var row = sheet.CreateRow(GetFirstRowIndex(sheet)); // Use existing column populate the first row. if (columns != null) { foreach (var column in columns) { var cell = row.CreateCell(column.Attribute.Index); if (!HasHeader) continue; SetCell(cell, column.Attribute.Name ?? column.HeaderValue, column, true); } return row; } // If no column cached, populate the first row with attributes and object properties. MapHelper.LoadAttributes(Attributes, type); var attributes = Attributes.Where(p => p.Value.Property != null && p.Value.Property.ReflectedType == type); var properties = new List<PropertyInfo>(type.GetProperties(MapHelper.BindingFlag)); // Firstly populate for those have Attribute specified. foreach (var pair in attributes) { var pi = pair.Key; var attribute = pair.Value; if (pair.Value.Index < 0) continue; var cell = row.CreateCell(attribute.Index); if (HasHeader) { cell.SetCellValue(attribute.Name ?? pi.Name); } properties.Remove(pair.Key); // Remove populated property. } var index = 0; // Then populate for those do not have Attribute specified. foreach (var pi in properties) { var attribute = Attributes.ContainsKey(pi) ? Attributes[pi] : null; if (attribute?.Ignored == true) continue; while (row.GetCell(index) != null) index++; var cell = row.CreateCell(index); if (HasHeader) { cell.SetCellValue(attribute?.Name ?? pi.Name); } else { new ColumnAttribute { Index = index, Property = pi }.MergeTo(Attributes); } index++; } return row; } private List<ColumnInfo> GetTrackedColumns(string sheetName, Type type) { if (!TrackedColumns.ContainsKey(sheetName)) return null; IEnumerable<ColumnInfo> columns = null; var cols = TrackedColumns[sheetName]; if (cols.ContainsKey(type)) { columns = cols[type].OfType<ColumnInfo>(); } return columns?.ToList(); } private void SetCell(ICell cell, object value, ColumnInfo column, bool isHeader = false, bool setStyle = true) { if (value == null || value is ICollection) { cell.SetCellValue((string)null); } else if (value is DateTime) { cell.SetCellValue((DateTime)value); } else if (value.GetType().IsNumeric()) { cell.SetCellValue(Convert.ToDouble(value)); } else if (value is bool) { cell.SetCellValue((bool)value); } else { cell.SetCellValue(value.ToString()); } if (column != null && setStyle) { column.SetCellStyle(cell, value, isHeader, TypeFormats, Helper); } } #endregion Export private int GetFirstRowIndex(ISheet sheet) => FirstRowIndex >= 0 ? FirstRowIndex : sheet.FirstRowNum; #endregion } }
40.891344
203
0.555215
[ "MIT" ]
OleVanSanten/Npoi.Mapper
Npoi.Mapper/src/Npoi.Mapper/Mapper.cs
44,410
C#
using App.Domain.Features.Places; using App.Domain.Interfaces.Base; using App.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace App.Domain.Interfaces.Places { public interface IVenueService : IService<Venue> { Venue GetByFoursquareId(string foursquareId); int InsertSimilariry(Venue a, VenueSimilarityDTO similar); IList<VenueSimilarityDTO> GetVenuesWithSimilarName(Venue venue); void DeleteById(Venue venue); void InsertVisitors(Venue venue); } }
28.619048
74
0.740433
[ "MIT" ]
leticiaventura/instagramScrapper
App/App.Domain/Interfaces/Places/IVenueService.cs
603
C#
namespace Songbird.Web.Models { public record SlackMessageWithLinkButton : SlackMessage { public string ButtonText { get; init; } public string ButtonUrl { get; init; } } }
28.142857
61
0.675127
[ "MIT" ]
karl-sjogren/songbird
src/Songbird.Web/Models/SlackMessageWithLinkButton.cs
197
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.Text; using Roslynator.CodeMetrics; namespace Roslynator { internal static class Extensions { public static SymbolGroupFilter ToSymbolGroupFilter(this TypeKind typeKind) { switch (typeKind) { case TypeKind.Class: return SymbolGroupFilter.Class; case TypeKind.Module: return SymbolGroupFilter.Module; case TypeKind.Delegate: return SymbolGroupFilter.Delegate; case TypeKind.Enum: return SymbolGroupFilter.Enum; case TypeKind.Interface: return SymbolGroupFilter.Interface; case TypeKind.Struct: return SymbolGroupFilter.Struct; default: throw new ArgumentException($"Invalid enum value '{typeKind}'", nameof(typeKind)); } } public static MemberDeclarationKind GetMemberDeclarationKind(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: { return (((IEventSymbol)symbol).ExplicitInterfaceImplementations.Any()) ? MemberDeclarationKind.ExplicitlyImplementedEvent : MemberDeclarationKind.Event; } case SymbolKind.Field: { var fieldSymbol = (IFieldSymbol)symbol; return (fieldSymbol.IsConst) ? MemberDeclarationKind.Const : MemberDeclarationKind.Field; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; switch (methodSymbol.MethodKind) { case MethodKind.Ordinary: return MemberDeclarationKind.Method; case MethodKind.ExplicitInterfaceImplementation: return MemberDeclarationKind.ExplicitlyImplementedMethod; case MethodKind.Constructor: return MemberDeclarationKind.Constructor; case MethodKind.Destructor: return MemberDeclarationKind.Destructor; case MethodKind.StaticConstructor: return MemberDeclarationKind.StaticConstructor; case MethodKind.Conversion: return MemberDeclarationKind.ConversionOperator; case MethodKind.UserDefinedOperator: return MemberDeclarationKind.Operator; } break; } case SymbolKind.Property: { var propertySymbol = (IPropertySymbol)symbol; bool explicitlyImplemented = propertySymbol.ExplicitInterfaceImplementations.Any(); if (propertySymbol.IsIndexer) { return (explicitlyImplemented) ? MemberDeclarationKind.ExplicitlyImplementedIndexer : MemberDeclarationKind.Indexer; } else { return (explicitlyImplemented) ? MemberDeclarationKind.ExplicitlyImplementedProperty : MemberDeclarationKind.Property; } } } Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); return MemberDeclarationKind.None; } public static SymbolGroup GetSymbolGroup(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.NamedType: { var namedType = (INamedTypeSymbol)symbol; switch (namedType.TypeKind) { case TypeKind.Class: return SymbolGroup.Class; case TypeKind.Module: return SymbolGroup.Module; case TypeKind.Delegate: return SymbolGroup.Delegate; case TypeKind.Enum: return SymbolGroup.Enum; case TypeKind.Interface: return SymbolGroup.Interface; case TypeKind.Struct: return SymbolGroup.Struct; } Debug.Fail(namedType.TypeKind.ToString()); return SymbolGroup.None; } case SymbolKind.Event: { return SymbolGroup.Event; } case SymbolKind.Field: { return (((IFieldSymbol)symbol).IsConst) ? SymbolGroup.Const : SymbolGroup.Field; } case SymbolKind.Method: { return SymbolGroup.Method; } case SymbolKind.Property: { return (((IPropertySymbol)symbol).IsIndexer) ? SymbolGroup.Indexer : SymbolGroup.Property; } } Debug.Fail(symbol.Kind.ToString()); return SymbolGroup.None; } public static string GetText(this SymbolGroup symbolGroup) { switch (symbolGroup) { case SymbolGroup.Namespace: return "namespace"; case SymbolGroup.Module: return "module"; case SymbolGroup.Class: return "class"; case SymbolGroup.Delegate: return "delegate"; case SymbolGroup.Enum: return "enum"; case SymbolGroup.Interface: return "interface"; case SymbolGroup.Struct: return "struct"; case SymbolGroup.Event: return "event"; case SymbolGroup.Field: return "field"; case SymbolGroup.Const: return "const"; case SymbolGroup.Method: return "method"; case SymbolGroup.Property: return "property"; case SymbolGroup.Indexer: return "indexer"; } Debug.Fail(symbolGroup.ToString()); return ""; } public static string GetPluralText(this SymbolGroup symbolGroup) { switch (symbolGroup) { case SymbolGroup.Namespace: return "namespaces"; case SymbolGroup.Module: return "modules"; case SymbolGroup.Class: return "classes"; case SymbolGroup.Delegate: return "delegates"; case SymbolGroup.Enum: return "enums"; case SymbolGroup.Interface: return "interfaces"; case SymbolGroup.Struct: return "structs"; case SymbolGroup.Event: return "events"; case SymbolGroup.Field: return "fields"; case SymbolGroup.Const: return "consts"; case SymbolGroup.Method: return "methods"; case SymbolGroup.Property: return "properties"; case SymbolGroup.Indexer: return "indexers"; } Debug.Fail(symbolGroup.ToString()); return ""; } public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) { if (dictionary.TryGetValue(key, out TValue value)) return value; return default; } public static bool StartsWith(this string s, string value1, string value2, StringComparison comparisonType) { return s.StartsWith(value1, comparisonType) || s.StartsWith(value2, comparisonType); } public static bool HasFixAllProvider(this CodeFixProvider codeFixProvider, FixAllScope fixAllScope) { return codeFixProvider.GetFixAllProvider()?.GetSupportedFixAllScopes().Contains(fixAllScope) == true; } public static Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync( this Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationWithAnalyzersOptions analysisOptions, CancellationToken cancellationToken = default) { var compilationWithAnalyzers = new CompilationWithAnalyzers(compilation, analyzers, analysisOptions); return compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken); } public static void Add(this AnalyzerTelemetryInfo telemetryInfo, AnalyzerTelemetryInfo telemetryInfoToAdd) { telemetryInfo.CodeBlockActionsCount += telemetryInfoToAdd.CodeBlockActionsCount; telemetryInfo.CodeBlockEndActionsCount += telemetryInfoToAdd.CodeBlockEndActionsCount; telemetryInfo.CodeBlockStartActionsCount += telemetryInfoToAdd.CodeBlockStartActionsCount; telemetryInfo.CompilationActionsCount += telemetryInfoToAdd.CompilationActionsCount; telemetryInfo.CompilationEndActionsCount += telemetryInfoToAdd.CompilationEndActionsCount; telemetryInfo.CompilationStartActionsCount += telemetryInfoToAdd.CompilationStartActionsCount; telemetryInfo.ExecutionTime += telemetryInfoToAdd.ExecutionTime; telemetryInfo.OperationActionsCount += telemetryInfoToAdd.OperationActionsCount; telemetryInfo.OperationBlockActionsCount += telemetryInfoToAdd.OperationBlockActionsCount; telemetryInfo.OperationBlockEndActionsCount += telemetryInfoToAdd.OperationBlockEndActionsCount; telemetryInfo.OperationBlockStartActionsCount += telemetryInfoToAdd.OperationBlockStartActionsCount; telemetryInfo.SemanticModelActionsCount += telemetryInfoToAdd.SemanticModelActionsCount; telemetryInfo.SymbolActionsCount += telemetryInfoToAdd.SymbolActionsCount; telemetryInfo.SyntaxNodeActionsCount += telemetryInfoToAdd.SyntaxNodeActionsCount; telemetryInfo.SyntaxTreeActionsCount += telemetryInfoToAdd.SyntaxTreeActionsCount; } public static ConsoleColor GetColor(this DiagnosticSeverity diagnosticSeverity) { switch (diagnosticSeverity) { case DiagnosticSeverity.Hidden: return ConsoleColor.DarkGray; case DiagnosticSeverity.Info: return ConsoleColor.Cyan; case DiagnosticSeverity.Warning: return ConsoleColor.Yellow; case DiagnosticSeverity.Error: return ConsoleColor.Red; default: throw new InvalidOperationException($"Unknown diagnostic severity '{diagnosticSeverity}'."); } } public static async Task<CodeMetricsInfo> CountLinesAsync( this ICodeMetricsService service, Project project, LinesOfCodeKind kind, CodeMetricsOptions options = null, CancellationToken cancellationToken = default) { CodeMetricsInfo codeMetrics = default; foreach (Document document in project.Documents) { if (!document.SupportsSyntaxTree) continue; CodeMetricsInfo documentMetrics = await service.CountLinesAsync(document, kind, options, cancellationToken).ConfigureAwait(false); codeMetrics = codeMetrics.Add(documentMetrics); } return codeMetrics; } public static async Task<CodeMetricsInfo> CountLinesAsync( this ICodeMetricsService service, Document document, LinesOfCodeKind kind, CodeMetricsOptions options = null, CancellationToken cancellationToken = default) { SyntaxTree tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree == null) return default; if (!options.IncludeGeneratedCode && GeneratedCodeUtility.IsGeneratedCode(tree, f => service.SyntaxFacts.IsComment(f), cancellationToken)) { return default; } SyntaxNode root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); switch (kind) { case LinesOfCodeKind.Physical: return service.CountPhysicalLines(root, sourceText, options, cancellationToken); case LinesOfCodeKind.Logical: return service.CountLogicalLines(root, sourceText, options, cancellationToken); default: throw new InvalidOperationException(); } } public static OperationCanceledException GetOperationCanceledException(this AggregateException aggregateException) { OperationCanceledException operationCanceledException = null; foreach (Exception ex in aggregateException.InnerExceptions) { if (ex is OperationCanceledException operationCanceledException2) { if (operationCanceledException == null) operationCanceledException = operationCanceledException2; } else if (ex is AggregateException aggregateException2) { foreach (Exception ex2 in aggregateException2.InnerExceptions) { if (ex2 is OperationCanceledException operationCanceledException3) { if (operationCanceledException == null) operationCanceledException = operationCanceledException3; } else { return null; } } return operationCanceledException; } else { return null; } } return null; } public static ConsoleColor GetColor(this WorkspaceDiagnosticKind kind) { switch (kind) { case WorkspaceDiagnosticKind.Failure: return ConsoleColor.Red; case WorkspaceDiagnosticKind.Warning: return ConsoleColor.Yellow; default: throw new InvalidOperationException($"Unknown value '{kind}'."); } } } }
40.82598
160
0.537072
[ "Apache-2.0" ]
RickeyEstes/Roslynator
src/Workspaces.Core/Extensions/Extensions.cs
16,659
C#
// Copyright 2014-2017 ClassicalSharp | Licensed under BSD-3 using System; using System.IO; namespace ClassicalSharp { /// <summary> Implements a non-seekable stream that can only be read from. </summary> internal abstract class ReadOnlyStream : Stream { static NotSupportedException ex = new NotSupportedException("Writing/Seeking not supported"); public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw ex; } } public override long Position { get { throw ex; } set { throw ex; } } public override long Seek(long offset, SeekOrigin origin) { throw ex; } public override void SetLength(long value) { throw ex; } public override void Write(byte[] buffer, int offset, int count) { throw ex; } } }
31.931034
96
0.680346
[ "BSD-3-Clause" ]
CybertronicToon/ClassicalSharp-Survival
ClassicalSharp/Utils/ReadOnlyStream.cs
928
C#
// <auto-generated /> using ITest.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace ITest.Data.Migrations { [DbContext(typeof(ITestDbContext))] [Migration("20180504163635_Test Names Are Not Unique")] partial class TestNamesAreNotUnique { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.2-rtm-10011") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Itest.Data.Models.Answer", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Content") .IsRequired(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsCorrect"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<Guid>("QuestionId"); b.HasKey("Id"); b.HasIndex("QuestionId"); b.ToTable("Answers"); }); modelBuilder.Entity("Itest.Data.Models.Category", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .IsRequired(); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Categories"); }); modelBuilder.Entity("Itest.Data.Models.Question", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Body") .IsRequired(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<Guid>("TestId"); b.HasKey("Id"); b.HasIndex("TestId"); b.ToTable("Questions"); }); modelBuilder.Entity("Itest.Data.Models.Test", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<Guid>("CategoryId"); b.Property<string>("CreatedByUserId") .IsRequired(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<int>("Duration"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<bool>("IsPublished"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .IsRequired(); b.HasKey("Id"); b.HasIndex("CategoryId"); b.HasIndex("CreatedByUserId"); b.ToTable("Tests"); }); modelBuilder.Entity("Itest.Data.Models.UserAnswer", b => { b.Property<string>("UserId"); b.Property<Guid>("AnswerId"); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.HasKey("UserId", "AnswerId"); b.HasIndex("AnswerId"); b.ToTable("UserAnswers"); }); modelBuilder.Entity("Itest.Data.Models.UserTest", b => { b.Property<string>("UserId"); b.Property<Guid>("TestId"); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<double>("ExecutionTime"); b.Property<bool>("IsDeleted"); b.Property<bool?>("IsPassed"); b.Property<bool?>("IsSubmited"); b.Property<DateTime?>("ModifiedOn"); b.Property<DateTime>("StartedOn"); b.HasKey("UserId", "TestId"); b.HasIndex("TestId"); b.ToTable("UserTests"); }); modelBuilder.Entity("ITest.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Itest.Data.Models.Answer", b => { b.HasOne("Itest.Data.Models.Question", "Question") .WithMany("Answers") .HasForeignKey("QuestionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Itest.Data.Models.Question", b => { b.HasOne("Itest.Data.Models.Test", "Test") .WithMany("Questions") .HasForeignKey("TestId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Itest.Data.Models.Test", b => { b.HasOne("Itest.Data.Models.Category", "Category") .WithMany("Tests") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ITest.Models.ApplicationUser", "CreatedByUser") .WithMany("Tests") .HasForeignKey("CreatedByUserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Itest.Data.Models.UserAnswer", b => { b.HasOne("Itest.Data.Models.Answer", "Answer") .WithMany("UserAnswers") .HasForeignKey("AnswerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ITest.Models.ApplicationUser", "User") .WithMany("UserAnswers") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Itest.Data.Models.UserTest", b => { b.HasOne("Itest.Data.Models.Test", "Test") .WithMany("UserTests") .HasForeignKey("TestId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ITest.Models.ApplicationUser", "User") .WithMany("UserTests") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("ITest.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("ITest.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ITest.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("ITest.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
32.493304
117
0.449612
[ "MIT" ]
The-Singing-Melons/ITestSystem
ITest/ITest.Data/Migrations/20180504163635_Test Names Are Not Unique.Designer.cs
14,559
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class ModifyDiskSpecResponse : AcsResponse { private string requestId; private string taskId; public string RequestId { get { return requestId; } set { requestId = value; } } public string TaskId { get { return taskId; } set { taskId = value; } } } }
22.403509
63
0.686766
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/ModifyDiskSpecResponse.cs
1,277
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Commands.Sql.ServiceTierAdvisor.Services { /// <summary> /// Adapter for Service Tier Advisor operations /// </summary> public class AzureSqlServiceTierAdvisorAdapter { /// <summary> /// Master database name /// </summary> private const string MasterDatabase = "master"; /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlServiceTierAdvisorCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public AzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private AzureSubscription _subscription { get; set; } /// <summary> /// Constructs a service tier advisor adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlServiceTierAdvisorAdapter(AzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlServiceTierAdvisorCommunicator(Context); } /// <summary> /// Get upgrade database hints for database. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of Azure Sql server</param> /// <param name="databaseName">The name of Azure Sql database</param> /// <param name="excludeEpCandidates">Exclude databases if it is already recommended for elastic pool</param> /// <returns>Upgrade database hints</returns> public RecommendedDatabaseProperties GetUpgradeDatabaseHints(string resourceGroupName, string serverName, string databaseName, bool excludeEpCandidates) { // if excludeEpCandidates is set and database is included in recommended elastic pools return null if (excludeEpCandidates) { var pools = Communicator.GetRecommendedElasticPoolsExpanded(resourceGroupName, serverName, "databases", Util.GenerateTracingId()); if (pools.SelectMany(pool => pool.Properties.Databases).Any(poolDatabase => databaseName == poolDatabase.Name)) { return null; } } var database = Communicator.GetDatabaseExpanded(resourceGroupName, serverName, databaseName, "upgradeHint", Util.GenerateTracingId()); return CreateUpgradeDatabaseHint(database); } /// <summary> /// List recommended database service tier and SLO for all databases on server. /// </summary> /// <param name="resourceGroupName">Resource group</param> /// <param name="serverName">Server name</param> /// <param name="excludeEpCandidates">Exclude databases that are already recommended for elastic pools</param> /// <returns>List of UpgradeDatabaseHint</returns> public ICollection<RecommendedDatabaseProperties> ListUpgradeDatabaseHints(string resourceGroupName, string serverName, bool excludeEpCandidates) { var databases = Communicator.ListDatabasesExpanded(resourceGroupName, serverName, "upgradeHint", Util.GenerateTracingId()); // if excludeEpCandidates flag is set filter out databases that are in recommended elastic pools if (excludeEpCandidates && databases.Count > 0) { var pools = Communicator.GetRecommendedElasticPoolsExpanded(resourceGroupName, serverName, "databases", Util.GenerateTracingId()); var pooledDatabaseNames = new HashSet<string>(pools.SelectMany(pool => pool.Properties.Databases).Select(d => d.Name)); databases = databases.Where(database => !pooledDatabaseNames.Contains(database.Name)).ToList(); } return databases.Where(d => d.Name != MasterDatabase) .Select(CreateUpgradeDatabaseHint).ToList(); } /// <summary> /// Creates UpgradeDatabaseHint from database object by using same edition and SLO from upgrade hint. /// </summary> /// <param name="database">Database object</param> /// <returns>Returns UpgradeDatabaseHint</returns> private RecommendedDatabaseProperties CreateUpgradeDatabaseHint(Management.Sql.Models.Database database) { return new RecommendedDatabaseProperties() { Name = database.Name, TargetEdition = SloToEdition(database.Properties.UpgradeHint.TargetServiceLevelObjective), TargetServiceLevelObjective = database.Properties.UpgradeHint.TargetServiceLevelObjective }; } /// <summary> /// Map SLO to Edition /// </summary> /// <param name="ServiceLevelObjective">Service level objective string</param> /// <returns>Edition</returns> private string SloToEdition(string ServiceLevelObjective) { if (ServiceLevelObjective.StartsWith("B")) return "Basic"; if (ServiceLevelObjective.StartsWith("S")) return "Standard"; if (ServiceLevelObjective.StartsWith("P")) return "Premium"; return null; } } }
49.139706
161
0.6328
[ "MIT" ]
Peter-Schneider/azure-powershell
src/ResourceManager/Sql/Commands.Sql/ServiceTierAdvisor/Services/AzureSqlServiceTierAdvisorAdapter.cs
6,550
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.live.Model.V20161101; namespace Aliyun.Acs.live.Transform.V20161101 { public class AddCasterEpisodeResponseUnmarshaller { public static AddCasterEpisodeResponse Unmarshall(UnmarshallerContext context) { AddCasterEpisodeResponse addCasterEpisodeResponse = new AddCasterEpisodeResponse(); addCasterEpisodeResponse.HttpResponse = context.HttpResponse; addCasterEpisodeResponse.RequestId = context.StringValue("AddCasterEpisode.RequestId"); addCasterEpisodeResponse.EpisodeId = context.StringValue("AddCasterEpisode.EpisodeId"); return addCasterEpisodeResponse; } } }
37.560976
91
0.764286
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-live/Live/Transform/V20161101/AddCasterEpisodeResponseUnmarshaller.cs
1,540
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.Data.Tables.Models { /// <summary> A signed identifier. </summary> public partial class SignedIdentifier { /// <summary> Initializes a new instance of SignedIdentifier. </summary> /// <param name="id"> A unique id. </param> /// <param name="accessPolicy"> The access policy. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="accessPolicy"/> is null. </exception> public SignedIdentifier(string id, AccessPolicy accessPolicy) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (accessPolicy == null) { throw new ArgumentNullException(nameof(accessPolicy)); } Id = id; AccessPolicy = accessPolicy; } /// <summary> A unique id. </summary> public string Id { get; set; } /// <summary> The access policy. </summary> public AccessPolicy AccessPolicy { get; set; } } }
30.725
131
0.583401
[ "MIT" ]
mattschoutends/azure-sdk-for-net
sdk/tables/Azure.Data.Tables/src/Generated/Models/SignedIdentifier.cs
1,229
C#
using System; using System.Diagnostics; using System.Resources; using System.Windows; using System.Windows.Markup; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using SkyMoon.WinPhone.Resources; namespace SkyMoon.WinPhone { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public static PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) { // Unregister the event so it doesn't get called again RootFrame.Navigated -= ClearBackStackAfterReset; // Only clear the stack for 'new' (forward) and 'refresh' navigations if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh) return; // For UI consistency, clear the entire page stack while (RootFrame.RemoveBackEntry() != null) { ; // do nothing } } #endregion // Initialize the app's font and flow direction as defined in its localized resource strings. // // To ensure that the font of your application is aligned with its supported languages and that the // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage // and ResourceFlowDirection should be initialized in each resx file to match these values with that // file's culture. For example: // // AppResources.es-ES.resx // ResourceLanguage's value should be "es-ES" // ResourceFlowDirection's value should be "LeftToRight" // // AppResources.ar-SA.resx // ResourceLanguage's value should be "ar-SA" // ResourceFlowDirection's value should be "RightToLeft" // // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072. // private void InitializeLanguage() { try { // Set the font to match the display language defined by the // ResourceLanguage resource string for each supported language. // // Fall back to the font of the neutral language if the Display // language of the phone is not supported. // // If a compiler error is hit then ResourceLanguage is missing from // the resource file. RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage); // Set the FlowDirection of all elements under the root frame based // on the ResourceFlowDirection resource string for each // supported language. // // If a compiler error is hit then ResourceFlowDirection is missing from // the resource file. FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection); RootFrame.FlowDirection = flow; } catch { // If an exception is caught here it is most likely due to either // ResourceLangauge not being correctly set to a supported language // code or ResourceFlowDirection is set to a value other than LeftToRight // or RightToLeft. if (Debugger.IsAttached) { Debugger.Break(); } throw; } } } }
33.723214
115
0.73524
[ "MIT" ]
Julien-Mialon/XamarinTD
TD-01/SkyMoon/SkyMoon/SkyMoon.WinPhone/App.xaml.cs
7,556
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 auditmanager-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AuditManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AuditManager.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetSettings operation /// </summary> public class GetSettingsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetSettingsResponse response = new GetSettingsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("settings", targetDepth)) { var unmarshaller = SettingsUnmarshaller.Instance; response.Settings = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonAuditManagerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static GetSettingsResponseUnmarshaller _instance = new GetSettingsResponseUnmarshaller(); internal static GetSettingsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetSettingsResponseUnmarshaller Instance { get { return _instance; } } } }
38.298246
196
0.62918
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AuditManager/Generated/Model/Internal/MarshallTransformations/GetSettingsResponseUnmarshaller.cs
4,366
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.eShopOnContainers.Services.Marketing.API.Model; namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.EntityConfigurations { class RuleEntityTypeConfiguration : IEntityTypeConfiguration<Rule> { public void Configure(EntityTypeBuilder<Rule> builder) { builder.ToTable("Rule"); builder.HasKey(r => r.Id); builder.Property(r => r.Id) .ForSqlServerUseSequenceHiLo("rule_hilo") .IsRequired(); builder.HasDiscriminator<int>("RuleTypeId") .HasValue<UserProfileRule>(RuleType.UserProfileRule.Id) .HasValue<PurchaseHistoryRule>(RuleType.PurchaseHistoryRule.Id) .HasValue<UserLocationRule>(RuleType.UserLocationRule.Id); builder.Property(r => r.Description) .HasColumnName("Description") .IsRequired(); } } }
33.806452
96
0.65458
[ "MIT" ]
07101994/eShopOnContainers
src/Services/Marketing/Marketing.API/Infrastructure/EntityConfigurations/RuleEntityTypeConfiguration.cs
1,050
C#
/* * Copyright 2020 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 redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Redshift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ClusterSubnetGroupAlreadyExistsException operation /// </summary> public class ClusterSubnetGroupAlreadyExistsExceptionUnmarshaller : IErrorResponseUnmarshaller<ClusterSubnetGroupAlreadyExistsException, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ClusterSubnetGroupAlreadyExistsException Unmarshall(XmlUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public ClusterSubnetGroupAlreadyExistsException Unmarshall(XmlUnmarshallerContext context, ErrorResponse errorResponse) { ClusterSubnetGroupAlreadyExistsException response = new ClusterSubnetGroupAlreadyExistsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { } } return response; } private static ClusterSubnetGroupAlreadyExistsExceptionUnmarshaller _instance = new ClusterSubnetGroupAlreadyExistsExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ClusterSubnetGroupAlreadyExistsExceptionUnmarshaller Instance { get { return _instance; } } } }
37.181818
164
0.667176
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/Internal/MarshallTransformations/ClusterSubnetGroupAlreadyExistsExceptionUnmarshaller.cs
3,272
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.Collections.Immutable; using System.Text; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { internal class DocCommentFormatter { private const int s_indentSize = 2; private const int s_wrapLength = 80; private static readonly string s_summaryHeader = FeaturesResources.Summary_colon; private static readonly string s_paramHeader = FeaturesResources.Parameters_colon; private const string s_labelFormat = "{0}:"; private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon; private static readonly string s_returnsHeader = FeaturesResources.Returns_colon; private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon; private static readonly string s_remarksHeader = FeaturesResources.Remarks_colon; internal static ImmutableArray<string> Format(IDocumentationCommentFormattingService docCommentFormattingService, DocumentationComment docComment) { var formattedCommentLinesBuilder = ArrayBuilder<string>.GetInstance(); var lineBuilder = new StringBuilder(); var formattedSummaryText = docCommentFormattingService.Format(docComment.SummaryText); if (!string.IsNullOrWhiteSpace(formattedSummaryText)) { formattedCommentLinesBuilder.Add(s_summaryHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedSummaryText)); } var parameterNames = docComment.ParameterNames; if (parameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_paramHeader); for (var i = 0; i < parameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, parameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawParameterText = docComment.GetParameterText(parameterNames[i]); var formattedParameterText = docCommentFormattingService.Format(rawParameterText); if (!string.IsNullOrWhiteSpace(formattedParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedParameterText)); } } } var typeParameterNames = docComment.TypeParameterNames; if (typeParameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_typeParameterHeader); for (var i = 0; i < typeParameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, typeParameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawTypeParameterText = docComment.GetTypeParameterText(typeParameterNames[i]); var formattedTypeParameterText = docCommentFormattingService.Format(rawTypeParameterText); if (!string.IsNullOrWhiteSpace(formattedTypeParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedTypeParameterText)); } } } var formattedReturnsText = docCommentFormattingService.Format(docComment.ReturnsText); if (!string.IsNullOrWhiteSpace(formattedReturnsText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_returnsHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedReturnsText)); } var exceptionTypes = docComment.ExceptionTypes; if (exceptionTypes.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_exceptionsHeader); for (var i = 0; i < exceptionTypes.Length; i++) { var rawExceptionTexts = docComment.GetExceptionTexts(exceptionTypes[i]); for (var j = 0; j < rawExceptionTexts.Length; j++) { if (i != 0 || j != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, exceptionTypes[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var formattedExceptionText = docCommentFormattingService.Format(rawExceptionTexts[j]); if (!string.IsNullOrWhiteSpace(formattedExceptionText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedExceptionText)); } } } } var formattedRemarksText = docCommentFormattingService.Format(docComment.RemarksText); if (!string.IsNullOrWhiteSpace(formattedRemarksText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_remarksHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedRemarksText)); } // Eliminate any blank lines at the beginning. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[0].Length == 0) { formattedCommentLinesBuilder.RemoveAt(0); } // Eliminate any blank lines at the end. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[formattedCommentLinesBuilder.Count - 1].Length == 0) { formattedCommentLinesBuilder.RemoveAt(formattedCommentLinesBuilder.Count - 1); } return formattedCommentLinesBuilder.ToImmutableAndFree(); } private static ImmutableArray<string> CreateWrappedTextFromRawText(string rawText) { var lines = ArrayBuilder<string>.GetInstance(); // First split the string into constituent lines. var split = rawText.Split(new[] { "\r\n" }, System.StringSplitOptions.None); // Now split each line into multiple lines. foreach (var item in split) { SplitRawLineIntoFormattedLines(item, lines); } return lines.ToImmutableAndFree(); } private static void SplitRawLineIntoFormattedLines( string line, ArrayBuilder<string> lines) { var indent = new StringBuilder().Append(' ', s_indentSize * 2).ToString(); var words = line.Split(' '); var firstInLine = true; var sb = new StringBuilder(); sb.Append(indent); foreach (var word in words) { // We must always append at least one word to ensure progress. if (firstInLine) { firstInLine = false; } else { sb.Append(' '); } sb.Append(word); if (sb.Length >= s_wrapLength) { lines.Add(sb.ToString()); sb.Clear(); sb.Append(indent); firstInLine = true; } } if (sb.ToString().Trim() != string.Empty) { lines.Add(sb.ToString()); } } } } }
45.488263
161
0.542058
[ "Apache-2.0" ]
20chan/roslyn
src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.DocCommentFormatter.cs
9,691
C#
// Copyright 2019 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Xml; using UnityEngine; namespace Mujoco { public class MjSiteVectorSensor : MjBaseSensor { // NOTE: These names must match sensor names listed on mujoco.org. // Changing them is justified only when Mujoco is upgraded to a new version. public enum AvailableSensors { Accelerometer, Velocimeter, Gyro, Force, Torque, Magnetometer, FramePos, FrameXAxis, FrameYAxis, FrameZAxis, FrameLinVel, FrameAngVel, FrameLinAcc, FrameAngAcc, } public AvailableSensors SensorType; public MjSite Site; public Vector3 SensorReading { get; private set; } protected override XmlElement ToMjcf(XmlDocument doc) { if (Site == null) { throw new NullReferenceException("Missing a reference to a MjSite."); } var tag = SensorType.ToString().ToLower(); var mjcf = doc.CreateElement(tag); if (tag.Contains("frame")) { mjcf.SetAttribute("objtype", "site"); mjcf.SetAttribute("objname", Site.MujocoName); } else { mjcf.SetAttribute("site", Site.MujocoName); } return mjcf; } protected override void FromMjcf(XmlElement mjcf) { if (!Enum.TryParse(mjcf.Name, ignoreCase: true, result: out SensorType)) { throw new ArgumentException($"Unknown sensor type {mjcf.Name}."); } if (mjcf.Name.Contains("frame")) { Site = mjcf.GetObjectReferenceAttribute<MjSite>("objname"); } else { Site = mjcf.GetObjectReferenceAttribute<MjSite>("site"); } } public override unsafe void OnSyncState(MujocoLib.mjData_* data) { SensorReading = MjEngineTool.UnityVector3(data->sensordata + _sensorAddress); } } }
30.223684
81
0.70222
[ "Apache-2.0" ]
deepmind/mujoco
unity/Runtime/Components/Sensors/MjSiteVectorSensor.cs
2,297
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Cache.V20190701 { public static class GetRedis { /// <summary> /// A single Redis item in List or Get Operation. /// </summary> public static Task<GetRedisResult> InvokeAsync(GetRedisArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetRedisResult>("azure-native:cache/v20190701:getRedis", args ?? new GetRedisArgs(), options.WithVersion()); } public sealed class GetRedisArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the Redis cache. /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetRedisArgs() { } } [OutputType] public sealed class GetRedisResult { /// <summary> /// The keys of the Redis cache - not set if this object is not the response to Create or Update redis cache /// </summary> public readonly Outputs.RedisAccessKeysResponse AccessKeys; /// <summary> /// Specifies whether the non-ssl Redis server port (6379) is enabled. /// </summary> public readonly bool? EnableNonSslPort; /// <summary> /// Redis host name. /// </summary> public readonly string HostName; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// List of the Redis instances associated with the cache /// </summary> public readonly ImmutableArray<Outputs.RedisInstanceDetailsResponse> Instances; /// <summary> /// List of the linked servers associated with the cache /// </summary> public readonly ImmutableArray<Outputs.RedisLinkedServerResponse> LinkedServers; /// <summary> /// The geo-location where the resource lives /// </summary> public readonly string Location; /// <summary> /// Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2') /// </summary> public readonly string? MinimumTlsVersion; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Redis non-SSL port. /// </summary> public readonly int Port; /// <summary> /// Redis instance provisioning status. /// </summary> public readonly string ProvisioningState; /// <summary> /// All Redis Settings. Few possible keys: rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value etc. /// </summary> public readonly ImmutableDictionary<string, string>? RedisConfiguration; /// <summary> /// Redis version. /// </summary> public readonly string RedisVersion; /// <summary> /// The number of replicas to be created per master. /// </summary> public readonly int? ReplicasPerMaster; /// <summary> /// The number of shards to be created on a Premium Cluster Cache. /// </summary> public readonly int? ShardCount; /// <summary> /// The SKU of the Redis cache to deploy. /// </summary> public readonly Outputs.SkuResponse Sku; /// <summary> /// Redis SSL port. /// </summary> public readonly int SslPort; /// <summary> /// Static IP address. Required when deploying a Redis cache inside an existing Azure Virtual Network. /// </summary> public readonly string? StaticIP; /// <summary> /// The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1 /// </summary> public readonly string? SubnetId; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// A dictionary of tenant settings /// </summary> public readonly ImmutableDictionary<string, string>? TenantSettings; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// A list of availability zones denoting where the resource needs to come from. /// </summary> public readonly ImmutableArray<string> Zones; [OutputConstructor] private GetRedisResult( Outputs.RedisAccessKeysResponse accessKeys, bool? enableNonSslPort, string hostName, string id, ImmutableArray<Outputs.RedisInstanceDetailsResponse> instances, ImmutableArray<Outputs.RedisLinkedServerResponse> linkedServers, string location, string? minimumTlsVersion, string name, int port, string provisioningState, ImmutableDictionary<string, string>? redisConfiguration, string redisVersion, int? replicasPerMaster, int? shardCount, Outputs.SkuResponse sku, int sslPort, string? staticIP, string? subnetId, ImmutableDictionary<string, string>? tags, ImmutableDictionary<string, string>? tenantSettings, string type, ImmutableArray<string> zones) { AccessKeys = accessKeys; EnableNonSslPort = enableNonSslPort; HostName = hostName; Id = id; Instances = instances; LinkedServers = linkedServers; Location = location; MinimumTlsVersion = minimumTlsVersion; Name = name; Port = port; ProvisioningState = provisioningState; RedisConfiguration = redisConfiguration; RedisVersion = redisVersion; ReplicasPerMaster = replicasPerMaster; ShardCount = shardCount; Sku = sku; SslPort = sslPort; StaticIP = staticIP; SubnetId = subnetId; Tags = tags; TenantSettings = tenantSettings; Type = type; Zones = zones; } } }
34.391509
406
0.595254
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Cache/V20190701/GetRedis.cs
7,291
C#
using System; using System.Collections.Generic; namespace Lncodes.Example.Delegate { public sealed class InventoryController { public readonly int MaxCapacity = 3; private readonly List<string> _itemCollection = new List<string>(); //Declare Delegate using delegate keyword public delegate void DeleteItemCallback(int itemIndex, string itemName); private readonly DeleteItemCallback _deleteItemCallback; /// <summary> /// Constructor /// </summary> /// <param name="deleteItem"></param> public InventoryController(DeleteItemCallback deleteItem) => _deleteItemCallback = deleteItem; /// <summary> /// Method for adding item to inventory /// </summary> /// <param name="item">Item Want To Add To Inventory</param> /// <param name="addItemCallback">Delegate Call When Success Adding Item</param> public void AddingItem(string item, Action<string> addItemCallback) { if (_itemCollection.Count < MaxCapacity) { _itemCollection.Add(item); addItemCallback(item); } else Console.WriteLine("Your inventory has reached max capacity"); } /// <summary> /// Method for adding item to inventory /// </summary> /// <param name="getRandomItem">Delegate Return Item</param> /// <param name="addItemCallback">Delegate Call When Success Adding Item</param> public void AddingItem(Func<string> getRandomItem, Action<string> addItemCallback) { if (_itemCollection.Count < MaxCapacity) { var item = getRandomItem(); _itemCollection.Add(item); addItemCallback(item); } else Console.WriteLine("Your inventory has reached max capacity"); } /// <summary> /// Method for adding item to inventory /// </summary> /// <param name="getRandomItem">Delegate Return Item</param> /// <param name="addItemCallback">Delegate Call When Success Adding Item</param> /// <param name="canAddingItems">Delegate Check If Can Adding New Item</param> public void AddingItem(Func<string> getRandomItem, Action<string> addItemCallback, Predicate<int> canAddingItems) { if (canAddingItems(_itemCollection.Count)) { var item = getRandomItem(); _itemCollection.Add(item); addItemCallback(item); } else Console.WriteLine("Your inventory has reached max capacity"); } /// <summary> /// Method for delete item from inventory /// </summary> /// <param name="itemIndex">Item index that want to delete</param> public void DeleteItem(int itemIndex) { var itemName = _itemCollection[itemIndex]; _itemCollection.RemoveAt(itemIndex); _deleteItemCallback(itemIndex, itemName); } /// <summary> /// Method to show all item in inventory /// </summary> public void ShowAllItem() { Console.WriteLine(); Console.WriteLine("All items in inventory"); _itemCollection.ForEach(Console.WriteLine); } } }
37.263736
121
0.59304
[ "MIT" ]
lncodes/-csharp-delegate
src/Inventory/InventoryController.cs
3,393
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NFluentShould.cs" company="NFluent"> // Copyright 2018 Thomas PIERRAIN & Cyrille DUPUYDAUBY // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace NFluent.Tests { using System; using Extensibility; using NFluent.Helpers; using NUnit.Framework; [TestFixture(Category = "Obsolete")] public class CheckerShould { [Test] public void HelpToCreateAnErrorMessage() { var check = Check.That(2); var checker = ExtensibilityHelper.ExtractChecker(check); var message = checker.BuildMessage("general error"); Check.That(message).IsInstanceOf<FluentMessage>(); Check.That(message.ToString()).AsLines().ContainsExactly("", "general error", "The checked value:", "\t[2]"); } [Test] public void HandleProperlyNegationOnFailing() { var check = Check.That(2); var checker = ExtensibilityHelper.ExtractChecker(check.Not); checker.ExecuteNotChainableCheck(()=> throw ExceptionHelper.BuildException("oups"), "should have failed"); Check.ThatCode(() => checker.ExecuteNotChainableCheck(() => { }, "should have failed")) .IsAFailingCheck(); } [Test] public void OfferSimpleExtensibility() { var check = Check.That(2); var checker = ExtensibilityHelper.ExtractChecker(check); Check.ThatCode(() => { checker.ExecuteCheck(() => { }, "should not fail").And.IsEqualTo(3); }).IsAFailingCheck(); } [Test] public void HandleProperlyNonFailingChecksOnNonChainable() { var check = Check.That(2); ExtensibilityHelper.ExtractChecker(check).ExecuteNotChainableCheck(() => { }, "should have succeedeed"); Check.ThatCode(() => ExtensibilityHelper.ExtractChecker(check).ExecuteNotChainableCheck( () => throw ExceptionHelper.BuildException("failed"), "should fail")).IsAFailingCheck(); } [Test] public void LetUnknownExceptionGetThrough() { var check = Check.That(2); Check.ThatCode(() => ExtensibilityHelper.ExtractChecker(check) .ExecuteNotChainableCheck(() => throw new ArgumentException(), "should fails")) .Throws<ArgumentException>(); } [Test] public void SupportExecuteAndProvideSubItem() { var check = Check.That(2); Check.That( ExtensibilityHelper.ExtractChecker(check) .ExecuteCheckAndProvideSubItem(() => Check.That(2), "on negation")). InheritsFrom<ICheckLinkWhich<ICheck<int>, ICheck<int>>>(); } } }
39.5
121
0.543513
[ "Apache-2.0" ]
MendelMonteiro/NFluent
code/tests/NFluent.Tests/ForObsoleteStuff/CheckerShould.cs
3,699
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FieldTree2D_v2.Utilities { public static class Utils { public static Tuple<TObj, TVal> MinObj<TObj, TVal>(IEnumerable<TObj> objs, Func<TObj, TVal> func, IComparer<TVal> comparer = null) { if (objs == null) throw new ArgumentNullException("source"); if (func == null) throw new ArgumentNullException("selector"); comparer = comparer ?? Comparer<TVal>.Default; TObj minObj = default(TObj); TVal minVal = default(TVal); using (var iterator = objs.GetEnumerator()) { bool first_entry = true; while (iterator.MoveNext()) { var obj = iterator.Current; var val = func(obj); if (first_entry) { minObj = obj; minVal = val; first_entry = false; } if (comparer.Compare(val, minVal) < 0) { minObj = obj; minVal = val; } } } return Tuple.Create(minObj, minVal); } public static Dictionary<TObj, TVal> MinOrUpperBound<TObj, TVal>(IEnumerable<TObj> objs, Func<TObj, TVal> func, TVal upperBound, IComparer<TVal> comparer = null) { if (objs == null) throw new ArgumentNullException("source"); if (func == null) throw new ArgumentNullException("selector"); comparer = comparer ?? Comparer<TVal>.Default; Dictionary<TObj, TVal> answer = new Dictionary<TObj, TVal>(); if (objs == null || !objs.Any()) { return answer; } TObj minObj = default(TObj); TVal minVal = default(TVal); bool used = false; using (var iterator = objs.GetEnumerator()) { bool first_entry = true; while (iterator.MoveNext()) { var obj = iterator.Current; var val = func(obj); if (first_entry) { minObj = obj; minVal = val; first_entry = false; } if (comparer.Compare(val, upperBound) < 0) { minObj = obj; minVal = val; answer.Add(minObj, minVal); used = true; } else if (comparer.Compare(val, minVal) < 0) { minObj = obj; minVal = val; used = false; } } if (!used) { answer.Add(minObj, minVal); } } return answer; } public static Tuple<TObj, TVal> MaxObj<TObj, TVal>(IEnumerable<TObj> objs, Func<TObj, TVal> func, IComparer<TVal> comparer = null) { if (objs == null) throw new ArgumentNullException("source"); if (func == null) throw new ArgumentNullException("selector"); comparer = comparer ?? Comparer<TVal>.Default; TObj maxObj = default(TObj); TVal maxVal = default(TVal); using (var iterator = objs.GetEnumerator()) { bool first_entry = true; while (iterator.MoveNext()) { var obj = iterator.Current; var val = func(obj); if (first_entry) { maxObj = obj; maxVal = val; first_entry = false; } if (comparer.Compare(val, maxVal) > 0) { maxObj = obj; maxVal = val; } } } return Tuple.Create(maxObj, maxVal); } } }
31.731884
169
0.423156
[ "MIT" ]
AliveDevil/Fieldtree2D
FieldTree2D_v2/Utilities/Utils.cs
4,381
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 cloudfront-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DistributionList Object /// </summary> public class DistributionListUnmarshaller : IUnmarshaller<DistributionList, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public DistributionList Unmarshall(XmlUnmarshallerContext context) { DistributionList unmarshalledObject = new DistributionList(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("IsTruncated", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.IsTruncated = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Items/DistributionSummary", targetDepth)) { var unmarshaller = DistributionSummaryUnmarshaller.Instance; unmarshalledObject.Items.Add(unmarshaller.Unmarshall(context)); continue; } if (context.TestExpression("Marker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Marker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MaxItems", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MaxItems = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NextMarker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.NextMarker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Quantity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Quantity = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } private static DistributionListUnmarshaller _instance = new DistributionListUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DistributionListUnmarshaller Instance { get { return _instance; } } } }
38.913793
108
0.565574
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/DistributionListUnmarshaller.cs
4,514
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Configuration { /// <summary> /// An interface which can be bound to other <see cref="IBindable"/>s in order to watch for (and react to) <see cref="IBindable.Disabled"/> changes. /// </summary> public interface IBindable : IParseable, ICanBeDisabled, IHasDefaultValue, IUnbindable, IHasDescription { /// <summary> /// Binds outselves to another bindable such that we receive any value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindable them); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> IBindable GetBoundCopy(); } /// <summary> /// An interface which can be bound to other <see cref="IBindable{T}"/>s in order to watch for (and react to) <see cref="IBindable{T}.Disabled"/> and <see cref="IBindable{T}.Value"/> changes. /// </summary> /// <typeparam name="T">The type of value encapsulated by this <see cref="IBindable{T}"/>.</typeparam> public interface IBindable<T> : IParseable, ICanBeDisabled, IHasDefaultValue, IUnbindable, IHasDescription { /// <summary> /// An event which is raised when <see cref="Value"/> has changed. /// </summary> event Action<T> ValueChanged; /// <summary> /// The current value of this bindable. /// </summary> T Value { get; } /// <summary> /// The default value of this bindable. Used when querying <see cref="IBindable{T}.IsDefault"/>. /// </summary> T Default { get; } /// <summary> /// Binds outselves to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindable<T> them); /// <summary> /// Bind an action to <see cref="ValueChanged"/> with the option of running the bound action once immediately. /// </summary> /// <param name="onChange">The action to perform when <see cref="Value"/> changes.</param> /// <param name="runOnceImmediately">Whether the action provided in <see cref="onChange"/> should be run once immediately.</param> void BindValueChanged(Action<T> onChange, bool runOnceImmediately = false); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> IBindable<T> GetBoundCopy(); } }
49
196
0.630354
[ "MIT" ]
AtomCrafty/osu-framework
osu.Framework/Configuration/IBindable.cs
3,411
C#
/* * Coda API * * # Introduction The Coda API is a RESTful API that lets you programmatically interact with Coda docs: * List and search Coda docs * Create new docs and copy existing ones * Share and publish docs * Discover pages, tables, formulas, and controls * Read, insert, upsert, update, and delete rows Version 1 of the API will be supported until at least January 15, 2021. As we update and release newer versions of the API, we reserve the right to remove older APIs and functionality with a 3-month deprecation notice. We will post about such changes as well as announce new features in the [Developers Central](https://community.coda.io/c/developers-central) section of our Community, and update the [API updates](https://coda.io/api-updates) doc. # Getting Started Our [Getting Started Guide](https://coda.io/t/Getting-Started-Guide-Coda-API_toujpmwflfy) helps you learn the basic of working with the API and shows a few ways you can use it. Check it out, and learn how to: - Read data from Coda tables and write back to them - Build a one-way sync from one Coda doc to another - Automate reminders - Sync your Google Calendar to Coda # Using the API Coda's REST API is designed to be straightforward to use. You can use the language and platform of your choice to make requests. To get a feel for the API, you can also use a tool like [Postman](https://www.getpostman.com/) or [Insomnia](https://insomnia.rest/). ## API Endpoint This API uses a base path of `https://coda.io/apis/v1`. ## Resource IDs and Links Each resource instance retrieved via the API has the following fields: - `id`: The resource's immutable ID, which can be used to refer to it within its context - `type`: The type of resource, useful for identifying it in a heterogenous collection of results - `href`: A fully qualified URI that can be used to refer to and get the latest details on the resource Most resources can be queried by their name or ID. We recommend sticking with IDs where possible, as names are fragile and prone to being changed by your doc's users. ### List Endpoints Endpoints supporting listing of resources have the following fields: - `items`: An array containing the listed resources, limited by the `limit` and `pageToken` query parameters - `nextPageLink`: If more results are available, an API link to the next page of results - `nextPageToken`: If more results are available, a page token that can be passed into the `pageToken` query parameter **The maximum page size may change at any time, and may be different for different endpoints.** Please do not rely on it for any behavior of your application. If you pass a `limit` parameter that is larger than our maximum allowed limit, we will only return as many results as our maximum limit. You should look for the presence of the `nextPageToken` on the response to see if there are more results available, rather than relying on a result set that matches your provided limit. ### Doc IDs While most object IDs will have to be discovered via the API, you may find yourself frequently wanting to get the ID of a specific Coda doc. Here's a handy tool that will extract it for you. (See if you can find the pattern!) <form> <fieldset style=\"margin: 0px 25px 25px 25px; display: inline;\"> <legend>Doc ID Extractor</legend> <input type=\"text\" id=\"de_docUrl\" placeholder=\"Paste in a Coda doc URL\" style=\"width: 250px; padding: 8px; margin-right: 20px;\" /> <span> Your doc ID is:&nbsp;&nbsp;&nbsp; <input id=\"de_docId\" readonly=\"true\" style=\"width: 150px; padding: 8px; font-family: monospace; border: 1px dashed gray;\" /> </fieldset> </form> <script> (() => { const docUrl = document.getElementById('de_docUrl'); const docId = document.getElementById('de_docId'); docUrl.addEventListener('input', () => { docId.value = (docUrl.value.match(/_d([\\w-]+)/) || [])[1] || ''; }); docId.addEventListener('mousedown', () => docId.select()); docId.addEventListener('click', () => docId.select()); })(); </script> ## Rate Limiting The Coda API sets a reasonable limit on the number of requests that can be made per minute. Once this limit is reached, calls to the API will start returning errors with an HTTP status code of 429. If you find yourself hitting rate limits and would like your individual rate to be raised, please contact us at <help+api@coda.io>. ## Consistency While edits made in Coda are shared with other collaborators in real-time, it can take a few seconds for them to become available via the API. You may also notice that changes made via the API, such as updating a row, are not immediate. These endpoints all return an HTTP 202 status code, instead of a standard 200, indicating that the edit has been accepted and queued for processing. This generally takes a few seconds, and the edit may fail if invalid. Each such edit will return a `requestId` in the response, and you can pass this `requestId` to the [`#getMutationStatus`](#operation/getMutationStatus) endpoint to find out if it has been applied. ## Volatile Formulas Coda exposes a number of \"volatile\" formulas, as as `Today()`, `Now()`, and `User()`. When used in a live Coda doc, these formulas affect what's visible in realtime, tailored to the current user. Such formulas behave differently with the API. Time-based values may only be current to the last edit made to the doc. User-based values may be blank or invalid. ## Free and Paid Workspaces We make the Coda API available to all of our users free of charge, in both free and paid workspaces. However, API usage is subject to the role of the user associated with the API token in the workspace applicable to each API request. What this means is: - For the [`#createDoc`](#operation/createDoc) endpoint specifically, the owner of the API token must be a Doc Maker (or Admin) in the workspace. If the \"Any member can create docs\" option in enabled in the workspace settings, they can be an Editor and will get auto-promoted to Doc Maker upon using this endpoint. Lastly, if in addition, the API key owner matches the \"Approved email domains\" setting, they will be auto-added to the workspace and promoted to Doc Maker upon using this endpoint This behavior applies to the API as well as any integrations that may use it, such as Zapier. ## Examples To help you get started, this documentation provides code examples in Python, Unix shell, and Google Apps Script. These examples are based on a simple doc that looks something like this: ![](https://cdn.coda.io/external/img/api_example_doc.png) ### Python examples These examples use Python 3.6+. If you don't already have the `requests` module, use `pip` or `easy_install` to get it. ### Shell examples The shell examples are intended to be run in a Unix shell. If you're on Windows, you will need to install [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10). These examples use the standard cURL utility to pull from the API, and then process it with `jq` to extract and format example output. If you don't already have it, you can either [install it](https://stedolan.github.io/jq/) or run the command without it to see the raw JSON output. ### Google Apps Script examples ![](https://cdn.coda.io/external/img/api_gas.png) [Google Apps Script](https://script.google.com/) makes it easy to write code in a JavaScript-like syntax and easily access many Google products with built-in libraries. You can set up your scripts to run periodically, which makes it a good environment for writing tools without maintaining your own server. Coda provides a library for Google Apps Script. To use it, go into `Resources -> Libraries...` and enter the following library ID: `15IQuWOk8MqT50FDWomh57UqWGH23gjsWVWYFms3ton6L-UHmefYHS9Vl`. If you want to see the library's source code, it's available [here](https://script.google.com/d/15IQuWOk8MqT50FDWomh57UqWGH23gjsWVWYFms3ton6L-UHmefYHS9Vl/edit). Google provides autocomplete for API functions as well as generated docs. You can access these docs via the Libraries dialog by clicking on the library name. Required parameters that would be included in the URL path are positional arguments in each of these functions, followed by the request body, if applicable. All remaining parameters can be specified in the options object. ## OpenAPI/Swagger Spec In an effort to standardize our API and make it accessible, we offer an OpenAPI 3.0 specification: - [OpenAPI 3.0 spec - YAML](https://coda.io/apis/v1/openapi.yaml) - [OpenAPI 3.0 spec - JSON](https://coda.io/apis/v1/openapi.json) ### Swagger 2.0 We also offer a downgraded Swagger 2.0 version of our specification. This may be useful for a number of tools that haven't yet been adapted to OpenAPI 3.0. Here are the links: - [Swagger 2.0 spec - YAML](https://coda.io/apis/v1/swagger.yaml) - [Swagger 2.0 spec - JSON](https://coda.io/apis/v1/swagger.json) #### Postman collection To get started with prototyping the API quickly in Postman, you can use one of links above to import the Coda API into a collection. You'll then need to set the [appropriate header](#section/Authentication) and environment variables. ## Client libraries We do not currently support client libraries apart from Google Apps Script. To work with the Coda API, you can either use standard network libraries for your language, or use the appropriate Swagger Generator tool to auto-generate Coda API client libraries for your language of choice. We do not provide any guarantees that these autogenerated libraries are compatible with our API (e.g., some libraries may not work with Bearer authentication). ### OpenAPI 3.0 [Swagger Generator 3](https://generator3.swagger.io/) (that link takes you to the docs for the generator API) can generate client libraries for [these languages](https://generator3.swagger.io/v2/clients). It's relatively new and thus only has support for a limited set of languages at this time. ### Swagger 2.0 [Swagger Generator](https://generator.swagger.io/) takes in a legacy Swagger 2.0 specification, but can generate client libraries for [more languages](http://generator.swagger.io/api/gen/clients). You can also use local [CLI tools](https://swagger.io/docs/open-source-tools/swagger-codegen/) to generate these libraries. ### Third-party client libraries Some members of our amazing community have written libraries to work with our API. These aren't officially supported by Coda, but are listed here for convenience. (Please let us know if you've written a library and would like to have it included here.) - [PHP](https://github.com/danielstieber/CodaPHP) by Daniel Stieber - [Node-RED](https://github.com/serene-water/node-red-contrib-coda-io) by Mori Sugimoto - [NodeJS](https://www.npmjs.com/package/coda-js) by Parker McMullin - [Ruby](https://rubygems.org/gems/coda_docs/) by Carlos Muñoz at Monday.vc - [Python](https://github.com/Blasterai/codaio) by Mikhail Beliansky * * OpenAPI spec version: 1.0.0 * Contact: help+api@coda.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// List of tables. /// </summary> [DataContract] public partial class TableList : IEquatable<TableList>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="TableList" /> class. /// </summary> /// <param name="items">items (required).</param> /// <param name="href">API link to these results.</param> /// <param name="nextPageToken">nextPageToken.</param> /// <param name="nextPageLink">nextPageLink.</param> public TableList(List<TableReference> items = default(List<TableReference>), string href = default(string), NextPageToken nextPageToken = default(NextPageToken), AllOfTableListNextPageLink nextPageLink = default(AllOfTableListNextPageLink)) { // to ensure "items" is required (not null) if (items == null) { throw new InvalidDataException("items is a required property for TableList and cannot be null"); } else { this.Items = items; } this.Href = href; this.NextPageToken = nextPageToken; this.NextPageLink = nextPageLink; } /// <summary> /// Gets or Sets Items /// </summary> [DataMember(Name="items", EmitDefaultValue=false)] public List<TableReference> Items { get; set; } /// <summary> /// API link to these results /// </summary> /// <value>API link to these results</value> [DataMember(Name="href", EmitDefaultValue=false)] public string Href { get; set; } /// <summary> /// Gets or Sets NextPageToken /// </summary> [DataMember(Name="nextPageToken", EmitDefaultValue=false)] public NextPageToken NextPageToken { get; set; } /// <summary> /// Gets or Sets NextPageLink /// </summary> [DataMember(Name="nextPageLink", EmitDefaultValue=false)] public AllOfTableListNextPageLink NextPageLink { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TableList {\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append(" Href: ").Append(Href).Append("\n"); sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); sb.Append(" NextPageLink: ").Append(NextPageLink).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as TableList); } /// <summary> /// Returns true if TableList instances are equal /// </summary> /// <param name="input">Instance of TableList to be compared</param> /// <returns>Boolean</returns> public bool Equals(TableList input) { if (input == null) return false; return ( this.Items == input.Items || this.Items != null && input.Items != null && this.Items.SequenceEqual(input.Items) ) && ( this.Href == input.Href || (this.Href != null && this.Href.Equals(input.Href)) ) && ( this.NextPageToken == input.NextPageToken || (this.NextPageToken != null && this.NextPageToken.Equals(input.NextPageToken)) ) && ( this.NextPageLink == input.NextPageLink || (this.NextPageLink != null && this.NextPageLink.Equals(input.NextPageLink)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Items != null) hashCode = hashCode * 59 + this.Items.GetHashCode(); if (this.Href != null) hashCode = hashCode * 59 + this.Href.GetHashCode(); if (this.NextPageToken != null) hashCode = hashCode * 59 + this.NextPageToken.GetHashCode(); if (this.NextPageLink != null) hashCode = hashCode * 59 + this.NextPageLink.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
96.414365
11,013
0.679732
[ "MIT" ]
coda-hq/api-csharp-lib
src/IO.Swagger/Model/TableList.cs
17,452
C#
 using UnityEngine; public class GameStats : MonoBehaviour { public static int NumOfGems = 1; }
11.666667
40
0.704762
[ "MIT" ]
Jaxw501/ParkourKnightGame
ParkourKnight/Assets/#Script/LvlDesign/GameStats.cs
107
C#
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using Chat.Core.Dtos; using Chat.Core.Features.Chat.SendMessage; using Chat.Core.Infrastructure.Nats; using Chat.Core.Models; using Humanizer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Chat.Console { class Program { static async Task Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName) .AddJsonFile("appsettings.json", optional: false); IConfiguration config = builder.Build(); var host = CreateHostBuilder(args, config).Build(); var services = host.Services; var apiOption = services.GetRequiredService<APIOptions>(); var chatUiService = services.GetRequiredService<IChatUIService>(); var bus = services.GetRequiredService<INatsBus>(); var httpClientFactory = services.GetRequiredService<IHttpClientFactory>(); System.Console.WriteLine("Your user name:"); var userName = System.Console.ReadLine()?.Trim(); System.Console.WriteLine("Chat with user name:"); var targetUserName = System.Console.ReadLine()?.Trim(); System.Console.WriteLine("Chat Started."); System.Console.WriteLine(""); chatUiService.SubscribeOnChatMessage(userName, bus); await chatUiService.LoadReceivedMessages(userName, httpClientFactory, apiOption); while (true) { var inputMessage = System.Console.ReadLine(); await chatUiService.SendMessage(userName, targetUserName, inputMessage, httpClientFactory, apiOption); } } private static IHostBuilder CreateHostBuilder(string[] args, IConfiguration configuration) { return Host.CreateDefaultBuilder(args) .ConfigureLogging(config => { config.ClearProviders(); }) .ConfigureServices((_, services) => { services.AddTransient<INatsBus, NatsBus>() .AddTransient<IChatUIService, ChatUIService>() .AddOptions<NatsOptions>().Bind(configuration.GetSection("NatsOptions")) .ValidateDataAnnotations(); var apiOptions = configuration.GetSection("APIOptions").Get<APIOptions>(); services.AddSingleton(apiOptions); var baseAddress = apiOptions.BaseAddress; services.AddHttpClient("APIClient", config => { config.BaseAddress = new Uri(baseAddress); config.Timeout = new TimeSpan(0, 0, 30); config.DefaultRequestHeaders.Clear(); }); } ); } } }
40.493671
118
0.600188
[ "MIT" ]
meysamhadeli/Chat.Application
src/Chat.Console/Program.cs
3,201
C#
using MagicalLifeAPI.Filing.Logging; using MagicalLifeAPI.Networking.Serialization; using ProtoBuf; using System; using System.Collections.Generic; using System.IO; namespace MagicalLifeAPI.Networking { /// <summary> /// Used to buffer Protobuf-net (<see cref="BaseMessage"/>) messages correctly in order to handle a TCP connection. /// </summary> public class MessageBuffer { private List<byte> Buffer { get; set; } private int NextMessageLength = -1; public MessageBuffer() { this.Buffer = new List<byte>(); } /// <summary> /// Handles new data from the TCP connection. /// </summary> /// <param name="data"></param> public void ReceiveData(byte[] data) { this.Buffer.AddRange(data); if (NextMessageLength == -1) { this.CalculateNextMessageLength(); } } private void CalculateNextMessageLength() { if (this.Buffer.Count > 0) { ProtoBuf.Serializer.TryReadLengthPrefix(this.Buffer.ToArray(), 0, this.Buffer.Count, ProtoBuf.PrefixStyle.Base128, out this.NextMessageLength); } else { this.NextMessageLength = -1; } } /// <summary> /// Determines if there is a message to be taken. /// </summary> /// <returns></returns> public bool IsMessageAvailible() { return (this.NextMessageLength != -1 && this.NextMessageLength <= this.Buffer.Count); } /// <summary> /// Returns the next message. Returns null if no message is ready. /// </summary> /// <returns></returns> public BaseMessage GetMessageData() { BaseMessage data = null; if (this.NextMessageLength != -1 && this.NextMessageLength <= this.Buffer.Count) { using (MemoryStream ms = new MemoryStream(this.Buffer.ToArray())) { data = (BaseMessage)ProtoUtil.TypeModel.DeserializeWithLengthPrefix(ms, null, typeof(BaseMessage), PrefixStyle.Base128, 0); this.Buffer.RemoveRange(0, Convert.ToInt32(ms.Position)); //Remove the trailing 0s from the last message //The starting index of the next message int start = this.Buffer.FindIndex(x => x != 0); if (start == -1) { this.Buffer.Clear(); } else { this.Buffer.RemoveRange(0, start); } } MasterLog.DebugWriteLine("Message Buffer: " + this.Buffer.Count); this.CalculateNextMessageLength(); } return data; } } }
31.284211
159
0.520861
[ "MIT" ]
Lynngr/MagicalLife
MagicalLifeAPI/Networking/MessageBuffer.cs
2,974
C#
// <auto-generated /> using System; using MarginTrading.AssetService.SqlRepositories; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace MarginTrading.AssetService.SqlRepositories.Migrations { [DbContext(typeof(AssetDbContext))] [Migration("20200917123621_ProductLinks")] partial class ProductLinks { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("dbo") .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.AssetTypeEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("RegulatoryTypeId") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AssetTypes"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.AuditEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("CorrelationId") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DataDiff") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DataReference") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DataType") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Timestamp") .HasColumnType("datetime2"); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AuditTrail"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ClientProfileEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<string>("RegulatoryProfileId") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("ClientProfiles"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ClientProfileSettingsEntity", b => { b.Property<string>("ClientProfileId") .HasColumnType("nvarchar(450)"); b.Property<string>("AssetTypeId") .HasColumnType("nvarchar(450)"); b.Property<decimal>("ExecutionFeesCap") .HasColumnType("decimal(18,2)"); b.Property<decimal>("ExecutionFeesFloor") .HasColumnType("decimal(18,2)"); b.Property<decimal>("ExecutionFeesRate") .HasColumnType("decimal(18,2)"); b.Property<decimal>("FinancingFeesRate") .HasColumnType("decimal(18,2)"); b.Property<bool>("IsAvailable") .HasColumnType("bit"); b.Property<decimal>("Margin") .HasColumnType("decimal(18,2)"); b.Property<decimal>("OnBehalfFee") .HasColumnType("decimal(18,2)"); b.HasKey("ClientProfileId", "AssetTypeId"); b.HasIndex("AssetTypeId"); b.ToTable("ClientProfileSettings"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.CurrencyEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<int>("Accuracy") .HasColumnType("int"); b.Property<string>("InterestRateMdsCode") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<byte[]>("Timestamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnType("rowversion"); b.HasKey("Id"); b.ToTable("Currencies"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.MarketSettingsEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<TimeSpan>("Close") .HasColumnType("time"); b.Property<decimal>("Dividends871M") .HasColumnType("decimal(18,13)"); b.Property<decimal>("DividendsLong") .HasColumnType("decimal(18,13)"); b.Property<decimal>("DividendsShort") .HasColumnType("decimal(18,13)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(450)"); b.Property<TimeSpan>("Open") .HasColumnType("time"); b.Property<string>("Timezone") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("MarketSettings"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ProductCategoryEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("LocalizationToken") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("ParentId") .HasColumnType("nvarchar(400)"); b.Property<byte[]>("Timestamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnType("rowversion"); b.HasKey("Id"); b.HasIndex("ParentId"); b.ToTable("ProductCategories"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ProductEntity", b => { b.Property<string>("ProductId") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("AssetTypeId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<string>("CategoryId") .IsRequired() .HasColumnType("nvarchar(400)"); b.Property<string>("Comments") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<int>("ContractSize") .HasColumnType("int") .HasMaxLength(400); b.Property<string>("ForceId") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("FreezeInfo") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<bool>("IsDiscontinued") .HasColumnType("bit"); b.Property<bool>("IsFrozen") .HasColumnType("bit"); b.Property<bool>("IsSuspended") .HasColumnType("bit"); b.Property<string>("IsinLong") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("IsinShort") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("Issuer") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("Keywords") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("MarketId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<string>("MarketMakerAssetAccountId") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<int>("MaxOrderSize") .HasColumnType("int"); b.Property<int>("MaxPositionSize") .HasColumnType("int"); b.Property<decimal>("MinOrderDistancePercent") .HasColumnType("decimal(18,2)"); b.Property<decimal>("MinOrderEntryInterval") .HasColumnType("decimal(18,2)"); b.Property<int>("MinOrderSize") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("NewsId") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<decimal>("OvernightMarginMultiplier") .HasColumnType("decimal(18,2)"); b.Property<int>("Parity") .HasColumnType("int"); b.Property<string>("PublicationRic") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("SettlementCurrency") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<bool>("ShortPosition") .HasColumnType("bit"); b.Property<string>("Tags") .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.Property<string>("TickFormulaId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<byte[]>("Timestamp") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnType("rowversion"); b.Property<string>("TradingCurrencyId") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<string>("UnderlyingMdsCode") .IsRequired() .HasColumnType("nvarchar(400)") .HasMaxLength(400); b.HasKey("ProductId"); b.HasIndex("AssetTypeId"); b.HasIndex("CategoryId"); b.HasIndex("MarketId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("TickFormulaId"); b.HasIndex("TradingCurrencyId"); b.ToTable("Products"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.TickFormulaEntity", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("PdlLadders") .HasColumnType("nvarchar(max)"); b.Property<string>("PdlTicks") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("TickFormulas"); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ClientProfileSettingsEntity", b => { b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.AssetTypeEntity", "AssetType") .WithMany() .HasForeignKey("AssetTypeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.ClientProfileEntity", "ClientProfile") .WithMany() .HasForeignKey("ClientProfileId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.MarketSettingsEntity", b => { b.OwnsMany("MarginTrading.AssetService.SqlRepositories.Entities.HolidayEntity", "Holidays", b1 => { b1.Property<DateTime>("Date") .HasColumnType("datetime2"); b1.Property<string>("MarketSettingsId") .HasColumnType("nvarchar(450)"); b1.HasKey("Date", "MarketSettingsId"); b1.HasIndex("MarketSettingsId"); b1.ToTable("Holidays"); b1.WithOwner() .HasForeignKey("MarketSettingsId"); }); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ProductCategoryEntity", b => { b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.ProductCategoryEntity", "Parent") .WithMany("Children") .HasForeignKey("ParentId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("MarginTrading.AssetService.SqlRepositories.Entities.ProductEntity", b => { b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.AssetTypeEntity", "AssetType") .WithMany() .HasForeignKey("AssetTypeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.ProductCategoryEntity", "Category") .WithMany("Products") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.MarketSettingsEntity", "Market") .WithMany() .HasForeignKey("MarketId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.TickFormulaEntity", "TickFormula") .WithMany() .HasForeignKey("TickFormulaId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("MarginTrading.AssetService.SqlRepositories.Entities.CurrencyEntity", "TradingCurrency") .WithMany() .HasForeignKey("TradingCurrencyId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); #pragma warning restore 612, 618 } } }
38.463519
125
0.461783
[ "MIT-0" ]
LykkeBusiness/MarginTrading.AssetService
src/MarginTrading.AssetService.SqlRepositories/Migrations/20200917123621_ProductLinks.Designer.cs
17,926
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LlegarMeta : MonoBehaviour { UserInterface ui; public int gananciaMaxima = 100; public bool Obligatorio = false; public int zonaActual; private void Start() { ui = GameObject.FindObjectOfType<UserInterface>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "Player") { ui.gananciaMaxBK = gananciaMaxima; collision.GetComponent<Player>().Win(); GameManager.instance.VictoryCondition(); if (Obligatorio) { FindObjectOfType<CutsceneManager>().obli = true; GameManager.instance.UnlockZone(zonaActual); } gameObject.SetActive(false); } } }
23.891892
64
0.587104
[ "MIT" ]
ClaraLongo/HermanosMariano_Longo
Assets/Scripts/Condiciones/LlegarMeta.cs
886
C#
//--------------------------------------------------------------------------------------- // Copyright 2014 North Carolina State University // // Center for Educational Informatics // http://www.cei.ncsu.edu/ // // 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; using System.Collections.Generic; namespace IntelliMedia { public class CourseSettingsService { private AppSettings appSettings; public CourseSettingsService(AppSettings appSettings) { this.appSettings = appSettings; } public AsyncTask LoadSettings(string studentId) { return new AsyncTask((prevResult, onCompleted, onError) => { try { Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute); Uri restUri = new Uri(serverUri, "rest/"); CourseSettingsRepository repo = new CourseSettingsRepository(restUri); if (repo == null) { throw new Exception("CourseSettingsRepository is not initialized."); } repo.GetByKey("studentid/", studentId, (CourseSettingsRepository.Response response) => { if (response.Success) { onCompleted(response.Item); } else { onError(new Exception(response.Error)); } }); } catch (Exception e) { onError(e); } }); } } }
34.705128
91
0.664573
[ "BSD-2-Clause" ]
wangfei1988/TicTacToe
Assets/IntelliMediaCore/Source/Services/CourseSettingsService.cs
2,709
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zoologico { class Program { static void Main(string[] args) { FabricaMamiferos fabricamamiferos = new FabricaMamiferos(); } } }
16.35
71
0.611621
[ "Apache-2.0" ]
Yah-veh/ProgramacionIIIMLYL
Unidad4/Zoologico/Zoologico/Program.cs
329
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace HSoft.ClientManager.WCFService { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
25.956522
99
0.59799
[ "MIT" ]
renehugentobler/ClientManager
HSoft.ClientManager.WCFService/App_Start/RouteConfig.cs
599
C#
namespace Apex.Datacloud { using ApexSharp; using ApexSharp.ApexAttributes; using ApexSharp.Implementation; using global::Apex.System; /// <summary> /// https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Datacloud_FindDuplicates.htm#apex_class_Datacloud_FindDuplicates /// </summary> public class FindDuplicates { // infrastructure public FindDuplicates(dynamic self) { Self = self; } dynamic Self { get; set; } static dynamic Implementation { get { return Implementor.GetImplementation(typeof(FindDuplicates)); } } // API public static List<FindDuplicatesResult> findDuplicates(List<SObject> sObjects) { return Implementation.findDuplicates(sObjects); } public FindDuplicates() { Self = Implementation.Constructor(); } public object clone() { return Self.clone(); } } }
23.782609
156
0.579525
[ "MIT" ]
apexsharp/apexsharp
Apex/Datacloud/FindDuplicates.cs
1,094
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("HelloName")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HelloName")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0e8c9a12-7f94-4e6d-8bea-6d382b3fcdf5")] // 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")]
37.594595
84
0.744069
[ "MIT" ]
Shtereva/Fundamentals-with-CSharp
MethodsExercises/HelloName/Properties/AssemblyInfo.cs
1,394
C#
// Copyright (c) Piotr Stenke. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Durian.TestServices { /// <summary> /// A builder of the <see cref="GeneratorDriverRunResult"/> class. /// </summary> public sealed class GeneratorDriverRunResultBuilder { private readonly List<GeneratorRunResultBuilder> _childBuilders; private readonly List<GeneratorRunResult> _results; /// <summary> /// Initializes a new instance of the <see cref="GeneratorRunResultBuilder"/> class. /// </summary> public GeneratorDriverRunResultBuilder() { _results = new List<GeneratorRunResult>(); _childBuilders = new(); } /// <summary> /// Initializes a new instance of the <see cref="GeneratorRunResultBuilder"/> class. /// </summary> /// <param name="results">A collection of <see cref="GeneratorRunResult"/>s to be used when creating the <see cref="GeneratorDriverRunResult"/>.</param> public GeneratorDriverRunResultBuilder(IEnumerable<GeneratorRunResult>? results) { if (results is null) { _results = new(); } else { _results = new(results); } _childBuilders = new(); } /// <summary> /// Adds a new <see cref="GeneratorRunResult"/> to the <see cref="GeneratorDriverRunResult.Results"/> collection. /// </summary> /// <param name="result">A <see cref="GeneratorRunResult"/> to be added to the <see cref="GeneratorDriverRunResult.Results"/> collection.</param> /// <returns>This <see cref="GeneratorDriverRunResultBuilder"/>.</returns> public GeneratorDriverRunResultBuilder AddResult(in GeneratorRunResult result) { _results.Add(result); return this; } /// <summary> /// Adds a new <see cref="GeneratorRunResult"/> created from the provided data to the <see cref="GeneratorDriverRunResult.Results"/> collection. /// </summary> /// <param name="generator">A <see cref="ISourceGenerator"/> to be set to the <see cref="GeneratorRunResult.Generator"/> property.</param> /// <param name="generatedSources">A collection of <see cref="GeneratedSourceResult"/>s to be set to the <see cref="GeneratorRunResult.GeneratedSources"/> property.</param> /// <param name="diagnostics">A collection of <see cref="Diagnostic"/>s to be set to the <see cref="GeneratorRunResult.Diagnostics"/> property.</param> /// <param name="exception">An <see cref="Exception"/> to be set to the <see cref="GeneratorRunResult.Exception"/> property.</param> /// <exception cref="ArgumentNullException"><paramref name="generator"/> is <see langword="null"/>.</exception> /// <returns>This <see cref="GeneratorDriverRunResultBuilder"/>.</returns> public GeneratorDriverRunResultBuilder AddResult(ISourceGenerator generator, IEnumerable<GeneratedSourceResult>? generatedSources, IEnumerable<Diagnostic>? diagnostics, Exception? exception) { _results.Add(GeneratorResultFactory.CreateGeneratorResult(generator, generatedSources, diagnostics, exception)); return this; } /// <summary> /// Adds a range of <see cref="GeneratorRunResult"/>s to the <see cref="GeneratorDriverRunResult.Results"/> collection. /// </summary> /// <param name="generatedSources">A range <see cref="GeneratorRunResult"/>s to be added to the <see cref="GeneratorDriverRunResult.Results"/> collection.</param> /// <returns>This <see cref="GeneratorDriverRunResultBuilder"/>.</returns> public GeneratorDriverRunResultBuilder AddResults(IEnumerable<GeneratorRunResult>? generatedSources) { if (generatedSources is not null) { _results.AddRange(generatedSources); } return this; } /// <summary> /// Begins building a new <see cref="GeneratorRunResult"/>. /// </summary> public GeneratorRunResultBuilder BeginResult() { return new() { _parent = this }; } /// <summary> /// Actually creates the <see cref="GeneratorDriverRunResult"/>. /// </summary> public GeneratorDriverRunResult Build() { return GeneratorResultFactory.CreateDriverResult(_results); } /// <summary> /// Resets the builder. /// </summary> public void Reset() { _results.Clear(); foreach (GeneratorRunResultBuilder child in _childBuilders) { child._parent = null; } _childBuilders.Clear(); } /// <summary> /// Assigns a new collection of <see cref="GeneratorRunResult"/>s to the <see cref="GeneratorDriverRunResult.Results"/> property. /// </summary> /// <param name="results">A collection of <see cref="GeneratorRunResult"/>s to be set to the <see cref="GeneratorDriverRunResult.Results"/> property.</param> /// <returns>This <see cref="GeneratorDriverRunResultBuilder"/>.</returns> public GeneratorDriverRunResultBuilder WithResults(IEnumerable<GeneratorRunResult>? results) { if (results is not null) { _results.AddRange(results); } return this; } } }
35.5
192
0.714227
[ "MIT" ]
piotrstenke/Durian
src/Durian.TestServices/GeneratorDriverRunResultBuilder.cs
4,899
C#
//****************************************************************************************************** // IChannelCellCollection.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 02/18/2005 - J. Ritchie Carroll // Generated original version of source code. // 08/07/2009 - Josh L. Patterson // Edited Comments. // 09/15/2009 - Stephen C. Wills // Added new header and license agreement. // 10/5/2012 - Gavin E. Holden // Added new header and license agreement. // 12/17/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** namespace GSF.PhasorProtocols { /// <summary> /// Represents a protocol independent interface representation of a collection of <see cref="IChannelCell"/> objects. /// </summary> /// <typeparam name="T">Generic type used.</typeparam> public interface IChannelCellCollection<T> : IChannelCollection<T> where T : IChannelCell { /// <summary> /// Gets flag that determines if the lengths of <see cref="IChannelCell"/> elements in this <see cref="IChannelCellCollection{T}"/> are constant. /// </summary> bool ConstantCellLength { get; } } }
47.565217
153
0.600548
[ "MIT" ]
QuarkSoftware/gsf
Source/Libraries/GSF.PhasorProtocols/IChannelCellCollection.cs
2,189
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.Razor.Serialization; using Microsoft.VisualStudio.LanguageServices.Razor.Serialization; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.Razor { internal static class JsonConverterCollectionExtensions { public static JsonConverterCollection RegisterRazorConverters(this JsonConverterCollection collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } collection.Add(TagHelperDescriptorJsonConverter.Instance); collection.Add(RazorDiagnosticJsonConverter.Instance); collection.Add(RazorExtensionJsonConverter.Instance); collection.Add(RazorConfigurationJsonConverter.Instance); collection.Add(ProjectSnapshotHandleJsonConverter.Instance); return collection; } } }
35.566667
110
0.717901
[ "MIT" ]
dougbu/razor-tooling
src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Serialization/JsonConverterCollectionExtensions.cs
1,069
C#
using Microsoft.Research.SEAL; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace UWPMPProjectTests { [TestClass] public class TestLogisticRegression { [TestMethod] public void TestLogisticRegressionBinaryClassification_NoEncryption() { // these are the feature sets we will be encrypting and getting // the ML model results on along with the expected truth values of the ML model double[][] testX = new double[6][]; testX[0] = new double[] { 1, 1, 0, 0, 0, 1, 1, 0, 0, 1 }; testX[1] = new double[] { 1, 0, 1, 0, 1, 1, 0, 1, 0, 1 }; testX[2] = new double[] { 0, 1, 0, 0, 0, 1, 0, 1, 1, 0 }; testX[3] = new double[] { 0, 1, 1, 0, 1, 1, 1, 1, 0, 0 }; testX[4] = new double[] { 0, 1, 0, 1, 1, 1, 0, 0, 1, 1 }; testX[5] = new double[] { 1, 0, 1, 1, 0, 1, 0, 0, 0, 1 }; double[] testY = { 0, 0, 0, 1, 1, 1 }; bool[] expectedModelResults = { false, false, true, true, true, true }; // This is the 'evaluator' section // this is not a part of the client and would, in a cloud based solution, be run on the server // the server should not know the values of the input features, but it will do math on them double[] weights = {-0.0448429813505995, 0.22603459546040847, 0.8256180461493858, 2.970324762165545, -0.0022260364010428055, -0.27601604216924047, 0.7643519117530984, 0.552635425157094, -0.18622044388306305, -2.2604158458243537}; List<double> scores = new List<double>(); for (int i = 0; i < testX.Length; i++) { double[] xFeatures = testX[i]; double expectedY = testY[i]; var score = 0.0; for (int j = 0; j < xFeatures.Length; j++) { score += weights[j] * xFeatures[j]; } score = 1.0 / (1.0 + Math.Exp(-1.0 * score)); scores.Add(score); } List<bool> predictions = scores.Select(score => score > 0.5).ToList(); for (int i = 0; i < predictions.Count; i++) { Assert.AreEqual(predictions[i], expectedModelResults[i]); } } } }
38.661765
106
0.495626
[ "MIT" ]
randomguy7531/SEAL
UWPMPProjectTests/TestLogisticRegression.cs
2,629
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; using Azure.ResourceManager.Resources; using Azure.Core.TestFramework; using Azure.ResourceManager.EventHubs.Models; using Azure.ResourceManager.EventHubs; using Azure.ResourceManager.EventHubs.Tests.Helpers; namespace Azure.ResourceManager.EventHubs.Tests { public class SchemaGroupTests : EventHubTestBase { public SchemaGroupTests(bool isAsync): base(isAsync) { } private ResourceGroup _resourceGroup; private SchemaGroupCollection _schemaGroupCollection; [SetUp] public async Task CreateNamespaceAndGetEventhubCollection() { _resourceGroup = await CreateResourceGroupAsync(); string namespaceName = await CreateValidNamespaceName("testnamespacemgmt"); EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces(); EventHubNamespace eHNamespace = (await namespaceCollection.CreateOrUpdateAsync(namespaceName, new EventHubNamespaceData(DefaultLocation))).Value; _schemaGroupCollection = eHNamespace.GetSchemaGroups(); } [TearDown] public async Task ClearNamespaces() { //remove all namespaces under current resource group if (_resourceGroup != null) { EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces(); List<EventHubNamespace> namespaceList = await namespaceCollection.GetAllAsync().ToEnumerableAsync(); foreach (EventHubNamespace eventHubNamespace in namespaceList) { await eventHubNamespace.DeleteAsync(); } _resourceGroup = null; } } [Test] [RecordedTest] [Ignore("get and list not working")] public async Task CreateDeleteSchemaGroup() { //create schema group string schemaGroupName = Recording.GenerateAssetName("schemagroup"); SchemaGroupData parameters = new SchemaGroupData() { SchemaType = SchemaType.Avro }; SchemaGroup schemaGroup = (await _schemaGroupCollection.CreateOrUpdateAsync(schemaGroupName, parameters)).Value; Assert.NotNull(schemaGroup); Assert.AreEqual(schemaGroupName, schemaGroup.Id.Name); //validate if created successfully schemaGroup = await _schemaGroupCollection.GetIfExistsAsync(schemaGroupName); Assert.NotNull(schemaGroup); Assert.IsTrue(await _schemaGroupCollection.CheckIfExistsAsync(schemaGroupName)); //delete eventhub await schemaGroup.DeleteAsync(); //validate schemaGroup = await _schemaGroupCollection.GetIfExistsAsync(schemaGroupName); Assert.Null(schemaGroup); Assert.IsFalse(await _schemaGroupCollection.CheckIfExistsAsync(schemaGroupName)); } [Test] [RecordedTest] [Ignore("get and list not working")] public async Task GetAllSchemaGroups() { //create a schema group string schemaGroupName1 = Recording.GenerateAssetName("schemagroup1"); SchemaGroupData parameters = new SchemaGroupData() { SchemaType = SchemaType.Avro }; _ = (await _schemaGroupCollection.CreateOrUpdateAsync(schemaGroupName1, parameters)).Value; //validate int count = 0; SchemaGroup schemaGroup1 = null; await foreach (SchemaGroup schemaGroup in _schemaGroupCollection.GetAllAsync()) { count++; if (schemaGroup.Id.Name == schemaGroupName1) schemaGroup1 = schemaGroup; } } } }
40.049505
157
0.648208
[ "MIT" ]
LeiWang3/azure-sdk-for-net
sdk/eventhub/Azure.ResourceManager.EventHubs/tests/Tests/SchemaGroupTests.cs
4,047
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Runtime.InteropServices; using System.Text; namespace Mozilla.Glean.FFI { internal static class LibGleanFFI { private const string SharedGleanLibrary = "glean_ffi"; // Define the order of fields as laid out in memory. // **CAUTION**: This must match _exactly_ the definition on the Rust side. // If this side is changed, the Rust side need to be changed, too. [StructLayout(LayoutKind.Sequential)] internal class FfiConfiguration { public string data_dir; public string package_name; public bool upload_enabled; public Int32? max_events; public bool delay_ping_lifetime_io; } /// <summary> /// A base handle class meant to be extended by the different metric types to allow /// for calling metric specific clearing functions. /// </summary> internal class BaseGleanHandle : SafeHandle { public BaseGleanHandle() : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { // Note: this is meant to be implemented by the inheriting class in order to // provide a specific cleanup action. return false; } } internal class StringAsReturnValue : SafeHandle { public StringAsReturnValue() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } public string AsString() { int len = 0; while (Marshal.ReadByte(handle, len) != 0) { ++len; } byte[] buffer = new byte[len]; Marshal.Copy(handle, buffer, 0, buffer.Length); return Encoding.UTF8.GetString(buffer); } protected override bool ReleaseHandle() { if (!this.IsInvalid) { Console.WriteLine("Freeing string handle"); glean_str_free(handle); } return true; } } // Glean top-level API. [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_initialize(FfiConfiguration cfg); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_clear_application_lifetime_metrics(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_set_dirty_flag(byte flag); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_is_dirty_flag_set(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_test_clear_all_stores(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_is_first_run(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_destroy_glean(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_on_ready_to_submit_pings(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_enable_logging(); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_set_upload_enabled(bool flag); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_is_upload_enabled(); // TODO: add the rest of the ffi. // String /// <summary> /// A handle for the string metric type, which performs cleanup. /// </summary> internal sealed class StringMetricTypeHandle : BaseGleanHandle { protected override bool ReleaseHandle() { if (!this.IsInvalid) { Console.WriteLine("Freeing string metric type handle"); glean_destroy_string_metric(handle); } return true; } } [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern StringMetricTypeHandle glean_new_string_metric( string category, string name, string[] send_in_pings, Int32 send_in_pings_len, Int32 lifetime, bool disabled ); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_destroy_string_metric(IntPtr handle); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_string_set(StringMetricTypeHandle metric_id, string value); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern StringAsReturnValue glean_string_test_get_value(StringMetricTypeHandle metric_id, string storage_name); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern byte glean_string_test_has_value(StringMetricTypeHandle metric_id, string storage_name); [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern Int32 glean_string_test_get_num_recorded_errors( StringMetricTypeHandle metric_id, Int32 error_type, string storage_name ); // Misc [DllImport(SharedGleanLibrary, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] internal static extern void glean_str_free(IntPtr ptr); } }
40.623529
134
0.650738
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
mdboom/glean.rs
glean-core/csharp/Glean/LibGleanFFI.cs
6,908
C#
// // ServicePointManager.cs // // Author: // Rolf Bjarne Kvinge <rolf@xamarin.com> // // Copyright (c) 2016 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Net.Security; namespace System.Net { public partial class ServicePointManager { const string EXCEPTION_MESSAGE = "System.Net.ServicePointManager is not supported on the current platform."; public const int DefaultNonPersistentConnectionLimit = 4; #if MOBILE public const int DefaultPersistentConnectionLimit = 10; #else public const int DefaultPersistentConnectionLimit = 2; #endif private ServicePointManager () { } public static ICertificatePolicy CertificatePolicy { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static bool CheckCertificateRevocationList { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static int DefaultConnectionLimit { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static int DnsRefreshTimeout { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static bool EnableDnsRoundRobin { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static int MaxServicePointIdleTime { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static int MaxServicePoints { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static bool ReusePort { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static SecurityProtocolType SecurityProtocol { get; set; } = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; public static RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; } public static EncryptionPolicy EncryptionPolicy { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static bool Expect100Continue { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static bool UseNagleAlgorithm { get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval) { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } public static ServicePoint FindServicePoint (Uri address) { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy) { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy) { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); } } }
35.330769
110
0.773351
[ "BSD-3-Clause" ]
Gravelbones/javacc21
examples/csharp/testfiles/ServicePointManager.platformnotsupported.cs
4,593
C#
using System; using System.ComponentModel.DataAnnotations; using System.Net; using Core; using Core.Exceptions; using Core.Serialization.Newtonsoft; using Core.WebApi.Middlewares.ExceptionHandling; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Converters; using SmartHome.Temperature; namespace SmartHome.Api; public class Startup { private readonly IConfiguration config; public Startup(IConfiguration config) { this.config = config; } public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddNewtonsoftJson(opt => opt.SerializerSettings.WithDefaults()); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SmartHome", Version = "v1"}); }); services.AddCoreServices(); services.AddTemperaturesModule(config); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseExceptionHandlingMiddleware(exception => exception switch { AggregateNotFoundException _ => HttpStatusCode.NotFound, _ => HttpStatusCode.InternalServerError }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Meeting Management V1"); c.RoutePrefix = string.Empty; }); } }
25.805556
86
0.673843
[ "MIT" ]
Allann/EventSourcing.NetCore
Sample/AsyncProjections/SmartHome.Api/Startup.cs
1,858
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 Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class FullSolutionAnalysisOptionBinding { private readonly IOptionService _optionService; private readonly string _languageName; private readonly Option<bool> _fullSolutionAnalysis; private readonly PerLanguageOption<bool?> _closedFileDiagnostics; public FullSolutionAnalysisOptionBinding(IOptionService optionService, string languageName) { _optionService = optionService; _languageName = languageName; _fullSolutionAnalysis = RuntimeOptions.FullSolutionAnalysis; _closedFileDiagnostics = ServiceFeatureOnOffOptions.ClosedFileDiagnostic; } public bool Value { get { return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_optionService.GetOptions(), _languageName) && _optionService.GetOption(_fullSolutionAnalysis); } set { var oldOptions = _optionService.GetOptions(); // set normal option first var newOptions = oldOptions.WithChangedOption(_closedFileDiagnostics, _languageName, value); // we only enable this option if it is disabled. we never disable this option here. if (value) { newOptions = newOptions.WithChangedOption(_fullSolutionAnalysis, value); } _optionService.SetOptions(newOptions); OptionLogger.Log(oldOptions, newOptions); } } } }
36.865385
161
0.653625
[ "Apache-2.0" ]
AArnott/roslyn
src/VisualStudio/Core/Impl/Options/FullSolutionAnalysisOptionBinding.cs
1,919
C#
using System; using System.Linq; using Telerik.Core; using Telerik.Data.Core; using Telerik.UI.Xaml.Controls.Primitives; namespace Telerik.UI.Xaml.Controls.Data { internal class ListViewVisualStateService : ServiceBase<RadListView> { private DataProviderStatus dataStatus; private WeakReferenceList<IDataStatusListener> registeredDataLoadingListeners; internal ListViewVisualStateService(RadListView owner) : base(owner) { this.registeredDataLoadingListeners = new WeakReferenceList<IDataStatusListener>(); } internal void UpdateDataLoadingStatus(DataProviderStatus status) { this.dataStatus = status; foreach (var listener in this.registeredDataLoadingListeners) { listener.OnDataStatusChanged(status); } } internal void RegisterDataLoadingListener(IDataStatusListener listener) { if (!this.registeredDataLoadingListeners.Contains(listener)) { this.registeredDataLoadingListeners.Add(listener); } listener.OnDataStatusChanged(this.dataStatus); } internal void UnregisterDataLoadingListener(IDataStatusListener listener) { this.registeredDataLoadingListeners.Remove(listener); listener.OnDataStatusChanged(DataProviderStatus.Uninitialized); } } }
32.044444
95
0.677531
[ "Apache-2.0" ]
JackWangCUMT/UI-For-UWP
Controls/DataControls/DataControls.UWP/ListView/View/Services/ListViewVisualStateService.cs
1,444
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace WesternStatesWater.WaDE.Accessors.Tests { [TestClass] public class DtoMapper { [TestMethod] public void ConfigurationIsValid() { Mapping.DtoMapper.Configuration.AssertConfigurationIsValid(); } } }
21.333333
73
0.671875
[ "BSD-3-Clause" ]
WSWCWaterDataExchange/WaDE2.0
source/WesternStatesWater.WaDE.Accessors.Tests/DtoMapper.cs
320
C#
using System.Threading.Tasks; namespace ServerlessPersistence { public interface IHighScoreOperations { void Add(int points); void Reset(); } }
15.727273
41
0.66474
[ "MIT" ]
marcduiker/demos-serverless-persistence
src/ServerlessPersistence/DurableEntity/IHighScoreOperations.cs
173
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SceneChanger : MonoBehaviour { public static SceneChanger instance; // Use this for initialization void Start () { /*if (instance == null) { instance = this; DontDestroyOnLoad(this); } else { Destroy(gameObject); }*/ } // Update is called once per frame void Update () { } public void LoadScene(string scene) { SceneManager.LoadScene(scene); } }
14.828571
41
0.691715
[ "Unlicense" ]
paosalcedo/CoMix
AR Final/Assets/Scripts/SceneChanger.cs
521
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Immutable; namespace LocalisationAnalyser.Localisation { /// <summary> /// Represents a localisation method or member within a <see cref="LocalisationFile"/>. /// </summary> public class LocalisationMember : IEquatable<LocalisationMember> { /// <summary> /// The name. /// </summary> public readonly string Name; /// <summary> /// The key to use for lookups. /// </summary> public readonly string Key; /// <summary> /// The english default text. This is also used for the XMLDoc. /// </summary> public readonly string EnglishText; /// <summary> /// Any parameters. If this is non-empty, the <see cref="LocalisationMember"/> represents a method. /// </summary> public readonly ImmutableArray<LocalisationParameter> Parameters; /// <summary> /// Creates a new <see cref="LocalisationMember"/>. /// </summary> /// <param name="name">The name.</param> /// <param name="key">The localisation key to use for lookups.</param> /// <param name="englishText">The english default text. This is also used for the XMLDoc.</param> /// <param name="parameters">Any parameters. If this is non-empty, the <see cref="LocalisationMember"/> will represent a method.</param> public LocalisationMember(string name, string key, string englishText, params LocalisationParameter[] parameters) { Name = name; Key = key; EnglishText = englishText; Parameters = parameters.ToImmutableArray(); } public bool Equals(LocalisationMember? other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Name == other.Name && Key == other.Key && EnglishText == other.EnglishText && Parameters.Equals(other.Parameters); } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((LocalisationMember)obj); } public override int GetHashCode() => HashCode.Combine(Name, Key, EnglishText, Parameters); } }
37.246377
144
0.613619
[ "MIT" ]
smoogipoo/osu-localisation-analyser
LocalisationAnalyser/Localisation/LocalisationMember.cs
2,570
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using SFA.DAS.Reservations.Domain.Configuration; using SFA.DAS.Reservations.Domain.Infrastructure.ElasticSearch; using SFA.DAS.Reservations.Domain.Reservations; namespace SFA.DAS.Reservations.Data.Repository { public class ReservationIndexRepository : IReservationIndexRepository { public string IndexNamePrefix { get; } private readonly IElasticLowLevelClientWrapper _client; private readonly IIndexRegistry _registry; private readonly IElasticSearchQueries _elasticSearchQueries; public ReservationIndexRepository(IElasticLowLevelClientWrapper client, IIndexRegistry registry, IElasticSearchQueries elasticSearchQueries, ReservationJobsEnvironment environment) { IndexNamePrefix = $"{environment.EnvironmentName}-reservations-"; _client = client; _registry = registry; _elasticSearchQueries = elasticSearchQueries; } public async Task Add(IEnumerable<IndexedReservation> reservations) { var listOfJsonReservations = new List<string>(); foreach (var reservation in reservations) { listOfJsonReservations.Add(@"{ ""index"":{""_id"":""" + reservation.Id + @"""} }"); listOfJsonReservations.Add(JsonConvert.SerializeObject(reservation)); } var reservationBatches = BatchReservationDocs(listOfJsonReservations); foreach (var batch in reservationBatches) { await _client.CreateMany(_registry.CurrentIndexName, batch); } } public async Task DeleteIndices(uint daysOld) { await _registry.DeleteOldIndices(daysOld); } public async Task SaveReservationStatus(Guid id, ReservationStatus status) { var query = _elasticSearchQueries.UpdateReservationStatus.Replace("{status}",((short)status).ToString()) .Replace("{reservationId}",id.ToString()); await _client.UpdateByQuery(_registry.CurrentIndexName, query); } public async Task DeleteReservationsFromIndex(uint ukPrn, long accountLegalEntityId) { var query = _elasticSearchQueries.DeleteReservationsByQuery .Replace("{ukPrn}", ukPrn.ToString()) .Replace("{accountLegalEntityId}", accountLegalEntityId.ToString()); await _client.DeleteByQuery(_registry.CurrentIndexName, query); } public async Task CreateIndex() { var indexName = IndexNamePrefix + Guid.NewGuid(); var mapping = _elasticSearchQueries.ReservationIndexMapping; await _client.CreateIndicesWithMapping(indexName, mapping); await _registry.Add(indexName); } private static IEnumerable<IEnumerable<string>> BatchReservationDocs(List<string> listOfJsonReservations) { var maxItems = 10000; return listOfJsonReservations.Select((item, inx) => new { item, inx }) .GroupBy(x => x.inx / maxItems) .Select(g => g.Select(x => x.item)); } } }
38.159091
148
0.646218
[ "MIT" ]
SkillsFundingAgency/das-reservations-jobs
src/SFA.DAS.Reservations.Data/Repository/ReservationIndexRepository.cs
3,360
C#
using System; namespace PuzzleBox.Blockchain.Abstraction { public interface IP2PClientFactory<TData> { IP2PClient<TData> Create(Uri uri); } }
17.3
46
0.65896
[ "Apache-2.0" ]
JasonKStevens/PuzzleBox.Blockchain
PuzzleBox.Blockchain.Abstraction/IP2PClientFactory.cs
175
C#