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
private sealed class SubInstruction.SubUInt64 : SubInstruction // TypeDefIndex: 2678 { // Methods // RVA: 0x191EF30 Offset: 0x191F031 VA: 0x191EF30 Slot: 8 public override int Run(InterpretedFrame frame) { } // RVA: 0x191E430 Offset: 0x191E531 VA: 0x191E430 public void .ctor() { } }
24.333333
84
0.732877
[ "MIT" ]
SinsofSloth/RF5-global-metadata
_no_namespace/SubInstruction.SubUInt64.cs
292
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFeedPlaceholderViewServiceClientTest { [Category("Smoke")][Test] public void GetFeedPlaceholderViewRequestObject() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView response = client.GetFeedPlaceholderView(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetFeedPlaceholderViewRequestObjectAsync() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedPlaceholderView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView responseCallSettings = await client.GetFeedPlaceholderViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedPlaceholderView responseCancellationToken = await client.GetFeedPlaceholderViewAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetFeedPlaceholderView() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView response = client.GetFeedPlaceholderView(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetFeedPlaceholderViewAsync() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedPlaceholderView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView responseCallSettings = await client.GetFeedPlaceholderViewAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedPlaceholderView responseCancellationToken = await client.GetFeedPlaceholderViewAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetFeedPlaceholderViewResourceNames() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView response = client.GetFeedPlaceholderView(request.ResourceNameAsFeedPlaceholderViewName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetFeedPlaceholderViewResourceNamesAsync() { moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient> mockGrpcClient = new moq::Mock<FeedPlaceholderViewService.FeedPlaceholderViewServiceClient>(moq::MockBehavior.Strict); GetFeedPlaceholderViewRequest request = new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), }; gagvr::FeedPlaceholderView expectedResponse = new gagvr::FeedPlaceholderView { ResourceNameAsFeedPlaceholderViewName = gagvr::FeedPlaceholderViewName.FromCustomerPlaceholderType("[CUSTOMER_ID]", "[PLACEHOLDER_TYPE]"), PlaceholderType = gagve::PlaceholderTypeEnum.Types.PlaceholderType.App, }; mockGrpcClient.Setup(x => x.GetFeedPlaceholderViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedPlaceholderView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedPlaceholderViewServiceClient client = new FeedPlaceholderViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedPlaceholderView responseCallSettings = await client.GetFeedPlaceholderViewAsync(request.ResourceNameAsFeedPlaceholderViewName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedPlaceholderView responseCancellationToken = await client.GetFeedPlaceholderViewAsync(request.ResourceNameAsFeedPlaceholderViewName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
69.081761
248
0.731701
[ "Apache-2.0" ]
googleads/google-ads-dotnet
tests/V9/Services/FeedPlaceholderViewServiceClientTest.g.cs
10,984
C#
using System.Net.Http; using System.Threading.Tasks; namespace StravaSegmentHunter.Web { public class StravaClient { private readonly HttpClient _client; public StravaClient(HttpClient client) { _client = client; } public virtual async Task<string> GetStarredSegments() { return await _client.GetStringAsync("segments/starred"); } } }
21.45
68
0.62704
[ "MIT" ]
robertgregorywest/StravaSegmentHunter
src/StravaSegmentHunter.Web/StravaClient.cs
429
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.DataBox.Latest.Outputs { [OutputType] public sealed class UnencryptedCredentialsResponseResult { /// <summary> /// Name of the job. /// </summary> public readonly string JobName; /// <summary> /// Secrets related to this job. /// </summary> public readonly object JobSecrets; [OutputConstructor] private UnencryptedCredentialsResponseResult( string jobName, object jobSecrets) { JobName = jobName; JobSecrets = jobSecrets; } } }
25.555556
81
0.627174
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataBox/Latest/Outputs/UnencryptedCredentialsResponseResult.cs
920
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace CrypticPay.Migrations { public partial class Cacader : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AspNetUsers_Wallet_WalletKryptikId", table: "AspNetUsers"); migrationBuilder.DropForeignKey( name: "FK_CurrencyWallet_CrypticPayCoins_CoinId", table: "CurrencyWallet"); migrationBuilder.DropForeignKey( name: "FK_CurrencyWallet_Wallet_WalletId", table: "CurrencyWallet"); migrationBuilder.DropTable( name: "CrypticPayCoins"); migrationBuilder.DropIndex( name: "IX_CurrencyWallet_CoinId", table: "CurrencyWallet"); migrationBuilder.DropIndex( name: "IX_CurrencyWallet_WalletId", table: "CurrencyWallet"); migrationBuilder.DropIndex( name: "IX_AspNetUsers_WalletKryptikId", table: "AspNetUsers"); migrationBuilder.DropColumn( name: "WalletId", table: "CurrencyWallet"); migrationBuilder.DropColumn( name: "WalletKryptikId", table: "AspNetUsers"); migrationBuilder.AddColumn<string>( name: "CrypticPayUserForeignKey", table: "Wallet", nullable: true); migrationBuilder.AlterColumn<string>( name: "CoinId", table: "CurrencyWallet", nullable: true, oldClrType: typeof(string), oldType: "nvarchar(450)", oldNullable: true); migrationBuilder.AddColumn<string>( name: "WalletKryptikId", table: "CurrencyWallet", nullable: true); migrationBuilder.CreateIndex( name: "IX_Wallet_CrypticPayUserForeignKey", table: "Wallet", column: "CrypticPayUserForeignKey", unique: true, filter: "[CrypticPayUserForeignKey] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_CurrencyWallet_WalletKryptikId", table: "CurrencyWallet", column: "WalletKryptikId"); migrationBuilder.AddForeignKey( name: "FK_CurrencyWallet_Wallet_WalletKryptikId", table: "CurrencyWallet", column: "WalletKryptikId", principalTable: "Wallet", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Wallet_AspNetUsers_CrypticPayUserForeignKey", table: "Wallet", column: "CrypticPayUserForeignKey", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_CurrencyWallet_Wallet_WalletKryptikId", table: "CurrencyWallet"); migrationBuilder.DropForeignKey( name: "FK_Wallet_AspNetUsers_CrypticPayUserForeignKey", table: "Wallet"); migrationBuilder.DropIndex( name: "IX_Wallet_CrypticPayUserForeignKey", table: "Wallet"); migrationBuilder.DropIndex( name: "IX_CurrencyWallet_WalletKryptikId", table: "CurrencyWallet"); migrationBuilder.DropColumn( name: "CrypticPayUserForeignKey", table: "Wallet"); migrationBuilder.DropColumn( name: "WalletKryptikId", table: "CurrencyWallet"); migrationBuilder.AlterColumn<string>( name: "CoinId", table: "CurrencyWallet", type: "nvarchar(450)", nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddColumn<string>( name: "WalletId", table: "CurrencyWallet", type: "nvarchar(450)", nullable: true); migrationBuilder.AddColumn<string>( name: "WalletKryptikId", table: "AspNetUsers", type: "nvarchar(450)", nullable: true); migrationBuilder.CreateTable( name: "CrypticPayCoins", columns: table => new { Id = table.Column<string>(type: "nvarchar(450)", nullable: false), ApiTag = table.Column<string>(type: "nvarchar(max)", nullable: true), Color = table.Column<string>(type: "nvarchar(max)", nullable: true), DateCreated = table.Column<DateTime>(type: "datetime2", nullable: false), IsSupported = table.Column<bool>(type: "bit", nullable: false), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), ThumbnailPath = table.Column<string>(type: "nvarchar(max)", nullable: true), Ticker = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_CrypticPayCoins", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_CurrencyWallet_CoinId", table: "CurrencyWallet", column: "CoinId"); migrationBuilder.CreateIndex( name: "IX_CurrencyWallet_WalletId", table: "CurrencyWallet", column: "WalletId"); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_WalletKryptikId", table: "AspNetUsers", column: "WalletKryptikId"); migrationBuilder.AddForeignKey( name: "FK_AspNetUsers_Wallet_WalletKryptikId", table: "AspNetUsers", column: "WalletKryptikId", principalTable: "Wallet", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CurrencyWallet_CrypticPayCoins_CoinId", table: "CurrencyWallet", column: "CoinId", principalTable: "CrypticPayCoins", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CurrencyWallet_Wallet_WalletId", table: "CurrencyWallet", column: "WalletId", principalTable: "Wallet", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
37.015228
96
0.535244
[ "Apache-2.0" ]
jettblu/Kryptik
CrypticPay/Migrations/20210812184437_Cacader.cs
7,294
C#
#region copyright // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion 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("DeviceMetadataInstallTool")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sensics, Inc.")] [assembly: AssemblyProduct("DeviceMetadataInstallTool")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("469ffd72-e914-4527-8358-7a588d2c1ccb")] // 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")]
39.576923
84
0.748299
[ "Apache-2.0" ]
sensics/DeviceMetadataTools
DeviceMetadataInstallTool/Properties/AssemblyInfo.cs
2,061
C#
// Copyright (c) TotalSoft. // This source code is licensed under the MIT license. using NBB.Messaging.Abstractions; using System; namespace NBB.Messaging.Noop { public class NoopTransportMonitor : ITransportMonitor, IDisposable { private bool disposedValue; public event TransportErrorHandler OnError; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { OnError = null; } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
21.882353
70
0.538978
[ "MIT" ]
VCuzmin/nbb
src/Messaging/NBB.Messaging.Noop/NoopTransportMonitor.cs
746
C#
/****************************** Module Header ******************************\ * Module Name: AutoLogin.aspx.cs * Project: CSASPNETAutoLogin * Copyright (c) Microsoft Corporation. * * This page request the Login.aspx firstly, and get the __VIEWSTATE and __EVENTVALIDATION'fields. * Then we can set the post data string, such as the __VIEWSTATE, __EVENTVALIDATION, * UserName,Password and loginButton id parameters. * We use the webrequest to post these data into the login.aspx to login this site. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Net; using System.Web; using System.Text; namespace CSASPNETAutoLogin { public partial class AutoLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Response.Clear(); } protected void autoLogin_Click(object sender, EventArgs e) { string url = HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login"); CookieContainer myCookieContainer = new CookieContainer(); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = myCookieContainer; request.Method = "GET"; request.KeepAlive = false; HttpWebResponse response = request.GetResponse() as HttpWebResponse; System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); string srcString = reader.ReadToEnd(); // get the page ViewState string viewStateFlag = "id=\"__VIEWSTATE\" value=\""; int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length; int j = srcString.IndexOf("\"", i); string viewState = srcString.Substring(i, j - i); // get page EventValidation string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\""; i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length; j = srcString.IndexOf("\"", i); string eventValidation = srcString.Substring(i, j - i); string submitButton = "LoginButton"; // UserName and Password string userName = btnUserName.Text; string password = btnPassword.Text; // Convert the text into the url encoding string viewState = System.Web.HttpUtility.UrlEncode(viewState); eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation); submitButton = System.Web.HttpUtility.UrlEncode(submitButton); // Concat the string data which will be submit string formatString = "UserName={0}&Password={1}&loginButton={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}"; string postString = string.Format(formatString, userName, password, submitButton, viewState, eventValidation); // Convert the submit string data into the byte array byte[] postData = Encoding.ASCII.GetBytes(postString); // Set the request parameters request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.Referer = url; request.KeepAlive = false; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = myCookieContainer; System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie"); ck.Domain = request.RequestUri.Host; request.CookieContainer.Add(ck); request.CookieContainer.Add(response.Cookies); request.ContentLength = postData.Length; // Submit the request data System.IO.Stream outputStream = request.GetRequestStream(); request.AllowAutoRedirect = true; outputStream.Write(postData, 0, postData.Length); outputStream.Close(); // Get the return data response = request.GetResponse() as HttpWebResponse; responseStream = response.GetResponseStream(); reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); srcString = reader.ReadToEnd(); Response.Write(srcString); Response.End(); } } }
45.238938
211
0.625391
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
OneCodeTeam/Auto user login in ASP.NET site w HttpWebRequest (CSASPNETAutoLogin)/[C#]-Auto user login in ASP.NET site w HttpWebRequest (CSASPNETAutoLogin)/C#/CSASPNETAutoLogin/AutoLogin.aspx.cs
5,114
C#
using Newtonsoft.Json; namespace GhostSharp.Entities { /// <summary> /// Represents a single menu item on your publication. /// </summary> public class Navigation { /// <summary> /// Menu label as visitors see it /// </summary> [JsonProperty("label")] public string Label { get; set; } /// <summary> /// Menu URL (relative URL, such as /about-me) /// </summary> [JsonProperty("url")] public string Url { get; set; } } }
22.913043
58
0.535104
[ "MIT" ]
grantwinney/GhostSharp
GhostSharp/Entities/Navigation.cs
529
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] [RequireComponent(typeof(Animator))] public class SelectableTile : MonoBehaviour { private SpriteRenderer renderer; protected Animator animator; [SerializeField] private Sprite shadow; [SerializeField] private Sprite hammer; protected GameManager gm; private float alfaShadow = 145f / 255f; private float alfaHammer = 255f / 255f; virtual protected void Awake() { gm = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>(); animator = GetComponent<Animator>(); renderer = GetComponent<SpriteRenderer>(); renderer.sprite = shadow; renderer.enabled = false; } public void OnMouseOver() { if (!gm.isWacked) { renderer.enabled = true; } } public void OnMouseExit() { if (!gm.isWacked) { renderer.enabled = false; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { OnMouseOver(); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { OnMouseExit(); } } protected virtual void OnMouseDown() { if (gm.isWacked) { return; } renderer.sprite = hammer; Color tmpColor = renderer.color; tmpColor.a = alfaHammer; renderer.color = tmpColor; gm.SetIsWacked(true); } protected IEnumerator WaitSeconds(float seconds) { yield return new WaitForSeconds(seconds); ResetAnimations(); gm.SetIsWacked(false); Color tmpColor = renderer.color; tmpColor.a = alfaShadow; renderer.color = tmpColor; renderer.sprite = shadow; renderer.enabled = false; } virtual protected void ResetAnimations() { animator.SetBool("isEmpty", false); } }
23.765957
90
0.571173
[ "CC0-1.0" ]
jaumeriera/GuacaMole
Assets/Scripts/FloorTiles/SelectableTile.cs
2,234
C#
// Generated by TankLibHelper // ReSharper disable All namespace TankLib.STU.Types { [STU(0xA408D74F, 72)] public class STUVoiceConversation : STUInstance { [STUField(0x401F5484, 8)] // size: 16 public teStructuredDataAssetRef<STUVoiceStimulus> m_stimulus; [STUField(0x90D76F17, 24, ReaderType = typeof(InlineInstanceFieldReader))] // size: 16 public STUVoiceConversationLine[] m_90D76F17; [STUField(0x15C9002C, 40)] // size: 24 public teStructuredDataHashMap<STUVoiceConversationLine> m_15C9002C; [STUField(0x4FF98D41, 56, ReaderType = typeof(EmbeddedInstanceFieldReader))] // size: 8 public STUCriteriaContainer m_criteria; [STUField(0x9CDDC24D, 64)] // size: 4 public float m_weight = 1f; [STUField(0x98F0E612, 68)] // size: 1 public byte m_98F0E612 = 0x0; } }
32.928571
95
0.649675
[ "MIT" ]
Pandaaa2507/OWLib
TankLib/STU/Types/STUVoiceConversation.cs
922
C#
using Catalog.Api.Entities; using Catalog.Api.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace Catalog.Api.Controllers { [ApiController] [Route("api/v1/[controller]")] public class CatalogController : ControllerBase { private readonly IProductRepository _productRepository; private readonly ILogger<CatalogController> _logger; public CatalogController(IProductRepository productRepository, ILogger<CatalogController> logger) { _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } [HttpGet] [ProducesResponseType(statusCode:StatusCodes.Status404NotFound)] [ProducesResponseType(statusCode:(int)HttpStatusCode.OK, Type = typeof(IEnumerable<Product>))] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { var products = await _productRepository.GetProducts(); if (products == null) { return NotFound(); } return Ok(products); } [HttpGet("{id:length(24)}", Name = "GetProduct")] [ProducesResponseType(statusCode: StatusCodes.Status404NotFound)] [ProducesResponseType(statusCode: StatusCodes.Status200OK, type: typeof(Product))] public async Task<ActionResult<Product>> GetProductById(string id) { var product = await _productRepository.GetProductById(id: id); if (product == null) { return NotFound(); } return Ok(product); } [HttpGet] [Route("[action]/{categoryName}", Name = "GetProductByCategory")] [ProducesResponseType(statusCode: StatusCodes.Status404NotFound)] [ProducesResponseType(statusCode: StatusCodes.Status200OK, type: typeof(IEnumerable<Product>))] public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(string categoryName) { var product = await _productRepository.GetProductByCategory(categoryName: categoryName); if (product == null) { return NotFound(); } return Ok(value: product); } [HttpPost] [ProducesResponseType(type: typeof(Product), statusCode: StatusCodes.Status200OK)] [ProducesResponseType(statusCode: StatusCodes.Status201Created, type: typeof(Product))] public async Task<ActionResult<Product>> CreateProduct([FromBody]Product product) { await _productRepository.CreateProduct(product); return CreatedAtRoute(routeName: "GetProduct", routeValues: new {id = product.Id}, value: product); } [HttpPut] [ProducesResponseType(statusCode: StatusCodes.Status200OK, type: typeof(Product))] public async Task<IActionResult> UpdateProduct([FromBody]Product product) { return Ok(await _productRepository.UpdateProduct(product: product)); } [HttpDelete(template: "{id:length(24)}", Name = "DeleteProduct")] [ProducesResponseType(statusCode: StatusCodes.Status200OK, type: typeof(Product))] public async Task<ActionResult<bool>> DeleteProduct(string id) { return Ok(await _productRepository.DeleteProduct(id)); } } }
39.271739
113
0.66067
[ "MIT" ]
Hamidnch/AspnetMicroservices
src/Services/Catalog/Catalog.Api/Controllers/CatalogController.cs
3,615
C#
using System.Collections.Generic; using System.Linq; using StardewModdingAPI; using StardewValley; using TehPers.Core.Api.Content; using TehPers.Core.Api.DI; namespace TehPers.FishingOverhaul.Services.Tokens { internal class MissingSecretNotesToken : MissingNotesToken { public MissingSecretNotesToken( IAssetTracker assetTracker, [ContentSource(ContentSource.GameContent)] IAssetProvider gameAssets ) : base(assetTracker, gameAssets) { } public override IEnumerable<string> GetValues(string? input) { if (Game1.player is not { secretNotesSeen: { } secretNotesSeen } player) { return Enumerable.Empty<string>(); } return this.SecretNotes.Keys.Where(id => id < GameLocation.JOURNAL_INDEX) .Except(secretNotesSeen) .Where( id => !player.hasItemInInventoryNamed($"Secret Note #{id}") && (id != 10 || player.mailReceived.Contains("QiChallengeComplete")) ) .Select(id => id.ToString("G")); } } }
32.5
92
0.596581
[ "MIT" ]
TehPers/StardewValleyMods
src/TehPers.FishingOverhaul/Services/Tokens/MissingSecretNotesToken.cs
1,172
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Grpc.Net.Client.Tests.Infrastructure { public class NullHttpHandler : HttpMessageHandler { private bool _disposed; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (_disposed) { throw new ObjectDisposedException(nameof(NullHttpHandler)); } throw new NotImplementedException(); } protected override void Dispose(bool disposing) { _disposed = true; base.Dispose(disposing); } } }
28.93617
127
0.689706
[ "Apache-2.0" ]
Alibesharat/grpc-dotnet
test/Grpc.Net.Client.Tests/Infrastructure/NullHttpHandler.cs
1,362
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Collections_Generic_Dictionary_2_String_Int32_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Collections.Generic.Dictionary<System.String, System.Int32>); args = new Type[]{typeof(System.String), typeof(System.Int32)}; method = type.GetMethod("set_Item", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_Item_0); args = new Type[]{}; method = type.GetMethod("GetEnumerator", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetEnumerator_1); args = new Type[]{typeof(System.String)}; method = type.GetMethod("get_Item", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Item_2); args = new Type[]{typeof(System.String), typeof(System.Int32)}; method = type.GetMethod("Add", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Add_3); args = new Type[]{}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static StackObject* set_Item_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @value = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Collections.Generic.Dictionary<System.String, System.Int32> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Int32>)typeof(System.Collections.Generic.Dictionary<System.String, System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); instance_of_this_method[key] = value; return __ret; } static StackObject* GetEnumerator_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Generic.Dictionary<System.String, System.Int32> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Int32>)typeof(System.Collections.Generic.Dictionary<System.String, System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetEnumerator(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* get_Item_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.Dictionary<System.String, System.Int32> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Int32>)typeof(System.Collections.Generic.Dictionary<System.String, System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method[key]; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method; return __ret + 1; } static StackObject* Add_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @value = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Collections.Generic.Dictionary<System.String, System.Int32> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Int32>)typeof(System.Collections.Generic.Dictionary<System.String, System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0); __intp.Free(ptr_of_this_method); instance_of_this_method.Add(@key, @value); return __ret; } static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new System.Collections.Generic.Dictionary<System.String, System.Int32>(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
52.158273
359
0.702897
[ "MIT" ]
233Chad/ILRuntime
ILRuntimeTestBase/AutoGenerate/System_Collections_Generic_Dictionary_2_String_Int32_Binding.cs
7,250
C#
using System; using System.Collections.Generic; using System.Data.Common; using Abp.Data; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Security; using MySuperStats.EntityFrameworkCore; using MySuperStats.EntityFrameworkCore.Seed; using MySuperStats.MultiTenancy; namespace MySuperStats.Migrator { public class MultiTenantMigrateExecuter : ITransientDependency { private readonly Log _log; private readonly AbpZeroDbMigrator _migrator; private readonly IRepository<Tenant> _tenantRepository; private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver; public MultiTenantMigrateExecuter( AbpZeroDbMigrator migrator, IRepository<Tenant> tenantRepository, Log log, IDbPerTenantConnectionStringResolver connectionStringResolver) { _log = log; _migrator = migrator; _tenantRepository = tenantRepository; _connectionStringResolver = connectionStringResolver; } public bool Run(bool skipConnVerification) { var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MultiTenancySides.Host))); if (hostConnStr.IsNullOrWhiteSpace()) { _log.Write("Configuration file should contain a connection string named 'Default'"); return false; } _log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr)); if (!skipConnVerification) { _log.Write("Continue to migration for this host database and all tenants..? (Y/N): "); var command = Console.ReadLine(); if (!command.IsIn("Y", "y")) { _log.Write("Migration canceled."); return false; } } _log.Write("HOST database migration started..."); try { _migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb); } catch (Exception ex) { _log.Write("An error occured during migration of host database:"); _log.Write(ex.ToString()); _log.Write("Canceled migrations."); return false; } _log.Write("HOST database migration completed."); _log.Write("--------------------------------------------------------"); var migratedDatabases = new HashSet<string>(); var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != ""); for (var i = 0; i < tenants.Count; i++) { var tenant = tenants[i]; _log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count)); _log.Write("Name : " + tenant.Name); _log.Write("TenancyName : " + tenant.TenancyName); _log.Write("Tenant Id : " + tenant.Id); _log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString)); if (!migratedDatabases.Contains(tenant.ConnectionString)) { try { _migrator.CreateOrMigrateForTenant(tenant); } catch (Exception ex) { _log.Write("An error occured during migration of tenant database:"); _log.Write(ex.ToString()); _log.Write("Skipped this tenant and will continue for others..."); } migratedDatabases.Add(tenant.ConnectionString); } else { _log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it...."); } _log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count)); _log.Write("--------------------------------------------------------"); } _log.Write("All databases have been migrated."); return true; } private static string CensorConnectionString(string connectionString) { var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; var keysToMask = new[] { "password", "pwd", "user id", "uid" }; foreach (var key in keysToMask) { if (builder.ContainsKey(key)) { builder[key] = "*****"; } } return builder.ToString(); } } }
38.272727
163
0.542953
[ "MIT" ]
ykirkanahtar/MySuperStats
aspnet-core/src/MySuperStats.Migrator/MultiTenantMigrateExecuter.cs
5,052
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Sms.Model")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Sms.Model")] [assembly: System.Reflection.AssemblyTitleAttribute("Sms.Model")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generado por la clase WriteCodeFragment de MSBuild.
40.791667
80
0.642492
[ "MIT" ]
marioballe/sms-push
SmsPush/Sms.Model/obj/Debug/netstandard2.0/Sms.Model.AssemblyInfo.cs
979
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; using System.Net.Http; using Microsoft.Owin; using Microsoft.Owin.Security; using Owin.Security.Providers.TripIt.Messages; using Owin.Security.Providers.TripIt.Provider; namespace Owin.Security.Providers.TripIt { /// <summary> /// Options for the TripIt authentication middleware. /// </summary> public class TripItAuthenticationOptions : AuthenticationOptions { /// <summary> /// Initializes a new instance of the <see cref="TripItAuthenticationOptions"/> class. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Owin.Security.Providers.TripIt.TripItAuthenticationOptions.set_Caption(System.String)", Justification = "Not localizable")] public TripItAuthenticationOptions() : base(Constants.DefaultAuthenticationType) { Caption = Constants.DefaultAuthenticationType; CallbackPath = new PathString("/signin-tripit"); AuthenticationMode = AuthenticationMode.Passive; BackchannelTimeout = TimeSpan.FromSeconds(60); BackchannelCertificateValidator = null; } /// <summary> /// Gets or sets the consumer key used to communicate with TripIt. /// </summary> /// <value>The consumer key used to communicate with TripIt.</value> public string ConsumerKey { get; set; } /// <summary> /// Gets or sets the consumer secret used to sign requests to TripIt. /// </summary> /// <value>The consumer secret used to sign requests to TripIt.</value> public string ConsumerSecret { get; set; } /// <summary> /// Gets or sets timeout value in milliseconds for back channel communications with TripIt. /// </summary> /// <value> /// The back channel timeout. /// </value> public TimeSpan BackchannelTimeout { get; set; } /// <summary> /// Gets or sets the a pinned certificate validator to use to validate the endpoints used /// in back channel communications belong to TripIt. /// </summary> /// <value> /// The pinned certificate validator. /// </value> /// <remarks>If this property is null then the default certificate checks are performed, /// validating the subject name and if the signing chain is a trusted party.</remarks> public ICertificateValidator BackchannelCertificateValidator { get; set; } /// <summary> /// The HttpMessageHandler used to communicate with TripIt. /// This cannot be set at the same time as BackchannelCertificateValidator unless the value /// can be downcast to a WebRequestHandler. /// </summary> public HttpMessageHandler BackchannelHttpHandler { get; set; } /// <summary> /// Get or sets the text that the user can display on a sign in user interface. /// </summary> public string Caption { get { return Description.Caption; } set { Description.Caption = value; } } /// <summary> /// The request path within the application's base path where the user-agent will be returned. /// The middleware will process this request when it arrives. /// Default value is "/signin-tripit". /// </summary> public PathString CallbackPath { get; set; } /// <summary> /// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user <see cref="System.Security.Claims.ClaimsIdentity"/>. /// </summary> public string SignInAsAuthenticationType { get; set; } /// <summary> /// Gets or sets the type used to secure data handled by the middleware. /// </summary> public ISecureDataFormat<RequestToken> StateDataFormat { get; set; } /// <summary> /// Gets or sets the <see cref="ITripItAuthenticationProvider"/> used to handle authentication events. /// </summary> public ITripItAuthenticationProvider Provider { get; set; } } }
42.650485
177
0.644207
[ "MIT" ]
AliEbadi/OwinOAuthProviders
src/Owin.Security.Providers.TripIt/TripItAuthenticationOptions.cs
4,395
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { #if UNITY_STANDALONE || UNITY_EDITOR MovementComponent movementComponent; // Use this for initialization void Awake () { //Retrieve reference to the Movement Component movementComponent = GetComponent<MovementComponent>(); //Disable this script in case the Movement Component is not found, and leave an error message. if(movementComponent == null) { Debug.LogError("Missing MovementComponent on " + gameObject.name + " to run PlayerController. Please add one."); Destroy(this); } } // Update is called once per frame void Update () { } void FixedUpdate() { //Send input to the Movement Component in order to move the character movementComponent.MoveCharacter(Input.GetAxis("Horizontal")); //Check if the Up Arrow has been pressed, and if so, send the Jump input to the Movement Component if (Input.GetKeyDown(KeyCode.UpArrow)) { movementComponent.Jump(); } } #endif }
28.825
124
0.673027
[ "MIT" ]
PacktPublishing/Unity-2017-2D-Game-Development-Projects
Chapter10/PlayerController.cs
1,155
C#
using System.Collections; using Managers; using UnityEngine; using UnityEngine.EventSystems; namespace Behaviours { public class GuitaristCharacterBehaviour : MonoBehaviour { public CharacterSituation CharacterSituation; public float Angle; private bool _isMouseClaimed; private Vector2 _mouseDir; private float _vertical; Vector2 guitarLastPos, drumLastPos; public LayerMask layerMask; [SerializeField] private MouseListener mouseListener; [SerializeField] public Rigidbody2D Rigidbody2D; [SerializeField] private DrumCharacterBehaviour _drumCharacter; [SerializeField] private Animator _animator; [HideInInspector] public GuitarBubbleBehaviour currentBubble; [SerializeField] private BaseBossBehaviour boss; [SerializeField] public HealthManager _healthManager; public int guitaristMissInput; [SerializeField] private AudioClip _failEffect; [SerializeField] private GameManager _gameManager; [SerializeField] private AudioSource _audioSource, _mainAudioSource; private static readonly int Die = Animator.StringToHash("Die"); [SerializeField] private UltimateComboManager ComboManager; private static readonly int Ulti1 = Animator.StringToHash("Ulti"); private static readonly int FirstAttack = Animator.StringToHash("FirstAttack"); public void Initialize() { _isMouseClaimed = true; mouseListener.LeftClick += OnLeftClick; mouseListener.RightClick += OnRightClick; mouseListener.LeftClickDraggedUp += OnLeftClickDragUp; mouseListener.LeftClickDraggedDown += OnLeftClickDragDown; mouseListener.RightClickDraggedUp += OnRightClickDragUp; mouseListener.RightClickDraggedDown += OnRightClickDragDown; _healthManager.OnDead += OnGuitaristDead; ComboManager.OnSuccess += Ulti; _mainAudioSource.Play(); } private void Ulti() { ComboManager.OnSuccess -= Ulti; _animator.SetTrigger(Ulti1); } private void FixedUpdate() { if(CharacterSituation==CharacterSituation.OnMap) { LookAtMouse(); } } void LookAtMouse() { if (!(Camera.main is null)) _mouseDir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position); Angle = Mathf.Atan2(_mouseDir.y, _mouseDir.x) * Mathf.Rad2Deg; //_drumCharacter.transform.rotation = Quaternion.AngleAxis(Angle, Vector3.forward); //transform.rotation = Quaternion.AngleAxis(Angle, Vector3.forward); } private void BubbleCorrectHit(GameObject bubbleObject) { LeanTween.scale(bubbleObject, new Vector3(2.5f, 2.5f, 2.5f), .1f).setOnComplete(() => { Destroy(bubbleObject,.01f); }); } // Mouse Inputs private void OnLeftClick(PointerEventData eventData) { if (currentBubble!=null && currentBubble.input == MouseInputs.LeftClick && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { DamageGuitarist(); ComboManager.ComboFailed(); } } private void OnRightClick(PointerEventData eventData) { if (currentBubble!=null && currentBubble.input == MouseInputs.RightClick && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { DamageGuitarist(); ComboManager.ComboFailed(); } } private void OnLeftClickDragUp(PointerEventData eventData) { if (currentBubble!=null && currentBubble.input == MouseInputs.LeftClickDragUp && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { DamageGuitarist(); ComboManager.ComboFailed(); } } private void OnLeftClickDragDown(PointerEventData eventData) { if (currentBubble!=null && currentBubble.input == MouseInputs.LeftClickDragDown && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { DamageGuitarist(); ComboManager.ComboFailed(); } } private void OnRightClickDragUp(PointerEventData eventData) { if (currentBubble!=null && currentBubble.input == MouseInputs.RightClickDragUp && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { ComboManager.ComboFailed(); DamageGuitarist(); } } private void OnRightClickDragDown(PointerEventData eventData) { if (currentBubble!=null&&currentBubble.input == MouseInputs.RightClickDragDown && currentBubble._isInteractable) { currentBubble._isInteractable = false; BubbleCorrectHit(currentBubble.gameObject); HitDamage(5); ComboManager.ComboBarProgression(); } else { DamageGuitarist(); ComboManager.ComboFailed(); } } private void OnCollisionEnter2D(Collision2D collision) { guitarLastPos = transform.position; drumLastPos = _drumCharacter.transform.position; } private void OnCollisionStay2D(Collision2D collision) { RaycastHit2D hit = Physics2D.Raycast(transform.position, Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position), 1.5f, layerMask); if (hit.collider != null) { transform.position = guitarLastPos; _drumCharacter.transform.position = drumLastPos; } } private void HitDamage(int damage) { _animator.SetTrigger(FirstAttack); boss.damageTaken = damage; boss.DamageBoss(); } public void DamageGuitarist() { _healthManager.SetHealth(guitaristMissInput,true); _mainAudioSource.volume=0.1f; _audioSource.clip=_failEffect; _audioSource.Play(); _mainAudioSource.volume=0.5f; } private IEnumerator ContinueMusicAgain(float delay) { yield return new WaitForSeconds(delay); _mainAudioSource.volume=0.2f; } private void OnGuitaristDead() { CharacterSituation = CharacterSituation.Dead; mouseListener.LeftClick -= OnLeftClick; mouseListener.RightClick -= OnRightClick; mouseListener.LeftClickDraggedUp -= OnLeftClickDragUp; mouseListener.LeftClickDraggedDown -= OnLeftClickDragDown; mouseListener.RightClickDraggedUp -= OnRightClickDragUp; mouseListener.RightClickDraggedDown -= OnRightClickDragDown; _healthManager.OnDead -= OnGuitaristDead; _animator.SetTrigger(Die); gameObject.SetActive(false); boss.KillPlayer(); _gameManager.BadEnd(gameObject); } } }
36.597403
160
0.590253
[ "MIT" ]
Maestroymn/LoremIpsumJamProject
Assets/Scripts/Behaviours/GuitaristCharacterBehaviour.cs
8,456
C#
using DeckOfCards.WorkoutCreator; using Microsoft.Azure.Cosmos.Table; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace DeckOfCards.ImageGallery { public static class TableOperations { const string WORKOUTS_TABLE_NAME = "Workouts"; private static CloudTable GetWorkoutsTable(string connectionString) { var storageAccount = CloudStorageAccount.Parse(connectionString); var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration()); return tableClient.GetTableReference(WORKOUTS_TABLE_NAME); } public static List<WorkoutEntity> GetWorkouts(string connectionString) { var table = GetWorkoutsTable(connectionString); var query = new TableQuery<WorkoutEntity>(); return table.ExecuteQuery(query).ToList(); } public static WorkoutEntity GetWorkout(string connectionString, string workoutId) { var table = GetWorkoutsTable(connectionString); var operation = TableOperation.Retrieve<WorkoutEntity>(workoutId, workoutId); var result = table.Execute(operation); return result.Result as WorkoutEntity; } public static WorkoutEntity SaveWorkout(string connectionString, WorkoutEntity workout) { var table = GetWorkoutsTable(connectionString); var operation = TableOperation.InsertOrReplace(workout); var result = table.Execute(operation); return result.Result as WorkoutEntity; } public static WorkoutEntity DeleteWorkout(string connectionString, WorkoutEntity workout) { workout.ETag = "*"; var table = GetWorkoutsTable(connectionString); var operation = TableOperation.Delete(workout); var result = table.Execute(operation); return workout; } public static List<ExerciseEntity> GetExercisesByWorkout(string workoutId) { return null; } } }
31.754098
92
0.747031
[ "MIT" ]
ChiefInnovator/Developing-Microsoft-Azure-Solutions
ch07/DeckOfCards.WorkoutCreator/TableOperations.cs
1,939
C#
// Copyright (c) Bynder. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. namespace Bynder.Api.Impl.Oauth { /// <summary> /// Class to hold token credentials to call the API. /// </summary> internal class Credentials { /// <summary> /// Initializes new instance with specified values /// </summary> /// <param name="consumerKey">consumer key</param> /// <param name="consumerSecret">consumer secret</param> /// <param name="token">token. This can be null if we are going to log in into Bynder through the browser</param> /// <param name="tokenSecret">token secret. This can be null if we are going to log in into Bynder through the browser</param> public Credentials(string consumerKey, string consumerSecret, string token, string tokenSecret) { CONSUMER_KEY = consumerKey; CONSUMER_SECRET = consumerSecret; ACCESS_TOKEN = token; ACCESS_TOKEN_SECRET = tokenSecret; INITIAL_TOKEN = token; INITIAL_SECRET = tokenSecret; } /// <summary> /// Gets the consumer key /// </summary> public string CONSUMER_KEY { get; private set; } /// <summary> /// Gets the consumer secret /// </summary> public string CONSUMER_SECRET { get; private set; } /// <summary> /// Gets the access token /// </summary> public string ACCESS_TOKEN { get; private set; } /// <summary> /// Gets the access token secret /// </summary> public string ACCESS_TOKEN_SECRET { get; private set; } /// <summary> /// Initial token. Used when we want to reset credentials /// </summary> private string INITIAL_TOKEN { get; set; } /// <summary> /// Initial token secret. Used when we want to reset credentials /// </summary> private string INITIAL_SECRET { get; set; } /// <summary> /// Resets access token/secret to the initial ones. /// </summary> public void Reset() { ACCESS_TOKEN = INITIAL_TOKEN; ACCESS_TOKEN_SECRET = INITIAL_SECRET; } /// <summary> /// Sets new access token/secret /// </summary> /// <param name="token">new access token</param> /// <param name="secret">new access secret</param> public void Set(string token, string secret) { ACCESS_TOKEN = token; ACCESS_TOKEN_SECRET = secret; } } }
33.4625
134
0.577139
[ "MIT" ]
Geta/bynder-c-sharp-sdk
Bynder/Api/Impl/Oauth/Credentials.cs
2,679
C#
using Assets.UnityFoundation.DialogueSystem; using CsvHelper; using CsvHelper.Configuration; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; namespace Assets.UnityFoundation.Systems.DialogueSystem.Editor { public class DialogueCsvHandler { private readonly DialogueSO dialogue; public DialogueCsvHandler(DialogueSO dialogue) { this.dialogue = dialogue; } public void ImportCSV() { string path = EditorUtility.OpenFilePanel("Overwrite with csv", "", "csv"); Debug.Log($"Importing file: {path}"); if(string.IsNullOrEmpty(path)) return; dialogue.Clear(); foreach(var row in ReadCsv(path)) { dialogue.name = row.DialogueName; var newDialogueNode = ScriptableObject.CreateInstance<DialogueNode>(); newDialogueNode.name = row.DialogueNodeName; newDialogueNode.Text = row.Text; if(!string.IsNullOrEmpty(row.NextDialogues)) { newDialogueNode.NextDialogueNodes.AddRange(row.NextDialogues.Split('|')); } if(!string.IsNullOrEmpty(row.PreviousDialogues)) { newDialogueNode.PreviousDialogueNodes .AddRange(row.PreviousDialogues.Split('|')); } string[] rectDimensions = row.Rect.Split('|'); newDialogueNode.Rect = new Rect( float.Parse(rectDimensions[0]), float.Parse(rectDimensions[1]), float.Parse(rectDimensions[2]), float.Parse(rectDimensions[3]) ); dialogue.DialogueNodes.Add(newDialogueNode.name, newDialogueNode); var speaker = AssetDatabase.LoadAssetAtPath<SpearkerSO>($"{row.SpearkerName}"); if(speaker != null) { Debug.Log($"Imported speaker on path: {row.SpearkerName}"); newDialogueNode.Spearker = speaker; } else { Debug.Log( $"Failed import speaker: {row.SpearkerName}." + $" Please put the SpeakerSO asset in the same folder." ); } } string assetPath = AssetDatabase.GetAssetPath(dialogue.GetInstanceID()); AssetDatabase.RenameAsset(assetPath, dialogue.name); AssetDatabase.SaveAssets(); } private IEnumerable<DialogueCsvRow> ReadCsv(string path) { using var reader = new StreamReader(path); using var csv = new CsvReader( reader, new CsvConfiguration(CultureInfo.InvariantCulture) { MissingFieldFound = null } ); csv.Read(); csv.ReadHeader(); while(csv.Read()) { yield return csv.GetRecord<DialogueCsvRow>(); } } public void ExportCSV() { string exportFolderPath = Application.dataPath + "/Export/Dialogues/"; if(!Directory.Exists(exportFolderPath)) { Directory.CreateDirectory(exportFolderPath); } string filePath = exportFolderPath + $"{dialogue.name}" + $"_{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}" + $".csv"; Debug.Log($"CSV exported to path: {filePath}"); using var writer = new StreamWriter(filePath); using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture); csv.WriteRecords( dialogue .DialogueNodesValues .Select(node => { var row = new DialogueCsvRow(dialogue, node); var spearkerPath = AssetDatabase.GetAssetPath(node.Spearker); if(spearkerPath != null) { Debug.Log($"Export speaker on path: {spearkerPath}"); row.SpearkerName = spearkerPath; } else { Debug.Log($"Couldn't find speaker {row.SpearkerName} file"); } return row; }) ); } } class DialogueCsvRow { public string DialogueName { get; set; } public string DialogueNodeName { get; set; } public string SpearkerName { get; set; } public string Text { get; set; } public string NextDialogues { get; set; } public string PreviousDialogues { get; set; } = null; public string Rect { get; set; } public DialogueCsvRow() { } public DialogueCsvRow(DialogueSO dialogueSO, DialogueNode dialogueNode) { DialogueName = dialogueSO.name; DialogueNodeName = dialogueNode.name; SpearkerName = dialogueNode.Spearker?.name; Text = dialogueNode.Text; NextDialogues = string.Join("|", dialogueNode.NextDialogueNodes); PreviousDialogues = string.Join("|", dialogueNode.PreviousDialogueNodes); Rect = string.Join("|", new float[] { dialogueNode.Rect.position.x, dialogueNode.Rect.position.y, dialogueNode.Rect.width, dialogueNode.Rect.height }); } } }
34.082353
95
0.524853
[ "Apache-2.0" ]
BrunoBiluca/UnityFoundation
Systems/DialogueSystem/Editor/DialogueCsvHandler.cs
5,794
C#
// ************************************************************************ // // * Copyright 2018 OSIsoft, LLC // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * <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.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 OSIsoft.PIDevClub.PIWebApiClient.Client; using System.Runtime.InteropServices; namespace OSIsoft.PIDevClub.PIWebApiClient.Model { /// <summary> /// PIAnalysisRule /// </summary> [DataContract] public class PIAnalysisRule { public PIAnalysisRule(string WebId = null, string Id = null, string Name = null, string Description = null, string Path = null, string ConfigString = null, string DisplayString = null, string EditorType = null, bool? HasChildren = null, bool? IsConfigured = null, bool? IsInitializing = null, string PlugInName = null, List<string> SupportedBehaviors = null, string VariableMapping = null, PIAnalysisRuleLinks Links = null, PIWebException WebException = null) { this.WebId = WebId; this.Id = Id; this.Name = Name; this.Description = Description; this.Path = Path; this.ConfigString = ConfigString; this.DisplayString = DisplayString; this.EditorType = EditorType; this.HasChildren = HasChildren; this.IsConfigured = IsConfigured; this.IsInitializing = IsInitializing; this.PlugInName = PlugInName; this.SupportedBehaviors = SupportedBehaviors; this.VariableMapping = VariableMapping; this.Links = Links; this.WebException = WebException; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "WebId", EmitDefaultValue = false)] public string WebId { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "Id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "Name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "Description", EmitDefaultValue = false)] public string Description { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "Path", EmitDefaultValue = false)] public string Path { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "ConfigString", EmitDefaultValue = false)] public string ConfigString { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "DisplayString", EmitDefaultValue = false)] public string DisplayString { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "EditorType", EmitDefaultValue = false)] public string EditorType { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "HasChildren", EmitDefaultValue = false)] public bool? HasChildren { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "IsConfigured", EmitDefaultValue = false)] public bool? IsConfigured { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "IsInitializing", EmitDefaultValue = false)] public bool? IsInitializing { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "PlugInName", EmitDefaultValue = false)] public string PlugInName { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "SupportedBehaviors", EmitDefaultValue = false)] public List<string> SupportedBehaviors { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "VariableMapping", EmitDefaultValue = false)] public string VariableMapping { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "Links", EmitDefaultValue = false)] public PIAnalysisRuleLinks Links { get; set; } /// <summary> /// Gets or Sets PIAnalysisRule /// </summary> [DataMember(Name = "WebException", EmitDefaultValue = false)] public PIWebException WebException { get; set; } } }
31.823899
461
0.671937
[ "Apache-2.0" ]
lydonchandra/PI-Web-API-Client-DotNet-Standard
src/OSIsoft.PIDevClub.PIWebApiClient/OSIsoft.PIDevClub.PIWebApiClient/Model/PIAnalysisRule.cs
5,060
C#
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // 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.ComponentModel; using System.Web.Services; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.ResultObjects; using Microsoft.Web.Services3; namespace WebsitePanel.EnterpriseServer { /// <summary> /// Summary description for esApplicationsInstaller /// </summary> [WebService(Namespace = "http://smbsaas/websitepanel/enterpriseserver")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [Policy("ServerPolicy")] [ToolboxItem(false)] public class esCRM : WebService { [WebMethod] public OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode) { return CRMController.CreateOrganization(organizationId, baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName, userId, collation, baseLanguageCode); } [WebMethod] public StringArrayResultObject GetCollation(int packageId) { return CRMController.GetCollation(packageId); } [WebMethod] public StringArrayResultObject GetCollationByServiceId(int serviceId) { return CRMController.GetCollationByServiceId(serviceId); } [WebMethod] public CurrencyArrayResultObject GetCurrency(int packageId) { return CRMController.GetCurrency(packageId); } [WebMethod] public CurrencyArrayResultObject GetCurrencyByServiceId(int serviceId) { return CRMController.GetCurrencyByServiceId(serviceId); } [WebMethod] public ResultObject DeleteCRMOrganization(int organizationId) { return CRMController.DeleteOrganization(organizationId); } [WebMethod] public OrganizationUsersPagedResult GetCRMUsersPaged(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int maximumRows) { return CRMController.GetCRMUsers(itemId, sortColumn, sortDirection, name, email, startRow, maximumRows); } [WebMethod] public IntResult GetCRMUserCount(int itemId, string name, string email, int CALType) { return CRMController.GetCRMUsersCount(itemId, name, email, CALType); } [WebMethod] public UserResult CreateCRMUser(OrganizationUser user, int packageId, int itemId, Guid businessUnitOrgId, int CALType) { return CRMController.CreateCRMUser(user, packageId, itemId, businessUnitOrgId, CALType); } [WebMethod] public CRMBusinessUnitsResult GetBusinessUnits(int itemId, int packageId) { return CRMController.GetCRMBusinessUnits(itemId, packageId); } [WebMethod] public CrmRolesResult GetCrmRoles(int itemId, int accountId, int packageId) { return CRMController.GetCRMRoles(itemId, accountId, packageId); } [WebMethod] public ResultObject SetUserRoles(int itemId, int accountId, int packageId, Guid[] roles) { return CRMController.SetUserRoles(itemId, accountId, packageId, roles); } [WebMethod] public ResultObject SetUserCALType(int itemId, int accountId, int packageId, int CALType) { return CRMController.SetUserCALType(itemId, accountId, packageId, CALType); } [WebMethod] public ResultObject ChangeUserState(int itemId, int accountId, bool disable) { return CRMController.ChangeUserState(itemId, accountId, disable); } [WebMethod] public CrmUserResult GetCrmUser(int itemId, int accountId) { return CRMController.GetCrmUser(itemId, accountId); } [WebMethod] public ResultObject SetMaxDBSize(int itemId, int packageId, long maxSize) { return CRMController.SetMaxDBSize(itemId, packageId, maxSize); } [WebMethod] public long GetDBSize(int itemId, int packageId) { return CRMController.GetDBSize(itemId, packageId); } [WebMethod] public long GetMaxDBSize(int itemId, int packageId) { return CRMController.GetMaxDBSize(itemId, packageId); } [WebMethod] public int[] GetInstalledLanguagePacks(int packageId) { return CRMController.GetInstalledLanguagePacks(packageId); } [WebMethod] public int[] GetInstalledLanguagePacksByServiceId(int serviceId) { return CRMController.GetInstalledLanguagePacksByServiceId(serviceId); } } }
38.392045
221
0.662128
[ "BSD-3-Clause" ]
9192939495969798/Websitepanel
WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esCRM.asmx.cs
6,757
C#
public enum CommandTypes { Unknown, Exit, Help, Set, Test }
11.428571
27
0.55
[ "Unlicense" ]
StewartScottRogers/PubActiveSubService
PubActiveSubService.Console/Library/CommandTypes.cs
82
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 FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p4.Pisp.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Defines headers for Domestic Standing Orders operation. /// </summary> public partial class OBC2DomesticStandingOrdersHeaders1 { /// <summary> /// Initializes a new instance of the /// OBC2DomesticStandingOrdersHeaders1 class. /// </summary> public OBC2DomesticStandingOrdersHeaders1() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// OBC2DomesticStandingOrdersHeaders1 class. /// </summary> /// <param name="xFapiInteractionId">An RFC4122 UID used as a /// correlation id.</param> /// <param name="xJwsSignature">Header containing a detached JWS /// signature of the body of the payload. /// </param> /// <param name="retryAfter">Number in seconds to wait</param> public OBC2DomesticStandingOrdersHeaders1(string xFapiInteractionId = default(string), string xJwsSignature = default(string), int? retryAfter = default(int?)) { XFapiInteractionId = xFapiInteractionId; XJwsSignature = xJwsSignature; RetryAfter = retryAfter; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets an RFC4122 UID used as a correlation id. /// </summary> [JsonProperty(PropertyName = "x-fapi-interaction-id")] public string XFapiInteractionId { get; set; } /// <summary> /// Gets or sets header containing a detached JWS signature of the body /// of the payload. /// /// </summary> [JsonProperty(PropertyName = "x-jws-signature")] public string XJwsSignature { get; set; } /// <summary> /// Gets or sets number in seconds to wait /// </summary> [JsonProperty(PropertyName = "Retry-After")] public int? RetryAfter { get; set; } } }
34.253521
167
0.61102
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p4/Pisp/Models/OBC2DomesticStandingOrdersHeaders1.cs
2,432
C#
using System; using MediatR; namespace BugLog.Application.Customers.Queries { public class GetCustomerDetailQuery : IRequest<CustomerDetailViewModel> { public Guid Id { get; set; } } }
20.5
75
0.717073
[ "MIT" ]
FahadSProgramming/BugLog
BugLog.Application/Customers/Queries/GetCustomerDetail/GetCustomerDetailQuery.cs
205
C#
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using RobotArm; using DynamicWorkAssist; namespace shaft { public class Part { const double PERP_RATIO = .5; Parts.Part part; public void Open(Parts.Part prt) { part = prt; Parts.RegisterHandler(part.name,DeterminePartData2D); } bool DeterminePartData2D(Bitmap bm, Rectangle rect, bool surface, ref DomainShared.ObjData od) { bool rtn = false,no_min = false; int i,j,maxy = 0, maxx = 0,maxz = 0,minz = 0,count = 0,minx = 0,miny = 0,maxw = 0,clipped = 0,minh = 0,too_low = 0,maxh = 0; long sy = 0, sz = 0,sx = 0; RobotArm.Shared.space_3d_mm rcloc = new RobotArm.Shared.space_3d_mm(),ccloc = new RobotArm.Shared.space_3d_mm(),minxpt = new RobotArm.Shared.space_3d_mm(); RobotArm.Shared.space_3d_mm maxypt = new RobotArm.Shared.space_3d_mm(),maxzpt = new RobotArm.Shared.space_3d_mm(),maxxpt = new RobotArm.Shared.space_3d_mm(); RobotArm.Shared.space_3d_mm minzpt = new RobotArm.Shared.space_3d_mm(), minypt = new RobotArm.Shared.space_3d_mm(); TextWriter tw = null; DateTime now = DateTime.Now; string fname; Color color; Point pt = new Point(),tpt = new Point(),fpt = new Point(); fname = RobotArm.Log.LogDir() + "Object analysis " + now.Month + "." + now.Day + "." + now.Year + " " + now.Hour + "." + now.Minute + "-" + RobotArm.Shared.GetUFileNo() + ".csv"; if (surface) no_min = true; else minh = HandDetect.TOP_HEIGHT_CLEAR_MM; tw = File.CreateText(fname); if (tw != null) { tw.WriteLine("Object data set"); tw.WriteLine(now.ToShortDateString() + " " + now.ToShortTimeString()); if (no_min) tw.WriteLine("min height(mm): none"); else tw.WriteLine("min height (mm): " + minh); tw.WriteLine("object name: " + part.name); tw.WriteLine("surface: " + surface); tw.WriteLine(); tw.WriteLine("X,Z,Y"); } for (i = 0; i < rect.Width; i++) { for (j = 0; j < rect.Height; j++) { color = bm.GetPixel(i, j); if ((color.R == 255) && (color.G == 255) & (color.B == 255)) { RobotArm.D415Camera.DetermineLocCC(j + rect.Y, i + rect.X, RobotArm.CameraPanTilt.tilt_deg, ref ccloc, false); RobotArm.Shared.ConvertCC_to_RC(ccloc, ref rcloc, RobotArm.CameraPanTilt.tilt_deg, false); if ((no_min | (rcloc.y > minh)) && (rcloc.z > 0)) { if (count == 0) { minx = rcloc.x + 1; maxx = rcloc.x - 1; miny = rcloc.y + 1; maxy = rcloc.y - 1; maxz = rcloc.z - 1; minz = rcloc.z + 1; } maxw = minx + part.max_dim_mm; maxh = minz + part.max_dim_mm; if ((rcloc.x <= maxw) && (rcloc.z <= maxh)) { if (tw != null) tw.WriteLine(rcloc.x + "," + rcloc.z + "," + rcloc.y); count += 1; if (rcloc.y > maxy ) { maxy = rcloc.y; maxypt.x = rcloc.x; maxypt.y = rcloc.y; maxypt.z = rcloc.z; } if (rcloc.y < miny) { miny = rcloc.y; minypt.x = rcloc.x; minypt.y = rcloc.y; minypt.z = rcloc.z; } if (rcloc.x < minx) { minx = rcloc.x; minxpt.x = rcloc.x; minxpt.y = rcloc.y; minxpt.z = rcloc.z; } if (rcloc.x > maxx) { maxx = rcloc.x; maxxpt.x = rcloc.x; maxxpt.y = rcloc.y; maxxpt.z = rcloc.z; } if (rcloc.z > maxz) { maxz = rcloc.z; maxzpt.x = rcloc.x; maxzpt.y = rcloc.y; maxzpt.z = rcloc.z; } if (rcloc.z < minz) { minz = rcloc.z; minzpt.x = rcloc.x; minzpt.y = rcloc.y; minzpt.z = rcloc.z; } sy += rcloc.y; sz += rcloc.z; sx += rcloc.x; } else clipped += 1; } else if (rcloc.z > 0) too_low += 1; } } } if (count > Parts.MIN_BLOB_AREA) { double dnx,dx; if (tw != null) { tw.WriteLine(); tw.WriteLine(); } od.maxy = maxy; od.minz = minz; od.center.x = (int) Math.Round((double) sx/count); od.center.y = (int) Math.Round((double) sy/count); od.center.z = (int) Math.Round((double) sz/count); if (tw != null) { tw.WriteLine(",,X,Y,Z"); tw.WriteLine("Center point," + od.center.ToCsvString()); tw.WriteLine("Min X first pt," + minxpt.ToCsvString()); tw.WriteLine("Max X first pt," + maxxpt.ToCsvString()); if (surface) { tw.WriteLine("Max Z first pt," + maxzpt.ToCsvString()); tw.WriteLine("Min Z first pt," + minzpt.ToCsvString()); } else { tw.WriteLine("Max Y first pt," + maxypt.ToCsvString()); tw.WriteLine("Min Y first pt," + minypt.ToCsvString()); } } dx = maxxpt.x - minxpt.x; if (surface) { od.pick = od.center; dnx = maxzpt.z - minzpt.z; } else { dnx = maxypt.y - minypt.y; } if (dx/dnx < PERP_RATIO) { tpt.X = maxzpt.x; fpt.X = od.center.x; od.end = maxzpt; if (surface) { tpt.Y = maxzpt.z; fpt.Y = od.center.z; } else { tpt.Y = maxzpt.y; fpt.Y = od.center.y; od.pick.x = (int) Math.Round((double) (maxzpt.x + od.center.x)/2); od.pick.y = (int)Math.Round((double) (maxzpt.y + od.center.y)/ 2); od.pick.z = (int)Math.Round((double) (maxzpt.z + od.center.z)/ 2); } } else { tpt.X = minxpt.x; fpt.X = od.center.x; od.end = minxpt; if (surface) { tpt.Y = minxpt.z; fpt.Y = od.center.z; } else { tpt.Y = minxpt.y; fpt.Y = od.center.y; od.pick = minxpt; od.pick.x = (int) Math.Round((double) (minxpt.x + od.center.x)/ 2); od.pick.y = (int) Math.Round((double) (minxpt.y + od.center.y)/ 2); od.pick.z = (int) Math.Round((double) (minxpt.z + od.center.z)/ 2); } } od.planeorient = Shared.DetermineOrient(tpt, fpt); if (Math.Abs(od.planeorient) > 90) if (od.planeorient > 0) od.planeorient -= 180; else od.planeorient += 180; if (tw != null) { tw.WriteLine("dx/dnx," + dx/dnx); tw.WriteLine("center point," + od.center.ToCsvString()); tw.WriteLine("end point," + od.end.ToCsvString()); tw.WriteLine("pick point," + od.pick.ToCsvString()); tw.WriteLine("gripper orientation," + od.planeorient); tw.WriteLine(); tw.WriteLine(); tw.WriteLine("final maxw: " + maxw); tw.WriteLine("final maxh: " + maxh); tw.WriteLine("clipped pts: " + clipped); tw.WriteLine("too low pts: " + too_low); tw.WriteLine("no pts: " + count + " " + od.ToString()); tw.WriteLine("maxx: " + maxx + " minx: " + minx + " maxy: " + maxy + " miny: " + miny + " maxz: " + maxz + " minz: " + minz); tw.Close(); RobotArm.Log.LogEntry("Saved: " + fname); } Bitmap nbm = (Bitmap)RobotArm.Shared.vimg.Clone(); Graphics g = Graphics.FromImage(nbm); if (!surface) { RobotArm.Shared.ConvertRC_to_CC(od.center, ref ccloc, RobotArm.CameraPanTilt.tilt_deg); RobotArm.D415Camera.DetermineVid(ccloc, RobotArm.CameraPanTilt.tilt_deg, ref pt); g.DrawRectangle(Pens.Red, rect); rect.X = pt.X - 2; rect.Y = pt.Y - 2; rect.Width = 4; rect.Height = 4; g.FillRectangle(Brushes.Red, rect); } RobotArm.Shared.ConvertRC_to_CC(od.pick, ref ccloc, RobotArm.CameraPanTilt.tilt_deg); RobotArm.D415Camera.DetermineVid(ccloc, RobotArm.CameraPanTilt.tilt_deg, ref pt); g.DrawRectangle(Pens.Red,rect); rect.X = pt.X - 2; rect.Y = pt.Y - 2; rect.Width = 4; rect.Height = 4; g.FillRectangle(Brushes.Red,rect); RobotArm.Shared.ConvertRC_to_CC(od.end, ref ccloc, RobotArm.CameraPanTilt.tilt_deg); RobotArm.D415Camera.DetermineVid(ccloc, RobotArm.CameraPanTilt.tilt_deg, ref pt); rect.X = pt.X - 2; rect.Y = pt.Y - 2; rect.Width = 4; rect.Height = 4; g.FillRectangle(Brushes.Yellow, rect); RobotArm.Shared.SaveVideoPic(nbm); RobotArm.Shared.SaveDeptBin(); rtn = true; } else if (tw != null) { tw.WriteLine(); tw.WriteLine(count + " points is insufficent data for analysis"); tw.Close(); } else RobotArm.Log.LogEntry(count + " points is insufficent data for analysis"); return (rtn); } } }
29.391753
181
0.551385
[ "MIT" ]
terry-ess/ARA
domains/DynamicWorkAssist/shaft/Part.cs
8,555
C#
namespace Fluxera.Utilities.UnitTests.Extensions.String { using System.Globalization; using FluentAssertions; using NUnit.Framework; using Utilities.Extensions; [TestFixture] public class RemoveSpecialCharactersTests { [SetUp] public void Setup() { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); } [Test] public void ShouldRemoveSpecialCharacters() { // Arrange string str = "!32§1%abc$x(y)z&1?2=3"; // Act string result = str.RemoveSpecialCharacters(); // Assert result.Should().Be("321abcxyz123"); } [Test] public void ShouldRemoveSpecialCharactersWithIgnoreList() { // Arrange string str = "!32§1%abc$x(y)z&1?2=3"; // Act string result = str.RemoveSpecialCharacters('$'); // Assert result.Should().Be("321abc$xyz123"); } } }
18.772727
68
0.682809
[ "MIT" ]
fluxera/Fluxera.Utilities
tests/Fluxera.Utilities.UnitTests/Extensions/String/RemoveSpecialCharactersTests.cs
830
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; using System.IO; namespace Magick.NET.Tests { public class TemporaryDirectory : IDisposable { private DirectoryInfo _tempDirectory; public TemporaryDirectory() : this(string.Empty) { } public TemporaryDirectory(string directoryName) { _tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + directoryName)); _tempDirectory.Create(); } public string FullName => _tempDirectory.FullName; public void Dispose() => Cleanup.DeleteDirectory(_tempDirectory); } }
25.096774
124
0.636247
[ "Apache-2.0" ]
AFWberlin/Magick.NET
tests/Magick.NET.Tests/TestHelpers/TemporaryDirectory.cs
780
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace BookReservationSystem { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
26.363636
70
0.712069
[ "MIT" ]
geroqu/Book-Reservation-System
BookReservationSystem/Global.asax.cs
582
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Threading.Tasks; namespace IdNet6.Validation { /// <summary> /// Allows inserting custom token validation logic /// </summary> public interface ICustomTokenValidator { /// <summary> /// Custom validation logic for access tokens. /// </summary> /// <param name="result">The validation result so far.</param> /// <returns>The validation result</returns> Task<TokenValidationResult> ValidateAccessTokenAsync(TokenValidationResult result); /// <summary> /// Custom validation logic for identity tokens. /// </summary> /// <param name="result">The validation result so far.</param> /// <returns>The validation result</returns> Task<TokenValidationResult> ValidateIdentityTokenAsync(TokenValidationResult result); } }
36.607143
107
0.669268
[ "Apache-2.0" ]
simple0x47/IdNet6
src/IdNet6/src/Validation/ICustomTokenValidator.cs
1,027
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Valve.VR { using System; using UnityEngine; public partial class SteamVR_Actions { private static SteamVR_Input_ActionSet_default p__default; private static SteamVR_Input_ActionSet_platformer p_platformer; private static SteamVR_Input_ActionSet_buggy p_buggy; private static SteamVR_Input_ActionSet_mixedreality p_mixedreality; private static SteamVR_Input_ActionSet_vrsketch p_vrsketch; public static SteamVR_Input_ActionSet_default _default { get { return SteamVR_Actions.p__default.GetCopy<SteamVR_Input_ActionSet_default>(); } } public static SteamVR_Input_ActionSet_platformer platformer { get { return SteamVR_Actions.p_platformer.GetCopy<SteamVR_Input_ActionSet_platformer>(); } } public static SteamVR_Input_ActionSet_buggy buggy { get { return SteamVR_Actions.p_buggy.GetCopy<SteamVR_Input_ActionSet_buggy>(); } } public static SteamVR_Input_ActionSet_mixedreality mixedreality { get { return SteamVR_Actions.p_mixedreality.GetCopy<SteamVR_Input_ActionSet_mixedreality>(); } } public static SteamVR_Input_ActionSet_vrsketch vrsketch { get { return SteamVR_Actions.p_vrsketch.GetCopy<SteamVR_Input_ActionSet_vrsketch>(); } } private static void StartPreInitActionSets() { SteamVR_Actions.p__default = ((SteamVR_Input_ActionSet_default)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_default>("/actions/default"))); SteamVR_Actions.p_platformer = ((SteamVR_Input_ActionSet_platformer)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_platformer>("/actions/platformer"))); SteamVR_Actions.p_buggy = ((SteamVR_Input_ActionSet_buggy)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_buggy>("/actions/buggy"))); SteamVR_Actions.p_mixedreality = ((SteamVR_Input_ActionSet_mixedreality)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_mixedreality>("/actions/mixedreality"))); SteamVR_Actions.p_vrsketch = ((SteamVR_Input_ActionSet_vrsketch)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_vrsketch>("/actions/vrsketch"))); Valve.VR.SteamVR_Input.actionSets = new Valve.VR.SteamVR_ActionSet[] { SteamVR_Actions._default, SteamVR_Actions.platformer, SteamVR_Actions.buggy, SteamVR_Actions.mixedreality, SteamVR_Actions.vrsketch}; } } }
38.27907
175
0.609052
[ "MIT" ]
V-Sekai/CASSIE
Assets/SteamVR_Input/SteamVR_Input_ActionSets.cs
3,292
C#
/* Copyright 2021 Enjin Pte. Ltd. * * 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 JetBrains.Annotations; using Newtonsoft.Json; namespace Enjin.SDK.Models { /// <summary> /// Models a smart contract used by the platform. /// </summary> [PublicAPI] public class Contracts { /// <summary> /// Represents the ENJ contract address. /// </summary> /// <value>The contract address.</value> [JsonProperty("enj")] public string? Enj { get; private set; } /// <summary> /// Represents the crypto items contract address. /// </summary> /// <value>The contract address.</value> [JsonProperty("cryptoItems")] public string? CryptoItems { get; private set; } /// <summary> /// Represents the platform registry contract address. /// </summary> /// <value>The contract address.</value> [JsonProperty("platformRegistry")] public string? PlatformRegistry { get; private set; } /// <summary> /// Represents the supply models used by the platform. /// </summary> /// <value>The supply models.</value> [JsonProperty("supplyModels")] public SupplyModels? SupplyModels { get; private set; } } }
33.472727
75
0.622488
[ "Apache-2.0" ]
VisionGameOrg/enjin-csharp-sdk
EnjinCSharpSDK/Models/Contracts.cs
1,841
C#
using cloudscribe.Logging.Models; using cloudscribe.Logging.Web; using cloudscribe.Logging.Web.Models; using cloudscribe.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Configuration; namespace Microsoft.Extensions.DependencyInjection { public static class StartupExtensions { public static IServiceCollection AddCloudscribeLogging( this IServiceCollection services, IConfiguration config = null ) { services.AddScoped<IWebRequestInfoProvider, WebRequestInfoProvider>(); services.AddScoped<LogManager>(); services.AddScoped<IVersionProvider, VersionProvider>(); if(config != null) { services.Configure<DbLoggerConfig>(config.GetSection("DbLoggerConfig")); } else { services.Configure<DbLoggerConfig>(logConfig => { }); } return services; } public static AuthorizationOptions AddCloudscribeLoggingDefaultPolicy(this AuthorizationOptions options) { options.AddPolicy( "SystemLogPolicy", authBuilder => { authBuilder.RequireRole("ServerAdmins"); }); return options; } } }
29.44
113
0.561821
[ "Apache-2.0" ]
cloudscribe/cloudscribe.Logging
src/cloudscribe.Logging.Web/StartupExtensions.cs
1,474
C#
/* * Copyright (c) 2021 ETH Zürich, Educational Development and Technology (LET) * * 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.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using SafeExamBrowser.Logging.Contracts; using SafeExamBrowser.Settings.Logging; namespace SafeExamBrowser.Logging.UnitTests { [TestClass] public class LoggerTests { [TestMethod] public void MustAddMessagesToLog() { var sut = new Logger(); var debug = "I'm a debug message"; var info = "I'm an info message"; var warn = "I'm a warning!"; var error = "I AM AN ERROR!!"; var exceptionMessage = "I'm an exception message"; var exception = new Exception(exceptionMessage); var message = "I'm a simple text message"; sut.Debug(debug); sut.Info(info); sut.Warn(warn); sut.Error(error); sut.Error(error, exception); sut.Log(message); var log = sut.GetLog(); Assert.IsTrue(log.Count == 7); Assert.IsTrue(debug.Equals((log[0] as ILogMessage).Message)); Assert.IsTrue((log[0] as ILogMessage).Severity == LogLevel.Debug); Assert.IsTrue(info.Equals((log[1] as ILogMessage).Message)); Assert.IsTrue((log[1] as ILogMessage).Severity == LogLevel.Info); Assert.IsTrue(warn.Equals((log[2] as ILogMessage).Message)); Assert.IsTrue((log[2] as ILogMessage).Severity == LogLevel.Warning); Assert.IsTrue(error.Equals((log[3] as ILogMessage).Message)); Assert.IsTrue((log[3] as ILogMessage).Severity == LogLevel.Error); Assert.IsTrue(error.Equals((log[4] as ILogMessage).Message)); Assert.IsTrue((log[4] as ILogMessage).Severity == LogLevel.Error); Assert.IsTrue((log[5] as ILogText).Text.Contains(exceptionMessage)); Assert.IsTrue(message.Equals((log[6] as ILogText).Text)); } [TestMethod] public void MustAddInnerExceptionsToLog() { var sut = new Logger(); var outerMessage = "Some message for the outer exception"; var innerMessage = "BAAAAM! Inner one here."; var innerInnerMessage = "Yikes, a null reference..."; var exception = new Exception(outerMessage, new ArgumentException(innerMessage, new NullReferenceException(innerInnerMessage))); sut.Error("blubb", exception); var log = sut.GetLog(); var logText = log[1] as ILogText; Assert.AreEqual(2, log.Count); Assert.IsTrue(logText.Text.Contains(outerMessage)); Assert.IsTrue(logText.Text.Contains(innerMessage)); Assert.IsTrue(logText.Text.Contains(innerInnerMessage)); } [TestMethod] public void MustReturnCopyOfLog() { var sut = new Logger(); var debug = "I'm a debug message"; var info = "I'm an info message"; var warn = "I'm a warning!"; var error = "I AM AN ERROR!!"; sut.Debug(debug); sut.Info(info); sut.Warn(warn); sut.Error(error); var log1 = sut.GetLog(); var log2 = sut.GetLog(); Assert.AreNotSame(log1, log2); foreach (var message in log1) { Assert.AreNotSame(message, log2[log1.IndexOf(message)]); } } [TestMethod] public void MustNotAllowLoggingNull() { var sut = new Logger(); Assert.ThrowsException<ArgumentNullException>(() => sut.Debug(null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Info(null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Warn(null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Error(null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Error(null, null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Error("Hello world!", null)); Assert.ThrowsException<ArgumentNullException>(() => sut.Error(null, new Exception())); Assert.ThrowsException<ArgumentNullException>(() => sut.Log((string) null)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void MustNotAllowNullObserver() { var sut = new Logger(); sut.Subscribe(null); } [TestMethod] public void MustNotSubscribeSameObserverMultipleTimes() { var sut = new Logger(); var observer = new Mock<ILogObserver>(); observer.Setup(o => o.Notify(It.IsAny<ILogMessage>())); sut.Subscribe(observer.Object); sut.Subscribe(observer.Object); sut.Subscribe(observer.Object); sut.Info("Blubb"); observer.Verify(o => o.Notify(It.IsAny<ILogMessage>()), Times.Once()); } [TestMethod] public void MustNotFailWhenRemovingNullObserver() { var sut = new Logger(); sut.Unsubscribe(null); } [TestMethod] public void MustSubscribeObserver() { var sut = new Logger(); var observer = new Mock<ILogObserver>(); var message = "Blubb"; var messages = new List<ILogContent>(); observer.Setup(o => o.Notify(It.IsAny<ILogContent>())).Callback<ILogContent>(m => messages.Add(m)); sut.Subscribe(observer.Object); sut.Info(message); sut.Warn(message); observer.Verify(o => o.Notify(It.IsAny<ILogContent>()), Times.Exactly(2)); Assert.IsTrue(messages.Count == 2); Assert.IsTrue((messages[0] as ILogMessage).Severity == LogLevel.Info); Assert.IsTrue(message.Equals((messages[0] as ILogMessage).Message)); Assert.IsTrue((messages[1] as ILogMessage).Severity == LogLevel.Warning); Assert.IsTrue(message.Equals((messages[1] as ILogMessage).Message)); } [TestMethod] public void MustRespectLogLevel() { var sut = new Logger(); sut.LogLevel = LogLevel.Error; sut.Debug("debug"); sut.Info("info"); sut.Warn("warn"); Assert.AreEqual(0, sut.GetLog().Count); sut = new Logger(); sut.LogLevel = LogLevel.Warning; sut.Debug("debug"); sut.Info("info"); sut.Warn("warn"); Assert.AreEqual(1, sut.GetLog().Count); sut = new Logger(); sut.LogLevel = LogLevel.Info; sut.Debug("debug"); sut.Info("info"); sut.Warn("warn"); Assert.AreEqual(2, sut.GetLog().Count); sut = new Logger(); sut.LogLevel = LogLevel.Debug; sut.Debug("debug"); sut.Info("info"); sut.Warn("warn"); Assert.AreEqual(3, sut.GetLog().Count); } [TestMethod] public void MustUnsubscribeObserver() { var sut = new Logger(); var observer = new Mock<ILogObserver>(); var message = "Blubb"; var messages = new List<ILogContent>(); observer.Setup(o => o.Notify(It.IsAny<ILogContent>())).Callback<ILogContent>(m => messages.Add(m)); sut.Subscribe(observer.Object); sut.Info(message); sut.Unsubscribe(observer.Object); sut.Warn(message); observer.Verify(o => o.Notify(It.IsAny<ILogContent>()), Times.Once()); Assert.IsTrue(messages.Count == 1); Assert.IsTrue((messages[0] as ILogMessage).Severity == LogLevel.Info); Assert.IsTrue(message.Equals((messages[0] as ILogMessage).Message)); } } }
28.127572
131
0.683687
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Bien-Technologies/seb-win-refactoring
SafeExamBrowser.Logging.UnitTests/LoggerTests.cs
6,838
C#
/* * [The "BSD Licence"] * Copyright (c) 2011-2012 Chundong Gao * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. */ namespace Gimela.Knifer.CommandLines.ProcessStatus { internal class ProcessStatusCommandLineOptions { public ProcessStatusCommandLineOptions() { } public bool IsSetHelp { get; set; } public bool IsSetVersion { get; set; } } }
42.731707
76
0.753425
[ "MIT" ]
J-W-Chan/Gimela
src/Knifer/Gimela.Knifer.CommandLines.ProcessStatus/ProcessStatusCommandLineOptions.cs
1,756
C#
// <auto-generated/> // Contents of: hl7.fhir.r4.core version: 4.0.1 using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using Hl7.Fhir.Model; using Hl7.Fhir.Model.JsonExtensions; using Hl7.Fhir.Serialization; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ namespace Hl7.Fhir.Model.JsonExtensions { /// <summary> /// JSON Serialization Extensions for RequestGroup /// </summary> public static class RequestGroupJsonExtensions { /// <summary> /// Serialize a FHIR RequestGroup into JSON /// </summary> public static void SerializeJson(this RequestGroup current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } writer.WriteString("resourceType","RequestGroup"); // Complex: RequestGroup, Export: RequestGroup, Base: DomainResource (DomainResource) ((Hl7.Fhir.Model.DomainResource)current).SerializeJson(writer, options, false); if ((current.Identifier != null) && (current.Identifier.Count != 0)) { writer.WritePropertyName("identifier"); writer.WriteStartArray(); foreach (Identifier val in current.Identifier) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.InstantiatesCanonicalElement != null) && (current.InstantiatesCanonicalElement.Count != 0)) { int valueCount = 0; int extensionCount = 0; foreach (Canonical val in current.InstantiatesCanonicalElement) { if (!string.IsNullOrEmpty(val.Value)) { valueCount++; } if (val.HasExtensions()) { extensionCount++; } } if (valueCount > 0) { writer.WritePropertyName("instantiatesCanonical"); writer.WriteStartArray(); foreach (Canonical val in current.InstantiatesCanonicalElement) { if (string.IsNullOrEmpty(val.Value)) { writer.WriteNullValue(); } else { writer.WriteStringValue(val.Value); } } writer.WriteEndArray(); } if (extensionCount > 0) { writer.WritePropertyName("_instantiatesCanonical"); writer.WriteStartArray(); foreach (Canonical val in current.InstantiatesCanonicalElement) { if (val.HasExtensions() || (!string.IsNullOrEmpty(val.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,string.Empty,true,val.Extension,val.ElementId); } else { writer.WriteNullValue(); } } writer.WriteEndArray(); } } if ((current.InstantiatesUriElement != null) && (current.InstantiatesUriElement.Count != 0)) { int valueCount = 0; int extensionCount = 0; foreach (FhirUri val in current.InstantiatesUriElement) { if (!string.IsNullOrEmpty(val.Value)) { valueCount++; } if (val.HasExtensions()) { extensionCount++; } } if (valueCount > 0) { writer.WritePropertyName("instantiatesUri"); writer.WriteStartArray(); foreach (FhirUri val in current.InstantiatesUriElement) { if (string.IsNullOrEmpty(val.Value)) { writer.WriteNullValue(); } else { writer.WriteStringValue(val.Value); } } writer.WriteEndArray(); } if (extensionCount > 0) { writer.WritePropertyName("_instantiatesUri"); writer.WriteStartArray(); foreach (FhirUri val in current.InstantiatesUriElement) { if (val.HasExtensions() || (!string.IsNullOrEmpty(val.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,string.Empty,true,val.Extension,val.ElementId); } else { writer.WriteNullValue(); } } writer.WriteEndArray(); } } if ((current.BasedOn != null) && (current.BasedOn.Count != 0)) { writer.WritePropertyName("basedOn"); writer.WriteStartArray(); foreach (ResourceReference val in current.BasedOn) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.Replaces != null) && (current.Replaces.Count != 0)) { writer.WritePropertyName("replaces"); writer.WriteStartArray(); foreach (ResourceReference val in current.Replaces) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (current.GroupIdentifier != null) { writer.WritePropertyName("groupIdentifier"); current.GroupIdentifier.SerializeJson(writer, options); } writer.WriteString("status",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.StatusElement.Value)); writer.WriteString("intent",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.IntentElement.Value)); if (current.PriorityElement != null) { if (current.PriorityElement.Value != null) { writer.WriteString("priority",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.PriorityElement.Value)); } if (current.PriorityElement.HasExtensions() || (!string.IsNullOrEmpty(current.PriorityElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_priority",false,current.PriorityElement.Extension,current.PriorityElement.ElementId); } } if (current.Code != null) { writer.WritePropertyName("code"); current.Code.SerializeJson(writer, options); } if (current.Subject != null) { writer.WritePropertyName("subject"); current.Subject.SerializeJson(writer, options); } if (current.Encounter != null) { writer.WritePropertyName("encounter"); current.Encounter.SerializeJson(writer, options); } if (current.AuthoredOnElement != null) { if (!string.IsNullOrEmpty(current.AuthoredOnElement.Value)) { writer.WriteString("authoredOn",current.AuthoredOnElement.Value); } if (current.AuthoredOnElement.HasExtensions() || (!string.IsNullOrEmpty(current.AuthoredOnElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_authoredOn",false,current.AuthoredOnElement.Extension,current.AuthoredOnElement.ElementId); } } if (current.Author != null) { writer.WritePropertyName("author"); current.Author.SerializeJson(writer, options); } if ((current.ReasonCode != null) && (current.ReasonCode.Count != 0)) { writer.WritePropertyName("reasonCode"); writer.WriteStartArray(); foreach (CodeableConcept val in current.ReasonCode) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.ReasonReference != null) && (current.ReasonReference.Count != 0)) { writer.WritePropertyName("reasonReference"); writer.WriteStartArray(); foreach (ResourceReference val in current.ReasonReference) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.Note != null) && (current.Note.Count != 0)) { writer.WritePropertyName("note"); writer.WriteStartArray(); foreach (Annotation val in current.Note) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.Action != null) && (current.Action.Count != 0)) { writer.WritePropertyName("action"); writer.WriteStartArray(); foreach (RequestGroup.ActionComponent val in current.Action) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize JSON into a FHIR RequestGroup /// </summary> public static void DeserializeJson(this RequestGroup current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"RequestGroup >>> RequestGroup.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"RequestGroup: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } /// <summary> /// Deserialize JSON into a FHIR RequestGroup /// </summary> public static void DeserializeJsonProperty(this RequestGroup current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "identifier": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'identifier' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Identifier = new List<Identifier>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.Identifier v_Identifier = new Hl7.Fhir.Model.Identifier(); v_Identifier.DeserializeJson(ref reader, options); current.Identifier.Add(v_Identifier); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'identifier' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Identifier.Count == 0) { current.Identifier = null; } break; case "instantiatesCanonical": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'instantiatesCanonical' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.InstantiatesCanonicalElement = new List<Canonical>(); while (reader.TokenType != JsonTokenType.EndArray) { if (reader.TokenType == JsonTokenType.Null) { current.InstantiatesCanonicalElement.Add(new Canonical()); reader.Skip(); } else { current.InstantiatesCanonicalElement.Add(new Canonical(reader.GetString())); } if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'instantiatesCanonical' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.InstantiatesCanonicalElement.Count == 0) { current.InstantiatesCanonicalElement = null; } break; case "_instantiatesCanonical": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'instantiatesCanonical' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } int i_instantiatesCanonical = 0; while (reader.TokenType != JsonTokenType.EndArray) { if (i_instantiatesCanonical >= current.InstantiatesCanonicalElement.Count) { current.InstantiatesCanonicalElement.Add(new Canonical()); } if (reader.TokenType == JsonTokenType.Null) { reader.Skip(); } else { ((Hl7.Fhir.Model.Element)current.InstantiatesCanonicalElement[i_instantiatesCanonical++]).DeserializeJson(ref reader, options); } if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'instantiatesCanonical' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } break; case "instantiatesUri": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'instantiatesUri' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.InstantiatesUriElement = new List<FhirUri>(); while (reader.TokenType != JsonTokenType.EndArray) { if (reader.TokenType == JsonTokenType.Null) { current.InstantiatesUriElement.Add(new FhirUri()); reader.Skip(); } else { current.InstantiatesUriElement.Add(new FhirUri(reader.GetString())); } if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'instantiatesUri' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.InstantiatesUriElement.Count == 0) { current.InstantiatesUriElement = null; } break; case "_instantiatesUri": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'instantiatesUri' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } int i_instantiatesUri = 0; while (reader.TokenType != JsonTokenType.EndArray) { if (i_instantiatesUri >= current.InstantiatesUriElement.Count) { current.InstantiatesUriElement.Add(new FhirUri()); } if (reader.TokenType == JsonTokenType.Null) { reader.Skip(); } else { ((Hl7.Fhir.Model.Element)current.InstantiatesUriElement[i_instantiatesUri++]).DeserializeJson(ref reader, options); } if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'instantiatesUri' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } break; case "basedOn": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'basedOn' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.BasedOn = new List<ResourceReference>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.ResourceReference v_BasedOn = new Hl7.Fhir.Model.ResourceReference(); v_BasedOn.DeserializeJson(ref reader, options); current.BasedOn.Add(v_BasedOn); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'basedOn' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.BasedOn.Count == 0) { current.BasedOn = null; } break; case "replaces": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'replaces' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Replaces = new List<ResourceReference>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.ResourceReference v_Replaces = new Hl7.Fhir.Model.ResourceReference(); v_Replaces.DeserializeJson(ref reader, options); current.Replaces.Add(v_Replaces); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'replaces' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Replaces.Count == 0) { current.Replaces = null; } break; case "groupIdentifier": current.GroupIdentifier = new Hl7.Fhir.Model.Identifier(); ((Hl7.Fhir.Model.Identifier)current.GroupIdentifier).DeserializeJson(ref reader, options); break; case "status": if (reader.TokenType == JsonTokenType.Null) { current.StatusElement = new Code<Hl7.Fhir.Model.RequestStatus>(); reader.Skip(); } else { current.StatusElement = new Code<Hl7.Fhir.Model.RequestStatus>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.RequestStatus>(reader.GetString())); } break; case "_status": if (current.StatusElement == null) { current.StatusElement = new Code<Hl7.Fhir.Model.RequestStatus>(); } ((Hl7.Fhir.Model.Element)current.StatusElement).DeserializeJson(ref reader, options); break; case "intent": if (reader.TokenType == JsonTokenType.Null) { current.IntentElement = new Code<Hl7.Fhir.Model.RequestIntent>(); reader.Skip(); } else { current.IntentElement = new Code<Hl7.Fhir.Model.RequestIntent>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.RequestIntent>(reader.GetString())); } break; case "_intent": if (current.IntentElement == null) { current.IntentElement = new Code<Hl7.Fhir.Model.RequestIntent>(); } ((Hl7.Fhir.Model.Element)current.IntentElement).DeserializeJson(ref reader, options); break; case "priority": if (reader.TokenType == JsonTokenType.Null) { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(); reader.Skip(); } else { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.RequestPriority>(reader.GetString())); } break; case "_priority": if (current.PriorityElement == null) { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(); } ((Hl7.Fhir.Model.Element)current.PriorityElement).DeserializeJson(ref reader, options); break; case "code": current.Code = new Hl7.Fhir.Model.CodeableConcept(); ((Hl7.Fhir.Model.CodeableConcept)current.Code).DeserializeJson(ref reader, options); break; case "subject": current.Subject = new Hl7.Fhir.Model.ResourceReference(); ((Hl7.Fhir.Model.ResourceReference)current.Subject).DeserializeJson(ref reader, options); break; case "encounter": current.Encounter = new Hl7.Fhir.Model.ResourceReference(); ((Hl7.Fhir.Model.ResourceReference)current.Encounter).DeserializeJson(ref reader, options); break; case "authoredOn": if (reader.TokenType == JsonTokenType.Null) { current.AuthoredOnElement = new FhirDateTime(); reader.Skip(); } else { current.AuthoredOnElement = new FhirDateTime(reader.GetString()); } break; case "_authoredOn": if (current.AuthoredOnElement == null) { current.AuthoredOnElement = new FhirDateTime(); } ((Hl7.Fhir.Model.Element)current.AuthoredOnElement).DeserializeJson(ref reader, options); break; case "author": current.Author = new Hl7.Fhir.Model.ResourceReference(); ((Hl7.Fhir.Model.ResourceReference)current.Author).DeserializeJson(ref reader, options); break; case "reasonCode": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'reasonCode' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.ReasonCode = new List<CodeableConcept>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.CodeableConcept v_ReasonCode = new Hl7.Fhir.Model.CodeableConcept(); v_ReasonCode.DeserializeJson(ref reader, options); current.ReasonCode.Add(v_ReasonCode); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'reasonCode' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.ReasonCode.Count == 0) { current.ReasonCode = null; } break; case "reasonReference": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'reasonReference' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.ReasonReference = new List<ResourceReference>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.ResourceReference v_ReasonReference = new Hl7.Fhir.Model.ResourceReference(); v_ReasonReference.DeserializeJson(ref reader, options); current.ReasonReference.Add(v_ReasonReference); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'reasonReference' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.ReasonReference.Count == 0) { current.ReasonReference = null; } break; case "note": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'note' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Note = new List<Annotation>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.Annotation v_Note = new Hl7.Fhir.Model.Annotation(); v_Note.DeserializeJson(ref reader, options); current.Note.Add(v_Note); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'note' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Note.Count == 0) { current.Note = null; } break; case "action": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"RequestGroup error reading 'action' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Action = new List<RequestGroup.ActionComponent>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.RequestGroup.ActionComponent v_Action = new Hl7.Fhir.Model.RequestGroup.ActionComponent(); v_Action.DeserializeJson(ref reader, options); current.Action.Add(v_Action); if (!reader.Read()) { throw new JsonException($"RequestGroup error reading 'action' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Action.Count == 0) { current.Action = null; } break; // Complex: RequestGroup, Export: RequestGroup, Base: DomainResource default: ((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Serialize a FHIR RequestGroup#Action into JSON /// </summary> public static void SerializeJson(this RequestGroup.ActionComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } // Component: RequestGroup#Action, Export: ActionComponent, Base: BackboneElement (BackboneElement) ((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false); if (current.PrefixElement != null) { if (!string.IsNullOrEmpty(current.PrefixElement.Value)) { writer.WriteString("prefix",current.PrefixElement.Value); } if (current.PrefixElement.HasExtensions() || (!string.IsNullOrEmpty(current.PrefixElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_prefix",false,current.PrefixElement.Extension,current.PrefixElement.ElementId); } } if (current.TitleElement != null) { if (!string.IsNullOrEmpty(current.TitleElement.Value)) { writer.WriteString("title",current.TitleElement.Value); } if (current.TitleElement.HasExtensions() || (!string.IsNullOrEmpty(current.TitleElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_title",false,current.TitleElement.Extension,current.TitleElement.ElementId); } } if (current.DescriptionElement != null) { if (!string.IsNullOrEmpty(current.DescriptionElement.Value)) { writer.WriteString("description",current.DescriptionElement.Value); } if (current.DescriptionElement.HasExtensions() || (!string.IsNullOrEmpty(current.DescriptionElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_description",false,current.DescriptionElement.Extension,current.DescriptionElement.ElementId); } } if (current.TextEquivalentElement != null) { if (!string.IsNullOrEmpty(current.TextEquivalentElement.Value)) { writer.WriteString("textEquivalent",current.TextEquivalentElement.Value); } if (current.TextEquivalentElement.HasExtensions() || (!string.IsNullOrEmpty(current.TextEquivalentElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_textEquivalent",false,current.TextEquivalentElement.Extension,current.TextEquivalentElement.ElementId); } } if (current.PriorityElement != null) { if (current.PriorityElement.Value != null) { writer.WriteString("priority",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.PriorityElement.Value)); } if (current.PriorityElement.HasExtensions() || (!string.IsNullOrEmpty(current.PriorityElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_priority",false,current.PriorityElement.Extension,current.PriorityElement.ElementId); } } if ((current.Code != null) && (current.Code.Count != 0)) { writer.WritePropertyName("code"); writer.WriteStartArray(); foreach (CodeableConcept val in current.Code) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.Documentation != null) && (current.Documentation.Count != 0)) { writer.WritePropertyName("documentation"); writer.WriteStartArray(); foreach (RelatedArtifact val in current.Documentation) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.Condition != null) && (current.Condition.Count != 0)) { writer.WritePropertyName("condition"); writer.WriteStartArray(); foreach (RequestGroup.ConditionComponent val in current.Condition) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((current.RelatedAction != null) && (current.RelatedAction.Count != 0)) { writer.WritePropertyName("relatedAction"); writer.WriteStartArray(); foreach (RequestGroup.RelatedActionComponent val in current.RelatedAction) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (current.Timing != null) { switch (current.Timing) { case FhirDateTime v_FhirDateTime: if (v_FhirDateTime != null) { if (!string.IsNullOrEmpty(v_FhirDateTime.Value)) { writer.WriteString("timingDateTime",v_FhirDateTime.Value); } if (v_FhirDateTime.HasExtensions() || (!string.IsNullOrEmpty(v_FhirDateTime.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_timingDateTime",false,v_FhirDateTime.Extension,v_FhirDateTime.ElementId); } } break; case Age v_Age: writer.WritePropertyName("timingAge"); v_Age.SerializeJson(writer, options); break; case Period v_Period: writer.WritePropertyName("timingPeriod"); v_Period.SerializeJson(writer, options); break; case Duration v_Duration: writer.WritePropertyName("timingDuration"); v_Duration.SerializeJson(writer, options); break; case Range v_Range: writer.WritePropertyName("timingRange"); v_Range.SerializeJson(writer, options); break; case Timing v_Timing: writer.WritePropertyName("timingTiming"); v_Timing.SerializeJson(writer, options); break; } } if ((current.Participant != null) && (current.Participant.Count != 0)) { writer.WritePropertyName("participant"); writer.WriteStartArray(); foreach (ResourceReference val in current.Participant) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (current.Type != null) { writer.WritePropertyName("type"); current.Type.SerializeJson(writer, options); } if (current.GroupingBehaviorElement != null) { if (current.GroupingBehaviorElement.Value != null) { writer.WriteString("groupingBehavior",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.GroupingBehaviorElement.Value)); } if (current.GroupingBehaviorElement.HasExtensions() || (!string.IsNullOrEmpty(current.GroupingBehaviorElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_groupingBehavior",false,current.GroupingBehaviorElement.Extension,current.GroupingBehaviorElement.ElementId); } } if (current.SelectionBehaviorElement != null) { if (current.SelectionBehaviorElement.Value != null) { writer.WriteString("selectionBehavior",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.SelectionBehaviorElement.Value)); } if (current.SelectionBehaviorElement.HasExtensions() || (!string.IsNullOrEmpty(current.SelectionBehaviorElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_selectionBehavior",false,current.SelectionBehaviorElement.Extension,current.SelectionBehaviorElement.ElementId); } } if (current.RequiredBehaviorElement != null) { if (current.RequiredBehaviorElement.Value != null) { writer.WriteString("requiredBehavior",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.RequiredBehaviorElement.Value)); } if (current.RequiredBehaviorElement.HasExtensions() || (!string.IsNullOrEmpty(current.RequiredBehaviorElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_requiredBehavior",false,current.RequiredBehaviorElement.Extension,current.RequiredBehaviorElement.ElementId); } } if (current.PrecheckBehaviorElement != null) { if (current.PrecheckBehaviorElement.Value != null) { writer.WriteString("precheckBehavior",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.PrecheckBehaviorElement.Value)); } if (current.PrecheckBehaviorElement.HasExtensions() || (!string.IsNullOrEmpty(current.PrecheckBehaviorElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_precheckBehavior",false,current.PrecheckBehaviorElement.Extension,current.PrecheckBehaviorElement.ElementId); } } if (current.CardinalityBehaviorElement != null) { if (current.CardinalityBehaviorElement.Value != null) { writer.WriteString("cardinalityBehavior",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.CardinalityBehaviorElement.Value)); } if (current.CardinalityBehaviorElement.HasExtensions() || (!string.IsNullOrEmpty(current.CardinalityBehaviorElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer,options,"_cardinalityBehavior",false,current.CardinalityBehaviorElement.Extension,current.CardinalityBehaviorElement.ElementId); } } if (current.Resource != null) { writer.WritePropertyName("resource"); current.Resource.SerializeJson(writer, options); } if ((current.Action != null) && (current.Action.Count != 0)) { writer.WritePropertyName("action"); writer.WriteStartArray(); foreach (RequestGroup.ActionComponent val in current.Action) { val.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#Action /// </summary> public static void DeserializeJson(this RequestGroup.ActionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"RequestGroup.ActionComponent >>> RequestGroup#Action.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"RequestGroup.ActionComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#Action /// </summary> public static void DeserializeJsonProperty(this RequestGroup.ActionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "prefix": if (reader.TokenType == JsonTokenType.Null) { current.PrefixElement = new FhirString(); reader.Skip(); } else { current.PrefixElement = new FhirString(reader.GetString()); } break; case "_prefix": if (current.PrefixElement == null) { current.PrefixElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.PrefixElement).DeserializeJson(ref reader, options); break; case "title": if (reader.TokenType == JsonTokenType.Null) { current.TitleElement = new FhirString(); reader.Skip(); } else { current.TitleElement = new FhirString(reader.GetString()); } break; case "_title": if (current.TitleElement == null) { current.TitleElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.TitleElement).DeserializeJson(ref reader, options); break; case "description": if (reader.TokenType == JsonTokenType.Null) { current.DescriptionElement = new FhirString(); reader.Skip(); } else { current.DescriptionElement = new FhirString(reader.GetString()); } break; case "_description": if (current.DescriptionElement == null) { current.DescriptionElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.DescriptionElement).DeserializeJson(ref reader, options); break; case "textEquivalent": if (reader.TokenType == JsonTokenType.Null) { current.TextEquivalentElement = new FhirString(); reader.Skip(); } else { current.TextEquivalentElement = new FhirString(reader.GetString()); } break; case "_textEquivalent": if (current.TextEquivalentElement == null) { current.TextEquivalentElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.TextEquivalentElement).DeserializeJson(ref reader, options); break; case "priority": if (reader.TokenType == JsonTokenType.Null) { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(); reader.Skip(); } else { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.RequestPriority>(reader.GetString())); } break; case "_priority": if (current.PriorityElement == null) { current.PriorityElement = new Code<Hl7.Fhir.Model.RequestPriority>(); } ((Hl7.Fhir.Model.Element)current.PriorityElement).DeserializeJson(ref reader, options); break; case "code": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'code' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Code = new List<CodeableConcept>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.CodeableConcept v_Code = new Hl7.Fhir.Model.CodeableConcept(); v_Code.DeserializeJson(ref reader, options); current.Code.Add(v_Code); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'code' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Code.Count == 0) { current.Code = null; } break; case "documentation": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'documentation' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Documentation = new List<RelatedArtifact>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.RelatedArtifact v_Documentation = new Hl7.Fhir.Model.RelatedArtifact(); v_Documentation.DeserializeJson(ref reader, options); current.Documentation.Add(v_Documentation); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'documentation' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Documentation.Count == 0) { current.Documentation = null; } break; case "condition": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'condition' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Condition = new List<RequestGroup.ConditionComponent>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.RequestGroup.ConditionComponent v_Condition = new Hl7.Fhir.Model.RequestGroup.ConditionComponent(); v_Condition.DeserializeJson(ref reader, options); current.Condition.Add(v_Condition); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'condition' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Condition.Count == 0) { current.Condition = null; } break; case "relatedAction": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'relatedAction' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.RelatedAction = new List<RequestGroup.RelatedActionComponent>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.RequestGroup.RelatedActionComponent v_RelatedAction = new Hl7.Fhir.Model.RequestGroup.RelatedActionComponent(); v_RelatedAction.DeserializeJson(ref reader, options); current.RelatedAction.Add(v_RelatedAction); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'relatedAction' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.RelatedAction.Count == 0) { current.RelatedAction = null; } break; case "timingDateTime": if (reader.TokenType == JsonTokenType.Null) { current.Timing = new FhirDateTime(); reader.Skip(); } else { current.Timing = new FhirDateTime(reader.GetString()); } break; case "_timingDateTime": if (current.Timing == null) { current.Timing = new FhirDateTime(); } ((Hl7.Fhir.Model.Element)current.Timing).DeserializeJson(ref reader, options); break; case "timingAge": current.Timing = new Hl7.Fhir.Model.Age(); ((Hl7.Fhir.Model.Age)current.Timing).DeserializeJson(ref reader, options); break; case "timingPeriod": current.Timing = new Hl7.Fhir.Model.Period(); ((Hl7.Fhir.Model.Period)current.Timing).DeserializeJson(ref reader, options); break; case "timingDuration": current.Timing = new Hl7.Fhir.Model.Duration(); ((Hl7.Fhir.Model.Duration)current.Timing).DeserializeJson(ref reader, options); break; case "timingRange": current.Timing = new Hl7.Fhir.Model.Range(); ((Hl7.Fhir.Model.Range)current.Timing).DeserializeJson(ref reader, options); break; case "timingTiming": current.Timing = new Hl7.Fhir.Model.Timing(); ((Hl7.Fhir.Model.Timing)current.Timing).DeserializeJson(ref reader, options); break; case "participant": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'participant' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Participant = new List<ResourceReference>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.ResourceReference v_Participant = new Hl7.Fhir.Model.ResourceReference(); v_Participant.DeserializeJson(ref reader, options); current.Participant.Add(v_Participant); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'participant' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Participant.Count == 0) { current.Participant = null; } break; case "type": current.Type = new Hl7.Fhir.Model.CodeableConcept(); ((Hl7.Fhir.Model.CodeableConcept)current.Type).DeserializeJson(ref reader, options); break; case "groupingBehavior": if (reader.TokenType == JsonTokenType.Null) { current.GroupingBehaviorElement = new Code<Hl7.Fhir.Model.ActionGroupingBehavior>(); reader.Skip(); } else { current.GroupingBehaviorElement = new Code<Hl7.Fhir.Model.ActionGroupingBehavior>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionGroupingBehavior>(reader.GetString())); } break; case "_groupingBehavior": if (current.GroupingBehaviorElement == null) { current.GroupingBehaviorElement = new Code<Hl7.Fhir.Model.ActionGroupingBehavior>(); } ((Hl7.Fhir.Model.Element)current.GroupingBehaviorElement).DeserializeJson(ref reader, options); break; case "selectionBehavior": if (reader.TokenType == JsonTokenType.Null) { current.SelectionBehaviorElement = new Code<Hl7.Fhir.Model.ActionSelectionBehavior>(); reader.Skip(); } else { current.SelectionBehaviorElement = new Code<Hl7.Fhir.Model.ActionSelectionBehavior>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionSelectionBehavior>(reader.GetString())); } break; case "_selectionBehavior": if (current.SelectionBehaviorElement == null) { current.SelectionBehaviorElement = new Code<Hl7.Fhir.Model.ActionSelectionBehavior>(); } ((Hl7.Fhir.Model.Element)current.SelectionBehaviorElement).DeserializeJson(ref reader, options); break; case "requiredBehavior": if (reader.TokenType == JsonTokenType.Null) { current.RequiredBehaviorElement = new Code<Hl7.Fhir.Model.ActionRequiredBehavior>(); reader.Skip(); } else { current.RequiredBehaviorElement = new Code<Hl7.Fhir.Model.ActionRequiredBehavior>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionRequiredBehavior>(reader.GetString())); } break; case "_requiredBehavior": if (current.RequiredBehaviorElement == null) { current.RequiredBehaviorElement = new Code<Hl7.Fhir.Model.ActionRequiredBehavior>(); } ((Hl7.Fhir.Model.Element)current.RequiredBehaviorElement).DeserializeJson(ref reader, options); break; case "precheckBehavior": if (reader.TokenType == JsonTokenType.Null) { current.PrecheckBehaviorElement = new Code<Hl7.Fhir.Model.ActionPrecheckBehavior>(); reader.Skip(); } else { current.PrecheckBehaviorElement = new Code<Hl7.Fhir.Model.ActionPrecheckBehavior>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionPrecheckBehavior>(reader.GetString())); } break; case "_precheckBehavior": if (current.PrecheckBehaviorElement == null) { current.PrecheckBehaviorElement = new Code<Hl7.Fhir.Model.ActionPrecheckBehavior>(); } ((Hl7.Fhir.Model.Element)current.PrecheckBehaviorElement).DeserializeJson(ref reader, options); break; case "cardinalityBehavior": if (reader.TokenType == JsonTokenType.Null) { current.CardinalityBehaviorElement = new Code<Hl7.Fhir.Model.ActionCardinalityBehavior>(); reader.Skip(); } else { current.CardinalityBehaviorElement = new Code<Hl7.Fhir.Model.ActionCardinalityBehavior>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionCardinalityBehavior>(reader.GetString())); } break; case "_cardinalityBehavior": if (current.CardinalityBehaviorElement == null) { current.CardinalityBehaviorElement = new Code<Hl7.Fhir.Model.ActionCardinalityBehavior>(); } ((Hl7.Fhir.Model.Element)current.CardinalityBehaviorElement).DeserializeJson(ref reader, options); break; case "resource": current.Resource = new Hl7.Fhir.Model.ResourceReference(); ((Hl7.Fhir.Model.ResourceReference)current.Resource).DeserializeJson(ref reader, options); break; case "action": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException($"ActionComponent error reading 'action' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } current.Action = new List<RequestGroup.ActionComponent>(); while (reader.TokenType != JsonTokenType.EndArray) { Hl7.Fhir.Model.RequestGroup.ActionComponent v_Action = new Hl7.Fhir.Model.RequestGroup.ActionComponent(); v_Action.DeserializeJson(ref reader, options); current.Action.Add(v_Action); if (!reader.Read()) { throw new JsonException($"ActionComponent error reading 'action' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); } } if (current.Action.Count == 0) { current.Action = null; } break; // Complex: action, Export: ActionComponent, Base: BackboneElement default: ((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Serialize a FHIR RequestGroup#Condition into JSON /// </summary> public static void SerializeJson(this RequestGroup.ConditionComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } // Component: RequestGroup#Condition, Export: ConditionComponent, Base: BackboneElement (BackboneElement) ((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false); writer.WriteString("kind",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.KindElement.Value)); if (current.Expression != null) { writer.WritePropertyName("expression"); current.Expression.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#Condition /// </summary> public static void DeserializeJson(this RequestGroup.ConditionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"RequestGroup.ConditionComponent >>> RequestGroup#Condition.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"RequestGroup.ConditionComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#Condition /// </summary> public static void DeserializeJsonProperty(this RequestGroup.ConditionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "kind": if (reader.TokenType == JsonTokenType.Null) { current.KindElement = new Code<Hl7.Fhir.Model.ActionConditionKind>(); reader.Skip(); } else { current.KindElement = new Code<Hl7.Fhir.Model.ActionConditionKind>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionConditionKind>(reader.GetString())); } break; case "_kind": if (current.KindElement == null) { current.KindElement = new Code<Hl7.Fhir.Model.ActionConditionKind>(); } ((Hl7.Fhir.Model.Element)current.KindElement).DeserializeJson(ref reader, options); break; case "expression": current.Expression = new Hl7.Fhir.Model.Expression(); ((Hl7.Fhir.Model.Expression)current.Expression).DeserializeJson(ref reader, options); break; // Complex: condition, Export: ConditionComponent, Base: BackboneElement default: ((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Serialize a FHIR RequestGroup#RelatedAction into JSON /// </summary> public static void SerializeJson(this RequestGroup.RelatedActionComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } // Component: RequestGroup#RelatedAction, Export: RelatedActionComponent, Base: BackboneElement (BackboneElement) ((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false); writer.WriteString("actionId",current.ActionIdElement.Value); writer.WriteString("relationship",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.RelationshipElement.Value)); if (current.Offset != null) { switch (current.Offset) { case Duration v_Duration: writer.WritePropertyName("offsetDuration"); v_Duration.SerializeJson(writer, options); break; case Range v_Range: writer.WritePropertyName("offsetRange"); v_Range.SerializeJson(writer, options); break; } } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#RelatedAction /// </summary> public static void DeserializeJson(this RequestGroup.RelatedActionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"RequestGroup.RelatedActionComponent >>> RequestGroup#RelatedAction.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"RequestGroup.RelatedActionComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } /// <summary> /// Deserialize JSON into a FHIR RequestGroup#RelatedAction /// </summary> public static void DeserializeJsonProperty(this RequestGroup.RelatedActionComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "actionId": if (reader.TokenType == JsonTokenType.Null) { current.ActionIdElement = new Id(); reader.Skip(); } else { current.ActionIdElement = new Id(reader.GetString()); } break; case "_actionId": if (current.ActionIdElement == null) { current.ActionIdElement = new Id(); } ((Hl7.Fhir.Model.Element)current.ActionIdElement).DeserializeJson(ref reader, options); break; case "relationship": if (reader.TokenType == JsonTokenType.Null) { current.RelationshipElement = new Code<Hl7.Fhir.Model.ActionRelationshipType>(); reader.Skip(); } else { current.RelationshipElement = new Code<Hl7.Fhir.Model.ActionRelationshipType>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ActionRelationshipType>(reader.GetString())); } break; case "_relationship": if (current.RelationshipElement == null) { current.RelationshipElement = new Code<Hl7.Fhir.Model.ActionRelationshipType>(); } ((Hl7.Fhir.Model.Element)current.RelationshipElement).DeserializeJson(ref reader, options); break; case "offsetDuration": current.Offset = new Hl7.Fhir.Model.Duration(); ((Hl7.Fhir.Model.Duration)current.Offset).DeserializeJson(ref reader, options); break; case "offsetRange": current.Offset = new Hl7.Fhir.Model.Range(); ((Hl7.Fhir.Model.Range)current.Offset).DeserializeJson(ref reader, options); break; // Complex: relatedAction, Export: RelatedActionComponent, Base: BackboneElement default: ((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Resource converter to support Sytem.Text.Json interop. /// </summary> public class RequestGroupJsonConverter : JsonConverter<RequestGroup> { /// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, RequestGroup value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); } /// <summary> /// Reads and converts the JSON to a typed object. /// </summary> public override RequestGroup Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { RequestGroup target = new RequestGroup(); target.DeserializeJson(ref reader, options); return target; } } } } // end of file
38.76367
233
0.621848
[ "MIT" ]
FirelyTeam/fhir-codegen
generated/SystemTextJsonExt_R4/Model/RequestGroup.cs
63,805
C#
#nullable disable using VocaDb.Model.DataContracts.PVs; namespace VocaDb.Web.Models.Shared.Partials.PV { public class EmbedBiliViewModel { public EmbedBiliViewModel(PVContract pv, int width, int height) { PV = pv; Width = width; Height = height; } public PVContract PV { get; set; } public int Width { get; set; } public int Height { get; set; } } }
18.136364
66
0.651629
[ "MIT" ]
AgFlore/vocadb
VocaDbWeb/Models/Shared/Partials/PV/EmbedBiliViewModel.cs
399
C#
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using System; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "World Transform Params", "Object Transform", "World Transform Params contains information about the transform, W is usually 1.0, or -1.0 for odd-negative scale transforms" )] public sealed class WorldTransformParams : ConstVecShaderVariable { protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); ChangeOutputName( 1, "X" ); ChangeOutputName( 2, "Y" ); ChangeOutputName( 3, "Z" ); ChangeOutputName( 4, "W" ); m_value = "unity_WorldTransformParams"; m_previewShaderGUID = "5a2642605f085da458d6e03ade47b87a"; } public override void RefreshExternalReferences() { base.RefreshExternalReferences(); if( !m_outputPorts[ 0 ].IsConnected ) { m_outputPorts[ 0 ].Visible = false; m_sizeIsDirty = true; } } } }
29.666667
193
0.721144
[ "MIT" ]
142333lzg/jynew
jyx2/Assets/3rd/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/ShaderVariables/Various/WorldTransformParams.cs
979
C#
using MongoDataAccess.App.Database; using MongoDB.Bson; namespace MongoDataAccess.UnitTest.Tests; [Collection("Sequential")] public class CheerUpTest : IClassFixture<ServiceFixture>, IDisposable { private readonly IHost testHost; private readonly IDBContext dbContext; public CheerUpTest(ServiceFixture fixture) { testHost = fixture.TestHost; dbContext = testHost.Services.GetRequiredService<IDBContext>(); } [Fact] public void HaveFun() { Assert.Equal("🤣", "🤣"); } public void Dispose() { dbContext.Drop(); GC.SuppressFinalize(this); } }
23.333333
71
0.673016
[ "MIT" ]
xmj-alliance/pit
dotnet/mongo-data-access/MongoDataAccess.UnitTest/Tests/CheerUp.cs
638
C#
namespace Adnc.Infra.Entities.Config { public struct EntityProperty { public readonly int MaxLength; public readonly bool IsRequired; private EntityProperty(bool isRequired, int maxLength) { IsRequired = isRequired; MaxLength = maxLength; } public static implicit operator EntityProperty((bool IsRequired, int MaxLength) info) { return new EntityProperty(info.IsRequired, info.MaxLength); } } }
25.5
93
0.62549
[ "MIT" ]
AjuPrince/Adnc
src/ServerApi/Infrastructures/Adnc.Infra.Repository/Entities/EfEnities/Config/EntityProperty.cs
512
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2019 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 using System; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Senparc.NeuChar.Context; using Senparc.NeuChar.Entities; using Senparc.Weixin.MP.Entities; using Senparc.Weixin.MP.Entities.Request; using Senparc.Weixin.MP.MessageHandlers; namespace Senparc.Weixin.MP.Test.MessageHandlers { public class CancelMessageHandlers : MessageHandler<MessageContext<IRequestMessageBase, IResponseMessageBase>> { public string RunStep { get; set; } public CancelMessageHandlers(XDocument requestDoc, PostModel postModel) : base(requestDoc, postModel) { } public override void OnExecuting() { RunStep = "OnExecuting"; CancelExcute = true;//取消执行 base.OnExecuting(); } public override void OnExecuted() { RunStep = "OnExecuted"; base.OnExecuted(); } public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { RunStep = "Execute"; var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "文字信息"; return responseMessage; } /// <summary> /// 默认消息 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage) { var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "您发送的消息类型暂未被识别。"; return responseMessage; } } [TestClass] public class MessageHandlers_CancelTest { string xmlText = @"<?xml version=""1.0"" encoding=""utf-8""?> <xml> <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> <CreateTime>1357986928</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[TNT2]]></Content> <MsgId>5832509444155992350</MsgId> </xml> "; [TestMethod] public void CancelTest() { var postModel = new PostModel() { AppId = "appId" }; { //一开始就取消 var messageHandler = new CancelMessageHandlers(XDocument.Parse(xmlText), postModel); messageHandler.CancelExcute = true; messageHandler.Execute(); Assert.AreEqual(null, messageHandler.RunStep); } { //OnExecuting中途取消 var messageHandler = new CancelMessageHandlers(XDocument.Parse(xmlText), postModel); messageHandler.Execute(); Assert.AreEqual("OnExecuting", messageHandler.RunStep); } } } }
33.535714
114
0.627263
[ "Apache-2.0" ]
370041597/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP.Test/MessageHandlers/MessageHandlers_CancelTest.cs
3,830
C#
using System; using System.Collections.Generic; using Clustri.Crawl.Console.Interfaces; using Clustri.Crawl.Crawler.Interfaces; using Clustri.Repository.Core.Interfaces; using Clustri.Repository.Entities; namespace Clustri.Crawl.Console.Mfc { public class MfcCrawler { private readonly IUserRepository _userRepository; private readonly IPrinter _printer; private readonly ICommunityDecider _communityDecider; private readonly IWebCrawler crawler; public MfcCrawler(IocContainer ioc, IUserRepository userRepository, IPrinter printer, ICommunityDecider communityDecider, int waitTime = 200) { _userRepository = userRepository; _printer = printer; _communityDecider = communityDecider; crawler = ioc.SteamCrawler(1000, waitTime); } public void Crawl(int maxDepth, Uri link) { var depth = 0; var lastWeight = 0.5; foreach (var vertex in crawler.Crawl(link)) { var community = false; _printer.Print(vertex); var shouldCreate = _communityDecider.ShouldCreateCommunity(lastWeight, vertex.Weight); lastWeight = vertex.Weight; if (shouldCreate) community = true; var newUser = new User { UserId = vertex.Id, Weight = vertex.Weight, Community = community}; _userRepository.Add(newUser); depth++; if (depth >= maxDepth) break; AddChildren(newUser, vertex.Degrees); } } private void AddChildren(User parent, IEnumerable<IProfile> children) { foreach (var profile in children) { _printer.Print(profile, true); var friend = new User { UserId = profile.Id, Community = parent.Community}; _userRepository.Add(friend); _userRepository.RelateFriendsByUser(parent, friend); } } } }
29.816901
108
0.590931
[ "MIT" ]
ObliviousJamie/Clustri
Clustri.Crawl.Console/Mfc/MfcCrawler.cs
2,119
C#
using System; using FluentAssertions; using NUnit.Framework; using SandBeige.MediaBox.Composition.Enum; using SandBeige.MediaBox.Models.Album.Filter.FilterItemObjects; namespace SandBeige.MediaBox.Tests.Models.Album.Filter.FilterItemObjects { internal class RateFilterItemObjectTest : ModelTestClassBase { [TestCase(1, SearchTypeComparison.GreaterThan, "評価が1を超える")] [TestCase(2, SearchTypeComparison.GreaterThanOrEqual, "評価が2以上")] [TestCase(3, SearchTypeComparison.Equal, "評価が3と等しい")] [TestCase(4, SearchTypeComparison.LessThanOrEqual, "評価が4以下")] [TestCase(5, SearchTypeComparison.LessThan, "評価が5未満")] public void プロパティ(int rate, SearchTypeComparison searchType, string displayName) { var io = new RateFilterItemObject(rate, searchType); io.Rate.Should().Be(rate); io.SearchType.Should().Be(searchType); io.DisplayName.Should().Be(displayName); #pragma warning disable 618 var io2 = new RateFilterItemObject(); #pragma warning restore 618 io2.Rate.Should().Be(0); io2.SearchType.Should().Be(SearchTypeComparison.GreaterThan); io2.Rate = rate; io2.SearchType = searchType; io2.Rate.Should().Be(rate); io2.SearchType.Should().Be(searchType); io2.DisplayName.Should().Be(displayName); } [TestCase(5, (SearchTypeComparison)100)] public void フィルター作成例外(int rate, SearchTypeComparison searchType) { Action act = () => { _ = new RateFilterItemObject(rate, searchType); }; act.Should().ThrowExactly<ArgumentException>(); } } }
33.244444
84
0.751337
[ "MIT" ]
southernwind/MediaBox
Tests/MediaBox.Tests/Models/Album/Filter/FilterItemObjects/RateFilterItemObjectTest.cs
1,582
C#
using OpenHardwareMonitor.Eszkozok; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace OpenHardwareMonitor.GUI { public partial class BiztSzenzorok : Form { FoAblak MF; public BiztSzenzorok(FoAblak MFbe) { InitializeComponent(); Program.OsszesForm.Add(this); this.TopMost = Program.KONFFelulMarado; MF = MFbe; if (Program.KONFNyelv != "hun") { this.Text = Eszk.GetNyelvSzo("BiztSzenzCIM"); Lokalizalj(); } BiztLeker(); HomLeker(); } void Lokalizalj() { label1.Text = Eszk.GetNyelvSzo("Szenzor") + " 1:"; label2.Text = Eszk.GetNyelvSzo("Szenzor") + " 2:"; labelHat1.Text = Eszk.GetNyelvSzo("BIZHLabHatár"); labelHat2.Text = Eszk.GetNyelvSzo("BIZHLabHatár"); button2.Text = Eszk.GetNyelvSzo("Frissítés"); } const double SZENZARANY = 2.55; void HomLeker() { try { for (int i = 0; i < 10 && Program.SorosKuldes == true; ++i) { System.Threading.Thread.Sleep(50); } Program.SorosKuldes = true; for (int k = 0; k < 3; k++) { Program.SorosPort.ReadExisting(); Fajlkezelo.UARTbajtKuldo((byte)(115 + Program.UARTKod100)); string bejovo = ""; for (int i = 0; i < 10; i++) { Thread.Sleep(50); bejovo += Program.SorosPort.ReadExisting(); if (bejovo.Length >= 8) break; } if (bejovo.Length >= 8) { if (CRCTesztHomLeker(bejovo)) { #region Logaritmikus //double Roszt1 = (5 / ((double)((byte)bejovo[1] | (byte)bejovo[2] << 6) * ((double)5 / 1024))) - (double)1; //double Roszt2 = (5 / ((double)((byte)bejovo[3] | (byte)bejovo[4] << 6) * ((double)5 / 1024))) - (double)1; //if (Roszt1 < 0.13726) //{ // double a = 1.09742 * Math.Pow(10, 8), b = -5.66757 * Math.Pow(10, 7), c = 1.20244 * Math.Pow(10, 7), d = -1.36339 * Math.Pow(10, 6), e = 90847.61862, f = -3870.48053, g = 174.69727; // try { labelS1Ert.Text = Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g).ToString() + "°C"; } catch { } //} //else if (Roszt1 < 0.61822) //{ // double a = 12979.45085, b = -29382.10459, c = 27256.64504, d = -13492.89839, e = 3927.45688, f = -734.46067, g = 123.3825; // try { labelS1Ert.Text = Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g).ToString() + "°C"; } catch { } //} //else //{ // double a = 0, b = 0, c = 0, d = -11.33434, e = 45.64721, f = -77.38692, g = 68.07405; // //decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g); // try { labelS1Ert.Text = Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g).ToString() + "°C"; } catch { } //} //if (Roszt2 < 0.13726) //{ // double a = 1.09742 * Math.Pow(10, 8), b = -5.66757 * Math.Pow(10, 7), c = 1.20244 * Math.Pow(10, 7), d = -1.36339 * Math.Pow(10, 6), e = 90847.61862, f = -3870.48053, g = 174.69727; // try { labelS2Ert.Text = Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g).ToString() + "°C"; } catch { } //} //else if (Roszt2 < 0.61822) //{ // double a = 12979.45085, b = -29382.10459, c = 27256.64504, d = -13492.89839, e = 3927.45688, f = -734.46067, g = 123.3825; // try { labelS2Ert.Text = Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g).ToString() + "°C"; } catch { } //} //else //{ // double a = 0, b = 0, c = 0, d = -11.33434, e = 45.64721, f = -77.38692, g = 68.07405; // //decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g); // try { labelS2Ert.Text = Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g).ToString() + "°C"; } catch { } //} #endregion double ADC1 = (double)((byte)bejovo[1] | (byte)bejovo[2] << 6); double ADC2 = (double)((byte)bejovo[3] | (byte)bejovo[4] << 6); if (Math.Round((ADC1 * ((double)5 / 1024) * 100) - 273) > 180) labelS1Ert.Text = "N/A" + "°C"; else labelS1Ert.Text = Math.Round((ADC1 * ((double)5 / 1024) * 100) - 273).ToString() + "°C"; if (Math.Round((ADC2 * ((double)5 / 1024) * 100) - 273) > 180) labelS2Ert.Text = "N/A" + "°C"; else labelS2Ert.Text = Math.Round((ADC2 * ((double)5 / 1024) * 100) - 273).ToString() + "°C"; break; // felső for-ból } } } } catch { } Program.SorosKuldes = false; } bool CRCTesztHomLeker(string bejovo) { byte CRC1 = 0, CRC2 = 0, CRC3 = 0; for (int i = 1; i < 5; i++) { if ((bejovo[i] & Convert.ToByte("00000001", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00000010", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("00000100", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00001000", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("00010000", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00100000", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("01000000", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("10000000", 2)) != 0) { ++CRC1; ++CRC2; } } if (CRC1 == bejovo[5] && CRC2 == bejovo[6] && CRC3 == bejovo[7]) return true; return false; } void BiztLeker() { try { for (int i = 0; i < 10 && Program.SorosKuldes == true; ++i) { System.Threading.Thread.Sleep(50); } Program.SorosKuldes = true; for (int k = 0; k < 3; k++) { Program.SorosPort.ReadExisting(); Fajlkezelo.UARTbajtKuldo((byte)(118 + Program.UARTKod100)); string bejovo = ""; for (int i = 0; i < 10; i++) { Thread.Sleep(50); bejovo += Program.SorosPort.ReadExisting(); if (bejovo.Length >= 8) break; } if (bejovo.Length >= 8) { if (CRCTesztBiztLeker(bejovo)) { #region Logaritmikus //double Roszt1 = (5 / ((double)((byte)bejovo[1] | (byte)bejovo[2] << 6) * ((double)5 / 1024))) - (double)1; //double Roszt2 = (5 / ((double)((byte)bejovo[3] | (byte)bejovo[4] << 6) * ((double)5 / 1024))) - (double)1; //if (Roszt1 < 0.13726) //{ // double a = 1.09742 * Math.Pow(10, 8), b = -5.66757 * Math.Pow(10, 7), c = 1.20244 * Math.Pow(10, 7), d = -1.36339 * Math.Pow(10, 6), e = 90847.61862, f = -3870.48053, g = 174.69727; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g); // try { numericUpDown1.Value = (dec> numericUpDown1.Maximum)?numericUpDown1.Maximum : dec; } catch { } //} //else if (Roszt1 < 0.61822) //{ // double a = 12979.45085, b = -29382.10459, c = 27256.64504, d = -13492.89839, e = 3927.45688, f = -734.46067, g = 123.3825; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g); // try { numericUpDown1.Value = (dec > numericUpDown1.Maximum) ? numericUpDown1.Maximum : dec; } catch { } //} //else //{ // double a = 0, b = 0, c = 0, d = -11.33434, e = 45.64721, f = -77.38692, g = 68.07405; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt1, 6) + b * Math.Pow(Roszt1, 5) + c * Math.Pow(Roszt1, 4) + d * Math.Pow(Roszt1, 3) + e * Math.Pow(Roszt1, 2) + f * Roszt1 + g); // try { numericUpDown1.Value = (dec > numericUpDown1.Maximum) ? numericUpDown1.Maximum : dec; } catch { } //} //if (Roszt2 < 0.13726) //{ // double a = 1.09742 * Math.Pow(10, 8), b = -5.66757 * Math.Pow(10, 7), c = 1.20244 * Math.Pow(10, 7), d = -1.36339 * Math.Pow(10, 6), e = 90847.61862, f = -3870.48053, g = 174.69727; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g); // try { numericUpDown2.Value = (dec > numericUpDown2.Maximum) ? numericUpDown2.Maximum : dec; } catch { } //} //else if (Roszt2 < 0.61822) //{ // double a = 12979.45085, b = -29382.10459, c = 27256.64504, d = -13492.89839, e = 3927.45688, f = -734.46067, g = 123.3825; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g); // try { numericUpDown2.Value = (dec > numericUpDown2.Maximum) ? numericUpDown2.Maximum : dec; } catch { } //} //else //{ // double a = 0, b = 0, c = 0, d = -11.33434, e = 45.64721, f = -77.38692, g = 68.07405; // decimal dec = (decimal)Math.Round(a * Math.Pow(Roszt2, 6) + b * Math.Pow(Roszt2, 5) + c * Math.Pow(Roszt2, 4) + d * Math.Pow(Roszt2, 3) + e * Math.Pow(Roszt2, 2) + f * Roszt2 + g); // try { numericUpDown2.Value = (dec > numericUpDown2.Maximum) ? numericUpDown2.Maximum : dec; } catch { } //} #endregion double ADC1 = (double)((byte)bejovo[1] | (byte)bejovo[2] << 5); double ADC2 = (double)((byte)bejovo[3] | (byte)bejovo[4] << 5); decimal Ho1 = (decimal)Math.Round((ADC1 * ((double)5 / 1024) * 100) - 273); decimal Ho2 = (decimal)Math.Round((ADC2 * ((double)5 / 1024) * 100) - 273); numericUpDown1.Value = (Ho1 < numericUpDown1.Minimum || Ho1 > numericUpDown1.Maximum) ? 60 : Ho1; numericUpDown2.Value = (Ho2 < numericUpDown2.Minimum || Ho2 > numericUpDown2.Maximum) ? 60 : Ho2; break; // felső for-ból } } } } catch { } Program.SorosKuldes = false; } bool CRCTesztBiztLeker(string bejovo) { byte CRC1 = 0, CRC2 = 0, CRC3 = 0; for (int i = 1; i < 5; i++) { if ((bejovo[i] & Convert.ToByte("00000001", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00000010", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("00000100", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00001000", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("00010000", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("00100000", 2)) != 0) { ++CRC1; ++CRC2; } if ((bejovo[i] & Convert.ToByte("01000000", 2)) != 0) { ++CRC1; ++CRC3; } if ((bejovo[i] & Convert.ToByte("10000000", 2)) != 0) { ++CRC1; ++CRC2; } } if (CRC1 == bejovo[5] && CRC2 == bejovo[6] && CRC3 == bejovo[7]) return true; return false; } private void button1_Click(object sender, EventArgs ea) { for (int i = 0; i < 10 && Program.SorosKuldes == true; ++i) { System.Threading.Thread.Sleep(50); } Program.SorosKuldes = true; #region Logaritmikus //double x1 = (double)numericUpDown1.Value, x2 = (double)numericUpDown2.Value; //double a = 6.71704, b = -3.3054, c = 6.76037, d = -7.49996, e = 0.00492, f = -0.19097, g = 3.63119; //double s1 = a * Math.Pow(10, -12) * Math.Pow(x1, 6) + b * Math.Pow(10, -9) * Math.Pow(x1, 5) + c * Math.Pow(10, -7) * Math.Pow(x1, 4) + d * Math.Pow(10, -5) * Math.Pow(x1, 3) + e * Math.Pow(x1, 2) + f * x1 + g; //double s2 = a * Math.Pow(10, -12) * Math.Pow(x2, 6) + b * Math.Pow(10, -9) * Math.Pow(x2, 5) + c * Math.Pow(10, -7) * Math.Pow(x2, 4) + d * Math.Pow(10, -5) * Math.Pow(x2, 3) + e * Math.Pow(x2, 2) + f * x2 + g; //s1 = (double)5 / (s1 + 1); //s2 = (double)5 / (s2 + 1); //s1 = s1 / ((double)5 / 1024); //s2 = s2 / ((double)5 / 1024); //if (s1 > 1020) // s1 = 1020; //if (s2 > 1020) // s2 = 1020; #endregion double s1 = Math.Round(((double)numericUpDown1.Value + 273) / ((((double)5 / 1024) * 100))); double s2 = Math.Round(((double)numericUpDown2.Value + 273) / ((((double)5 / 1024) * 100))); //MessageBox.Show("S1: " + s1 + "\ns2: " + s2); byte[] kuldendo = new byte[] { (byte)((ushort)Math.Round(s1) & Convert.ToUInt16("0000000000111111", 2)), (byte)(((ushort)Math.Round(s1) & Convert.ToUInt16("0000111111000000", 2)) >> 6), (byte)((ushort)Math.Round(s2) & Convert.ToUInt16("0000000000111111", 2)), (byte)(((ushort)Math.Round(s2) & Convert.ToUInt16("0000111111000000", 2)) >> 6) }; Enabled = false; bool siker = false; try { for (int i = 0; i < 2; i++) { if (Fajlkezelo.UARTbajtKuldo(120, kuldendo)) { siker = true; break; } } if (!siker) { MF.KezfogasSzalIndito(false); for (int i = 0; i < 2; i++) { if (Fajlkezelo.UARTbajtKuldo(120, kuldendo)) { siker = true; break; } } } } catch { } if (!siker) MessageBox.Show((Program.KONFNyelv == "hun") ? "A feltöltés sikertelen!\nPróbálja meg újra!" : Eszk.GetNyelvSzo("IndFordszHibaSZOVEG"), (Program.KONFNyelv == "hun") ? "Sikertelen Feltöltés" : Eszk.GetNyelvSzo("IndFordszHibaCIM"), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); else { MF.menuItem57.Checked = true; Program.KONFVanVezerlo = true; Eszkozok.Eszk.Elnevezo(); Program.SorosKuldes = false; try { Close(); } catch { } } Program.SorosKuldes = false; Enabled = true; } private void button2_Click(object sender, EventArgs e) { HomLeker(); } } }
51.355978
358
0.417959
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
gatsjanos/Feverkill
OHM/OHM FELD/GUI/BiztSzenzorok.cs
18,926
C#
using Perculus.XSDK.Models; using System; using System.Collections.Generic; using System.Text; namespace Perculus.XSDK.ExampleApp { internal class Common { private static Perculus _perculusClient = null; public static Perculus CreatePerculusClient(bool createNewInstance = false) { Perculus client = null; if (!createNewInstance && _perculusClient != null) { return _perculusClient; } var config = Config.GetInstance(); client = new Perculus(new Uri(config.API_URL), new Uri(config.AUTH_URL), config.ACCOUNT_ID, config.USERNAME, config.PASSWORD, config.LOG_FILE_PATH); if (!createNewInstance) { _perculusClient = client; } return client; } public static void HandleErrorResponse(ApiErrorResponse response) { Console.Out.WriteLine($"API Error: {response.Code}\nHTTP Status Code: {response.HttpStatusCode}\nDetails:{response.Details}"); } } }
28.447368
160
0.616096
[ "MIT" ]
advancity/perculus-plus-sdk
Perculus.XSDK.ExampleApp/Common.cs
1,083
C#
namespace DotNetConsoleAppToolkit.Console { public enum Color3BitMap { darkgray = 0b0, gray = 0b1111, red = 0b1, green = 0b10, yellow = 0b11, blue = 0b100, magenta = 0b101, cyan = 0b110, white = 0b111, black = 0b1000, darkred = 0b1001, darkgreen = 0b1010, darkyellow = 0b1011, darkblue = 0b1100, darkmagenta = 0b1101, darkcyan = 0b1110, } }
22.125
42
0.46516
[ "MIT" ]
franck-gaspoz/dotnet-console-app-toolkit
Console/Color3BitMap.cs
533
C#
namespace dp2Catalog { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.menuStrip_main = new System.Windows.Forms.MenuStrip(); this.MenuItem_file = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openZSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openZBatchSearchForm1 = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openDtlpSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openDp2SearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openAmazonSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openOaiSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_linkMarcFile = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openMarcDetailForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_loadXmlDetailForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openDcForm = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openZhongcihaoForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_systemManagement = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_changePassword = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openDtlpLogForm = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_clearCfgCache = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openEaccForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openBerDebugForm1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openTestForm = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_saveOriginRecordToWorksheet = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_saveOriginRecordToIso2709 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_exit = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_function = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_saveToTemplate = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_viewAccessPoint = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openMarcDetailFormEx = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openDcFormEx = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_editMarcoTable = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openZBatchSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openAdvertiseForm = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_ui = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_font = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_window = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_tileHorizontal = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_tileVertical = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_cascade = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_arrangeIcons = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_help = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_cfg = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_openUserFolder = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openDataFolder = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_openProgramFolder = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator(); this.MenuItem_resetSerialCode = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItem_copyright = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip_main = new System.Windows.Forms.ToolStrip(); this.toolButton_saveTo = new System.Windows.Forms.ToolStripButton(); this.toolButton_save = new System.Windows.Forms.ToolStripButton(); this.toolButton_saveToDB = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_delete = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_prev = new System.Windows.Forms.ToolStripButton(); this.toolButton_next = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_nextBatch = new System.Windows.Forms.ToolStripButton(); this.toolButton_getAllRecords = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_loadFullRecord = new System.Windows.Forms.ToolStripButton(); this.toolButton_refresh = new System.Windows.Forms.ToolStripButton(); this.toolButton_loadTemplate = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_searchZ = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_searchA = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_copyToFixed = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator20 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_dup = new System.Windows.Forms.ToolStripButton(); this.toolButton_verify = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.toolButton_search = new System.Windows.Forms.ToolStripButton(); this.toolButton_stop = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_testSearch = new System.Windows.Forms.ToolStripButton(); this.statusStrip_main = new System.Windows.Forms.StatusStrip(); this.toolStripProgressBar_main = new System.Windows.Forms.ToolStripProgressBar(); this.toolStripStatusLabel_main = new System.Windows.Forms.ToolStripStatusLabel(); this.panel_fixed = new System.Windows.Forms.Panel(); this.tabControl_panelFixed = new System.Windows.Forms.TabControl(); this.tabPage_operHistory = new System.Windows.Forms.TabPage(); this.webBrowser_history = new System.Windows.Forms.WebBrowser(); this.tabPage_property = new System.Windows.Forms.TabPage(); this.tabPage_verifyResult = new System.Windows.Forms.TabPage(); this.tabPage_generateData = new System.Windows.Forms.TabPage(); this.toolStrip_panelFixed = new System.Windows.Forms.ToolStrip(); this.toolStripButton_close = new System.Windows.Forms.ToolStripButton(); this.splitter_fixed = new System.Windows.Forms.Splitter(); this.MenuItem_openSruSearchForm = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip_main.SuspendLayout(); this.toolStrip_main.SuspendLayout(); this.statusStrip_main.SuspendLayout(); this.panel_fixed.SuspendLayout(); this.tabControl_panelFixed.SuspendLayout(); this.tabPage_operHistory.SuspendLayout(); this.toolStrip_panelFixed.SuspendLayout(); this.SuspendLayout(); // // menuStrip_main // this.menuStrip_main.ImageScalingSize = new System.Drawing.Size(24, 24); this.menuStrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_file, this.MenuItem_function, this.MenuItem_ui, this.MenuItem_window, this.MenuItem_help}); this.menuStrip_main.Location = new System.Drawing.Point(0, 0); this.menuStrip_main.MdiWindowListItem = this.MenuItem_window; this.menuStrip_main.Name = "menuStrip_main"; this.menuStrip_main.Padding = new System.Windows.Forms.Padding(6, 3, 0, 3); this.menuStrip_main.Size = new System.Drawing.Size(867, 34); this.menuStrip_main.TabIndex = 0; this.menuStrip_main.Text = "menuStrip1"; // // MenuItem_file // this.MenuItem_file.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_openZSearchForm, this.MenuItem_openZBatchSearchForm1, this.MenuItem_openDtlpSearchForm, this.MenuItem_openDp2SearchForm, this.MenuItem_openAmazonSearchForm, this.MenuItem_openSruSearchForm, this.MenuItem_openOaiSearchForm, this.toolStripSeparator12, this.MenuItem_linkMarcFile, this.toolStripSeparator8, this.MenuItem_openMarcDetailForm, this.MenuItem_loadXmlDetailForm, this.MenuItem_openDcForm, this.toolStripSeparator7, this.MenuItem_openZhongcihaoForm, this.MenuItem_systemManagement, this.toolStripSeparator3, this.MenuItem_saveOriginRecordToWorksheet, this.MenuItem_saveOriginRecordToIso2709, this.toolStripSeparator4, this.MenuItem_exit}); this.MenuItem_file.Name = "MenuItem_file"; this.MenuItem_file.Size = new System.Drawing.Size(80, 28); this.MenuItem_file.Text = "文件(&F)"; // // MenuItem_openZSearchForm // this.MenuItem_openZSearchForm.Name = "MenuItem_openZSearchForm"; this.MenuItem_openZSearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openZSearchForm.Text = "Z39.50检索窗(&Z)"; this.MenuItem_openZSearchForm.Click += new System.EventHandler(this.MenuItem_openZSearchForm_Click); // // MenuItem_openZBatchSearchForm1 // this.MenuItem_openZBatchSearchForm1.Name = "MenuItem_openZBatchSearchForm1"; this.MenuItem_openZBatchSearchForm1.Size = new System.Drawing.Size(314, 30); this.MenuItem_openZBatchSearchForm1.Text = "Z39.50批检索窗(&B)"; this.MenuItem_openZBatchSearchForm1.Click += new System.EventHandler(this.MenuItem_openZBatchSearchForm1_Click); // // MenuItem_openDtlpSearchForm // this.MenuItem_openDtlpSearchForm.Name = "MenuItem_openDtlpSearchForm"; this.MenuItem_openDtlpSearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openDtlpSearchForm.Text = "DTLP检索窗(&D)"; this.MenuItem_openDtlpSearchForm.Click += new System.EventHandler(this.MenuItem_openDtlpSearchForm_Click); // // MenuItem_openDp2SearchForm // this.MenuItem_openDp2SearchForm.Name = "MenuItem_openDp2SearchForm"; this.MenuItem_openDp2SearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openDp2SearchForm.Text = "dp2检索窗(&P)"; this.MenuItem_openDp2SearchForm.Click += new System.EventHandler(this.MenuItem_openDp2SearchForm_Click); // // MenuItem_openAmazonSearchForm // this.MenuItem_openAmazonSearchForm.Name = "MenuItem_openAmazonSearchForm"; this.MenuItem_openAmazonSearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openAmazonSearchForm.Text = "亚马逊检索窗(&A)"; this.MenuItem_openAmazonSearchForm.Click += new System.EventHandler(this.MenuItem_openAmazonSearchForm_Click); // // MenuItem_openOaiSearchForm // this.MenuItem_openOaiSearchForm.Name = "MenuItem_openOaiSearchForm"; this.MenuItem_openOaiSearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openOaiSearchForm.Text = "OAI检索窗(O)"; this.MenuItem_openOaiSearchForm.Visible = false; this.MenuItem_openOaiSearchForm.Click += new System.EventHandler(this.MenuItem_openOaiSearchForm_Click); // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; this.toolStripSeparator12.Size = new System.Drawing.Size(311, 6); // // MenuItem_linkMarcFile // this.MenuItem_linkMarcFile.Name = "MenuItem_linkMarcFile"; this.MenuItem_linkMarcFile.Size = new System.Drawing.Size(314, 30); this.MenuItem_linkMarcFile.Text = "连接MARC文件(&L)..."; this.MenuItem_linkMarcFile.Click += new System.EventHandler(this.MenuItem_linkMarcFile_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(311, 6); // // MenuItem_openMarcDetailForm // this.MenuItem_openMarcDetailForm.Name = "MenuItem_openMarcDetailForm"; this.MenuItem_openMarcDetailForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openMarcDetailForm.Text = "MARC记录窗(&M)..."; this.MenuItem_openMarcDetailForm.Click += new System.EventHandler(this.MenuItem_openMarcDetailForm_Click); // // MenuItem_loadXmlDetailForm // this.MenuItem_loadXmlDetailForm.Name = "MenuItem_loadXmlDetailForm"; this.MenuItem_loadXmlDetailForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_loadXmlDetailForm.Text = "XML记录窗(&L)..."; this.MenuItem_loadXmlDetailForm.Click += new System.EventHandler(this.MenuItem_loadXmlDetailForm_Click); // // MenuItem_openDcForm // this.MenuItem_openDcForm.Name = "MenuItem_openDcForm"; this.MenuItem_openDcForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openDcForm.Text = "DC记录窗(&D)..."; this.MenuItem_openDcForm.Click += new System.EventHandler(this.MenuItem_openDcForm_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(311, 6); // // MenuItem_openZhongcihaoForm // this.MenuItem_openZhongcihaoForm.Name = "MenuItem_openZhongcihaoForm"; this.MenuItem_openZhongcihaoForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openZhongcihaoForm.Text = "dp2种次号窗(&Z)..."; this.MenuItem_openZhongcihaoForm.Click += new System.EventHandler(this.MenuItem_openZhongcihaoForm_Click); // // MenuItem_systemManagement // this.MenuItem_systemManagement.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_changePassword, this.toolStripSeparator13, this.MenuItem_openDtlpLogForm, this.toolStripSeparator16, this.MenuItem_clearCfgCache, this.toolStripSeparator15, this.MenuItem_openEaccForm, this.MenuItem_openBerDebugForm1, this.toolStripSeparator14, this.MenuItem_openTestForm}); this.MenuItem_systemManagement.Name = "MenuItem_systemManagement"; this.MenuItem_systemManagement.Size = new System.Drawing.Size(314, 30); this.MenuItem_systemManagement.Text = "系统维护(&M)"; // // MenuItem_changePassword // this.MenuItem_changePassword.Name = "MenuItem_changePassword"; this.MenuItem_changePassword.Size = new System.Drawing.Size(296, 30); this.MenuItem_changePassword.Text = "修改密码(&P)..."; this.MenuItem_changePassword.Click += new System.EventHandler(this.MenuItem_changePassword_Click); // // toolStripSeparator13 // this.toolStripSeparator13.Name = "toolStripSeparator13"; this.toolStripSeparator13.Size = new System.Drawing.Size(293, 6); // // MenuItem_openDtlpLogForm // this.MenuItem_openDtlpLogForm.Name = "MenuItem_openDtlpLogForm"; this.MenuItem_openDtlpLogForm.Size = new System.Drawing.Size(296, 30); this.MenuItem_openDtlpLogForm.Text = "DTLP日志窗(&L)..."; this.MenuItem_openDtlpLogForm.Click += new System.EventHandler(this.MenuItem_openDtlpLogForm_Click); // // toolStripSeparator16 // this.toolStripSeparator16.Name = "toolStripSeparator16"; this.toolStripSeparator16.Size = new System.Drawing.Size(293, 6); // // MenuItem_clearCfgCache // this.MenuItem_clearCfgCache.Name = "MenuItem_clearCfgCache"; this.MenuItem_clearCfgCache.Size = new System.Drawing.Size(296, 30); this.MenuItem_clearCfgCache.Text = "清除配置文件本地缓存(&C)"; this.MenuItem_clearCfgCache.Click += new System.EventHandler(this.MenuItem_clearCfgCache_Click); // // toolStripSeparator15 // this.toolStripSeparator15.Name = "toolStripSeparator15"; this.toolStripSeparator15.Size = new System.Drawing.Size(293, 6); // // MenuItem_openEaccForm // this.MenuItem_openEaccForm.Name = "MenuItem_openEaccForm"; this.MenuItem_openEaccForm.Size = new System.Drawing.Size(296, 30); this.MenuItem_openEaccForm.Text = "EACC编码维护窗(&E)..."; this.MenuItem_openEaccForm.Click += new System.EventHandler(this.MenuItem_openEaccForm_Click); // // MenuItem_openBerDebugForm1 // this.MenuItem_openBerDebugForm1.Name = "MenuItem_openBerDebugForm1"; this.MenuItem_openBerDebugForm1.Size = new System.Drawing.Size(296, 30); this.MenuItem_openBerDebugForm1.Text = "BER包调试窗(&D)..."; this.MenuItem_openBerDebugForm1.Click += new System.EventHandler(this.MenuItem_openBerDebugForm_Click); // // toolStripSeparator14 // this.toolStripSeparator14.Name = "toolStripSeparator14"; this.toolStripSeparator14.Size = new System.Drawing.Size(293, 6); // // MenuItem_openTestForm // this.MenuItem_openTestForm.Name = "MenuItem_openTestForm"; this.MenuItem_openTestForm.Size = new System.Drawing.Size(296, 30); this.MenuItem_openTestForm.Text = "测试窗(&T)..."; this.MenuItem_openTestForm.Click += new System.EventHandler(this.MenuItem_openTestForm_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(311, 6); // // MenuItem_saveOriginRecordToWorksheet // this.MenuItem_saveOriginRecordToWorksheet.Name = "MenuItem_saveOriginRecordToWorksheet"; this.MenuItem_saveOriginRecordToWorksheet.Size = new System.Drawing.Size(314, 30); this.MenuItem_saveOriginRecordToWorksheet.Text = "保存记录到工作单文件(&W)..."; this.MenuItem_saveOriginRecordToWorksheet.Click += new System.EventHandler(this.MenuItem_saveOriginRecordToWorksheet_Click); // // MenuItem_saveOriginRecordToIso2709 // this.MenuItem_saveOriginRecordToIso2709.Name = "MenuItem_saveOriginRecordToIso2709"; this.MenuItem_saveOriginRecordToIso2709.Size = new System.Drawing.Size(314, 30); this.MenuItem_saveOriginRecordToIso2709.Text = "保存记录到MARC文件(&S)..."; this.MenuItem_saveOriginRecordToIso2709.Click += new System.EventHandler(this.MenuItem_saveOriginRecordToIso2709_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(311, 6); // // MenuItem_exit // this.MenuItem_exit.Name = "MenuItem_exit"; this.MenuItem_exit.Size = new System.Drawing.Size(314, 30); this.MenuItem_exit.Text = "退出(&X)"; this.MenuItem_exit.Click += new System.EventHandler(this.MenuItem_exit_Click); // // MenuItem_function // this.MenuItem_function.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_saveToTemplate, this.MenuItem_viewAccessPoint, this.toolStripSeparator17, this.MenuItem_openMarcDetailFormEx, this.MenuItem_openDcFormEx, this.MenuItem_editMarcoTable, this.toolStripSeparator18, this.MenuItem_openZBatchSearchForm, this.MenuItem_openAdvertiseForm}); this.MenuItem_function.Name = "MenuItem_function"; this.MenuItem_function.Size = new System.Drawing.Size(83, 28); this.MenuItem_function.Text = "功能(&U)"; // // MenuItem_saveToTemplate // this.MenuItem_saveToTemplate.Name = "MenuItem_saveToTemplate"; this.MenuItem_saveToTemplate.Size = new System.Drawing.Size(309, 30); this.MenuItem_saveToTemplate.Text = "保存到记录模板(&T)"; this.MenuItem_saveToTemplate.Click += new System.EventHandler(this.MenuItem_saveToTemplate_Click); // // MenuItem_viewAccessPoint // this.MenuItem_viewAccessPoint.Name = "MenuItem_viewAccessPoint"; this.MenuItem_viewAccessPoint.Size = new System.Drawing.Size(309, 30); this.MenuItem_viewAccessPoint.Text = "观察检索点(&A)"; this.MenuItem_viewAccessPoint.Click += new System.EventHandler(this.MenuItem_viewAccessPoint_Click); // // toolStripSeparator17 // this.toolStripSeparator17.Name = "toolStripSeparator17"; this.toolStripSeparator17.Size = new System.Drawing.Size(306, 6); // // MenuItem_openMarcDetailFormEx // this.MenuItem_openMarcDetailFormEx.Name = "MenuItem_openMarcDetailFormEx"; this.MenuItem_openMarcDetailFormEx.Size = new System.Drawing.Size(309, 30); this.MenuItem_openMarcDetailFormEx.Text = "MARC记录窗[带模板](&M)..."; this.MenuItem_openMarcDetailFormEx.Click += new System.EventHandler(this.MenuItem_openMarcDetailFormEx_Click); // // MenuItem_openDcFormEx // this.MenuItem_openDcFormEx.Name = "MenuItem_openDcFormEx"; this.MenuItem_openDcFormEx.Size = new System.Drawing.Size(309, 30); this.MenuItem_openDcFormEx.Text = "DC记录窗[带模板](&D)..."; this.MenuItem_openDcFormEx.Click += new System.EventHandler(this.MenuItem_openDcFormEx_Click); // // MenuItem_editMarcoTable // this.MenuItem_editMarcoTable.Name = "MenuItem_editMarcoTable"; this.MenuItem_editMarcoTable.Size = new System.Drawing.Size(309, 30); this.MenuItem_editMarcoTable.Text = "宏定义(&M) ..."; this.MenuItem_editMarcoTable.Click += new System.EventHandler(this.MenuItem_editMarcoTable_Click); // // toolStripSeparator18 // this.toolStripSeparator18.Name = "toolStripSeparator18"; this.toolStripSeparator18.Size = new System.Drawing.Size(306, 6); // // MenuItem_openZBatchSearchForm // this.MenuItem_openZBatchSearchForm.Name = "MenuItem_openZBatchSearchForm"; this.MenuItem_openZBatchSearchForm.Size = new System.Drawing.Size(309, 30); this.MenuItem_openZBatchSearchForm.Text = "Z39.50批检索窗(&B)"; this.MenuItem_openZBatchSearchForm.Click += new System.EventHandler(this.MenuItem_openZBatchSearchForm_Click); // // MenuItem_openAdvertiseForm // this.MenuItem_openAdvertiseForm.Name = "MenuItem_openAdvertiseForm"; this.MenuItem_openAdvertiseForm.Size = new System.Drawing.Size(309, 30); this.MenuItem_openAdvertiseForm.Text = "广告窗(&A)"; this.MenuItem_openAdvertiseForm.Click += new System.EventHandler(this.MenuItem_openAdvertiseForm_Click); // // MenuItem_ui // this.MenuItem_ui.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_font}); this.MenuItem_ui.Name = "MenuItem_ui"; this.MenuItem_ui.Size = new System.Drawing.Size(75, 28); this.MenuItem_ui.Text = "外观(&I)"; // // MenuItem_font // this.MenuItem_font.Name = "MenuItem_font"; this.MenuItem_font.Size = new System.Drawing.Size(198, 30); this.MenuItem_font.Text = "设置字体(&F)..."; this.MenuItem_font.Click += new System.EventHandler(this.MenuItem_font_Click); // // MenuItem_window // this.MenuItem_window.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_tileHorizontal, this.MenuItem_tileVertical, this.MenuItem_cascade, this.MenuItem_arrangeIcons}); this.MenuItem_window.Name = "MenuItem_window"; this.MenuItem_window.Size = new System.Drawing.Size(88, 28); this.MenuItem_window.Text = "窗口(&W)"; // // MenuItem_tileHorizontal // this.MenuItem_tileHorizontal.Name = "MenuItem_tileHorizontal"; this.MenuItem_tileHorizontal.Size = new System.Drawing.Size(198, 30); this.MenuItem_tileHorizontal.Text = "平铺[水平](&T)"; this.MenuItem_tileHorizontal.Click += new System.EventHandler(this.MenuItem_mdi_arrange_Click); // // MenuItem_tileVertical // this.MenuItem_tileVertical.Name = "MenuItem_tileVertical"; this.MenuItem_tileVertical.Size = new System.Drawing.Size(198, 30); this.MenuItem_tileVertical.Text = "平铺[垂直](&I)"; this.MenuItem_tileVertical.Click += new System.EventHandler(this.MenuItem_mdi_arrange_Click); // // MenuItem_cascade // this.MenuItem_cascade.Name = "MenuItem_cascade"; this.MenuItem_cascade.Size = new System.Drawing.Size(198, 30); this.MenuItem_cascade.Text = "层叠(&C)"; this.MenuItem_cascade.Click += new System.EventHandler(this.MenuItem_mdi_arrange_Click); // // MenuItem_arrangeIcons // this.MenuItem_arrangeIcons.Name = "MenuItem_arrangeIcons"; this.MenuItem_arrangeIcons.Size = new System.Drawing.Size(198, 30); this.MenuItem_arrangeIcons.Text = "排列图标(&A)"; this.MenuItem_arrangeIcons.Click += new System.EventHandler(this.MenuItem_mdi_arrange_Click); // // MenuItem_help // this.MenuItem_help.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuItem_cfg, this.toolStripSeparator6, this.MenuItem_openUserFolder, this.MenuItem_openDataFolder, this.MenuItem_openProgramFolder, this.toolStripSeparator19, this.MenuItem_resetSerialCode, this.MenuItem_copyright}); this.MenuItem_help.Name = "MenuItem_help"; this.MenuItem_help.Size = new System.Drawing.Size(84, 28); this.MenuItem_help.Text = "帮助(&H)"; // // MenuItem_cfg // this.MenuItem_cfg.Name = "MenuItem_cfg"; this.MenuItem_cfg.Size = new System.Drawing.Size(244, 30); this.MenuItem_cfg.Text = "参数配置(&P)..."; this.MenuItem_cfg.Click += new System.EventHandler(this.MenuItem_cfg_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(241, 6); // // MenuItem_openUserFolder // this.MenuItem_openUserFolder.Name = "MenuItem_openUserFolder"; this.MenuItem_openUserFolder.Size = new System.Drawing.Size(244, 30); this.MenuItem_openUserFolder.Text = "打开用户文件夹(&U)"; this.MenuItem_openUserFolder.Click += new System.EventHandler(this.MenuItem_openUserFolder_Click); // // MenuItem_openDataFolder // this.MenuItem_openDataFolder.Name = "MenuItem_openDataFolder"; this.MenuItem_openDataFolder.Size = new System.Drawing.Size(244, 30); this.MenuItem_openDataFolder.Text = "打开数据文件夹(&D)"; this.MenuItem_openDataFolder.Click += new System.EventHandler(this.MenuItem_openDataFolder_Click); // // MenuItem_openProgramFolder // this.MenuItem_openProgramFolder.Name = "MenuItem_openProgramFolder"; this.MenuItem_openProgramFolder.Size = new System.Drawing.Size(244, 30); this.MenuItem_openProgramFolder.Text = "打开程序文件夹(&P)"; this.MenuItem_openProgramFolder.Click += new System.EventHandler(this.MenuItem_openProgramFolder_Click); // // toolStripSeparator19 // this.toolStripSeparator19.Name = "toolStripSeparator19"; this.toolStripSeparator19.Size = new System.Drawing.Size(241, 6); // // MenuItem_resetSerialCode // this.MenuItem_resetSerialCode.Name = "MenuItem_resetSerialCode"; this.MenuItem_resetSerialCode.Size = new System.Drawing.Size(244, 30); this.MenuItem_resetSerialCode.Text = "设置序列号(&R) ..."; this.MenuItem_resetSerialCode.Click += new System.EventHandler(this.MenuItem_resetSerialCode_Click); // // MenuItem_copyright // this.MenuItem_copyright.Name = "MenuItem_copyright"; this.MenuItem_copyright.Size = new System.Drawing.Size(244, 30); this.MenuItem_copyright.Text = "关于(&A)..."; this.MenuItem_copyright.Click += new System.EventHandler(this.MenuItem_copyright_Click); // // toolStrip_main // this.toolStrip_main.ImageScalingSize = new System.Drawing.Size(24, 24); this.toolStrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolButton_saveTo, this.toolButton_save, this.toolButton_saveToDB, this.toolStripSeparator9, this.toolButton_delete, this.toolStripSeparator1, this.toolButton_prev, this.toolButton_next, this.toolStripSeparator2, this.toolButton_nextBatch, this.toolButton_getAllRecords, this.toolStripSeparator5, this.toolButton_loadFullRecord, this.toolButton_refresh, this.toolButton_loadTemplate, this.toolStripSeparator10, this.toolStripButton_searchZ, this.toolStripButton_searchA, this.toolStripButton_copyToFixed, this.toolStripSeparator20, this.toolButton_dup, this.toolButton_verify, this.toolStripSeparator11, this.toolButton_search, this.toolButton_stop, this.toolStripButton_testSearch}); this.toolStrip_main.Location = new System.Drawing.Point(0, 34); this.toolStrip_main.Name = "toolStrip_main"; this.toolStrip_main.Padding = new System.Windows.Forms.Padding(0, 0, 2, 0); this.toolStrip_main.Size = new System.Drawing.Size(867, 31); this.toolStrip_main.TabIndex = 1; this.toolStrip_main.Text = "toolStrip1"; // // toolButton_saveTo // this.toolButton_saveTo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_saveTo.Enabled = false; this.toolButton_saveTo.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_saveTo.Image"))); this.toolButton_saveTo.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_saveTo.Name = "toolButton_saveTo"; this.toolButton_saveTo.Size = new System.Drawing.Size(28, 28); this.toolButton_saveTo.Text = "保存到..."; this.toolButton_saveTo.Click += new System.EventHandler(this.toolButton_saveTo_Click); // // toolButton_save // this.toolButton_save.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_save.Enabled = false; this.toolButton_save.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_save.Image"))); this.toolButton_save.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_save.Name = "toolButton_save"; this.toolButton_save.Size = new System.Drawing.Size(28, 28); this.toolButton_save.Text = "保存(到数据库) F2"; this.toolButton_save.Click += new System.EventHandler(this.toolButton_save_Click); // // toolButton_saveToDB // this.toolButton_saveToDB.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_saveToDB.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_saveToDB.Image"))); this.toolButton_saveToDB.ImageTransparentColor = System.Drawing.Color.Black; this.toolButton_saveToDB.Name = "toolButton_saveToDB"; this.toolButton_saveToDB.Size = new System.Drawing.Size(28, 28); this.toolButton_saveToDB.Text = "另存(到数据库) F3"; this.toolButton_saveToDB.Click += new System.EventHandler(this.toolButton_saveToDB_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(6, 31); // // toolButton_delete // this.toolButton_delete.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_delete.Enabled = false; this.toolButton_delete.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_delete.Image"))); this.toolButton_delete.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_delete.Name = "toolButton_delete"; this.toolButton_delete.Size = new System.Drawing.Size(28, 28); this.toolButton_delete.Text = "删除"; this.toolButton_delete.Click += new System.EventHandler(this.toolButton_delete_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 31); // // toolButton_prev // this.toolButton_prev.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_prev.Enabled = false; this.toolButton_prev.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_prev.Image"))); this.toolButton_prev.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_prev.Name = "toolButton_prev"; this.toolButton_prev.Size = new System.Drawing.Size(28, 28); this.toolButton_prev.Text = "上一记录"; this.toolButton_prev.Click += new System.EventHandler(this.toolButton_prev_Click); // // toolButton_next // this.toolButton_next.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_next.Enabled = false; this.toolButton_next.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_next.Image"))); this.toolButton_next.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_next.Name = "toolButton_next"; this.toolButton_next.Size = new System.Drawing.Size(28, 28); this.toolButton_next.Text = "下一记录"; this.toolButton_next.Click += new System.EventHandler(this.toolButton_next_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 31); // // toolButton_nextBatch // this.toolButton_nextBatch.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_nextBatch.Enabled = false; this.toolButton_nextBatch.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_nextBatch.Image"))); this.toolButton_nextBatch.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_nextBatch.Name = "toolButton_nextBatch"; this.toolButton_nextBatch.Size = new System.Drawing.Size(28, 28); this.toolButton_nextBatch.Text = "下一批记录"; this.toolButton_nextBatch.Click += new System.EventHandler(this.toolButton_nextBatch_Click); // // toolButton_getAllRecords // this.toolButton_getAllRecords.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_getAllRecords.Enabled = false; this.toolButton_getAllRecords.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_getAllRecords.Image"))); this.toolButton_getAllRecords.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_getAllRecords.Name = "toolButton_getAllRecords"; this.toolButton_getAllRecords.Size = new System.Drawing.Size(28, 28); this.toolButton_getAllRecords.Text = "获得检索命中的全部记录"; this.toolButton_getAllRecords.Click += new System.EventHandler(this.toolButton_getAllRecords_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 31); // // toolButton_loadFullRecord // this.toolButton_loadFullRecord.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_loadFullRecord.Enabled = false; this.toolButton_loadFullRecord.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_loadFullRecord.Image"))); this.toolButton_loadFullRecord.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_loadFullRecord.Name = "toolButton_loadFullRecord"; this.toolButton_loadFullRecord.Size = new System.Drawing.Size(28, 28); this.toolButton_loadFullRecord.Text = "装载详细记录"; this.toolButton_loadFullRecord.Click += new System.EventHandler(this.toolButton_loadFullRecord_Click); // // toolButton_refresh // this.toolButton_refresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_refresh.Enabled = false; this.toolButton_refresh.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_refresh.Image"))); this.toolButton_refresh.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolButton_refresh.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_refresh.Name = "toolButton_refresh"; this.toolButton_refresh.Size = new System.Drawing.Size(23, 28); this.toolButton_refresh.Text = "刷新"; this.toolButton_refresh.Click += new System.EventHandler(this.toolButton_refresh_Click); // // toolButton_loadTemplate // this.toolButton_loadTemplate.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_loadTemplate.Enabled = false; this.toolButton_loadTemplate.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_loadTemplate.Image"))); this.toolButton_loadTemplate.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolButton_loadTemplate.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_loadTemplate.Name = "toolButton_loadTemplate"; this.toolButton_loadTemplate.Size = new System.Drawing.Size(26, 28); this.toolButton_loadTemplate.Text = "装载模板"; this.toolButton_loadTemplate.Click += new System.EventHandler(this.toolButton_loadTemplate_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(6, 31); // // toolStripButton_searchZ // this.toolStripButton_searchZ.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton_searchZ.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton_searchZ.Image"))); this.toolStripButton_searchZ.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_searchZ.Name = "toolStripButton_searchZ"; this.toolStripButton_searchZ.Size = new System.Drawing.Size(25, 28); this.toolStripButton_searchZ.Text = "Z"; this.toolStripButton_searchZ.ToolTipText = "用 Z39.50 检索当前记录"; this.toolStripButton_searchZ.Click += new System.EventHandler(this.toolStripButton_searchZ_Click); // // toolStripButton_searchA // this.toolStripButton_searchA.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton_searchA.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton_searchA.Image"))); this.toolStripButton_searchA.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_searchA.Name = "toolStripButton_searchA"; this.toolStripButton_searchA.Size = new System.Drawing.Size(27, 28); this.toolStripButton_searchA.Text = "A"; this.toolStripButton_searchA.ToolTipText = "用亚马逊检索当前记录"; this.toolStripButton_searchA.Click += new System.EventHandler(this.toolStripButton_searchA_Click); // // toolStripButton_copyToFixed // this.toolStripButton_copyToFixed.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton_copyToFixed.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton_copyToFixed.Image"))); this.toolStripButton_copyToFixed.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_copyToFixed.Name = "toolStripButton_copyToFixed"; this.toolStripButton_copyToFixed.Size = new System.Drawing.Size(63, 28); this.toolStripButton_copyToFixed.Text = "<复制"; this.toolStripButton_copyToFixed.ToolTipText = "从当前窗口复制到固定窗口"; this.toolStripButton_copyToFixed.Click += new System.EventHandler(this.toolStripButton_copyToFixed_Click); // // toolStripSeparator20 // this.toolStripSeparator20.Name = "toolStripSeparator20"; this.toolStripSeparator20.Size = new System.Drawing.Size(6, 31); // // toolButton_dup // this.toolButton_dup.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_dup.Enabled = false; this.toolButton_dup.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_dup.Image"))); this.toolButton_dup.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolButton_dup.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_dup.Name = "toolButton_dup"; this.toolButton_dup.Size = new System.Drawing.Size(26, 28); this.toolButton_dup.Text = "查重"; this.toolButton_dup.Click += new System.EventHandler(this.toolButton_dup_Click); // // toolButton_verify // this.toolButton_verify.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_verify.Enabled = false; this.toolButton_verify.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_verify.Image"))); this.toolButton_verify.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_verify.Name = "toolButton_verify"; this.toolButton_verify.Size = new System.Drawing.Size(28, 28); this.toolButton_verify.Text = "校验数据 (Ctrl+Y)"; this.toolButton_verify.Click += new System.EventHandler(this.toolButton_verify_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Size = new System.Drawing.Size(6, 31); // // toolButton_search // this.toolButton_search.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_search.Enabled = false; this.toolButton_search.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_search.Image"))); this.toolButton_search.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolButton_search.Name = "toolButton_search"; this.toolButton_search.Size = new System.Drawing.Size(28, 28); this.toolButton_search.Text = "检索"; this.toolButton_search.Click += new System.EventHandler(this.toolButton_search_Click); // // toolButton_stop // this.toolButton_stop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolButton_stop.Enabled = false; this.toolButton_stop.Image = ((System.Drawing.Image)(resources.GetObject("toolButton_stop.Image"))); this.toolButton_stop.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolButton_stop.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.toolButton_stop.Name = "toolButton_stop"; this.toolButton_stop.Size = new System.Drawing.Size(26, 28); this.toolButton_stop.Text = "停止"; this.toolButton_stop.Click += new System.EventHandler(this.toolButton_stop_Click); // // toolStripButton_testSearch // this.toolStripButton_testSearch.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripButton_testSearch.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton_testSearch.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton_testSearch.Image"))); this.toolStripButton_testSearch.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_testSearch.Name = "toolStripButton_testSearch"; this.toolStripButton_testSearch.Size = new System.Drawing.Size(111, 28); this.toolStripButton_testSearch.Text = "Test Search"; this.toolStripButton_testSearch.Visible = false; this.toolStripButton_testSearch.Click += new System.EventHandler(this.toolStripButton_testSearch_Click); // // statusStrip_main // this.statusStrip_main.ImageScalingSize = new System.Drawing.Size(24, 24); this.statusStrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripProgressBar_main, this.toolStripStatusLabel_main}); this.statusStrip_main.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; this.statusStrip_main.Location = new System.Drawing.Point(0, 443); this.statusStrip_main.MinimumSize = new System.Drawing.Size(0, 34); this.statusStrip_main.Name = "statusStrip_main"; this.statusStrip_main.Padding = new System.Windows.Forms.Padding(2, 0, 15, 0); this.statusStrip_main.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.statusStrip_main.Size = new System.Drawing.Size(867, 34); this.statusStrip_main.TabIndex = 2; this.statusStrip_main.Text = "statusStrip1"; // // toolStripProgressBar_main // this.toolStripProgressBar_main.AutoSize = false; this.toolStripProgressBar_main.BackColor = System.Drawing.SystemColors.Control; this.toolStripProgressBar_main.Name = "toolStripProgressBar_main"; this.toolStripProgressBar_main.Size = new System.Drawing.Size(150, 26); this.toolStripProgressBar_main.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this.toolStripProgressBar_main.Visible = false; // // toolStripStatusLabel_main // this.toolStripStatusLabel_main.Name = "toolStripStatusLabel_main"; this.toolStripStatusLabel_main.RightToLeft = System.Windows.Forms.RightToLeft.No; this.toolStripStatusLabel_main.Size = new System.Drawing.Size(184, 24); this.toolStripStatusLabel_main.Spring = true; this.toolStripStatusLabel_main.Text = "欢迎使用dp2Catalog"; this.toolStripStatusLabel_main.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // panel_fixed // this.panel_fixed.Controls.Add(this.tabControl_panelFixed); this.panel_fixed.Controls.Add(this.toolStrip_panelFixed); this.panel_fixed.Dock = System.Windows.Forms.DockStyle.Right; this.panel_fixed.Location = new System.Drawing.Point(623, 65); this.panel_fixed.Name = "panel_fixed"; this.panel_fixed.Size = new System.Drawing.Size(244, 378); this.panel_fixed.TabIndex = 6; // // tabControl_panelFixed // this.tabControl_panelFixed.Appearance = System.Windows.Forms.TabAppearance.FlatButtons; this.tabControl_panelFixed.Controls.Add(this.tabPage_operHistory); this.tabControl_panelFixed.Controls.Add(this.tabPage_property); this.tabControl_panelFixed.Controls.Add(this.tabPage_verifyResult); this.tabControl_panelFixed.Controls.Add(this.tabPage_generateData); this.tabControl_panelFixed.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl_panelFixed.Location = new System.Drawing.Point(0, 25); this.tabControl_panelFixed.Margin = new System.Windows.Forms.Padding(0); this.tabControl_panelFixed.Name = "tabControl_panelFixed"; this.tabControl_panelFixed.Padding = new System.Drawing.Point(0, 0); this.tabControl_panelFixed.SelectedIndex = 0; this.tabControl_panelFixed.Size = new System.Drawing.Size(244, 353); this.tabControl_panelFixed.TabIndex = 1; // // tabPage_operHistory // this.tabPage_operHistory.Controls.Add(this.webBrowser_history); this.tabPage_operHistory.Location = new System.Drawing.Point(4, 31); this.tabPage_operHistory.Margin = new System.Windows.Forms.Padding(4); this.tabPage_operHistory.Name = "tabPage_operHistory"; this.tabPage_operHistory.Size = new System.Drawing.Size(236, 318); this.tabPage_operHistory.TabIndex = 4; this.tabPage_operHistory.Text = "操作历史"; this.tabPage_operHistory.UseVisualStyleBackColor = true; // // webBrowser_history // this.webBrowser_history.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser_history.Location = new System.Drawing.Point(0, 0); this.webBrowser_history.Margin = new System.Windows.Forms.Padding(4); this.webBrowser_history.MinimumSize = new System.Drawing.Size(30, 30); this.webBrowser_history.Name = "webBrowser_history"; this.webBrowser_history.Size = new System.Drawing.Size(236, 318); this.webBrowser_history.TabIndex = 0; // // tabPage_property // this.tabPage_property.Location = new System.Drawing.Point(4, 31); this.tabPage_property.Margin = new System.Windows.Forms.Padding(4); this.tabPage_property.Name = "tabPage_property"; this.tabPage_property.Size = new System.Drawing.Size(236, 318); this.tabPage_property.TabIndex = 1; this.tabPage_property.Text = "属性"; this.tabPage_property.UseVisualStyleBackColor = true; // // tabPage_verifyResult // this.tabPage_verifyResult.Location = new System.Drawing.Point(4, 31); this.tabPage_verifyResult.Margin = new System.Windows.Forms.Padding(4); this.tabPage_verifyResult.Name = "tabPage_verifyResult"; this.tabPage_verifyResult.Size = new System.Drawing.Size(236, 318); this.tabPage_verifyResult.TabIndex = 2; this.tabPage_verifyResult.Text = "校验结果"; this.tabPage_verifyResult.UseVisualStyleBackColor = true; // // tabPage_generateData // this.tabPage_generateData.Location = new System.Drawing.Point(4, 31); this.tabPage_generateData.Margin = new System.Windows.Forms.Padding(4); this.tabPage_generateData.Name = "tabPage_generateData"; this.tabPage_generateData.Size = new System.Drawing.Size(236, 318); this.tabPage_generateData.TabIndex = 3; this.tabPage_generateData.Text = "创建数据"; this.tabPage_generateData.UseVisualStyleBackColor = true; // // toolStrip_panelFixed // this.toolStrip_panelFixed.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip_panelFixed.ImageScalingSize = new System.Drawing.Size(24, 24); this.toolStrip_panelFixed.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton_close}); this.toolStrip_panelFixed.Location = new System.Drawing.Point(0, 0); this.toolStrip_panelFixed.Name = "toolStrip_panelFixed"; this.toolStrip_panelFixed.Padding = new System.Windows.Forms.Padding(0, 0, 2, 0); this.toolStrip_panelFixed.Size = new System.Drawing.Size(244, 25); this.toolStrip_panelFixed.TabIndex = 3; this.toolStrip_panelFixed.Text = "toolStrip1"; // // toolStripButton_close // this.toolStripButton_close.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripButton_close.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_close.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton_close.Image"))); this.toolStripButton_close.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolStripButton_close.ImageTransparentColor = System.Drawing.Color.White; this.toolStripButton_close.Name = "toolStripButton_close"; this.toolStripButton_close.Size = new System.Drawing.Size(23, 22); this.toolStripButton_close.Text = "隐藏面板"; this.toolStripButton_close.Click += new System.EventHandler(this.toolStripButton_close_Click); // // splitter_fixed // this.splitter_fixed.Dock = System.Windows.Forms.DockStyle.Right; this.splitter_fixed.Location = new System.Drawing.Point(620, 65); this.splitter_fixed.Name = "splitter_fixed"; this.splitter_fixed.Size = new System.Drawing.Size(3, 378); this.splitter_fixed.TabIndex = 7; this.splitter_fixed.TabStop = false; // // MenuItem_openSruSearchForm // this.MenuItem_openSruSearchForm.Name = "MenuItem_openSruSearchForm"; this.MenuItem_openSruSearchForm.Size = new System.Drawing.Size(314, 30); this.MenuItem_openSruSearchForm.Text = "SRU 检索窗(S)"; this.MenuItem_openSruSearchForm.Click += new System.EventHandler(this.MenuItem_openSruSearchForm_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(867, 477); this.Controls.Add(this.splitter_fixed); this.Controls.Add(this.panel_fixed); this.Controls.Add(this.statusStrip_main); this.Controls.Add(this.toolStrip_main); this.Controls.Add(this.menuStrip_main); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.MainMenuStrip = this.menuStrip_main; this.Name = "MainForm"; this.Text = "dp2Catalog V3 -- dp2编目前端"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed); this.Load += new System.EventHandler(this.MainForm_Load); this.menuStrip_main.ResumeLayout(false); this.menuStrip_main.PerformLayout(); this.toolStrip_main.ResumeLayout(false); this.toolStrip_main.PerformLayout(); this.statusStrip_main.ResumeLayout(false); this.statusStrip_main.PerformLayout(); this.panel_fixed.ResumeLayout(false); this.panel_fixed.PerformLayout(); this.tabControl_panelFixed.ResumeLayout(false); this.tabPage_operHistory.ResumeLayout(false); this.toolStrip_panelFixed.ResumeLayout(false); this.toolStrip_panelFixed.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip_main; private System.Windows.Forms.ToolStrip toolStrip_main; private System.Windows.Forms.ToolStripMenuItem MenuItem_file; private System.Windows.Forms.StatusStrip statusStrip_main; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_main; private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar_main; private System.Windows.Forms.ToolStripMenuItem MenuItem_openZSearchForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_window; private System.Windows.Forms.ToolStripMenuItem MenuItem_openMarcDetailForm; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; public System.Windows.Forms.ToolStripButton toolButton_search; public System.Windows.Forms.ToolStripButton toolButton_prev; public System.Windows.Forms.ToolStripButton toolButton_next; public System.Windows.Forms.ToolStripButton toolButton_nextBatch; public System.Windows.Forms.ToolStripButton toolButton_saveTo; public System.Windows.Forms.ToolStripButton toolButton_getAllRecords; public System.Windows.Forms.ToolStripButton toolButton_save; public System.Windows.Forms.ToolStripButton toolButton_delete; public System.Windows.Forms.ToolStripMenuItem MenuItem_copyright; public System.Windows.Forms.ToolStripMenuItem MenuItem_saveOriginRecordToIso2709; public System.Windows.Forms.ToolStripMenuItem MenuItem_font; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem MenuItem_exit; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem MenuItem_tileHorizontal; private System.Windows.Forms.ToolStripMenuItem MenuItem_tileVertical; private System.Windows.Forms.ToolStripMenuItem MenuItem_cascade; private System.Windows.Forms.ToolStripMenuItem MenuItem_arrangeIcons; private System.Windows.Forms.ToolStripMenuItem MenuItem_help; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDtlpSearchForm; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripMenuItem MenuItem_cfg; private System.Windows.Forms.ToolStripMenuItem MenuItem_systemManagement; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDtlpLogForm; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDataFolder; private System.Windows.Forms.ToolStripMenuItem MenuItem_openEaccForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_ui; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripMenuItem MenuItem_loadXmlDetailForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openBerDebugForm1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDcForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDp2SearchForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openOaiSearchForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openZhongcihaoForm; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; public System.Windows.Forms.ToolStripButton toolButton_loadTemplate; public System.Windows.Forms.ToolStripButton toolButton_refresh; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; public System.Windows.Forms.ToolStripButton toolButton_dup; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripMenuItem MenuItem_linkMarcFile; private System.Windows.Forms.ToolStripMenuItem MenuItem_changePassword; private System.Windows.Forms.ToolStripSeparator toolStripSeparator13; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; private System.Windows.Forms.ToolStripMenuItem MenuItem_openTestForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_clearCfgCache; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private System.Windows.Forms.ToolStripMenuItem MenuItem_function; public System.Windows.Forms.ToolStripMenuItem MenuItem_saveToTemplate; public System.Windows.Forms.ToolStripMenuItem MenuItem_viewAccessPoint; private System.Windows.Forms.ToolStripButton toolStripButton_testSearch; public System.Windows.Forms.ToolStripButton toolButton_stop; public System.Windows.Forms.ToolStripButton toolButton_saveToDB; public System.Windows.Forms.Panel panel_fixed; public System.Windows.Forms.TabControl tabControl_panelFixed; public System.Windows.Forms.TabPage tabPage_property; private System.Windows.Forms.TabPage tabPage_verifyResult; private System.Windows.Forms.ToolStrip toolStrip_panelFixed; private System.Windows.Forms.ToolStripButton toolStripButton_close; public System.Windows.Forms.Splitter splitter_fixed; public System.Windows.Forms.ToolStripMenuItem MenuItem_saveOriginRecordToWorksheet; private System.Windows.Forms.ToolStripSeparator toolStripSeparator17; private System.Windows.Forms.ToolStripMenuItem MenuItem_openMarcDetailFormEx; private System.Windows.Forms.ToolStripMenuItem MenuItem_openDcFormEx; public System.Windows.Forms.ToolStripButton toolButton_verify; private System.Windows.Forms.TabPage tabPage_generateData; private System.Windows.Forms.ToolStripSeparator toolStripSeparator18; private System.Windows.Forms.ToolStripMenuItem MenuItem_openProgramFolder; private System.Windows.Forms.ToolStripSeparator toolStripSeparator19; public System.Windows.Forms.ToolStripButton toolButton_loadFullRecord; private System.Windows.Forms.ToolStripMenuItem MenuItem_openZBatchSearchForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openAmazonSearchForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openZBatchSearchForm1; private System.Windows.Forms.TabPage tabPage_operHistory; private System.Windows.Forms.WebBrowser webBrowser_history; private System.Windows.Forms.ToolStripMenuItem MenuItem_resetSerialCode; private System.Windows.Forms.ToolStripMenuItem MenuItem_openAdvertiseForm; private System.Windows.Forms.ToolStripMenuItem MenuItem_openUserFolder; private System.Windows.Forms.ToolStripButton toolStripButton_searchZ; private System.Windows.Forms.ToolStripButton toolStripButton_searchA; private System.Windows.Forms.ToolStripSeparator toolStripSeparator20; public System.Windows.Forms.ToolStripButton toolStripButton_copyToFixed; private System.Windows.Forms.ToolStripMenuItem MenuItem_editMarcoTable; private System.Windows.Forms.ToolStripMenuItem MenuItem_openSruSearchForm; } }
60.408935
168
0.667401
[ "Apache-2.0" ]
donsllon/dp2
dp2Catalog/MainForm/MainForm.Designer.cs
70,934
C#
using FakeXrmEasy; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace LAT.WorkflowUtilities.String.Tests { [TestClass] public class B64EncodeTests { #region Test Initialization and Cleanup // Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void ClassInitialize(TestContext testContext) { } // Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void ClassCleanup() { } // Use TestInitialize to run code before running each test [TestInitialize()] public void TestMethodInitialize() { } // Use TestCleanup to run code after each test has run [TestCleanup()] public void TestMethodCleanup() { } #endregion [TestMethod] public void B64Encode_Given_EmptyString_Then_EmptyStringReturn() { //Arrange XrmFakedWorkflowContext workflowContext = new XrmFakedWorkflowContext(); var inputs = new Dictionary<string, object> { { "StringToEncode", string.Empty }, }; XrmFakedContext xrmFakedContext = new XrmFakedContext(); const string expected = ""; //Act var result = xrmFakedContext.ExecuteCodeActivity<B64Encode>(workflowContext, inputs); //Assert Assert.AreEqual(expected, result["B64EncodedString"]); } [TestMethod] public void B64Encode_Given_String_Then_B64StringReturn() { //Arrange XrmFakedWorkflowContext workflowContext = new XrmFakedWorkflowContext(); var inputs = new Dictionary<string, object> { { "StringToEncode", "Hello World!" }, }; XrmFakedContext xrmFakedContext = new XrmFakedContext(); const string expected = "SGVsbG8gV29ybGQh"; //Act var result = xrmFakedContext.ExecuteCodeActivity<B64Encode>(workflowContext, inputs); //Assert Assert.AreEqual(expected, result["B64EncodedString"]); } } }
31.333333
97
0.618351
[ "MIT" ]
jlattimer/CRM-String-Workflow-Utilities
LAT.WorkflowUtilities.String.Tests/B64EncodeTests.cs
2,258
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using LocatorServer.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using LocatorServer.Services; namespace LocatorServer.Areas.Identity.Pages.Account { [AllowAnonymous] public class LoginModel : PageModel { private readonly UserManager<LocatorUser> _userManager; private readonly SignInManager<LocatorUser> _signInManager; private readonly ILogger<LoginModel> _logger; public LoginModel(SignInManager<LocatorUser> signInManager, ILogger<LoginModel> logger, UserManager<LocatorUser> userManager) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public async Task OnGetAsync(string returnUrl = null) { if (!string.IsNullOrEmpty(ErrorMessage)) { ModelState.AddModelError(string.Empty, ErrorMessage); } returnUrl ??= Url.Content("~/"); // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation("User logged in."); return LocalRedirect(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToPage("./Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return Page(); } } // If we got this far, something failed, redisplay form return Page(); } } }
34.95614
143
0.584944
[ "MIT" ]
blaxbb/locatorserver
LocatorServer/Areas/Identity/Pages/Account/Login.cshtml.cs
3,987
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.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Utils; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Scoring; namespace osu.Game.Rulesets.Scoring { public class ScoreProcessor : JudgementProcessor { private const double max_score = 1000000; /// <summary> /// The current total score. /// </summary> public readonly BindableDouble TotalScore = new BindableDouble { MinValue = 0 }; /// <summary> /// The current accuracy. /// </summary> public readonly BindableDouble Accuracy = new BindableDouble(1) { MinValue = 0, MaxValue = 1 }; /// <summary> /// The current combo. /// </summary> public readonly BindableInt Combo = new BindableInt(); /// <summary> /// The current selected mods /// </summary> public readonly Bindable<IReadOnlyList<Mod>> Mods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>()); /// <summary> /// The current rank. /// </summary> public readonly Bindable<ScoreRank> Rank = new Bindable<ScoreRank>(ScoreRank.X); /// <summary> /// The highest combo achieved by this score. /// </summary> public readonly BindableInt HighestCombo = new BindableInt(); /// <summary> /// The <see cref="ScoringMode"/> used to calculate scores. /// </summary> public readonly Bindable<ScoringMode> Mode = new Bindable<ScoringMode>(); /// <summary> /// The default portion of <see cref="max_score"/> awarded for hitting <see cref="HitObject"/>s accurately. Defaults to 30%. /// </summary> protected virtual double DefaultAccuracyPortion => 0.3; /// <summary> /// The default portion of <see cref="max_score"/> awarded for achieving a high combo. Default to 70%. /// </summary> protected virtual double DefaultComboPortion => 0.7; private readonly double accuracyPortion; private readonly double comboPortion; private int maxAchievableCombo; private double maxBaseScore; private double rollingMaxBaseScore; private double baseScore; private readonly List<HitEvent> hitEvents = new List<HitEvent>(); private HitObject lastHitObject; private double scoreMultiplier = 1; public ScoreProcessor() { accuracyPortion = DefaultAccuracyPortion; comboPortion = DefaultComboPortion; if (!Precision.AlmostEquals(1.0, accuracyPortion + comboPortion)) throw new InvalidOperationException($"{nameof(DefaultAccuracyPortion)} + {nameof(DefaultComboPortion)} must equal 1."); Combo.ValueChanged += combo => HighestCombo.Value = Math.Max(HighestCombo.Value, combo.NewValue); Accuracy.ValueChanged += accuracy => { Rank.Value = rankFrom(accuracy.NewValue); foreach (var mod in Mods.Value.OfType<IApplicableToScoreProcessor>()) Rank.Value = mod.AdjustRank(Rank.Value, accuracy.NewValue); }; Mode.ValueChanged += _ => updateScore(); Mods.ValueChanged += mods => { scoreMultiplier = 1; foreach (var m in mods.NewValue) scoreMultiplier *= m.ScoreMultiplier; updateScore(); }; } private readonly Dictionary<HitResult, int> scoreResultCounts = new Dictionary<HitResult, int>(); protected sealed override void ApplyResultInternal(JudgementResult result) { result.ComboAtJudgement = Combo.Value; result.HighestComboAtJudgement = HighestCombo.Value; if (result.FailedAtJudgement) return; if (!result.Type.IsScorable()) return; if (result.Type.AffectsCombo()) { switch (result.Type) { case HitResult.Miss: case HitResult.LargeTickMiss: Combo.Value = 0; break; default: Combo.Value++; break; } } double scoreIncrease = result.Type.IsHit() ? result.Judgement.NumericResultFor(result) : 0; if (!result.Type.IsBonus()) { baseScore += scoreIncrease; rollingMaxBaseScore += result.Judgement.MaxNumericResult; } scoreResultCounts[result.Type] = scoreResultCounts.GetOrDefault(result.Type) + 1; hitEvents.Add(CreateHitEvent(result)); lastHitObject = result.HitObject; updateScore(); } /// <summary> /// Creates the <see cref="HitEvent"/> that describes a <see cref="JudgementResult"/>. /// </summary> /// <param name="result">The <see cref="JudgementResult"/> to describe.</param> /// <returns>The <see cref="HitEvent"/>.</returns> protected virtual HitEvent CreateHitEvent(JudgementResult result) => new HitEvent(result.TimeOffset, result.Type, result.HitObject, lastHitObject, null); protected sealed override void RevertResultInternal(JudgementResult result) { Combo.Value = result.ComboAtJudgement; HighestCombo.Value = result.HighestComboAtJudgement; if (result.FailedAtJudgement) return; if (!result.Type.IsScorable()) return; double scoreIncrease = result.Type.IsHit() ? result.Judgement.NumericResultFor(result) : 0; if (!result.Type.IsBonus()) { baseScore -= scoreIncrease; rollingMaxBaseScore -= result.Judgement.MaxNumericResult; } scoreResultCounts[result.Type] = scoreResultCounts.GetOrDefault(result.Type) - 1; Debug.Assert(hitEvents.Count > 0); lastHitObject = hitEvents[^1].LastHitObject; hitEvents.RemoveAt(hitEvents.Count - 1); updateScore(); } private void updateScore() { if (rollingMaxBaseScore != 0) Accuracy.Value = baseScore / rollingMaxBaseScore; TotalScore.Value = getScore(Mode.Value); } private double getScore(ScoringMode mode) { return GetScore(mode, maxAchievableCombo, maxBaseScore > 0 ? baseScore / maxBaseScore : 0, maxAchievableCombo > 0 ? (double)HighestCombo.Value / maxAchievableCombo : 1, scoreResultCounts); } /// <summary> /// Computes the total score. /// </summary> /// <param name="mode">The <see cref="ScoringMode"/> to compute the total score in.</param> /// <param name="maxCombo">The maximum combo achievable in the beatmap.</param> /// <param name="accuracyRatio">The accuracy percentage achieved by the player.</param> /// <param name="comboRatio">The proportion of <paramref name="maxCombo"/> achieved by the player.</param> /// <param name="statistics">Any statistics to be factored in.</param> /// <returns>The total score.</returns> public double GetScore(ScoringMode mode, int maxCombo, double accuracyRatio, double comboRatio, Dictionary<HitResult, int> statistics) { switch (mode) { default: case ScoringMode.Standardised: double accuracyScore = accuracyPortion * accuracyRatio; double comboScore = comboPortion * comboRatio; return (max_score * (accuracyScore + comboScore) + getBonusScore(statistics)) * scoreMultiplier; case ScoringMode.Classic: // should emulate osu-stable's scoring as closely as we can (https://osu.ppy.sh/help/wiki/Score/ScoreV1) return getBonusScore(statistics) + (accuracyRatio * Math.Max(1, maxCombo) * 300) * (1 + Math.Max(0, (comboRatio * maxCombo) - 1) * scoreMultiplier / 25); } } private double getBonusScore(Dictionary<HitResult, int> statistics) => statistics.GetOrDefault(HitResult.SmallBonus) * Judgement.SMALL_BONUS_SCORE + statistics.GetOrDefault(HitResult.LargeBonus) * Judgement.LARGE_BONUS_SCORE; private ScoreRank rankFrom(double acc) { if (acc == 1) return ScoreRank.X; if (acc > 0.95) return ScoreRank.S; if (acc > 0.9) return ScoreRank.A; if (acc > 0.8) return ScoreRank.B; if (acc > 0.7) return ScoreRank.C; return ScoreRank.D; } public int GetStatistic(HitResult result) => scoreResultCounts.GetOrDefault(result); public double GetStandardisedScore() => getScore(ScoringMode.Standardised); /// <summary> /// Resets this ScoreProcessor to a default state. /// </summary> /// <param name="storeResults">Whether to store the current state of the <see cref="ScoreProcessor"/> for future use.</param> protected override void Reset(bool storeResults) { base.Reset(storeResults); scoreResultCounts.Clear(); hitEvents.Clear(); lastHitObject = null; if (storeResults) { maxAchievableCombo = HighestCombo.Value; maxBaseScore = baseScore; } baseScore = 0; rollingMaxBaseScore = 0; TotalScore.Value = 0; Accuracy.Value = 1; Combo.Value = 0; Rank.Value = ScoreRank.X; HighestCombo.Value = 0; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); hitEvents.Clear(); } /// <summary> /// Retrieve a score populated with data for the current play this processor is responsible for. /// </summary> public virtual void PopulateScore(ScoreInfo score) { score.TotalScore = (long)Math.Round(GetStandardisedScore()); score.Combo = Combo.Value; score.MaxCombo = HighestCombo.Value; score.Accuracy = Math.Round(Accuracy.Value, 4); score.Rank = Rank.Value; score.Date = DateTimeOffset.Now; foreach (var result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Where(r => r.IsScorable())) score.Statistics[result] = GetStatistic(result); score.HitEvents = hitEvents; } /// <summary> /// Create a <see cref="HitWindows"/> for this processor. /// </summary> [Obsolete("Method is now unused.")] // Can be removed 20210328 public virtual HitWindows CreateHitWindows() => new HitWindows(); } public enum ScoringMode { Standardised, Classic } }
37.244514
174
0.567461
[ "MIT" ]
Airkek/osu
osu.Game/Rulesets/Scoring/ScoreProcessor.cs
11,565
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ArraySolver")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ArraySolver")] [assembly: System.Reflection.AssemblyTitleAttribute("ArraySolver")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.958333
80
0.648016
[ "MIT" ]
mfaqiri/PO-week-1
ArraySolver/obj/Debug/net5.0/ArraySolver.AssemblyInfo.cs
983
C#
//----------------------------------------------------------------------------- // Filename: SIPTCPChannel.cs // // Description: SIP transport for TCP. Not this is also the base class for the // SIPTLSChannel. For the TLS channel the TCP base class will accept or connect and // then switch to the TLS class to upgrade to an SSL stream. // // Author(s): // Aaron Clauson (aaron@sipsorcery.com) // // History: // 19 Apr 2008 Aaron Clauson Created, Hobart, Australia. // 16 Oct 2019 Aaron Clauson Added IPv6 support. // 24 Oct 2019 Aaron Clauson Major refactor to avoid TIME_WAIT state on connection close. // 19 Nov 2019 Aaron Clauson Enhanced to deal with listening on IPAddress.Any. // // Notes: // See https://stackoverflow.com/questions/58506815/how-to-apply-linger-option-with-winsock2/58511052#58511052 for // a discussion about the TIME_WAIT and the Linger option. It's very relevant for this class which potentially // needs to close a TCP connection and then quickly re-establish it. For example if there is a SIP parsing // error and the end of a SIP message cannot be determined the only reliable way to recover is to close and // re-establish the TCP connection. // // Additional background information on TIME_WAIT: // https://tools.ietf.org/html/draft-faber-time-wait-avoidance-00: RFC for mechanism to avoid TIME_WAIT state on busy web servers. // http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html: // Explanation of TIME_WAIT state purpose. // // Asynchronous Sockets: // The async socket mechanism used in this class is the "new high performance" approach described at // https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socketasynceventargs?view=netframework-4.8#remarks // While that sounds nice the main motivation for this class was simply to switch to an async method // that did not require the BeginReceive & EndReceive callbacks or the "Asynchronous Programming Model" (APM) // see https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/. A "Task-based Asynchronous Pattern" // would have been preferred but only for consistency with the rest of the code base and .NET libraries. // Also note that the SIPUDPChannel is using the APM BeginReceiveMessageFrom/EndReceiveMessageFrom approach. The motivation // for that decision is that it's the only one of the UDP socket receives methods that provides access to the received on // IP address when listening on IPAddress.Any. // // License: // BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. //----------------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using SIPSorcery.Sys; namespace SIPSorcery.SIP { public class SIPTCPChannel : SIPChannel { private const int MAX_TCP_CONNECTIONS = 1000; // Maximum number of connections for the TCP listener. private const int PRUNE_CONNECTIONS_INTERVAL = 60000; // The period at which to prune the connections. private const int PRUNE_NOTRANSMISSION_MINUTES = 70; // The number of minutes after which if no transmissions are sent or received a connection will be pruned. /// <summary> /// This is the main object managed by this class. It is the socket listening for incoming connections. /// </summary> protected TcpListener m_tcpServerListener; /// <summary> /// List of sockets that are in the process of being connected to. /// Needed to avoid SIP re-transmits initiating multiple connect attempts. /// </summary> protected List<string> m_connectingSockets = new List<string>(); /// <summary> /// This string is used in debug messages. It makes it possible to differentiate /// whether an instance in acting solely as a TCP channel or as the base class of a TLS channel. /// </summary> virtual protected string ProtDescr { get; } = "TCP"; /// <summary> /// Can be set to allow TCP channels hosted in the same process to send to each other. Useful for testing. /// By default sends between TCP channels in the same process are disabled to prevent resource exhaustion. /// </summary> public bool DisableLocalTCPSocketsCheck; /// <summary> /// Keeps a list of TCP sockets this process is listening on to prevent it establishing TCP connections to itself. /// </summary> private static List<string> m_localTCPSockets = new List<string>(); /// <summary> /// Maintains a list of all current TCP connections currently connected to/from this channel. This allows the SIP transport /// layer to quickly find a channel where the same connection must be re-used. /// </summary> private ConcurrentDictionary<string, SIPStreamConnection> m_connections = new ConcurrentDictionary<string, SIPStreamConnection>(); private CancellationTokenSource m_cts = new CancellationTokenSource(); /// <summary> /// Creates a SIP channel to listen for and send SIP messages over TCP. /// </summary> /// <param name="endPoint">The IP end point to listen on and send from.</param> /// <param name="protocol">Whether the channel is being used with TCP or TLS (TLS channels get upgraded once connected).</param> public SIPTCPChannel(IPEndPoint endPoint, SIPProtocolsEnum protocol) : base() { if (endPoint == null) { throw new ArgumentNullException("endPoint", "The end point must be specified when creating a SIPTCPChannel."); } ListeningIPAddress = endPoint.Address; Port = endPoint.Port; SIPProtocol = protocol; IsReliable = true; Initialise(endPoint); } public SIPTCPChannel(IPEndPoint endPoint) : this(endPoint, SIPProtocolsEnum.tcp) { } public SIPTCPChannel(IPAddress listenAddress, int listenPort) : this(new IPEndPoint(listenAddress, listenPort), SIPProtocolsEnum.tcp) { } /// <summary> /// Initialises the SIP channel's socket listener. /// </summary> private void Initialise(IPEndPoint listenEndPoint) { try { m_tcpServerListener = new TcpListener(listenEndPoint); m_tcpServerListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); m_tcpServerListener.Server.LingerState = new LingerOption(true, 0); if (listenEndPoint.AddressFamily == AddressFamily.InterNetworkV6) { m_tcpServerListener.Server.DualMode = true; } m_tcpServerListener.Start(MAX_TCP_CONNECTIONS); if (listenEndPoint.Port == 0) { Port = (m_tcpServerListener.Server.LocalEndPoint as IPEndPoint).Port; } m_localTCPSockets.Add(ListeningEndPoint.ToString()); Task.Run(AcceptConnections); Task.Run(PruneConnections); logger.LogInformation($"SIP {ProtDescr} Channel created for {ListeningEndPoint}."); } catch (Exception excp) { logger.LogError("Exception SIPTCPChannel Initialise. " + excp.Message); throw excp; } } /// <summary> /// Processes the socket accepts from the channel's socket listener. /// </summary> private async Task AcceptConnections() { logger.LogDebug($"SIP {ProtDescr} Channel socket on {m_tcpServerListener.Server.LocalEndPoint} accept connections thread started."); while (!Closed) { try { Socket clientSocket = await m_tcpServerListener.AcceptSocketAsync(); if (!Closed) { logger.LogDebug($"SIP {ProtDescr} Channel connection accepted from {clientSocket.RemoteEndPoint} by {clientSocket.LocalEndPoint}."); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); clientSocket.LingerState = new LingerOption(true, 0); SIPStreamConnection sipStmConn = new SIPStreamConnection(clientSocket, clientSocket.RemoteEndPoint as IPEndPoint, SIPProtocol); sipStmConn.SIPMessageReceived += SIPTCPMessageReceived; m_connections.TryAdd(sipStmConn.ConnectionID, sipStmConn); await OnAccept(sipStmConn); } } catch (ObjectDisposedException) { // This is a result of the transport channel being closed. Safe to ignore. logger.LogDebug($"SIP {ProtDescr} Channel accepts for {ListeningEndPoint} cancelled."); } catch (SocketException acceptSockExcp) when (acceptSockExcp.SocketErrorCode == SocketError.Interrupted) { // This is a result of the transport channel being closed and WSACancelBlockingCall being called in WinSock2. Safe to ignore. logger.LogDebug($"SIP {ProtDescr} Channel accepts for {ListeningEndPoint} cancelled."); } catch (Exception acceptExcp) { // This exception gets thrown if the remote end disconnects during the socket accept. logger.LogWarning($"Exception SIP {ProtDescr} Channel accepting socket (" + acceptExcp.GetType() + "). " + acceptExcp.Message); } } } /// <summary> /// For TCP channel no special action is required when accepting a new client connection. Can start receiving immediately. /// </summary> /// <param name="streamConnection">The stream connection holding the newly accepted client socket.</param> protected virtual Task OnAccept(SIPStreamConnection streamConnection) { SocketAsyncEventArgs args = streamConnection.RecvSocketArgs; args.AcceptSocket = streamConnection.StreamSocket; args.UserToken = streamConnection; args.Completed += IO_Completed; bool willRaise = streamConnection.StreamSocket.ReceiveAsync(args); if (!willRaise) { ProcessReceive(args); } return Task.FromResult(0); } /// <summary> /// Event handler for the socket newer SendAsync and ReceiveAsync socket calls. /// </summary> /// <param name="sender">The socket that the IO event occurred on.</param> /// <param name="e">The socket args for the completed IO operation.</param> private void IO_Completed(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; case SocketAsyncOperation.Disconnect: var sipStreamConn = m_connections.Where(x => x.Value.RemoteEndPoint.Equals(e.RemoteEndPoint as IPEndPoint)).FirstOrDefault().Value; OnSIPStreamDisconnected(sipStreamConn, e.SocketError); break; default: throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } /// <summary> /// Receive event handler for the newer ReceiveAsync socket call. /// </summary> /// <param name="e">The socket args for the completed receive operation.</param> private void ProcessReceive(SocketAsyncEventArgs e) { SIPStreamConnection streamConn = (SIPStreamConnection)e.UserToken; try { if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { byte[] buffer = streamConn.RecvSocketArgs.Buffer; streamConn.ExtractSIPMessages(this, buffer, e.BytesTransferred); streamConn.RecvSocketArgs.SetBuffer(buffer, streamConn.RecvEndPosn, buffer.Length - streamConn.RecvEndPosn); bool willRaiseEvent = streamConn.StreamSocket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { OnSIPStreamDisconnected(streamConn, e.SocketError); } } catch (SocketException sockExcp) { OnSIPStreamDisconnected(streamConn, sockExcp.SocketErrorCode); } catch (Exception excp) { // There was an error processing the last message received. Remove the disconnected socket. logger.LogError($"Exception processing SIP {ProtDescr} stream receive on read from {e.RemoteEndPoint} closing connection. {excp.Message}"); OnSIPStreamDisconnected(streamConn, SocketError.Fault); } } /// <summary> /// Send event handler for the newer SendAsync socket call. /// </summary> /// <param name="e">The socket args for the completed send operation.</param> private void ProcessSend(SocketAsyncEventArgs e) { SIPStreamConnection streamConn = (SIPStreamConnection)e.UserToken; if (e.BytesTransferred == 0 || e.SocketError != SocketError.Success) { // There was an error processing the last message send. Remove the disconnected socket. logger.LogWarning($"SIP {ProtDescr} Channel Socket send to {e.RemoteEndPoint} failed with socket error {e.SocketError}, removing connection."); OnSIPStreamDisconnected(streamConn, e.SocketError); } } /// <summary> /// Attempts to create a client TCP socket connection to a remote end point. /// </summary> /// <param name="dstEndPoint">The remote TCP end point to attempt to connect to.</param> /// <param name="buffer">An optional buffer that if set can contain data to transmit immediately after connecting.</param> /// <returns>If successful a connected client socket or null if not.</returns> internal async Task<SocketError> ConnectClientAsync(IPEndPoint dstEndPoint, byte[] buffer, string serverCertificateName) { try { // No existing TCP connection to the destination. Attempt a new socket connection. IPAddress localAddress = ListeningIPAddress; if (ListeningIPAddress == IPAddress.Any) { localAddress = NetServices.GetLocalAddressForRemote(dstEndPoint.Address); } IPEndPoint localEndPoint = new IPEndPoint(localAddress, Port); logger.LogDebug($"ConnectAsync SIP {ProtDescr} Channel local end point of {localEndPoint} selected for connection to {dstEndPoint}."); Socket clientSocket = new Socket(dstEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); clientSocket.LingerState = new LingerOption(true, 0); clientSocket.Bind(localEndPoint); SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs { RemoteEndPoint = dstEndPoint }; // NOTE: The approach of setting the buffer on the connect args worked properly on Windows BUT // not so on Linux. Since it's such a tiny saving skip setting the buffer on the connect and // do the send once the sockets are connected (use SendOnConnected). // If this is a TCP channel can take a shortcut and set the first send payload on the connect args. //if (buffer != null && buffer.Length > 0 && serverCertificateName == null) //{ // connectArgs.SetBuffer(buffer, 0, buffer.Length); //} logger.LogDebug($"Attempting TCP connection from {localEndPoint} to {dstEndPoint}."); // Attempt to connect. TaskCompletionSource<SocketError> connectTcs = new TaskCompletionSource<SocketError>(); connectArgs.Completed += (sender, sockArgs) => { if (sockArgs.LastOperation == SocketAsyncOperation.Connect) { connectTcs.SetResult(sockArgs.SocketError); } }; bool willRaiseEvent = clientSocket.ConnectAsync(connectArgs); if (!willRaiseEvent) { if (connectArgs.LastOperation == SocketAsyncOperation.Connect) { connectTcs.SetResult(connectArgs.SocketError); } } var connectResult = await connectTcs.Task; logger.LogDebug($"ConnectAsync SIP {ProtDescr} Channel connect completed result for {localEndPoint}->{dstEndPoint} {connectResult}."); if (connectResult != SocketError.Success) { logger.LogWarning($"SIP {ProtDescr} Channel send to {dstEndPoint} failed. Attempt to create a client socket failed."); } else { SIPStreamConnection sipStmConn = new SIPStreamConnection(clientSocket, clientSocket.RemoteEndPoint as IPEndPoint, SIPProtocol); sipStmConn.SIPMessageReceived += SIPTCPMessageReceived; m_connections.TryAdd(sipStmConn.ConnectionID, sipStmConn); await OnClientConnect(sipStmConn, serverCertificateName); await SendOnConnected(sipStmConn, buffer); } return connectResult; } catch (Exception excp) { logger.LogError($"Exception ConnectClientAsync. {excp.Message}"); return SocketError.Fault; } } /// <summary> /// For TCP channel no special action is required when a new outgoing client connection is established. /// Can start receiving immediately. /// </summary> /// <param name="streamConnection">The stream connection holding the newly connected client socket.</param> protected virtual Task OnClientConnect(SIPStreamConnection streamConnection, string certificateName) { SocketAsyncEventArgs recvArgs = streamConnection.RecvSocketArgs; recvArgs.AcceptSocket = streamConnection.StreamSocket; recvArgs.UserToken = streamConnection; recvArgs.Completed += IO_Completed; bool willRaise = streamConnection.StreamSocket.ReceiveAsync(recvArgs); if (!willRaise) { ProcessReceive(recvArgs); } // Task.IsCompleted not available for net452. return Task.FromResult(0); } public override Task<SocketError> SendAsync(SIPEndPoint dstEndPoint, byte[] buffer, string connectionIDHint) { return SendSecureAsync(dstEndPoint, buffer, null, connectionIDHint); } /// <summary> /// Attempts to send data to the remote end point over a reliable connection. If an existing /// connection exists it will be used otherwise an attempt will be made to establish a new connection. /// </summary> /// <param name="dstSIPEndPoint">The remote SIP end point to send the reliable data to.</param> /// <param name="buffer">The data to send.</param> /// <param name="serverCertificateName">Optional. Only relevant for SSL streams. The common name /// that is expected for the remote SSL server.</param> /// <param name="connectionIDHint">Optional. The ID of the specific TCP connection to try and the send the message on.</param> /// <returns>If no errors SocketError.Success otherwise an error value.</returns> public override Task<SocketError> SendSecureAsync(SIPEndPoint dstSIPEndPoint, byte[] buffer, string serverCertificateName, string connectionIDHint) { try { IPEndPoint dstEndPoint = dstSIPEndPoint?.GetIPEndPoint(); if (dstEndPoint == null) { throw new ArgumentException("dstEndPoint", "An empty destination was specified to Send in SIPTCPChannel."); } if (buffer == null || buffer.Length == 0) { throw new ApplicationException("An empty buffer was specified to Send in SIPTCPChannel."); } else if (DisableLocalTCPSocketsCheck == false && m_localTCPSockets.Contains(dstEndPoint.ToString())) { logger.LogWarning($"SIP {ProtDescr} Channel blocked Send to {dstEndPoint} as it was identified as a locally hosted {ProtDescr} socket.\r\n" + Encoding.UTF8.GetString(buffer)); throw new ApplicationException($"A Send call was blocked in SIP {ProtDescr} Channel due to the destination being another local TCP socket."); } else { // Lookup a client socket that is connected to the destination. If it does not exist attempt to connect a new one. SIPStreamConnection sipStreamConn = null; if (connectionIDHint != null) { m_connections.TryGetValue(connectionIDHint, out sipStreamConn); } if (sipStreamConn == null && HasConnection(dstSIPEndPoint)) { sipStreamConn = m_connections.Where(x => x.Value.RemoteEndPoint.Equals(dstEndPoint)).First().Value; } if (sipStreamConn != null) { SendOnConnected(sipStreamConn, buffer); return Task.FromResult(SocketError.Success); } else { return ConnectClientAsync(dstEndPoint, buffer, serverCertificateName); } } } catch (SocketException sockExcp) { return Task.FromResult(sockExcp.SocketErrorCode); } catch (ApplicationException) { throw; } catch (Exception excp) { logger.LogError($"Exception SIPTCPChannel Send (sendto=> {dstSIPEndPoint}. {excp.Message}"); throw; } } /// <summary> /// Sends data once the stream is connected. /// Can be overridden in sub classes that need to implement a different mechanism to send. For example SSL connections. /// </summary> /// <param name="sipStreamConn">The connected SIP stream wrapping the TCP connection.</param> /// <param name="buffer">The data to send.</param> protected virtual Task SendOnConnected(SIPStreamConnection sipStreamConn, byte[] buffer) { IPEndPoint dstEndPoint = sipStreamConn.RemoteEndPoint; try { lock (sipStreamConn.StreamSocket) { sipStreamConn.LastTransmission = DateTime.Now; var args = new SocketAsyncEventArgs(); args.UserToken = sipStreamConn; args.SetBuffer(buffer, 0, buffer.Length); args.Completed += IO_Completed; if (!sipStreamConn.StreamSocket.SendAsync(args)) { ProcessSend(args); } } return Task.FromResult(0); } catch (SocketException sockExcp) { logger.LogWarning($"SocketException SIP {ProtDescr} Channel SendOnConnected {dstEndPoint}. ErrorCode {sockExcp.SocketErrorCode}. {sockExcp}"); OnSIPStreamDisconnected(sipStreamConn, sockExcp.SocketErrorCode); throw; } } /// <summary> /// Event handler for a reliable SIP stream socket being disconnected. /// </summary> /// <param name="connection">The disconnected stream.</param> /// <param name="socketError">The cause of the disconnect.</param> protected void OnSIPStreamDisconnected(SIPStreamConnection connection, SocketError socketError) { try { if (connection != null) { logger.LogWarning($"SIP {ProtDescr} stream disconnected {connection.RemoteEndPoint} {socketError}."); if (m_connections.TryRemove(connection.ConnectionID, out _)) { var socket = connection.StreamSocket; // Important: Due to the way TCP works the end of the connection that initiates the close // is meant to go into a TIME_WAIT state. On Windows that results in the same pair of sockets // being unable to reconnect for 30s. SIP can deal with stray and duplicate messages at the // application layer so the TIME_WAIT is not that useful. In fact it TIME_WAIT is a major annoyance for SIP // as if a connection is dropped for whatever reason, such as a parser error or inactivity, it will // prevent the connection being re-established for the TIME_WAIT period. // // For this reason this implementation uses a hard RST close for client initiated socket closes. This // results in a TCP RST packet instead of the graceful FIN-ACK sequence. Two things are necessary with // WinSock2 to force the hard RST: // // - the Linger option must be set on the raw socket before binding as Linger option {1, 0}. // - the close method must be called on the socket without shutting down the stream. // Linux (WSL) note: This mechanism does not work. Calling socket close does not send the RST and instead // sends the graceful FIN-ACK. // TODO: Research if there is a way to force a socket reset with dotnet on LINUX. socket.Close(); } } } catch (Exception excp) { logger.LogError("Exception OnSIPStreamDisconnected. " + excp.Message); } } /// <summary> /// Gets fired when a suspected SIP message is extracted from the TCP data stream. /// </summary> protected Task SIPTCPMessageReceived(SIPChannel channel, SIPEndPoint localEndPoint, SIPEndPoint remoteEndPoint, byte[] buffer) { return SIPMessageReceived?.Invoke(channel, localEndPoint, remoteEndPoint, buffer); } /// <summary> /// Checks whether the SIP channel has a connection matching a unique connection ID. /// </summary> /// <param name="connectionID">The connection ID to check for a match on.</param> /// <returns>True if a match is found or false if not.</returns> public override bool HasConnection(string connectionID) { return m_connections.ContainsKey(connectionID); } /// <summary> /// Checks whether there is an existing connection for a remote end point. Existing connections include /// connections that have been accepted by this channel's listener and connections that have been initiated /// due to sends from this channel. /// </summary> /// <param name="remoteEndPoint">The remote end point to check for an existing connection.</param> /// <returns>True if there is a connection or false if not.</returns> public override bool HasConnection(SIPEndPoint remoteEndPoint) { return m_connections.Any(x => x.Value.RemoteEndPoint.Equals(remoteEndPoint.GetIPEndPoint())); } /// <summary> /// Not implemented for the TCP channel. /// </summary> public override bool HasConnection(Uri serverUri) { throw new NotImplementedException("This HasConnection method is not available in the SIP TCP channel, please use an alternative overload."); } /// <summary> /// Checks whether the specified address family is supported. /// </summary> /// <param name="addresFamily">The address family to check.</param> /// <returns>True if supported, false if not.</returns> public override bool IsAddressFamilySupported(AddressFamily addresFamily) { return addresFamily == ListeningIPAddress.AddressFamily; } /// <summary> /// Checks whether the specified protocol is supported. /// </summary> /// <param name="protocol">The protocol to check.</param> /// <returns>True if supported, false if not.</returns> public override bool IsProtocolSupported(SIPProtocolsEnum protocol) { return protocol == SIPProtocolsEnum.tcp; } /// <summary> /// Closes the channel and any open sockets. /// </summary> public override void Close() { if (!Closed == true) { logger.LogDebug($"Closing SIP {ProtDescr} Channel {ListeningEndPoint}."); Closed = true; m_cts.Cancel(); lock (m_connections) { foreach (SIPStreamConnection streamConnection in m_connections.Values) { try { // See explanation in OnSIPStreamSocketDisconnected on why the close is done on the socket and NOT the stream. streamConnection.StreamSocket?.Close(); } catch (Exception closeExcp) { logger.LogError($"Exception closing SIP connection on {ProtDescr}. {closeExcp.Message}"); } } m_connections.Clear(); } // If it's an outbound only channel there will be no listener. if (m_tcpServerListener != null) { try { logger.LogDebug($"Stopping SIP {ProtDescr} Channel listener {ListeningEndPoint}."); m_tcpServerListener.Stop(); } catch (Exception stopExcp) { logger.LogError($"Exception SIP {ProtDescr} Channel Close (shutting down listener). {stopExcp.Message}"); } } logger.LogDebug($"Successfully closed SIP {ProtDescr} Channel for {ListeningEndPoint}."); } } public override void Dispose() { this.Close(); } /// <summary> /// Periodically checks the established connections and closes any that have not had a transmission for a specified /// period or where the number of connections allowed per IP address has been exceeded. /// </summary> private async Task PruneConnections() { try { await Task.Delay(PRUNE_CONNECTIONS_INTERVAL, m_cts.Token); while (!Closed) { bool checkComplete = false; while (!checkComplete) { try { SIPStreamConnection inactiveConnection = null; lock (m_connections) { var inactiveConnectionKey = (from connection in m_connections where connection.Value.LastTransmission < DateTime.Now.AddMinutes(PRUNE_NOTRANSMISSION_MINUTES * -1) select connection.Key).FirstOrDefault(); if (inactiveConnectionKey != null) { inactiveConnection = m_connections[inactiveConnectionKey]; m_connections.TryRemove(inactiveConnectionKey, out _); } } if (inactiveConnection != null) { logger.LogDebug($"Pruning inactive connection on {ProtDescr} {ListeningEndPoint} to remote end point {inactiveConnection.RemoteEndPoint}."); inactiveConnection.StreamSocket.Close(); } else { checkComplete = true; } } catch (SocketException sockExcp) { // Will be thrown if the socket is already closed. logger.LogWarning($"Socket error in PruneConnections. {sockExcp.Message} ({sockExcp.ErrorCode})."); } catch (Exception pruneExcp) { logger.LogError("Exception PruneConnections (pruning). " + pruneExcp.Message); checkComplete = true; } } await Task.Delay(PRUNE_CONNECTIONS_INTERVAL, m_cts.Token); checkComplete = false; } logger.LogDebug($"SIP {ProtDescr} Channel socket on {ListeningEndPoint} pruning connections halted."); } catch (OperationCanceledException) { } catch (Exception excp) { logger.LogError($"Exception SIP {ProtDescr} Channel PruneConnections. " + excp.Message); } } } }
48.348806
196
0.566013
[ "BSD-3-Clause" ]
bleissem/sipsorcery
src/core/SIP/Channels/SIPTCPChannel.cs
36,455
C#
using Neo.IO; using System; using System.Collections.Generic; using static Neo.Helper; namespace Neo.Cryptography.MPT { partial class MPTTrie<TKey, TValue> { public bool Delete(TKey key) { var path = ToNibbles(key.ToArray()); if (path.Length == 0) return false; return TryDelete(ref root, path); } private bool TryDelete(ref MPTNode node, ReadOnlySpan<byte> path) { switch (node) { case LeafNode _: { if (path.IsEmpty) { node = HashNode.EmptyNode; return true; } return false; } case ExtensionNode extensionNode: { if (path.StartsWith(extensionNode.Key)) { var result = TryDelete(ref extensionNode.Next, path[extensionNode.Key.Length..]); if (!result) return false; if (extensionNode.Next is HashNode hashNode && hashNode.IsEmpty) { node = extensionNode.Next; return true; } if (extensionNode.Next is ExtensionNode sn) { extensionNode.Key = Concat(extensionNode.Key, sn.Key); extensionNode.Next = sn.Next; } extensionNode.SetDirty(); PutToStore(extensionNode); return true; } return false; } case BranchNode branchNode: { bool result; if (path.IsEmpty) { result = TryDelete(ref branchNode.Children[BranchNode.ChildCount - 1], path); } else { result = TryDelete(ref branchNode.Children[path[0]], path[1..]); } if (!result) return false; List<byte> childrenIndexes = new List<byte>(BranchNode.ChildCount); for (int i = 0; i < BranchNode.ChildCount; i++) { if (branchNode.Children[i] is HashNode hn && hn.IsEmpty) continue; childrenIndexes.Add((byte)i); } if (childrenIndexes.Count > 1) { branchNode.SetDirty(); PutToStore(branchNode); return true; } var lastChildIndex = childrenIndexes[0]; var lastChild = branchNode.Children[lastChildIndex]; if (lastChildIndex == BranchNode.ChildCount - 1) { node = lastChild; return true; } if (lastChild is HashNode hashNode) { lastChild = Resolve(hashNode); if (lastChild is null) return false; } if (lastChild is ExtensionNode exNode) { exNode.Key = Concat(childrenIndexes.ToArray(), exNode.Key); exNode.SetDirty(); PutToStore(exNode); node = exNode; return true; } node = new ExtensionNode() { Key = childrenIndexes.ToArray(), Next = lastChild, }; PutToStore(node); return true; } case HashNode hashNode: { if (hashNode.IsEmpty) { return true; } var newNode = Resolve(hashNode); if (newNode is null) return false; node = newNode; return TryDelete(ref node, path); } default: return false; } } } }
40.14876
109
0.35776
[ "MIT" ]
Lichen9618/neo
src/neo/Cryptography/MPT/MPTTrie.Delete.cs
4,858
C#
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleOanda.SampleOandaPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleOanda { using System; using System.Collections.Generic; using System.ComponentModel; using System.Security; using System.Windows; using Ecng.Common; using Ecng.Xaml; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.Oanda; using StockSharp.Localization; public partial class MainWindow { private bool _isConnected; public OandaTrader Trader; private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly TradesWindow _tradesWindow = new TradesWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); public MainWindow() { InitializeComponent(); Title = Title.Put("OANDA"); _ordersWindow.MakeHideable(); _myTradesWindow.MakeHideable(); _tradesWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); Instance = this; } protected override void OnClosing(CancelEventArgs e) { _ordersWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _tradesWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _securitiesWindow.Close(); _tradesWindow.Close(); _myTradesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); if (Trader != null) Trader.Dispose(); base.OnClosing(e); } public static MainWindow Instance { get; private set; } private void ConnectClick(object sender, RoutedEventArgs e) { if (!_isConnected) { if (Token.Password.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3836); return; } if (Trader == null) { // create connector Trader = new OandaTrader(); Trader.Restored += () => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(true); MessageBox.Show(this, LocalizedStrings.Str2958); }); // subscribe on connection successfully event Trader.Connected += () => { // set flag (connection is established) _isConnected = true; // update gui labes this.GuiAsync(() => ChangeConnectStatus(true)); }; Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false)); // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { // update gui labes ChangeConnectStatus(false); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, msg) => this.GuiAsync(() => MessageBox.Show(this, msg.Error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; Trader.MassOrderCancelFailed += (transId, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716)); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowMyTrades.IsEnabled = ShowOrders.IsEnabled = ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true; } Trader.Token = Token.Password.To<SecureString>(); Trader.Server = IsDemo.IsChecked == true ? OandaServers.Practice : OandaServers.Real; // clear password box for security reason //Token.Clear(); Trader.Connect(); } else { Trader.Disconnect(); } } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153); }); } private void ChangeConnectStatus(bool isConnected) { _isConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_tradesWindow); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } } }
29.382716
131
0.69958
[ "Apache-2.0" ]
cuihantao/StockSharp
Samples/Oanda/SampleOanda/MainWindow.xaml.cs
7,140
C#
namespace GuruComponents.Netrix.Designer { /// <summary> /// TODO: Add Comments. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void DirectiveEventHandler(object sender, DirectiveEventArgs e); }
26.6
84
0.642857
[ "MIT" ]
andydunkel/netrix
Netrix2.0/Core/Designer/DirectiveEventHandler.cs
266
C#
using System.Collections.Concurrent; using System.Collections.Generic; using Unianio.Enums; using Unianio.Extensions; using Unianio.IK; using UnityEngine; namespace Unianio.Genesis.State { public class HumanInitialStats { public HumanInitialStats(IComplexHuman h) { if (h.IsGenesis8()) { var mouth = h.GetAbsMouthPosition(); LowerNeckToMouthRelVec = (mouth - h.Spine.Handle.position).AsLocalVec(h.Spine.NeckLower); PelvisToMouthDistance = h.Pelvis.position.DistanceTo(mouth); } FootHeight = h.LegL.Foot.position.y - h.position.y; PelvisHeight = h.Pelvis.position.y - h.position.y; HipHeight = h.Hip.position.y - h.position.y; ShoulderHeight = h.ArmL.Shoulder.position.y - h.position.y; RelaxedArmHeight = (ShoulderHeight - h.ArmL.MaxStretch); ModelVecHipToSpine = (h.Spine.position - h.Hip.position).AsLocalVec(h.Model); LocPosHead = h.Head.Holder.localPosition; LocRotHead = h.Head.Holder.localRotation; if (h.IsGenesis8()) { LocPosJaw = h.GenFace.LowerJaw.Holder.localPosition; LocRotJaw = h.GenFace.LowerJaw.Holder.localRotation; } else if (h.IsMakeHuman()) { LocPosJaw = h.MHFace.Jaw.Holder.localPosition; LocRotJaw = h.MHFace.Jaw.Holder.localRotation; } ModelPosArmL = h.ArmL.Control.position.AsLocalPoint(h.Model); ModelPosArmR = h.ArmR.Control.position.AsLocalPoint(h.Model); LocalPosArmL = h.ArmL.Control.localPosition; LocalPosArmR = h.ArmR.Control.localPosition; LocRotArmL = h.ArmL.Control.localRotation; LocRotArmR = h.ArmR.Control.localRotation; Fingers[BodySide.Left] = new Dictionary<FingerName, IDictionary<int, PosRot>>() { { FingerName.Thumb, new Dictionary<int, PosRot>() }, { FingerName.Index, new Dictionary<int, PosRot>() }, { FingerName.Middle, new Dictionary<int, PosRot>() }, { FingerName.Ring, new Dictionary<int, PosRot>() }, { FingerName.Pinky, new Dictionary<int, PosRot>() } }; Fingers[BodySide.Right] = new Dictionary<FingerName, IDictionary<int, PosRot>>() { { FingerName.Thumb, new Dictionary<int, PosRot>() }, { FingerName.Index, new Dictionary<int, PosRot>() }, { FingerName.Middle, new Dictionary<int, PosRot>() }, { FingerName.Ring, new Dictionary<int, PosRot>() }, { FingerName.Pinky, new Dictionary<int, PosRot>() } }; foreach (var side in new[]{ BodySide.Left, BodySide.Right}) { var a = side == BodySide.Left ? h.ArmL : h.ArmR; Fingers[side][FingerName.Thumb] = new Dictionary<int, PosRot> { { 0, new PosRot(a.Thumb1.localPosition, a.Thumb1.localRotation) }, { 1, new PosRot(a.Thumb1.localPosition, a.Thumb1.localRotation) }, { 2, new PosRot(a.Thumb2.localPosition, a.Thumb2.localRotation) }, { 3, new PosRot(a.Thumb3.localPosition, a.Thumb3.localRotation) } }; Fingers[side][FingerName.Index] = new Dictionary<int, PosRot> { { 0, new PosRot(a.Index0.localPosition, a.Index0.localRotation) }, { 1, new PosRot(a.Index1.localPosition, a.Index1.localRotation) }, { 2, new PosRot(a.Index2.localPosition, a.Index2.localRotation) }, { 3, new PosRot(a.Index3.localPosition, a.Index3.localRotation) } }; Fingers[side][FingerName.Middle] = new Dictionary<int, PosRot> { { 0, new PosRot(a.Middle0.localPosition, a.Middle0.localRotation) }, { 1, new PosRot(a.Middle1.localPosition, a.Middle1.localRotation) }, { 2, new PosRot(a.Middle2.localPosition, a.Middle2.localRotation) }, { 3, new PosRot(a.Middle3.localPosition, a.Middle3.localRotation) } }; Fingers[side][FingerName.Ring] = new Dictionary<int, PosRot> { { 0, new PosRot(a.Ring0.localPosition, a.Ring0.localRotation) }, { 1, new PosRot(a.Ring1.localPosition, a.Ring1.localRotation) }, { 2, new PosRot(a.Ring2.localPosition, a.Ring2.localRotation) }, { 3, new PosRot(a.Ring3.localPosition, a.Ring3.localRotation) } }; Fingers[side][FingerName.Pinky] = new Dictionary<int, PosRot> { { 0, new PosRot(a.Pinky0.localPosition, a.Pinky0.localRotation) }, { 1, new PosRot(a.Pinky1.localPosition, a.Pinky1.localRotation) }, { 2, new PosRot(a.Pinky2.localPosition, a.Pinky2.localRotation) }, { 3, new PosRot(a.Pinky3.localPosition, a.Pinky3.localRotation) } }; } } public readonly IDictionary<BodySide, IDictionary<FingerName, IDictionary<int, PosRot>>> Fingers = new Dictionary<BodySide, IDictionary<FingerName, IDictionary<int, PosRot>>>(); public readonly float PelvisToMouthDistance, FootHeight, PelvisHeight, HipHeight, ShoulderHeight, RelaxedArmHeight; public readonly Vector3 LowerNeckToMouthRelVec, LocPosHead, LocPosJaw, ModelPosArmL, ModelPosArmR, LocalPosArmL, LocalPosArmR, ModelVecHipToSpine; public readonly Quaternion LocRotHead, LocRotJaw, LocRotArmL, LocRotArmR; } }
50.452991
154
0.57547
[ "MIT" ]
vbodurov/unianio-framework
Unianio_Framework_Project/Assets/Unianio_Framework/Unianio/Genesis/State/HumanInitialStats.cs
5,905
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Newtonsoft.Json; using NExpect; using NUnit.Framework; using PeanutButter.RandomGenerators; using PeanutButter.TestUtils.Generic; using static PeanutButter.RandomGenerators.RandomValueGen; using static NExpect.Expectations; // ReSharper disable InconsistentNaming // ReSharper disable UnusedMethodReturnValue.Global // ReSharper disable MemberHidesStaticFromOuterClass // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable ClassNeverInstantiated.Global namespace PeanutButter.Utils.Tests { [TestFixture] public class TestDeepEqualityTester { [TestFixture] public class AreDeepEqual { // mostly this class is tested through the DeepEquals() // extension method testing. However, I'd like to allow // for a slower operation where discrepencies are recorded [Test] public void GivenTwoEqualPrimitives_ShouldNotPopulateErrors() { //--------------- Arrange ------------------- var sut = Create(1, 1); //--------------- Assume ---------------- Expect(sut.Errors).To.Be.Empty(); //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.True(); //--------------- Assert ----------------------- Expect(sut.Errors).To.Be.Empty(); } [Test] public void GivenTwoDifferentPrimitives_ShouldSetExpectedError() { //--------------- Arrange ------------------- var sut = Create(true, false); //--------------- Assume ---------------- //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.False(); //--------------- Assert ----------------------- Expect(sut.Errors).To.Contain("Primitive values differ"); } [Test] public void GivenDifferingComplexObjectsWithOnePropertyOfSameNameAndValue_ShouldRecordError() { //--------------- Arrange ------------------- var item1 = new {foo = 1}; var item2 = new {foo = 2}; var sut = Create(item1, item2); //--------------- Assume ---------------- //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.False(); //--------------- Assert ----------------------- var error = sut.Errors.Last(); Expect(error).To.Contain("foo"); Expect(error).To.Contain("1"); Expect(error).To.Contain("2"); } [Test] public void WhenBothItemsHaveCollections_ShouldCompareThem_Positive() { //--------------- Arrange ------------------- var item1 = new { Subs = new[] {1, 2,} }; var item2 = new ThingWithCollection() { Subs = new[] {1, 2} }; var sut = Create(item1, item2); //--------------- Assume ---------------- //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.True(); //--------------- Assert ----------------------- } [Test] public void WhenBothItemsHaveCollections_ShouldCompareThem_WithoutCaringAboutOrder() { //--------------- Arrange ------------------- var item1 = new ThingWithCollection() { Subs = new[] {2, 1,} }; var item2 = new { Subs = new[] {1, 2} }; var sut = Create(item1, item2); //--------------- Assume ---------------- //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.True(); //--------------- Assert ----------------------- } [Test] public void WhenBothItemsHaveCollections_ShouldCompareThem_Negative() { //--------------- Arrange ------------------- var item1 = new ThingWithCollection() { Subs = new[] {1, 2, 3} }; var item2 = new ThingWithCollection() { Subs = new[] {1, 2} }; var sut = Create(item1, item2); //--------------- Assume ---------------- //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.False(); //--------------- Assert ----------------------- } [Test] public void WhenBothItemsHaveCollections_ButOneIsNull_ShouldNotBarf() { //--------------- Arrange ------------------- var item1 = new ThingWithCollection() { Subs = new[] {1, 2, 3} }; var item2 = new ThingWithCollection(); var sut = Create(item1, item2); //--------------- Assume ---------------- Expect(item2.Subs).To.Be.Null(); //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.False(); //--------------- Assert ----------------------- } [Test] public void WhenBothItemsHaveCollections_ButOneIsNull_ShouldNotBarfReversed() { //--------------- Arrange ------------------- var item1 = new ThingWithCollection(); var item2 = new ThingWithCollection() { Subs = new[] {1, 2, 3} }; var sut = Create(item1, item2); //--------------- Assume ---------------- Expect(item1.Subs).To.Be.Null(); //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.False(); //--------------- Assert ----------------------- } [Test] public void WhenBothItemsHaveCollections_ButBothAreNull_ShouldBehaveAccordingly() { //--------------- Arrange ------------------- var item1 = new ThingWithCollection(); var item2 = new ThingWithCollection(); var sut = Create(item1, item2); //--------------- Assume ---------------- Expect(item1.Subs).To.Be.Null(); Expect(item2.Subs).To.Be.Null(); //--------------- Act ---------------------- Expect(sut.AreDeepEqual()).To.Be.True(); //--------------- Assert ----------------------- } [TestFixture] public class WithOnlyCompareShapeTrue { [TestFixture] public class DeepSubEquals { [Test] public void GivenObjectWithMoreThanOther() { // Arrange var left = new { Id = 2 }; var right = new { Id = 1, Name = "Moo" }; var sut = Create(left, right); sut.FailOnMissingProperties = false; sut.OnlyCompareShape = true; // Pre-Assert // Act Expect(sut.AreDeepEqual()).To.Be.True(sut.PrintErrors()); // Assert } public class OurVersion { public int Major { get; set; } public int Minor { get; set; } } public class TheirVersion { public int Major { get; set; } public int Minor { get; set; } } public class OurObject { public OurVersion Version { get; set; } } public class TheirObject { public TheirVersion Version { get; set; } } [Test] public void GivenObjectsWithDifferentTypedButSameShapedProps() { // Arrange var mine = GetRandom<OurObject>(); var theirs = GetRandom<TheirObject>(); var tester = new DeepEqualityTester(mine, theirs) { OnlyCompareShape = true, RecordErrors = true }; // Pre-Assert // Act var result = tester.AreDeepEqual(); // Assert Expect(result) .To.Be.True( tester.Errors.JoinWith("\n") ); } public class OurSemVer { public int Major { get; set; } public int Minor { get; set; } public int Patch { get; set; } } public class OurObjectWithSemVer { public Guid Id { get; set; } public OurSemVer Version { get; set; } } [Test] public void GivenObjectsWithDifferentTypedButSameSubShapedProps() { // Arrange var mine = GetRandom<OurObjectWithSemVer>(); var theirs = GetRandom<TheirObject>(); var tester = new DeepEqualityTester(mine, theirs) { OnlyCompareShape = true, FailOnMissingProperties = false, RecordErrors = true }; // Pre-Assert // Act var result = tester.AreDeepEqual(); // Assert Expect(result) .To.Be.True( tester.Errors.AsText() ); } public class LeVersion { public int LeMajor { get; set; } public int LeMinor { get; set; } } public class TheirFrenchObject { public LeVersion Version { get; set; } } [Test] public void GivenObjectsWithDifferentSubShapes_WhenAllowMissingProperties_ButNoMatchedProperties_ShouldThrow() { // Arrange var ours = GetRandom<OurObject>(); var theirs = GetRandom<TheirFrenchObject>(); var tester = new DeepEqualityTester(ours, theirs) { FailOnMissingProperties = false, RecordErrors = true, OnlyCompareShape = true }; // Pre-Assert // Act var result = tester.AreDeepEqual(); // Assert Expect(result).To.Be.False(); Console.WriteLine(tester.Errors.AsText()); } } [TestFixture] public class DeepEquals { [Test] public void GivenTwoObjectsOfSameType() { // Arrange var sut = Create(GetRandomString(), GetRandomString()); sut.OnlyCompareShape = true; // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void GivenTwoObjectsOfSameShape_DifferentType() { // Arrange var left = new { Foo = new { id = 1, Name = "bob", When = DateTime.Now }, Stuffs = new[] { new { Id = 2, Name = "Billy" }, new { Id = 3, Name = "Bob" } }, Ints = new[] {1, 2, 3} }; var right = new { Foo = new { id = 1, Name = "bob", When = DateTime.Now }, Stuffs = new[] { new { Id = 2, Name = "Billy" }, }, Ints = new List<int>() { 0, 12, 43 } }; var sut = Create(left, right); sut.OnlyCompareShape = true; // Pre-Assert // Act Expect(sut.AreDeepEqual()) .To.Be.True( "* " + sut.Errors.JoinWith("\n *") ); // Assert } } } } [TestFixture] public class UsingAsExtensionMethod { [TestFixture] public class DeepEquals { [Test] public void ShouldNotDerpRoundTwo() { // Arrange var left = new ThingWithField() {StringField = GetRandomString()}; var right = new ThingWithField() {StringField = GetAnother(left.StringField)}; // Act var result = left.DeepEquals(right); // Assert Expect(result).To.Be.False(); } } [Test] public void ShouldHaveOverloadToLogError() { // TODO: update this test when markers are added around deep equality failure // Arrange var left = new { foo = 1 }; var right = new { foo = 2 }; var logs = new List<string>(); // Pre-assert // Act var result = left.DeepEquals(right, s => logs.Add(s)); // Assert Expect(result).To.Be.False(); Expect(logs).To.Contain.Only(1) .Matched.By(l => l.Contains(left.Stringify()) && l.Contains(right.Stringify())); } [Test] public void ShouldReturnFalseForTwoArraysWithSameSizeAndDifferentItems() { // Arrange var left = new[] { 1 }; var right = new[] { 2 }; // Pre-assert // Act var result1 = left.DeepEquals(right); var result2 = right.DeepEquals(left); // Assert Expect(result1).To.Be.False(); Expect(result2).To.Be.False(); } [Test] public void ShouldReturnTrueForTwoArraysWithSameSizeAndSameItems() { // Arrange var left = new[] { 1 }; var right = new[] { 1 }; // Pre-assert // Act var result1 = left.DeepEquals(right); var result2 = right.DeepEquals(left); // Assert Expect(result1).To.Be.True(); Expect(result2).To.Be.True(); } [TestFixture] public class ShapeEquals { [Test] public void ShouldBeTrueForMatchingShapes() { // Arrange var left = new { Foo = new { id = 1, Name = "bob", When = DateTime.Now }, Stuffs = new[] { new { Id = 2, Name = "Billy" }, new { Id = 3, Name = "Bob" } }, Ints = new[] {1, 2, 3} }; var right = new { Foo = new { id = 1, Name = "bob", When = DateTime.Now }, Stuffs = new[] { new { Id = 2, Name = "Billy" }, }, Ints = new List<int>() { 0, 12, 43 } }; // Pre-Assert // Act Expect(left.ShapeEquals(right)) .To.Be.True(); // Assert } } [TestFixture] public class ShapeSubEquals { [Test] public void ShouldBeTrueWhenSourcePropsAreFoundAtTarget() { // Arrange var left = new { Id = 1, Enabled = false }; var right = new { Id = 123, Name = "Bob", Enabled = true }; // Pre-Assert // Act Expect(left.ShapeSubEquals(right)).To.Be.True(); // Assert } } } [TestFixture] public class WildCases { [TestFixture] public class PropertyAssert_AreDeepEqual { [Test] public void ShouldReturnTrueForCaseInWild() { // Arrange var original = GetRandom<MooCakesAndStuff>(); var encoded = MooCakesAndStuffWithEncodedGraphData.From(original); // Pre-Assert PropertyAssert.AreDeepEqual(original.AuthorData, encoded.AuthorData); PropertyAssert.AreDeepEqual(original.SomeOtherData, encoded.SomeOtherData); // Act var decoded = encoded.Decode(); // Assert PropertyAssert.AreDeepEqual(decoded.AuthorData, original.AuthorData); PropertyAssert.AreDeepEqual(decoded.SomeOtherData, original.SomeOtherData); PropertyAssert.AreDeepEqual(decoded.WubWubs, original.WubWubs); } [Test] public void WildCaseExactReplica() { // Arrange var thang = GetRandom<MooCakesAndStuff>(); var encoded = new MooCakesAndStuffWithEncodedGraphData(); thang.CopyPropertiesTo(encoded); encoded.EnkiEnki = DataUriFor(thang.WubWubs); encoded.WubWubs = null; // Pre-assert // Act var result = encoded.Decode(); // Assert PropertyAssert.AreDeepEqual(result, thang); } } } [TestFixture] public class DateTimes { [Test] public void LocalDateTimeShouldNotEqualUtcDateTime() { // Arrange var src = GetRandomDate(); var local = new DateTime( src.Year, src.Month, src.Day, src.Hour, src.Minute, src.Second, DateTimeKind.Local); var utc = new DateTime( src.Year, src.Month, src.Day, src.Hour, src.Minute, src.Second, DateTimeKind.Utc); var sut = Create(local, utc); // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.False(); } } [TestFixture] public class Dictionary { [Test] public void WhenValuesAndKeysAreTheSame_ShouldReturnTrue() { // Arrange var key1 = GetRandomString(); var key2 = GetRandomString(); var value1 = GetRandomString(); var value2 = GetRandomInt(); var dictionary1 = DictionaryBuilder<string, object>.Create() .WithItem(key1, value1) .WithItem(key2, value2) .Build(); var dictionary2 = DictionaryBuilder<string, object>.Create() .WithItem(key1, value1) .WithItem(key2, value2) .Build(); var sut = Create(dictionary1, dictionary2); // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void WhenKeysAreTheSame_ButValuesAreDifferent_ShouldReturnFalse() { // Arrange var key1 = GetRandomString(); var key2 = GetRandomString(); var dictionary1 = DictionaryBuilder<string, object>.Create() .WithItem(key1, GetRandomString()) .WithItem(key2, GetRandomInt()) .Build(); var dictionary2 = DictionaryBuilder<string, object>.Create() .WithItem(key1, GetRandomString()) .WithItem(key2, GetRandomInt()) .Build(); var sut = Create(dictionary1, dictionary2); // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.False(); } [Test] public void WhenValuesAreTheSame_ButKeysAreDifferent_ShouldReturnFalse() { // Arrange var value1 = GetRandomString(); var value2 = GetRandomInt(); var dictionary1 = DictionaryBuilder<string, object>.Create() .WithItem(GetRandomString(), value1) .WithItem(GetRandomString(), value2) .Build(); var dictionary2 = DictionaryBuilder<string, object>.Create() .WithItem(GetRandomString(), value1) .WithItem(GetRandomString(), value2) .Build(); var sut = Create(dictionary1, dictionary2); // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.False(); } [Test] public void WhenDifferentNumberOfEntries_ShouldReturnFalse() { // Arrange var key1 = GetRandomString(); var key2 = GetRandomString(); var value1 = GetRandomString(); var value2 = GetRandomInt(); var dictionary1 = DictionaryBuilder<string, object>.Create() .WithItem(key1, value1) .Build(); var dictionary2 = DictionaryBuilder<string, object>.Create() .WithItem(key1, value1) .WithItem(key2, value2) .Build(); var sut = Create(dictionary1, dictionary2); // Pre-Assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.False(); } } [TestFixture] public class ArbitraryBehaviors { [Test] public void ComparingTwoSimpleTypesWhereOneIsDecimalAndDifferentValues() { // Arrange var left = "123"; var right = 124M; var sut = Create(left, right); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.False(); } [Test] public void ComparingTwoSimpleTypesWhereOneIsDecimalAndSameValuesWhereBothNumeric() { // Arrange var left = 123; var right = 123M; var sut = Create(left, right); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void ComparingTwoSimpleTypesWhereOneIsDecimalAndSameValuesButOneNotNumeric() { // Arrange var left = "123"; var right = 123M; var sut = Create(left, right); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } } [TestFixture] public class CustomEqualityTesting { [Test] public void GivenCustomDateTimeComparer() { // Arrange var left = new {Date = DateTime.Now.AddSeconds(-1)}; var right = new {Date = left.Date.AddSeconds(1)}; var sut = Create(left, right); sut.AddCustomComparer(new DateComparerByDayOnly()); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void GivenCustomDateTimeComparerAsObject() { // Arrange var left = new {Date = DateTime.Now.AddSeconds(-1)}; var right = new {Date = left.Date.AddSeconds(1)}; var sut = Create(left, right); sut.AddCustomComparer(new DateComparerByDayOnly() as object); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void GivenDisparateNumericTypesAndCustomDecimalComparer() { // Arrange var left = new {id = (long)1}; var right = new {id = 2}; var sut = Create(left, right); sut.AddCustomComparer(new DecimalComparerWhichAllowsUpTo2Delta()); // Pre-assert // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(); } [Test] public void GivenCustomComparerForComplexType() { // Arrange var left = GetRandom<Parent>(); var right = GetRandom<Parent>(); right.Id = left.Id; right.Name = left.Name; var sut = Create(left, right); sut.RecordErrors = true; sut.AddCustomComparer(new ChildEqualityComparer()); // Pre-assert Expect(left.Child).Not.To.Deep.Equal(right.Child); // Act var result = sut.AreDeepEqual(); // Assert Expect(result).To.Be.True(sut.Errors.JoinWith("\n")); } public class ChildEqualityComparer : IEqualityComparer<Child> { public bool Equals(Child x, Child y) { return true; // all children are loved just the same! } public int GetHashCode(Child obj) { return 0; } } public class Parent { public int Id { get; set; } public string Name { get; set; } public Child Child { get; set; } } public class Child { public int Id { get; set; } public string Name { get; set; } } } public class DecimalComparerWhichAllowsUpTo2Delta : IEqualityComparer<decimal> { public bool Equals(decimal x, decimal y) { return Math.Abs(x - y) < 2; } public int GetHashCode(decimal obj) { return 0; } } public class DateComparerByDayOnly : IEqualityComparer<DateTime> { public bool Equals(DateTime x, DateTime y) { return x.Year == y.Year && x.Month == y.Month && x.Day == y.Day; } public int GetHashCode(DateTime obj) { return 0; } } private static string DataUriFor<T>(T input) { var json = JsonConvert.SerializeObject(input); var encoded = json.AsBytes().ToBase64(); return $"data:application/json;base64,{encoded}"; } public class ThingWithCollection { public ICollection<int> Subs { get; set; } } private static DeepEqualityTester Create(object obj1, object obj2) { var sut = new DeepEqualityTester(obj1, obj2) {RecordErrors = true}; return sut; } public class ThingWithField { public string StringField; } // TODO: obsfucate me public class MooCakesAndStuff { public Guid Id { get; set; } public string Name { get; set; } public int MajorVersion { get; set; } public int MinorVersion { get; set; } public SomeOtherDataThing SomeOtherData { get; set; } public YetAnotherCollectionOfProperties WubWubs { get; set; } public BeerMooCakeCroc AuthorData { get; set; } public const int NameMaxLength = 100; } public class BeerMooCakeCroc { public DateTime Created { get; set; } public DateTime LastModified { get; set; } public long ClownId { get; set; } public long CreatedById { get; set; } public string CreatedBy { get; set; } public long LastModifiedById { get; set; } public string LastModifiedBy { get; set; } } public class YetAnotherCollectionOfProperties { // TODO: generalize down to BiltongSlab // as that type can support things which aren't wait events, // such as, eg (at some point) decision diamonds public ThingyMaBob[] ThingyMaBobs { get; set; } public WerkelSchmerkel[] WerkelSchmerkels { get; set; } } public class WerkelSchmerkel { public string FromId { get; set; } public string ToId { get; set; } } } public class ThingyMaBob : BiltongSlab { // -> backend WaitEvent public string ThingType { get; set; } public Guid ThingTypeId { get; set; } public ThingCondition[] ThingConditions { get; set; } public CakesOfMoo[] CakesOfMoos { get; set; } } public class ThingCondition { // -> backend: Trigger public Option Condition { get; set; } public Option Operator { get; set; } public Option[] SelectedValues { get; set; } } public class Option { public string Label { get; set; } public string Value { get; set; } } public class CakesOfMoo { // -> backend: StepAction public Guid Id { get; set; } // -> this conditional action's id public Guid CakeId { get; set; } // -> maps to the id of the source action public string CakeName { get; set; } public Dictionary<string, object[]> Settings { get; set; } public TurkeyInnards[] TurkeyStuffings { get; set; } } public class TurkeyInnards { public NamedIdentifier Part1 { get; set; } public NamedIdentifier Part2 { get; set; } } public class NamedIdentifier { public int Id { get; set; } public string Name { get; set; } } public class BiltongSlab { // -> used at client only public string Id { get; set; } // often a guid, but may be a static like "stateBegin" public int Top { get; set; } public int Left { get; set; } public int Width { get; set; } public int Height { get; set; } public string WankelRotaryEngine { get; set; } } public class SomeOtherDataThing { public FirstPart PartTheFirst { get; set; } public SecondPart PartTheSecond { get; set; } public ThirdPart PartTheThird { get; set; } } public class FirstPart { public string[] HaveSome { get; set; } public string[] HaveNone { get; set; } } public class SecondPart { public Flibber Flibber { get; set; } public DateTime Nerf { get; set; } public DateTime DeNerf { get; set; } public bool NerfFreeZone { get; set; } public bool CanNerfTheUnNerfable { get; set; } public Blargh Blargh { get; set; } } public class Flibber { // TODO: complete this public Frequency Frequency { get; set; } public int Interval { get; set; } } public enum Frequency { Hertz, HertzMore, HertzTheMost } public class Blargh { public Salutations Salutations { get; set; } public string Exclamation { get; set; } } public enum Salutations { Loud, Louder } public class ThirdPart { public int? SomeNumber1 { get; set; } public bool IsSomeNumber1 { get; set; } public int? SomeNumber2 { get; set; } public bool IsSomeNumber2 { get; set; } public int Arb { get; set; } public bool Boom { get; set; } public bool Stick { get; set; } public const int Wombat = 1; public const int Feh = 90; } // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class MooCakesAndStuffWithEncodedGraphData : TestDeepEqualityTester.MooCakesAndStuff { // ReSharper disable once MemberCanBePrivate.Global public string EnkiEnki { get; set; } private readonly object _lock = new object(); public TestDeepEqualityTester.MooCakesAndStuff Decode() { var result = StartMeOffJoe(); if (EnkiEnki == null) return result; lock (_lock) { result.WubWubs = JsonConvert .DeserializeObject<TestDeepEqualityTester.YetAnotherCollectionOfProperties>( Convert.FromBase64String(GetDataPartOf(EnkiEnki)) .ToUTF8String()); } return result; } private readonly Regex _dataUriRegex = new Regex(@"^(data:application/json;base64,)(?<data>.*)"); private string GetDataPartOf(string barf) { var match = _dataUriRegex.Match(barf); var dataGroup = match.Groups["data"]; if (!dataGroup.Success) { throw new InvalidDataException($"Expected to find a base64-encoded data uri, but got:\n${barf}"); } return dataGroup.Value; } private static readonly PropertyInfo[] _props = typeof(TestDeepEqualityTester.MooCakesAndStuff).GetProperties(BindingFlags.Public | BindingFlags.Instance); private static readonly PropertyInfo[] _moreProps = typeof(MooCakesAndStuffWithEncodedGraphData).GetProperties(BindingFlags.Public | BindingFlags.Instance); private TestDeepEqualityTester.MooCakesAndStuff StartMeOffJoe() { var moo = new TestDeepEqualityTester.MooCakesAndStuff(); foreach (var propertyInfo in _props) { var match = _moreProps.First(pi => pi.Name == propertyInfo.Name); var myVal = match.GetValue(this); propertyInfo.SetValue(moo, myVal); } return moo; } public static MooCakesAndStuffWithEncodedGraphData From(TestDeepEqualityTester.MooCakesAndStuff moo) { var result = new MooCakesAndStuffWithEncodedGraphData(); foreach (var propertyInfo in _props) { var match = _moreProps.First(pi => pi.Name == propertyInfo.Name); var srcVal = match.GetValue(moo); propertyInfo.SetValue(result, srcVal); } result.EnkiEnki = $"data:application/json;base64,{Convert.ToBase64String(JsonConvert.SerializeObject(moo.WubWubs).AsBytes())}"; return result; } } public class MooBuilder : GenericBuilder<MooBuilder, TestDeepEqualityTester.MooCakesAndStuff> { public MooBuilder WithCreatedDate(DateTime date) { return WithProp(dto => dto.AuthorData.Created = date); } public MooBuilder WithCreatedById(int id) { return WithProp(dto => dto.AuthorData = dto.AuthorData ?? GetRandom<TestDeepEqualityTester.BeerMooCakeCroc>()) .WithProp(dto => dto.AuthorData.CreatedById = id); } public MooBuilder WithName(string name) { return WithProp(o => o.Name = name); } public MooBuilder WithInvalidProps() { return WithRandomProps() .WithName("") .WithProp(dto => dto.SomeOtherData.PartTheFirst.HaveSome = new string[0]) .WithProp(dto => dto.SomeOtherData.PartTheSecond.DeNerf = DateTime.MinValue) .WithProp(dto => dto.SomeOtherData.PartTheSecond.Nerf = DateTime.MaxValue) .WithProp(dto => dto.SomeOtherData.PartTheThird.IsSomeNumber1 = false) .WithProp(dto => dto.SomeOtherData.PartTheThird.SomeNumber1 = int.MinValue) .WithProp(dto => dto.SomeOtherData.PartTheThird.IsSomeNumber2 = false) .WithProp(dto => dto.SomeOtherData.PartTheThird.SomeNumber2 = int.MinValue) .WithProp(dto => dto.SomeOtherData.PartTheThird.Arb = int.MinValue); } public MooBuilder WithAllValidProps() { return WithRandomProps() .WithName(GetRandomString(5, 15)) .WithProp(dto => dto.SomeOtherData.PartTheFirst.HaveSome = new[] {GetRandomString(5, 11)}) .WithProp(dto => dto.SomeOtherData.PartTheSecond.Nerf = DateTime.Now) .WithProp(dto => dto.SomeOtherData.PartTheSecond.DeNerf = DateTime.Now.AddDays(10)) .WithProp(dto => dto.SomeOtherData.PartTheThird.IsSomeNumber1 = false) .WithProp(dto => dto.SomeOtherData.PartTheThird.SomeNumber1 = 10) .WithProp(dto => dto.SomeOtherData.PartTheThird.IsSomeNumber2 = false) .WithProp(dto => dto.SomeOtherData.PartTheThird.SomeNumber2 = 1) .WithProp(dto => dto.SomeOtherData.PartTheThird.Arb = 5); } public MooBuilder WithNullGraphData() { return WithProp(o => o.WubWubs = null); } public MooBuilder WithNullWidgets() { return WithProp(o => o.WubWubs.ThingyMaBobs = null); } public MooBuilder WithEmptyWidgets() { return WithProp(o => o.WubWubs.ThingyMaBobs = new ThingyMaBob[0]); } public MooBuilder WithNullConnections() { return WithProp(o => o.WubWubs.WerkelSchmerkels = null); } public MooBuilder WithEmptyConnections() { return WithProp(o => o.WubWubs.WerkelSchmerkels = new TestDeepEqualityTester.WerkelSchmerkel[0]); } public MooBuilder WithNoInitiatingTrigger() { return WithProp( o => o.WubWubs.WerkelSchmerkels = o.WubWubs.WerkelSchmerkels .EmptyIfNull() .Where(c => c.FromId != "WibbleStix") .ToArray() ); } public MooBuilder WithUnconfiguredAction() { return WithProp( o => { var widget = o.WubWubs.ThingyMaBobs.Second(); widget.CakesOfMoos.First().Settings["Moo"] = GetRandomBoolean() ? null : new object[] { }; }); } public MooBuilder WithUnconfiguredCondition() { return WithProp( o => { var widget = o.WubWubs.ThingyMaBobs.Second(); widget.ThingConditions.First().SelectedValues = GetRandomBoolean() ? null : new Option[0]; }); } public MooBuilder WithMultipleEventsButNoActions() { return WithProp( o => { o.WubWubs.ThingyMaBobs.ForEach( w => { w.CakesOfMoos = null; }); }); } public class EventConditionBuilder : GenericBuilder<EventConditionBuilder, ThingCondition> { public override EventConditionBuilder WithRandomProps() { return base.WithRandomProps() .WithProp(condition => condition.Condition = GetRandom<Option>()) .WithProp(condition => condition.Operator = GetRandom<Option>()) .WithProp(condition => condition.SelectedValues = GetRandomCollection<Option>(1).ToArray()); } } public class ConditionalActionBuilder : GenericBuilder<ConditionalActionBuilder, CakesOfMoo> { public override ConditionalActionBuilder WithRandomProps() { return WithProp(o => o.CakeId = Guid.NewGuid()) .WithProp(o => o.CakeName = GetRandomString(4)) .WithProp(o => o.Id = Guid.NewGuid()) .WithProp( o => o.Settings = new Dictionary<string, object[]>() { [GetRandomString(2, 4)] = GetRandomCollection<int>(2).Cast<object>().ToArray() }); } } public class WaitEventWidgetDtoBuilder : GenericBuilder<WaitEventWidgetDtoBuilder, ThingyMaBob> { public override WaitEventWidgetDtoBuilder WithRandomProps() { return base.WithRandomProps() .WithGuidId() .WithRandomThingConditions() .WithRandomMooCakes(); } public WaitEventWidgetDtoBuilder WithGuidId() { return WithProp(o => o.Id = $"{Guid.NewGuid()}"); } private readonly string _depositId = Guid.NewGuid().ToString(); public WaitEventWidgetDtoBuilder AsDeposit() { return WithGuidId() .WithThingTypeId(_depositId) .WithThingType( "Deposit"); // this is what the client gets; it's only interesting to humans -- we'll use the id } public WaitEventWidgetDtoBuilder WithThingType(string thingType) { return WithProp(o => o.ThingType = thingType); } public WaitEventWidgetDtoBuilder WithThingTypeId(string guid) { return WithProp(o => o.ThingTypeId = Guid.Parse(guid)); } public WaitEventWidgetDtoBuilder WithRandomMooCakes() { return WithProp( o => WithMooCakes(GetRandomCollection<CakesOfMoo>(1, 3).ToArray()) ); } public WaitEventWidgetDtoBuilder WithId(string id) { return WithProp(o => o.Id = id); } public WaitEventWidgetDtoBuilder WithMooCakes(params CakesOfMoo[] actions) { return WithProp( o => o.CakesOfMoos = o.CakesOfMoos.EmptyIfNull().And(actions) ); } public WaitEventWidgetDtoBuilder WithRandomThingConditions() { return WithProp( o => WithThingConditions(GetRandomCollection<ThingCondition>(1, 3).ToArray()) ); } public WaitEventWidgetDtoBuilder WithThingConditions(params ThingCondition[] conditions) { return WithProp(o => o.ThingConditions = o.ThingConditions.EmptyIfNull().And(conditions)); } } public class YacopBuilder : GenericBuilder<YacopBuilder, TestDeepEqualityTester.YetAnotherCollectionOfProperties > { private static readonly ThingyMaBob _start = new ThingyMaBob() { Id = "stateBegin", ThingTypeId = Guid.Empty, WankelRotaryEngine = "pjc-state-begin" }; public override YacopBuilder WithRandomProps() { return base.WithRandomProps() .WithStart() .WithProp( o => { var waitEventWidgets = GetRandomCollection<ThingyMaBob>(2, 4).ToArray(); WithThingies(waitEventWidgets); }) .WithSomePlan(); } private YacopBuilder WithSomePlan() { return WithProp( o => { var start = o.ThingyMaBobs.FirstOrDefault(w => w.Id == "WibbleStix"); if (start == null) return; var others = new Queue<ThingyMaBob>(o.ThingyMaBobs.Except(new[] {start}).ToArray()); var last = start; while (others.Count > 0) { var next = others.Dequeue(); o.WerkelSchmerkels = o.WerkelSchmerkels.EmptyIfNull().And(ConnectWibbleStix(last, next)); last = next; } }); TestDeepEqualityTester.WerkelSchmerkel ConnectWibbleStix(BiltongSlab fromWidget, BiltongSlab toWidget) { return new TestDeepEqualityTester.WerkelSchmerkel() { FromId = fromWidget.Id == "WibbleStix" ? fromWidget.Id : $"success.{fromWidget.Id}", ToId = $"wait-event.{toWidget.Id}" }; } } public YacopBuilder WithThingies(params ThingyMaBob[] connections) { return WithProp( o => o.ThingyMaBobs = o.ThingyMaBobs.EmptyIfNull().And(connections) ); } public YacopBuilder WithWerkels(params TestDeepEqualityTester.WerkelSchmerkel[] connections) { return WithProp(o => o.WerkelSchmerkels = o.WerkelSchmerkels.EmptyIfNull().And(connections)); } public YacopBuilder WithStart() { return WithProp(o => o.ThingyMaBobs = o.ThingyMaBobs.And(_start)); } } } public class DictionaryBuilder<TKey, TValue> : GenericBuilder<DictionaryBuilder<TKey, TValue>, Dictionary<TKey, TValue>> { public DictionaryBuilder<TKey, TValue> WithItem(TKey key, TValue value) { return WithProp(o => o.Add(key, value)); } } }
35.241263
125
0.431301
[ "BSD-3-Clause" ]
Rohland/PeanutButter
source/Utils/PeanutButter.Utils.Tests/TestDeepEqualityTester.cs
52,441
C#
#pragma checksum "E:\Repos\TZJGH\ExtensionsForNetCorePack\src\Extentions\WebApplication1\Views\_ViewImports.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "729efaa87342638aecfe1a972ce9f9f8dff55b4c" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewImports), @"mvc.1.0.view", @"/Views/_ViewImports.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "E:\Repos\TZJGH\ExtensionsForNetCorePack\src\Extentions\WebApplication1\Views\_ViewImports.cshtml" using WebApplication1; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\Repos\TZJGH\ExtensionsForNetCorePack\src\Extentions\WebApplication1\Views\_ViewImports.cshtml" using WebApplication1.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"729efaa87342638aecfe1a972ce9f9f8dff55b4c", @"/Views/_ViewImports.cshtml")] public class Views__ViewImports : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
49.82
199
0.773183
[ "MIT" ]
TZJGH/ExtensionsForNetCorePack
src/Extentions/WebApplication1/obj/Debug/netcoreapp3.1/Razor/Views/_ViewImports.cshtml.g.cs
2,491
C#
namespace LemonadeStand.Common.RandomEvents { public class HeatWave : RandomEvent { public HeatWave() : base("Heat wave") { } public override string ForecastMessage { get { return "There's a heat wave predicted today."; } } public override double Modify(double baseSales, Choices choices) { return baseSales*2; } } }
22.473684
72
0.562061
[ "MIT" ]
kevinmel2000/lemonade-stand-1
LemonadeStand.Common/RandomEvents/HeatWave.cs
429
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Sales.ServiceApi.Data; namespace Sales.ServiceApi.Migrations { [DbContext(typeof(ECommerceDbContext))] [Migration("20161009143501_ECommerceMigration1")] partial class ECommerceMigration1 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.1") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Sales.Data.Core.Models.Product", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ImageUrl"); b.Property<int>("LikesCount"); b.Property<string>("Link"); b.Property<string>("Name"); b.Property<decimal>("Price"); b.Property<int>("PurchaseByCount"); b.Property<decimal>("Rating"); b.Property<string>("Tags"); b.HasKey("Id"); b.ToTable("Products"); }); } } }
29.354167
117
0.574876
[ "Apache-2.0" ]
vishipayyallore/ASP-Dotnet-Core-Samples
SalesWebApp/Sales.ServiceApi/Migrations/20161009143501_ECommerceMigration1.Designer.cs
1,411
C#
using System; namespace Atlasd.Battlenet.Exceptions { class GameProtocolException : ProtocolException { public GameProtocolException(ClientState client) : base(Battlenet.ProtocolType.Types.Game, client) { } public GameProtocolException(ClientState client, string message) : base(Battlenet.ProtocolType.Types.Game, client, message) { } public GameProtocolException(ClientState client, string message, Exception innerException) : base(Battlenet.ProtocolType.Types.Game, client, message, innerException) { } } }
46.5
178
0.747312
[ "MIT" ]
BNETDocs/Atlas
src/Atlasd/Battlenet/Exceptions/GameProtocolException.cs
549
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace PrismGTKTest.Views.Templates { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MenuItemTemplate : ContentView { public MenuItemTemplate() { InitializeComponent(); } } }
20.95
55
0.711217
[ "MIT" ]
DlbSt/PrismGTKTest
PrismGTKTest/PrismGTKTest/PrismGTKTest/Views/Templates/MenuItemTemplate.xaml.cs
421
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Planet spawner. This component spawns planets and asteroids "kind of" random /// based. /// </summary> public class PlanetSpawner : MonoBehaviour { // Empty transform objects used to group the spawned planets and asteroids [Header("Containers")] public Transform planetContainer; public Transform asteroidContainer; // Prefabs of the objects to spawn (i.e. planets and asteroids); [Header("Prefabs")] public GameObject[] planetPrefabsDualColor; public GameObject[] planetPrefabsSingleColor; public GameObject planetPrefabSchmaturn; public GameObject planetPrefabSchmenus; public GameObject[] asteroidPrefabs; // The color palette for the planets public Color[] PlanetColorArray; // The Range of the universe // i.e. the area in which objects spawn is between -range and range // for both, the x- and y-axis public float range = 10000f; // the min and max level for the planets public int minLevel = 1; public int maxLevel = 100; // The min and max sizes for the planets public float sizeMin = 0.3f; public float sizeMax = 100; // The min and max size for asteroids public float sizeMinAsteroids = 0.5f; public float sizeMaxAsteroids = 3f; // The name generator, which is used to generate names for planets // Thanks, Captain Obvious. private NameGenerator nameGenerator; /// <summary> /// Initialize the PlanetSpawner i.e. create the name generator. /// </summary> private void Awake() { nameGenerator = new NameGenerator(); } /// <summary> /// Spawns a planet. /// </summary> public void SpawnPlanet() { float x, y, size; Vector3 position; int level; // roll out a position, which is at least 10 times the size away from // every other planet. Thus smaller planets with a lower level appear // closer together and more in the center of the universe, bigger // planets spawn in the outer rim. do { x = NextGaussian(0, 100, -range, range); y = NextGaussian(0, 100, -range, range); position = new Vector3(x, 0, y); // roll out the level of the planet depending on the position // i.e. higher level planets are more away from the center/home planet level = Mathf.RoundToInt( Mathf.Ceil(Vector3.Distance(Vector3.zero, position) / range * maxLevel * Random.Range(0.8f, 1.2f))); // "transform" the level value into the size interval size = MapToInterval(level, minLevel, maxLevel, sizeMin, sizeMax); // generate a new position if there is already a planet on this spot } while (Physics.OverlapSphere(position, size*10).Length > 0); // generate a name for the planet to spawn. var name = nameGenerator.GenerateName(); // Create/instantiate the planet game object. // if it is a special planet i.e. its name is SCHMATURN or SCHMENUS // pick a special prefab. // Otherwise randomly choose between single or double colored planets GameObject go = null; if (name.Contains("SCHMATURN")) { go = Instantiate(planetPrefabSchmaturn) as GameObject; go.GetComponent<MeshRenderer>().material.color = PlanetColorArray[Random.Range(0, PlanetColorArray.Length)]; } else if (name.Contains("SCHMENUS")) { go = Instantiate(planetPrefabSchmenus) as GameObject; go.GetComponent<MeshRenderer>().material.color = PlanetColorArray[Random.Range(0, PlanetColorArray.Length)]; } else { if (Random.Range(0, 100) < 50) { go = InstantiateSingleColor(); } else { go = InstantiateDualColor(); } } // pack the spawned planet into the planet container // and initialize attributes like the layer, the name, position, etc. go.transform.SetParent(planetContainer); go.layer = LayerMask.NameToLayer("Planet"); go.tag = "Planet"; go.name = name; go.transform.position = position; go.transform.localScale = new Vector3(size, size, size); // add the planet component script to the planet game object var planet = go.AddComponent<Planet>(); planet.level = level; planet.name = name; } /// <summary> /// Instaniates a single-colored planet. /// </summary> /// <returns>The instaniated planet game object.</returns> private GameObject InstantiateSingleColor() { // Pick a random planet prefab var prefab = planetPrefabsSingleColor[Random.Range(0, planetPrefabsSingleColor.Length)]; // Instantiate it and pick & set a color for the planet randomly out of the palette var go = Instantiate(prefab) as GameObject; go.GetComponent<MeshRenderer>().material.color = PlanetColorArray[Random.Range(0, PlanetColorArray.Length)]; return go; } /// <summary> /// Instaniates a dual-colored planet. /// </summary> /// <returns>The instaniated planet game object.</returns> private GameObject InstantiateDualColor() { // Pick a random planet prefab var prefab = planetPrefabsDualColor[Random.Range(0, planetPrefabsDualColor.Length)]; // Instantiate it and pick & set two colors for the planet randomly out of the palette var go = Instantiate(prefab) as GameObject; go.GetComponent<MeshRenderer>().materials[0].color = PlanetColorArray[Random.Range(0, PlanetColorArray.Length)]; go.GetComponent<MeshRenderer>().materials[1].color = PlanetColorArray[Random.Range(0, PlanetColorArray.Length)]; return go; } /// <summary> /// Spawns the asteroid gameobjects. /// </summary> public void SpawnAsteroid() { // pick a random asteroid prefab and instaniate it var prefab = asteroidPrefabs[Random.Range(0, asteroidPrefabs.Length)]; var go = Instantiate(prefab) as GameObject; go.transform.SetParent(asteroidContainer); // Calculate normal distributed values for the x and y position // and "move" the spawned asteroid to this randomly choosen position. var x = NextGaussian(0, range/4, -range, range); var y = NextGaussian(0, range/4, -range, range); go.transform.position = new Vector3(x, 0, y); // Randomly scale the asteroids. var size = Random.Range(sizeMinAsteroids, sizeMaxAsteroids); go.transform.localScale = new Vector3(size, size, size); } /// <summary> /// Map the given value from the interval (from1, to1) to value in the /// interval (from2, to2). This is can be used to transform the level of a /// planet to its size. /// Calculates: /// (value - from1) / (to1 - from1) * (to2-from2) + from2 /// </summary> /// <returns>The mapped single value.</returns> /// <param name="value">The main contributing value e.g. the level of the /// planet</param> /// <param name="from1">The minimum of the value range e.g. the minimum /// planet levels</param> /// <param name="to1">The maximum of the value range e.g. the maximum planet /// level</param> /// <param name="from2">The minimum of the range for the returned value e.g. /// the minimum planet size</param> /// <param name="to2">The maximum of the range for the returned value e.g. /// the maximum planet size</param> private static float MapToInterval(float value, float from1, float to1, float from2, float to2) { return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } /// <summary> /// Picks a normal distributed random number, NOT limited to an interval. /// </summary> /// <returns>The gaussian normal distributed random number.</returns> private static float NextGaussian() { float v1, v2, s; do { v1 = 2.0f * Random.Range(0f, 1f) - 1.0f; v2 = 2.0f * Random.Range(0f, 1f) - 1.0f; s = v1 * v1 + v2 * v2; } while (s >= 1.0f || Mathf.Abs(s - 0f) < 0.000000001f); s = Mathf.Sqrt((-2.0f * Mathf.Log(s)) / s); return v1 * s; } /// <summary> /// Picks a normal distributed random number, NOT limited to an interval. /// </summary> /// <returns>The gaussian normal distributed random number.</returns> /// <param name="mean">The mean of the normal distribution, i.e. the values /// are scattered around this mean value.</param> /// <param name="standard_deviation">The possible deviation factor of the /// randomly choosen value.</param> private static float NextGaussian(float mean, float standard_deviation) { return mean + NextGaussian() * standard_deviation; } /// <summary> /// Picks a normal distributed random number, limited to an interval. /// </summary> /// <returns>The gaussian normal distributed random number.</returns> /// <param name="mean">The mean of the normal distribution, i.e. the values /// are scattered around this mean value.</param> /// <param name="standard_deviation">The possible deviation factor of the /// randomly choosen value.</param> /// <param name="min">The minimum of the range. I.e. no random value will be /// smaller than the minimum.</param> /// <param name="max">The maximum of the range. I.e. no random value will be /// greater than the maximum.</param> private static float NextGaussian (float mean, float standard_deviation, float min, float max) { float x; do { x = NextGaussian(mean, standard_deviation); } while (x < min || x > max); return x; } }
36.083004
114
0.694271
[ "MIT" ]
PixelManiacs/DonUniverso
beansjam_unity/Assets/_Game/Scripts/PlanetSpawner.cs
9,131
C#
namespace Twitter.IO { using System; public class ConsoleWriter { public void WriteLine(string message) => Console.WriteLine(message); } }
16.5
76
0.654545
[ "MIT" ]
valkin88/CSharp-Fundamentals
CSharp OOP Advanced/Unit Testing - Exercises/Twitter/Twitter/IO/ConsoleWriter.cs
167
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using NQuery.Text; namespace NQuery { public sealed class SyntaxToken { private readonly SyntaxTree _syntaxTree; private readonly string _text; internal SyntaxToken(SyntaxTree syntaxTree, SyntaxKind kind, SyntaxKind contextualKind, bool isMissing, TextSpan span, string text, object value, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia, IEnumerable<Diagnostic> diagnostics) { _syntaxTree = syntaxTree; Kind = kind; ContextualKind = contextualKind; IsMissing = isMissing; Span = span; _text = text; Value = value; LeadingTrivia = leadingTrivia.ToImmutableArray(); TrailingTrivia = trailingTrivia.ToImmutableArray(); Diagnostics = diagnostics.ToImmutableArray(); } public SyntaxNode Parent => _syntaxTree?.GetParentNode(this); public SyntaxKind Kind { get; } public SyntaxKind ContextualKind { get; } public bool IsMissing { get; } public string Text => _text ?? Kind.GetText(); public object Value { get; } public string ValueText => Value as string ?? Text; public TextSpan Span { get; } public TextSpan FullSpan { get { var start = LeadingTrivia.Length == 0 ? Span.Start : LeadingTrivia[0].Span.Start; var end = TrailingTrivia.Length == 0 ? Span.End : TrailingTrivia[TrailingTrivia.Length - 1].Span.End; return TextSpan.FromBounds(start, end); } } public ImmutableArray<SyntaxTrivia> LeadingTrivia { get; } public ImmutableArray<SyntaxTrivia> TrailingTrivia { get; } public ImmutableArray<Diagnostic> Diagnostics { get; } public SyntaxToken GetPreviousToken(bool includeZeroLength = false, bool includeSkippedTokens = false) { return SyntaxTreeNavigation.GetPreviousToken(this, includeZeroLength, includeSkippedTokens); } public SyntaxToken GetNextToken(bool includeZeroLength = false, bool includeSkippedTokens = false) { return SyntaxTreeNavigation.GetNextToken(this, includeZeroLength, includeSkippedTokens); } public void WriteTo(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); foreach (var syntaxTrivia in LeadingTrivia) syntaxTrivia.WriteTo(writer); writer.Write(_text); foreach (var syntaxTrivia in TrailingTrivia) syntaxTrivia.WriteTo(writer); } public bool IsEquivalentTo(SyntaxToken other) { if (other == null) throw new ArgumentNullException(nameof(other)); return SyntaxTreeEquivalence.AreEquivalent(this, other); } public SyntaxToken WithDiagnotics(IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) throw new ArgumentNullException(nameof(diagnostics)); return new SyntaxToken(_syntaxTree, Kind, ContextualKind, IsMissing, Span, _text, Value, LeadingTrivia, TrailingTrivia, diagnostics); } public SyntaxToken WithKind(SyntaxKind kind) { return new SyntaxToken(_syntaxTree, kind, ContextualKind, IsMissing, Span, _text, Value, LeadingTrivia, TrailingTrivia, Diagnostics); } public SyntaxToken WithLeadingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (trivia == null) throw new ArgumentNullException(nameof(trivia)); return new SyntaxToken(_syntaxTree, Kind, ContextualKind, IsMissing, Span, _text, Value, trivia, TrailingTrivia, Diagnostics); } public SyntaxToken WithTrailingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (trivia == null) throw new ArgumentNullException(nameof(trivia)); return new SyntaxToken(_syntaxTree, Kind, ContextualKind, IsMissing, Span, _text, Value, LeadingTrivia, trivia, Diagnostics); } public override string ToString() { using (var writer = new StringWriter()) { WriteTo(writer); return writer.ToString(); } } } }
34.42963
273
0.612091
[ "MIT" ]
dallmair/nquery-vnext
src/NQuery/SyntaxToken.cs
4,648
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Dreidel.Spinner.Services; namespace Dreidel.Spinner { public static class Dreidel { private static IDreidelService _dreidelService; [FunctionName("SpinDreidel")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "dreidel/spin")] HttpRequest req, ILogger log) { log.LogInformation("Happy Hanukkah - C# HTTP trigger function to spin a dreidel."); _dreidelService = new DreidelService(); var _spinResult = await _dreidelService.Spin(); return _spinResult != null ? (ActionResult)new OkObjectResult(_spinResult) : new BadRequestObjectResult("Opps, you dreidel failed to spin!"); } } }
32.53125
104
0.654179
[ "MIT" ]
stuartleaver/25-days-of-serverless
01-serverless-dreidel/Dreidel.cs
1,041
C#
using System.Linq; using NUnit.Framework; using SQLite.Net.Attributes; namespace SQLite.Net.Tests { [TestFixture] public class DeleteTest { private class TestTable { [PrimaryKey, AutoIncrement] public int Id { get; set; } public int Datum { get; set; } public string Test { get; set; } } private const int Count = 100; private SQLiteConnection CreateDb() { var db = new TestDb(); db.CreateTable<TestTable>(); var items = from i in Enumerable.Range(0, Count) select new TestTable { Datum = 1000 + i, Test = "Hello World" } ; db.InsertAll(items); Assert.AreEqual(Count, db.Table<TestTable>().Count()); return db; } [Test] public void DeleteAll() { var db = CreateDb(); var r = db.DeleteAll<TestTable>(); Assert.AreEqual(Count, r); Assert.AreEqual(0, db.Table<TestTable>().Count()); } [Test] public void DeleteAllWithPredicate() { var db = CreateDb(); var r = db.Table<TestTable>().Delete(p => p.Test == "Hello World"); Assert.AreEqual(Count, r); Assert.AreEqual(0, db.Table<TestTable>().Count()); } [Test] public void DeleteAllWithPredicateHalf() { var db = CreateDb(); db.Insert(new TestTable { Datum = 1, Test = "Hello World 2" }); var r = db.Table<TestTable>().Delete(p => p.Test == "Hello World"); Assert.AreEqual(Count, r); Assert.AreEqual(1, db.Table<TestTable>().Count()); } [Test] public void DeleteEntityOne() { var db = CreateDb(); var r = db.Delete(db.Get<TestTable>(1)); Assert.AreEqual(1, r); Assert.AreEqual(Count - 1, db.Table<TestTable>().Count()); } [Test] public void DeletePKNone() { var db = CreateDb(); var r = db.Delete<TestTable>(348597); Assert.AreEqual(0, r); Assert.AreEqual(Count, db.Table<TestTable>().Count()); } [Test] public void DeletePKOne() { var db = CreateDb(); var r = db.Delete<TestTable>(1); Assert.AreEqual(1, r); Assert.AreEqual(Count - 1, db.Table<TestTable>().Count()); } } }
24.752294
79
0.469978
[ "MIT" ]
MontakOleg/SQLite.Net-PCL
tests/DeleteTest.cs
2,698
C#
using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Xml.Linq; using System.Xml.XPath; using System.Linq; using System.Xml; public enum Target { Library, Exe, Module, WinExe } public enum LanguageVersion { ISO_1 = 1, Default_MCS = 2, ISO_2 = 3, LINQ = 4, Future = 5, Default = LINQ } class SlnGenerator { public static readonly string NewLine = "\r\n"; //Environment.NewLine; // "\n"; public SlnGenerator (string formatVersion = "2012") { switch (formatVersion) { case "2008": this.header = MakeHeader ("10.00", "2008"); break; default: this.header = MakeHeader ("12.00", "2012"); break; } } const string project_start = "Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = \"{0}\", \"{1}\", \"{2}\""; // Note: No need to double up on {} around {2} const string project_end = "EndProject"; public List<MsbuildGenerator.VsCsproj> libraries = new List<MsbuildGenerator.VsCsproj> (); string header; string MakeHeader (string formatVersion, string yearTag) { return string.Format ("Microsoft Visual Studio Solution File, Format Version {0}" + NewLine + "# Visual Studio {1}", formatVersion, yearTag); } public void Add (MsbuildGenerator.VsCsproj vsproj) { try { libraries.Add (vsproj); } catch (Exception ex) { Console.WriteLine (ex); } } public void Write (string filename) { using (var sln = new StreamWriter (filename)) { sln.WriteLine (); sln.WriteLine (header); foreach (var proj in libraries) { sln.WriteLine (project_start, proj.library, proj.csProjFilename, proj.projectGuid); sln.WriteLine (project_end); } sln.WriteLine ("Global"); sln.WriteLine ("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution"); sln.WriteLine ("\t\tDebug|Any CPU = Debug|Any CPU"); sln.WriteLine ("\t\tRelease|Any CPU = Release|Any CPU"); sln.WriteLine ("\tEndGlobalSection"); sln.WriteLine ("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution"); foreach (var proj in libraries) { var guid = proj.projectGuid; sln.WriteLine ("\t\t{0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", guid); sln.WriteLine ("\t\t{0}.Debug|Any CPU.Build.0 = Debug|Any CPU", guid); sln.WriteLine ("\t\t{0}.Release|Any CPU.ActiveCfg = Release|Any CPU", guid); sln.WriteLine ("\t\t{0}.Release|Any CPU.Build.0 = Release|Any CPU", guid); } sln.WriteLine ("\tEndGlobalSection"); sln.WriteLine ("\tGlobalSection(SolutionProperties) = preSolution"); sln.WriteLine ("\t\tHideSolutionNode = FALSE"); sln.WriteLine ("\tEndGlobalSection"); sln.WriteLine ("EndGlobal"); } } internal bool ContainsProjectIdentifier (string projId) { return libraries.FindIndex (x => (x.library == projId)) >= 0; } public int Count { get { return libraries.Count; } } } class MsbuildGenerator { static readonly string NewLine = SlnGenerator.NewLine; static XmlNamespaceManager xmlns; public const string profile_2_0 = "_2_0"; public const string profile_3_5 = "_3_5"; public const string profile_4_0 = "_4_0"; public const string profile_4_5 = "_4_5"; static void Usage () { Console.WriteLine ("Invalid argument"); } static string template; static MsbuildGenerator () { using (var input = new StreamReader ("csproj.tmpl")) { template = input.ReadToEnd (); } xmlns = new XmlNamespaceManager (new NameTable ()); xmlns.AddNamespace ("x", "http://schemas.microsoft.com/developer/msbuild/2003"); } // The directory as specified in order.xml public string dir; string library; string projectGuid; string fx_version; XElement xproject; public string CsprojFilename; // // Our base directory, this is relative to our exectution point mono/msvc/scripts string base_dir; string mcs_topdir; public string LibraryOutput, AbsoluteLibraryOutput; public MsbuildGenerator (XElement xproject) { this.xproject = xproject; dir = xproject.Attribute ("dir").Value; library = xproject.Attribute ("library").Value; CsprojFilename = "..\\..\\mcs\\" + dir + "\\" + library + ".csproj"; LibraryOutput = xproject.Element ("library_output").Value; projectGuid = LookupOrGenerateGuid (); fx_version = xproject.Element ("fx_version").Value; Csproj = new VsCsproj () { csProjFilename = this.CsprojFilename, projectGuid = this.projectGuid, library_output = this.LibraryOutput, fx_version = double.Parse (fx_version), library = this.library, MsbuildGenerator = this }; if (dir == "mcs") { mcs_topdir = "../"; class_dir = "../class/"; base_dir = "../../mcs/mcs"; } else { mcs_topdir = "../"; foreach (char c in dir) { if (c == '/') mcs_topdir = "..//" + mcs_topdir; } class_dir = mcs_topdir.Substring (3); base_dir = Path.Combine ("..", "..", "mcs", dir); } AbsoluteLibraryOutput = Path.GetFullPath (Path.Combine (base_dir, LibraryOutput)); } string LookupOrGenerateGuid () { var projectFile = NativeName (CsprojFilename); if (File.Exists (projectFile)){ var doc = XDocument.Load (projectFile); return doc.XPathSelectElement ("x:Project/x:PropertyGroup/x:ProjectGuid", xmlns).Value; } return "{" + Guid.NewGuid ().ToString ().ToUpper () + "}"; } // Currently used bool Unsafe = false; StringBuilder defines = new StringBuilder (); bool Optimize = true; bool want_debugging_support = false; Dictionary<string, string> embedded_resources = new Dictionary<string, string> (); List<string> warning_as_error = new List<string> (); List<int> ignore_warning = new List<int> (); bool load_default_config = true; bool StdLib = true; List<string> references = new List<string> (); List<string> libs = new List<string> (); List<string> reference_aliases = new List<string> (); bool showWarnings = false; // Currently unused #pragma warning disable 0219, 0414 int WarningLevel = 4; bool Checked = false; bool WarningsAreErrors; bool VerifyClsCompliance = true; string win32IconFile; string StrongNameKeyFile; bool copyLocal = true; Target Target = Target.Exe; string TargetExt = ".exe"; string OutputFile; string StrongNameKeyContainer; bool StrongNameDelaySign = false; LanguageVersion Version = LanguageVersion.Default; string CodePage; // Class directory, relative to string class_dir; #pragma warning restore 0219,414 readonly char [] argument_value_separator = new char [] { ';', ',' }; // // This parses the -arg and /arg options to the compiler, even if the strings // in the following text use "/arg" on the strings. // bool CSCParseOption (string option, ref string [] args) { int idx = option.IndexOf (':'); string arg, value; if (idx == -1) { arg = option; value = ""; } else { arg = option.Substring (0, idx); value = option.Substring (idx + 1); } switch (arg.ToLower (CultureInfo.InvariantCulture)) { case "/nologo": return true; case "/t": case "/target": switch (value) { case "exe": Target = Target.Exe; break; case "winexe": Target = Target.WinExe; break; case "library": Target = Target.Library; TargetExt = ".dll"; break; case "module": Target = Target.Module; TargetExt = ".netmodule"; break; default: return false; } return true; case "/out": if (value.Length == 0) { Usage (); Environment.Exit (1); } OutputFile = value; return true; case "/o": case "/o+": case "/optimize": case "/optimize+": Optimize = true; return true; case "/o-": case "/optimize-": Optimize = false; return true; case "/incremental": case "/incremental+": case "/incremental-": // nothing. return true; case "/d": case "/define": { if (value.Length == 0) { Usage (); Environment.Exit (1); } foreach (string d in value.Split (argument_value_separator)) { if (defines.Length != 0) defines.Append (";"); defines.Append (d); } return true; } case "/bugreport": // // We should collect data, runtime, etc and store in the file specified // return true; case "/linkres": case "/linkresource": case "/res": case "/resource": bool embeded = arg [1] == 'r' || arg [1] == 'R'; string [] s = value.Split (argument_value_separator); switch (s.Length) { case 1: if (s [0].Length == 0) goto default; embedded_resources [s [0]] = Path.GetFileName (s [0]); break; case 2: embedded_resources [s [0]] = s [1]; break; case 3: Console.WriteLine ("Does not support this method yet: {0}", arg); Environment.Exit (1); break; default: Console.WriteLine ("Wrong number of arguments for option `{0}'", option); Environment.Exit (1); break; } return true; case "/recurse": Console.WriteLine ("/recurse not supported"); Environment.Exit (1); return true; case "/r": case "/reference": { if (value.Length == 0) { Console.WriteLine ("-reference requires an argument"); Environment.Exit (1); } string [] refs = value.Split (argument_value_separator); foreach (string r in refs) { string val = r; int index = val.IndexOf ('='); if (index > -1) { reference_aliases.Add (r); continue; } if (val.Length != 0) references.Add (val); } return true; } case "/main": case "/m": case "/addmodule": case "/win32res": case "/doc": if (showWarnings) Console.WriteLine ("{0} = not supported", arg); return true; case "/lib": { libs.Add (value); return true; } case "/win32icon": { win32IconFile = value; return true; } case "/debug-": want_debugging_support = false; return true; case "/debug": case "/debug+": want_debugging_support = true; return true; case "/checked": case "/checked+": Checked = true; return true; case "/checked-": Checked = false; return true; case "/clscheck": case "/clscheck+": return true; case "/clscheck-": VerifyClsCompliance = false; return true; case "/unsafe": case "/unsafe+": Unsafe = true; return true; case "/unsafe-": Unsafe = false; return true; case "/warnaserror": case "/warnaserror+": if (value.Length == 0) { WarningsAreErrors = true; } else { foreach (string wid in value.Split (argument_value_separator)) warning_as_error.Add (wid); } return true; case "/-runtime": // Console.WriteLine ("Warning ignoring /runtime:v4"); return true; case "/warnaserror-": if (value.Length == 0) { WarningsAreErrors = false; } else { foreach (string wid in value.Split (argument_value_separator)) warning_as_error.Remove (wid); } return true; case "/warn": WarningLevel = Int32.Parse (value); return true; case "/nowarn": { string [] warns; if (value.Length == 0) { Console.WriteLine ("/nowarn requires an argument"); Environment.Exit (1); } warns = value.Split (argument_value_separator); foreach (string wc in warns) { try { if (wc.Trim ().Length == 0) continue; int warn = Int32.Parse (wc); if (warn < 1) { throw new ArgumentOutOfRangeException ("warn"); } ignore_warning.Add (warn); } catch { Console.WriteLine (String.Format ("`{0}' is not a valid warning number", wc)); Environment.Exit (1); } } return true; } case "/noconfig": load_default_config = false; return true; case "/nostdlib": case "/nostdlib+": StdLib = false; return true; case "/nostdlib-": StdLib = true; return true; case "/fullpaths": return true; case "/keyfile": if (value == String.Empty) { Console.WriteLine ("{0} requires an argument", arg); Environment.Exit (1); } StrongNameKeyFile = value; return true; case "/keycontainer": if (value == String.Empty) { Console.WriteLine ("{0} requires an argument", arg); Environment.Exit (1); } StrongNameKeyContainer = value; return true; case "/delaysign+": case "/delaysign": StrongNameDelaySign = true; return true; case "/delaysign-": StrongNameDelaySign = false; return true; case "/langversion": switch (value.ToLower (CultureInfo.InvariantCulture)) { case "iso-1": Version = LanguageVersion.ISO_1; return true; case "default": Version = LanguageVersion.Default; return true; case "iso-2": Version = LanguageVersion.ISO_2; return true; case "future": Version = LanguageVersion.Future; return true; } Console.WriteLine ("Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value); Environment.Exit (1); return true; case "/codepage": CodePage = value; return true; } Console.WriteLine ("Failing with : {0}", arg); return false; } static string [] LoadArgs (string file) { StreamReader f; var args = new List<string> (); string line; try { f = new StreamReader (file); } catch { return null; } StringBuilder sb = new StringBuilder (); while ((line = f.ReadLine ()) != null) { int t = line.Length; for (int i = 0; i < t; i++) { char c = line [i]; if (c == '"' || c == '\'') { char end = c; for (i++; i < t; i++) { c = line [i]; if (c == end) break; sb.Append (c); } } else if (c == ' ') { if (sb.Length > 0) { args.Add (sb.ToString ()); sb.Length = 0; } } else sb.Append (c); } if (sb.Length > 0) { args.Add (sb.ToString ()); sb.Length = 0; } } string [] ret_value = new string [args.Count]; args.CopyTo (ret_value, 0); return ret_value; } static string Load (string f) { var native = NativeName (f); if (File.Exists (native)) { using (var sr = new StreamReader (native)) { return sr.ReadToEnd (); } } else return ""; } public static string NativeName (string path) { if (System.IO.Path.DirectorySeparatorChar == '/') return path.Replace ("\\", "/"); else return path.Replace ("/", "\\"); } public class VsCsproj { public string projectGuid; public string output; public string library_output; public string csProjFilename; public double fx_version; public List<VsCsproj> projReferences = new List<VsCsproj> (); public string library; public MsbuildGenerator MsbuildGenerator; } public VsCsproj Csproj; public VsCsproj Generate (Dictionary<string,MsbuildGenerator> projects, bool showWarnings = false) { var generatedProjFile = NativeName (Csproj.csProjFilename); //Console.WriteLine ("Generating: {0}", generatedProjFile); string boot, flags, output_name, built_sources, response, profile; boot = xproject.Element ("boot").Value; flags = xproject.Element ("flags").Value; output_name = xproject.Element ("output").Value; built_sources = xproject.Element ("built_sources").Value; response = xproject.Element ("response").Value; //if (library.EndsWith("-build")) fx_version = "2.0"; // otherwise problem if .NET4.5 is installed, seems. (https://github.com/nikhilk/scriptsharp/issues/156) profile = xproject.Element ("profile").Value; if (string.IsNullOrEmpty (response)) { // Address the issue where entries are missing the fx_version // Should be fixed in the Makefile or elsewhere; this is a workaround //<fx_version>basic</fx_version> //<profile>./../build/deps/mcs.exe.sources.response</profile> //<response></response> response = profile; profile = fx_version; if (response.Contains ("build") || response.Contains ("basic") || response.Contains (profile_2_0)) { fx_version = "2.0"; if (response.Contains (profile_2_0)) profile = "net_2_0"; } if (response.Contains ("build") || response.Contains ("basic") || response.Contains (profile_2_0)) { fx_version = "2.0"; } else if (response.Contains (profile_3_5)) { fx_version = "3.5"; profile = "net_3_5"; } else if (response.Contains (profile_4_0)) { fx_version = "4.0"; profile = "net_4_0"; } else if (response.Contains (profile_4_5)) { fx_version = "4.5"; profile = "net_4_5"; } } // // Prebuild code, might be in inputs, check: // inputs/LIBRARY-PROFILE.pre // inputs/LIBRARY.pre // string prebuild = Load (library + ".pre"); string prebuild_windows, prebuild_unix; int q = library.IndexOf ("-"); if (q != -1) prebuild = prebuild + Load (library.Substring (0, q) + ".pre"); if (prebuild.IndexOf ("@MONO@") != -1){ prebuild_unix = prebuild.Replace ("@MONO@", "mono").Replace ("@CAT@", "cat"); prebuild_windows = prebuild.Replace ("@MONO@", "").Replace ("@CAT@", "type"); } else { prebuild_unix = prebuild.Replace ("jay.exe", "jay"); prebuild_windows = prebuild; } const string condition_unix = "Condition=\" '$(OS)' != 'Windows_NT' \""; const string condition_windows = "Condition=\" '$(OS)' == 'Windows_NT' \""; prebuild = " <PreBuildEvent " + condition_unix + ">" + NewLine + prebuild_unix + NewLine + " </PreBuildEvent>" + NewLine + " <PreBuildEvent " + condition_windows + ">" + NewLine + prebuild_windows + NewLine + " </PreBuildEvent>" + NewLine; var all_args = new Queue<string []> (); all_args.Enqueue (flags.Split ()); while (all_args.Count > 0) { string [] f = all_args.Dequeue (); for (int i = 0; i < f.Length; i++) { if (f [i].Length > 0 && f [i][0] == '-') f [i] = "/" + f [i].Substring (1); if (f [i] [0] == '@') { string [] extra_args; string response_file = f [i].Substring (1); var resp_file_full = Path.Combine (base_dir, response_file); extra_args = LoadArgs (resp_file_full); if (extra_args == null) { Console.WriteLine ("Unable to open response file: " + resp_file_full); Environment.Exit (1); } all_args.Enqueue (extra_args); continue; } if (CSCParseOption (f [i], ref f)) continue; Console.WriteLine ("Failure with {0}", f [i]); Environment.Exit (1); } } string [] source_files; //Console.WriteLine ("Base: {0} res: {1}", base_dir, response); using (var reader = new StreamReader (NativeName (base_dir + "\\" + response))) { source_files = reader.ReadToEnd ().Split (); } Array.Sort (source_files); StringBuilder sources = new StringBuilder (); foreach (string s in source_files) { if (s.Length == 0) continue; string src = s.Replace ("/", "\\"); if (src.StartsWith (@"Test\..\")) src = src.Substring (8, src.Length - 8); sources.AppendFormat (" <Compile Include=\"{0}\" />" + NewLine, src); } source_files = built_sources.Split (); Array.Sort (source_files); foreach (string s in source_files) { if (s.Length == 0) continue; string src = s.Replace ("/", "\\"); if (src.StartsWith (@"Test\..\")) src = src.Substring (8, src.Length - 8); sources.AppendFormat (" <Compile Include=\"{0}\" />" + NewLine, src); } sources.Remove (sources.Length - 1, 1); //if (library == "corlib-build") // otherwise, does not compile on fx_version == 4.0 //{ // references.Add("System.dll"); // references.Add("System.Xml.dll"); //} //if (library == "System.Core-build") // otherwise, slow compile. May be a transient need. //{ // this.ignore_warning.Add(1685); // this.ignore_warning.Add(0436); //} var refs = new StringBuilder (); bool is_test = response.Contains ("_test_"); if (is_test) { // F:\src\mono\mcs\class\lib\net_2_0\nunit.framework.dll // F:\src\mono\mcs\class\SomeProject\SomeProject_test_-net_2_0.csproj var nunitLibPath = string.Format (@"..\lib\{0}\nunit.framework.dll", profile); refs.Append (string.Format (" <Reference Include=\"{0}\" />" + NewLine, nunitLibPath)); } var resources = new StringBuilder (); if (embedded_resources.Count > 0) { resources.AppendFormat (" <ItemGroup>" + NewLine); foreach (var dk in embedded_resources) { resources.AppendFormat (" <EmbeddedResource Include=\"{0}\">" + NewLine, dk.Key); resources.AppendFormat (" <LogicalName>{0}</LogicalName>" + NewLine, dk.Value); resources.AppendFormat (" </EmbeddedResource>" + NewLine); } resources.AppendFormat (" </ItemGroup>" + NewLine); } if (references.Count > 0 || reference_aliases.Count > 0) { // -r:mscorlib.dll -r:System.dll //<ProjectReference Include="..\corlib\corlib-basic.csproj"> // <Project>{155aef28-c81f-405d-9072-9d52780e3e70}</Project> // <Name>corlib-basic</Name> //</ProjectReference> //<ProjectReference Include="..\System\System-basic.csproj"> // <Project>{2094e859-db2f-481f-9630-f89d31d9ed48}</Project> // <Name>System-basic</Name> //</ProjectReference> var refdistinct = references.Distinct (); foreach (string r in refdistinct) { var match = GetMatchingCsproj (Path.GetFileName (r), projects); if (match != null) { AddProjectReference (refs, Csproj, match, r, null); } else { if (showWarnings){ Console.WriteLine ("{0}: Could not find a matching project reference for {1}", library, Path.GetFileName (r)); Console.WriteLine (" --> Adding reference with hintpath instead"); } refs.Append (" <Reference Include=\"" + r + "\">" + NewLine); refs.Append (" <SpecificVersion>False</SpecificVersion>" + NewLine); refs.Append (" <HintPath>" + r + "</HintPath>" + NewLine); refs.Append (" <Private>False</Private>" + NewLine); refs.Append (" </Reference>" + NewLine); } } foreach (string r in reference_aliases) { int index = r.IndexOf ('='); string alias = r.Substring (0, index); string assembly = r.Substring (index + 1); var match = GetMatchingCsproj (assembly, projects, explicitPath: true); if (match != null) { AddProjectReference (refs, Csproj, match, r, alias); } else { throw new NotSupportedException (string.Format ("From {0}, could not find a matching project reference for {1}", library, r)); refs.Append (" <Reference Include=\"" + assembly + "\">" + NewLine); refs.Append (" <SpecificVersion>False</SpecificVersion>" + NewLine); refs.Append (" <HintPath>" + r + "</HintPath>" + NewLine); refs.Append (" <Aliases>" + alias + "</Aliases>" + NewLine); refs.Append (" </Reference>" + NewLine); } } } // Possible inputs: // ../class/lib/build/tmp/System.Xml.dll [No longer possible, we should be removing this from order.xml] // /class/lib/basic/System.Core.dll // <library_output>mcs.exe</library_output> string build_output_dir; if (LibraryOutput.Contains ("/")) build_output_dir = Path.GetDirectoryName (LibraryOutput); else build_output_dir = "bin\\Debug\\" + library; string postbuild_unix = string.Empty; string postbuild_windows = string.Empty; var postbuild = " <PostBuildEvent " + condition_unix + ">" + NewLine + postbuild_unix + NewLine + " </PostBuildEvent>" + NewLine + " <PostBuildEvent " + condition_windows + ">" + NewLine + postbuild_windows + NewLine + " </PostBuildEvent>"; bool basic_or_build = (library.Contains ("-basic") || library.Contains ("-build")); // // Replace the template values // string strongNameSection = ""; if (StrongNameKeyFile != null){ strongNameSection = String.Format ( " <PropertyGroup>" + NewLine + " <SignAssembly>true</SignAssembly>" + NewLine + "{1}" + " </PropertyGroup>" + NewLine + " <PropertyGroup>" + NewLine + " <AssemblyOriginatorKeyFile>{0}</AssemblyOriginatorKeyFile>" + NewLine + " </PropertyGroup>", StrongNameKeyFile, StrongNameDelaySign ? " <DelaySign>true</DelaySign>" + NewLine : ""); } Csproj.output = template. Replace ("@SIGNATURE@", strongNameSection). Replace ("@PROJECTGUID@", Csproj.projectGuid). Replace ("@DEFINES@", defines.ToString ()). Replace ("@DISABLEDWARNINGS@", string.Join (",", (from i in ignore_warning select i.ToString ()).ToArray ())). //Replace("@NOSTDLIB@", (basic_or_build || (!StdLib)) ? "<NoStdLib>true</NoStdLib>" : string.Empty). Replace ("@NOSTDLIB@", "<NoStdLib>" + (!StdLib).ToString () + "</NoStdLib>"). Replace ("@NOCONFIG@", "<NoConfig>" + (!load_default_config).ToString () + "</NoConfig>"). Replace ("@ALLOWUNSAFE@", Unsafe ? "<AllowUnsafeBlocks>true</AllowUnsafeBlocks>" : ""). Replace ("@FX_VERSION", fx_version). Replace ("@ASSEMBLYNAME@", Path.GetFileNameWithoutExtension (output_name)). Replace ("@OUTPUTDIR@", build_output_dir). Replace ("@DEFINECONSTANTS@", defines.ToString ()). Replace ("@DEBUG@", want_debugging_support ? "true" : "false"). Replace ("@DEBUGTYPE@", want_debugging_support ? "full" : "pdbonly"). Replace ("@REFERENCES@", refs.ToString ()). Replace ("@PREBUILD@", prebuild). Replace ("@POSTBUILD@", postbuild). //Replace ("@ADDITIONALLIBPATHS@", String.Format ("<AdditionalLibPaths>{0}</AdditionalLibPaths>", string.Join (",", libs.ToArray ()))). Replace ("@ADDITIONALLIBPATHS@", String.Empty). Replace ("@RESOURCES@", resources.ToString ()). Replace ("@OPTIMIZE@", Optimize ? "true" : "false"). Replace ("@SOURCES@", sources.ToString ()); //Console.WriteLine ("Generated {0}", ofile.Replace ("\\", "/")); using (var o = new StreamWriter (generatedProjFile)) { o.WriteLine (Csproj.output); } return Csproj; } void AddProjectReference (StringBuilder refs, VsCsproj result, MsbuildGenerator match, string r, string alias) { refs.AppendFormat (" <ProjectReference Include=\"{0}\">{1}", GetRelativePath (result.csProjFilename, match.CsprojFilename), NewLine); refs.Append (" <Project>" + match.projectGuid + "</Project>" + NewLine); refs.Append (" <Name>" + Path.GetFileNameWithoutExtension (match.CsprojFilename.Replace ('\\', Path.DirectorySeparatorChar)) + "</Name>" + NewLine); if (alias != null) refs.Append (" <Aliases>" + alias + "</Aliases>"); refs.Append (" </ProjectReference>" + NewLine); if (!result.projReferences.Contains (match.Csproj)) result.projReferences.Add (match.Csproj); } public static string GetRelativePath (string from, string to) { from = from.Replace ("\\", "/"); to = to.Replace ("\\", "/"); var fromUri = new Uri (Path.GetFullPath (from)); var toUri = new Uri (Path.GetFullPath (to)); var ret = fromUri.MakeRelativeUri (toUri).ToString ().Replace ("%5C", "\x5c"); return ret; } MsbuildGenerator GetMatchingCsproj (string dllReferenceName, Dictionary<string,MsbuildGenerator> projects, bool explicitPath = false) { // libDir would be "./../../class/lib/net_4_5 for example // project if (!dllReferenceName.EndsWith (".dll")) dllReferenceName += ".dll"; if (explicitPath){ var probe = Path.GetFullPath (Path.Combine (base_dir, dllReferenceName)); foreach (var project in projects){ if (probe == project.Value.AbsoluteLibraryOutput) return project.Value; } } // not explicit, search for the library in the lib path order specified foreach (var libDir in libs) { var abs = Path.GetFullPath (Path.Combine (base_dir, libDir)); foreach (var project in projects){ var probe = Path.Combine (abs, dllReferenceName); if (probe == project.Value.AbsoluteLibraryOutput) return project.Value; } } Console.WriteLine ("Did not find referenced {0} with libs={1}", dllReferenceName, String.Join (", ", libs)); foreach (var p in projects) { Console.WriteLine (" => {0}", p.Value.AbsoluteLibraryOutput); } return null; } } public class Driver { static IEnumerable<XElement> GetProjects (bool full = false) { XDocument doc = XDocument.Load ("order.xml"); foreach (XElement project in doc.Root.Elements ()) { string dir = project.Attribute ("dir").Value; string library = project.Attribute ("library").Value; var profile = project.Element ("profile").Value; // // Do only class libraries for now // if (!(dir.StartsWith ("class") || dir.StartsWith ("mcs") || dir.StartsWith ("basic"))) continue; if (full){ if (!library.Contains ("tests")) yield return project; continue; } // // Do not do 2.1, it is not working yet // Do not do basic, as there is no point (requires a system mcs to be installed). // if (library.Contains ("moonlight") || library.Contains ("-basic") || library.EndsWith ("bootstrap") || library.Contains ("build")) continue; // The next ones are to make debugging easier for now if (profile == "basic") continue; if (profile != "net_4_5" || library.Contains ("tests")) continue; yield return project; } } static void Main (string [] args) { if (!File.Exists ("genproj.cs")) { Console.WriteLine ("This command must be executed from mono/msvc/scripts"); Environment.Exit (1); } if (args.Length == 1 && args [0].ToLower ().Contains ("-h")) { Console.WriteLine ("Usage:"); Console.WriteLine ("genproj.exe [visual_studio_release] [output_full_solutions]"); Console.WriteLine ("If output_full_solutions is false, only the main System*.dll"); Console.WriteLine (" assemblies (and dependencies) is included in the solution."); Console.WriteLine ("Example:"); Console.WriteLine ("genproj.exe 2012 false"); Console.WriteLine ("genproj.exe with no arguments is equivalent to 'genproj.exe 2012 true'\n\n"); Console.WriteLine ("genproj.exe deps"); Console.WriteLine ("Generates a Makefile dependency file from the projects input"); Environment.Exit (0); } var slnVersion = (args.Length > 0) ? args [0] : "2012"; bool fullSolutions = (args.Length > 1) ? bool.Parse (args [1]) : true; // To generate makefile depenedencies var makefileDeps = (args.Length > 0 && args [0] == "deps"); var sln_gen = new SlnGenerator (slnVersion); var two_sln_gen = new SlnGenerator (slnVersion); var four_sln_gen = new SlnGenerator (slnVersion); var three_five_sln_gen = new SlnGenerator (slnVersion); var four_five_sln_gen = new SlnGenerator (slnVersion); var projects = new Dictionary<string,MsbuildGenerator> (); var duplicates = new List<string> (); foreach (var project in GetProjects (makefileDeps)) { var library_output = project.Element ("library_output").Value; projects [library_output] = new MsbuildGenerator (project); } foreach (var project in GetProjects (makefileDeps)){ var library_output = project.Element ("library_output").Value; var gen = projects [library_output]; try { var csproj = gen.Generate (projects); var csprojFilename = csproj.csProjFilename; if (!sln_gen.ContainsProjectIdentifier (csproj.library)) { sln_gen.Add (csproj); } else { duplicates.Add (csprojFilename); } } catch (Exception e) { Console.WriteLine ("Error in {0}\n{1}", project, e); } } Func<MsbuildGenerator.VsCsproj, bool> additionalFilter; additionalFilter = fullSolutions ? (Func<MsbuildGenerator.VsCsproj, bool>)null : IsCommonLibrary; FillSolution (two_sln_gen, MsbuildGenerator.profile_2_0, projects.Values, additionalFilter); FillSolution (four_five_sln_gen, MsbuildGenerator.profile_4_5, projects.Values, additionalFilter); FillSolution (four_sln_gen, MsbuildGenerator.profile_4_0, projects.Values, additionalFilter); FillSolution (three_five_sln_gen, MsbuildGenerator.profile_3_5, projects.Values, additionalFilter); var sb = new StringBuilder (); sb.AppendLine ("WARNING: Skipped some project references, apparent duplicates in order.xml:"); foreach (var item in duplicates) { sb.AppendLine (item); } Console.WriteLine (sb.ToString ()); WriteSolution (two_sln_gen, MakeSolutionName (MsbuildGenerator.profile_2_0)); WriteSolution (three_five_sln_gen, MakeSolutionName (MsbuildGenerator.profile_3_5)); WriteSolution (four_sln_gen, MakeSolutionName (MsbuildGenerator.profile_4_0)); WriteSolution (four_five_sln_gen, MakeSolutionName (MsbuildGenerator.profile_4_5)); if (makefileDeps){ const string classDirPrefix = "./../../"; Console.WriteLine ("here {0}", sln_gen.libraries.Count); foreach (var p in sln_gen.libraries){ string rebasedOutput = RebaseToClassDirectory (MsbuildGenerator.GetRelativePath ("../../mcs/class", p.library_output)); Console.Write ("{0}: ", rebasedOutput); foreach (var r in p.projReferences){ var lo = r.library_output; if (lo.StartsWith (classDirPrefix)) lo = lo.Substring (classDirPrefix.Length); else lo = "<<ERROR-dependency is not a class library>>"; Console.Write ("{0} ", lo); } Console.Write ("\n\t(cd {0}; make {1})", p.MsbuildGenerator.dir, p.library_output); Console.WriteLine ("\n"); } } // A few other optional solutions // Solutions with 'everything' and the most common libraries used in development may be of interest //WriteSolution (sln_gen, "mcs_full.sln"); //WriteSolution (small_full_sln_gen, "small_full.sln"); // The following may be useful if lacking visual studio or MonoDevelop, to bootstrap mono compiler self-hosting //WriteSolution (basic_sln_gen, "mcs_basic.sln"); //WriteSolution (build_sln_gen, "mcs_build.sln"); } // Rebases a path, assuming that execution is taking place in the "class" subdirectory, // so it strips ../class/ from a path, which is a no-op static string RebaseToClassDirectory (string path) { const string prefix = "../class/"; int p = path.IndexOf (prefix); if (p == -1) return path; return path.Substring (0, p) + path.Substring (p+prefix.Length); return path; } static string MakeSolutionName (string profileTag) { return "net" + profileTag + ".sln"; } static void FillSolution (SlnGenerator solution, string profileString, IEnumerable<MsbuildGenerator> projects, Func<MsbuildGenerator.VsCsproj, bool> additionalFilter = null) { foreach (var generator in projects) { var vsCsproj = generator.Csproj; if (!vsCsproj.library.Contains (profileString)) continue; if (additionalFilter != null && !additionalFilter (vsCsproj)) continue; var csprojFilename = vsCsproj.csProjFilename; if (!solution.ContainsProjectIdentifier (vsCsproj.library)) { solution.Add (vsCsproj); RecursiveAddProj (solution, vsCsproj); } } } static void RecursiveAddProj (SlnGenerator solution, MsbuildGenerator.VsCsproj vsCsproj, int recursiveDepth = 1) { const int max_recursive = 16; if (recursiveDepth > max_recursive) throw new Exception (string.Format ("Reached {0} levels of project dependency", max_recursive)); foreach (var projRef in vsCsproj.projReferences) { if (!solution.ContainsProjectIdentifier (projRef.library)) { solution.Add (projRef); RecursiveAddProj (solution, projRef, recursiveDepth + 1); } } } static void WriteSolution (SlnGenerator sln_gen, string slnfilename) { Console.WriteLine (String.Format ("Writing solution {1}, with {0} projects", sln_gen.Count, slnfilename)); sln_gen.Write (slnfilename); } static bool IsCommonLibrary (MsbuildGenerator.VsCsproj proj) { var library = proj.library; //if (library.Contains ("-basic")) // return true; //if (library.Contains ("-build")) // return true; //if (library.StartsWith ("corlib")) // return true; if (library.StartsWith ("System-")) return true; if (library.StartsWith ("System.Xml")) return true; if (library.StartsWith ("System.Secu")) return true; if (library.StartsWith ("System.Configuration")) return true; if (library.StartsWith ("System.Core")) return true; //if (library.StartsWith ("Mono.")) // return true; return false; } }
30.128162
174
0.65314
[ "Apache-2.0" ]
Distrotech/mono
msvc/scripts/genproj.cs
35,732
C#
using System.ComponentModel.DataAnnotations; namespace Commander.Dtos { public class CommandUpdateDto : CommandCreateDto { } }
15.666667
52
0.744681
[ "Apache-2.0" ]
JamesPartsafas/commander-app
Dtos/CommandUpdateDto.cs
141
C#
using MassTransit; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace ServiceTemplate { public class HostedService : IHostedService { private readonly IBusControl _busControl; public HostedService(IBusControl busControl) { _busControl = busControl; } public Task StartAsync(CancellationToken cancellationToken) { return _busControl.StartAsync(cancellationToken); } public Task StopAsync(CancellationToken cancellationToken) { return _busControl.StopAsync(cancellationToken); } } }
24.516129
68
0.659211
[ "MIT" ]
swpuzhang/CleanGameArchitecture
Services/ServiceTemplate/HostedService.cs
762
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using ICSharpCode.CodeConverter.Shared; using ICSharpCode.CodeConverter.Util; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SyntaxFactory = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using VBasic = Microsoft.CodeAnalysis.VisualBasic; using VBSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax; using static ICSharpCode.CodeConverter.CSharp.SyntaxKindExtensions; namespace ICSharpCode.CodeConverter.CSharp { /// <summary> /// Executable statements - which includes executable blocks such as if statements /// Maintains state relevant to the called method-like object. A fresh one must be used for each method, and the same one must be reused for statements in the same method /// </summary> internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVisitor<SyntaxList<StatementSyntax>> { private readonly VBasic.VisualBasicSyntaxNode _methodNode; private readonly SemanticModel _semanticModel; private readonly CommentConvertingVisitorWrapper<CSharpSyntaxNode> _expressionVisitor; private readonly Stack<ExpressionSyntax> _withBlockLhs; private readonly HashSet<string> _extraUsingDirectives; private readonly MethodsWithHandles _methodsWithHandles; private readonly HashSet<string> _generatedNames = new HashSet<string>(); public bool IsIterator { get; set; } public IdentifierNameSyntax ReturnVariable { get; set; } public bool HasReturnVariable => ReturnVariable != null; public VBasic.VisualBasicSyntaxVisitor<SyntaxList<StatementSyntax>> CommentConvertingVisitor { get; } private CommonConversions CommonConversions { get; } public MethodBodyExecutableStatementVisitor(VBasic.VisualBasicSyntaxNode methodNode, SemanticModel semanticModel, CommentConvertingVisitorWrapper<CSharpSyntaxNode> expressionVisitor, CommonConversions commonConversions, Stack<ExpressionSyntax> withBlockLhs, HashSet<string> extraUsingDirectives, AdditionalLocals additionalLocals, MethodsWithHandles methodsWithHandles, TriviaConverter triviaConverter) { _methodNode = methodNode; _semanticModel = semanticModel; _expressionVisitor = expressionVisitor; CommonConversions = commonConversions; _withBlockLhs = withBlockLhs; _extraUsingDirectives = extraUsingDirectives; _methodsWithHandles = methodsWithHandles; var byRefParameterVisitor = new ByRefParameterVisitor(this, additionalLocals, semanticModel, _generatedNames); CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(byRefParameterVisitor, triviaConverter); } public override SyntaxList<StatementSyntax> DefaultVisit(SyntaxNode node) { throw new NotImplementedException($"Conversion for {VBasic.VisualBasicExtensions.Kind(node)} not implemented, please report this issue") .WithNodeInformation(node); } public override SyntaxList<StatementSyntax> VisitStopOrEndStatement(VBSyntax.StopOrEndStatementSyntax node) { return SingleStatement(SyntaxFactory.ParseStatement(ConvertStopOrEndToCSharpStatementText(node))); } private string ConvertStopOrEndToCSharpStatementText(VBSyntax.StopOrEndStatementSyntax node) { switch (VBasic.VisualBasicExtensions.Kind(node.StopOrEndKeyword)) { case VBasic.SyntaxKind.StopKeyword: _extraUsingDirectives.Add("System.Diagnostics"); return "Debugger.Break();"; case VBasic.SyntaxKind.EndKeyword: _extraUsingDirectives.Add("System"); return "Environment.Exit(0);"; default: throw new NotImplementedException(node.StopOrEndKeyword.Kind() + " not implemented!"); } } public override SyntaxList<StatementSyntax> VisitLocalDeclarationStatement(VBSyntax.LocalDeclarationStatementSyntax node) { var modifiers = CommonConversions.ConvertModifiers(node.Declarators[0].Names[0], node.Modifiers, TokenContext.Local); var isConst = modifiers.Any(a => a.Kind() == SyntaxKind.ConstKeyword); var declarations = new List<LocalDeclarationStatementSyntax>(); foreach (var declarator in node.Declarators) foreach (var decl in CommonConversions.SplitVariableDeclarations(declarator, preferExplicitType: isConst)) declarations.Add(SyntaxFactory.LocalDeclarationStatement(modifiers, decl.Value)); return SyntaxFactory.List<StatementSyntax>(declarations); } public override SyntaxList<StatementSyntax> VisitAddRemoveHandlerStatement(VBSyntax.AddRemoveHandlerStatementSyntax node) { var syntaxKind = ConvertAddRemoveHandlerToCSharpSyntaxKind(node); return SingleStatement(SyntaxFactory.AssignmentExpression(syntaxKind, (ExpressionSyntax)node.EventExpression.Accept(_expressionVisitor), (ExpressionSyntax)node.DelegateExpression.Accept(_expressionVisitor))); } private static SyntaxKind ConvertAddRemoveHandlerToCSharpSyntaxKind(VBSyntax.AddRemoveHandlerStatementSyntax node) { switch (node.Kind()) { case VBasic.SyntaxKind.AddHandlerStatement: return SyntaxKind.AddAssignmentExpression; case VBasic.SyntaxKind.RemoveHandlerStatement: return SyntaxKind.SubtractAssignmentExpression; default: throw new NotImplementedException(node.Kind() + " not implemented!"); } } public override SyntaxList<StatementSyntax> VisitExpressionStatement(VBSyntax.ExpressionStatementSyntax node) { if (node.Expression is VBSyntax.InvocationExpressionSyntax invoke && invoke.Expression is VBSyntax.MemberAccessExpressionSyntax access) { if (access.Expression is VBSyntax.MyBaseExpressionSyntax && access.Name.Identifier.ValueText.Equals("Finalize", StringComparison.OrdinalIgnoreCase)) { return new SyntaxList<StatementSyntax>(); } else if (CommonConversions.InMethodCalledInitializeComponent(node) && access.Name.Identifier.ValueText.Equals("ResumeLayout", StringComparison.OrdinalIgnoreCase)) { var eventSubscriptionStatements = _methodsWithHandles.GetPreResumeLayoutEventHandlers(); if (eventSubscriptionStatements.Any()) { return SyntaxFactory.List(eventSubscriptionStatements.Concat(SingleStatement((ExpressionSyntax)node.Expression.Accept(_expressionVisitor)))); } } } return SingleStatement((ExpressionSyntax)node.Expression.Accept(_expressionVisitor)); } public override SyntaxList<StatementSyntax> VisitAssignmentStatement(VBSyntax.AssignmentStatementSyntax node) { var lhs = (ExpressionSyntax)node.Left.Accept(_expressionVisitor); var lOperation = _semanticModel.GetOperation(node.Left); //Already dealt with by call to the same method in VisitInvocationExpression if (CommonConversions.GetParameterizedPropertyAccessMethod(lOperation, out var _) != null) return SingleStatement(lhs); var rhs = (ExpressionSyntax)node.Right.Accept(_expressionVisitor); if (node.Left is VBSyntax.IdentifierNameSyntax id && _methodNode is VBSyntax.MethodBlockSyntax mb && HasReturnVariable && id.Identifier.ValueText.Equals(mb.SubOrFunctionStatement.Identifier.ValueText, StringComparison.OrdinalIgnoreCase)) { lhs = ReturnVariable; } if (node.IsKind(VBasic.SyntaxKind.ExponentiateAssignmentStatement)) { rhs = SyntaxFactory.InvocationExpression( SyntaxFactory.ParseExpression($"{nameof(Math)}.{nameof(Math.Pow)}"), ExpressionSyntaxExtensions.CreateArgList(lhs, rhs)); } var kind = node.Kind().ConvertToken(TokenContext.Local); var assignment = SyntaxFactory.AssignmentExpression(kind, lhs, rhs); var postAssignment = GetPostAssignmentStatements(node); return postAssignment.Insert(0, SyntaxFactory.ExpressionStatement(assignment)); } private SyntaxList<StatementSyntax> GetPostAssignmentStatements(VBSyntax.AssignmentStatementSyntax node) { var potentialPropertySymbol = _semanticModel.GetSymbolInfo(node.Left).ExtractBestMatch(); return _methodsWithHandles.GetPostAssignmentStatements(node, potentialPropertySymbol); } public override SyntaxList<StatementSyntax> VisitEraseStatement(VBSyntax.EraseStatementSyntax node) { var eraseStatements = node.Expressions.Select<VBSyntax.ExpressionSyntax, StatementSyntax>(arrayExpression => { var lhs = arrayExpression.Accept(_expressionVisitor); var rhs = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); var assignmentExpressionSyntax = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)lhs, rhs); return SyntaxFactory.ExpressionStatement(assignmentExpressionSyntax); }); return SyntaxFactory.List(eraseStatements); } public override SyntaxList<StatementSyntax> VisitReDimStatement(VBSyntax.ReDimStatementSyntax node) { return SyntaxFactory.List(node.Clauses.SelectMany(arrayExpression => ConvertRedimClause(arrayExpression))); } /// <remarks> /// RedimClauseSyntax isn't an executable statement, therefore this isn't a "Visit" method. /// Since it returns multiple statements it's easiest for it to be here in the current architecture. /// </remarks> private SyntaxList<StatementSyntax> ConvertRedimClause(VBSyntax.RedimClauseSyntax node) { bool preserve = node.Parent is VBSyntax.ReDimStatementSyntax rdss && rdss.PreserveKeyword.IsKind(VBasic.SyntaxKind.PreserveKeyword); var csTargetArrayExpression = (ExpressionSyntax) node.Expression.Accept(_expressionVisitor); var convertedBounds = CommonConversions.ConvertArrayBounds(node.ArrayBounds).ToList(); var newArrayAssignment = CreateNewArrayAssignment(node.Expression, csTargetArrayExpression, convertedBounds, node.SpanStart); if (!preserve) return SingleStatement(newArrayAssignment); var oldTargetName = GetUniqueVariableNameInScope(node, "old" + csTargetArrayExpression.ToString().ToPascalCase()); var oldArrayAssignment = CreateLocalVariableDeclarationAndAssignment(oldTargetName, csTargetArrayExpression); var oldTargetExpression = SyntaxFactory.IdentifierName(oldTargetName); var arrayCopyIfNotNull = CreateConditionalArrayCopy(node, oldTargetExpression, csTargetArrayExpression, convertedBounds); return SyntaxFactory.List(new StatementSyntax[] {oldArrayAssignment, newArrayAssignment, arrayCopyIfNotNull}); } /// <summary> /// Cut down version of Microsoft.VisualBasic.CompilerServices.Utils.CopyArray /// </summary> private IfStatementSyntax CreateConditionalArrayCopy(VBasic.VisualBasicSyntaxNode originalVbNode, IdentifierNameSyntax sourceArrayExpression, ExpressionSyntax targetArrayExpression, List<ExpressionSyntax> convertedBounds) { var sourceLength = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, sourceArrayExpression, SyntaxFactory.IdentifierName("Length")); var arrayCopyStatement = convertedBounds.Count == 1 ? CreateArrayCopyWithMinOfLengths(sourceArrayExpression, sourceLength, targetArrayExpression, convertedBounds.Single()) : CreateArrayCopy(originalVbNode, sourceArrayExpression, sourceLength, targetArrayExpression, convertedBounds); var oldTargetNotEqualToNull = SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression, sourceArrayExpression, SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); return SyntaxFactory.IfStatement(oldTargetNotEqualToNull, arrayCopyStatement); } /// <summary> /// Array copy for multiple array dimensions represented by <paramref name="convertedBounds"/> /// </summary> /// <remarks> /// Exception cases will sometimes silently succeed in the converted code, /// but existing VB code relying on the exception thrown from a multidimensional redim preserve on /// different rank arrays is hopefully rare enough that it's worth saving a few lines of code /// </remarks> private StatementSyntax CreateArrayCopy(VBasic.VisualBasicSyntaxNode originalVbNode, IdentifierNameSyntax sourceArrayExpression, MemberAccessExpressionSyntax sourceLength, ExpressionSyntax targetArrayExpression, ICollection convertedBounds) { var lastSourceLengthArgs = ExpressionSyntaxExtensions.CreateArgList(CommonConversions.Literal(convertedBounds.Count - 1)); var sourceLastRankLength = SyntaxFactory.InvocationExpression( SyntaxFactory.ParseExpression($"{sourceArrayExpression.Identifier}.GetLength"), lastSourceLengthArgs); var targetLastRankLength = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression($"{targetArrayExpression}.GetLength"), lastSourceLengthArgs); var length = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("Math.Min"), ExpressionSyntaxExtensions.CreateArgList(sourceLastRankLength, targetLastRankLength)); var loopVariableName = GetUniqueVariableNameInScope(originalVbNode, "i"); var loopVariableIdentifier = SyntaxFactory.IdentifierName(loopVariableName); var sourceStartForThisIteration = SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression, loopVariableIdentifier, sourceLastRankLength); var targetStartForThisIteration = SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression, loopVariableIdentifier, targetLastRankLength); var arrayCopy = CreateArrayCopyWithStartingPoints(sourceArrayExpression, sourceStartForThisIteration, targetArrayExpression, targetStartForThisIteration, length); var sourceArrayCount = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, sourceLength, sourceLastRankLength), CommonConversions.Literal(1)); return CreateForZeroToValueLoop(loopVariableIdentifier, arrayCopy, sourceArrayCount); } private ForStatementSyntax CreateForZeroToValueLoop(SimpleNameSyntax loopVariableIdentifier, StatementSyntax loopStatement, ExpressionSyntax inclusiveLoopUpperBound) { var loopVariableAssignment = CommonConversions.CreateVariableDeclarationAndAssignment(loopVariableIdentifier.Identifier.Text, CommonConversions.Literal(0)); var lessThanSourceBounds = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, loopVariableIdentifier, inclusiveLoopUpperBound); var incrementors = SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>( SyntaxFactory.PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, loopVariableIdentifier)); var forStatementSyntax = SyntaxFactory.ForStatement(loopVariableAssignment, SyntaxFactory.SeparatedList<ExpressionSyntax>(), lessThanSourceBounds, incrementors, loopStatement); return forStatementSyntax; } private static ExpressionStatementSyntax CreateArrayCopyWithMinOfLengths( IdentifierNameSyntax sourceExpression, ExpressionSyntax sourceLength, ExpressionSyntax targetExpression, ExpressionSyntax targetLength) { var minLength = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("Math.Min"), ExpressionSyntaxExtensions.CreateArgList(targetLength, sourceLength)); var copyArgList = ExpressionSyntaxExtensions.CreateArgList(sourceExpression, targetExpression, minLength); var arrayCopy = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("Array.Copy"), copyArgList); return SyntaxFactory.ExpressionStatement(arrayCopy); } private static ExpressionStatementSyntax CreateArrayCopyWithStartingPoints( IdentifierNameSyntax sourceExpression, ExpressionSyntax sourceStart, ExpressionSyntax targetExpression, ExpressionSyntax targetStart, ExpressionSyntax length) { var copyArgList = ExpressionSyntaxExtensions.CreateArgList(sourceExpression, sourceStart, targetExpression, targetStart, length); var arrayCopy = SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression("Array.Copy"), copyArgList); return SyntaxFactory.ExpressionStatement(arrayCopy); } private ExpressionStatementSyntax CreateNewArrayAssignment(VBSyntax.ExpressionSyntax vbArrayExpression, ExpressionSyntax csArrayExpression, List<ExpressionSyntax> convertedBounds, int nodeSpanStart) { var arrayRankSpecifierSyntax = SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SeparatedList(convertedBounds)); var convertedType = (IArrayTypeSymbol) _semanticModel.GetTypeInfo(vbArrayExpression).ConvertedType; var typeSyntax = GetTypeSyntaxFromTypeSymbol(convertedType.ElementType, nodeSpanStart); var arrayCreation = SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(typeSyntax, SyntaxFactory.SingletonList(arrayRankSpecifierSyntax))); var assignmentExpressionSyntax = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, csArrayExpression, arrayCreation); var newArrayAssignment = SyntaxFactory.ExpressionStatement(assignmentExpressionSyntax); return newArrayAssignment; } private TypeSyntax GetTypeSyntaxFromTypeSymbol(ITypeSymbol convertedType, int nodeSpanStart) { var predefinedKeywordKind = convertedType.SpecialType.GetPredefinedKeywordKind(); if (predefinedKeywordKind != SyntaxKind.None) return SyntaxFactory.PredefinedType(SyntaxFactory.Token(predefinedKeywordKind)); return SyntaxFactory.ParseTypeName(convertedType.ToMinimalCSharpDisplayString(_semanticModel, nodeSpanStart)); } public override SyntaxList<StatementSyntax> VisitThrowStatement(VBSyntax.ThrowStatementSyntax node) { return SingleStatement(SyntaxFactory.ThrowStatement((ExpressionSyntax)node.Expression?.Accept(_expressionVisitor))); } public override SyntaxList<StatementSyntax> VisitReturnStatement(VBSyntax.ReturnStatementSyntax node) { if (IsIterator) return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement)); return SingleStatement(SyntaxFactory.ReturnStatement((ExpressionSyntax)node.Expression?.Accept(_expressionVisitor))); } public override SyntaxList<StatementSyntax> VisitContinueStatement(VBSyntax.ContinueStatementSyntax node) { return SingleStatement(SyntaxFactory.ContinueStatement()); } public override SyntaxList<StatementSyntax> VisitYieldStatement(VBSyntax.YieldStatementSyntax node) { return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, (ExpressionSyntax)node.Expression?.Accept(_expressionVisitor))); } public override SyntaxList<StatementSyntax> VisitExitStatement(VBSyntax.ExitStatementSyntax node) { switch (VBasic.VisualBasicExtensions.Kind(node.BlockKeyword)) { case VBasic.SyntaxKind.SubKeyword: return SingleStatement(SyntaxFactory.ReturnStatement()); case VBasic.SyntaxKind.FunctionKeyword: VBasic.VisualBasicSyntaxNode typeContainer = (VBasic.VisualBasicSyntaxNode)node.Ancestors().OfType<VBSyntax.LambdaExpressionSyntax>().FirstOrDefault() ?? node.Ancestors().OfType<VBSyntax.MethodBlockSyntax>().FirstOrDefault(); var info = typeContainer.TypeSwitch( (VBSyntax.LambdaExpressionSyntax e) => _semanticModel.GetTypeInfo(e).Type.GetReturnType(), (VBSyntax.MethodBlockSyntax e) => { var type = (TypeSyntax)e.SubOrFunctionStatement.AsClause?.Type.Accept(_expressionVisitor) ?? SyntaxFactory.ParseTypeName("object"); return _semanticModel.GetSymbolInfo(type).Symbol?.GetReturnType(); } ); ExpressionSyntax expr; if (HasReturnVariable) expr = ReturnVariable; else if (info == null) expr = null; else if (info.IsReferenceType) expr = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); else if (info.CanBeReferencedByName) expr = SyntaxFactory.DefaultExpression(SyntaxFactory.ParseTypeName(info.ToMinimalCSharpDisplayString(_semanticModel, node.SpanStart))); else throw new NotSupportedException(); return SingleStatement(SyntaxFactory.ReturnStatement(expr)); default: return SingleStatement(SyntaxFactory.BreakStatement()); } } public override SyntaxList<StatementSyntax> VisitRaiseEventStatement(VBSyntax.RaiseEventStatementSyntax node) { var argumentListSyntax = (ArgumentListSyntax)node.ArgumentList.Accept(_expressionVisitor); var symbolInfo = _semanticModel.GetSymbolInfo(node.Name).ExtractBestMatch() as IEventSymbol; if (symbolInfo?.RaiseMethod != null) { return SingleStatement(SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName($"On{symbolInfo.Name}"), argumentListSyntax)); } var memberBindingExpressionSyntax = SyntaxFactory.MemberBindingExpression(SyntaxFactory.IdentifierName("Invoke")); var conditionalAccessExpressionSyntax = SyntaxFactory.ConditionalAccessExpression( (NameSyntax)node.Name.Accept(_expressionVisitor), SyntaxFactory.InvocationExpression(memberBindingExpressionSyntax, argumentListSyntax) ); return SingleStatement( conditionalAccessExpressionSyntax ); } public override SyntaxList<StatementSyntax> VisitSingleLineIfStatement(VBSyntax.SingleLineIfStatementSyntax node) { var condition = (ExpressionSyntax)node.Condition.Accept(_expressionVisitor); var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); ElseClauseSyntax elseClause = null; if (node.ElseClause != null) { var elseBlock = SyntaxFactory.Block(node.ElseClause.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); elseClause = SyntaxFactory.ElseClause(elseBlock.UnpackNonNestedBlock()); } return SingleStatement(SyntaxFactory.IfStatement(condition, block.UnpackNonNestedBlock(), elseClause)); } public override SyntaxList<StatementSyntax> VisitMultiLineIfBlock(VBSyntax.MultiLineIfBlockSyntax node) { var condition = (ExpressionSyntax)node.IfStatement.Condition.Accept(_expressionVisitor); var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); ElseClauseSyntax elseClause = null; if (node.ElseBlock != null) { var elseBlock = SyntaxFactory.Block(node.ElseBlock.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); elseClause = SyntaxFactory.ElseClause(elseBlock.UnpackPossiblyNestedBlock());// so that you get a neat "else if" at the end } foreach (var elseIf in node.ElseIfBlocks.Reverse()) { var elseBlock = SyntaxFactory.Block(elseIf.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); var ifStmt = SyntaxFactory.IfStatement((ExpressionSyntax)elseIf.ElseIfStatement.Condition.Accept(_expressionVisitor), elseBlock.UnpackNonNestedBlock(), elseClause); elseClause = SyntaxFactory.ElseClause(ifStmt); } return SingleStatement(SyntaxFactory.IfStatement(condition, block.UnpackNonNestedBlock(), elseClause)); } public override SyntaxList<StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node) { var stmt = node.ForStatement; ExpressionSyntax startValue = (ExpressionSyntax)stmt.FromValue.Accept(_expressionVisitor); VariableDeclarationSyntax declaration = null; ExpressionSyntax id; if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax) { var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable; declaration = CommonConversions.SplitVariableDeclarations(v).Values.Single(); declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue)))); id = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier); } else { id = (ExpressionSyntax)stmt.ControlVariable.Accept(_expressionVisitor); var symbol = _semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol; if (symbol != null && !_semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any()) { declaration = CommonConversions.CreateVariableDeclarationAndAssignment(symbol.Name, startValue); } else { startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue); } } var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(_expressionVisitor); PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax; ExpressionSyntax condition; // In Visual Basic, the To expression is only evaluated once, but in C# will be evaluated every loop. // If it could evaluate differently or has side effects, it must be extracted as a variable var preLoopStatements = new List<SyntaxNode>(); var csToValue = (ExpressionSyntax)stmt.ToValue.Accept(_expressionVisitor); if (!_semanticModel.GetConstantValue(stmt.ToValue).HasValue) { var loopToVariableName = GetUniqueVariableNameInScope(node, "loopTo"); var loopEndDeclaration = SyntaxFactory.LocalDeclarationStatement(CommonConversions.CreateVariableDeclarationAndAssignment(loopToVariableName, csToValue)); // Does not do anything about porting newline trivia upwards to maintain spacing above the loop preLoopStatements.Add(loopEndDeclaration); csToValue = SyntaxFactory.IdentifierName(loopToVariableName); }; if (value == null) { condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, csToValue); } else { condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, csToValue); } if (step == null) step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id); else step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step); var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); var forStatementSyntax = SyntaxFactory.ForStatement( declaration, declaration != null ? SyntaxFactory.SeparatedList<ExpressionSyntax>() : SyntaxFactory.SingletonSeparatedList(startValue), condition, SyntaxFactory.SingletonSeparatedList(step), block.UnpackNonNestedBlock()); return SyntaxFactory.List(preLoopStatements.Concat(new[] {forStatementSyntax})); } public override SyntaxList<StatementSyntax> VisitForEachBlock(VBSyntax.ForEachBlockSyntax node) { var stmt = node.ForEachStatement; TypeSyntax type = null; SyntaxToken id; if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax) { var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable; var declaration = CommonConversions.SplitVariableDeclarations(v).Values.Single(); type = declaration.Type; id = declaration.Variables[0].Identifier; } else { var v = (IdentifierNameSyntax)stmt.ControlVariable.Accept(_expressionVisitor); id = v.Identifier; type = SyntaxFactory.ParseTypeName("var"); } var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); return SingleStatement(SyntaxFactory.ForEachStatement( type, id, (ExpressionSyntax)stmt.Expression.Accept(_expressionVisitor), block.UnpackNonNestedBlock() )); } public override SyntaxList<StatementSyntax> VisitLabelStatement(VBSyntax.LabelStatementSyntax node) { return SingleStatement(SyntaxFactory.LabeledStatement(node.LabelToken.Text, SyntaxFactory.EmptyStatement())); } public override SyntaxList<StatementSyntax> VisitGoToStatement(VBSyntax.GoToStatementSyntax node) { return SingleStatement(SyntaxFactory.GotoStatement(SyntaxKind.GotoStatement, SyntaxFactory.IdentifierName(node.Label.LabelToken.Text))); } public override SyntaxList<StatementSyntax> VisitSelectBlock(VBSyntax.SelectBlockSyntax node) { var expr = (ExpressionSyntax)node.SelectStatement.Expression.Accept(_expressionVisitor); var exprWithoutTrivia = expr.WithoutTrivia().WithoutAnnotations(); var sections = new List<SwitchSectionSyntax>(); foreach (var block in node.CaseBlocks) { var labels = new List<SwitchLabelSyntax>(); foreach (var c in block.CaseStatement.Cases) { if (c is VBSyntax.SimpleCaseClauseSyntax s) { var originalExpressionSyntax = (ExpressionSyntax)s.Value.Accept(_expressionVisitor); // CSharp allows an implicit cast from the base type (e.g. int) in the special case of switching on an enum var expressionSyntax = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(s.Value, originalExpressionSyntax, implicitCastFromIntToEnum: true); SwitchLabelSyntax caseSwitchLabelSyntax = SyntaxFactory.CaseSwitchLabel(expressionSyntax); if (!_semanticModel.GetConstantValue(s.Value).HasValue || originalExpressionSyntax != expressionSyntax) { caseSwitchLabelSyntax = WrapInCasePatternSwitchLabelSyntax(node, expressionSyntax); } labels.Add(caseSwitchLabelSyntax); } else if (c is VBSyntax.ElseCaseClauseSyntax) { labels.Add(SyntaxFactory.DefaultSwitchLabel()); } else if (c is VBSyntax.RelationalCaseClauseSyntax relational) { var operatorKind = VBasic.VisualBasicExtensions.Kind(relational); var cSharpSyntaxNode = SyntaxFactory.BinaryExpression(operatorKind.ConvertToken(TokenContext.Local), exprWithoutTrivia, (ExpressionSyntax) relational.Value.Accept(_expressionVisitor)); labels.Add(WrapInCasePatternSwitchLabelSyntax(node, cSharpSyntaxNode, treatAsBoolean: true)); } else if (c is VBSyntax.RangeCaseClauseSyntax range) { var lowerBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, (ExpressionSyntax) range.LowerBound.Accept(_expressionVisitor), exprWithoutTrivia); var upperBoundCheck = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, exprWithoutTrivia, (ExpressionSyntax) range.UpperBound.Accept(_expressionVisitor)); var withinBounds = SyntaxFactory.BinaryExpression(SyntaxKind.LogicalAndExpression, lowerBoundCheck, upperBoundCheck); labels.Add(WrapInCasePatternSwitchLabelSyntax(node, withinBounds, treatAsBoolean: true)); } else throw new NotSupportedException(c.Kind().ToString()); } var csBlockStatements = block.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)).ToList(); if (csBlockStatements.LastOrDefault() ?.IsKind(SyntaxKind.ReturnStatement) != true) { csBlockStatements.Add(SyntaxFactory.BreakStatement()); } var list = SingleStatement(SyntaxFactory.Block(csBlockStatements)); sections.Add(SyntaxFactory.SwitchSection(SyntaxFactory.List(labels), list)); } var switchStatementSyntax = ValidSyntaxFactory.SwitchStatement(expr, sections); return SingleStatement(switchStatementSyntax); } private CasePatternSwitchLabelSyntax WrapInCasePatternSwitchLabelSyntax(VBSyntax.SelectBlockSyntax node, ExpressionSyntax cSharpSyntaxNode, bool treatAsBoolean = false) { var typeInfo = _semanticModel.GetTypeInfo(node.SelectStatement.Expression); DeclarationPatternSyntax patternMatch; if (typeInfo.ConvertedType.SpecialType == SpecialType.System_Boolean || treatAsBoolean) { patternMatch = SyntaxFactory.DeclarationPattern( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SyntaxFactory.DiscardDesignation()); } else { var varName = CommonConversions.ConvertIdentifier(SyntaxFactory.Identifier(GetUniqueVariableNameInScope(node, "case"))).ValueText; patternMatch = SyntaxFactory.DeclarationPattern( SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(varName))); cSharpSyntaxNode = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), cSharpSyntaxNode); } var casePatternSwitchLabelSyntax = SyntaxFactory.CasePatternSwitchLabel(patternMatch, SyntaxFactory.WhenClause(cSharpSyntaxNode), SyntaxFactory.Token(SyntaxKind.ColonToken)); return casePatternSwitchLabelSyntax; } public override SyntaxList<StatementSyntax> VisitWithBlock(VBSyntax.WithBlockSyntax node) { var withExpression = (ExpressionSyntax)node.WithStatement.Expression.Accept(_expressionVisitor); var generateVariableName = !_semanticModel.GetTypeInfo(node.WithStatement.Expression).Type.IsValueType; ExpressionSyntax lhsExpression; List<StatementSyntax> prefixDeclarations = new List<StatementSyntax>(); if (generateVariableName) { string uniqueVariableNameInScope = GetUniqueVariableNameInScope(node, "withBlock"); lhsExpression = SyntaxFactory.IdentifierName(uniqueVariableNameInScope); prefixDeclarations.Add( CreateLocalVariableDeclarationAndAssignment(uniqueVariableNameInScope, withExpression)); } else { lhsExpression = withExpression; } _withBlockLhs.Push(lhsExpression); try { var statements = node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor)); IEnumerable<StatementSyntax> statementSyntaxs = prefixDeclarations.Concat(statements).ToArray(); return generateVariableName ? SingleStatement(SyntaxFactory.Block(statementSyntaxs)) : SyntaxFactory.List(statementSyntaxs); } finally { _withBlockLhs.Pop(); } } private LocalDeclarationStatementSyntax CreateLocalVariableDeclarationAndAssignment(string variableName, ExpressionSyntax initValue) { return SyntaxFactory.LocalDeclarationStatement(CommonConversions.CreateVariableDeclarationAndAssignment(variableName, initValue)); } private string GetUniqueVariableNameInScope(VBasic.VisualBasicSyntaxNode node, string variableNameBase) { return NameGenerator.GetUniqueVariableNameInScope(_semanticModel, _generatedNames, node, variableNameBase); } public override SyntaxList<StatementSyntax> VisitTryBlock(VBSyntax.TryBlockSyntax node) { var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); return SingleStatement( SyntaxFactory.TryStatement( block, SyntaxFactory.List(node.CatchBlocks.Select(c => (CatchClauseSyntax)c.Accept(_expressionVisitor))), (FinallyClauseSyntax)node.FinallyBlock?.Accept(_expressionVisitor) ) ); } public override SyntaxList<StatementSyntax> VisitSyncLockBlock(VBSyntax.SyncLockBlockSyntax node) { return SingleStatement(SyntaxFactory.LockStatement( (ExpressionSyntax)node.SyncLockStatement.Expression.Accept(_expressionVisitor), SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))).UnpackNonNestedBlock() )); } public override SyntaxList<StatementSyntax> VisitUsingBlock(VBSyntax.UsingBlockSyntax node) { var statementSyntax = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))); if (node.UsingStatement.Expression == null) { StatementSyntax stmt = statementSyntax; foreach (var v in node.UsingStatement.Variables.Reverse()) foreach (var declaration in CommonConversions.SplitVariableDeclarations(v).Values.Reverse()) stmt = SyntaxFactory.UsingStatement(declaration, null, stmt); return SingleStatement(stmt); } var expr = (ExpressionSyntax)node.UsingStatement.Expression.Accept(_expressionVisitor); var unpackPossiblyNestedBlock = statementSyntax.UnpackPossiblyNestedBlock(); // Allow reduced indentation for multiple usings in a row return SingleStatement(SyntaxFactory.UsingStatement(null, expr, unpackPossiblyNestedBlock)); } public override SyntaxList<StatementSyntax> VisitWhileBlock(VBSyntax.WhileBlockSyntax node) { return SingleStatement(SyntaxFactory.WhileStatement( (ExpressionSyntax)node.WhileStatement.Condition.Accept(_expressionVisitor), SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))).UnpackNonNestedBlock() )); } public override SyntaxList<StatementSyntax> VisitDoLoopBlock(VBSyntax.DoLoopBlockSyntax node) { var statements = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(CommentConvertingVisitor))).UnpackNonNestedBlock(); if (node.DoStatement.WhileOrUntilClause != null) { var stmt = node.DoStatement.WhileOrUntilClause; if (SyntaxTokenExtensions.IsKind(stmt.WhileOrUntilKeyword, VBasic.SyntaxKind.WhileKeyword)) return SingleStatement(SyntaxFactory.WhileStatement( (ExpressionSyntax)stmt.Condition.Accept(_expressionVisitor), statements )); return SingleStatement(SyntaxFactory.WhileStatement( ((ExpressionSyntax)stmt.Condition.Accept(_expressionVisitor)).InvertCondition(), statements )); } var whileOrUntilStmt = node.LoopStatement.WhileOrUntilClause; ExpressionSyntax conditionExpression; bool isUntilStmt; if (whileOrUntilStmt != null) { conditionExpression = (ExpressionSyntax)whileOrUntilStmt.Condition.Accept(_expressionVisitor); isUntilStmt = SyntaxTokenExtensions.IsKind(whileOrUntilStmt.WhileOrUntilKeyword, VBasic.SyntaxKind.UntilKeyword); } else { conditionExpression = SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression); isUntilStmt = false; } if (isUntilStmt) { conditionExpression = conditionExpression.InvertCondition(); } return SingleStatement(SyntaxFactory.DoStatement(statements, conditionExpression)); } public override SyntaxList<StatementSyntax> VisitCallStatement(VBSyntax.CallStatementSyntax node) { return SingleStatement((ExpressionSyntax) node.Invocation.Accept(_expressionVisitor)); } SyntaxList<StatementSyntax> SingleStatement(StatementSyntax statement) { return SyntaxFactory.SingletonList(statement); } SyntaxList<StatementSyntax> SingleStatement(ExpressionSyntax expression) { return SyntaxFactory.SingletonList<StatementSyntax>(SyntaxFactory.ExpressionStatement(expression)); } } static class Extensions { /// <summary> /// Returns the single statement in a block if it has no nested statements. /// If it has nested statements, and the surrounding block was removed, it could be ambiguous, /// e.g. if (...) { if (...) return null; } else return ""; /// Unbundling the middle if statement would bind the else to it, rather than the outer if statement /// </summary> public static StatementSyntax UnpackNonNestedBlock(this BlockSyntax block) { return block.Statements.Count == 1 && !block.ContainsNestedStatements() ? block.Statements[0] : block; } /// <summary> /// Only use this over <see cref="UnpackNonNestedBlock"/> in special cases where it will display more neatly and where you're sure nested statements don't introduce ambiguity /// </summary> public static StatementSyntax UnpackPossiblyNestedBlock(this BlockSyntax block) { return block.Statements.Count == 1 ? block.Statements[0] : block; } private static bool ContainsNestedStatements(this BlockSyntax block) { return block.Statements.Any(HasDescendantCSharpStatement); } private static bool HasDescendantCSharpStatement(this StatementSyntax c) { return c.DescendantNodes().OfType<StatementSyntax>().Any(); } } }
60.277045
209
0.675728
[ "MIT" ]
fabienDaou/CodeConverter
ICSharpCode.CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs
44,935
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ex17")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ex17")] [assembly: System.Reflection.AssemblyTitleAttribute("ex17")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Gerado pela classe WriteCodeFragment do MSBuild.
40.086957
80
0.638829
[ "MIT" ]
fabiodias97/Exercicio-CSharp
ex17/obj/Debug/net6.0/ex17.AssemblyInfo.cs
922
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Modify the reseller level data associated with Emergency Call /// Notification. /// The response is either a SuccessResponse or an ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""b009175f2a2a9d38115e319a6ad64d7f:531""}]")] public class ResellerEmergencyCallNotificationModifyRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _resellerId; [XmlElement(ElementName = "resellerId", IsNullable = false, Namespace = "")] [Group(@"b009175f2a2a9d38115e319a6ad64d7f:531")] [MinLength(1)] [MaxLength(36)] public string ResellerId { get => _resellerId; set { ResellerIdSpecified = true; _resellerId = value; } } [XmlIgnore] protected bool ResellerIdSpecified { get; set; } private string _defaultFromAddress; [XmlElement(ElementName = "defaultFromAddress", IsNullable = true, Namespace = "")] [Optional] [Group(@"b009175f2a2a9d38115e319a6ad64d7f:531")] [MinLength(1)] [MaxLength(80)] public string DefaultFromAddress { get => _defaultFromAddress; set { DefaultFromAddressSpecified = true; _defaultFromAddress = value; } } [XmlIgnore] protected bool DefaultFromAddressSpecified { get; set; } } }
29.625
129
0.613924
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/ResellerEmergencyCallNotificationModifyRequest.cs
1,896
C#
using System; using Microsoft.Extensions.DependencyInjection; using Ray.BiliBiliTool.Console; using Ray.BiliBiliTool.DomainService.Interfaces; using Ray.BiliBiliTool.Infrastructure; using Xunit; namespace DailyTaskTest { public class ReceiveMangaVipReward { [Fact] public void Test1() { Program.CreateHost(new string[] { }); using (var scope = Global.ServiceProviderRoot.CreateScope()) { var dailyTask = scope.ServiceProvider.GetRequiredService<IMangaDomainService>(); var account = scope.ServiceProvider.GetRequiredService<IAccountDomainService>(); var userInfo = account.LoginByCookie(); dailyTask.ReceiveMangaVipReward(1, userInfo); Assert.True(true); } } } }
28.933333
97
0.619816
[ "MIT" ]
sakkios/Bilibili_Helper
test/DailyTaskTest/ReceiveMangaVipReward.cs
868
C#
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.IdentityModel.Clients.ActiveDirectory { internal static class TokenCachePlugin { public static void BeforeAccess(TokenCacheNotificationArgs args) { // Default implementation, do nothing } public static void AfterAccess(TokenCacheNotificationArgs args) { // Default implementation, do nothing } } }
38.22449
80
0.676455
[ "MIT" ]
mpaliath/azure-activedirectory-library-for-dotnet
src/Microsoft.IdentityModel.Clients.ActiveDirectory/Platforms/net45/TokenCachePlugin.cs
1,875
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq.Expressions; using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Mvc.Rendering.Expressions; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Mvc.Razor { /// <summary> /// Represents the properties and methods that are needed in order to render a view that uses Razor syntax. /// </summary> /// <typeparam name="TModel">The type of the view data model.</typeparam> public abstract class RazorPage<TModel> : RazorPage { private IModelMetadataProvider _provider; public TModel Model { get { return ViewData == null ? default(TModel) : ViewData.Model; } } [Activate] public ViewDataDictionary<TModel> ViewData { get; set; } /// <summary> /// Returns a <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>. /// </summary> /// <typeparam name="TValue">The type of the <paramref name="expression"/> result.</typeparam> /// <param name="expression">An expression to be evaluated against the current model.</param> /// <returns>A new <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>. /// </returns> /// <remarks> /// Compiler normally infers <typeparamref name="TValue"/> from the given <paramref name="expression"/>. /// </remarks> public ModelExpression CreateModelExpression<TValue>([NotNull] Expression<Func<TModel, TValue>> expression) { if (_provider == null) { _provider = Context.RequestServices.GetRequiredService<IModelMetadataProvider>(); } var name = ExpressionHelper.GetExpressionText(expression); var metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, _provider); if (metadata == null) { throw new InvalidOperationException( Resources.FormatRazorPage_NullModelMetadata(nameof(IModelMetadataProvider), name)); } return new ModelExpression(name, metadata); } } }
40.393443
117
0.646104
[ "Apache-2.0" ]
ardalis/Mvc
src/Microsoft.AspNet.Mvc.Razor/RazorPageOfT.cs
2,464
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using GraphProcessor; using System.Linq; [System.Serializable, NodeMenuItem("Custom/InspectorNode")] public class InspectorNode : BaseNode { [Input(name = "In")] public float input; [Output(name = "Out")] public float output; [ShowInInspector] public bool additionalSettings; [ShowInInspector] public string additionalParam; public override string name => "InspectorNode"; protected override void Process() { output = input * 42; } }
19.928571
59
0.72043
[ "MIT" ]
Bezarius/NodeGraphProcessor
Assets/Examples/DefaultNodes/Nodes/InspectorNode.cs
560
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/ddraw.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DDCAPS_DX5" /> struct.</summary> public static unsafe partial class DDCAPS_DX5Tests { /// <summary>Validates that the <see cref="DDCAPS_DX5" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DDCAPS_DX5>(), Is.EqualTo(sizeof(DDCAPS_DX5))); } /// <summary>Validates that the <see cref="DDCAPS_DX5" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DDCAPS_DX5).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DDCAPS_DX5" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(DDCAPS_DX5), Is.EqualTo(364)); } } }
37.027778
145
0.656414
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/ddraw/DDCAPS_DX5Tests.cs
1,335
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using NuGet.Common; using NuGet.Test.Utility; using Xunit; namespace NuGet.Commands.Test { public class SignCommandRunnerTests : IClassFixture<CertificatesFixture> { private readonly CertificatesFixture _fixture; public SignCommandRunnerTests(CertificatesFixture fixture) { _fixture = fixture; } [Fact] public async Task ExecuteCommandAsync_WithCertificateFileNotFound_ThrowsAsync() { using (var test = await Test.CreateAsync(_fixture.GetDefaultCertificate())) { var certificateFilePath = Path.Combine(test.Directory.Path, "certificate.pfx"); test.Args.CertificatePath = certificateFilePath; var exception = await Assert.ThrowsAsync<SignCommandException>( () => test.Runner.ExecuteCommandAsync(test.Args)); Assert.Equal(NuGetLogCode.NU3001, exception.AsLogMessage().Code); Assert.Equal($"Certificate file '{certificateFilePath}' not found. For a list of accepted ways to provide a certificate, please visit https://docs.nuget.org/docs/reference/command-line-reference", exception.Message); } } [Fact] public async Task ExecuteCommandAsync_WithEmptyPkcs7File_ThrowsAsync() { using (var test = await Test.CreateAsync(_fixture.GetDefaultCertificate())) { const string fileName = "EmptyCertificateStore.p7b"; var certificateFilePath = Path.Combine(test.Directory.Path, fileName); // This resource was created by calling X509Certificate2Collection.Export(X509ContentType.SerializedStore) // with no certificates in the collection. Programmatic creation works fine on Windows but not under Mono, // hence the static resource. var bytes = GetResource(fileName); File.WriteAllBytes(certificateFilePath, bytes); test.Args.CertificatePath = certificateFilePath; var exception = await Assert.ThrowsAsync<SignCommandException>( () => test.Runner.ExecuteCommandAsync(test.Args)); Assert.Equal(NuGetLogCode.NU3001, exception.AsLogMessage().Code); Assert.Equal($"Certificate file '{certificateFilePath}' is invalid. For a list of accepted ways to provide a certificate, please visit https://docs.nuget.org/docs/reference/command-line-reference", exception.Message); } } [Fact] public async Task ExecuteCommandAsync_WithNoCertificateFound_ThrowsAsync() { using (var test = await Test.CreateAsync(_fixture.GetDefaultCertificate())) { test.Args.CertificateFingerprint = "invalid fingerprint"; test.Args.CertificateStoreLocation = StoreLocation.CurrentUser; test.Args.CertificateStoreName = StoreName.My; var exception = await Assert.ThrowsAsync<SignCommandException>( () => test.Runner.ExecuteCommandAsync(test.Args)); Assert.Equal(NuGetLogCode.NU3001, exception.AsLogMessage().Code); Assert.Equal("No certificates were found that meet all the given criteria. For a list of accepted ways to provide a certificate, please visit https://docs.nuget.org/docs/reference/command-line-reference", exception.Message); } } [Fact] public async Task ExecuteCommandAsync_WithIncorrectPassword_ThrowsAsync() { const string password = "password"; using (var test = await Test.CreateAsync(_fixture.GetCertificateWithPassword(password))) { var certificateFilePath = Path.Combine(test.Directory.Path, "certificate.pfx"); File.WriteAllBytes(certificateFilePath, test.Certificate.Export(X509ContentType.Pkcs12, password)); test.Args.CertificatePath = certificateFilePath; test.Args.CertificatePassword = "incorrect password"; var exception = await Assert.ThrowsAsync<SignCommandException>( () => test.Runner.ExecuteCommandAsync(test.Args)); Assert.Equal(NuGetLogCode.NU3001, exception.AsLogMessage().Code); Assert.Equal($"Invalid password was provided for the certificate file '{certificateFilePath}'. Please provide a valid password using the '-CertificatePassword' option", exception.Message); } } [Fact] public async Task ExecuteCommandAsync_WithAmbiguousMatch_ThrowsAsync() { using (var test = await Test.CreateAsync(_fixture.GetDefaultCertificate())) { test.Args.CertificateSubjectName = "Root"; test.Args.CertificateStoreLocation = StoreLocation.LocalMachine; test.Args.CertificateStoreName = StoreName.Root; var exception = await Assert.ThrowsAsync<SignCommandException>( () => test.Runner.ExecuteCommandAsync(test.Args)); Assert.Equal(NuGetLogCode.NU3001, exception.AsLogMessage().Code); Assert.Equal("Multiple certificates were found that meet all the given criteria. Use the '-CertificateFingerprint' option with the hash of the desired certificate.", exception.Message); } } [Fact] public async Task ExecuteCommandAsync_WithMultiplePackagesAndInvalidCertificate_RaisesErrorsOnceAsync() { const string password = "password"; using (var test = await Test.CreateAsync(_fixture.GetCertificateWithPassword(password))) { var certificateFilePath = Path.Combine(test.Directory.Path, "certificate.pfx"); File.WriteAllBytes(certificateFilePath, test.Certificate.Export(X509ContentType.Pkcs12, password)); test.Args.CertificatePath = certificateFilePath; test.Args.CertificatePassword = password; await Test.CreatePackageAsync(test.Directory, "package2.nupkg"); var packagesFilePath = Path.Combine(test.Directory, "*.nupkg"); test.Args.PackagePath = packagesFilePath; test.Args.SignatureHashAlgorithm = HashAlgorithmName.SHA256; test.Args.TimestampHashAlgorithm = HashAlgorithmName.SHA256; await test.Runner.ExecuteCommandAsync(test.Args); Assert.Equal(1, test.Logger.LogMessages.Count( message => message.Level == LogLevel.Warning && message.Code == NuGetLogCode.NU3018)); } } private static byte[] GetResource(string name) { return ResourceTestUtility.GetResourceBytes( $"NuGet.Commands.Test.compiler.resources.{name}", typeof(SignCommandRunnerTests)); } private sealed class Test : IDisposable { private bool _isDisposed; internal SignArgs Args { get; } internal X509Certificate2 Certificate { get; } internal TestDirectory Directory { get; } internal TestLogger Logger { get; } internal SignCommandRunner Runner { get; } internal Test(SignArgs args, TestDirectory directory, X509Certificate2 certificate, TestLogger logger) { Args = args; Directory = directory; Certificate = certificate; Runner = new SignCommandRunner(); Logger = logger; } public void Dispose() { if (!_isDisposed) { Certificate.Dispose(); GC.SuppressFinalize(this); _isDisposed = true; } } internal static async Task<Test> CreateAsync(X509Certificate2 certificate) { var directory = TestDirectory.Create(); var packageFilePath = await CreatePackageAsync(directory, "package.nupkg"); var logger = new TestLogger(); var args = new SignArgs() { Logger = logger, NonInteractive = true, PackagePath = packageFilePath }; return new Test(args, directory, certificate, logger); } internal static async Task<string> CreatePackageAsync(TestDirectory directory, string packageFileName) { var packageFilePath = Path.Combine(directory.Path, packageFileName); var package = new SimpleTestPackageContext(); using (var readStream = await package.CreateAsStreamAsync()) using (var writeStream = File.OpenWrite(packageFilePath)) { readStream.CopyTo(writeStream); } return packageFilePath; } } } }
42.759091
240
0.620283
[ "Apache-2.0" ]
BdDsl/NuGet.Client
test/NuGet.Core.Tests/NuGet.Commands.Test/SignCommandRunnerTests.cs
9,407
C#
namespace UniAppKids.ExternServiceController.Areas.HelpPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
31.571429
77
0.773756
[ "Apache-2.0" ]
andycarmona/Uni-AppKids
UniAppKids.ExternServiceController/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs
221
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !(DOTNET || PORTABLE || PORTABLE40) using System; using System.Runtime.Serialization; using Newtonsoft.Json.Shims; namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> [Preserve] public class JsonISerializableContract : JsonContainerContract { /// <summary> /// Gets or sets the ISerializable object constructor. /// </summary> /// <value>The ISerializable object constructor.</value> public ObjectConstructor<object> ISerializableCreator { get; set; } /// <summary> /// Initializes a new instance of the <see cref="JsonISerializableContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonISerializableContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Serializable; } } } #endif
38.54386
92
0.705052
[ "MIT" ]
parentelement/Json-NET-for-Unity
Source/Newtonsoft.Json/Serialization/JsonISerializableContract.cs
2,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WispFramework.Utility; namespace WispFramework.Extensions.Linq { /// <summary> /// Helper methods for the lists. /// </summary> public static class ListExtensions { public static IEnumerable<IEnumerable<T>> ChunkBy<T>(this IEnumerable<T> source, int chunkSize) { return source .Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / chunkSize) .Select(x => x.Select(v => v.Value).ToList()) .ToList(); } public static string ToCsv<T>(this IEnumerable<T> list) { return list.Stringify().Join(", "); } public static string Join<T>(this IEnumerable<T> list, string separator, Func<T, string> toStringExpression) { return list.Stringify(toStringExpression).Join(separator); } public static IEnumerable<string> Stringify<T>(this IEnumerable<T> list) { return list.Select(t => t.ToString()); } public static IEnumerable<string> Stringify<T>(this IEnumerable<T> list, Func<T, string> toStringExpression) { return list.Select(toStringExpression); } public static string Join(this IEnumerable<string> list, string separator) { return string.Join(separator, list); } public static T RandomItem<T>(this IEnumerable<T> list) { var enumerable = list as T[] ?? list.ToArray(); return !enumerable.Any() ? default : enumerable.ElementAtOrDefault(RandomUtil.Range(0, enumerable.Count())); } /// <summary> /// Shuffle the IEnumerable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var enumerable = list as T[] ?? list.ToArray(); var shuffledList = enumerable.Select(x => new {Number = RandomUtil.Range(0, enumerable.Count()), Item = x}).OrderBy(x => x.Number).Select(x => x.Item); return shuffledList.ToList(); } } }
33.7
149
0.576939
[ "MIT" ]
ddolyniuk1/WispFramework
WispFramework/Extensions/Linq/EnumerableExtensions.cs
2,361
C#
/* Copyright 2017 NAXAM 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 UIKit; using Foundation; using ObjCRuntime; using MapKit; namespace Naxam.iOS.PlacePicker { // The first step to creating a binding is to add your native library ("libNativeLibrary.a") // to the project by right-clicking (or Control-clicking) the folder containing this source // file and clicking "Add files..." and then simply select the native library (or libraries) // that you want to bind. // // When you do that, you'll notice that MonoDevelop generates a code-behind file for each // native library which will contain a [LinkWith] attribute. MonoDevelop auto-detects the // architectures that the native library supports and fills in that information for you, // however, it cannot auto-detect any Frameworks or other system libraries that the // native library may depend on, so you'll need to fill in that information yourself. // // Once you've done that, you're ready to move on to binding the API... // // // Here is where you'd define your API definition for the native Objective-C library. // // For example, to bind the following Objective-C class: // // @interface Widget : NSObject { // } // // The C# binding would look like this: // // [BaseType (typeof (NSObject))] // interface Widget { // } // // To bind Objective-C properties, such as: // // @property (nonatomic, readwrite, assign) CGPoint center; // // You would add a property definition in the C# interface like so: // // [Export ("center")] // CGPoint Center { get; set; } // // To bind an Objective-C method, such as: // // -(void) doSomething:(NSObject *)object atIndex:(NSInteger)index; // // You would add a method definition to the C# interface like so: // // [Export ("doSomething:atIndex:")] // void DoSomething (NSObject object, int index); // // Objective-C "constructors" such as: // // -(id)initWithElmo:(ElmoMuppet *)elmo; // // Can be bound as: // // [Export ("initWithElmo:")] // IntPtr Constructor (ElmoMuppet elmo); // // For more information, see http://developer.xamarin.com/guides/ios/advanced_topics/binding_objective-c/ // // @protocol NXPlacePickerDelegate <NSObject> /// <summary> /// Delegate for NXPlacePickerViewController /// </summary> [Protocol, Model] [BaseType(typeof(NSObject))] interface NXPlacePickerDelegate { // @required -(void)placePicker:(NXPlacePickerViewController *)viewController didSelectPlace:(MKPlacemark *)place; /// <summary> /// To be called when a place is picked /// </summary> /// <param name="viewController">View controller.</param> /// <param name="place">Place.</param> [Abstract] [Export("placePicker:didSelectPlace:")] void DidSelectPlace(NXPlacePickerViewController viewController, MKPlacemark place); } // @interface NXPlacePickerViewController : UIViewController <MKMapViewDelegate> /// <summary> /// A view controller for user to select a place, start searching for a place. /// </summary> [BaseType(typeof(UIViewController))] interface NXPlacePickerViewController : IMKMapViewDelegate { /// <summary> /// NXPlacePickerDelegate /// </summary> /// <value>The delegate.</value> [NullAllowed, Wrap("WeakDelegate")] NSObject Delegate { get; set; } // @property (weak) id<NXPlacePickerDelegate> delegate; /// <summary> /// Weak Delegate for NXPlacePickerDelegate /// </summary> /// <value>The delegate.</value> [NullAllowed, Export("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // +(instancetype)initWithDelegate:(id<NXPlacePickerDelegate>)delegate; /// <summary> /// Create a new instance of NXPlacePickerViewController /// </summary> /// <returns>The with delegate.</returns> /// <param name="delegate">Delegate.</param> [Static] [Export("initWithDelegate:")] NXPlacePickerViewController InitWithDelegate([NullAllowed] INXPlacePickerDelegate @delegate); } public partial interface INXPlacePickerDelegate : INativeObject { } }
39.131783
460
0.720087
[ "MIT" ]
NAXAM/ios-nativeplacepicker
xam-binding/Naxam.iOS.PlacePicker/ApiDefinition.cs
5,050
C#
using System.Runtime.InteropServices; namespace Vulkan { [StructLayout(LayoutKind.Sequential)] public struct VkBindIndexBufferIndirectCommandNV { [NativeTypeName("VkDeviceAddress")] public ulong BufferAddress; [NativeTypeName("uint32_t")] public uint Size; public VkIndexType IndexType; } }
22.266667
71
0.721557
[ "BSD-3-Clause" ]
trmcnealy/Vulkan
Vulkan/Structs/VkBindIndexBufferIndirectCommandNV.cs
334
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.ElasticLoadBalancingV2")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.5.22")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
52.773585
241
0.785484
[ "Apache-2.0" ]
rczwojdrak/aws-sdk-net
sdk/src/Services/ElasticLoadBalancingV2/Properties/AssemblyInfo.cs
2,797
C#
using System.Linq; using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.Domain.Repositories; using Abp.Extensions; using Abp.IdentityFramework; using Abp.Linq.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Security; using CmsFeature.Authorization; using CmsFeature.Authorization.Roles; using CmsFeature.Authorization.Users; using CmsFeature.Editions; using CmsFeature.MultiTenancy.Dto; using Microsoft.AspNetCore.Identity; namespace CmsFeature.MultiTenancy { [AbpAuthorize(PermissionNames.Pages_Tenants)] public class TenantAppService : AsyncCrudAppService<Tenant, TenantDto, int, PagedTenantResultRequestDto, CreateTenantDto, TenantDto>, ITenantAppService { private readonly TenantManager _tenantManager; private readonly EditionManager _editionManager; private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IAbpZeroDbMigrator _abpZeroDbMigrator; public TenantAppService( IRepository<Tenant, int> repository, TenantManager tenantManager, EditionManager editionManager, UserManager userManager, RoleManager roleManager, IAbpZeroDbMigrator abpZeroDbMigrator) : base(repository) { _tenantManager = tenantManager; _editionManager = editionManager; _userManager = userManager; _roleManager = roleManager; _abpZeroDbMigrator = abpZeroDbMigrator; } public override async Task<TenantDto> Create(CreateTenantDto input) { CheckCreatePermission(); // Create tenant var tenant = ObjectMapper.Map<Tenant>(input); tenant.ConnectionString = input.ConnectionString.IsNullOrEmpty() ? null : SimpleStringCipher.Instance.Encrypt(input.ConnectionString); var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName); if (defaultEdition != null) { tenant.EditionId = defaultEdition.Id; } await _tenantManager.CreateAsync(tenant); await CurrentUnitOfWork.SaveChangesAsync(); // To get new tenant's id. // Create tenant database _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant); // We are working entities of new tenant, so changing tenant filter using (CurrentUnitOfWork.SetTenantId(tenant.Id)) { // Create static roles for new tenant CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id)); await CurrentUnitOfWork.SaveChangesAsync(); // To get static role ids // Grant all permissions to admin role var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin); await _roleManager.GrantAllPermissionsAsync(adminRole); // Create admin user for the tenant var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress); await _userManager.InitializeOptionsAsync(tenant.Id); CheckErrors(await _userManager.CreateAsync(adminUser, User.DefaultPassword)); await CurrentUnitOfWork.SaveChangesAsync(); // To get admin user's id // Assign admin user to role! CheckErrors(await _userManager.AddToRoleAsync(adminUser, adminRole.Name)); await CurrentUnitOfWork.SaveChangesAsync(); } return MapToEntityDto(tenant); } protected override IQueryable<Tenant> CreateFilteredQuery(PagedTenantResultRequestDto input) { return Repository.GetAll() .WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.TenancyName.Contains(input.Keyword) || x.Name.Contains(input.Keyword)) .WhereIf(input.IsActive.HasValue, x => x.IsActive == input.IsActive); } protected override void MapToEntity(TenantDto updateInput, Tenant entity) { // Manually mapped since TenantDto contains non-editable properties too. entity.Name = updateInput.Name; entity.TenancyName = updateInput.TenancyName; entity.IsActive = updateInput.IsActive; } public override async Task Delete(EntityDto<int> input) { CheckDeletePermission(); var tenant = await _tenantManager.GetByIdAsync(input.Id); await _tenantManager.DeleteAsync(tenant); } private void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
39.266129
155
0.662559
[ "MIT" ]
mathro/CmsFeature
src/CmsFeature.Application/MultiTenancy/TenantAppService.cs
4,871
C#
/* * eZmax API Definition (Full) * * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; using System.Linq; using System.IO; using System.Collections.Generic; using eZmaxApi.Api; using eZmaxApi.Model; using eZmaxApi.Client; using System.Reflection; using Newtonsoft.Json; namespace eZmaxApi.Test.Model { /// <summary> /// Class for testing EzsigntemplatedocumentpageResponseCompound /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class EzsigntemplatedocumentpageResponseCompoundTests : IDisposable { // TODO uncomment below to declare an instance variable for EzsigntemplatedocumentpageResponseCompound //private EzsigntemplatedocumentpageResponseCompound instance; public EzsigntemplatedocumentpageResponseCompoundTests() { // TODO uncomment below to create an instance of EzsigntemplatedocumentpageResponseCompound //instance = new EzsigntemplatedocumentpageResponseCompound(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of EzsigntemplatedocumentpageResponseCompound /// </summary> [Fact] public void EzsigntemplatedocumentpageResponseCompoundInstanceTest() { // TODO uncomment below to test "IsType" EzsigntemplatedocumentpageResponseCompound //Assert.IsType<EzsigntemplatedocumentpageResponseCompound>(instance); } /// <summary> /// Test the property 'PkiEzsigntemplatedocumentpageID' /// </summary> [Fact] public void PkiEzsigntemplatedocumentpageIDTest() { // TODO unit test for the property 'PkiEzsigntemplatedocumentpageID' } /// <summary> /// Test the property 'IEzsigntemplatedocumentpageWidthimage' /// </summary> [Fact] public void IEzsigntemplatedocumentpageWidthimageTest() { // TODO unit test for the property 'IEzsigntemplatedocumentpageWidthimage' } /// <summary> /// Test the property 'IEzsigntemplatedocumentpageHeightimage' /// </summary> [Fact] public void IEzsigntemplatedocumentpageHeightimageTest() { // TODO unit test for the property 'IEzsigntemplatedocumentpageHeightimage' } /// <summary> /// Test the property 'IEzsigntemplatedocumentpageWidthpdf' /// </summary> [Fact] public void IEzsigntemplatedocumentpageWidthpdfTest() { // TODO unit test for the property 'IEzsigntemplatedocumentpageWidthpdf' } /// <summary> /// Test the property 'IEzsigntemplatedocumentpageHeightpdf' /// </summary> [Fact] public void IEzsigntemplatedocumentpageHeightpdfTest() { // TODO unit test for the property 'IEzsigntemplatedocumentpageHeightpdf' } /// <summary> /// Test the property 'IEzsigntemplatedocumentpagePagenumber' /// </summary> [Fact] public void IEzsigntemplatedocumentpagePagenumberTest() { // TODO unit test for the property 'IEzsigntemplatedocumentpagePagenumber' } /// <summary> /// Test the property 'SImageUrl' /// </summary> [Fact] public void SImageUrlTest() { // TODO unit test for the property 'SImageUrl' } } }
32.35
110
0.644256
[ "MIT" ]
ezmaxinc/eZmax-SDK-csharp-netcore
src/eZmaxApi.Test/Model/EzsigntemplatedocumentpageResponseCompoundTests.cs
3,882
C#
//----------------------------------------------------------------------- // <copyright file="NSwagSettings.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.DependencyInjection; using NConsole; using Newtonsoft.Json; using NSwag.Generation.AspNetCore; using NJsonSchema.Yaml; using NJsonSchema; using Microsoft.AspNetCore.Hosting; using NSwag.Generation; using NJsonSchema.Generation; using Namotion.Reflection; #if NETCOREAPP || NETSTANDARD using System.Runtime.Loader; #endif namespace NSwag.Commands.Generation.AspNetCore { /// <summary>The generator.</summary> [Command(Name = "aspnetcore2openapi", Description = "Generates a Swagger specification ASP.NET Core Mvc application using ApiExplorer.")] public class AspNetCoreToOpenApiCommand : AspNetCoreToSwaggerCommand { } /// <summary>The generator.</summary> [Command(Name = "aspnetcore2swagger", Description = "Generates a Swagger specification ASP.NET Core Mvc application using ApiExplorer (obsolete: use aspnetcore2openapi instead).")] public class AspNetCoreToSwaggerCommand : OpenApiGeneratorCommandBase<AspNetCoreOpenApiDocumentGeneratorSettings> { private const string LauncherBinaryName = "NSwag.AspNetCore.Launcher"; [Argument(Name = nameof(Project), IsRequired = false, Description = "The project to use.")] public string Project { get; set; } [Argument(Name = nameof(MSBuildProjectExtensionsPath), IsRequired = false, Description = "The MSBuild project extensions path. Defaults to \"obj\".")] public string MSBuildProjectExtensionsPath { get; set; } [Argument(Name = nameof(Configuration), IsRequired = false, Description = "The configuration to use.")] public string Configuration { get; set; } [Argument(Name = nameof(Runtime), IsRequired = false, Description = "The runtime to use.")] public string Runtime { get; set; } [Argument(Name = nameof(TargetFramework), IsRequired = false, Description = "The target framework to use.")] public string TargetFramework { get; set; } [Argument(Name = nameof(NoBuild), IsRequired = false, Description = "Don't build the project. Only use this when the build is up-to-date.")] public bool NoBuild { get; set; } [Argument(Name = nameof(Verbose), IsRequired = false, Description = "Print verbose output.")] public bool Verbose { get; set; } = true; [Argument(Name = nameof(WorkingDirectory), IsRequired = false, Description = "The working directory to use.")] public string WorkingDirectory { get; set; } [Argument(Name = "RequireParametersWithoutDefault", IsRequired = false, Description = "Parameters without default value are always required" + "(i.e. api explorer info and only optional when default is set, legacy, default: false).")] public bool RequireParametersWithoutDefault { get => Settings.RequireParametersWithoutDefault; set => Settings.RequireParametersWithoutDefault = value; } [Argument(Name = "ApiGroupNames", IsRequired = false, Description = "The ASP.NET Core API Explorer group names to include (comma separated, default: empty = all).")] public string[] ApiGroupNames { get => Settings.ApiGroupNames; set => Settings.ApiGroupNames = value; } public override async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { if (!string.IsNullOrEmpty(Project) && AssemblyPaths.Any()) { throw new InvalidOperationException("Either provide a Project or an assembly but not both."); } if (string.IsNullOrEmpty(Project)) { // Run with assembly return await base.RunAsync(processor, host); } else { // Run with .csproj var verboseHost = Verbose ? host : null; var projectFile = ProjectMetadata.FindProject(Project); var projectMetadata = await ProjectMetadata.GetProjectMetadata( projectFile, MSBuildProjectExtensionsPath, TargetFramework, Configuration, Runtime, NoBuild, verboseHost).ConfigureAwait(false); if (!File.Exists(Path.Combine(projectMetadata.OutputPath, projectMetadata.TargetFileName))) { throw new InvalidOperationException($"Project outputs could not be located in " + $"'{projectMetadata.OutputPath}'. Ensure that the project has been built."); } var cleanupFiles = new List<string>(); var args = new List<string>(); string executable; #if NET461 var toolDirectory = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.Exists(toolDirectory)) { toolDirectory = Path.GetDirectoryName(typeof(AspNetCoreToSwaggerCommand).GetTypeInfo().Assembly.Location); } if (projectMetadata.TargetFrameworkIdentifier == ".NETFramework") { string binaryName; var is32BitProject = string.Equals(projectMetadata.PlatformTarget, "x86", StringComparison.OrdinalIgnoreCase); if (is32BitProject) { if (Environment.Is64BitProcess) { throw new InvalidOperationException($"The ouput of {projectFile} is a 32-bit application and requires NSwag.Console.x86 to be processed."); } binaryName = LauncherBinaryName + ".x86.exe"; } else { if (!Environment.Is64BitProcess) { throw new InvalidOperationException($"The ouput of {projectFile} is a 64-bit application and requires NSwag.Console to be processed."); } binaryName = LauncherBinaryName + ".exe"; } var executableSource = Path.Combine(toolDirectory, binaryName); if (!File.Exists(executableSource)) { throw new InvalidOperationException($"Unable to locate {binaryName} in {toolDirectory}."); } executable = Path.Combine(projectMetadata.OutputPath, binaryName); File.Copy(executableSource, executable, overwrite: true); cleanupFiles.Add(executable); var appConfig = Path.Combine(projectMetadata.OutputPath, projectMetadata.TargetFileName + ".config"); if (File.Exists(appConfig)) { var copiedAppConfig = Path.ChangeExtension(executable, ".exe.config"); File.Copy(appConfig, copiedAppConfig, overwrite: true); cleanupFiles.Add(copiedAppConfig); } } #elif NETCOREAPP || NETSTANDARD var toolDirectory = AppContext.BaseDirectory; if (!Directory.Exists(toolDirectory)) { toolDirectory = Path.GetDirectoryName(typeof(AspNetCoreToSwaggerCommand).GetTypeInfo().Assembly.Location); } if (projectMetadata.TargetFrameworkIdentifier == ".NETCoreApp") { executable = "dotnet"; args.Add("exec"); args.Add("--depsfile"); args.Add(projectMetadata.ProjectDepsFilePath); args.Add("--runtimeconfig"); args.Add(projectMetadata.ProjectRuntimeConfigFilePath); var binaryName = LauncherBinaryName + ".dll"; var executorBinary = Path.Combine(toolDirectory, binaryName); if (!File.Exists(executorBinary)) { throw new InvalidOperationException($"Unable to locate {binaryName} in {toolDirectory}."); } args.Add(executorBinary); } #endif else { throw new InvalidOperationException($"Unsupported target framework '{projectMetadata.TargetFrameworkIdentifier}'."); } var commandFile = Path.GetTempFileName(); var outputFile = Path.GetTempFileName(); File.WriteAllText(commandFile, JsonConvert.SerializeObject(this)); cleanupFiles.Add(commandFile); cleanupFiles.Add(outputFile); args.Add(commandFile); args.Add(outputFile); args.Add(projectMetadata.AssemblyName); args.Add(toolDirectory); try { var exitCode = await Exe.RunAsync(executable, args, verboseHost).ConfigureAwait(false); if (exitCode != 0) { throw new InvalidOperationException($"Swagger generation failed with non-zero exit code '{exitCode}'."); } host?.WriteMessage($"Output written to {outputFile}.{Environment.NewLine}"); JsonReferenceResolver ReferenceResolverFactory(OpenApiDocument d) => new JsonAndYamlReferenceResolver(new JsonSchemaResolver(d, Settings)); var documentJson = File.ReadAllText(outputFile); var document = await OpenApiDocument.FromJsonAsync(documentJson, null, OutputType, ReferenceResolverFactory).ConfigureAwait(false); await this.TryWriteDocumentOutputAsync(host, NewLineBehavior, () => document).ConfigureAwait(false); return document; } finally { TryDeleteFiles(cleanupFiles); } } } internal string ChangeWorkingDirectoryAndSetAspNetCoreEnvironment() { if (!string.IsNullOrEmpty(AspNetCoreEnvironment)) { Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", AspNetCoreEnvironment); } var currentWorkingDirectory = Directory.GetCurrentDirectory(); if (!string.IsNullOrEmpty(WorkingDirectory)) { Directory.SetCurrentDirectory(WorkingDirectory); } else if (!string.IsNullOrEmpty(Project)) { var workingDirectory = Path.GetDirectoryName(Project); if (Directory.Exists(workingDirectory)) { Directory.SetCurrentDirectory(workingDirectory); } } else if (AssemblyPaths.Any()) { var workingDirectory = Path.GetDirectoryName(AssemblyPaths.First()); if (Directory.Exists(workingDirectory)) { Directory.SetCurrentDirectory(workingDirectory); } } return currentWorkingDirectory; } public async Task<OpenApiDocument> GenerateDocumentAsync(AssemblyLoader.AssemblyLoader assemblyLoader, IServiceProvider serviceProvider, string currentWorkingDirectory) { Directory.SetCurrentDirectory(currentWorkingDirectory); if (UseDocumentProvider) { return await GenerateDocumentWithDocumentProviderAsync(serviceProvider); } else { return await GenerateDocumentWithApiDescriptionAsync(assemblyLoader, serviceProvider, currentWorkingDirectory); } } private async Task<OpenApiDocument> GenerateDocumentWithDocumentProviderAsync(IServiceProvider serviceProvider) { var documentGenerator = serviceProvider.GetRequiredService<IOpenApiDocumentGenerator>(); var document = await documentGenerator.GenerateAsync(DocumentName); return document; } private async Task<OpenApiDocument> GenerateDocumentWithApiDescriptionAsync(AssemblyLoader.AssemblyLoader assemblyLoader, IServiceProvider serviceProvider, string currentWorkingDirectory) { InitializeCustomTypes(assemblyLoader); // In the case of KeyNotFoundException, see https://github.com/aspnet/Mvc/issues/5690 var apiDescriptionProvider = serviceProvider.GetRequiredService<IApiDescriptionGroupCollectionProvider>(); var settings = await CreateSettingsAsync(assemblyLoader, serviceProvider, currentWorkingDirectory); var generator = new AspNetCoreOpenApiDocumentGenerator(settings); var document = await generator.GenerateAsync(apiDescriptionProvider.ApiDescriptionGroups).ConfigureAwait(false); PostprocessDocument(document); return document; } protected override async Task<string> RunIsolatedAsync(AssemblyLoader.AssemblyLoader assemblyLoader) { var currentWorkingDirectory = ChangeWorkingDirectoryAndSetAspNetCoreEnvironment(); using (var webHost = await CreateWebHostAsync(assemblyLoader)) { var document = await GenerateDocumentAsync(assemblyLoader, webHost.TryGetPropertyValue<IServiceProvider>("Services"), currentWorkingDirectory); return UseDocumentProvider ? document.ToJson() : document.ToJson(OutputType); } } private static void TryDeleteFiles(List<string> files) { foreach (var file in files) { try { if (File.Exists(file)) { File.Delete(file); } } catch { // Don't throw any if any clean up operation fails. } } } } }
44.666667
195
0.588086
[ "MIT" ]
0xced/NSwag
src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs
15,010
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; public class GameSystemManager : MonoBehaviour { GameObject btnSubmit, txtUserId, txtPwd, chkCreate, btnJoin, lblU, lblP, lblInfo, gameBoard, txtMsg, btnSend, ddlMsg, chatBox, pnlChat, btnSendPrefixMsg, btnJoinObserver, btnReplay, ddlPlayer; GameObject txtCMsg, btnCSend, LoginSys, MsgSend, PMsgSend, C2C, JoinSys, txtReplay, pnlReplay, chk2player; GameObject btn11, btn12, btn13, btn21, btn22, btn23, btn31, btn32, btn33; public GameObject networkedClient; string currentPlayerName = ""; public int playerNumber = 0; bool isPlayer = false; List<string> preFixMsg = new List<string> { "hello", "test", "bye", "call you later" }; // Start is called before the first frame update void Start() { GameObject[] allobjects = FindObjectsOfType<GameObject>(); foreach (GameObject go in allobjects) { if (go.name == "btnJoin") { btnJoin = go; } else if (go.name == "lblInfo") { lblInfo = go; } else if (go.name == "btnLogin") { btnSubmit = go; } else if (go.name == "txtUser") { txtUserId = go; } else if (go.name == "txtPwd") { txtPwd = go; } else if (go.name == "chkCreate") { chkCreate = go; } else if (go.name == "lblUser") { lblU = go; } else if (go.name == "lblPwd") { lblP = go; } else if (go.name == "btnReplay") { btnReplay = go; } else if (go.name == "txtReplay") { txtReplay = go; } else if (go.name == "pnlReplay") { pnlReplay = go; } else if (go.name == "txtMsg") txtMsg = go; else if (go.name == "btnSend") btnSend = go; else if (go.name == "ddlMsg") ddlMsg = go; else if (go.name == "chatBox") chatBox = go; else if (go.name == "pnlChat") pnlChat = go; else if (go.name == "btnSendPrefixMsg") btnSendPrefixMsg = go; else if (go.name == "btnJoinObserver") btnJoinObserver = go; else if (go.name == "ddlPlayer") { ddlPlayer = go; } else if (go.name == "PMsgSend") { PMsgSend = go; } else if (go.name == "JoinSys") { JoinSys = go; } else if (go.name == "C2C") { C2C = go; } else if (go.name == "MsgSend") { MsgSend = go; } else if (go.name == "LoginSys") { LoginSys = go; } else if (go.name == "btnCSend") { btnCSend = go; } else if (go.name == "txtCMsg") { txtCMsg = go; } else if (go.name == "chk2player") { chk2player = go; } else if (go.name == "btn11") { btn11 = go; } else if (go.name == "btn12") { btn12 = go; } else if (go.name == "btn13") { btn13 = go; } else if (go.name == "btn21") { btn21 = go; } else if (go.name == "btn22") { btn22 = go; } else if (go.name == "btn23") { btn23 = go; } else if (go.name == "btn31") { btn31 = go; } else if (go.name == "btn32") { btn32 = go; } else if (go.name == "btn33") { btn33 = go; } } btn11.GetComponent<Button>().onClick.AddListener(btn11Click); btn21.GetComponent<Button>().onClick.AddListener(btn21Click); btn31.GetComponent<Button>().onClick.AddListener(btn31Click); btn12.GetComponent<Button>().onClick.AddListener(btn12Click); btn22.GetComponent<Button>().onClick.AddListener(btn22Click); btn32.GetComponent<Button>().onClick.AddListener(btn32Click); btn13.GetComponent<Button>().onClick.AddListener(btn13Click); btn23.GetComponent<Button>().onClick.AddListener(btn23Click); btn33.GetComponent<Button>().onClick.AddListener(btn33Click); btnSubmit.GetComponent<Button>().onClick.AddListener(SubmitButtonPressed); btnJoin.GetComponent<Button>().onClick.AddListener(JoinButtonPressed); btnJoinObserver.GetComponent<Button>().onClick.AddListener(ObserveButtonPressed); btnReplay.GetComponent<Button>().onClick.AddListener(ReplayButtonPressed); btnSend.GetComponent<Button>().onClick.AddListener(SendButtonPressed); btnSendPrefixMsg.GetComponent<Button>().onClick.AddListener(SendPrefButtonPressed); btnCSend.GetComponent<Button>().onClick.AddListener(SendClientButtonPressed); chkCreate.GetComponent<Toggle>().onValueChanged.AddListener(CreateToggleChanged); ChangeState(GameStates.LoginMenu); ddlMsg.GetComponent<Dropdown>().AddOptions(preFixMsg); } bool change = false; public void gmPlay(int btn, int player) { string choice = ""; int cell = 0; switch (btn) { case 11: choice = filledValue(player, btn11.GetComponentInChildren<Text>().text); btn11.GetComponentInChildren<Text>().text = choice; cell = 1; break; case 12: choice = filledValue(player, btn12.GetComponentInChildren<Text>().text); btn12.GetComponentInChildren<Text>().text = choice; cell = 2; break; case 13: choice = filledValue(player, btn13.GetComponentInChildren<Text>().text); btn13.GetComponentInChildren<Text>().text = choice; cell = 3; break; case 21: choice = filledValue(player, btn21.GetComponentInChildren<Text>().text); btn21.GetComponentInChildren<Text>().text = choice; cell = 4; break; case 22: choice = filledValue(player, btn22.GetComponentInChildren<Text>().text); btn22.GetComponentInChildren<Text>().text = choice; cell = 5; break; case 23: choice = filledValue(player, btn23.GetComponentInChildren<Text>().text); btn23.GetComponentInChildren<Text>().text = choice; cell = 6; break; case 31: choice = filledValue(player, btn31.GetComponentInChildren<Text>().text); btn31.GetComponentInChildren<Text>().text = choice; cell = 7; break; case 32: choice = filledValue(player, btn32.GetComponentInChildren<Text>().text); btn32.GetComponentInChildren<Text>().text = choice; cell = 8; break; case 33: choice = filledValue(player, btn33.GetComponentInChildren<Text>().text); btn33.GetComponentInChildren<Text>().text = choice; cell = 9; break; default: break; } string msg = ClientToServerSignifiers.PlayGame + "," + currentPlayerName + ","+choice + ","+cell; Debug.Log("play " + msg); if(change) networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); } public void setTextButton(int btn,string val) { switch (btn) { case 1: btn11.GetComponentInChildren<Text>().text = val; break; case 2: btn12.GetComponentInChildren<Text>().text = val; break; case 3: btn13.GetComponentInChildren<Text>().text = val; break; case 4: btn21.GetComponentInChildren<Text>().text = val; break; case 5: btn22.GetComponentInChildren<Text>().text = val; break; case 6: btn23.GetComponentInChildren<Text>().text = val; break; case 7: btn31.GetComponentInChildren<Text>().text = val; break; case 8: btn32.GetComponentInChildren<Text>().text = val; break; case 9: btn33.GetComponentInChildren<Text>().text = val; break; default: break; } } public string filledValue(int player,string prevVal) { string newVal = ""; if (prevVal == "_")//empty box { change = true; if (player == 1) newVal = "X"; else newVal = "O"; } else { newVal = prevVal;//can't play change = false; } return newVal; } public void btn11Click() { gmPlay(11, playerNumber); } public void btn12Click() { gmPlay(12, playerNumber); } public void btn13Click() { gmPlay(13, playerNumber); } public void btn21Click() { gmPlay(21, playerNumber); } public void btn22Click() { gmPlay(22, playerNumber); } public void btn23Click() { gmPlay(23, playerNumber); } public void btn31Click() { gmPlay(31, playerNumber); } public void btn32Click() { gmPlay(32, playerNumber); } public void btn33Click() { gmPlay(33, playerNumber); } public bool getchk2player() { Debug.Log("chk " + chkCreate.GetComponent<Toggle>().isOn); return chkCreate.GetComponent<Toggle>().isOn; } public bool getIsPlayer() { return isPlayer; } public void updateChat(string msg) { chatBox.GetComponent<TMP_Text>().text += msg+"\n"; } public void updateReplay(string msg) { txtReplay.GetComponent<TMP_Text>().text += msg + "\n"; } public void updateUserName(string name) { currentPlayerName = name; lblInfo.GetComponent<Text>().text ="Logged in user: "+ name; } public void LoadPlayer(List<string> list) { ddlPlayer.GetComponent<Dropdown>().ClearOptions(); foreach (string it in list) { if (it.Contains(currentPlayerName)) { list.Remove(it); break; } } ddlPlayer.GetComponent<Dropdown>().AddOptions(list); } public void ReplayButtonPressed() { string msg = ""; if (chk2player.GetComponent<Toggle>().isOn) { btn11.GetComponentInChildren<Text>().text = "_"; btn12.GetComponentInChildren<Text>().text = "_"; btn13.GetComponentInChildren<Text>().text = "_"; btn21.GetComponentInChildren<Text>().text = "_"; btn22.GetComponentInChildren<Text>().text = "_"; btn23.GetComponentInChildren<Text>().text = "_"; btn31.GetComponentInChildren<Text>().text = "_"; btn32.GetComponentInChildren<Text>().text = "_"; btn33.GetComponentInChildren<Text>().text = "_"; msg = ClientToServerSignifiers.ReplayPlay + "," + "0,X"; } else { msg = ClientToServerSignifiers.ReplayMsg + "," + currentPlayerName; } Debug.Log("replay " + msg); networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); } // Update is called once per frame void Update() { } public void SendClientButtonPressed() { string msg = ClientToServerSignifiers.SendClientMsg + "," + ddlPlayer.GetComponent<Dropdown>().options[ddlPlayer.GetComponent<Dropdown>().value].text.ToString()+","+ txtCMsg.GetComponent<InputField>().text+","+currentPlayerName; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); Debug.Log("client send " + msg); } public void SendPrefButtonPressed() { string msg = ClientToServerSignifiers .SendPrefixMsg+","+ ddlMsg.GetComponent<Dropdown>().options[ddlMsg.GetComponent<Dropdown>().value].text.ToString() + "," + currentPlayerName; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); Debug.Log("sendpre " + msg); } public void SendButtonPressed() { string msg = ClientToServerSignifiers .SendMsg+","+ txtMsg.GetComponent<InputField>().text + "," + currentPlayerName; Debug.Log("msg:" + msg); networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); Debug.Log("send " + msg); } public void SubmitButtonPressed() { Debug.Log("button"); string p = txtPwd.GetComponent<InputField>().text; string n = txtUserId.GetComponent<InputField>().text; string msg; if (chkCreate.GetComponent<Toggle>().isOn) msg = ClientToServerSignifiers.CreateAccount + "," + n + "," + p; else msg = ClientToServerSignifiers.Login + "," + n + "," + p; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); } public void JoinButtonPressed() { //Debug.Log("join "); string msg = ""; if (chk2player.GetComponent<Toggle>().isOn) { msg = ClientToServerSignifiers.JoinDGameRoomQueue + "," + currentPlayerName; } else { msg = ClientToServerSignifiers.JoinChatRoomQueue + "," + currentPlayerName; } isPlayer = true; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); // ChangeState(GameStates.TicTacToe); } public void ObserveButtonPressed() { string msg = ""; if (chk2player.GetComponent<Toggle>().isOn) msg =ClientToServerSignifiers.JoinDAsObserver + ","+currentPlayerName; else msg = ClientToServerSignifiers.JoinAsObserver + "," + currentPlayerName; isPlayer = false; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); //ChangeState(GameStates.Observer); } public void CreateToggleChanged(bool newValue) { } public void PlayButtonPressed() { string msg = ClientToServerSignifiers.PlayGame + ""; networkedClient.GetComponent<NetworkedClient>().SendMessageToHost(msg); //load tictactoe ChangeState(GameStates.TickTacToePlay); } public void ChangeState(int newState) { //LoginSys.SetActive(false); //JoinSys.SetActive(false); btnJoin.SetActive(false); btnJoinObserver.SetActive(false); btnSubmit.SetActive(false); chkCreate.SetActive(false); txtPwd.SetActive(false); txtUserId.SetActive(false); lblU.SetActive(false); lblP.SetActive(false); //btnPlay.SetActive(false); //txtMsg, btnSend, ddlMsg, chatBox, btnSendPrefixMsg //MsgSend.SetActive(false); txtMsg.SetActive(false); btnSend.SetActive(false); //PMsgSend.SetActive(false); ddlMsg.SetActive(false); btnSendPrefixMsg.SetActive(false); //C2C.SetActive(false); ddlPlayer.SetActive(false); btnCSend.SetActive(false); txtCMsg.SetActive(false); chatBox.SetActive(false); pnlChat.SetActive(false); txtReplay.SetActive(false); btnReplay.SetActive(false); pnlReplay.SetActive(false); lblInfo.SetActive(false); chk2player.SetActive(false); btn11.SetActive(false); btn12.SetActive(false); btn13.SetActive(false); btn21.SetActive(false); btn22.SetActive(false); btn23.SetActive(false); btn31.SetActive(false); btn32.SetActive(false); btn33.SetActive(false); if (newState == GameStates.LoginMenu) { // LoginSys.SetActive(true); btnSubmit.SetActive(true); chkCreate.SetActive(true); txtPwd.SetActive(true); txtUserId.SetActive(true); lblU.SetActive(true); lblP.SetActive(true); } else if (newState == GameStates.MainMenu) { lblInfo.SetActive(true); //JoinSys.SetActive(true); btnJoin.SetActive(true); btnJoinObserver.SetActive(true); //MsgSend.SetActive(true); txtMsg.SetActive(true); btnSend.SetActive(true); //PMsgSend.SetActive(true); ddlMsg.SetActive(true); btnSendPrefixMsg.SetActive(true); //C2C.SetActive(true); ddlPlayer.SetActive(true); btnCSend.SetActive(true); txtCMsg.SetActive(true); chatBox.SetActive(true); pnlChat.SetActive(true); txtReplay.SetActive(true); btnReplay.SetActive(true); pnlReplay.SetActive(true); chk2player.SetActive(true); } else if (newState == GameStates.WaitingInQueue) { } else if (newState == GameStates.WaitingForPlayer) { lblInfo.GetComponent<Text>().text = "waiting for player"; } else if (newState == GameStates.Chatting) { lblInfo.SetActive(true); //btnPlay.SetActive(true); //MsgSend.SetActive(true); txtMsg.SetActive(true); btnSend.SetActive(true); //PMsgSend.SetActive(true); btnSendPrefixMsg.SetActive(true); ddlMsg.SetActive(true); //C2C.SetActive(true); ddlPlayer.SetActive(true); btnCSend.SetActive(true); txtCMsg.SetActive(true); chatBox.SetActive(true); pnlChat.SetActive(true); txtReplay.SetActive(true); btnReplay.SetActive(true); pnlReplay.SetActive(true); } else if (newState == GameStates.TickTacToePlay) { lblInfo.SetActive(true); btnReplay.SetActive(true); //btnPlay.SetActive(true); //MsgSend.SetActive(true); //txtMsg.SetActive(true); //btnSend.SetActive(true); //PMsgSend.SetActive(true); //btnSendPrefixMsg.SetActive(true); //ddlMsg.SetActive(true); //C2C.SetActive(true); //ddlPlayer.SetActive(true); //btnCSend.SetActive(true); //txtCMsg.SetActive(true); chatBox.SetActive(true); pnlChat.SetActive(true); // txtReplay.SetActive(true); //btnReplay.SetActive(true); //pnlReplay.SetActive(true); btn11.SetActive(true); btn12.SetActive(true); btn13.SetActive(true); btn21.SetActive(true); btn22.SetActive(true); btn23.SetActive(true); btn31.SetActive(true); btn32.SetActive(true); btn33.SetActive(true); if (btn11.GetComponentInChildren<Text>().text != "_") btn11.GetComponent<Button>().interactable = false; if (btn12.GetComponentInChildren<Text>().text != "_") btn12.GetComponent<Button>().interactable = false; if (btn13.GetComponentInChildren<Text>().text != "_") btn13.GetComponent<Button>().interactable = false; if (btn21.GetComponentInChildren<Text>().text != "_") btn21.GetComponent<Button>().interactable = false; if (btn22.GetComponentInChildren<Text>().text != "_") btn22.GetComponent<Button>().interactable = false; if (btn23.GetComponentInChildren<Text>().text != "_") btn23.GetComponent<Button>().interactable = false; if (btn31.GetComponentInChildren<Text>().text != "_") btn31.GetComponent<Button>().interactable = false; if (btn32.GetComponentInChildren<Text>().text != "_") btn32.GetComponent<Button>().interactable = false; if (btn33.GetComponentInChildren<Text>().text != "_") btn33.GetComponent<Button>().interactable = false; } else if (newState == GameStates.TickTacToeEnd) { chatBox.SetActive(true); pnlChat.SetActive(true); btnReplay.SetActive(true); // txtReplay.SetActive(true); //btnReplay.SetActive(true); //pnlReplay.SetActive(true); btn11.SetActive(true); btn12.SetActive(true); btn13.SetActive(true); btn21.SetActive(true); btn22.SetActive(true); btn23.SetActive(true); btn31.SetActive(true); btn32.SetActive(true); btn33.SetActive(true); btn11.GetComponent<Button>().interactable = false; btn12.GetComponent<Button>().interactable = false; btn13.GetComponent<Button>().interactable = false; btn21.GetComponent<Button>().interactable = false; btn22.GetComponent<Button>().interactable = false; btn23.GetComponent<Button>().interactable = false; btn31.GetComponent<Button>().interactable = false; btn32.GetComponent<Button>().interactable = false; btn33.GetComponent<Button>().interactable = false; } else if (newState == GameStates.TickTacToeReplay) { chatBox.SetActive(true); pnlChat.SetActive(true); btnReplay.SetActive(true); // txtReplay.SetActive(true); //btnReplay.SetActive(true); //pnlReplay.SetActive(true); btn11.SetActive(true); btn12.SetActive(true); btn13.SetActive(true); btn21.SetActive(true); btn22.SetActive(true); btn23.SetActive(true); btn31.SetActive(true); btn32.SetActive(true); btn33.SetActive(true); btn11.GetComponent<Button>().interactable = false; btn12.GetComponent<Button>().interactable = false; btn13.GetComponent<Button>().interactable = false; btn21.GetComponent<Button>().interactable = false; btn22.GetComponent<Button>().interactable = false; btn23.GetComponent<Button>().interactable = false; btn31.GetComponent<Button>().interactable = false; btn32.GetComponent<Button>().interactable = false; btn33.GetComponent<Button>().interactable = false; } else if (newState == GameStates.Observer) { lblInfo.SetActive(true); chatBox.SetActive(true); pnlChat.SetActive(true); txtReplay.SetActive(true); btnReplay.SetActive(true); pnlReplay.SetActive(true); //btn11.SetActive(true); //btn12.SetActive(true); //btn13.SetActive(true); //btn21.SetActive(true); //btn22.SetActive(true); //btn23.SetActive(true); //btn31.SetActive(true); //btn32.SetActive(true); //btn33.SetActive(true); //btn11.GetComponent<Button>().interactable = false; //btn12.GetComponent<Button>().interactable = false; //btn13.GetComponent<Button>().interactable = false; //btn21.GetComponent<Button>().interactable = false; //btn22.GetComponent<Button>().interactable = false; //btn23.GetComponent<Button>().interactable = false; //btn31.GetComponent<Button>().interactable = false; //btn32.GetComponent<Button>().interactable = false; //btn33.GetComponent<Button>().interactable = false; } } } static public class GameStates { public const int LoginMenu = 1; public const int MainMenu = 2; public const int WaitingInQueue = 3; public const int Chatting = 4; public const int WaitingForPlayer = 5; public const int TickTacToePlay = 6; public const int TickTacToeEnd = 6; public const int Observer = 7; public const int TickTacToeReplay = 6; }
35.383333
236
0.538271
[ "MIT" ]
shilaranidas/SimplestClient
Assets/GameSystemManager.cs
25,478
C#
using System.Collections.Generic; using System.Collections.Specialized; using KoAR.Core; using KoAR.SaveEditor.Constructs; namespace KoAR.SaveEditor.Views.Inventory { public sealed class ItemModel : ItemModelBase<Item> { private readonly NotifyingCollection<Buff> _itemBuffs; private readonly NotifyingCollection<Buff> _playerBuffs; public ItemModel(Item item) : base(item) { this._itemBuffs = new(item.ItemBuffs.List); this._itemBuffs.CollectionChanged += this.Buffs_CollectionChanged; this._playerBuffs = new(item.PlayerBuffs); this._playerBuffs.CollectionChanged += this.Buffs_CollectionChanged; } public override float CurrentDurability { get => base.CurrentDurability; set => this.SetItemValue(value); } public override bool IsStolen { get => base.IsStolen; set => this.SetItemValue(value); } public bool IsUnsellable { get => this.Item.IsUnsellable; set => this.SetItemValue(value); } public bool IsUnstashable { get => this.Item.IsUnstashable; set => this.SetItemValue(value); } public override IReadOnlyList<Buff> ItemBuffs => this._itemBuffs; public int ItemId => this.Item.ItemId; public int ItemIndex => this.Item.ItemOffset; public override string ItemName { get => base.ItemName; set { if (this.SetItemValue(value)) { this.OnPropertyChanged(nameof(this.HasCustomName)); this.OnPropertyChanged(nameof(this.DisplayName)); } } } public override byte Level { get => base.Level; set => this.SetItemValue(value); } public override float MaxDurability { get => base.MaxDurability; set => this.SetItemValue(value); } public override IReadOnlyList<Buff> PlayerBuffs => this._playerBuffs; public override Buff? Prefix { get => base.Prefix; set { if (!this.SetItemValue(value, $"{nameof(IItem.ItemBuffs)}.{nameof(this.Prefix)}")) { return; } this.OnPropertyChanged(nameof(this.AffixCount)); if (this.Item.Definition.AffixableName) { this.OnPropertyChanged(nameof(DisplayName)); this.OnPropertyChanged(nameof(DefinitionDisplayName)); } } } public override Buff? Suffix { get => base.Suffix; set { if (!this.SetItemValue(value, $"{nameof(IItem.ItemBuffs)}.{nameof(this.Suffix)}")) { return; } this.OnPropertyChanged(nameof(this.AffixCount)); if (this.Item.Definition.AffixableName) { this.OnPropertyChanged(nameof(DisplayName)); this.OnPropertyChanged(nameof(DefinitionDisplayName)); } } } public override bool UnsupportedFormat => this.Item.ItemBuffs.UnsupportedFormat; public void AddItemBuff(Buff buff) => this._itemBuffs.Add(buff); public void AddPlayerBuff(Buff buff) => this._playerBuffs.Add(buff); public void ChangeDefinition(ItemDefinition definition, bool retainStats) { this.Item.ChangeDefinition(definition, retainStats); this.OnPropertyChanged(string.Empty); this._playerBuffs.OnReset(); this._itemBuffs.OnReset(); } public void RemoveItemBuff(Buff buff) => this._itemBuffs.Remove(buff); public void RemovePlayerBuff(Buff buff) => this._playerBuffs.Remove(buff); protected override void Dispose(bool disposing) { this._playerBuffs.CollectionChanged -= this.Buffs_CollectionChanged; this._itemBuffs.CollectionChanged -= this.Buffs_CollectionChanged; base.Dispose(disposing); } private void Buffs_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => this.OnPropertyChanged(nameof(this.Rarity)); } }
31.559441
143
0.566142
[ "MIT" ]
mburbea/koar-item-editor
KoAR.SaveEditor/Views/Inventory/ItemModel.cs
4,515
C#
using System; using System.Collections.Generic; using System.Linq; namespace ElmahCore { public delegate void ExceptionFilterEventHandler(object sender, ExceptionFilterEventArgs args); [ Serializable ] public sealed class ExceptionFilterEventArgs : EventArgs { private readonly List<string> _notifiers = new List<string>(); internal IEnumerable<string> DismissedNotifiers => _notifiers; public ExceptionFilterEventArgs(Exception e, object context) { Exception = e ?? throw new ArgumentNullException(nameof(e)); Context = context; } public Exception Exception { get; } [field: NonSerialized] public object Context { get; } public bool Dismissed { get; private set; } public void Dismiss() { Dismissed = true; } public void DismissForNotifiers(IEnumerable<string> notifiers) { foreach (var notifier in notifiers) { if (!_notifiers.Any(i => i.Equals(notifier, StringComparison.InvariantCultureIgnoreCase))) { _notifiers.Add(notifier); } } Dismissed = true; } } }
27
106
0.607085
[ "Apache-2.0" ]
Aidan-Chang/ElmahCore
ElmahCore/ExceptionFiltering.cs
1,242
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MySql.Data.MySqlClient; using SocialNetwork.Infrastructure.Configuration; namespace SocialNetwork.Infrastructure.MySQL { public class MessagesDbContext : DbContext<MessagesReplicationGroupConnectionStrings> { public MessagesDbContext(SqlConnectionFactory<MessagesReplicationGroupConnectionStrings> connectionFactory) : base(connectionFactory) { } } public class DbContext : DbContext<ReplicationGroupConnectionStrings> { public DbContext(SqlConnectionFactory<ReplicationGroupConnectionStrings> connectionFactory) : base(connectionFactory) { } } public class DbContext<TSettings> : IAsyncDisposable, IDisposable where TSettings: class, IReplicationGroupConnectionStrings { private readonly List<Func<MySqlConnection, Task>> _commands; private readonly MySqlConnection _writeConnection; private readonly MySqlConnection _readConnection; private bool _isWriteConnectionOpen; private bool _isReadConnectionOpen; public DbContext(SqlConnectionFactory<TSettings> connectionFactory) { _writeConnection = connectionFactory.CreateMasterConnection(); _readConnection = connectionFactory.CreateReadConnection(); _commands = new List<Func<MySqlConnection, Task>>(); } public Task AddCommandAsync(Func<MySqlConnection, Task> func) { _commands.Add(func); return Task.CompletedTask; } public async Task<T> ExecuteQueryAsync<T>(Func<MySqlConnection, Task<T>> query, bool isUpdate = false) { if (isUpdate) { await OpenWriteConnectionAsync(); return await query(_writeConnection); } await OpenReadConnectionAsync(); return await query(_readConnection); } public async Task<int> SaveChangesAsync() { if (!_commands.Any()) return _commands.Count; await OpenWriteConnectionAsync(); await using (var transaction = await _writeConnection.BeginTransactionAsync()) { var commandTasks = _commands.Select(c => c(_writeConnection)).ToList(); await Task.WhenAll(commandTasks); await transaction.CommitAsync(); } var result = _commands.Count; _commands.Clear(); return result; } private async Task OpenWriteConnectionAsync() { if (!IsWriteConnectionOpen) { await _writeConnection.OpenAsync(); _isWriteConnectionOpen = true; } } private async Task OpenReadConnectionAsync() { if (!IsReadConnectionOpen) { await _readConnection.OpenAsync(); _isReadConnectionOpen = true; } } private bool IsWriteConnectionOpen => _writeConnection.Equals(_readConnection) ? _isWriteConnectionOpen || _isReadConnectionOpen : _isWriteConnectionOpen; private bool IsReadConnectionOpen => _writeConnection.Equals(_readConnection) ? _isWriteConnectionOpen || _isReadConnectionOpen : _isReadConnectionOpen; public async ValueTask DisposeAsync() { await SaveChangesAsync().ConfigureAwait(false); if (IsReadConnectionOpen) await _readConnection.CloseAsync().ConfigureAwait(false); if (IsWriteConnectionOpen) await _writeConnection.CloseAsync().ConfigureAwait(false); } public void Dispose() { DisposeAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } } }
30.8125
141
0.630578
[ "MIT" ]
andrew-kulikov/otus-architect
src/SocialNetwork.Infrastructure/MySQL/DbContext.cs
3,946
C#
using System.Collections; using System.Collections.Generic; using System.Configure; using System.Linq; using UnityEngine; namespace UnityEngine.Configure { public class ResourcesConfigurationSource : IConfigurationSource { public string Directory { get; private set; } public ResourcesConfigurationSource(string directory) { this.Directory = directory; } public IEnumerable<string> GetConfigNames() { return Resources.LoadAll(Directory, typeof(TextAsset)).Select(o => o.name + ".xml").ToArray(); } public string LoadData(string configName) { TextAsset textAsset = Resources.Load<TextAsset>(Directory + "/" + configName.Substring(0, configName.Length - 4)); return textAsset.text; } } }
26.03125
126
0.64946
[ "MIT" ]
liuwenjiexx/Unity.Configure
Assets/Plugins/Unity.Configure/Runtime/ResourcesConfigurationSource.cs
835
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using GRModels; namespace GRMVC.Models { public class RecordIndexVM { [DisplayName("Record")] public string RecordName { get; set; } [DisplayName("Artist")] public string ArtistName { get; set; } [DisplayName("Genre")] public Genre GenreType { get; set; } [DisplayName("Condition")] public Condition ConditionType { get; set; } [DisplayName("Format")] public Format FormatType { get; set; } public decimal Price { get; set; } public int ID { get; set; } } }
26.692308
52
0.62536
[ "MIT" ]
210215-USF-NET/Joaquin_Olivar-P1
GRMVC/Models/RecordIndexVM.cs
696
C#
using System.Linq; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation (XamlCompilationOptions.Compile)] namespace CoreSpotlightSearch { public class App : Application { public static TodoItemManager TodoManager { get; private set; } public static ITextToSpeech Speech { get; set; } public App () { TodoManager = new TodoItemManager (); MainPage = new NavigationPage (new TodoListPage ()); MessagingCenter.Subscribe <CoreSpotlightSearch.App, string> (this, "ShowItem", async (sender, arg) => { var todoItems = TodoManager.All; var item = todoItems.FirstOrDefault (i => i.ID == arg); await MainPage.Navigation.PopToRootAsync (); var todoItemPage = new TodoItemPage (); todoItemPage.BindingContext = item; await MainPage.Navigation.PushAsync (todoItemPage); }); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
23.808511
106
0.705987
[ "Apache-2.0" ]
Pkirugu/xamarin-recipes
cross-platform/xamarin-forms/iOS/CoreSpotlightSearch/CoreSpotlightSearch/App.cs
1,121
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adapter { public class ManagersData { public string GetQualifiedData() { return "AllManagers qualified data"; } } }
17.176471
48
0.657534
[ "MIT" ]
pories/DesignPatterns
DesignPatternsApp/Adapter/ManagersData.cs
294
C#
namespace Tagada.Swagger { internal enum SwaggerOperationMethod { Get = 1, Post, Put, Delete } }
12.909091
40
0.514085
[ "MIT" ]
Odonno/tagada
Tagada/Tagada.Swagger/SwaggerOperationMethod.cs
144
C#