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
// <copyright file="SoundTime.cs" company="KinsonDigital"> // Copyright (c) KinsonDigital. All rights reserved. // </copyright> namespace CASL { /// <summary> /// Represents a time value of a sound. /// </summary> /// <remarks> /// This could represent the current position or the length of a sound. /// </remarks> public struct SoundTime { /// <summary> /// Initializes a new instance of the <see cref="SoundTime"/> struct. /// </summary> /// <param name="totalSeconds">The total number of seconds of the time.</param> public SoundTime(float totalSeconds) { Milliseconds = totalSeconds * 1000f; Seconds = totalSeconds % 60f; Minutes = totalSeconds / 60f; } /// <summary> /// Gets the milliseconds of the sound. /// </summary> public float Milliseconds { get; } /// <summary> /// Gets the seconds of the sound. /// </summary> public float Seconds { get; } /// <summary> /// Gets the minutes of the sound. /// </summary> public float Minutes { get; } /// <summary> /// Gets the total number of seconds of the sound. /// </summary> public float TotalSeconds => Minutes * 60f; } }
28.595745
87
0.547619
[ "MIT" ]
KinsonDigital/CASL
CASL/SoundTime.cs
1,346
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Acme.BookStore.Migrations { public partial class Added_Books : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AppBooks", columns: table => new { Id = table.Column<Guid>(type: "uuid", nullable: false), Name = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false), Type = table.Column<int>(type: "integer", nullable: false), PublishDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false), Price = table.Column<float>(type: "real", nullable: false), ExtraProperties = table.Column<string>(type: "text", nullable: true), ConcurrencyStamp = table.Column<string>(type: "character varying(40)", maxLength: 40, nullable: true), CreationTime = table.Column<DateTime>(type: "timestamp without time zone", nullable: false), CreatorId = table.Column<Guid>(type: "uuid", nullable: true), LastModificationTime = table.Column<DateTime>(type: "timestamp without time zone", nullable: true), LastModifierId = table.Column<Guid>(type: "uuid", nullable: true), IsDeleted = table.Column<bool>(type: "boolean", nullable: false, defaultValue: false), DeleterId = table.Column<Guid>(type: "uuid", nullable: true), DeletionTime = table.Column<DateTime>(type: "timestamp without time zone", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AppBooks", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AppBooks"); } } }
49.785714
122
0.568627
[ "MIT" ]
antosubash/BookStore
src/Acme.BookStore.EntityFrameworkCore.DbMigrations/Migrations/20210214141311_Added_Books.cs
2,093
C#
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.IO; using System.Runtime.Serialization.Formatters.Binary; using log4net.Util; using NUnit.Framework; namespace log4net.Tests.Util { /// <summary> /// Used for internal unit testing the <see cref="PropertiesDictionary"/> class. /// </summary> /// <remarks> /// Used for internal unit testing the <see cref="PropertiesDictionary"/> class. /// </remarks> [TestFixture] public class PropertiesDictionaryTest { [Test] public void TestSerialization() { PropertiesDictionary pd = new PropertiesDictionary(); for(int i = 0; i < 10; i++) { pd[i.ToString()] = i; } Assert.AreEqual(10, pd.Count, "Dictionary should have 10 items"); // Serialize the properties into a memory stream BinaryFormatter formatter = new BinaryFormatter(); MemoryStream memory = new MemoryStream(); formatter.Serialize(memory, pd); // Deserialize the stream into a new properties dictionary memory.Position = 0; PropertiesDictionary pd2 = (PropertiesDictionary)formatter.Deserialize(memory); Assert.AreEqual(10, pd2.Count, "Deserialized Dictionary should have 10 items"); foreach(string key in pd.GetKeys()) { Assert.AreEqual(pd[key], pd2[key], "Check Value Persisted for key [{0}]", key); } } } }
31.149254
83
0.726881
[ "Apache-2.0" ]
gecambridge/logging-log4net
tests/src/Util/PropertiesDictionaryTest.cs
2,087
C#
using DevExpress.XtraEditors.Repository; using DevExpress.XtraGrid.Columns; using Tabular.Types; namespace Tabular.GridColumnExtensions { public class IntSpinEditGridColumn: GridColumn { public IntSpinEditGridColumn() { Init(); } public IntSpinEditGridColumn(IntSpinEditType textEditType) { Init(); Populate(textEditType); } private void Init() { ColumnEdit = new RepositoryItemSpinEdit(); } private void Populate(IntSpinEditType textEditType) { Name = string.Format("GridColumn_{0}", textEditType.Name); FieldName = textEditType.Name; Caption = textEditType.Caption; Visible = true; var repEditor = ColumnEdit as RepositoryItemSpinEdit; if (repEditor == null) return; repEditor.MinValue = textEditType.MinValue; repEditor.MaxValue = textEditType.MaxValue; } } }
25.55
70
0.599804
[ "Apache-2.0" ]
jtermine/tabular
Tabular/GridColumnExtensions/IntSpinEditGridColumn.cs
1,024
C#
using System; namespace Drenalol.TcpClientIo.Batches { /// <summary> /// TcpBatch creation or update rules /// </summary> public class TcpBatchRules<TResponse> { /// <summary> /// Creating rule of <see cref="ITcpBatch{TResponse}"/> /// </summary> public Func<TResponse, ITcpBatch<TResponse>> Create { get; set; } /// <summary> /// Update rule of <see cref="ITcpBatch{TResponse}"/> /// </summary> public Func<ITcpBatch<TResponse>, TResponse, ITcpBatch<TResponse>> Update { get; set; } /// <summary> /// Default rules for Create and Update /// </summary> public static TcpBatchRules<TResponse> Default => new TcpBatchRules<TResponse> { Create = response => { var batch = new DefaultTcpBatch<TResponse> {response}; return batch; }, Update = (batch, response) => { batch.Add(response); return batch; } }; } }
29.216216
95
0.523589
[ "MIT" ]
Drenalol/TcpClientDuplex
TcpClientIo.Core/Batches/TcpBatchRules.cs
1,083
C#
using System; using System.Collections.Generic; using CreepyTowers.Avatars; using CreepyTowers.Content; using DeltaEngine.Content; using DeltaEngine.Entities; using DeltaEngine.Scenes; using DeltaEngine.Scenes.Controls; namespace $safeprojectname$.GUI { public class AvatarSelectionMenu : Menu { public AvatarSelectionMenu() { sceneMaterials = new AvatarSelectionMaterials(); avatarSlots = new List<AvatarSlot>(); avatarList = (Content.Avatars[])Enum.GetValues(typeof(Content.Avatars)); count = 0; totalAvatarCount = Enum.GetValues(typeof(Content.Avatars)).Length; CreateScene(); } private readonly AvatarSelectionMaterials sceneMaterials; private readonly List<AvatarSlot> avatarSlots; private readonly Content.Avatars[] avatarList; private int count; private readonly int totalAvatarCount; protected override sealed void CreateScene() { Scene = ContentLoader.Load<Scene>(GameMenus.SceneAvatarSelection.ToString()); InitializeAvatarImageAndInfo(); CreateAvatarSlots(); UpdateAvatarSlots(); Hide(); AttachButtonEvents(); } private void InitializeAvatarImageAndInfo() { selectedAvatarImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.SelectedAvatarImage.ToString()); selectedAvatarInfo = (Picture)GetSceneControl(Content.AvatarSelectionMenu.SelectedAvatarInfo.ToString()); } private Picture selectedAvatarInfo; private Picture selectedAvatarImage; private void CreateAvatarSlots() { avatarSlots.Add(new AvatarSlot { IconImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot1.ToString()), LockImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot1Lock.ToString()), GemImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot1Gem.ToString()) }); avatarSlots.Add(new AvatarSlot { IconImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot2.ToString()), LockImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot2Lock.ToString()), GemImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot2Gem.ToString()) }); avatarSlots.Add(new AvatarSlot { IconImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot3.ToString()), LockImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot3Lock.ToString()), GemImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot3Gem.ToString()) }); avatarSlots.Add(new AvatarSlot { IconImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot4.ToString()), LockImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot4Lock.ToString()), GemImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot4Gem.ToString()) }); avatarSlots.Add(new AvatarSlot { IconImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot5.ToString()), LockImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot5Lock.ToString()), GemImage = (Picture)GetSceneControl(Content.AvatarSelectionMenu.AvatarSlot5Gem.ToString()) }); } private void UpdateAvatarSlots() { var slotCount = count; foreach (AvatarSlot avatarSlot in avatarSlots) { CheckIfAvatarIsUnlocked(avatarSlot, slotCount); slotCount++; } } private void CheckIfAvatarIsUnlocked(AvatarSlot avatarSlot, int index) { if (index >= totalAvatarCount || index < 0) { avatarSlot.IsVisible = false; return; } if (!avatarSlot.IsVisible) avatarSlot.IsVisible = true; avatarSlot.AvatarName = avatarList[index]; foreach (Avatar avatar in Player.Current.AvailableAvatars) if (IsAvatarAvailable(avatarSlot, avatar)) { avatarSlot.LockImage.IsVisible = false; avatarSlot.GemImage.IsVisible = false; avatarSlot.IconImage.Material = sceneMaterials.AvatarIconsMaterials[index]; return; } else { avatarSlot.LockImage.IsVisible = true; avatarSlot.GemImage.IsVisible = true; avatarSlot.IconImage.Material = sceneMaterials.AvatarIconsGreyMaterials[index]; } } private static bool IsAvatarAvailable(AvatarSlot avatarSlot, Entity avatar) { return avatar.GetTags().Contains(avatarSlot.AvatarName.ToString()); } private void AttachButtonEvents() { AddMoveLeftButtonEvent(); AddMoveRightButtonEvent(); AddBackButtonEvent(); AddButtonContinueEvent(); } private void AddMoveLeftButtonEvent() { var moveLeftButton = (InteractiveButton)GetSceneControl(Content.AvatarSelectionMenu.ButtonLeft.ToString()); moveLeftButton.Clicked += MoveOneItemLeft; } private void MoveOneItemLeft() { count--; if (count < -avatarSlots.Count / 2) { count = -avatarSlots.Count / 2; return; } UpdateAvatarSlots(); UpdateAvatarImageAndInfo(); } private void UpdateAvatarImageAndInfo() { selectedAvatarImage.Material = sceneMaterials.AvatarImageMaterials[count + 2]; selectedAvatarInfo.Material = sceneMaterials.AvatarInfoMaterials[count + 2]; } private void AddMoveRightButtonEvent() { var moveLeftButton = (InteractiveButton)GetSceneControl(Content.AvatarSelectionMenu.ButtonRight.ToString()); moveLeftButton.Clicked += MoveOneItemRight; } private void MoveOneItemRight() { count++; if (count >= (totalAvatarCount - avatarSlots.Count / 2)) { count = (totalAvatarCount - avatarSlots.Count / 2) - 1; return; } UpdateAvatarSlots(); UpdateAvatarImageAndInfo(); } private void AddBackButtonEvent() { var backButton = (InteractiveButton)GetSceneControl(Content.AvatarSelectionMenu.ButtonBack.ToString()); backButton.Clicked += () => ToggleVisibility(GameMenus.SceneAvatarSelection, GameMenus.SceneMainMenu); } private static void ToggleVisibility(GameMenus menuToHide, GameMenus menuToShow) { MenuController.Current.HideMenu(menuToHide); MenuController.Current.ShowMenu(menuToShow); } private void AddButtonContinueEvent() { var continueButton = (InteractiveButton)GetSceneControl(Content.AvatarSelectionMenu.ButtonContinue.ToString()); continueButton.Clicked += () => ToggleVisibility(GameMenus.SceneAvatarSelection, GameMenus.SceneNightmare1); } public override void Show() { if (Scene == null || Scene.Controls.Count == 0) return; Scene.Show(); UpdateAvatarSlots(); } public override void Reset() { count = 0; UpdateAvatarSlots(); UpdateAvatarImageAndInfo(); } } }
29.991189
95
0.718566
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
VisualStudioTemplates/Delta Engine/CreepyTowers/GUI/AvatarSelectionMenu.cs
6,808
C#
using System.Diagnostics.CodeAnalysis; using HarmonyLib; namespace SolastaCommunityExpansion.Patches.GameUi.Battle; [HarmonyPatch(typeof(BattleState_Victory), "Update")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class BattleState_Victory_Update { public static void Postfix() { if (!Main.Settings.AutoPauseOnVictory) { return; } if (Gui.Battle != null) { return; } if (ServiceRepository.GetService<INarrativeDirectionService>()?.CurrentSequence != null) { // Don't pause in the middle of a narrative sequence it hangs the game. // For example during the tutorial shoving the rock to destroy the bridge transitions // directly into a narrative sequence. I believe there are several other battle -> // narrative transitions in the game (like the crown vision paladin fight). return; } Gui.PauseGameAsNeeded(); } }
31.617647
106
0.651163
[ "MIT" ]
ChrisPJohn/SolastaCommunityExpansion
SolastaCommunityExpansion/Patches/GameUi/Battle/BattleState_VictoryUpdatePatcher.cs
1,077
C#
namespace NKnockoutUI.Tree { public class Handlers { public string SelectNode { get; set; } public string AddNode { get; set; } public string RenameNode { get; set; } public string DeleteNode { get; set; } public string MoveNode { get; set; } public string DoubleClick { get; set; } public string StartDrag { get; set; } public string EndDrag { get; set; } } }
29.2
47
0.591324
[ "MIT" ]
madcapnmckay/Knockout-UI
connectors/NKnockoutUI/Tree/Handlers.cs
440
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WinFormsMVC.Controller; using WinFormsMVC.Facade; using WinFormsMVC.Services; using WinFormsMVC.View; using WinFormsMVCSample.View; using WinFormsMVCSample.Controller; namespace WinFormsMVCSample { public class UserApplicationContext<T> : ApplicationContext where T : BaseForm { protected FormsManagement _form_manager; protected ViewFacadeCore FacadeCore; protected T _root_form; public UserApplicationContext() { // 初期化 try { _form_manager = new FormsManagement(); FacadeCore = new ViewFacade(_form_manager); _root_form = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]); _root_form.Closed += new EventHandler(OnFormClosed); } catch (Exception e) { MessageBox.Show(string.Format("例外が発生しました:\n{0}\n詳細は発注元に問い合わせください。\n", e.Message)); } // フォーム生成 _form_manager.LaunchForm(null, _root_form, false); } protected void OnFormClosed(object sender, EventArgs e) { ExitThread(); } } }
27.66
99
0.602314
[ "MIT" ]
belre/WinFormsMVC
WinFormsMVCSample/UserApplicationContext.cs
1,457
C#
using Microsoft.AspNetCore.Mvc; using Pierres.Models; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using Pierres.ViewModels; namespace Pierres.Controllers { public class AccountController : Controller { private readonly PierresContext _db; private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, PierresContext db) { _userManager = userManager; _signInManager = signInManager; _db = db; } public ActionResult Index() { return View(); } public IActionResult Register() { return View(); } [HttpPost] public async Task<ActionResult> Register(RegisterViewModel model) { var user = new ApplicationUser { UserName = model.Email }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return RedirectToAction("Index"); } else { return View(); } } public ActionResult Login() { return View(); } [HttpPost] public async Task<ActionResult> Login(LoginViewModel model) { Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: true, lockoutOnFailure: false); if (result.Succeeded) { return RedirectToAction("Index"); } else { return View(); } } [HttpPost] public async Task<ActionResult> LogOff() { await _signInManager.SignOutAsync(); return RedirectToAction("Index"); } } }
24.72973
173
0.673224
[ "MIT" ]
zakkreyshort/PierresSweetTreats
Pierres/Controllers/AccountController.cs
1,830
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace xTask; public interface ITaskEntry { IEnumerable<string> Aliases { get; } ITask Task { get; } }
24.909091
101
0.722628
[ "MIT" ]
JeremyKuhne/MacIO
xTask/Tasks/ITaskEntry.cs
276
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the finspace-data-2020-07-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.FinSpaceData.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.FinSpaceData.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateDataView operation /// </summary> public class CreateDataViewResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateDataViewResponse response = new CreateDataViewResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("datasetId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.DatasetId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("dataViewId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.DataViewId = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonFinSpaceDataException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateDataViewResponseUnmarshaller _instance = new CreateDataViewResponseUnmarshaller(); internal static CreateDataViewResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateDataViewResponseUnmarshaller Instance { get { return _instance; } } } }
40.772059
195
0.630658
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/FinSpaceData/Generated/Model/Internal/MarshallTransformations/CreateDataViewResponseUnmarshaller.cs
5,545
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace TheGrapho.Parser.Syntax { public sealed class DotAttributeListSyntax : DotSyntax { public DotAttributeListSyntax( [DisallowNull] IReadOnlyList<(PunctuationSyntax, DotAssignmentListSyntax?, PunctuationSyntax)> attributes) : base( SyntaxKind.DotAttributeList, attributes?.First().Item1?.FullWidth ?? 0, attributes?.Sum(it => (it.Item1?.FullWidth ?? 0) + (it.Item2?.FullWidth ?? 0) + (it.Item3?.FullWidth ?? 0)) ?? 0, attributes?.SelectMany(it => new SyntaxNode?[] {it.Item1, it.Item2, it.Item3}).ToList()) { Attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); if (attributes.Count == 0) throw new IndexOutOfRangeException(nameof(attributes)); foreach (var (leftBracket, _, rightBracket) in attributes) { if (leftBracket == null) throw new ArgumentNullException(nameof(attributes)); if (rightBracket == null) throw new ArgumentNullException(nameof(attributes)); } } [NotNull] public IReadOnlyList<(PunctuationSyntax LeftSquareBracket, DotAssignmentListSyntax? AssignmentList, PunctuationSyntax RightSquareBracket)> Attributes { get; } [return: MaybeNull] public override TResult Accept<TResult>([DisallowNull] DotSyntaxVisitor<TResult> syntaxVisitor) { if (syntaxVisitor == null) throw new ArgumentNullException(nameof(syntaxVisitor)); return syntaxVisitor.VisitAttributeList(this); } public override void Accept([DisallowNull] DotSyntaxVisitor syntaxVisitor) { if (syntaxVisitor == null) throw new ArgumentNullException(nameof(syntaxVisitor)); syntaxVisitor.VisitAttributeList(this); } [return: NotNull] public override string ToString() => $"{base.ToString()}, {nameof(Attributes)}: {Attributes}"; } }
44.132075
120
0.64985
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ssyp-ru/ssyp-ws09
TheGrapho.Parser/Syntax/DotAttributeListSyntax.cs
2,341
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGame2D { public class Map : GameObject { public override void Click() { } } }
14.529412
36
0.651822
[ "MIT" ]
Devdood/Bridge.NET-MMORPG
TestGame2D/Models/Map.cs
249
C#
#pragma checksum "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "c318659bd8a18ea07e93236ad74da48f5364eada" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_SongChords_Index), @"mvc.1.0.view", @"/Views/SongChords/Index.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/SongChords/Index.cshtml", typeof(AspNetCore.Views_SongChords_Index))] 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; #line 1 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\_ViewImports.cshtml" using WebApp; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c318659bd8a18ea07e93236ad74da48f5364eada", @"/Views/SongChords/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"acc6ad5436936d69f19a0c25649740de595ab008", @"/Views/_ViewImports.cshtml")] public class Views_SongChords_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<BLL.App.DTO.DomainEntityDTOs.SongChord>> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Details", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(60, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" ViewData["Title"] = "Index"; #line default #line hidden BeginContext(103, 29, true); WriteLiteral("\r\n<h1>Index</h1>\r\n\r\n<p>\r\n "); EndContext(); BeginContext(132, 37, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c318659bd8a18ea07e93236ad74da48f5364eada4605", async() => { BeginContext(155, 10, true); WriteLiteral("Create New"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(169, 92, true); WriteLiteral("\r\n</p>\r\n<table class=\"table\">\r\n <thead>\r\n <tr>\r\n <th>\r\n "); EndContext(); BeginContext(262, 40, false); #line 16 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" Write(Html.DisplayNameFor(model => model.Song)); #line default #line hidden EndContext(); BeginContext(302, 55, true); WriteLiteral("\r\n </th>\r\n <th>\r\n "); EndContext(); BeginContext(358, 41, false); #line 19 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" Write(Html.DisplayNameFor(model => model.Chord)); #line default #line hidden EndContext(); BeginContext(399, 86, true); WriteLiteral("\r\n </th>\r\n <th></th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n"); EndContext(); #line 25 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" foreach (var item in Model) { #line default #line hidden BeginContext(517, 48, true); WriteLiteral(" <tr>\r\n <td>\r\n "); EndContext(); BeginContext(566, 46, false); #line 28 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" Write(Html.DisplayFor(modelItem => item.Song.Author)); #line default #line hidden EndContext(); BeginContext(612, 55, true); WriteLiteral("\r\n </td>\r\n <td>\r\n "); EndContext(); BeginContext(668, 45, false); #line 31 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" Write(Html.DisplayFor(modelItem => item.Chord.Name)); #line default #line hidden EndContext(); BeginContext(713, 55, true); WriteLiteral("\r\n </td>\r\n <td>\r\n "); EndContext(); BeginContext(768, 53, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c318659bd8a18ea07e93236ad74da48f5364eada8118", async() => { BeginContext(813, 4, true); WriteLiteral("Edit"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #line 34 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" WriteLiteral(item.Id); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(821, 20, true); WriteLiteral(" |\r\n "); EndContext(); BeginContext(841, 59, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c318659bd8a18ea07e93236ad74da48f5364eada10464", async() => { BeginContext(889, 7, true); WriteLiteral("Details"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #line 35 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" WriteLiteral(item.Id); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(900, 20, true); WriteLiteral(" |\r\n "); EndContext(); BeginContext(920, 57, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c318659bd8a18ea07e93236ad74da48f5364eada12817", async() => { BeginContext(967, 6, true); WriteLiteral("Delete"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #line 36 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" WriteLiteral(item.Id); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(977, 36, true); WriteLiteral("\r\n </td>\r\n </tr>\r\n"); EndContext(); #line 39 "C:\Users\X\RiderProjects\Learn2Play\Learn2Play\WebApp\Views\SongChords\Index.cshtml" } #line default #line hidden BeginContext(1016, 24, true); WriteLiteral(" </tbody>\r\n</table>\r\n"); EndContext(); } #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<IEnumerable<BLL.App.DTO.DomainEntityDTOs.SongChord>> Html { get; private set; } } } #pragma warning restore 1591
61.804598
300
0.694749
[ "MIT" ]
JanekV/Learn2Play
Learn2Play/WebApp/obj/Debug/netcoreapp2.2/Razor/Views/SongChords/Index.g.cshtml.cs
16,131
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GeoSphereBaseFaces { public static readonly int baseFacesCount = 80; public static readonly Vector3[] vertices = new Vector3[] { new Vector3(-0.4472136f, 0.8506508f, -0.2763932f), new Vector3(-0.5257311f, 0.8090169f, 0.2628656f), new Vector3(0f, 1f, 0f), new Vector3(-0.4472136f, 0.5257311f, 0.7236068f), new Vector3(0f, 0.8090169f, 0.5877853f), new Vector3(0.4472136f, 0.8506508f, 0.2763932f), new Vector3(0.5257311f, 0.8090169f, -0.2628656f), new Vector3(0.4472136f, 0.5257311f, -0.7236068f), new Vector3(0f, 0.8090169f, -0.5877853f), new Vector3(0.8506508f, 0.5f, 0.1624598f), new Vector3(1f, 0f, 0f), new Vector3(0.8506508f, 0.309017f, -0.4253253f), new Vector3(0.525731f, 0.5f, 0.6881909f), new Vector3(0.4472136f, 0f, 0.8944272f), new Vector3(0.8506508f, 0f, 0.5257311f), new Vector3(-1f, 0f, 0f), new Vector3(-0.8506508f, 0.5f, -0.1624598f), new Vector3(-0.8506508f, 0f, -0.5257311f), new Vector3(-0.525731f, 0.5f, -0.6881909f), new Vector3(-0.4472136f, 0f, -0.8944272f), new Vector3(-0.8506508f, 0.309017f, 0.4253253f), new Vector3(-0.8506508f, -0.309017f, 0.4253253f), new Vector3(-0.4472136f, -0.5257311f, 0.7236068f), new Vector3(-0.5257311f, 0f, 0.8506508f), new Vector3(-0f, 0.309017f, -0.9510564f), new Vector3(0f, 0.309017f, 0.9510564f), new Vector3(0.5257311f, 0f, -0.8506508f), new Vector3(0.4472136f, -0.5257311f, -0.7236068f), new Vector3(-0f, -0.309017f, -0.9510564f), new Vector3(0f, -0.309017f, 0.9510564f), new Vector3(0.8506508f, -0.309017f, -0.4253253f), new Vector3(0.8506508f, -0.5f, 0.1624598f), new Vector3(0.4472136f, -0.8506508f, 0.2763932f), new Vector3(0.5257311f, -0.8090169f, -0.2628656f), new Vector3(0.525731f, -0.5f, 0.6881909f), new Vector3(0f, -0.8090169f, 0.5877853f), new Vector3(-0.8506508f, -0.5f, -0.1624598f), new Vector3(-0.525731f, -0.5f, -0.6881909f), new Vector3(-0.4472136f, -0.8506508f, -0.2763932f), new Vector3(-0.5257311f, -0.8090169f, 0.2628656f), new Vector3(0f, -1f, 0f), new Vector3(0f, -0.8090169f, -0.5877853f) }; public static readonly int[] triangles = new int[] { 0,1,2, 3,4,1, 5,2,4, 1,4,2, 5,6,2, 7,8,6, 0,2,8, 6,8,2, 5,9,6, 10,11,9, 7,6,11, 9,11,6, 5,12,9, 13,14,12, 10,9,14, 12,14,9, 15,16,17, 0,18,16, 19,17,18, 16,18,17, 0,16,1, 15,20,16, 3,1,20, 16,20,1, 15,21,20, 22,23,21, 3,20,23, 21,23,20, 0,8,18, 7,24,8, 19,18,24, 8,24,18, 5,4,12, 3,25,4, 13,12,25, 4,25,12, 7,26,24, 27,28,26, 19,24,28, 26,28,24, 3,23,25, 22,29,23, 13,25,29, 23,29,25, 10,30,11, 27,26,30, 7,11,26, 30,26,11, 10,31,30, 32,33,31, 27,30,33, 31,33,30, 13,34,14, 32,31,34, 10,14,31, 34,31,14, 32,34,35, 13,29,34, 22,35,29, 34,29,35, 15,17,36, 19,37,17, 38,36,37, 17,37,36, 22,21,39, 15,36,21, 38,39,36, 21,36,39, 22,39,35, 38,40,39, 32,35,40, 39,40,35, 38,37,41, 19,28,37, 27,41,28, 37,28,41, 32,40,33, 38,41,40, 27,33,41, 40,41,33 }; }
29.489051
63
0.483663
[ "MIT" ]
45545xax/WorldMaker
Assets/Scripts/Geosphere/GeoSphereBaseFaces.cs
4,042
C#
namespace CookWithMe.Services.Data.Lifestyles { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CookWithMe.Data.Common.Repositories; using CookWithMe.Data.Models; using CookWithMe.Services.Mapping; using CookWithMe.Services.Models.Lifestyles; using Microsoft.EntityFrameworkCore; public class LifestyleService : ILifestyleService { private const string InvalidLifestyleIdErrorMessage = "Lifestyle with ID: {0} does not exist."; private const string InvalidLifestyleTypeErrorMessage = "Lifestyle with Type: {0} does not exist."; private readonly IRepository<Lifestyle> lifestyleRepository; public LifestyleService(IRepository<Lifestyle> lifestyleRepository) { this.lifestyleRepository = lifestyleRepository; } public async Task<bool> CreateAllAsync(string[] lifestyleTypes) { foreach (var lifestyleType in lifestyleTypes) { var lifestyle = new Lifestyle { Type = lifestyleType, }; await this.lifestyleRepository.AddAsync(lifestyle); } var result = await this.lifestyleRepository.SaveChangesAsync(); return result > 0; } public async Task<IEnumerable<string>> GetAllTypesAsync() { return await this.lifestyleRepository .AllAsNoTracking() .Select(x => x.Type) .ToListAsync(); } public async Task<LifestyleServiceModel> GetByIdAsync(int id) { var lifestyle = await this.lifestyleRepository .AllAsNoTracking() .SingleOrDefaultAsync(x => x.Id == id); if (lifestyle == null) { throw new ArgumentNullException( string.Format(InvalidLifestyleIdErrorMessage, id)); } return lifestyle.To<LifestyleServiceModel>(); } public async Task<int> GetIdByTypeAsync(string lifestyleType) { var lifestyle = await this.lifestyleRepository .AllAsNoTracking() .SingleOrDefaultAsync(x => x.Type == lifestyleType); if (lifestyle == null) { throw new ArgumentNullException( string.Format(InvalidLifestyleTypeErrorMessage, lifestyleType)); } return lifestyle.Id; } public async Task SetLifestyleToRecipeAsync(string lifestyleType, Recipe recipe) { var lifestyle = await this.lifestyleRepository.All() .SingleOrDefaultAsync(x => x.Type == lifestyleType); if (lifestyle == null) { throw new ArgumentNullException( string.Format(InvalidLifestyleTypeErrorMessage, lifestyleType)); } recipe.Lifestyles.Add(new RecipeLifestyle { Lifestyle = lifestyle, }); } public async Task SetLifestyleToUserAsync(string lifestyleType, ApplicationUser user) { var lifestyle = await this.lifestyleRepository.All() .SingleOrDefaultAsync(x => x.Type == lifestyleType); if (lifestyle == null) { throw new ArgumentNullException( string.Format(InvalidLifestyleTypeErrorMessage, lifestyleType)); } user.Lifestyle = lifestyle; } } }
31.877193
107
0.583654
[ "MIT" ]
VioletaKirova/CookWithMe
Services/CookWithMe.Services.Data/Lifestyles/LifestyleService.cs
3,636
C#
using AllureSpecFlow; using TechTalk.SpecFlow.Bindings; using TechTalk.SpecFlow.Plugins; using TechTalk.SpecFlow.Tracing; using TechTalk.SpecFlow.UnitTestProvider; [assembly: RuntimePlugin(typeof(AllurePlugin))] namespace AllureSpecFlow { public class AllurePlugin : IRuntimePlugin { public void Initialize(RuntimePluginEvents runtimePluginEvents, RuntimePluginParameters runtimePluginParameters, UnitTestProviderConfiguration unitTestProviderConfiguration) { runtimePluginEvents.CustomizeGlobalDependencies += (sender, args) => args.ObjectContainer.RegisterTypeAs<AllureBindingInvoker, IBindingInvoker>(); runtimePluginEvents.CustomizeTestThreadDependencies += (sender, args) => args.ObjectContainer.RegisterTypeAs<AllureTestTracerWrapper, ITestTracer>(); } } }
37.826087
120
0.750575
[ "MIT" ]
DanielVuurboom/Allure.NUnit
AllureSpecFlow/AllurePlugin.cs
872
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.Collections.Generic; using System.Data.SqlClient; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Migrations.Model; using Microsoft.Data.Entity.Relational; using Microsoft.Data.Entity.SqlServer.Utilities; using Microsoft.Data.Entity.Storage; namespace Microsoft.Data.Entity.SqlServer { public class SqlServerDataStoreCreator : DataStoreCreator { private readonly SqlServerConnection _connection; private readonly ModelDiffer _modelDiffer; private readonly SqlServerMigrationOperationSqlGenerator _sqlGenerator; private readonly SqlStatementExecutor _statementExecutor; public SqlServerDataStoreCreator( [NotNull] SqlServerConnection connection, [NotNull] ModelDiffer modelDiffer, [NotNull] SqlServerMigrationOperationSqlGenerator sqlGenerator, [NotNull] SqlStatementExecutor statementExecutor) { Check.NotNull(connection, "connection"); Check.NotNull(modelDiffer, "modelDiffer"); Check.NotNull(sqlGenerator, "sqlGenerator"); Check.NotNull(statementExecutor, "statementExecutor"); _connection = connection; _modelDiffer = modelDiffer; _sqlGenerator = sqlGenerator; _statementExecutor = statementExecutor; } public override void Create() { using (var masterConnection = _connection.CreateMasterConnection()) { _statementExecutor.ExecuteNonQuery(masterConnection, CreateCreateOperations()); ClearPool(); } } public override async Task CreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { using (var masterConnection = _connection.CreateMasterConnection()) { await _statementExecutor.ExecuteNonQueryAsync(masterConnection, CreateCreateOperations(), cancellationToken); ClearPool(); } } public override void CreateTables(IModel model) { Check.NotNull(model, "model"); _statementExecutor.ExecuteNonQuery(_connection.DbConnection, CreateSchemaCommands(model)); } public override async Task CreateTablesAsync(IModel model, CancellationToken cancellationToken = default(CancellationToken)) { Check.NotNull(model, "model"); await _statementExecutor.ExecuteNonQueryAsync(_connection.DbConnection, CreateSchemaCommands(model), cancellationToken); } public override bool HasTables() { return (int)_statementExecutor.ExecuteScalar(_connection.DbConnection, CreateHasTablesCommand()) != 0; } public override async Task<bool> HasTablesAsync(CancellationToken cancellationToken = new CancellationToken()) { return (int)(await _statementExecutor.ExecuteScalarAsync(_connection.DbConnection, CreateHasTablesCommand(), cancellationToken)) != 0; } private IEnumerable<SqlStatement> CreateSchemaCommands(IModel model) { return _sqlGenerator.Generate(_modelDiffer.DiffSource(model), generateIdempotentSql: false); } private SqlStatement CreateHasTablesCommand() { return new SqlStatement("IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES) SELECT 1 ELSE SELECT 0"); } private IEnumerable<SqlStatement> CreateCreateOperations() { // TODO Check DbConnection.Database always gives us what we want var databaseName = _connection.DbConnection.Database; var operations = new MigrationOperation[] { new CreateDatabaseOperation(databaseName) }; var masterCommands = _sqlGenerator.Generate(operations, generateIdempotentSql: false); return masterCommands; } public override bool Exists() { var retryCount = 0; while (true) { try { _connection.Open(); _connection.Close(); return true; } catch (SqlException e) { if (IsDoesNotExist(e)) { return false; } if (!RetryOnNoProcessOnEndOfPipe(e, ref retryCount)) { throw; } } } } public override async Task<bool> ExistsAsync(CancellationToken cancellationToken = default(CancellationToken)) { var retryCount = 0; while (true) { try { await _connection.OpenAsync(cancellationToken); _connection.Close(); return true; } catch (SqlException e) { if (IsDoesNotExist(e)) { return false; } if (!RetryOnNoProcessOnEndOfPipe(e, ref retryCount)) { throw; } } } } private static bool IsDoesNotExist(SqlException exception) { // TODO Explore if there are important scenarios where this could give a false negative // Login failed is thrown when database does not exist return exception.Number == 4060; } private bool RetryOnNoProcessOnEndOfPipe(SqlException exception, ref int retryCount) { // This is to handle the case where Open throws: // System.Data.SqlClient.SqlException : A connection was successfully established with the // server, but then an error occurred during the login process. (provider: Named Pipes // Provider, error: 0 - No process is on the other end of the pipe.) // It appears that this happens when the database has just been created but has not yet finished // opening or is auto-closing when using the AUTO_CLOSE option. The workaround is to flush the pool // for the connection and then retry the Open call. if (exception.Number == 233 && retryCount++ < 3) { ClearPool(); return true; } return false; } public override void Delete() { ClearAllPools(); using (var masterConnection = _connection.CreateMasterConnection()) { _statementExecutor.ExecuteNonQuery(masterConnection, CreateDropCommands()); } } public override async Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken)) { ClearAllPools(); using (var masterConnection = _connection.CreateMasterConnection()) { await _statementExecutor.ExecuteNonQueryAsync(masterConnection, CreateDropCommands(), cancellationToken); } } private IEnumerable<SqlStatement> CreateDropCommands() { var operations = new MigrationOperation[] { // TODO Check DbConnection.Database always gives us what we want new DropDatabaseOperation(_connection.DbConnection.Database) }; var masterCommands = _sqlGenerator.Generate(operations, generateIdempotentSql: false); return masterCommands; } private static void ClearAllPools() { // Clear connection pools in case there are active connections that are pooled SqlConnection.ClearAllPools(); } private void ClearPool() { // Clear connection pool for the database connection since after the 'create database' call, a previously // invalid connection may now be valid. SqlConnection.ClearPool((SqlConnection)_connection.DbConnection); } } }
37.376623
146
0.596363
[ "Apache-2.0" ]
avdinfotech/EntityFramework
src/Microsoft.Data.Entity.SqlServer/SqlServerDataStoreCreator.cs
8,634
C#
using UnityEngine; using System.Collections; [AddComponentMenu("Alterations/Hue Alteration")] public class HueAlteration : ObjectAlteration { bool isSet; public Color ColorAlteration; Color originalColor; // Use this for initialization public override void Set() { isSet = true; originalColor = this.renderer.material.color; Debug.Log(this.name + ": color " + ColorAlteration); this.renderer.material.color = ColorAlteration; } // Update is called once per frame public override void Reset() { if (isSet) this.renderer.material.color = originalColor; } }
23.428571
60
0.660061
[ "MIT" ]
justinmchase/GameCraftMN
src/Assets/Scripts/Alterations/HueAlteration.cs
658
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Threading; namespace Reaqtor.ReificationFramework { /// <summary> /// Operation to repeat an operation until a cancellation is requested. /// </summary> public class RepeatUntil : OperationBase { internal RepeatUntil(ReifiedOperation operation, CancellationToken token) : base(ReifiedOperationKind.RepeatUntil, operation) { Token = token; } /// <summary> /// The cancellation token. /// </summary> public CancellationToken Token { get; } } }
29.461538
81
0.656658
[ "MIT" ]
Botcoin-com/reaqtor
Reaqtor/Core/Testing/Reaqtor.ReificationFramework/Operations/RepeatUntil.cs
768
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; namespace Sce.Atf.Dom { /// <summary> /// Adapts a DOM node to implement IDocument</summary> public class DomDocument : DomResource, IDocument { #region IDocument Members /// <summary> /// Gets whether the document is read-only</summary> public virtual bool IsReadOnly { get { return false; } } /// <summary> /// Gets or sets whether the document is dirty (does it differ from its file)</summary> public virtual bool Dirty { get { return m_dirty; } set { if (value != m_dirty) { m_dirty = value; OnDirtyChanged(EventArgs.Empty); } } } /// <summary> /// Event that is raised when the Dirty property changes</summary> public event EventHandler DirtyChanged; #endregion /// <summary> /// Raises the DirtyChanged event</summary> /// <param name="e">Event args</param> protected virtual void OnDirtyChanged(EventArgs e) { DirtyChanged.Raise(this, e); } /// <summary> /// Raises the IObservableContext.Reloaded event</summary> /// <param name="args">Event args</param> protected virtual void OnReloaded(EventArgs args) { } private bool m_dirty; } }
26.206349
96
0.502726
[ "Apache-2.0" ]
StirfireStudios/ATF
Framework/Atf.Core/Dom/DomDocument.cs
1,592
C#
using static TensorShader.VariableNode; namespace TensorShader { public partial class Field { /// <summary>符号</summary> public static Field Sign(Field x) { Field y = new(); Link link = new Links.UnaryArithmetric.Sign(x, y); link.Forward(); return y; } } } namespace TensorShader.Links.UnaryArithmetric { /// <summary>符号</summary> internal class Sign : UnaryArithmetric { /// <summary>コンストラクタ</summary> public Sign(Field infield, Field outfield) : base(infield, outfield) { } /// <summary>順伝搬</summary> public override void Forward() { Y.AssignValue(Sign(X.Value)); } } }
24.4
62
0.569672
[ "MIT" ]
tk-yoshimura/TensorShader
TensorShader/Links/UnaryArithmetric/Sign.cs
760
C#
// <copyright file="RiakIndexId.cs" company="Basho Technologies, Inc."> // Copyright 2011 - OJ Reeves & Jeremiah Peschka // Copyright 2014 - Basho Technologies, Inc. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </copyright> namespace RiakClient.Models { using System; /// <summary> /// An Id that specifies a specific index in Riak. Immutable once created. /// </summary> public class RiakIndexId : IEquatable<RiakIndexId> { private readonly string bucketName; private readonly string bucketType; private readonly string indexName; /// <summary> /// Initializes a new instance of the <see cref="RiakIndexId" /> class. /// </summary> /// <param name="bucketName">The bucket name to use.</param> /// <param name="indexName">The index name to use.</param> public RiakIndexId(string bucketName, string indexName) : this(null, bucketName, indexName) { } /// <summary> /// Initializes a new instance of the <see cref="RiakIndexId" /> class. /// </summary> /// <param name="bucketType">The bucket type to use.</param> /// <param name="bucketName">The bucket name to use.</param> /// <param name="indexName">The index name to use.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="bucketName"/> cannot be null, empty, or whitespace.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="indexName"/> cannot be null, empty, or whitespace.</exception> public RiakIndexId(string bucketType, string bucketName, string indexName) { if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentOutOfRangeException("bucketName", "bucketName cannot be null, empty, or whitespace."); } if (string.IsNullOrEmpty(indexName)) { throw new ArgumentOutOfRangeException("indexName", "indexName cannot be null, empty, or whitespace."); } this.bucketType = bucketType; this.bucketName = bucketName; this.indexName = indexName; } /// <summary> /// Get the Bucket Type of the Index Id. /// </summary> public string BucketType { get { return bucketType; } } /// <summary> /// Get the Bucket Name of the Index Id. /// </summary> public string BucketName { get { return bucketName; } } /// <summary> /// Get the Index Name of the Index Id. /// </summary> public string IndexName { get { return indexName; } } /// <summary> /// Determines whether the one object is equal to another object. /// </summary> /// <param name="left">The first <see cref="RiakIndexId"/> to compare.</param> /// <param name="right">The other <see cref="RiakIndexId"/> to compare.</param> /// <returns><b>true</b> if the specified object is equal to the current object, otherwise, <b>false</b>.</returns> public static bool operator ==(RiakIndexId left, RiakIndexId right) { return Equals(left, right); } /// <summary> /// Determines whether the one object is <b>not</b> equal to another object. /// </summary> /// <param name="left">The first <see cref="RiakObjectId"/> to compare.</param> /// <param name="right">The other <see cref="RiakObjectId"/> to compare.</param> /// <returns><b>true</b> if the specified object is <b>not</b> equal to the current object, otherwise, <b>false</b>.</returns> public static bool operator !=(RiakIndexId left, RiakIndexId right) { return !Equals(left, right); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="other">The object to compare with the current object.</param> /// <returns><b>true</b> if the specified object is equal to the current object, otherwise, <b>false</b>.</returns> public bool Equals(RiakIndexId other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return string.Equals(bucketName, other.bucketName) && string.Equals(bucketType, other.bucketType) && string.Equals(indexName, other.indexName); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns><b>true</b> if the specified object is equal to the current object, otherwise, <b>false</b>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return Equals(obj as RiakIndexId); } /// <summary> /// Returns a hash code for the current object. /// Uses a combination of the public properties to generate a unique hash code. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { unchecked { var hashCode = bucketName != null ? bucketName.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (bucketType != null ? bucketType.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (indexName != null ? indexName.GetHashCode() : 0); return hashCode; } } internal RiakBinIndexId ToBinIndexId() { return new RiakBinIndexId(BucketType, BucketName, IndexName); } internal RiakIntIndexId ToIntIndexId() { return new RiakIntIndexId(BucketType, BucketName, IndexName); } } }
38.606557
138
0.565322
[ "Apache-2.0" ]
askovsgaard/riak-dotnet-client
src/RiakClient/Models/RiakIndexId.cs
6,883
C#
using Brakt.Bot.Formatters; using Brakt.Bot.Identification; using Brakt.Bot.Interpretor; using Brakt.Client; using DSharpPlus.EventArgs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Brakt.Bot.Commands { public class ResultsCommandHandler : CommandHandlerBase, ICommandHandler { public ResultsCommandHandler(IBraktApiClient client, IResponseFormatter formatter) : base(client, formatter) { } public string Command => "results"; public string HelpMessage => "If tournament concluded, shows tournament winner. If underway, shows last round results.\n * [tournament id] - an integer id given when a tournament is generated.This can be found with the list command if it has been forgotten."; public override async Task ExecuteAsync(MessageCreateEventArgs args, CommandTokens cmdToken, IdContext userContext, CancellationToken cancellationToken) { AssertGroupMemberContext(userContext); if (!TryGetTournamentId(cmdToken.Arguments, out int tournamentId)) { await args.Message.RespondAsync("TournamentId argument required."); return; } var tournament = await Client.GetTournamentAsync(tournamentId, cancellationToken); AssertTournamentExists(tournament); AssertTournamentBelongsToGroup(tournament, userContext.GroupMember.GroupId); var message = await Formatter.FormatTournamentResultsAsync(tournament, cancellationToken); await args.Message.RespondAsync(message); } } }
37.361702
250
0.692483
[ "MIT" ]
mark-roberts1/Brakt
Brakt.Bot/Commands/ResultsCommandHandler.cs
1,758
C#
using System; using NUnit.Framework; namespace UnityEngine.Analytics.Tests { public partial class AnalyticsEventTests { [Test] public void TutorialStep_StepIndexTest( [Values(-1, 0, 1)] int stepIndex ) { Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex)); EvaluateAnalyticsResult(m_Result); } [Test] public void TutorialStep_TutorialIdTest( [Values("test_tutorial", "", null)] string tutorialId ) { var stepIndex = 0; Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex, tutorialId)); EvaluateAnalyticsResult(m_Result); } [Test] public void TutorialStep_CustomDataTest() { var stepIndex = 0; var tutorialId = "test_tutorial"; Assert.DoesNotThrow(() => m_Result = AnalyticsEvent.TutorialStep(stepIndex, tutorialId, m_CustomData)); EvaluateCustomData(m_CustomData); EvaluateAnalyticsResult(m_Result); } } }
29.35
116
0.573254
[ "Unlicense" ]
ArnaudTang/PinguinGame
EmptyProject/Library/PackageCache/com.unity.analytics@3.6.11/Tests/Editor/TutorialStepTests.cs
1,174
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace gs.Services { public interface IDataStore<T> { Task<bool> AddItemAsync(T item); Task<bool> UpdateItemAsync(T item); Task<bool> DeleteItemAsync(string id); Task<T> GetItemAsync(string id); Task<IEnumerable<T>> GetItemsAsync(bool forceRefresh = false); } }
24.8125
70
0.677582
[ "MIT" ]
lisleitora/XF.HeaderShell
gs/Services/IDataStore.cs
399
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Windows; using System.Windows.Controls; namespace sistemaAlumnosITAM { class Conexion { public static SqlConnection conectar() { SqlConnection cnn = null; try { cnn = new SqlConnection("Data Source=CC101-07\\SA;Initial Catalog=baseSistemaAlumno;User ID=sa;Password=adminadmin"); cnn.Open(); MessageBox.Show("se conectó"); } catch (Exception e) { MessageBox.Show("no se pudo conectar y el error es: " + e); } return cnn; } public static String comprobarPwd(String usuario, String contra) { String resp = ""; SqlConnection con; SqlCommand cmd; SqlDataReader drd; try { con = Conexion.conectar(); cmd = new SqlCommand(String.Format("select contra from usuarios where nombreUsuario = '{0}'", usuario), con); drd = cmd.ExecuteReader(); if (drd.Read()) { if (drd.GetString(0).Equals(contra)) resp = "contraseña correcta"; else resp = "contraseña incorrecta"; } else resp = "usuario incorrecto"; con.Close(); drd.Close(); } catch (Exception e) { resp = "error " + e; } return resp; } public static void llenarComboAlta(ComboBox cb) { String resp = ""; SqlConnection con; SqlCommand cmd; SqlDataReader drd; try { con = Conexion.conectar(); cmd = new SqlCommand("select nombre from programa", con); drd = cmd.ExecuteReader(); while (drd.Read()) { cb.Items.Add(drd["nombre"].ToString()); } cb.SelectedIndex = 0; con.Close(); drd.Close(); } catch (Exception e) { MessageBox.Show("no se pudo llenar el combo " + e); } } } }
24.517241
126
0.536803
[ "MIT" ]
CaDe27/DAI
SistemaAlumnos/sistemaAlumnosITAM/sistemaAlumnosITAM/Conexion.cs
2,138
C#
using UnityEngine; namespace Mirror.Examples.Additive { [RequireComponent(typeof(CharacterController))] public class PlayerController : NetworkBehaviour { CharacterController characterController; public float moveSpeed = 300f; public float maxTurnSpeed = 90f; public float turnSpeedAccel = 30f; public float turnSpeedDecel = 30f; public override void OnStartServer() { base.OnStartServer(); playerColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); } [SyncVar(hook = nameof(SetColor))] public Color playerColor = Color.black; // Unity makes a clone of the material when GetComponent<Renderer>().material is used // Cache it here and Destroy it in OnDestroy to prevent a memory leak Material materialClone; void SetColor(Color color) { if (materialClone == null) materialClone = GetComponent<Renderer>().material; materialClone.color = color; } private void OnDestroy() { Destroy(materialClone); } Camera mainCam; public override void OnStartLocalPlayer() { base.OnStartLocalPlayer(); characterController = GetComponent<CharacterController>(); // Grab a refernce to the main camera so we can enable it again in OnDisable mainCam = Camera.main; // Turn off the main camera because the Player prefab has its own camera mainCam.enabled = false; // Enable the local player's camera GetComponentInChildren<Camera>().enabled = true; } void OnDisable() { if (isLocalPlayer) { // Disable the local player's camera GetComponentInChildren<Camera>().enabled = false; // Re-enable the main camera when Stop is pressed in the HUD if (mainCam != null) mainCam.enabled = true; } } float horizontal = 0f; float vertical = 0f; float turn = 0f; void Update() { if (!isLocalPlayer) return; horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); if (Input.GetKey(KeyCode.Q) && (turn > -maxTurnSpeed)) turn -= turnSpeedAccel; else if (Input.GetKey(KeyCode.E) && (turn < maxTurnSpeed)) turn += turnSpeedAccel; else { if (turn > turnSpeedDecel) turn -= turnSpeedDecel; else if (turn < -turnSpeedDecel) turn += turnSpeedDecel; else turn = 0f; } } void FixedUpdate() { if (!isLocalPlayer || characterController == null) return; transform.Rotate(0f, turn * Time.fixedDeltaTime, 0f); Vector3 direction = Vector3.ClampMagnitude(new Vector3(horizontal, 0f, vertical), 1f) * moveSpeed; direction = transform.TransformDirection(direction); characterController.SimpleMove(direction * Time.fixedDeltaTime); } } }
29.775701
110
0.576899
[ "Unlicense" ]
AceofGrades/MultiInvaders
Assets/Plugins/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs
3,186
C#
namespace SideBySide; public class DatabaseFixture : IDisposable { public DatabaseFixture() { lock (s_lock) { if (!s_isInitialized) { // increase the number of worker threads to reduce number of spurious failures from threadpool starvation ThreadPool.SetMinThreads(64, 64); var csb = AppConfig.CreateConnectionStringBuilder(); var database = csb.Database; csb.Database = ""; using (var db = new SingleStoreConnection(csb.ConnectionString)) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = $"create schema if not exists {database};"; cmd.ExecuteNonQuery(); if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase)) { cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } } db.Close(); } s_isInitialized = true; } } Connection = new SingleStoreConnection(AppConfig.ConnectionString); } public SingleStoreConnection Connection { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Connection.Dispose(); } } static object s_lock = new object(); static bool s_isInitialized; }
21.338983
109
0.671168
[ "MIT" ]
memsql/MySqlConnector
tests/SideBySide/DatabaseFixture.cs
1,259
C#
using System; using System.Reflection; namespace ModComponentAPI { public class TypeResolver { public static Type Resolve(string name) { Type result = Type.GetType(name, false); if (result != null) { return result; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly eachAssembly in assemblies) { result = eachAssembly.GetType(name, false); if (result != null) { return result; } } throw new ArgumentException("Could not resolve type '" + name + "'. Are you missing an assembly?"); } } }
26.482759
111
0.503906
[ "MIT" ]
WulfMarius/ModComponent
ModComponentAPI/src/TypeResolver.cs
770
C#
using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using PuppeteerSharp.Xunit; using PuppeteerSharp.Tests.Attributes; namespace PuppeteerSharp.Tests.QuerySelectorTests { [Collection(TestConstants.TestFixtureCollectionName)] public class PageQuerySelectorTests : PuppeteerPageBaseTest { public PageQuerySelectorTests(ITestOutputHelper output) : base(output) { } [PuppeteerTest("queryselector.spec.ts", "Page.$", "should query existing element")] [PuppeteerFact] public async Task ShouldQueryExistingElement() { await Page.SetContentAsync("<section>test</section>"); var element = await Page.QuerySelectorAsync("section"); Assert.NotNull(element); } [PuppeteerTest("queryselector.spec.ts", "Page.$", "should query existing element")] [PuppeteerFact] public async Task ShouldReturnNullForNonExistingElement() { var element = await Page.QuerySelectorAsync("non-existing-element"); Assert.Null(element); } } }
32.529412
91
0.673599
[ "MIT" ]
Androbin/puppeteer-sharp
lib/PuppeteerSharp.Tests/QuerySelectorTests/PageQuerySelectorTests.cs
1,106
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using BankWepApi.Models; using BankWepApi.Repositories; using BankWepApi.Services; namespace BankWepApi.Controllers { [Route("api/[controller]")] [ApiController] public class BanksController : ControllerBase { private readonly IBankService _bankService; public BanksController(IBankService bankRepository) { _bankService = bankRepository; } // GET: api/Banks [HttpGet] public ActionResult<List<Bank>> GetBanks() { return new JsonResult(_bankService.ReadBanks()); } // GET: api/Banks/5 [HttpGet("{id}")] public ActionResult<Bank> Get(int id) { var bank = _bankService.ReadBank(id); return new JsonResult(bank); } [HttpGet("{name}")] public ActionResult<Bank> Get(string name) { var bank = _bankService.ReadBank(name); return new JsonResult(bank); } // PUT: api/Banks/5 [HttpPut("{id}")] public ActionResult<Bank> Put(Bank bank, int id) { return new JsonResult(_bankService.UpdateBank(bank, id)); } // POST: api/Banks [HttpPost] public ActionResult<Bank> Post(Bank bank) { return new JsonResult(_bankService.CreateBank(bank)); } // DELETE: api/Banks/5 [HttpDelete("{id}")] public ActionResult Delete(int id) { return new JsonResult(_bankService.DeleteBank(id)); } } }
25.183099
69
0.587808
[ "MIT" ]
MikkoTKaipainen/bank-web-api
BankWepApi/Controllers/BanksController.cs
1,790
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Redis.Fluent.Models { using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; /// <summary> /// Defines values for TlsVersion. /// </summary> public sealed partial class TlsVersion : ExpandableStringEnum<TlsVersion> { public static readonly TlsVersion OneFullStopZero = Parse("1.0"); public static readonly TlsVersion OneFullStopOne = Parse("1.1"); public static readonly TlsVersion OneFullStopTwo = Parse("1.2"); } }
37.368421
95
0.723944
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/RedisCache/TlsVersion.cs
710
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/ProjectOxford-ClientSDK // // Copyright (c) Microsoft Corporation // All rights reserved. // // 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.Net; namespace Microsoft.ProjectOxford.Face { /// <summary> /// Represents client error with detailed error message and error code /// </summary> public class FaceAPIException : Exception { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="FaceAPIException" /> class /// </summary> public FaceAPIException() { } /// <summary> /// Initializes a new instance of the <see cref="FaceAPIException" /> class /// </summary> /// <param name="errorCode">Code represents the error category</param> /// <param name="errorMessage">Message represents the detailed error description</param> /// <param name="statusCode">Http status code</param> public FaceAPIException(string errorCode, string errorMessage, HttpStatusCode statusCode) { ErrorCode = errorCode; ErrorMessage = errorMessage; HttpStatus = statusCode; } #endregion Constructors #region Properties /// <summary> /// Gets or sets the error code /// </summary> public string ErrorCode { get; set; } /// <summary> /// Gets or sets the error message /// </summary> public string ErrorMessage { get; set; } /// <summary> /// Gets or sets http status of http response. /// </summary> /// <value> /// The HTTP status. /// </value> public HttpStatusCode HttpStatus { get; set; } #endregion Properties } }
32.474747
103
0.644168
[ "MIT" ]
ActiveNick/Xamarin-smarter-apps
talk/employee-directory/1. Starting/Microsoft.ProjectOxford.Face/FaceAPIException.cs
3,217
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.HybridCompute.V20210520.Inputs { /// <summary> /// Metadata pertaining to the geographic location of the resource. /// </summary> public sealed class LocationDataArgs : Pulumi.ResourceArgs { /// <summary> /// The city or locality where the resource is located. /// </summary> [Input("city")] public Input<string>? City { get; set; } /// <summary> /// The country or region where the resource is located /// </summary> [Input("countryOrRegion")] public Input<string>? CountryOrRegion { get; set; } /// <summary> /// The district, state, or province where the resource is located. /// </summary> [Input("district")] public Input<string>? District { get; set; } /// <summary> /// A canonical name for the geographic or physical location. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public LocationDataArgs() { } } }
29.914894
81
0.604552
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/HybridCompute/V20210520/Inputs/LocationDataArgs.cs
1,406
C#
using Azure; using Kaiyuanshe.OpenHackathon.Server.Biz; using Kaiyuanshe.OpenHackathon.Server.Biz.Options; using Kaiyuanshe.OpenHackathon.Server.Cache; using Kaiyuanshe.OpenHackathon.Server.Models; using Kaiyuanshe.OpenHackathon.Server.Storage; using Kaiyuanshe.OpenHackathon.Server.Storage.Entities; using Kaiyuanshe.OpenHackathon.Server.Storage.Tables; using Moq; using NUnit.Framework; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Kaiyuanshe.OpenHackathon.ServerTests.Biz { public class EnrollmentManagementTests { #region CreateEnrollmentAsync [TestCase(false, EnrollmentStatus.pendingApproval)] [TestCase(true, EnrollmentStatus.approved)] public async Task CreateEnrollmentAsync(bool autoApprove, EnrollmentStatus targetStatus) { HackathonEntity hackathon = new HackathonEntity { PartitionKey = "hack", AutoApprove = autoApprove, Enrollment = 5, }; Enrollment request = new Enrollment { userId = "uid", extensions = new Extension[] { new Extension { name = "n1", value = "v1" } } }; EnrollmentEntity enrollment = null; var enrollmentTable = new Mock<IEnrollmentTable>(); enrollmentTable.Setup(p => p.InsertAsync(It.IsAny<EnrollmentEntity>(), default)) .Callback<EnrollmentEntity, CancellationToken>((p, c) => { enrollment = p; }); var storageContext = new Mock<IStorageContext>(); var hackathonTable = new Mock<IHackathonTable>(); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); if (autoApprove) { hackathonTable.Setup(h => h.MergeAsync(hackathon, default)); storageContext.SetupGet(s => s.HackathonTable).Returns(hackathonTable.Object); } var cache = new Mock<ICacheProvider>(); var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, Cache = cache.Object, }; await enrollmentManagement.CreateEnrollmentAsync(hackathon, request, default); Mock.VerifyAll(storageContext, enrollmentTable, hackathonTable); enrollmentTable.VerifyNoOtherCalls(); if (autoApprove) { hackathonTable.Verify(h => h.MergeAsync(It.Is<HackathonEntity>(h => h.Enrollment == 6), default), Times.Once); } hackathonTable.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); cache.Verify(c => c.Remove("Enrollment-hack"), Times.Once); cache.VerifyNoOtherCalls(); Assert.AreEqual(targetStatus, enrollment.Status); } #endregion #region UpdateEnrollmentAsync [Test] public async Task UpdateEnrollmentAsync() { EnrollmentEntity existing = new EnrollmentEntity { PartitionKey = "hack" }; Enrollment request = new Enrollment { extensions = new Extension[] { new Extension { name = "n", value = "v" } } }; var enrollmentTable = new Mock<IEnrollmentTable>(); var storageContext = new Mock<IStorageContext>(); var hackathonTable = new Mock<IHackathonTable>(); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); var cache = new Mock<ICacheProvider>(); cache.Setup(c => c.Remove("Enrollment-hack")); var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, Cache = cache.Object, }; var result = await enrollmentManagement.UpdateEnrollmentAsync(existing, request, default); // verify Mock.VerifyAll(enrollmentTable, storageContext, cache); enrollmentTable.Verify(e => e.MergeAsync(It.Is<EnrollmentEntity>(en => en.Extensions.Count() == 1 && en.Extensions.First().name == "n" && en.Extensions.First().value == "v"), default), Times.Once); enrollmentTable.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); cache.VerifyNoOtherCalls(); Assert.AreEqual(1, result.Extensions.Count()); Assert.AreEqual("n", result.Extensions.First().name); Assert.AreEqual("v", result.Extensions.First().value); } #endregion #region UpdateEnrollmentStatusAsync [Test] public async Task EnrollUpdateStatusAsyncTest_Null() { HackathonEntity hackathon = null; EnrollmentEntity participant = null; CancellationToken cancellation = CancellationToken.None; var enrollmentManagement = new EnrollmentManagement(); await enrollmentManagement.UpdateEnrollmentStatusAsync(hackathon, participant, EnrollmentStatus.approved, cancellation); Assert.IsNull(participant); } [TestCase(EnrollmentStatus.none, EnrollmentStatus.approved, 1)] [TestCase(EnrollmentStatus.pendingApproval, EnrollmentStatus.approved, 1)] [TestCase(EnrollmentStatus.approved, EnrollmentStatus.approved, 0)] [TestCase(EnrollmentStatus.rejected, EnrollmentStatus.approved, 1)] [TestCase(EnrollmentStatus.none, EnrollmentStatus.rejected, 0)] [TestCase(EnrollmentStatus.pendingApproval, EnrollmentStatus.rejected, 0)] [TestCase(EnrollmentStatus.approved, EnrollmentStatus.rejected, -1)] [TestCase(EnrollmentStatus.rejected, EnrollmentStatus.rejected, 0)] public async Task EnrollUpdateStatusAsyncTest_Updated(EnrollmentStatus currentStatus, EnrollmentStatus targetStatus, int expectedIncreasement) { // data HackathonEntity hackathon = new HackathonEntity { PartitionKey = "hack", Enrollment = 5 }; EnrollmentEntity enrollment = new EnrollmentEntity { Status = currentStatus }; CancellationToken cancellation = CancellationToken.None; // setup var storageContext = new Mock<IStorageContext>(); var enrollmentTable = new Mock<IEnrollmentTable>(); var cache = new Mock<ICacheProvider>(); if (currentStatus != targetStatus) { storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); enrollmentTable.Setup(p => p.MergeAsync(It.IsAny<EnrollmentEntity>(), cancellation)); cache.Setup(c => c.Remove("Enrollment-hack")); } var hackathonTable = new Mock<IHackathonTable>(); if (expectedIncreasement != 0) { storageContext.SetupGet(p => p.HackathonTable).Returns(hackathonTable.Object); hackathonTable.Setup(h => h.MergeAsync(hackathon, cancellation)); } // test var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, Cache = cache.Object, }; await enrollmentManagement.UpdateEnrollmentStatusAsync(hackathon, enrollment, targetStatus, cancellation); // verify Mock.VerifyAll(storageContext, enrollmentTable, hackathonTable, cache); if (currentStatus != targetStatus) { enrollmentTable.Verify(p => p.MergeAsync(It.Is<EnrollmentEntity>(p => p.Status == targetStatus), cancellation), Times.Once); } enrollmentTable.VerifyNoOtherCalls(); if (expectedIncreasement != 0) { int expected = 5 + expectedIncreasement; hackathonTable.Verify(h => h.MergeAsync(It.Is<HackathonEntity>(h => h.Enrollment == expected), cancellation)); } hackathonTable.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); cache.VerifyNoOtherCalls(); } #endregion #region ListPaginatedEnrollmentsAsync [Test] public async Task ListPaginatedEnrollmentsAsync_NoOptions() { string hackName = "foo"; EnrollmentQueryOptions options = null; var entities = Page<EnrollmentEntity>.FromValues( new List<EnrollmentEntity> { new EnrollmentEntity{ PartitionKey="pk" } }, "np nr", null); var enrollmentTable = new Mock<IEnrollmentTable>(); enrollmentTable.Setup(p => p.ExecuteQuerySegmentedAsync("PartitionKey eq 'foo'", null, 100, null, default)) .ReturnsAsync(entities); var storageContext = new Mock<IStorageContext>(); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object }; var page = await enrollmentManagement.ListPaginatedEnrollmentsAsync(hackName, options, default); Mock.VerifyAll(enrollmentTable, storageContext); enrollmentTable.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); Assert.AreEqual(1, page.Values.Count()); Assert.AreEqual("pk", page.Values.First().HackathonName); var pagination = Pagination.FromContinuationToken(page.ContinuationToken); Assert.AreEqual("np", pagination.np); Assert.AreEqual("nr", pagination.nr); } [TestCase(5, 5)] [TestCase(-1, 100)] public async Task ListPaginatedEnrollmentsAsync_Options(int topInPara, int expectedTop) { string hackName = "foo"; EnrollmentQueryOptions options = new EnrollmentQueryOptions { Pagination = new Pagination { np = "np", nr = "nr", top = topInPara }, Status = EnrollmentStatus.approved }; var entities = Page<EnrollmentEntity>.FromValues( new List<EnrollmentEntity> { new EnrollmentEntity{ PartitionKey="pk" } }, "np2 nr2", null); var enrollmentTable = new Mock<IEnrollmentTable>(); enrollmentTable.Setup(p => p.ExecuteQuerySegmentedAsync("(PartitionKey eq 'foo') and (Status eq 2)", "np nr", expectedTop, null, default)) .ReturnsAsync(entities); var storageContext = new Mock<IStorageContext>(); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object }; var page = await enrollmentManagement.ListPaginatedEnrollmentsAsync(hackName, options, default); Mock.VerifyAll(enrollmentTable, storageContext); enrollmentTable.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); Assert.AreEqual(1, page.Values.Count()); Assert.AreEqual("pk", page.Values.First().HackathonName); var pagination = Pagination.FromContinuationToken(page.ContinuationToken); Assert.AreEqual("np2", pagination.np); Assert.AreEqual("nr2", pagination.nr); } #endregion #region GetEnrollmentAsync [TestCase(null, null)] [TestCase(null, "uid")] [TestCase("hack", null)] public async Task GetEnrollmentAsyncTest_NotFound(string hackathon, string userId) { var enrollmentManagement = new EnrollmentManagement(); var enrollment = await enrollmentManagement.GetEnrollmentAsync(hackathon, userId); Assert.IsNull(enrollment); } [Test] public async Task GetEnrollmentAsyncTest_Succeeded() { EnrollmentEntity participant = new EnrollmentEntity { Status = EnrollmentStatus.rejected }; CancellationToken cancellation = CancellationToken.None; var enrollmentTable = new Mock<IEnrollmentTable>(); enrollmentTable.Setup(p => p.RetrieveAsync("hack", "uid", cancellation)).ReturnsAsync(participant); var storageContext = new Mock<IStorageContext>(); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, }; var enrollment = await enrollmentManagement.GetEnrollmentAsync("Hack", "uid", cancellation); Assert.IsNotNull(enrollment); Assert.AreEqual(EnrollmentStatus.rejected, enrollment.Status); } #endregion #region IsUserEnrolledAsync [TestCase("anotheruser", EnrollmentStatus.approved, false)] [TestCase("uid", EnrollmentStatus.none, false)] [TestCase("uid", EnrollmentStatus.pendingApproval, false)] [TestCase("uid", EnrollmentStatus.rejected, false)] [TestCase("uid", EnrollmentStatus.approved, true)] public async Task IsUserEnrolledAsync_Small(string userId, EnrollmentStatus status, bool expectedResult) { HackathonEntity hackathon = new HackathonEntity { PartitionKey = "hack", MaxEnrollment = 1000 }; CancellationToken cancellationToken = default; IEnumerable<EnrollmentEntity> enrollments = new List<EnrollmentEntity> { new EnrollmentEntity { RowKey = "uid", Status = status } }; // mock var cache = new Mock<ICacheProvider>(); cache.Setup(c => c.GetOrAddAsync(It.IsAny<CacheEntry<IEnumerable<EnrollmentEntity>>>(), cancellationToken)) .ReturnsAsync(enrollments); var storageContext = new Mock<IStorageContext>(); // test var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, Cache = cache.Object, }; var result = await enrollmentManagement.IsUserEnrolledAsync(hackathon, userId, cancellationToken); Assert.IsFalse(await enrollmentManagement.IsUserEnrolledAsync(null, userId, cancellationToken)); Assert.IsFalse(await enrollmentManagement.IsUserEnrolledAsync(hackathon, "", cancellationToken)); // verify cache.Verify(c => c.GetOrAddAsync(It.Is<CacheEntry<IEnumerable<EnrollmentEntity>>>(e => e.AutoRefresh && e.CacheKey == "Enrollment-hack" && e.SlidingExpiration.Hours == 4), cancellationToken), Times.Once); cache.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); Assert.AreEqual(expectedResult, result); } private static IEnumerable IsUserEnrolledAsync_Big_TestData() { // arg0: max enrollment // arg1: EnrollmentEntity // arg2: expected result // empty yield return new TestCaseData( 1001, null, false); // unapproved yield return new TestCaseData( -1, new EnrollmentEntity { Status = EnrollmentStatus.none }, false); yield return new TestCaseData( -1, new EnrollmentEntity { Status = EnrollmentStatus.pendingApproval }, false); yield return new TestCaseData( -1, new EnrollmentEntity { Status = EnrollmentStatus.rejected }, false); // approved yield return new TestCaseData( 10000, new EnrollmentEntity { Status = EnrollmentStatus.approved }, true); } [Test, TestCaseSource(nameof(IsUserEnrolledAsync_Big_TestData))] public async Task IsUserEnrolledAsync_Big(int maxEnrollment, EnrollmentEntity enrollment, bool expectedResult) { HackathonEntity hackathon = new HackathonEntity { PartitionKey = "hack", MaxEnrollment = maxEnrollment }; string userId = "uid"; CancellationToken cancellationToken = default; // mock var cache = new Mock<ICacheProvider>(); var storageContext = new Mock<IStorageContext>(); var enrollmentTable = new Mock<IEnrollmentTable>(); enrollmentTable.Setup(p => p.RetrieveAsync("hack", userId, cancellationToken)).ReturnsAsync(enrollment); storageContext.SetupGet(p => p.EnrollmentTable).Returns(enrollmentTable.Object); // test var enrollmentManagement = new EnrollmentManagement() { StorageContext = storageContext.Object, Cache = cache.Object, }; var result = await enrollmentManagement.IsUserEnrolledAsync(hackathon, userId, cancellationToken); // verify Mock.VerifyAll(cache, storageContext, enrollmentTable); cache.VerifyNoOtherCalls(); storageContext.VerifyNoOtherCalls(); enrollmentTable.VerifyNoOtherCalls(); Assert.AreEqual(expectedResult, result); } #endregion } }
44.646341
218
0.598361
[ "MIT" ]
kaiyuanshe/open-hackathon-api
src/open-hackathon-server/Kaiyuanshe.OpenHackathon.ServerTests/Biz/EnrollmentManagementTests.cs
18,307
C#
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using Microsoft.Research.DryadLinq; using Microsoft.Research.Peloponnese.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; namespace DryadLinqTests { public static class GroupByReduceTests { public static void Run(DryadLinqContext context, string matchPattern) { TestLog.Message(" **********************"); TestLog.Message(" GroupByReduceTests "); TestLog.Message(" **********************"); var tests = new Dictionary<string, Action>() { {"Decomposition_Average", () => Decomposition_Average(context) }, {"DistributiveResultSelector_1", () => DistributiveResultSelector_1(context) }, {"DistributiveSelect_1", () => DistributiveSelect_1(context) }, {"BuiltInCountIsDistributable", () => BuiltInCountIsDistributable(context) }, {"Bug12078_GroupByReduceWithResultSelectingAggregate", () => Bug12078_GroupByReduceWithResultSelectingAggregate(context) }, {"GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner", () => GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner(context) }, {"GroupByReduceWithCustomDecomposableFunction_DistributableCombiner", () => GroupByReduceWithCustomDecomposableFunction_DistributableCombiner(context) }, {"GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes", () => GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes(context) }, {"GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer", () => GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer(context) }, {"GroupByReduce_UseAllInternalDecomposables", () => GroupByReduce_UseAllInternalDecomposables(context) }, {"GroupByReduce_BuiltIn_First", () => GroupByReduce_BuiltIn_First(context) }, {"GroupByReduce_ResultSelector_ComplexNewExpression", () => GroupByReduce_ResultSelector_ComplexNewExpression(context) }, // ToDo {"GroupByReduce_ProgrammingManualExample", () => GroupByReduce_ProgrammingManualExample(context) }, {"GroupByReduce_SameDecomposableUsedTwice", () => GroupByReduce_SameDecomposableUsedTwice(context) }, {"GroupByReduce_APIMisuse", () => GroupByReduce_APIMisuse(context) }, {"GroupByReduce_ListInitializerReducer", () => GroupByReduce_ListInitializerReducer(context) }, {"GroupByReduce_CustomListInitializerReducer", () => GroupByReduce_CustomListInitializerReducer(context) }, {"GroupByReduce_BitwiseNegationOperator", () => GroupByReduce_BitwiseNegationOperator(context) }, }; foreach (var test in tests) { if (Regex.IsMatch(test.Key, matchPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { test.Value.Invoke(); } } } public static bool Decomposition_Average(DryadLinqContext context) { string testName = "Decomposition_Average"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<double>[] result = new IEnumerable<double>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); double[] aggregates = pt1.GroupBy(x => x % 2).Select(g => g.Average()).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); double[] aggregates = pt1.GroupBy(x => x % 2).Select(g => g.Average()).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool DistributiveResultSelector_1(DryadLinqContext context) { string testName = "DistributiveResultSelector_1"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<int>[] result = new IEnumerable<int>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // this result selector satisfies "DistributiveOverConcat" int[] aggregates = pt1.GroupBy(x => x % 2, (key, seq) => seq.Sum()).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // this result selector satisfies "DistributiveOverConcat" int[] aggregates = pt1.GroupBy(x => x % 2, (key, seq) => seq.Sum()).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool DistributiveSelect_1(DryadLinqContext context) { string testName = "DistributiveSelect_1"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<int>[] result = new IEnumerable<int>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // this result selector satisfies "DistributiveOverConcat" int[] aggregates = pt1.GroupBy(x => x % 2).Select(group => group.Sum()).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // this result selector satisfies "DistributiveOverConcat" int[] aggregates = pt1.GroupBy(x => x % 2).Select(group => group.Sum()).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool BuiltInCountIsDistributable(DryadLinqContext context) { string testName = "BuiltInCountIsDistributable"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<int>[] result = new IEnumerable<int>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // Built in Count is Distributable as built-in logic knows to use Sum() as the combiner function. // Count(a,b,c,d) = Sum(Count(a,b), Count(c,d)) int[] aggregates = pt1.GroupBy(x => x % 2, (key, seq) => seq.Count()).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // Built in Count is Distributable as built-in logic knows to use Sum() as the combiner function. // Count(a,b,c,d) = Sum(Count(a,b), Count(c,d)) int[] aggregates = pt1.GroupBy(x => x % 2, (key, seq) => seq.Count()).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool Bug12078_GroupByReduceWithResultSelectingAggregate(DryadLinqContext context) { string testName = "Bug12078_GroupByReduceWithResultSelectingAggregate"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<double>[]result = new IEnumerable<double>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => seq.Aggregate((double)0, (acc, item) => acc + item, val => val / 100)).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => seq.Aggregate((double)0, (acc, item) => acc + item, val => val / 100)).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #region GroupByReduceWithCustomDecomposableFunction_DistributableCombiner [Decomposable(typeof(Decomposer_1))] public static double DecomposableFunc(IEnumerable<double> seq) { // hard to test with context system.. TestUtils.Assert(HpcLinq.LocalDebug, "This method should only be called during LocalDebug"); return seq.Aggregate((double)0, (acc, item) => acc + item, val => val / 100); } public class Decomposer_1 : IDecomposable<double, double, double> { public void Initialize(object state) { } public double Seed(double source) { return source; } public double Accumulate(double a, double x) { return a + x; } public double RecursiveAccumulate(double a, double x) { return a + x; } public double FinalReduce(double a) { return a / 100; } } public static bool GroupByReduceWithCustomDecomposableFunction_DistributableCombiner(DryadLinqContext context) { string testName = "GroupByReduceWithCustomDecomposableFunction_DistributableCombiner"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<double>[] result = new IEnumerable<double>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (k, g) => DecomposableFunc(g)) .ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (k, g) => DecomposableFunc(g)) .ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception) { passed &= false; } } catch (Exception) { passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #endregion GroupByReduceWithCustomDecomposableFunction_DistributableCombiner #region GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes // Tests a fully decomposed function whose reducer changes types. [Decomposable(typeof(Decomposer_2))] public static string DecomposableFunc2(IEnumerable<double> seq) { //TestUtils.Assert(HpcLinq.LocalDebug, "This method should only be called during LocalDebug"); return seq.Aggregate((double)0, (acc, item) => acc + item, val => ("hello:" + val.ToString())); } public class Decomposer_2 : IDecomposable<double, double, string> { public void Initialize(object state) { } public double Seed(double source) { return source; } public double Accumulate(double a, double x) { return a + x; } public double RecursiveAccumulate(double a, double x) { return a + x; } public string FinalReduce(double a) { return ("hello:" + a.ToString()); } } public static bool GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes(DryadLinqContext context) { string testName = "GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<string>[] result = new IEnumerable<string>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); string[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc2(seq)).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); string[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc2(seq)).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception) { passed &= false; } } catch (Exception) { passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #endregion GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_DifferingTypes #region GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer // Tests a decomposed function with no need for a particular reduce. // The combiner changes type, and the recursive-combiner operators on the altered type // The reducer just calls combiner again. [Decomposable(typeof(Decomposer_3))] public static string DecomposableFunc3(IEnumerable<double> seq) { // TestUtils.Assert(HpcLinq.LocalDebug, "This method should only be called during LocalDebug"); return seq.Aggregate("0", (acc, item) => (double.Parse(acc) + item).ToString()); } public class Decomposer_3 : IDecomposable<double, string, string> { public void Initialize(object state) { } public string Seed(double source) { return source.ToString(); } public string Accumulate(string a, double x) { return (double.Parse(a) + x).ToString(); } public string RecursiveAccumulate(string a, string x) { return (double.Parse(a) + double.Parse(x)).ToString(); } public string FinalReduce(string a) { return a; } } public static bool GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer(DryadLinqContext context) { string testName = "GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<string>[] result = new IEnumerable<string>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); string[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc3(seq)).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); string[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc3(seq)).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception ex) { TestLog.Message("Error: " + ex.Message); passed &= false; } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #endregion GroupByReduceWithCustomDecomposableFunction_DistributableCombiner_NoFinalizer #region GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner // Tests simplified pattern where the Combiner is not recursively applied. // Note: Func4 can be represented as a decomposable with distributive-combiner and a finalizer.. but here we choose not to. // Because of the form of the Combiner, it is critical that it not be used recursively. [Decomposable(typeof(Decomposer_4))] public static double DecomposableFunc4(IEnumerable<double> seq) { // TestUtils.Assert(HpcLinq.LocalDebug, "This method should only be called during LocalDebug"); return seq.Aggregate(0.0, (acc, item) => acc + item, acc => acc / 100); } public class Decomposer_4 : IDecomposable<double, double, double> { public void Initialize(object state) { } public double Seed(double source) { return source; } public double Accumulate(double a, double x) { return a + x; } public double RecursiveAccumulate(double a, double x) { return a + x; } public double FinalReduce(double a) { return a / 100; } } public static bool GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner(DryadLinqContext context) { string testName = "GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<double>[] result = new IEnumerable<double>[2]; // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc4(seq)).ToArray(); result[0] = aggregates; } // local { context.LocalDebug = true; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); double[] aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => DecomposableFunc4(seq)).ToArray(); result[1] = aggregates; } // compare result try { Validate.Check(result); } catch (Exception) { passed &= false; } } catch (Exception) { passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #endregion GroupByReduceWithCustomDecomposableFunction_NonDistributableCombiner public static bool GroupByReduce_UseAllInternalDecomposables(DryadLinqContext context) { string testName = "GroupByReduce_UseAllInternalDecomposables"; TestLog.TestStart(testName); bool passed = true; try { // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); var aggregates = pt1.Select(x => (double)x) .GroupBy(x => 0, (key, seq) => seq.Count()) .GroupBy(x => 0, (key, seq) => seq.LongCount()) .GroupBy(x => 0, (key, seq) => seq.Max()) .GroupBy(x => 0, (key, seq) => seq.Min()) .GroupBy(x => 0, (key, seq) => seq.Sum()) .GroupBy(x => 0, (key, seq) => seq.Average()) .GroupBy(x => 0, (key, seq) => seq.Aggregate((x, y) => x + y)) .GroupBy(x => 0, (key, seq) => seq.Any(x => true)) .SelectMany(x => new[] { x }) .GroupBy(x => 0, (key, seq) => seq.All(x => true)) .SelectMany(x => new[] { x }) .GroupBy(x => 0, (key, seq) => seq.Contains(true)) .SelectMany(x => new[] { x }) .GroupBy(x => 0, (key, seq) => seq.Distinct()) .SelectMany(x => new[] { x }) .GroupBy(x => 0, (key, seq) => seq.First()) .ToArray(); } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByReduce_BuiltIn_First(DryadLinqContext context) { string testName = "GroupByReduce_BuiltIn_First"; TestLog.TestStart(testName); bool passed = true; try { // cluster { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); int[] aggregates = pt1.GroupBy(x => 0, (key, seq) => seq.First()).ToArray(); // the output of First can be the first item of either partition. passed &= aggregates.SequenceEqual(new[] { 1 }) || aggregates.SequenceEqual(new[] { 101 }); // ToDo: remove hard coded } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByReduce_ResultSelector_ComplexNewExpression(DryadLinqContext context) { string testName = "GroupByReduce_ResultSelector_ComplexNewExpression"; TestLog.TestStart(testName); bool passed = true; try { IEnumerable<int>[] result = new IEnumerable<int>[2]; // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context); var aggregates = pt1.GroupBy(x => 0, (key, seq) => new KeyValuePair<int, KeyValuePair<double, double>>(key, new KeyValuePair<double, double>(seq.Average(), seq.Average()))).ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var expected = pt2.GroupBy(x => 0, (key, seq) => new KeyValuePair<int, KeyValuePair<double, double>>(key, new KeyValuePair<double, double>(seq.Average(), seq.Average()))).ToArray(); passed &= aggregates.SequenceEqual(expected); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } #region GroupByReduce_ProgrammingManualExample // ToDo: //public static bool GroupByReduce_ProgrammingManualExample(DryadLinqContext context) //{ // string testName = "GroupByReduce_ProgrammingManualExample"; // TestLog.TestStart(testName); // bool passed = true; // try // { // // cluster // { // context.LocalDebug = false; // IEnumerable<IEnumerable<int>> rawdata = new[] { Enumerable.Range(0, 334), Enumerable.Range(334, 333), Enumerable.Range(667, 333) }; // IQueryable<IEnumerable<int>> data = context.FromEnumerable(rawdata); // var count = data.Count(); // //decimal sum = data.Sum(); // var min = data.Min(); // var max = data.Max(); // var uniques = data.Distinct().Count(); // var results = data.GroupBy(x => x % 10, (key, seq) => new KeyValuePair<int, double>(key, seq.MyAverage())) // .OrderBy(y => y.Key) // .ToArray(); // passed &= (results.Count() == 10); // passed &= (results[0].Key == 0); // "first element should be key=0"); // passed &= (results[0].Value == 495); // "first element should be value=495 ie avg(0,10,20,..,990)"); // } // } // catch (Exception) // { // passed &= false; // } // TestLog.LogResult(new TestResult(testName, context, passed)); // return passed; //} [Decomposable(typeof(Decomposer_5))] public static double MyAverage(this IEnumerable<int> recordSequence) { int count = 0, sum = 0; foreach (var r in recordSequence) { sum += r; count++; } if (count == 0) throw new Exception("Can't average empty sequence"); return (double)sum / (double)count; } [Serializable] public struct Partial { public int PartialSum; public int PartialCount; } public class Decomposer_5 : IDecomposable<int, Partial, double> { public void Initialize(object state) { } public Partial Seed(int x) { Partial p = new Partial(); p.PartialSum = x; p.PartialCount = 1; return p; } public Partial Accumulate(Partial a, int x) { Partial p = new Partial(); p.PartialSum = a.PartialSum + x; p.PartialCount = a.PartialCount + 1; return p; } public Partial RecursiveAccumulate(Partial a, Partial x) { Partial p = new Partial(); p.PartialSum = a.PartialSum + x.PartialSum; p.PartialCount = a.PartialCount + x.PartialCount; return p; } public double FinalReduce(Partial a) { if (a.PartialCount == 0) throw new Exception("Can't average empty sequence"); return (double)a.PartialSum / (double)a.PartialCount; } } #endregion GroupByReduce_ProgrammingManualExample #region GroupByReduce_SameDecomposableUsedTwice public static bool GroupByReduce_SameDecomposableUsedTwice(DryadLinqContext context) { string testName = "GroupByReduce_SameDecomposableUsedTwice"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var results0 = pt1.GroupBy(x => x % 2, (k, g) => MyFunc(k, DecomposableFunc5(g), DecomposableFunc5(g), g.Average())).ToArray(); var results0_sorted = results0.OrderBy(x => x.Key).ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var results1 = pt2.GroupBy(x => x % 2, (k, g) => MyFunc(k, DecomposableFunc5(g), DecomposableFunc5(g), g.Average())).ToArray(); var results1_sorted = results1.OrderBy(x => x.Key).ToArray(); passed &= (results0_sorted.Length == results1_sorted.Length); passed &= (results0_sorted[0].Key == results1_sorted[0].Key); passed &= (results0_sorted[0].A == results1_sorted[0].A); passed &= (results0_sorted[0].B == results1_sorted[0].B); passed &= (results0_sorted[0].Av == results1_sorted[0].Av); passed &= (results0_sorted[1].Key == results1_sorted[1].Key); passed &= (results0_sorted[1].A == results1_sorted[1].A); passed &= (results0_sorted[1].B == results1_sorted[1].B); passed &= (results0_sorted[1].Av == results1_sorted[1].Av); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static MyStruct3 MyFunc(int key, int a, int b, double av) { return new MyStruct3(key, a, b, av); } [Decomposable(typeof(Decomposer_6))] private static int DecomposableFunc5(IEnumerable<int> g) { return g.Count(); } public class Decomposer_6 : IDecomposable<int, int, int> { public void Initialize(object state) { } public int Seed(int source) { return 1; } public int Accumulate(int a, int x) { return a + 1; } public int RecursiveAccumulate(int a, int x) { return a + x; } public int FinalReduce(int a) { return a; } } [Serializable] public struct MyStruct3 { public int Key; public int A; public int B; public double Av; public MyStruct3(int key, int a, int b, double av) { Key = key; A = a; B = b; Av = av; } } #endregion GroupByReduce_SameDecomposableUsedTwice #region API_Misuse internal static bool GroupByReduce_APIMisuse(DryadLinqContext context) { string testName = "GroupByReduce_APIMisuse"; TestLog.TestStart(testName); bool passed = true; try { context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); // internal-visibility decomposable type should fail. try { pt1.GroupBy(x => x, (k, g) => BadDecomposable1(g)).ToArray(); passed &= false; // "exception should be thrown" } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypeMustBePublic")); } // decomposable type doesn't implement IDecomposable or IDecomposableRecursive try { pt1.GroupBy(x => x, (k, g) => BadDecomposable2(g)).ToArray(); passed &= false; //"exception should be thrown"); } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypeDoesNotImplementInterface")); } // decomposable type implements more than one IDecomposable or IDecomposableRecursive try { pt1.GroupBy(x => x, (k, g) => BadDecomposable3(g)).ToArray(); passed &= false; } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypeImplementsTooManyInterfaces")); } // decomposable type doesn't have public default ctor try { pt1.GroupBy(x => x, (k, g) => BadDecomposable4(g)).ToArray(); passed &= false; } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypeDoesNotHavePublicDefaultCtor")); } // decomposable type input type doesn't match try { pt1.GroupBy(x => x, (k, g) => BadDecomposable5(g)).ToArray(); passed &= false; } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypesDoNotMatch")); } // decomposable type output type doesn't match try { pt1.GroupBy(x => x, (k, g) => BadDecomposable6(g)).ToArray(); passed &= false; } catch (DryadLinqException Ex) { passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("DecomposerTypesDoNotMatch")); } } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } [Decomposable(typeof(BadDecomposerType1))] private static int BadDecomposable1(IEnumerable<int> g) { throw new NotImplementedException(); } internal class BadDecomposerType1 : IDecomposable<int, int, int> { public void Initialize(object state) { } public int Seed(int x) { return x; } public int Accumulate(int a, int x) { throw new NotImplementedException(); } public int RecursiveAccumulate(int a, int x) { throw new NotImplementedException(); } public int FinalReduce(int a) { throw new NotImplementedException(); } } [Decomposable(typeof(BadDecomposerType2))] private static int BadDecomposable2(IEnumerable<int> g) { throw new NotImplementedException(); } public class BadDecomposerType2 { } [Decomposable(typeof(BadDecomposerType3))] private static int BadDecomposable3(IEnumerable<int> g) { throw new NotImplementedException(); } public class BadDecomposerType3 : IDecomposable<int, int, int> { public void Initialize(object state) { } public int Seed(int x) { return x; } public int Accumulate(int a, int x) { throw new NotImplementedException(); } public int RecursiveAccumulate(int a, int x) { throw new NotImplementedException(); } public int FinalReduce(int a) { throw new NotImplementedException(); } } [Decomposable(typeof(BadDecomposerType4))] private static int BadDecomposable4(IEnumerable<int> g) { throw new NotImplementedException(); } public class BadDecomposerType4 : IDecomposable<int, int, int> { internal BadDecomposerType4() { } public BadDecomposerType4(int x) { } public void Initialize(object state) { } public int Seed(int x) { return x; } public int Accumulate(int a, int x) { throw new NotImplementedException(); } public int RecursiveAccumulate(int a, int x) { throw new NotImplementedException(); } public int FinalReduce(int a) { throw new NotImplementedException(); } } [Decomposable(typeof(BadDecomposerType5))] private static int BadDecomposable5(IEnumerable<int> g) { throw new NotImplementedException(); } public class BadDecomposerType5 : IDecomposable<double, int, int> { public void Initialize(object state) { } public int Seed(double s) { throw new NotImplementedException(); } public int Accumulate(int a, double x) { throw new NotImplementedException(); } public int RecursiveAccumulate(int a, int x) { throw new NotImplementedException(); } public int FinalReduce(int a) { throw new NotImplementedException(); } } [Decomposable(typeof(BadDecomposerType6))] private static int BadDecomposable6(IEnumerable<int> g) { throw new NotImplementedException(); } public class BadDecomposerType6 : IDecomposable<int, int, double> { public void Initialize(object state) { } public int Seed(int s) { throw new NotImplementedException(); } public int Accumulate(int a, int x) { throw new NotImplementedException(); } public int RecursiveAccumulate(int a, int x) { throw new NotImplementedException(); } public double FinalReduce(int a) { throw new NotImplementedException(); } } #endregion API_Misuse public static bool GroupByReduce_ListInitializerReducer(DryadLinqContext context) { string testName = "GroupByReduce_ListInitializerReducer"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var results0 = pt1.GroupBy(x => x % 2, (k, g) => new List<int>() { k, g.Count(), g.Sum() }).ToArray(); var resultsSorted0 = results0.OrderBy(list => list[0]).ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var results1 = pt2.GroupBy(x => x % 2, (k, g) => new List<int>() { k, g.Count(), g.Sum() }).ToArray(); var resultsSorted1 = results1.OrderBy(list => list[0]).ToArray(); passed &= (resultsSorted0[0][0] == resultsSorted1[0][0]); passed &= (resultsSorted0[0][1] == resultsSorted1[0][1]); passed &= (resultsSorted0[0][2] == resultsSorted1[0][2]); passed &= (resultsSorted0[1][0] == resultsSorted1[1][0]); passed &= (resultsSorted0[1][1] == resultsSorted1[1][1]); passed &= (resultsSorted0[1][2] == resultsSorted1[1][2]); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } public static bool GroupByReduce_CustomListInitializerReducer(DryadLinqContext context) { string testName = "GroupByReduce_CustomListInitializerReducer"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var results0 = pt1.GroupBy(x => x % 2, (k, g) => new MultiParamInitializerClass() { {k, g.Count(), g.Sum()} , // one item, comprising three components }).ToArray(); var resultsSorted0 = results0.OrderBy(list => list.Key).ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var results1 = pt2.GroupBy(x => x % 2, (k, g) => new MultiParamInitializerClass() { {k, g.Count(), g.Sum()} , // one item, comprising three components }).ToArray(); var resultsSorted1 = results1.OrderBy(list => list.Key).ToArray(); passed &= (resultsSorted0[0].Key == resultsSorted1[0].Key); passed &= (resultsSorted0[0].Count() == resultsSorted1[0].Count()); passed &= (resultsSorted0[0].Sum() == resultsSorted1[0].Sum()); passed &= (resultsSorted0[1].Key == resultsSorted1[1].Key); passed &= (resultsSorted0[1].Count() == resultsSorted1[1].Count()); passed &= (resultsSorted0[1].Sum() == resultsSorted1[1].Sum()); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } // note: must be IEnumerable<> to be allowed to participate in list-initializer syntax. // we are cheating here and only supporting one "add" call, just as an example. [Serializable] public class MultiParamInitializerClass : IEnumerable<int> { public int Key; public int Sum; public int Count; public void Add(int key, int count, int sum) { Key = key; Count = count; Sum = sum; } public IEnumerator<int> GetEnumerator() { yield return Key; yield return Count; yield return Sum; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static bool GroupByReduce_BitwiseNegationOperator(DryadLinqContext context) { string testName = "GroupByReduce_BitwiseNegationOperator"; TestLog.TestStart(testName); bool passed = true; try { // cluster context.LocalDebug = false; IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context); var results0 = pt1.GroupBy(x => x % 2, (k, g) => new KeyValuePair<int, int>(k, ~g.Sum())).ToArray(); var resultsSorted0 = results0.OrderBy(list => list.Key).ToArray(); // local context.LocalDebug = true; IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context); var results1 = pt2.GroupBy(x => x % 2, (k, g) => new KeyValuePair<int, int>(k, ~g.Sum())).ToArray(); var resultsSorted1 = results1.OrderBy(list => list.Key).ToArray(); passed &= (resultsSorted0[0].Key == resultsSorted1[0].Key); passed &= (resultsSorted0[0].Value == resultsSorted1[0].Value); passed &= (resultsSorted0[1].Key == resultsSorted1[1].Key); passed &= (resultsSorted0[1].Value == resultsSorted1[1].Value); } catch (Exception Ex) { TestLog.Message("Error: " + Ex.Message); passed &= false; } TestLog.LogResult(new TestResult(testName, context, passed)); return passed; } } }
40.518967
201
0.508655
[ "Apache-2.0" ]
MicrosoftResearch/Dryad
DryadLinqTests/GroupByReduceTests.cs
50,203
C#
using System; using System.Runtime.ExceptionServices; using System.Linq; namespace System.Collections.Generic { internal static class DotnetPepperEnumerableExtensions { internal class ForEachError<T> { internal ForEachError(T item, long itemIndex, Exception ex) { Item = item; ItemIndex = itemIndex; _exceptionHolder = ExceptionDispatchInfo.Capture(ex ?? throw new ArgumentNullException(nameof(ex))); } private System.Runtime.ExceptionServices.ExceptionDispatchInfo _exceptionHolder { get; } public T Item { get; } public long ItemIndex { get; } public Exception Exception => _exceptionHolder.SourceException; public void Throw() => _exceptionHolder.Throw(); } internal static IEnumerable<ForEachError<T>> ForEach<T>(this IEnumerable<T> items, Action<T> action) { if (action == null) throw new ArgumentNullException(nameof(action)); long index = 0; foreach (var item in items) { Exception exception = null; try { action(item); } catch (Exception ex) { exception = ex; } if (exception != null) yield return new ForEachError<T>(item, index, exception); index++; } } internal static ICollection<ForEachError<T>> ForAll<T>(this IEnumerable<T> items, Action<T> action) => items.ForEach(action).ToArray(); internal static void ThrowAsAggregateException<T>(this ICollection<ForEachError<T>> errors, string message = null) { if (!errors.Any()) return; throw new AggregateException(message, errors.Select(e => e.Exception)); } internal static void ThrowFirstException<T>(this ICollection<ForEachError<T>> errors) { var error = errors.FirstOrDefault(); if (error != null) error.Throw(); } internal static void ThrowIfErrors<T>(this ICollection<ForEachError<T>> errors) { switch (errors.Count) { case 0: return; case 1: errors.First().Throw(); break; default: errors.ThrowAsAggregateException(); break; } } } }
33.782051
143
0.523719
[ "MIT" ]
stueeey/DotnetPepper.LanguageExtensions
src/DotnetPepper.EnumerableExtensions/DotnetPepperEnumerableExtensions.dnp.cs
2,637
C#
using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Mono.Options; using Mono.Profiler.Aot; using static System.Console; namespace aotprofiletool { class MainClass { static readonly string Name = "aotprofile-tool"; static bool Methods; static bool Modules; static bool Summary; static bool Types; static bool Verbose; static Regex FilterMethod; static Regex FilterModule; static Regex FilterType; static string Output; static string ProcessArguments (string [] args) { var help = false; var options = new OptionSet { $"Usage: {Name}.exe OPTIONS* <aotprofile-file>", "", "Processes AOTPROFILE files created by Mono's AOT Profiler", "", "Copyright 2019 Microsoft Corporation", "", "Options:", { "h|help|?", "Show this message and exit", v => help = v != null }, { "a|all", "Show modules, types and methods in the profile", v => Modules = Types = Methods = true }, { "d|modules", "Show modules in the profile", v => Modules = true }, { "filter-method=", "Filter by method with regex VALUE", v => FilterMethod = new Regex (v) }, { "filter-module=", "Filter by module with regex VALUE", v => FilterModule = new Regex (v) }, { "filter-type=", "Filter by type with regex VALUE", v => FilterType = new Regex (v) }, { "m|methods", "Show methods in the profile", v => Methods = true }, { "o|output=", "Write profile to OUTPUT file", v => Output = v }, { "s|summary", "Show summary of the profile", v => Summary = true }, { "t|types", "Show types in the profile", v => Types = true }, { "v|verbose", "Output information about progress during the run of the tool", v => Verbose = true }, "", "If no other option than -v is used then --all is used by default" }; var remaining = options.Parse (args); if (help || args.Length < 1) { options.WriteOptionDescriptions (Out); Environment.Exit (0); } if (remaining.Count != 1) { Error ("Please specify one <aotprofile-file> to process."); Environment.Exit (2); } return remaining [0]; } public static void Main (string [] args) { var path = ProcessArguments (args); if (!File.Exists (path)) { Error ($"'{path}' doesn't exist."); Environment.Exit (3); } if (args.Length == 1) { Modules = Types = Methods = true; } var reader = new ProfileReader (); ProfileData pd; using (var stream = new FileStream (path, FileMode.Open)) { if (Verbose) ColorWriteLine ($"Reading '{path}'...", ConsoleColor.Yellow); pd = reader.Read (stream); } List<MethodRecord> methods = pd.Methods; ICollection<TypeRecord> types = pd.Types; ICollection<ModuleRecord> modules = pd.Modules; if (FilterMethod != null || FilterType != null || FilterModule != null) { methods = new List<MethodRecord> (); types = new HashSet<TypeRecord> (); modules = new HashSet<ModuleRecord> (); foreach (var method in pd.Methods) { var type = method.Type; var module = type.Module; if (FilterModule != null) { var match = FilterModule.Match (module.ToString ()); if (!match.Success) continue; } if (FilterType != null) { var match = FilterType.Match (method.Type.ToString ()); if (!match.Success) continue; } if (FilterMethod != null) { var match = FilterMethod.Match (method.ToString ()); if (!match.Success) continue; } methods.Add (method); types.Add (type); modules.Add (module); } } if (FilterMethod == null && FilterType != null) { foreach (var type in pd.Types) { if (types.Contains (type)) continue; var match = FilterType.Match (type.ToString ()); if (!match.Success) continue; types.Add (type); } } if (Modules) { ColorWriteLine ($"Modules:", ConsoleColor.Green); foreach (var module in modules) WriteLine ($"\t{module.Mvid} {module}"); } if (Types) { ColorWriteLine ($"Types:", ConsoleColor.Green); foreach (var type in types) WriteLine ($"\t{type}"); } if (Methods) { ColorWriteLine ($"Methods:", ConsoleColor.Green); foreach (var method in methods) WriteLine ($"\t{method}"); } if (Summary) { ColorWriteLine ($"Summary:", ConsoleColor.Green); WriteLine ($"\tModules: {modules.Count.ToString ("N0"),10}{(modules.Count != pd.Modules.Count ? $" (of {pd.Modules.Count})" : "" )}"); WriteLine ($"\tTypes: {types.Count.ToString ("N0"),10}{(types.Count != pd.Types.Count ? $" (of {pd.Types.Count})" : "")}"); WriteLine ($"\tMethods: {methods.Count.ToString ("N0"),10}{(methods.Count != pd.Methods.Count ? $" (of {pd.Methods.Count})" : "")}"); } if (!string.IsNullOrEmpty (Output)) { if (Verbose) ColorWriteLine ($"Going to write the profile to '{Output}'", ConsoleColor.Yellow); var updatedPD = new ProfileData (new List<ModuleRecord>(modules), new List<TypeRecord> (types), methods); using (var stream = new FileStream (Output, FileMode.Create)) { var writer = new ProfileWriter (stream, updatedPD); writer.Write (); } } } static void ColorMessage (string message, ConsoleColor color, TextWriter writer, bool writeLine = true) { ForegroundColor = color; if (writeLine) writer.WriteLine (message); else writer.Write (message); ResetColor (); } public static void ColorWriteLine (string message, ConsoleColor color) => ColorMessage (message, color, Out); public static void ColorWrite (string message, ConsoleColor color) => ColorMessage (message, color, Out, false); public static void Error (string message) => ColorMessage ($"Error: {Name}: {message}", ConsoleColor.Red, Console.Error); public static void Warning (string message) => ColorMessage ($"Warning: {Name}: {message}", ConsoleColor.Yellow, Console.Error); } }
26.495652
139
0.616508
[ "MIT" ]
radekdoulik/aotprofile-tool
Program.cs
6,096
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunGesture : GestureBase { public EHand m_Hand; FingerExtendedDetails m_GestureDetail; void Start() { m_GestureDetail.bThumbExtended = true; m_GestureDetail.bIndexExtended = true; m_GestureDetail.bMiddleExtended = false; m_GestureDetail.bRingExtended = false; m_GestureDetail.bPinkeyExtended = false; } void Update() { } public override bool Detected() { DetectionManager.DetectionHand detectHand = DetectionManager.Get().GetHand(m_Hand); if (detectHand.IsSet()) { return detectHand.CheckWithDetails(m_GestureDetail); } return false; } }
20.421053
91
0.659794
[ "MIT" ]
KaiArch2014/HUD-with-Leap-Motion
Assets/LeapMotionGestureDetection/GestureDetection/Scripts/Gestures/GunGesture.cs
778
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.CostAndUsageReport")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 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.3.101.74")]
49.59375
303
0.753623
[ "Apache-2.0" ]
rluetzner/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/CostAndUsageReport/Properties/AssemblyInfo.cs
1,587
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.AnalysisServices.V20170714.Outputs { /// <summary> /// The gateway details. /// </summary> [OutputType] public sealed class GatewayDetailsResponse { /// <summary> /// Uri of the DMTS cluster. /// </summary> public readonly string DmtsClusterUri; /// <summary> /// Gateway object id from in the DMTS cluster for the gateway resource. /// </summary> public readonly string GatewayObjectId; /// <summary> /// Gateway resource to be associated with the server. /// </summary> public readonly string? GatewayResourceId; [OutputConstructor] private GatewayDetailsResponse( string dmtsClusterUri, string gatewayObjectId, string? gatewayResourceId) { DmtsClusterUri = dmtsClusterUri; GatewayObjectId = gatewayObjectId; GatewayResourceId = gatewayResourceId; } } }
28.608696
81
0.630699
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/AnalysisServices/V20170714/Outputs/GatewayDetailsResponse.cs
1,316
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LogIn")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LogIn")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0fedb0c1-27f5-4eb6-b617-7ca497f54f1a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.243243
84
0.745283
[ "MIT" ]
Xetier/HW0Refactor
LogIn/LogIn/Properties/AssemblyInfo.cs
1,381
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace WebAddressbookTests { [TestFixture] public class LoginTests : TestBase { [Test] public void LoginWithValidCredentials() { app.Auth.LogOut(); AccountData account = new AccountData("admin", "secret"); app.Auth.Login(account); Assert.IsTrue(app.Auth.IsLoggedIn(account)); } [Test] public void LoginWithInvalidCredentials() { app.Auth.LogOut(); AccountData account = new AccountData("admin", "sАeсsdret"); app.Auth.Login(account); Assert.IsFalse(app.Auth.IsLoggedIn(account)); } } }
25.21875
72
0.604709
[ "Apache-2.0" ]
SuhanovPV/csharp-training
addressbook-web-tests/addressbook-web-tests/addressbook-web-tests/tests/LoginTests.cs
811
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace JPAIUEO.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JPAIUEO.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// 查找类似 イカ/乌贼◎ ///かう/买う◎ ///めさす/目指す② ///たたかう/戦う◎ ///おく/置く置く② ///アイス/ice① ///きたい/期待期待 ///ここ◎ ///きこく/帰国 ///ちかく/近く ///きかい/机械 ///そこく/祖国 ///しお/塩 ///しあい/试合 ///ちしき/知识 ///かお/颜 ///たいせつ/大切 ///あいて/相手 ///くつした/靴下 ///てあし/手足 ///きおく/记忆 ///せかい/世界 ///くけい/矩形 ///あと/後 ///てあて/手当て ///くう/食う ///あさい/浅い ///いたい/痛い ///くい/悔い ///きそ/基础 ///とくい/得意 ///いく/行く ///あす/明日 ///とち/土地 ///ココア/cocoa ///しき/四季 ///とけい/时计 ///けいき/景気 ///あし/脚 ///いと/意図 ///こく/浓く ///うし/牛 ///ちかう/誓う ///こえ/声 ///こし/腰 ///うち/内 ///こい/鲤 ///おす/推す ///つくえ/机 ///すくう/救う ///きそく/规则 ///きせき/奇迹 ///おたく/お宅 ///つかう/使う ///きく/闻く ///しかく/资格 的本地化字符串。 /// </summary> internal static string danci1 { get { return ResourceManager.GetString("danci1", resourceCulture); } } /// <summary> /// 查找类似 あ行单词总结: /// ///あ ア ///● 雨(あめ)① 雨 ///● 飴(あめ)② 糖 ///● 挨拶(あいさつ)① 招呼 ///● 赤い(あかい)② 红的 ///● 青い(あおい)② 蓝的,绿的,苍白的 /// ///い イ ///● 家(いえ)② 家 ///● 椅子(いし)○ 0 椅子 ///● 糸(いと)① 线,丝 ///● 犬(いぬ)② 狗 ///● 石(いし)② 石头 /// ///う ウ ///● 牛(うし)② 牛 ///● 歌う(うたう)③ 唱歌 ///● 嬉しい(うれしい)③ 欢喜的,高兴的,喜悦的 ///● 海(うみ)① 海,大海 ///● 馬(うま)② 马 /// ///え エ ///● 絵(え)① 画,图画 ///● 映画(えいが)○ 0 电影 ///● 遠足(えんそく)○ 0 远足,郊游,(徒步)旅游 ///● 演奏(えんそう)○ 0 演奏 ///● 演出(えんしゅつ)○ 0 演出,表演 /// ///お オ ///● 思う(おもう)② 想,认为,打算 ///● 男(おとこ)③ 男子,男人 ///● 女(おんな)③ 女子,女人 ///● 起きる(おきる)② 起床,起来 ///● 温泉(おんせん)○ 0 温泉 /// ///绕口令练习: ///あえい あおう あえいう [字符串的其余部分被截断]&quot;; 的本地化字符串。 /// </summary> internal static string danci2 { get { return ResourceManager.GetString("danci2", resourceCulture); } } /// <summary> /// 查找 System.Byte[] 类型的本地化资源。 /// </summary> internal static byte[] data { get { object obj = ResourceManager.GetObject("data", resourceCulture); return ((byte[])(obj)); } } } }
27.643243
173
0.446422
[ "MIT" ]
aiqinxuancai/JPAIUEO
JPAIUEO/Properties/Resources.Designer.cs
6,738
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; using Microsoft.Azure.Devices; // Added from SendCloudToDevice using Newtonsoft.Json; using Microsoft.ServiceBus.Messaging; // Declare Junction Structure struct Junction { public string north_traffic; public int north_green_time; public int north_priority; public string east_traffic; public int east_green_time; public int east_priority; public string south_traffic; public int south_green_time; public int south_priority; public string west_traffic; public int west_green_time; public int west_priority; }; // Declare Ratio Structure public struct Ratio { public Ratio(int charArraySize) : this() { priority1 = new int[charArraySize]; priority2 = new int[charArraySize]; flow_value = new float[charArraySize]; percentage_value = new float[charArraySize]; } public int[] priority1; public int[] priority2; public float[] flow_value; public float[] percentage_value; } namespace InnovateTraffic { public partial class Form1 : Form { // Added from SendCloudToDevice static ServiceClient serviceClient; // Original from ReadDeviceToCloudMessages static string connectionString = "HostName=trafficIoT.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=gnpmxqawgwF4uybTebpFsh3XpFvHq5XbA40I5RIjNNA="; static string iotHubD2cEndpoint = "messages/events"; static EventHubClient eventHubClient; //private int _blink = 0; // Global Parameters int total_time; static int receive_status; // Junction 1 Parameters static byte[] junc1_priority = new byte[4]; byte[] junc1_direction = new byte[4] { 1, 2, 3, 4 }; byte junc1_temp_priority; static int[] junc1_green_time = new int[4]; int[] junc1_remaining_green_time = new int[4]; // Junction 2 Parameters static byte[] junc2_priority = new byte[4]; byte[] junc2_direction = new byte[4] { 1, 2, 3, 4 }; byte junc2_temp_priority; static int[] junc2_green_time = new int[4]; int[] junc2_remaining_green_time = new int[4]; //class junction //{ // byte[] priority = new byte[4]; // byte[] direction = new byte[4] { 1, 2, 3, 4 }; // byte temp_priority; // int[] temp_time = new int[4]; // int[] remaining_green_time = new int[4]; //} public Form1() { InitializeComponent(); button1.Visible = false; button2.Visible = false; Azure_Main(); } void Azure_Main() { eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint); // Added from SendCloudToDevice serviceClient = ServiceClient.CreateFromConnectionString(connectionString); var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds; foreach (string partition in d2cPartitions) { ReceiveMessagesFromDeviceAsync(partition); } } private async Task ReceiveMessagesFromDeviceAsync(string partition) { var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow); while (true) { EventData eventData = await eventHubReceiver.ReceiveAsync(); if (eventData == null) continue; string data = Encoding.UTF8.GetString(eventData.GetBytes()); dynamic test = JsonConvert.DeserializeObject(data); Junction Junction1; Junction Junction2; // Junction 1 Variables Initialization Junction1.north_traffic = test.nt1; Junction1.north_green_time = 0; Junction1.north_priority = 0; Junction1.east_traffic = test.et1; Junction1.east_green_time = 0; Junction1.east_priority = 0; Junction1.south_traffic = test.st1; Junction1.south_green_time = 0; Junction1.south_priority = 0; Junction1.west_traffic = test.wt1; Junction1.west_green_time = 0; Junction1.west_priority = 0; Junction1 = Algorithm(Junction1); SendCloudToDeviceMessageAsync(Junction1); // Junction 2 Variables Initialization Junction2.north_traffic = test.nt2; Junction2.north_green_time = 0; Junction2.north_priority = 0; Junction2.east_traffic = test.et2; Junction2.east_green_time = 0; Junction2.east_priority = 0; Junction2.south_traffic = test.st2; Junction2.south_green_time = 0; Junction2.south_priority = 0; Junction2.west_traffic = test.wt2; Junction2.west_green_time = 0; Junction2.west_priority = 0; Junction2 = Algorithm(Junction2); SendCloudToDeviceMessageAsync(Junction2); receive_status = TrafficLight_Init(Junction1, Junction2); Main(); } } private void Form1_Load(object sender, EventArgs e) { } // Turn the bulb On or Off private void ledBulb_Click(object sender, EventArgs e) { //((LedBulb)sender).On = !((LedBulb)sender).On; } private void ledBulb1_Click(object sender, EventArgs e) { //if (_blink == 0) _blink = 500; //else _blink = 0; //((LedBulb)sender).Blink(_blink); } private async void button1_Click(object sender, EventArgs e) { byte i; int counter1, counter2; int initial1 = 0; int initial2 = 0; while (receive_status == 0) { await Task.Delay(100); } Priority_Sort(); show_green_time(); calc_total_time(); calc_remaining_time(); show_remaining_time(); int[] junc1_north_array = new int[total_time]; int[] junc1_east_array = new int[total_time]; int[] junc1_south_array = new int[total_time]; int[] junc1_west_array = new int[total_time]; int[] junc2_north_array = new int[total_time]; int[] junc2_east_array = new int[total_time]; int[] junc2_south_array = new int[total_time]; int[] junc2_west_array = new int[total_time]; for (i = 0; i < 4; i++) { // Junction 1 All Direction Array junc1_temp_priority = junc1_direction[i]; if (junc1_temp_priority == 1) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_north_array[counter1] = 3; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_north_array[counter1] = 2; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_north_array[++counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 2) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_east_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_east_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_east_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 3) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_south_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_south_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_south_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 4) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_west_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; } junc1_west_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; initial1 = counter1; } // Junction 2 All Direction Array junc2_temp_priority = junc2_direction[i]; if (junc2_temp_priority == 1) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_north_array[counter2] = 3; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_north_array[counter2] = 2; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_north_array[++counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 2) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_east_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_east_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_east_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 3) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_south_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_south_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_south_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 4) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_west_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; } junc2_west_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; initial2 = counter2; } } for (i = 0; i < total_time; i++) { junc1_traffic_light(junc1_north_array[i], junc1_east_array[i], junc1_south_array[i], junc1_west_array[i]); junc2_traffic_light(junc2_north_array[i], junc2_east_array[i], junc2_south_array[i], junc2_west_array[i]); show_remaining_time(); await Task.Delay(1000); } } private void button2_Click(object sender, EventArgs e) { ledBulb1.On = false; ledBulb2.On = false; ledBulb3.On = false; ledBulb4.On = false; ledBulb5.On = false; ledBulb6.On = false; ledBulb7.On = false; ledBulb8.On = false; ledBulb9.On = false; ledBulb10.On = false; ledBulb11.On = false; ledBulb12.On = false; ledBulb13.On = false; ledBulb14.On = false; ledBulb15.On = false; ledBulb16.On = false; ledBulb17.On = false; ledBulb18.On = false; ledBulb19.On = false; ledBulb20.On = false; ledBulb21.On = false; ledBulb22.On = false; ledBulb23.On = false; ledBulb24.On = false; } async void Main() { byte i; int counter1, counter2; int initial1 = 0; int initial2 = 0; //sevenSegment1.ColorLight = Color.Red; //sevenSegment2.ColorLight = Color.Red; //sevenSegment3.ColorLight = Color.Red; //sevenSegment4.ColorLight = Color.Red; //sevenSegment5.ColorLight = Color.Red; //sevenSegment6.ColorLight = Color.Red; //sevenSegment7.ColorLight = Color.Red; //sevenSegment8.ColorLight = Color.Red; //sevenSegment9.ColorLight = Color.Red; //sevenSegment10.ColorLight = Color.Red; //sevenSegment11.ColorLight = Color.Red; //sevenSegment12.ColorLight = Color.Red; //sevenSegment13.ColorLight = Color.Red; //sevenSegment14.ColorLight = Color.Red; //sevenSegment15.ColorLight = Color.Red; //sevenSegment16.ColorLight = Color.Red; while (receive_status == 0) { await Task.Delay(100); } show_green_time(); Priority_Sort(); calc_total_time(); calc_remaining_time(); show_remaining_time(); int[] junc1_north_array = new int[total_time]; int[] junc1_east_array = new int[total_time]; int[] junc1_south_array = new int[total_time]; int[] junc1_west_array = new int[total_time]; int[] junc2_north_array = new int[total_time]; int[] junc2_east_array = new int[total_time]; int[] junc2_south_array = new int[total_time]; int[] junc2_west_array = new int[total_time]; for (i = 0; i < 4; i++) { // Junction 1 All Direction Array junc1_temp_priority = junc1_direction[i]; if (junc1_temp_priority == 1) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_north_array[counter1] = 3; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_north_array[counter1] = 2; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_north_array[++counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 2) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_east_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_east_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_east_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 3) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_south_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; } junc1_south_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; junc1_south_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_west_array[counter1] = 1; initial1 = counter1; } if (junc1_temp_priority == 4) { for (counter1 = initial1; counter1 < (initial1 + junc1_green_time[(junc1_temp_priority - 1)]); counter1++) { junc1_west_array[counter1] = 3; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; } junc1_west_array[counter1] = 2; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; junc1_west_array[++counter1] = 1; junc1_north_array[counter1] = 1; junc1_east_array[counter1] = 1; junc1_south_array[counter1] = 1; initial1 = counter1; } // Junction 2 All Direction Array junc2_temp_priority = junc2_direction[i]; if (junc2_temp_priority == 1) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_north_array[counter2] = 3; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_north_array[counter2] = 2; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_north_array[++counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 2) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_east_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_east_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_east_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 3) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_south_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; } junc2_south_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; junc2_south_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_west_array[counter2] = 1; initial2 = counter2; } if (junc2_temp_priority == 4) { for (counter2 = initial2; counter2 < (initial2 + junc2_green_time[(junc2_temp_priority - 1)]); counter2++) { junc2_west_array[counter2] = 3; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; } junc2_west_array[counter2] = 2; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; junc2_west_array[++counter2] = 1; junc2_north_array[counter2] = 1; junc2_east_array[counter2] = 1; junc2_south_array[counter2] = 1; initial2 = counter2; } } for (i = 0; i < total_time; i++) { junc1_traffic_light(junc1_north_array[i], junc1_east_array[i], junc1_south_array[i], junc1_west_array[i]); junc2_traffic_light(junc2_north_array[i], junc2_east_array[i], junc2_south_array[i], junc2_west_array[i]); show_remaining_time(); await Task.Delay(1000); } //Reset(); } void Reset() { ledBulb1.On = false; ledBulb2.On = false; ledBulb3.On = false; ledBulb4.On = false; ledBulb5.On = false; ledBulb6.On = false; ledBulb7.On = false; ledBulb8.On = false; ledBulb9.On = false; ledBulb10.On = false; ledBulb11.On = false; ledBulb12.On = false; ledBulb13.On = false; ledBulb14.On = false; ledBulb15.On = false; ledBulb16.On = false; ledBulb17.On = false; ledBulb18.On = false; ledBulb19.On = false; ledBulb20.On = false; ledBulb21.On = false; ledBulb22.On = false; ledBulb23.On = false; ledBulb24.On = false; //sevenSegment1.ColorLight = Color.DimGray; //sevenSegment2.ColorLight = Color.DimGray; //sevenSegment3.ColorLight = Color.DimGray; //sevenSegment4.ColorLight = Color.DimGray; //sevenSegment5.ColorLight = Color.DimGray; //sevenSegment6.ColorLight = Color.DimGray; //sevenSegment7.ColorLight = Color.DimGray; //sevenSegment8.ColorLight = Color.DimGray; //sevenSegment9.ColorLight = Color.DimGray; //sevenSegment10.ColorLight = Color.DimGray; //sevenSegment11.ColorLight = Color.DimGray; //sevenSegment12.ColorLight = Color.DimGray; //sevenSegment13.ColorLight = Color.DimGray; //sevenSegment14.ColorLight = Color.DimGray; //sevenSegment15.ColorLight = Color.DimGray; //sevenSegment16.ColorLight = Color.DimGray; //sevenSegment1.Value = Convert.ToString(8); //sevenSegment2.Value = Convert.ToString(8); //sevenSegment3.Value = Convert.ToString(8); //sevenSegment4.Value = Convert.ToString(8); //sevenSegment5.Value = Convert.ToString(8); //sevenSegment6.Value = Convert.ToString(8); //sevenSegment7.Value = Convert.ToString(8); //sevenSegment8.Value = Convert.ToString(8); //sevenSegment9.Value = Convert.ToString(8); //sevenSegment10.Value = Convert.ToString(8); //sevenSegment11.Value = Convert.ToString(8); //sevenSegment12.Value = Convert.ToString(8); //sevenSegment13.Value = Convert.ToString(8); //sevenSegment14.Value = Convert.ToString(8); //sevenSegment15.Value = Convert.ToString(8); //sevenSegment16.Value = Convert.ToString(8); } static int TrafficLight_Init(Junction junc1, Junction junc2) { //// Junction 1 Traffic Light Priority //junc1_priority[0] = 2; //junc1_priority[1] = 4; //junc1_priority[2] = 3; //junc1_priority[3] = 1; // Junction 1 Traffic Light Priority junc1_priority[0] = Convert.ToByte(junc1.north_priority); junc1_priority[1] = Convert.ToByte(junc1.east_priority); junc1_priority[2] = Convert.ToByte(junc1.south_priority); junc1_priority[3] = Convert.ToByte(junc1.west_priority); //// Junction 1 Traffic Light Duration //junc1_green_time[0] = 5; // 5 seconds //junc1_green_time[1] = 5; // 5 seconds //junc1_green_time[2] = 5; // 5 seconds //junc1_green_time[3] = 5; // 5 seconds // Junction 1 Traffic Light Duration junc1_green_time[0] = junc1.north_green_time; junc1_green_time[1] = junc1.east_green_time; junc1_green_time[2] = junc1.south_green_time; junc1_green_time[3] = junc1.west_green_time; //// Junction 2 Traffic Light Priority //junc2_priority[0] = 2; //junc2_priority[1] = 4; //junc2_priority[2] = 3; //junc2_priority[3] = 1; // Junction 2 Traffic Light Priority junc2_priority[0] = Convert.ToByte(junc2.north_priority); junc2_priority[1] = Convert.ToByte(junc2.east_priority); junc2_priority[2] = Convert.ToByte(junc2.south_priority); junc2_priority[3] = Convert.ToByte(junc2.west_priority); //// Junction 2 Traffic Light Duration //junc2_green_time[0] = 5; // 5 seconds //junc2_green_time[1] = 5; // 5 seconds //junc2_green_time[2] = 5; // 5 seconds //junc2_green_time[3] = 5; // 5 seconds // Junction 2 Traffic Light Duration junc2_green_time[0] = junc2.north_green_time; junc2_green_time[1] = junc2.east_green_time; junc2_green_time[2] = junc2.south_green_time; junc2_green_time[3] = junc2.west_green_time; // Junction 1 Traffic Lights Initial State ledBulb1.On = true; ledBulb2.On = false; ledBulb3.On = false; ledBulb4.On = true; ledBulb5.On = false; ledBulb6.On = false; ledBulb7.On = true; ledBulb8.On = false; ledBulb9.On = false; ledBulb10.On = true; ledBulb11.On = false; ledBulb12.On = false; // Junction 2 Traffic Lights Initial State ledBulb13.On = true; ledBulb14.On = false; ledBulb15.On = false; ledBulb16.On = true; ledBulb17.On = false; ledBulb18.On = false; ledBulb19.On = true; ledBulb20.On = false; ledBulb21.On = false; ledBulb22.On = true; ledBulb23.On = false; ledBulb24.On = false; return 1; } void calc_total_time() { total_time = junc1_green_time[0] + junc1_green_time[1] + junc1_green_time[2] + junc1_green_time[3]; total_time += 10; // 10 seconds tolerance } void calc_remaining_time() { int[] junc1_actual_direction = new int[4]; int[] junc2_actual_direction = new int[4]; junc1_actual_direction[0] = junc1_direction[0] - 1; junc1_actual_direction[1] = junc1_direction[1] - 1; junc1_actual_direction[2] = junc1_direction[2] - 1; junc1_actual_direction[3] = junc1_direction[3] - 1; junc1_remaining_green_time[junc1_actual_direction[0]] = 0; junc1_remaining_green_time[junc1_actual_direction[1]] = (junc1_green_time[junc1_actual_direction[0]] + 2); junc1_remaining_green_time[junc1_actual_direction[2]] = (junc1_green_time[junc1_actual_direction[0]] + junc1_green_time[junc1_actual_direction[1]] + 3); junc1_remaining_green_time[junc1_actual_direction[3]] = (junc1_green_time[junc1_actual_direction[0]] + junc1_green_time[junc1_actual_direction[1]] + junc1_green_time[junc1_actual_direction[2]] + 4); junc2_actual_direction[0] = junc2_direction[0] - 1; junc2_actual_direction[1] = junc2_direction[1] - 1; junc2_actual_direction[2] = junc2_direction[2] - 1; junc2_actual_direction[3] = junc2_direction[3] - 1; junc2_remaining_green_time[junc2_actual_direction[0]] = 0; junc2_remaining_green_time[junc2_actual_direction[1]] = (junc2_green_time[junc2_actual_direction[0]] + 2); junc2_remaining_green_time[junc2_actual_direction[2]] = (junc2_green_time[junc2_actual_direction[0]] + junc2_green_time[junc2_actual_direction[1]] + 3); junc2_remaining_green_time[junc2_actual_direction[3]] = (junc2_green_time[junc2_actual_direction[0]] + junc2_green_time[junc2_actual_direction[1]] + junc2_green_time[junc2_actual_direction[2]] + 4); } void show_remaining_time() { sevensegment_display(); //if (junc1_remaining_green_time[0] == 0) //{ // label1.Text = Convert.ToString(0); //} //else if (junc1_remaining_green_time[0] > 0) //{ // label1.Text = Convert.ToString(junc1_remaining_green_time[0]--); //} //if (junc1_remaining_green_time[1] == 0) //{ // label2.Text = Convert.ToString(0); //} //else if (junc1_remaining_green_time[1] > 0) //{ // label2.Text = Convert.ToString(junc1_remaining_green_time[1]--); //} //if (junc1_remaining_green_time[2] == 0) //{ // label3.Text = Convert.ToString(0); //} //else if (junc1_remaining_green_time[2] > 0) //{ // label3.Text = Convert.ToString(junc1_remaining_green_time[2]--); //} //if (junc1_remaining_green_time[3] == 0) //{ // label4.Text = Convert.ToString(0); //} //else if (junc1_remaining_green_time[3] > 0) //{ // label4.Text = Convert.ToString(junc1_remaining_green_time[3]--); //} //if (junc2_remaining_green_time[0] == 0) //{ // label5.Text = Convert.ToString(0); //} //else if (junc2_remaining_green_time[0] > 0) //{ // label5.Text = Convert.ToString(junc2_remaining_green_time[0]--); //} //if (junc2_remaining_green_time[1] == 0) //{ // label6.Text = Convert.ToString(0); //} //else if (junc2_remaining_green_time[1] > 0) //{ // label6.Text = Convert.ToString(junc2_remaining_green_time[1]--); //} //if (junc2_remaining_green_time[2] == 0) //{ // label7.Text = Convert.ToString(0); //} //else if (junc2_remaining_green_time[2] > 0) //{ // label7.Text = Convert.ToString(junc2_remaining_green_time[2]--); //} //if (junc2_remaining_green_time[3] == 0) //{ // label8.Text = Convert.ToString(0); //} //else if (junc2_remaining_green_time[3] > 0) //{ // label8.Text = Convert.ToString(junc2_remaining_green_time[3]--); //} // Improved Code Due To Show Green Time if (junc1_remaining_green_time[0] == 0) { } else if (junc1_remaining_green_time[0] > 0) { junc1_remaining_green_time[0]--; } if (junc1_remaining_green_time[1] == 0) { } else if (junc1_remaining_green_time[1] > 0) { junc1_remaining_green_time[1]--; } if (junc1_remaining_green_time[2] == 0) { } else if (junc1_remaining_green_time[2] > 0) { junc1_remaining_green_time[2]--; } if (junc1_remaining_green_time[3] == 0) { } else if (junc1_remaining_green_time[3] > 0) { junc1_remaining_green_time[3]--; } if (junc2_remaining_green_time[0] == 0) { } else if (junc2_remaining_green_time[0] > 0) { junc2_remaining_green_time[0]--; } if (junc2_remaining_green_time[1] == 0) { } else if (junc2_remaining_green_time[1] > 0) { junc2_remaining_green_time[1]--; } if (junc2_remaining_green_time[2] == 0) { } else if (junc2_remaining_green_time[2] > 0) { junc2_remaining_green_time[2]--; } if (junc2_remaining_green_time[3] == 0) { } else if (junc2_remaining_green_time[3] > 0) { junc2_remaining_green_time[3]--; } } void show_green_time() { label1.Text = Convert.ToString(junc1_green_time[0]); label2.Text = Convert.ToString(junc1_green_time[1]); label3.Text = Convert.ToString(junc1_green_time[2]); label4.Text = Convert.ToString(junc1_green_time[3]); label5.Text = Convert.ToString(junc2_green_time[0]); label6.Text = Convert.ToString(junc2_green_time[1]); label7.Text = Convert.ToString(junc2_green_time[2]); label8.Text = Convert.ToString(junc2_green_time[3]); } void junc1_traffic_light(int a, int b, int c, int d) { ledBulb1.On = false; ledBulb2.On = false; ledBulb3.On = false; if (a == 1) { ledBulb1.On = true; } else if (a == 2) { ledBulb2.On = true; } else if (a == 3) { ledBulb3.On = true; } ledBulb4.On = false; ledBulb5.On = false; ledBulb6.On = false; if (b == 1) { ledBulb4.On = true; } else if (b == 2) { ledBulb5.On = true; } else if (b == 3) { ledBulb6.On = true; } ledBulb7.On = false; ledBulb8.On = false; ledBulb9.On = false; if (c == 1) { ledBulb7.On = true; } else if (c == 2) { ledBulb8.On = true; } else if (c == 3) { ledBulb9.On = true; } ledBulb10.On = false; ledBulb11.On = false; ledBulb12.On = false; if (d == 1) { ledBulb10.On = true; } else if (d == 2) { ledBulb11.On = true; } else if (d == 3) { ledBulb12.On = true; } } void junc2_traffic_light(int a, int b, int c, int d) { ledBulb13.On = false; ledBulb14.On = false; ledBulb15.On = false; if (a == 1) { ledBulb13.On = true; } else if (a == 2) { ledBulb14.On = true; } else if (a == 3) { ledBulb15.On = true; } ledBulb16.On = false; ledBulb17.On = false; ledBulb18.On = false; if (b == 1) { ledBulb16.On = true; } else if (b == 2) { ledBulb17.On = true; } else if (b == 3) { ledBulb18.On = true; } ledBulb19.On = false; ledBulb20.On = false; ledBulb21.On = false; if (c == 1) { ledBulb19.On = true; } else if (c == 2) { ledBulb20.On = true; } else if (c == 3) { ledBulb21.On = true; } ledBulb22.On = false; ledBulb23.On = false; ledBulb24.On = false; if (d == 1) { ledBulb22.On = true; } else if (d == 2) { ledBulb23.On = true; } else if (d == 3) { ledBulb24.On = true; } } void sevensegment_display () { int temp_sevensegment; if (junc1_remaining_green_time[0] < 10) { sevenSegment1.Value = Convert.ToString(0); sevenSegment2.Value = Convert.ToString(junc1_remaining_green_time[0]); } else if (junc1_remaining_green_time[0] >= 10) { temp_sevensegment = junc1_remaining_green_time[0] / 10; sevenSegment1.Value = Convert.ToString(junc1_remaining_green_time[0] / 10); sevenSegment2.Value = Convert.ToString(junc1_remaining_green_time[0] - (temp_sevensegment*10)); } if (junc1_remaining_green_time[1] < 10) { sevenSegment3.Value = Convert.ToString(0); sevenSegment4.Value = Convert.ToString(junc1_remaining_green_time[1]); } else if (junc1_remaining_green_time[1] >= 10) { temp_sevensegment = junc1_remaining_green_time[1] / 10; sevenSegment3.Value = Convert.ToString(junc1_remaining_green_time[1] / 10); sevenSegment4.Value = Convert.ToString(junc1_remaining_green_time[1] - (temp_sevensegment * 10)); } if (junc1_remaining_green_time[2] < 10) { sevenSegment5.Value = Convert.ToString(0); sevenSegment6.Value = Convert.ToString(junc1_remaining_green_time[2]); } else if (junc1_remaining_green_time[2] >= 10) { temp_sevensegment = junc1_remaining_green_time[2] / 10; sevenSegment5.Value = Convert.ToString(junc1_remaining_green_time[2] / 10); sevenSegment6.Value = Convert.ToString(junc1_remaining_green_time[2] - (temp_sevensegment * 10)); } if (junc1_remaining_green_time[3] < 10) { sevenSegment7.Value = Convert.ToString(0); sevenSegment8.Value = Convert.ToString(junc1_remaining_green_time[3]); } else if (junc1_remaining_green_time[3] >= 10) { temp_sevensegment = junc1_remaining_green_time[3] / 10; sevenSegment7.Value = Convert.ToString(junc1_remaining_green_time[3] / 10); sevenSegment8.Value = Convert.ToString(junc1_remaining_green_time[3] - (temp_sevensegment * 10)); } if (junc2_remaining_green_time[0] < 10) { sevenSegment9.Value = Convert.ToString(0); sevenSegment10.Value = Convert.ToString(junc2_remaining_green_time[0]); } else if (junc2_remaining_green_time[0] >= 10) { temp_sevensegment = junc2_remaining_green_time[0] / 10; sevenSegment9.Value = Convert.ToString(junc2_remaining_green_time[0] / 10); sevenSegment10.Value = Convert.ToString(junc2_remaining_green_time[0] - (temp_sevensegment * 10)); } if (junc2_remaining_green_time[1] < 10) { sevenSegment11.Value = Convert.ToString(0); sevenSegment12.Value = Convert.ToString(junc2_remaining_green_time[1]); } else if (junc2_remaining_green_time[1] >= 10) { temp_sevensegment = junc2_remaining_green_time[1] / 10; sevenSegment11.Value = Convert.ToString(junc2_remaining_green_time[1] / 10); sevenSegment12.Value = Convert.ToString(junc2_remaining_green_time[1] - (temp_sevensegment * 10)); } if (junc2_remaining_green_time[2] < 10) { sevenSegment13.Value = Convert.ToString(0); sevenSegment14.Value = Convert.ToString(junc2_remaining_green_time[2]); } else if (junc2_remaining_green_time[2] >= 10) { temp_sevensegment = junc2_remaining_green_time[2] / 10; sevenSegment13.Value = Convert.ToString(junc2_remaining_green_time[2] / 10); sevenSegment14.Value = Convert.ToString(junc2_remaining_green_time[2] - (temp_sevensegment * 10)); } if (junc2_remaining_green_time[3] < 10) { sevenSegment15.Value = Convert.ToString(0); sevenSegment16.Value = Convert.ToString(junc2_remaining_green_time[3]); } else if (junc2_remaining_green_time[3] >= 10) { temp_sevensegment = junc2_remaining_green_time[3] / 10; sevenSegment15.Value = Convert.ToString(junc2_remaining_green_time[3] / 10); sevenSegment16.Value = Convert.ToString(junc2_remaining_green_time[3] - (temp_sevensegment * 10)); } } void Priority_Sort() { byte i, i2, temp_priority, temp_direction; int temp_time_buffer; byte[] priority_array = new byte[4]; byte[] direction_array = new byte[4]; int[] time_array = new int[4]; int[] remaining_time_array = new int[4]; // Junction 1 Priority Sort priority_array[0] = junc1_priority[0]; priority_array[1] = junc1_priority[1]; priority_array[2] = junc1_priority[2]; priority_array[3] = junc1_priority[3]; time_array[0] = junc1_green_time[0]; time_array[1] = junc1_green_time[1]; time_array[2] = junc1_green_time[2]; time_array[3] = junc1_green_time[3]; direction_array[0] = junc1_direction[0]; direction_array[1] = junc1_direction[1]; direction_array[2] = junc1_direction[2]; direction_array[3] = junc1_direction[3]; for (i2 = 0; i2 < 3; i2++) { for (i = 0; i < 4; i++) { if (i != 3) { if (priority_array[i] < priority_array[i + 1]) { temp_priority = priority_array[i]; priority_array[i] = priority_array[i + 1]; priority_array[i + 1] = temp_priority; temp_time_buffer = time_array[i]; time_array[i] = time_array[i + 1]; time_array[i + 1] = temp_time_buffer; temp_direction = direction_array[i]; direction_array[i] = direction_array[i + 1]; direction_array[i + 1] = temp_direction; } } } } junc1_priority[0] = priority_array[0]; junc1_priority[1] = priority_array[1]; junc1_priority[2] = priority_array[2]; junc1_priority[3] = priority_array[3]; junc1_green_time[0] = time_array[0]; junc1_green_time[1] = time_array[1]; junc1_green_time[2] = time_array[2]; junc1_green_time[3] = time_array[3]; junc1_direction[0] = direction_array[0]; junc1_direction[1] = direction_array[1]; junc1_direction[2] = direction_array[2]; junc1_direction[3] = direction_array[3]; // Junction 2 Priority Sort priority_array[0] = junc2_priority[0]; priority_array[1] = junc2_priority[1]; priority_array[2] = junc2_priority[2]; priority_array[3] = junc2_priority[3]; time_array[0] = junc2_green_time[0]; time_array[1] = junc2_green_time[1]; time_array[2] = junc2_green_time[2]; time_array[3] = junc2_green_time[3]; direction_array[0] = junc2_direction[0]; direction_array[1] = junc2_direction[1]; direction_array[2] = junc2_direction[2]; direction_array[3] = junc2_direction[3]; for (i2 = 0; i2 < 3; i2++) { for (i = 0; i < 4; i++) { if (i != 3) { if (priority_array[i] < priority_array[i + 1]) { temp_priority = priority_array[i]; priority_array[i] = priority_array[i + 1]; priority_array[i + 1] = temp_priority; temp_time_buffer = time_array[i]; time_array[i] = time_array[i + 1]; time_array[i + 1] = temp_time_buffer; temp_direction = direction_array[i]; direction_array[i] = direction_array[i + 1]; direction_array[i + 1] = temp_direction; } } } } junc2_priority[0] = priority_array[0]; junc2_priority[1] = priority_array[1]; junc2_priority[2] = priority_array[2]; junc2_priority[3] = priority_array[3]; junc2_green_time[0] = time_array[0]; junc2_green_time[1] = time_array[1]; junc2_green_time[2] = time_array[2]; junc2_green_time[3] = time_array[3]; junc2_direction[0] = direction_array[0]; junc2_direction[1] = direction_array[1]; junc2_direction[2] = direction_array[2]; junc2_direction[3] = direction_array[3]; } static Junction Algorithm(Junction junc_traffic) { /* Setup your example here, code that should run once */ int junc_north, junc_east, junc_south, junc_west; int[] volume = new int[4]; var ratio = new Ratio(4); int[] effective = new int[4]; int[] green = new int[4]; int[] res = new int[3]; int cycle = 20; // One Complete Cycle = 20 Seconds int max_flow_rate = 700; int i = 0; int x1, x2, y1, y2, temp1, temp2, temp3, temp4, temp5, temp6; junc_north = Convert.ToInt32(junc_traffic.north_traffic); junc_east = Convert.ToInt32(junc_traffic.east_traffic); junc_south = Convert.ToInt32(junc_traffic.south_traffic); junc_west = Convert.ToInt32(junc_traffic.west_traffic); /* Code in this loop will run repeatedly */ volume[0] = current_traffic_volume(junc_north, cycle); volume[1] = current_traffic_volume(junc_east, cycle); volume[2] = current_traffic_volume(junc_south, cycle); volume[3] = current_traffic_volume(junc_west, cycle); ratio.flow_value[0] = flow_ratio(volume[0], max_flow_rate); ratio.flow_value[1] = flow_ratio(volume[1], max_flow_rate); ratio.flow_value[2] = flow_ratio(volume[2], max_flow_rate); ratio.flow_value[3] = flow_ratio(volume[3], max_flow_rate); ratio.percentage_value[0] = (ratio.flow_value[0] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3])); ratio.percentage_value[1] = (ratio.flow_value[1] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3])); ratio.percentage_value[2] = (ratio.flow_value[2] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3])); ratio.percentage_value[3] = (ratio.flow_value[3] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3])); ratio = compare(ratio); // Find Max Ratio effective[0] = effective_green_time(ratio.percentage_value[0], cycle); green[0] = phase_green_time(effective[0]); res[0] = remaining_green_time(cycle, green[0]); effective[1] = remaining_effective_green_time(res[0], ratio.percentage_value[1], ratio.percentage_value[0], 0, ratio.percentage_value); green[1] = phase_green_time(effective[1]); res[1] = remaining_green_time(res[0], green[1]); effective[2] = remaining_effective_green_time(res[1], ratio.percentage_value[2], ratio.percentage_value[1], 1, ratio.percentage_value); green[2] = phase_green_time(effective[2]); res[2] = remaining_green_time(res[1], green[2]); effective[3] = remaining_effective_green_time(res[2], ratio.percentage_value[3], ratio.percentage_value[2], 2, ratio.percentage_value); green[3] = phase_green_time(effective[3]); for (x1 = 0; x1 < 3; x1++) { for (y1 = 0; y1 < 3; y1++) { if (green[y1] < green[y1 + 1]) { temp1 = green[y1]; green[y1] = green[y1 + 1]; green[y1] = temp1; temp2 = ratio.priority1[y1]; ratio.priority1[y1] = ratio.priority1[y1 + 1]; ratio.priority1[y1 + 1] = temp2; temp3 = ratio.priority2[y1]; ratio.priority2[y1] = ratio.priority2[y1 + 1]; ratio.priority2[y1 + 1] = temp3; } } } for (x2 = 0; x2 < 3; x2++) { for (y2 = 0; y2 < 3; y2++) { if (ratio.priority1[y2] > ratio.priority1[y2 + 1]) { temp4 = green[y2]; green[y2] = green[y2 + 1]; green[y2 + 1] = temp4; temp5 = ratio.priority1[y2]; ratio.priority1[y2] = ratio.priority1[y2 + 1]; ratio.priority1[y2 + 1] = temp5; temp6 = ratio.priority2[y2]; ratio.priority2[y2] = ratio.priority2[y2 + 1]; ratio.priority2[y2 + 1] = temp6; } } } junc_traffic.north_priority = ratio.priority2[0]; junc_traffic.east_priority = ratio.priority2[1]; junc_traffic.south_priority = ratio.priority2[2]; junc_traffic.west_priority = ratio.priority2[3]; for (i = 0; i < 4; i++) { if (ratio.priority1[i] == 1) { junc_traffic.north_green_time = green[0]; } else if (ratio.priority1[i] == 2) { junc_traffic.east_green_time = green[1]; } else if (ratio.priority1[i] == 3) { junc_traffic.south_green_time = green[2]; } else if (ratio.priority1[i] == 4) { junc_traffic.west_green_time = green[3]; } } return junc_traffic; } static int current_traffic_volume(int num_vechicle, int C) { int Q_RT; Q_RT = (num_vechicle * 3600) / C; return Q_RT; } static float flow_ratio(int Q_RT, int FS) { float ratio; ratio = Convert.ToSingle((float)Q_RT / (float)FS); return ratio; } static int effective_green_time(float flow_ratio, int C) { int VE; VE = Convert.ToInt32(Math.Round((flow_ratio * C))); return VE; } static int phase_green_time(int VE) { int V; int P = 2; int G = 2; V = VE + P - G; return V; } static int remaining_green_time(int VE, int V) { int Vres; Vres = VE - V; return Vres; } static int remaining_effective_green_time(int Vres, float flow_ratio_i, float flow_ratio_j, int n, float[] ratio) { int i; int VE_res; float flow_ratio_k = 0; for (i = n; i < 4; i++) { flow_ratio_k = (flow_ratio_k + ratio[i]); // Got problem!!!! } if (n == 2) { decimal temp_Vres = Math.Round(Convert.ToDecimal(Vres)); VE_res = Convert.ToInt32(temp_Vres); } else { VE_res = Convert.ToInt32(Math.Round(Vres * (flow_ratio_i / (flow_ratio_k - flow_ratio_j)))); } return VE_res; } static Ratio compare(Ratio ratio) { int i, n; float temp_value; int temp_priority; int[] temp_ratio_priority1 = new int[4]; int[] temp_ratio_priority2 = new int[4]; float[] temp_ratio_percentage_value = new float[4]; ratio.priority1[0] = 1; ratio.priority1[1] = 2; ratio.priority1[2] = 3; ratio.priority1[3] = 4; ratio.priority2[0] = 1; ratio.priority2[1] = 2; ratio.priority2[2] = 3; ratio.priority2[3] = 4; temp_ratio_priority2[0] = 1; temp_ratio_priority2[1] = 2; temp_ratio_priority2[2] = 3; temp_ratio_priority2[3] = 4; for (n = 0; n < 3; n++) { for (i = 0; i < 3; i++) { if (ratio.percentage_value[i] < ratio.percentage_value[i + 1]) { temp_value = ratio.percentage_value[i]; ratio.percentage_value[i] = ratio.percentage_value[i + 1]; ratio.percentage_value[i + 1] = temp_value; temp_priority = ratio.priority1[i]; ratio.priority1[i] = ratio.priority1[i + 1]; ratio.priority1[i + 1] = temp_priority; } } } return ratio; } private async static void SendCloudToDeviceMessageAsync(Junction junction) { var north_green_time = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.north_green_time))); north_green_time.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", north_green_time); var north_priority = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.north_priority))); north_priority.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", north_priority); var east_green_time = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.east_green_time))); east_green_time.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", east_green_time); var east_priority = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.east_priority))); east_priority.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", east_priority); var south_green_time = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.south_green_time))); south_green_time.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", south_green_time); var south_priority = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.south_priority))); south_priority.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", south_priority); var west_green_time = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.west_green_time))); west_green_time.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", west_green_time); var west_priority = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(Convert.ToString(junction.west_priority))); west_priority.Ack = DeliveryAcknowledgement.Full; await serviceClient.SendAsync("Lenovo01", west_priority); } } }
36.534722
210
0.506732
[ "MIT" ]
jerrychong25/TrafficLightSystem
MonitoringSoftware/1.0.5/InnovateTraffic/Form1.cs
63,134
C#
using System; using System.IO; using System.Runtime.Serialization; using NW.WIDJobs.Validation; namespace NW.WIDJobs.Files { /// <inheritdoc cref="IFileInfoAdapter"/> public class FileInfoAdapter : IFileInfoAdapter { #region Fields private FileInfo _fileInfo; #endregion #region Properties public bool IsReadOnly { get { return _fileInfo.IsReadOnly; } set { _fileInfo.IsReadOnly = value; } } public bool Exists { get { return _fileInfo.Exists; } } public string DirectoryName { get { return _fileInfo.DirectoryName; } } public DirectoryInfo Directory { get { return _fileInfo.Directory; } } public long Length { get { return _fileInfo.Length; } } public string Name { get { return _fileInfo.Name; } } public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { _fileInfo.LastWriteTime = value; } } public DateTime LastAccessTimeUtc { get { return _fileInfo.LastAccessTimeUtc; } set { _fileInfo.LastAccessTimeUtc = value; } } public DateTime LastAccessTime { get { return _fileInfo.LastAccessTime; } set { _fileInfo.LastAccessTime = value; } } public string FullName { get { return _fileInfo.FullName; } } public string Extension { get { return _fileInfo.Extension; } } public DateTime CreationTime { get { return _fileInfo.CreationTime; } set { _fileInfo.CreationTime = value; } } public DateTime LastWriteTimeUtc { get { return _fileInfo.LastWriteTimeUtc; } set { _fileInfo.LastWriteTimeUtc = value; } } public FileAttributes Attributes { get { return _fileInfo.Attributes; } set { _fileInfo.Attributes = value; } } public DateTime CreationTimeUtc { get { return _fileInfo.CreationTimeUtc; } set { _fileInfo.CreationTimeUtc = value; } } #endregion #region Constructors /// <summary>Initializes a <see cref="FileInfoAdapter"/> instance.</summary> /// <exception cref="ArgumentNullException"/> public FileInfoAdapter(FileInfo fileInfo) { Validator.ValidateObject(fileInfo, nameof(fileInfo)); _fileInfo = fileInfo; } /// <summary>Initializes a <see cref="FileInfoAdapter"/> instance.</summary> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentException"/> /// <exception cref="UnauthorizedAccessException"/> /// <exception cref="PathTooLongException"/> /// <exception cref="NotSupportedException"/> public FileInfoAdapter(string fileName) { _fileInfo = new FileInfo(fileName); } #endregion #region Methods_public public StreamWriter AppendText() => _fileInfo.AppendText(); public FileInfo CopyTo(string destFileName) => _fileInfo.CopyTo(destFileName); public FileInfo CopyTo(string destFileName, bool overwrite) => _fileInfo.CopyTo(destFileName, overwrite); public FileStream Create() => _fileInfo.Create(); public StreamWriter CreateText() => _fileInfo.CreateText(); public void Decrypt() => _fileInfo.Decrypt(); public void Delete() => _fileInfo.Delete(); public void Encrypt() => _fileInfo.Encrypt(); public void MoveTo(string destFileName) => _fileInfo.MoveTo(destFileName); public FileStream Open(FileMode mode, FileAccess access, FileShare share) => _fileInfo.Open(mode, access, share); public FileStream Open(FileMode mode, FileAccess access) => _fileInfo.Open(mode, access); public FileStream Open(FileMode mode) => _fileInfo.Open(mode); public FileStream OpenRead() => _fileInfo.OpenRead(); public StreamReader OpenText() => _fileInfo.OpenText(); public FileStream OpenWrite() => _fileInfo.OpenWrite(); public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) => _fileInfo.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors); public FileInfo Replace(string destinationFileName, string destinationBackupFileName) => _fileInfo.Replace(destinationFileName, destinationBackupFileName); public override string ToString() => _fileInfo.ToString(); public void GetObjectData(SerializationInfo info, StreamingContext context) => _fileInfo.GetObjectData(info, context); public void Refresh() => _fileInfo.Refresh(); #endregion } } /* Author: numbworks@gmail.com Last Update: 08.10.2021 */
31.252941
120
0.589497
[ "MIT" ]
numbworks/NW.WIDJobs
src/NW.WIDJobs/Files/FileInfoAdapter.cs
5,315
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.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Setup { internal class DifficultySection : SetupSection { private LabelledSliderBar<float> circleSizeSlider; private LabelledSliderBar<float> healthDrainSlider; private LabelledSliderBar<float> approachRateSlider; private LabelledSliderBar<float> overallDifficultySlider; public override LocalisableString Title => "Difficulty"; [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { circleSizeSlider = new LabelledSliderBar<float> { Label = "Object Size", Description = "The size of all hit objects", Current = new BindableFloat(Beatmap.BeatmapInfo.BaseDifficulty.CircleSize) { Default = BeatmapDifficulty.DEFAULT_DIFFICULTY, MinValue = 0, MaxValue = 10, Precision = 0.1f, } }, healthDrainSlider = new LabelledSliderBar<float> { Label = "Health Drain", Description = "The rate of passive health drain throughout playable time", Current = new BindableFloat(Beatmap.BeatmapInfo.BaseDifficulty.DrainRate) { Default = BeatmapDifficulty.DEFAULT_DIFFICULTY, MinValue = 0, MaxValue = 10, Precision = 0.1f, } }, approachRateSlider = new LabelledSliderBar<float> { Label = "Approach Rate", Description = "The speed at which objects are presented to the player", Current = new BindableFloat(Beatmap.BeatmapInfo.BaseDifficulty.ApproachRate) { Default = BeatmapDifficulty.DEFAULT_DIFFICULTY, MinValue = 0, MaxValue = 10, Precision = 0.1f, } }, overallDifficultySlider = new LabelledSliderBar<float> { Label = "Overall Difficulty", Description = "The harshness of hit windows and difficulty of special objects (ie. spinners)", Current = new BindableFloat(Beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty) { Default = BeatmapDifficulty.DEFAULT_DIFFICULTY, MinValue = 0, MaxValue = 10, Precision = 0.1f, } }, }; foreach (var item in Children.OfType<LabelledSliderBar<float>>()) item.Current.ValueChanged += onValueChanged; } private void onValueChanged(ValueChangedEvent<float> args) { // for now, update these on commit rather than making BeatmapMetadata bindables. // after switching database engines we can reconsider if switching to bindables is a good direction. Beatmap.BeatmapInfo.BaseDifficulty.CircleSize = circleSizeSlider.Current.Value; Beatmap.BeatmapInfo.BaseDifficulty.DrainRate = healthDrainSlider.Current.Value; Beatmap.BeatmapInfo.BaseDifficulty.ApproachRate = approachRateSlider.Current.Value; Beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty = overallDifficultySlider.Current.Value; Beatmap.UpdateAllHitObjects(); } } }
44.031579
115
0.548888
[ "MIT" ]
Aleeeesz/osu
osu.Game/Screens/Edit/Setup/DifficultySection.cs
4,089
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Singleton<T> : UnityEngine.MonoBehaviour where T:Singleton<T> { private static List<T> instances = new List<T>(); public static T Instance { get { for(var i= instances.Count-1; i>=0;i--) { if (instances[i] && instances[i].gameObject.scene != null) return instances[i]; } return null; } } public Singleton() : base() { instances.Add(this as T); } }
24.037037
75
0.531587
[ "MIT" ]
SardineFish/MAJIKA
Assets/Scripts/Utility/Singleton.cs
651
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RedisSet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedisSet")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("ea844151-c87a-4d5b-b1fa-1f73e0cdf3d6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.540541
84
0.743701
[ "MIT" ]
AbhishekHumagainOutcode/RedisForNetDevelopers
6.RedisSet/RedisSet/Properties/AssemblyInfo.cs
1,392
C#
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.Json.Schema.TestUtilities; using Microsoft.Json.Schema.ToDotNet.Hints; using Xunit; namespace Microsoft.Json.Schema.ToDotNet.UnitTests { public class DataModelGeneratorTests { private static readonly string PrimaryOutputFilePath = TestFileSystem.MakeOutputFilePath(TestSettings.RootClassName); private static readonly string PrimaryEqualityComparerOutputFilePath = TestFileSystem.MakeOutputFilePath(TestSettings.RootClassName + "EqualityComparer"); private static readonly string PrimaryComparerOutputFilePath = TestFileSystem.MakeOutputFilePath(TestSettings.RootClassName + "Comparer"); private static readonly string ComparerExtensionsOutputFilePath = TestFileSystem.MakeOutputFilePath("ComparerExtensions"); private static readonly string SyntaxInterfaceOutputFilePath = TestFileSystem.MakeOutputFilePath("ISNode"); private static readonly string KindEnumOutputFilePath = TestFileSystem.MakeOutputFilePath("SNodeKind"); private static readonly string RewritingVisitorOutputFilePath = TestFileSystem.MakeOutputFilePath("SRewritingVisitor"); private TestFileSystem _testFileSystem; private readonly DataModelGeneratorSettings _settings; public DataModelGeneratorTests() { _testFileSystem = new TestFileSystem(); _settings = TestSettings.MakeSettings(); } [Fact(DisplayName = "DataModelGenerator throws if output directory exists")] public void ThrowsIfOutputDirectoryExists() { _settings.ForceOverwrite = false; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(new JsonSchema()); // ... and the message should mention the output directory. action.Should().Throw<ApplicationException>().WithMessage($"*{TestFileSystem.OutputDirectory}*"); } [Fact(DisplayName = "DataModelGenerator does not throw if output directory does not exist")] public void DoesNotThrowIfOutputDirectoryDoesNotExist() { // Use a directory name other than the default. The mock file system believes // that only the default directory exists. _settings.OutputDirectory = _settings.OutputDirectory + "x"; JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Basic"); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(schema); action.Should().NotThrow(); } [Fact(DisplayName = "DataModelGenerator does not throw if ForceOverwrite setting is set")] public void DoesNotThowIfForceOverwriteSettingIsSet() { // This is the default from MakeSettings; restated here for explicitness. _settings.ForceOverwrite = true; JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Basic"); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(schema); action.Should().NotThrow(); } [Fact(DisplayName = "DataModelGenerator throws if root schema is not of type 'object'")] public void ThrowsIfRootSchemaIsNotOfTypeObject() { var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("NotAnObject"); Action action = () => generator.Generate(schema); // ... and the message should mention what the root type actually was. action.Should().Throw<ApplicationException>().WithMessage("*number*"); } [Fact(DisplayName = "DataModelGenerator generates class description")] public void GeneratesClassDescription() { const string Expected = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { /// <summary> /// The description /// </summary> [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { } }"; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Basic"); string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates properties with built-in types")] public void GeneratesPropertiesWithBuiltInTypes() { const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""stringProperty"", IsRequired = false, EmitDefaultValue = false)] public string StringProperty { get; set; } [DataMember(Name = ""numberProperty"", IsRequired = false, EmitDefaultValue = false)] public double NumberProperty { get; set; } [DataMember(Name = ""booleanProperty"", IsRequired = false, EmitDefaultValue = false)] public bool BooleanProperty { get; set; } [DataMember(Name = ""integerProperty"", IsRequired = false, EmitDefaultValue = false)] public int IntegerProperty { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.StringProperty != right.StringProperty) { return false; } if (left.NumberProperty != right.NumberProperty) { return false; } if (left.BooleanProperty != right.BooleanProperty) { return false; } if (left.IntegerProperty != right.IntegerProperty) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.StringProperty != null) { result = (result * 31) + obj.StringProperty.GetHashCode(); } result = (result * 31) + obj.NumberProperty.GetHashCode(); result = (result * 31) + obj.BooleanProperty.GetHashCode(); result = (result * 31) + obj.IntegerProperty.GetHashCode(); } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = string.Compare(left.StringProperty, right.StringProperty); if (compareResult != 0) { return compareResult; } compareResult = left.NumberProperty.CompareTo(right.NumberProperty); if (compareResult != 0) { return compareResult; } compareResult = left.BooleanProperty.CompareTo(right.BooleanProperty); if (compareResult != 0) { return compareResult; } compareResult = left.IntegerProperty.CompareTo(right.IntegerProperty); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Properties"); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates object-valued property with correct type")] public void GeneratesObjectValuedPropertyWithCorrectType() { const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""objectProp"", IsRequired = false, EmitDefaultValue = false)] public D ObjectProp { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!D.ValueComparer.Equals(left.ObjectProp, right.ObjectProp)) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ObjectProp != null) { result = (result * 31) + obj.ObjectProp.ValueGetHashCode(); } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = DComparer.Instance.Compare(left.ObjectProp, right.ObjectProp); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Object"); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass }, ["D"] = new ExpectedContents() }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator throws if reference is not a fragment")] public void ThrowsIfReferenceIsNotAFragment() { const string SchemaText = @" { ""type"": ""object"", ""properties"": { ""p"": { ""$ref"": ""https://example.com/pschema.schema.json/#"" } }, }"; JsonSchema schema = SchemaReader.ReadSchema(SchemaText, TestUtil.TestFilePath); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(schema); action.Should().Throw<ApplicationException>() .WithMessage("*https://example.com/pschema.schema.json/#*"); } [Fact(DisplayName = "DataModelGenerator throws if reference does not specify a definition")] public void ThrowsIfReferenceDoesNotSpecifyADefinition() { const string SchemaText = @" { ""type"": ""object"", ""properties"": { ""p"": { ""$ref"": ""#/notDefinitions/p"" } }, ""notDefinitions"": { ""p"": { } } }"; JsonSchema schema = SchemaReader.ReadSchema(SchemaText, TestUtil.TestFilePath); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(schema); action.Should().Throw<ApplicationException>() .WithMessage("*#/notDefinitions/p*"); } [Fact(DisplayName = "DataModelGenerator throws if referenced definition does not exist")] public void ThrowsIfReferencedDefinitionDoesNotExist() { const string SchemaText = @" { ""type"": ""object"", ""properties"": { ""p"": { ""$ref"": ""#/definitions/nonExistentDefinition"" } }, ""definitions"": { ""p"": { } } }"; JsonSchema schema = SchemaReader.ReadSchema(SchemaText, TestUtil.TestFilePath); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); Action action = () => generator.Generate(schema); action.Should().Throw<ApplicationException>() .WithMessage("*nonExistentDefinition*"); } [Fact(DisplayName = "DataModelGenerator generates array-valued properties")] public void GeneratesArrayValuedProperties() { const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""arrayProp"", IsRequired = false, EmitDefaultValue = false)] public IList<object> ArrayProp { get; set; } [DataMember(Name = ""arrayProp2"", IsRequired = false, EmitDefaultValue = false)] public IList<int> ArrayProp2 { get; set; } [DataMember(Name = ""arrayProp3"", IsRequired = false, EmitDefaultValue = false)] public IList<object> ArrayProp3 { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.ArrayProp, right.ArrayProp)) { if (left.ArrayProp == null || right.ArrayProp == null) { return false; } if (left.ArrayProp.Count != right.ArrayProp.Count) { return false; } for (int index_0 = 0; index_0 < left.ArrayProp.Count; ++index_0) { if (!object.Equals(left.ArrayProp[index_0], right.ArrayProp[index_0])) { return false; } } } if (!object.ReferenceEquals(left.ArrayProp2, right.ArrayProp2)) { if (left.ArrayProp2 == null || right.ArrayProp2 == null) { return false; } if (left.ArrayProp2.Count != right.ArrayProp2.Count) { return false; } for (int index_1 = 0; index_1 < left.ArrayProp2.Count; ++index_1) { if (left.ArrayProp2[index_1] != right.ArrayProp2[index_1]) { return false; } } } if (!object.ReferenceEquals(left.ArrayProp3, right.ArrayProp3)) { if (left.ArrayProp3 == null || right.ArrayProp3 == null) { return false; } if (left.ArrayProp3.Count != right.ArrayProp3.Count) { return false; } for (int index_2 = 0; index_2 < left.ArrayProp3.Count; ++index_2) { if (!object.Equals(left.ArrayProp3[index_2], right.ArrayProp3[index_2])) { return false; } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ArrayProp != null) { foreach (var value_0 in obj.ArrayProp) { result = result * 31; if (value_0 != null) { result = (result * 31) + value_0.GetHashCode(); } } } if (obj.ArrayProp2 != null) { foreach (var value_1 in obj.ArrayProp2) { result = result * 31; result = (result * 31) + value_1.GetHashCode(); } } if (obj.ArrayProp3 != null) { foreach (var value_2 in obj.ArrayProp3) { result = result * 31; if (value_2 != null) { result = (result * 31) + value_2.GetHashCode(); } } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.ArrayProp.ListCompares(right.ArrayProp, (a, b) => a.ObjectCompares(b)); if (compareResult != 0) { return compareResult; } compareResult = left.ArrayProp2.ListCompares(right.ArrayProp2); if (compareResult != 0) { return compareResult; } compareResult = left.ArrayProp3.ListCompares(right.ArrayProp3, (a, b) => a.ObjectCompares(b)); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Array"); string actual = generator.Generate(schema); TestUtil.WriteTestResultFiles(ExpectedClass, actual, nameof(GeneratesArrayValuedProperties)); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates XML comments for properties")] public void GeneratesXmlCommentsForProperties() { var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("PropertyDescription"); const string Expected = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { /// <summary> /// An example property. /// </summary> [DataMember(Name = ""exampleProp"", IsRequired = false, EmitDefaultValue = false)] public string ExampleProp { get; set; } } }"; string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates XML comments for properties whose property type is ref")] public void GeneratesXmlCommentsForPropertiesWhosePropertyTypeIsRef() { const string Schema = @"{ ""type"": ""object"", ""description"": ""Describes a console window."", ""properties"": { ""foregroundColor"": { ""$ref"": ""#/definitions/color"", ""description"": ""The color of the text on the screen."" }, ""backgroundColor"": { ""$ref"": ""#/definitions/color"", ""description"": ""The color of the screen background."" }, }, ""definitions"": { ""color"": { ""type"": ""object"", ""description"": ""Describes a color with R, G, and B components."", ""properties"": { ""red"": { ""type"": ""integer"", ""description"": ""The value of the R component."" }, ""green"": { ""type"": ""integer"", ""description"": ""The value of the G component."" }, ""blue"": { ""type"": ""integer"", ""description"": ""The value of the B component."" } } } } }"; const string ExpectedRootClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { /// <summary> /// Describes a console window. /// </summary> [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class ConsoleWindow { public static IEqualityComparer<ConsoleWindow> ValueComparer => ConsoleWindowEqualityComparer.Instance; public bool ValueEquals(ConsoleWindow other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<ConsoleWindow> Comparer => ConsoleWindowComparer.Instance; /// <summary> /// The color of the text on the screen. /// </summary> [DataMember(Name = ""foregroundColor"", IsRequired = false, EmitDefaultValue = false)] public Color ForegroundColor { get; set; } /// <summary> /// The color of the screen background. /// </summary> [DataMember(Name = ""backgroundColor"", IsRequired = false, EmitDefaultValue = false)] public Color BackgroundColor { get; set; } } }"; const string ExpectedRootEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type ConsoleWindow for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class ConsoleWindowEqualityComparer : IEqualityComparer<ConsoleWindow> { internal static readonly ConsoleWindowEqualityComparer Instance = new ConsoleWindowEqualityComparer(); public bool Equals(ConsoleWindow left, ConsoleWindow right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!Color.ValueComparer.Equals(left.ForegroundColor, right.ForegroundColor)) { return false; } if (!Color.ValueComparer.Equals(left.BackgroundColor, right.BackgroundColor)) { return false; } return true; } public int GetHashCode(ConsoleWindow obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ForegroundColor != null) { result = (result * 31) + obj.ForegroundColor.ValueGetHashCode(); } if (obj.BackgroundColor != null) { result = (result * 31) + obj.BackgroundColor.ValueGetHashCode(); } } return result; } } }"; const string ExpectedRootComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type ConsoleWindow for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class ConsoleWindowComparer : IComparer<ConsoleWindow> { internal static readonly ConsoleWindowComparer Instance = new ConsoleWindowComparer(); public int Compare(ConsoleWindow left, ConsoleWindow right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = ColorComparer.Instance.Compare(left.ForegroundColor, right.ForegroundColor); if (compareResult != 0) { return compareResult; } compareResult = ColorComparer.Instance.Compare(left.BackgroundColor, right.BackgroundColor); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; const string ExpectedColorClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { /// <summary> /// Describes a color with R, G, and B components. /// </summary> [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class Color { public static IEqualityComparer<Color> ValueComparer => ColorEqualityComparer.Instance; public bool ValueEquals(Color other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<Color> Comparer => ColorComparer.Instance; /// <summary> /// The value of the R component. /// </summary> [DataMember(Name = ""red"", IsRequired = false, EmitDefaultValue = false)] public int Red { get; set; } /// <summary> /// The value of the G component. /// </summary> [DataMember(Name = ""green"", IsRequired = false, EmitDefaultValue = false)] public int Green { get; set; } /// <summary> /// The value of the B component. /// </summary> [DataMember(Name = ""blue"", IsRequired = false, EmitDefaultValue = false)] public int Blue { get; set; } } }"; const string ExpectedColorEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Color for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class ColorEqualityComparer : IEqualityComparer<Color> { internal static readonly ColorEqualityComparer Instance = new ColorEqualityComparer(); public bool Equals(Color left, Color right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.Red != right.Red) { return false; } if (left.Green != right.Green) { return false; } if (left.Blue != right.Blue) { return false; } return true; } public int GetHashCode(Color obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { result = (result * 31) + obj.Red.GetHashCode(); result = (result * 31) + obj.Green.GetHashCode(); result = (result * 31) + obj.Blue.GetHashCode(); } return result; } } }"; const string ExpectedColorComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Color for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class ColorComparer : IComparer<Color> { internal static readonly ColorComparer Instance = new ColorComparer(); public int Compare(Color left, Color right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.Red.CompareTo(right.Red); if (compareResult != 0) { return compareResult; } compareResult = left.Green.CompareTo(right.Green); if (compareResult != 0) { return compareResult; } compareResult = left.Blue.CompareTo(right.Blue); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; _settings.RootClassName = "ConsoleWindow"; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedRootClass, EqualityComparerClassContents = ExpectedRootEqualityComparerClass, ComparerClassContents = ExpectedRootComparerClass }, ["Color"] = new ExpectedContents { ClassContents = ExpectedColorClass, EqualityComparerClassContents = ExpectedColorEqualityComparerClass, ComparerClassContents = ExpectedColorComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates copyright notice")] public void GeneratesCopyrightAtTopOfFile() { _settings.CopyrightNotice = @"// Copyright (c) 2016. All rights reserved. // Licensed under Apache 2.0 license. "; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("PropertyDescription"); const string Expected = @"// Copyright (c) 2016. All rights reserved. // Licensed under Apache 2.0 license. using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { /// <summary> /// An example property. /// </summary> [DataMember(Name = ""exampleProp"", IsRequired = false, EmitDefaultValue = false)] public string ExampleProp { get; set; } } }"; string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates cloning code")] public void GeneratesCloningCode() { JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""integerProperty"": { ""type"": ""integer"", ""description"": ""An integer property."" }, ""integerPropertyWithDefault"": { ""type"": ""integer"", ""description"": ""An integer property with a default value."", ""default"": 42 }, ""numberProperty"": { ""type"": ""number"", ""description"": ""A number property."" }, ""numberPropertyWithDefault"": { ""type"": ""number"", ""description"": ""A number property with a default value."", ""default"": 42.1 }, ""stringProperty"": { ""type"": ""string"", ""description"": ""A string property."" }, ""stringPropertyWithDefault"": { ""type"": ""string"", ""description"": ""A string property with a default value."", ""default"": ""Don't panic."" }, ""booleanProperty"": { ""type"": ""boolean"", ""description"": ""A Boolean property."" }, ""booleanPropertyWithTrueDefault"": { ""type"": ""boolean"", ""description"": ""A Boolean property with a true default value."", ""default"": true }, ""booleanPropertyWithFalseDefault"": { ""type"": ""boolean"", ""description"": ""A Boolean property with a false default value."", ""default"": false }, ""enumeratedPropertyWithDefault"": { ""description"": ""An enumerated property with a default value."", ""enum"": [ ""red"", ""green"", ""blue"", ""black"", ""white"" ], ""default"": ""green"" }, ""arrayProp"": { ""type"": ""array"", ""description"": ""An array property."", ""items"": { ""type"": ""number"" } }, ""uriProp"": { ""type"": ""string"", ""description"": ""A Uri property."", ""format"": ""uri"" }, ""dateTimeProp"": { ""type"": ""string"", ""description"": ""A DateTime property."", ""format"": ""date-time"" }, ""referencedTypeProp"": { ""$ref"": ""#/definitions/d"" }, ""arrayOfRefProp"": { ""type"": ""array"", ""description"": ""An array of a cloneable type."", ""items"": { ""$ref"": ""#/definitions/d"" } }, ""arrayOfArrayProp"": { ""type"": ""array"", ""description"": ""An array of arrays."", ""items"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/d"" } } }, ""dictionaryProp"": { ""description"": ""A dictionary property."", ""type"": ""object"" }, ""dictionaryWithPrimitiveSchemaProp"": { ""description"": ""A dictionary property whose values are defined by a primitive additionalProperties schema."", ""type"": ""object"", ""additionalProperties"": { ""type"": ""number"" } }, ""dictionaryWithObjectSchemaProp"": { ""description"": ""A dictionary property whose values are defined by an object-valued additionalProperties schema."", ""type"": ""object"", ""additionalProperties"": { ""$ref"": ""#/definitions/d"" } }, ""dictionaryWithObjectArraySchemaProp"": { ""description"": ""A dictionary property whose values are defined by an array-of-object-valued additionalProperties schema."", ""type"": ""object"", ""additionalProperties"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/d"" } } }, ""dictionaryWithUriKeyProp"": { ""description"": ""A dictionary property whose keys are Uris."", ""type"": ""object"", ""additionalProperties"": { ""$ref"": ""#/definitions/d"" } }, ""dictionaryWithHintedValueProp"": { ""description"": ""A dictionary property whose value type is hinted."", ""type"": ""object"" } }, ""definitions"": { ""d"": { ""type"": ""object"" } } }", TestUtil.TestFilePath); const string HintsText = @"{ ""C.EnumeratedPropertyWithDefault"": [ { ""kind"": ""EnumHint"", ""arguments"": { ""typeName"": ""Color"", ""description"": ""Some colors."" } } ], ""C.DictionaryProp"": [ { ""kind"": ""DictionaryHint"" } ], ""C.DictionaryWithPrimitiveSchemaProp"": [ { ""kind"": ""DictionaryHint"" } ], ""C.DictionaryWithObjectSchemaProp"": [ { ""kind"": ""DictionaryHint"" } ], ""C.DictionaryWithObjectArraySchemaProp"": [ { ""kind"": ""DictionaryHint"" } ], ""C.DictionaryWithUriKeyProp"": [ { ""kind"": ""DictionaryHint"", ""arguments"": { ""keyTypeName"": ""Uri"" } } ], ""C.DictionaryWithHintedValueProp"": [ { ""kind"": ""DictionaryHint"", ""arguments"": { ""valueTypeName"": ""V"", ""comparisonKind"": ""ObjectEquals"", ""hashKind"": ""ScalarReferenceType"", ""initializationKind"": ""SimpleAssign"" } } ] }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Newtonsoft.Json; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C : ISNode { /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> public SNodeKind SNodeKind { get { return SNodeKind.C; } } /// <summary> /// An integer property. /// </summary> [DataMember(Name = ""integerProperty"", IsRequired = false, EmitDefaultValue = false)] public int IntegerProperty { get; set; } /// <summary> /// An integer property with a default value. /// </summary> [DataMember(Name = ""integerPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(42)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public int IntegerPropertyWithDefault { get; set; } /// <summary> /// A number property. /// </summary> [DataMember(Name = ""numberProperty"", IsRequired = false, EmitDefaultValue = false)] public double NumberProperty { get; set; } /// <summary> /// A number property with a default value. /// </summary> [DataMember(Name = ""numberPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(42.1)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public double NumberPropertyWithDefault { get; set; } /// <summary> /// A string property. /// </summary> [DataMember(Name = ""stringProperty"", IsRequired = false, EmitDefaultValue = false)] public string StringProperty { get; set; } /// <summary> /// A string property with a default value. /// </summary> [DataMember(Name = ""stringPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(""Don't panic."")] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public string StringPropertyWithDefault { get; set; } /// <summary> /// A Boolean property. /// </summary> [DataMember(Name = ""booleanProperty"", IsRequired = false, EmitDefaultValue = false)] public bool BooleanProperty { get; set; } /// <summary> /// A Boolean property with a true default value. /// </summary> [DataMember(Name = ""booleanPropertyWithTrueDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(true)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public bool BooleanPropertyWithTrueDefault { get; set; } /// <summary> /// A Boolean property with a false default value. /// </summary> [DataMember(Name = ""booleanPropertyWithFalseDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public bool BooleanPropertyWithFalseDefault { get; set; } /// <summary> /// An enumerated property with a default value. /// </summary> [DataMember(Name = ""enumeratedPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(Color.Green)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public Color EnumeratedPropertyWithDefault { get; set; } /// <summary> /// An array property. /// </summary> [DataMember(Name = ""arrayProp"", IsRequired = false, EmitDefaultValue = false)] public IList<double> ArrayProp { get; set; } /// <summary> /// A Uri property. /// </summary> [DataMember(Name = ""uriProp"", IsRequired = false, EmitDefaultValue = false)] public Uri UriProp { get; set; } /// <summary> /// A DateTime property. /// </summary> [DataMember(Name = ""dateTimeProp"", IsRequired = false, EmitDefaultValue = false)] public DateTime DateTimeProp { get; set; } [DataMember(Name = ""referencedTypeProp"", IsRequired = false, EmitDefaultValue = false)] public D ReferencedTypeProp { get; set; } /// <summary> /// An array of a cloneable type. /// </summary> [DataMember(Name = ""arrayOfRefProp"", IsRequired = false, EmitDefaultValue = false)] public IList<D> ArrayOfRefProp { get; set; } /// <summary> /// An array of arrays. /// </summary> [DataMember(Name = ""arrayOfArrayProp"", IsRequired = false, EmitDefaultValue = false)] public IList<IList<D>> ArrayOfArrayProp { get; set; } /// <summary> /// A dictionary property. /// </summary> [DataMember(Name = ""dictionaryProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, string> DictionaryProp { get; set; } /// <summary> /// A dictionary property whose values are defined by a primitive additionalProperties schema. /// </summary> [DataMember(Name = ""dictionaryWithPrimitiveSchemaProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, double> DictionaryWithPrimitiveSchemaProp { get; set; } /// <summary> /// A dictionary property whose values are defined by an object-valued additionalProperties schema. /// </summary> [DataMember(Name = ""dictionaryWithObjectSchemaProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, D> DictionaryWithObjectSchemaProp { get; set; } /// <summary> /// A dictionary property whose values are defined by an array-of-object-valued additionalProperties schema. /// </summary> [DataMember(Name = ""dictionaryWithObjectArraySchemaProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, IList<D>> DictionaryWithObjectArraySchemaProp { get; set; } /// <summary> /// A dictionary property whose keys are Uris. /// </summary> [DataMember(Name = ""dictionaryWithUriKeyProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<Uri, D> DictionaryWithUriKeyProp { get; set; } /// <summary> /// A dictionary property whose value type is hinted. /// </summary> [DataMember(Name = ""dictionaryWithHintedValueProp"", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, V> DictionaryWithHintedValueProp { get; set; } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class. /// </summary> public C() { IntegerPropertyWithDefault = 42; NumberPropertyWithDefault = 42.1; StringPropertyWithDefault = ""Don't panic.""; BooleanPropertyWithTrueDefault = true; BooleanPropertyWithFalseDefault = false; EnumeratedPropertyWithDefault = Color.Green; } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the supplied values. /// </summary> /// <param name=""integerProperty""> /// An initialization value for the <see cref=""P:IntegerProperty"" /> property. /// </param> /// <param name=""integerPropertyWithDefault""> /// An initialization value for the <see cref=""P:IntegerPropertyWithDefault"" /> property. /// </param> /// <param name=""numberProperty""> /// An initialization value for the <see cref=""P:NumberProperty"" /> property. /// </param> /// <param name=""numberPropertyWithDefault""> /// An initialization value for the <see cref=""P:NumberPropertyWithDefault"" /> property. /// </param> /// <param name=""stringProperty""> /// An initialization value for the <see cref=""P:StringProperty"" /> property. /// </param> /// <param name=""stringPropertyWithDefault""> /// An initialization value for the <see cref=""P:StringPropertyWithDefault"" /> property. /// </param> /// <param name=""booleanProperty""> /// An initialization value for the <see cref=""P:BooleanProperty"" /> property. /// </param> /// <param name=""booleanPropertyWithTrueDefault""> /// An initialization value for the <see cref=""P:BooleanPropertyWithTrueDefault"" /> property. /// </param> /// <param name=""booleanPropertyWithFalseDefault""> /// An initialization value for the <see cref=""P:BooleanPropertyWithFalseDefault"" /> property. /// </param> /// <param name=""enumeratedPropertyWithDefault""> /// An initialization value for the <see cref=""P:EnumeratedPropertyWithDefault"" /> property. /// </param> /// <param name=""arrayProp""> /// An initialization value for the <see cref=""P:ArrayProp"" /> property. /// </param> /// <param name=""uriProp""> /// An initialization value for the <see cref=""P:UriProp"" /> property. /// </param> /// <param name=""dateTimeProp""> /// An initialization value for the <see cref=""P:DateTimeProp"" /> property. /// </param> /// <param name=""referencedTypeProp""> /// An initialization value for the <see cref=""P:ReferencedTypeProp"" /> property. /// </param> /// <param name=""arrayOfRefProp""> /// An initialization value for the <see cref=""P:ArrayOfRefProp"" /> property. /// </param> /// <param name=""arrayOfArrayProp""> /// An initialization value for the <see cref=""P:ArrayOfArrayProp"" /> property. /// </param> /// <param name=""dictionaryProp""> /// An initialization value for the <see cref=""P:DictionaryProp"" /> property. /// </param> /// <param name=""dictionaryWithPrimitiveSchemaProp""> /// An initialization value for the <see cref=""P:DictionaryWithPrimitiveSchemaProp"" /> property. /// </param> /// <param name=""dictionaryWithObjectSchemaProp""> /// An initialization value for the <see cref=""P:DictionaryWithObjectSchemaProp"" /> property. /// </param> /// <param name=""dictionaryWithObjectArraySchemaProp""> /// An initialization value for the <see cref=""P:DictionaryWithObjectArraySchemaProp"" /> property. /// </param> /// <param name=""dictionaryWithUriKeyProp""> /// An initialization value for the <see cref=""P:DictionaryWithUriKeyProp"" /> property. /// </param> /// <param name=""dictionaryWithHintedValueProp""> /// An initialization value for the <see cref=""P:DictionaryWithHintedValueProp"" /> property. /// </param> public C(int integerProperty, int integerPropertyWithDefault, double numberProperty, double numberPropertyWithDefault, string stringProperty, string stringPropertyWithDefault, bool booleanProperty, bool booleanPropertyWithTrueDefault, bool booleanPropertyWithFalseDefault, Color enumeratedPropertyWithDefault, IEnumerable<double> arrayProp, Uri uriProp, DateTime dateTimeProp, D referencedTypeProp, IEnumerable<D> arrayOfRefProp, IEnumerable<IEnumerable<D>> arrayOfArrayProp, IDictionary<string, string> dictionaryProp, IDictionary<string, double> dictionaryWithPrimitiveSchemaProp, IDictionary<string, D> dictionaryWithObjectSchemaProp, IDictionary<string, IList<D>> dictionaryWithObjectArraySchemaProp, IDictionary<Uri, D> dictionaryWithUriKeyProp, IDictionary<string, V> dictionaryWithHintedValueProp) { Init(integerProperty, integerPropertyWithDefault, numberProperty, numberPropertyWithDefault, stringProperty, stringPropertyWithDefault, booleanProperty, booleanPropertyWithTrueDefault, booleanPropertyWithFalseDefault, enumeratedPropertyWithDefault, arrayProp, uriProp, dateTimeProp, referencedTypeProp, arrayOfRefProp, arrayOfArrayProp, dictionaryProp, dictionaryWithPrimitiveSchemaProp, dictionaryWithObjectSchemaProp, dictionaryWithObjectArraySchemaProp, dictionaryWithUriKeyProp, dictionaryWithHintedValueProp); } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the specified instance. /// </summary> /// <param name=""other""> /// The instance from which the new instance is to be initialized. /// </param> /// <exception cref=""ArgumentNullException""> /// Thrown if <paramref name=""other"" /> is null. /// </exception> public C(C other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } Init(other.IntegerProperty, other.IntegerPropertyWithDefault, other.NumberProperty, other.NumberPropertyWithDefault, other.StringProperty, other.StringPropertyWithDefault, other.BooleanProperty, other.BooleanPropertyWithTrueDefault, other.BooleanPropertyWithFalseDefault, other.EnumeratedPropertyWithDefault, other.ArrayProp, other.UriProp, other.DateTimeProp, other.ReferencedTypeProp, other.ArrayOfRefProp, other.ArrayOfArrayProp, other.DictionaryProp, other.DictionaryWithPrimitiveSchemaProp, other.DictionaryWithObjectSchemaProp, other.DictionaryWithObjectArraySchemaProp, other.DictionaryWithUriKeyProp, other.DictionaryWithHintedValueProp); } ISNode ISNode.DeepClone() { return DeepCloneCore(); } /// <summary> /// Creates a deep copy of this instance. /// </summary> public C DeepClone() { return (C)DeepCloneCore(); } private ISNode DeepCloneCore() { return new C(this); } private void Init(int integerProperty, int integerPropertyWithDefault, double numberProperty, double numberPropertyWithDefault, string stringProperty, string stringPropertyWithDefault, bool booleanProperty, bool booleanPropertyWithTrueDefault, bool booleanPropertyWithFalseDefault, Color enumeratedPropertyWithDefault, IEnumerable<double> arrayProp, Uri uriProp, DateTime dateTimeProp, D referencedTypeProp, IEnumerable<D> arrayOfRefProp, IEnumerable<IEnumerable<D>> arrayOfArrayProp, IDictionary<string, string> dictionaryProp, IDictionary<string, double> dictionaryWithPrimitiveSchemaProp, IDictionary<string, D> dictionaryWithObjectSchemaProp, IDictionary<string, IList<D>> dictionaryWithObjectArraySchemaProp, IDictionary<Uri, D> dictionaryWithUriKeyProp, IDictionary<string, V> dictionaryWithHintedValueProp) { IntegerProperty = integerProperty; IntegerPropertyWithDefault = integerPropertyWithDefault; NumberProperty = numberProperty; NumberPropertyWithDefault = numberPropertyWithDefault; StringProperty = stringProperty; StringPropertyWithDefault = stringPropertyWithDefault; BooleanProperty = booleanProperty; BooleanPropertyWithTrueDefault = booleanPropertyWithTrueDefault; BooleanPropertyWithFalseDefault = booleanPropertyWithFalseDefault; EnumeratedPropertyWithDefault = enumeratedPropertyWithDefault; if (arrayProp != null) { var destination_0 = new List<double>(); foreach (var value_0 in arrayProp) { destination_0.Add(value_0); } ArrayProp = destination_0; } if (uriProp != null) { UriProp = new Uri(uriProp.OriginalString, uriProp.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative); } DateTimeProp = dateTimeProp; if (referencedTypeProp != null) { ReferencedTypeProp = new D(referencedTypeProp); } if (arrayOfRefProp != null) { var destination_1 = new List<D>(); foreach (var value_1 in arrayOfRefProp) { if (value_1 == null) { destination_1.Add(null); } else { destination_1.Add(new D(value_1)); } } ArrayOfRefProp = destination_1; } if (arrayOfArrayProp != null) { var destination_2 = new List<IList<D>>(); foreach (var value_2 in arrayOfArrayProp) { if (value_2 == null) { destination_2.Add(null); } else { var destination_3 = new List<D>(); foreach (var value_3 in value_2) { if (value_3 == null) { destination_3.Add(null); } else { destination_3.Add(new D(value_3)); } } destination_2.Add(destination_3); } } ArrayOfArrayProp = destination_2; } if (dictionaryProp != null) { DictionaryProp = new Dictionary<string, string>(dictionaryProp); } if (dictionaryWithPrimitiveSchemaProp != null) { DictionaryWithPrimitiveSchemaProp = new Dictionary<string, double>(dictionaryWithPrimitiveSchemaProp); } if (dictionaryWithObjectSchemaProp != null) { DictionaryWithObjectSchemaProp = new Dictionary<string, D>(); foreach (var value_4 in dictionaryWithObjectSchemaProp) { DictionaryWithObjectSchemaProp.Add(value_4.Key, new D(value_4.Value)); } } if (dictionaryWithObjectArraySchemaProp != null) { DictionaryWithObjectArraySchemaProp = new Dictionary<string, IList<D>>(); foreach (var value_5 in dictionaryWithObjectArraySchemaProp) { var destination_4 = new List<D>(); foreach (var value_6 in value_5.Value) { if (value_6 == null) { destination_4.Add(null); } else { destination_4.Add(new D(value_6)); } } DictionaryWithObjectArraySchemaProp.Add(value_5.Key, destination_4); } } if (dictionaryWithUriKeyProp != null) { DictionaryWithUriKeyProp = new Dictionary<Uri, D>(); foreach (var value_7 in dictionaryWithUriKeyProp) { DictionaryWithUriKeyProp.Add(value_7.Key, new D(value_7.Value)); } } if (dictionaryWithHintedValueProp != null) { DictionaryWithHintedValueProp = new Dictionary<string, V>(dictionaryWithHintedValueProp); } } } }"; const string ExpectedSyntaxInterface = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// An interface for all types generated from the S schema. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public interface ISNode { /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> SNodeKind SNodeKind { get; } /// <summary> /// Makes a deep copy of this instance. /// </summary> ISNode DeepClone(); } }"; const string ExpectedKindEnum = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// A set of values for all the types that implement <see cref=""ISNode"" />. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public enum SNodeKind { /// <summary> /// An uninitialized kind. /// </summary> None, /// <summary> /// A value indicating that the <see cref=""ISNode"" /> object is of type <see cref=""C"" />. /// </summary> C, /// <summary> /// A value indicating that the <see cref=""ISNode"" /> object is of type <see cref=""D"" />. /// </summary> D } }"; const string ExpectedRewritingVisitor = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; namespace N { /// <summary> /// Rewriting visitor for the S object model. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public abstract class SRewritingVisitor { /// <summary> /// Starts a rewriting visit of a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object Visit(ISNode node) { return this.VisitActual(node); } /// <summary> /// Visits and rewrites a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object VisitActual(ISNode node) { if (node == null) { throw new ArgumentNullException(""node""); } switch (node.SNodeKind) { case SNodeKind.C: return VisitC((C)node); case SNodeKind.D: return VisitD((D)node); default: return node; } } private T VisitNullChecked<T>(T node) where T : class, ISNode { if (node == null) { return null; } return (T)Visit(node); } public virtual C VisitC(C node) { if (node != null) { node.ReferencedTypeProp = VisitNullChecked(node.ReferencedTypeProp); if (node.ArrayOfRefProp != null) { for (int index_0 = 0; index_0 < node.ArrayOfRefProp.Count; ++index_0) { node.ArrayOfRefProp[index_0] = VisitNullChecked(node.ArrayOfRefProp[index_0]); } } if (node.ArrayOfArrayProp != null) { for (int index_0 = 0; index_0 < node.ArrayOfArrayProp.Count; ++index_0) { var value_0 = node.ArrayOfArrayProp[index_0]; if (value_0 != null) { for (int index_1 = 0; index_1 < value_0.Count; ++index_1) { value_0[index_1] = VisitNullChecked(value_0[index_1]); } } } } if (node.DictionaryWithObjectSchemaProp != null) { var keys = node.DictionaryWithObjectSchemaProp.Keys.ToArray(); foreach (var key in keys) { var value = node.DictionaryWithObjectSchemaProp[key]; if (value != null) { node.DictionaryWithObjectSchemaProp[key] = VisitNullChecked(value); } } } if (node.DictionaryWithObjectArraySchemaProp != null) { var keys = node.DictionaryWithObjectArraySchemaProp.Keys.ToArray(); foreach (var key in keys) { var value = node.DictionaryWithObjectArraySchemaProp[key]; if (value != null) { for (int index_0 = 0; index_0 < node.DictionaryWithObjectArraySchemaProp[key].Count; ++index_0) { node.DictionaryWithObjectArraySchemaProp[key][index_0] = VisitNullChecked(node.DictionaryWithObjectArraySchemaProp[key][index_0]); } } } } if (node.DictionaryWithUriKeyProp != null) { var keys = node.DictionaryWithUriKeyProp.Keys.ToArray(); foreach (var key in keys) { var value = node.DictionaryWithUriKeyProp[key]; if (value != null) { node.DictionaryWithUriKeyProp[key] = VisitNullChecked(value); } } } } return node; } public virtual D VisitD(D node) { if (node != null) { } return node; } } }"; const string ExpectedEnumType = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// Some colors. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """+ VersionConstants.FileVersion + @""")] public enum Color { Red, Green, Blue, Black, White } }"; _settings.GenerateCloningCode = true; _settings.HintDictionary = new HintDictionary(HintsText); var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); generator.Generate(schema); string referencedTypePath = TestFileSystem.MakeOutputFilePath("D"); string enumTypePath = TestFileSystem.MakeOutputFilePath("Color"); var expectedOutputFiles = new List<string> { PrimaryOutputFilePath, SyntaxInterfaceOutputFilePath, KindEnumOutputFilePath, RewritingVisitorOutputFilePath, referencedTypePath, enumTypePath }; _testFileSystem.Files.Count.Should().Be(expectedOutputFiles.Count); _testFileSystem.Files.Should().OnlyContain(path => expectedOutputFiles.Contains(path)); _testFileSystem[enumTypePath].Should().Be(ExpectedEnumType); _testFileSystem[PrimaryOutputFilePath].Should().Be(ExpectedClass); _testFileSystem[SyntaxInterfaceOutputFilePath].Should().Be(ExpectedSyntaxInterface); _testFileSystem[KindEnumOutputFilePath].Should().Be(ExpectedKindEnum); _testFileSystem[RewritingVisitorOutputFilePath].Should().Be(ExpectedRewritingVisitor); } [Fact(DisplayName = "DataModelGenerator generates classes for schemas in definitions")] public void GeneratesClassesForSchemasInDefinitions() { const string ExpectedRootClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""rootProp"", IsRequired = false, EmitDefaultValue = false)] public bool RootProp { get; set; } } }"; const string ExpectedRootEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.RootProp != right.RootProp) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { result = (result * 31) + obj.RootProp.GetHashCode(); } return result; } } }"; const string ExpectedRootComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.RootProp.CompareTo(right.RootProp); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; const string ExpectedDefinedClass1 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class Def1 { public static IEqualityComparer<Def1> ValueComparer => Def1EqualityComparer.Instance; public bool ValueEquals(Def1 other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<Def1> Comparer => Def1Comparer.Instance; [DataMember(Name = ""prop1"", IsRequired = false, EmitDefaultValue = false)] public string Prop1 { get; set; } } }"; const string ExpectedEqualityComparerClass1 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Def1 for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class Def1EqualityComparer : IEqualityComparer<Def1> { internal static readonly Def1EqualityComparer Instance = new Def1EqualityComparer(); public bool Equals(Def1 left, Def1 right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.Prop1 != right.Prop1) { return false; } return true; } public int GetHashCode(Def1 obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.Prop1 != null) { result = (result * 31) + obj.Prop1.GetHashCode(); } } return result; } } }"; const string ExpectedComparerClass1 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Def1 for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class Def1Comparer : IComparer<Def1> { internal static readonly Def1Comparer Instance = new Def1Comparer(); public int Compare(Def1 left, Def1 right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = string.Compare(left.Prop1, right.Prop1); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; const string ExpectedDefinedClass2 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class Def2 { public static IEqualityComparer<Def2> ValueComparer => Def2EqualityComparer.Instance; public bool ValueEquals(Def2 other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<Def2> Comparer => Def2Comparer.Instance; [DataMember(Name = ""prop2"", IsRequired = false, EmitDefaultValue = false)] public int Prop2 { get; set; } } }"; const string ExpectedEqualityComparerClass2 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Def2 for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class Def2EqualityComparer : IEqualityComparer<Def2> { internal static readonly Def2EqualityComparer Instance = new Def2EqualityComparer(); public bool Equals(Def2 left, Def2 right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.Prop2 != right.Prop2) { return false; } return true; } public int GetHashCode(Def2 obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { result = (result * 31) + obj.Prop2.GetHashCode(); } return result; } } }"; const string ExpectedComparerClass2 = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type Def2 for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class Def2Comparer : IComparer<Def2> { internal static readonly Def2Comparer Instance = new Def2Comparer(); public int Compare(Def2 left, Def2 right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.Prop2.CompareTo(right.Prop2); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = TestUtil.CreateSchemaFromTestDataFile("Definitions"); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedRootClass, EqualityComparerClassContents = ExpectedRootEqualityComparerClass, ComparerClassContents = ExpectedRootComparerClass }, ["Def1"] = new ExpectedContents { ClassContents = ExpectedDefinedClass1, EqualityComparerClassContents = ExpectedEqualityComparerClass1, ComparerClassContents = ExpectedComparerClass1 }, ["Def2"] = new ExpectedContents { ClassContents = ExpectedDefinedClass2, EqualityComparerClassContents = ExpectedEqualityComparerClass2, ComparerClassContents = ExpectedComparerClass2 } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates date-time-valued properties")] public void GeneratesDateTimeValuedProperties() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""startTime"": { ""type"": ""string"", ""format"": ""date-time"" } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""startTime"", IsRequired = false, EmitDefaultValue = false)] public DateTime StartTime { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.StartTime != right.StartTime) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { result = (result * 31) + obj.StartTime.GetHashCode(); } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.StartTime.CompareTo(right.StartTime); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates URI-valued properties from uri format")] public void GeneratesUriValuedPropertiesFromUriFormat() { string Schema = @"{ ""type"": ""object"", ""properties"": { ""targetFile"": { ""type"": ""string"", ""format"": ""uri"" } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""targetFile"", IsRequired = false, EmitDefaultValue = false)] public Uri TargetFile { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.TargetFile != right.TargetFile) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.TargetFile != null) { result = (result * 31) + obj.TargetFile.GetHashCode(); } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.TargetFile.UriCompares(right.TargetFile); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates URI-valued properties from uri-reference format")] public void GeneratesUriValuedPropertiesFromUriReferenceFormat() { string Schema = @"{ ""type"": ""object"", ""properties"": { ""targetFile"": { ""type"": ""string"", ""format"": ""uri-reference"" } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""targetFile"", IsRequired = false, EmitDefaultValue = false)] public Uri TargetFile { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.TargetFile != right.TargetFile) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.TargetFile != null) { result = (result * 31) + obj.TargetFile.GetHashCode(); } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.TargetFile.UriCompares(right.TargetFile); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates integer property from reference")] public void GeneratesIntegerPropertyFromReference() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""intDefProp"": { ""$ref"": ""#/definitions/d"" } }, ""definitions"": { ""d"": { ""type"": ""integer"" } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""intDefProp"", IsRequired = false, EmitDefaultValue = false)] public int IntDefProp { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.IntDefProp != right.IntDefProp) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { result = (result * 31) + obj.IntDefProp.GetHashCode(); } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.IntDefProp.CompareTo(right.IntDefProp); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass }, ["D"] = new ExpectedContents() }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates attributes for properties of primitive type with defaults.")] public void GeneratesAttributesForPropertiesOfPrimitiveTypeWithDefaults() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""integerProperty"": { ""type"": ""integer"", ""description"": ""An integer property."" }, ""integerPropertyWithDefault"": { ""type"": ""integer"", ""description"": ""An integer property with a default value."", ""default"": 42 }, ""numberProperty"": { ""type"": ""number"", ""description"": ""A number property."" }, ""numberPropertyWithDefault"": { ""type"": ""number"", ""description"": ""A number property with a default value."", ""default"": 42.1 }, ""stringProperty"": { ""type"": ""string"", ""description"": ""A string property."" }, ""stringPropertyWithDefault"": { ""type"": ""string"", ""description"": ""A string property with a default value."", ""default"": ""Thanks for all the fish."" }, ""booleanProperty"": { ""type"": ""boolean"", ""description"": ""A Boolean property."" }, ""booleanPropertyWithTrueDefault"": { ""type"": ""boolean"", ""description"": ""A Boolean property with a true default value."", ""default"": true }, ""booleanPropertyWithFalseDefault"": { ""type"": ""boolean"", ""description"": ""A Boolean property with a false default value."", ""default"": false }, ""nonPrimitivePropertyWithDefault"": { ""type"": ""array"", ""description"": ""A non-primitive property with a default value: DefaultValue attribute will -not- be emitted."", ""items"": { ""type"": ""integer"" }, ""default"": [] } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Newtonsoft.Json; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { /// <summary> /// An integer property. /// </summary> [DataMember(Name = ""integerProperty"", IsRequired = false, EmitDefaultValue = false)] public int IntegerProperty { get; set; } /// <summary> /// An integer property with a default value. /// </summary> [DataMember(Name = ""integerPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(42)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public int IntegerPropertyWithDefault { get; set; } /// <summary> /// A number property. /// </summary> [DataMember(Name = ""numberProperty"", IsRequired = false, EmitDefaultValue = false)] public double NumberProperty { get; set; } /// <summary> /// A number property with a default value. /// </summary> [DataMember(Name = ""numberPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(42.1)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public double NumberPropertyWithDefault { get; set; } /// <summary> /// A string property. /// </summary> [DataMember(Name = ""stringProperty"", IsRequired = false, EmitDefaultValue = false)] public string StringProperty { get; set; } /// <summary> /// A string property with a default value. /// </summary> [DataMember(Name = ""stringPropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(""Thanks for all the fish."")] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public string StringPropertyWithDefault { get; set; } /// <summary> /// A Boolean property. /// </summary> [DataMember(Name = ""booleanProperty"", IsRequired = false, EmitDefaultValue = false)] public bool BooleanProperty { get; set; } /// <summary> /// A Boolean property with a true default value. /// </summary> [DataMember(Name = ""booleanPropertyWithTrueDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(true)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public bool BooleanPropertyWithTrueDefault { get; set; } /// <summary> /// A Boolean property with a false default value. /// </summary> [DataMember(Name = ""booleanPropertyWithFalseDefault"", IsRequired = false, EmitDefaultValue = false)] [DefaultValue(false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public bool BooleanPropertyWithFalseDefault { get; set; } /// <summary> /// A non-primitive property with a default value: DefaultValue attribute will -not- be emitted. /// </summary> [DataMember(Name = ""nonPrimitivePropertyWithDefault"", IsRequired = false, EmitDefaultValue = false)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] public IList<int> NonPrimitivePropertyWithDefault { get; set; } } }"; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates array of primitive types by $ref")] public void GeneratesArrayOfPrimitiveTypeByReference() { _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""arrayOfIntByRef"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/d"" } } }, ""definitions"": { ""d"": { ""type"": ""integer"", } } } }", TestUtil.TestFilePath); const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""arrayOfIntByRef"", IsRequired = false, EmitDefaultValue = false)] public IList<int> ArrayOfIntByRef { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.ArrayOfIntByRef, right.ArrayOfIntByRef)) { if (left.ArrayOfIntByRef == null || right.ArrayOfIntByRef == null) { return false; } if (left.ArrayOfIntByRef.Count != right.ArrayOfIntByRef.Count) { return false; } for (int index_0 = 0; index_0 < left.ArrayOfIntByRef.Count; ++index_0) { if (left.ArrayOfIntByRef[index_0] != right.ArrayOfIntByRef[index_0]) { return false; } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ArrayOfIntByRef != null) { foreach (var value_0 in obj.ArrayOfIntByRef) { result = result * 31; result = (result * 31) + value_0.GetHashCode(); } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.ArrayOfIntByRef.ListCompares(right.ArrayOfIntByRef); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; string actual = generator.Generate(schema); TestUtil.WriteTestResultFiles(ExpectedClass, actual, nameof(GeneratesArrayOfPrimitiveTypeByReference)); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass, }, ["D"] = new ExpectedContents() }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates array of uri-formatted strings")] public void GeneratesArrayOfUriFormattedStrings() { JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""uriFormattedStrings"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""uri"" } } } }", TestUtil.TestFilePath); const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C : ISNode { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> public SNodeKind SNodeKind { get { return SNodeKind.C; } } [DataMember(Name = ""uriFormattedStrings"", IsRequired = false, EmitDefaultValue = false)] public IList<Uri> UriFormattedStrings { get; set; } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class. /// </summary> public C() { } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the supplied values. /// </summary> /// <param name=""uriFormattedStrings""> /// An initialization value for the <see cref=""P:UriFormattedStrings"" /> property. /// </param> public C(IEnumerable<Uri> uriFormattedStrings) { Init(uriFormattedStrings); } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the specified instance. /// </summary> /// <param name=""other""> /// The instance from which the new instance is to be initialized. /// </param> /// <exception cref=""ArgumentNullException""> /// Thrown if <paramref name=""other"" /> is null. /// </exception> public C(C other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } Init(other.UriFormattedStrings); } ISNode ISNode.DeepClone() { return DeepCloneCore(); } /// <summary> /// Creates a deep copy of this instance. /// </summary> public C DeepClone() { return (C)DeepCloneCore(); } private ISNode DeepCloneCore() { return new C(this); } private void Init(IEnumerable<Uri> uriFormattedStrings) { if (uriFormattedStrings != null) { var destination_0 = new List<Uri>(); foreach (var value_0 in uriFormattedStrings) { destination_0.Add(value_0); } UriFormattedStrings = destination_0; } } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.UriFormattedStrings, right.UriFormattedStrings)) { if (left.UriFormattedStrings == null || right.UriFormattedStrings == null) { return false; } if (left.UriFormattedStrings.Count != right.UriFormattedStrings.Count) { return false; } for (int index_0 = 0; index_0 < left.UriFormattedStrings.Count; ++index_0) { if (left.UriFormattedStrings[index_0] != right.UriFormattedStrings[index_0]) { return false; } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.UriFormattedStrings != null) { foreach (var value_0 in obj.UriFormattedStrings) { result = result * 31; if (value_0 != null) { result = (result * 31) + value_0.GetHashCode(); } } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.UriFormattedStrings.ListCompares(right.UriFormattedStrings, (a, b) => a.UriCompares(b)); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; const string ExpectedSyntaxInterface = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// An interface for all types generated from the S schema. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public interface ISNode { /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> SNodeKind SNodeKind { get; } /// <summary> /// Makes a deep copy of this instance. /// </summary> ISNode DeepClone(); } }"; const string ExpectedKindEnum = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// A set of values for all the types that implement <see cref=""ISNode"" />. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public enum SNodeKind { /// <summary> /// An uninitialized kind. /// </summary> None, /// <summary> /// A value indicating that the <see cref=""ISNode"" /> object is of type <see cref=""C"" />. /// </summary> C } }"; const string ExpectedRewritingVisitor = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; namespace N { /// <summary> /// Rewriting visitor for the S object model. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public abstract class SRewritingVisitor { /// <summary> /// Starts a rewriting visit of a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object Visit(ISNode node) { return this.VisitActual(node); } /// <summary> /// Visits and rewrites a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object VisitActual(ISNode node) { if (node == null) { throw new ArgumentNullException(""node""); } switch (node.SNodeKind) { case SNodeKind.C: return VisitC((C)node); default: return node; } } private T VisitNullChecked<T>(T node) where T : class, ISNode { if (node == null) { return null; } return (T)Visit(node); } public virtual C VisitC(C node) { if (node != null) { } return node; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; _settings.GenerateCloningCode = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); generator.Generate(schema); string equalityComparerOutputFilePath = TestFileSystem.MakeOutputFilePath(TestSettings.RootClassName + "EqualityComparer"); string comparerOutputFilePath = TestFileSystem.MakeOutputFilePath(TestSettings.RootClassName + "Comparer"); string comparerExtensionFilePath = TestFileSystem.MakeOutputFilePath("ComparerExtensions"); string syntaxInterfacePath = TestFileSystem.MakeOutputFilePath("ISNode"); string kindEnumPath = TestFileSystem.MakeOutputFilePath("SNodeKind"); string rewritingVisitorClassPath = TestFileSystem.MakeOutputFilePath("SRewritingVisitor"); var expectedOutputFiles = new List<string> { PrimaryOutputFilePath, equalityComparerOutputFilePath, comparerOutputFilePath, comparerExtensionFilePath, syntaxInterfacePath, kindEnumPath, rewritingVisitorClassPath, }; _testFileSystem.Files.Count.Should().Be(expectedOutputFiles.Count); _testFileSystem.Files.Should().OnlyContain(path => expectedOutputFiles.Contains(path)); _testFileSystem[PrimaryOutputFilePath].Should().Be(ExpectedClass); _testFileSystem[equalityComparerOutputFilePath].Should().Be(ExpectedEqualityComparerClass); _testFileSystem[comparerOutputFilePath].Should().Be(ExpectedComparerClass); _testFileSystem[syntaxInterfacePath].Should().Be(ExpectedSyntaxInterface); _testFileSystem[kindEnumPath].Should().Be(ExpectedKindEnum); _testFileSystem[rewritingVisitorClassPath].Should().Be(ExpectedRewritingVisitor); } [Fact(DisplayName = "DataModelGenerator generates array of arrays of primitive type")] public void GeneratesArrayOfArraysOfPrimitiveType() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""arrayOfArrayOfInt"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/itemType"" } } }, ""definitions"": { ""itemType"": { ""type"": ""array"", ""items"": { ""type"": ""integer"" } } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""arrayOfArrayOfInt"", IsRequired = false, EmitDefaultValue = false)] public IList<IList<int>> ArrayOfArrayOfInt { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.ArrayOfArrayOfInt, right.ArrayOfArrayOfInt)) { if (left.ArrayOfArrayOfInt == null || right.ArrayOfArrayOfInt == null) { return false; } if (left.ArrayOfArrayOfInt.Count != right.ArrayOfArrayOfInt.Count) { return false; } for (int index_0 = 0; index_0 < left.ArrayOfArrayOfInt.Count; ++index_0) { if (!object.ReferenceEquals(left.ArrayOfArrayOfInt[index_0], right.ArrayOfArrayOfInt[index_0])) { if (left.ArrayOfArrayOfInt[index_0] == null || right.ArrayOfArrayOfInt[index_0] == null) { return false; } if (left.ArrayOfArrayOfInt[index_0].Count != right.ArrayOfArrayOfInt[index_0].Count) { return false; } for (int index_1 = 0; index_1 < left.ArrayOfArrayOfInt[index_0].Count; ++index_1) { if (left.ArrayOfArrayOfInt[index_0][index_1] != right.ArrayOfArrayOfInt[index_0][index_1]) { return false; } } } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ArrayOfArrayOfInt != null) { foreach (var value_0 in obj.ArrayOfArrayOfInt) { result = result * 31; if (value_0 != null) { foreach (var value_1 in value_0) { result = result * 31; result = (result * 31) + value_1.GetHashCode(); } } } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.ArrayOfArrayOfInt.ListCompares(right.ArrayOfArrayOfInt, (a, b) => a.ListCompares(b)); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); string actual = generator.Generate(schema); TestUtil.WriteTestResultFiles(ExpectedClass, actual, nameof(GeneratesArrayOfArraysOfPrimitiveType)); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass, } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates array of arrays of object type")] public void GeneratesArrayOfArraysOfObjectType() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""arrayOfArrayOfObject"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/itemType"" } } }, ""definitions"": { ""itemType"": { ""type"": ""array"", ""items"": { ""type"": ""object"" } } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""arrayOfArrayOfObject"", IsRequired = false, EmitDefaultValue = false)] public IList<IList<object>> ArrayOfArrayOfObject { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.ArrayOfArrayOfObject, right.ArrayOfArrayOfObject)) { if (left.ArrayOfArrayOfObject == null || right.ArrayOfArrayOfObject == null) { return false; } if (left.ArrayOfArrayOfObject.Count != right.ArrayOfArrayOfObject.Count) { return false; } for (int index_0 = 0; index_0 < left.ArrayOfArrayOfObject.Count; ++index_0) { if (!object.ReferenceEquals(left.ArrayOfArrayOfObject[index_0], right.ArrayOfArrayOfObject[index_0])) { if (left.ArrayOfArrayOfObject[index_0] == null || right.ArrayOfArrayOfObject[index_0] == null) { return false; } if (left.ArrayOfArrayOfObject[index_0].Count != right.ArrayOfArrayOfObject[index_0].Count) { return false; } for (int index_1 = 0; index_1 < left.ArrayOfArrayOfObject[index_0].Count; ++index_1) { if (!object.Equals(left.ArrayOfArrayOfObject[index_0][index_1], right.ArrayOfArrayOfObject[index_0][index_1])) { return false; } } } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ArrayOfArrayOfObject != null) { foreach (var value_0 in obj.ArrayOfArrayOfObject) { result = result * 31; if (value_0 != null) { foreach (var value_1 in value_0) { result = result * 31; if (value_1 != null) { result = (result * 31) + value_1.GetHashCode(); } } } } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.ArrayOfArrayOfObject.ListCompares(right.ArrayOfArrayOfObject, (a, b) => a.ListCompares(b)); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); string actual = generator.Generate(schema); TestUtil.WriteTestResultFiles(ExpectedClass, actual, nameof(GeneratesArrayOfArraysOfObjectType)); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates array of arrays of class type")] public void GeneratesArrayOfArraysOfClassType() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""arrayOfArrayOfD"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/itemType"" } } }, ""definitions"": { ""itemType"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/definitions/d"" } }, ""d"": { ""type"": ""object"", } } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; [DataMember(Name = ""arrayOfArrayOfD"", IsRequired = false, EmitDefaultValue = false)] public IList<IList<D>> ArrayOfArrayOfD { get; set; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left.ArrayOfArrayOfD, right.ArrayOfArrayOfD)) { if (left.ArrayOfArrayOfD == null || right.ArrayOfArrayOfD == null) { return false; } if (left.ArrayOfArrayOfD.Count != right.ArrayOfArrayOfD.Count) { return false; } for (int index_0 = 0; index_0 < left.ArrayOfArrayOfD.Count; ++index_0) { if (!object.ReferenceEquals(left.ArrayOfArrayOfD[index_0], right.ArrayOfArrayOfD[index_0])) { if (left.ArrayOfArrayOfD[index_0] == null || right.ArrayOfArrayOfD[index_0] == null) { return false; } if (left.ArrayOfArrayOfD[index_0].Count != right.ArrayOfArrayOfD[index_0].Count) { return false; } for (int index_1 = 0; index_1 < left.ArrayOfArrayOfD[index_0].Count; ++index_1) { if (!D.ValueComparer.Equals(left.ArrayOfArrayOfD[index_0][index_1], right.ArrayOfArrayOfD[index_0][index_1])) { return false; } } } } } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.ArrayOfArrayOfD != null) { foreach (var value_0 in obj.ArrayOfArrayOfD) { result = result * 31; if (value_0 != null) { foreach (var value_1 in value_0) { result = result * 31; if (value_1 != null) { result = (result * 31) + value_1.ValueGetHashCode(); } } } } } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = left.ArrayOfArrayOfD.ListCompares(right.ArrayOfArrayOfD, (a, b) => a.ListCompares(b)); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; _settings.GenerateEqualityComparers = true; _settings.GenerateComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); string actual = generator.Generate(schema); TestUtil.WriteTestResultFiles(ExpectedClass, actual, nameof(GeneratesArrayOfArraysOfClassType)); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass, EqualityComparerClassContents = ExpectedEqualityComparerClass, ComparerClassContents = ExpectedComparerClass }, ["D"] = new ExpectedContents() }; VerifyGeneratedFileContents(expectedContentsDictionary); } [Fact(DisplayName = "DataModelGenerator generates string for inline enum of string")] public void GeneratesStringForInlineEnumOfString() { var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""version"": { ""enum"": [ ""v1.0"", ""v2.0"" ] } } }", TestUtil.TestFilePath); const string Expected = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { [DataMember(Name = ""version"", IsRequired = false, EmitDefaultValue = false)] public string Version { get; set; } } }"; string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates attributes for required and optional properties")] public void GeneratesAttributesForRequiredAndOptionalProperties() { var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""requiredProp1"": { ""type"": ""string"" }, ""optionalProp"": { ""type"": ""string"" }, ""requiredProp2"": { ""type"": ""string"" } }, ""required"": [ ""requiredProp1"", ""requiredProp2"" ] }", TestUtil.TestFilePath); const string Expected = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { [DataMember(Name = ""requiredProp1"", IsRequired = true)] public string RequiredProp1 { get; set; } [DataMember(Name = ""optionalProp"", IsRequired = false, EmitDefaultValue = false)] public string OptionalProp { get; set; } [DataMember(Name = ""requiredProp2"", IsRequired = true)] public string RequiredProp2 { get; set; } } }"; string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates sealed classes when option is set")] public void GeneratesSealedClassesWhenOptionIsSet() { _settings.SealClasses = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", }", TestUtil.TestFilePath); const string Expected = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public sealed class C { } }"; string actual = generator.Generate(schema); actual.Should().Be(Expected); } [Fact(DisplayName = "DataModelGenerator generates protected Init methods when option is set")] public void GeneratesProtectedInitMethodsWhenOptionIsSet() { _settings.ProtectedInitMethods = true; // Unless you generate cloning code, you don't get an Init method at all. _settings.GenerateCloningCode = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""prop"": { ""type"": ""string"" } } }", TestUtil.TestFilePath); const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C : ISNode { /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> public SNodeKind SNodeKind { get { return SNodeKind.C; } } [DataMember(Name = ""prop"", IsRequired = false, EmitDefaultValue = false)] public string Prop { get; set; } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class. /// </summary> public C() { } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the supplied values. /// </summary> /// <param name=""prop""> /// An initialization value for the <see cref=""P:Prop"" /> property. /// </param> public C(string prop) { Init(prop); } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the specified instance. /// </summary> /// <param name=""other""> /// The instance from which the new instance is to be initialized. /// </param> /// <exception cref=""ArgumentNullException""> /// Thrown if <paramref name=""other"" /> is null. /// </exception> public C(C other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } Init(other.Prop); } ISNode ISNode.DeepClone() { return DeepCloneCore(); } /// <summary> /// Creates a deep copy of this instance. /// </summary> public C DeepClone() { return (C)DeepCloneCore(); } private ISNode DeepCloneCore() { return new C(this); } protected virtual void Init(string prop) { Prop = prop; } } }"; string actualClass = generator.Generate(schema); actualClass.Should().Be(ExpectedClass); } [Fact(DisplayName = "DataModelGenerator generates virtual members when option is set")] public void GeneratesVirtualMembersWhenOptionIsSet() { _settings.VirtualMembers = true; _settings.GenerateComparers = true; _settings.GenerateCloningCode = true; _settings.GenerateEqualityComparers = true; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema( @"{ ""type"": ""object"", ""properties"": { ""prop"": { ""type"": ""string"" } } }", TestUtil.TestFilePath); const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C : ISNode { public static IEqualityComparer<C> ValueComparer => CEqualityComparer.Instance; public bool ValueEquals(C other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); public static IComparer<C> Comparer => CComparer.Instance; /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> public virtual SNodeKind SNodeKind { get { return SNodeKind.C; } } [DataMember(Name = ""prop"", IsRequired = false, EmitDefaultValue = false)] public virtual string Prop { get; set; } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class. /// </summary> public C() { } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the supplied values. /// </summary> /// <param name=""prop""> /// An initialization value for the <see cref=""P:Prop"" /> property. /// </param> public C(string prop) { Init(prop); } /// <summary> /// Initializes a new instance of the <see cref=""C"" /> class from the specified instance. /// </summary> /// <param name=""other""> /// The instance from which the new instance is to be initialized. /// </param> /// <exception cref=""ArgumentNullException""> /// Thrown if <paramref name=""other"" /> is null. /// </exception> public C(C other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } Init(other.Prop); } ISNode ISNode.DeepClone() { return DeepCloneCore(); } /// <summary> /// Creates a deep copy of this instance. /// </summary> public virtual C DeepClone() { return (C)DeepCloneCore(); } private ISNode DeepCloneCore() { return new C(this); } private void Init(string prop) { Prop = prop; } } }"; const string ExpectedEqualityComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for equality. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CEqualityComparer : IEqualityComparer<C> { internal static readonly CEqualityComparer Instance = new CEqualityComparer(); public bool Equals(C left, C right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.Prop != right.Prop) { return false; } return true; } public int GetHashCode(C obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.Prop != null) { result = (result * 31) + obj.Prop.GetHashCode(); } } return result; } } }"; const string ExpectedComparerClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace N { /// <summary> /// Defines methods to support the comparison of objects of type C for sorting. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] internal sealed class CComparer : IComparer<C> { internal static readonly CComparer Instance = new CComparer(); public int Compare(C left, C right) { int compareResult = 0; // TryReferenceCompares is an autogenerated extension method // that will properly handle the case when 'left' is null. if (left.TryReferenceCompares(right, out compareResult)) { return compareResult; } compareResult = string.Compare(left.Prop, right.Prop); if (compareResult != 0) { return compareResult; } return compareResult; } } }"; const string ExpectedSyntaxInterface = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// An interface for all types generated from the S schema. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public interface ISNode { /// <summary> /// Gets a value indicating the type of object implementing <see cref=""ISNode"" />. /// </summary> SNodeKind SNodeKind { get; } /// <summary> /// Makes a deep copy of this instance. /// </summary> ISNode DeepClone(); } }"; const string ExpectedKindEnum = @"using System.CodeDom.Compiler; namespace N { /// <summary> /// A set of values for all the types that implement <see cref=""ISNode"" />. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public enum SNodeKind { /// <summary> /// An uninitialized kind. /// </summary> None, /// <summary> /// A value indicating that the <see cref=""ISNode"" /> object is of type <see cref=""C"" />. /// </summary> C } }"; const string ExpectedRewritingVisitor = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; namespace N { /// <summary> /// Rewriting visitor for the S object model. /// </summary> [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public abstract class SRewritingVisitor { /// <summary> /// Starts a rewriting visit of a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object Visit(ISNode node) { return this.VisitActual(node); } /// <summary> /// Visits and rewrites a node in the S object model. /// </summary> /// <param name=""node""> /// The node to rewrite. /// </param> /// <returns> /// A rewritten instance of the node. /// </returns> public virtual object VisitActual(ISNode node) { if (node == null) { throw new ArgumentNullException(""node""); } switch (node.SNodeKind) { case SNodeKind.C: return VisitC((C)node); default: return node; } } private T VisitNullChecked<T>(T node) where T : class, ISNode { if (node == null) { return null; } return (T)Visit(node); } public virtual C VisitC(C node) { if (node != null) { } return node; } } }"; generator.Generate(schema); var expectedOutputFiles = new List<string> { PrimaryOutputFilePath, PrimaryComparerOutputFilePath, PrimaryEqualityComparerOutputFilePath, ComparerExtensionsOutputFilePath, SyntaxInterfaceOutputFilePath, KindEnumOutputFilePath, RewritingVisitorOutputFilePath }; _testFileSystem.Files.Count.Should().Be(expectedOutputFiles.Count); _testFileSystem.Files.Should().OnlyContain(path => expectedOutputFiles.Contains(path)); _testFileSystem[PrimaryOutputFilePath].Should().Be(ExpectedClass); _testFileSystem[PrimaryComparerOutputFilePath].Should().Be(ExpectedComparerClass); _testFileSystem[PrimaryEqualityComparerOutputFilePath].Should().Be(ExpectedEqualityComparerClass); _testFileSystem[SyntaxInterfaceOutputFilePath].Should().Be(ExpectedSyntaxInterface); _testFileSystem[KindEnumOutputFilePath].Should().Be(ExpectedKindEnum); _testFileSystem[RewritingVisitorOutputFilePath].Should().Be(ExpectedRewritingVisitor); } [Fact(DisplayName = "DataModelGenerator accepts a limited oneOf with \"type\": \"null\"")] public void AcceptsLimitedOneOfWithTypeNull() { const string Schema = @"{ ""type"": ""object"", ""properties"": { ""arrayOrNullProperty"": { ""description"": ""A property that can either be an array or null."", ""oneOf"": [ { ""type"": ""array"" }, { ""type"": ""null"" } ], ""items"": { ""type"": ""integer"" } } } }"; const string ExpectedClass = @"using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; namespace N { [DataContract] [GeneratedCode(""Microsoft.Json.Schema.ToDotNet"", """ + VersionConstants.FileVersion + @""")] public partial class C { /// <summary> /// A property that can either be an array or null. /// </summary> [DataMember(Name = ""arrayOrNullProperty"", IsRequired = false, EmitDefaultValue = false)] public IList<int> ArrayOrNullProperty { get; set; } } }"; var generator = new DataModelGenerator(_settings, _testFileSystem.FileSystem); JsonSchema schema = SchemaReader.ReadSchema(Schema, TestUtil.TestFilePath); generator.Generate(schema); var expectedContentsDictionary = new Dictionary<string, ExpectedContents> { [_settings.RootClassName] = new ExpectedContents { ClassContents = ExpectedClass } }; VerifyGeneratedFileContents(expectedContentsDictionary); } private void VerifyGeneratedFileContents(IDictionary<string, ExpectedContents> expectedContentsDictionary) { Assert.FileContentsMatchExpectedContents(_testFileSystem, expectedContentsDictionary, _settings.GenerateEqualityComparers, _settings.GenerateComparers); } } }
32.61955
821
0.565304
[ "Apache-2.0" ]
Microsoft/jschema
src/Json.Schema.ToDotNet.UnitTests/DataModelGeneratorTests.cs
163,850
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EngageHit : MonoBehaviour { private DamageChecker dCheck; [SerializeField] private float damage; public float Damage { get { return damage; } set { damage = value; } } private void Start() { dCheck = transform.parent.GetComponent<DamageChecker>(); } private void OnTriggerEnter2D(Collider2D collision) { //dCheck. Debug.Log(gameObject.ToString()); if (collision.isTrigger==true) collision.GetComponent<DamageChecker>().HurtDamage(Damage); } private void OnTriggerStay2D(Collider2D collision) { // Debug.Log(gameObject.ToString()+" is hitted" + collision.name); } }
27.777778
74
0.68
[ "MIT" ]
LocketGoma/YYT_20_Battle
Assets/Script/Charactor/EngageHit.cs
752
C#
using Munchkin.Core.Model; using System.Threading; using System.Threading.Tasks; namespace Munchkin.Core.Contracts.Actions { public abstract class MultiShotAction : DynamicAction, IMultiShotAction<Table> { private int _executionsLeft; protected MultiShotAction(int executionCount, string title, string description) : base(title, description) { _executionsLeft = executionCount; ExecutionsCount = executionCount; } public int ExecutionsCount { get; } public int ExecutionsLeft => _executionsLeft; public override Task<Table> ExecuteAsync(Table table) { Interlocked.Decrement(ref _executionsLeft); return Task.FromResult(table); } } }
27.535714
114
0.670558
[ "Apache-2.0" ]
walking-down-the-silence/munchkin
src/Munchkin.Core/Contracts/Actions/MultiShotAction.cs
773
C#
using System; using PubComp.NoSql.Core; namespace PubComp.NoSql.AdaptorTests.Mock { public class EntityForCalc : IEntity<Guid> { public Guid Id { get; set; } public Guid OwnerId { get; set; } public DateTime Date { get; set; } public double Money { get; set; } } }
23.142857
47
0.592593
[ "MIT" ]
pub-comp/no-sql
NoSql.AdaptorTests/Mock/EntityForCalc.cs
326
C#
// Project: Aguafrommars/TheIdServer // Copyright (c) 2022 @Olivier Lefebvre using Aguacongas.IdentityServer.Admin.Models; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; namespace Aguacongas.IdentityServer.Admin.Services { /// <summary> /// /// </summary> public interface IRegisterClientService { /// <summary> /// Registers the asynchronous. /// </summary> /// <param name="registration">The client registration.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns></returns> Task<ClientRegisteration> RegisterAsync(ClientRegisteration registration, HttpContext httpContext); /// <summary> /// Updates the registration asynchronous. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="registration">The registration.</param> /// <param name="uri">The URI.</param> /// <returns></returns> Task<ClientRegisteration> UpdateRegistrationAsync(string clientId, ClientRegisteration registration, string uri); /// <summary> /// Gets the registration asynchronous. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="uri">The URI.</param> /// <returns></returns> Task<ClientRegisteration> GetRegistrationAsync(string clientId, string uri); /// <summary> /// Deletes the registration asynchronous. /// </summary> /// <param name="clientId">The client identifier.</param> /// <returns></returns> Task DeleteRegistrationAsync(string clientId); } }
37.933333
121
0.630346
[ "Apache-2.0" ]
LibertyEngineeringMovement/TheIdServer
src/IdentityServer/Shared/Aguacongas.IdentityServer.Admin.Shared/Services/IRegisterClientService.cs
1,709
C#
using Microsoft.Playwright; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace Dn6Poc.DocuMgmtPortal.E2ETests { [TestClass] public class UnitTest1 { [TestMethod] public async Task TestMethod1Async() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false, Channel = "msedge", }); var context = await browser.NewContextAsync(); // Open new page var page = await context.NewPageAsync(); // Go to https://localhost:7241/ await page.GotoAsync("https://localhost:7241/"); // Click main[role="main"] >> text=Login await page.ClickAsync("main[role=\"main\"] >> text=Login"); // Assert.AreEqual("https://localhost:7241/Login", page.Url); // Click input[name="Password"] await page.ClickAsync("input[name=\"Password\"]"); // Fill input[name="Password"] await page.FillAsync("input[name=\"Password\"]", "ASds"); // Click text=Submit await page.ClickAsync("text=Submit"); // Assert.AreEqual("https://localhost:7241/Login", page.Url); } } }
37.621622
104
0.579023
[ "MIT" ]
ongzhixian/dc6Poc
Dn6Poc.DocuMgmtPortal.E2ETests/UnitTest1.cs
1,392
C#
using System; using System.Runtime.InteropServices; namespace Poltergeist.Core.Memory { public sealed unsafe class NativeStruct<T> : IDisposable where T : struct { // ReSharper disable once StaticMemberInGenericType public static readonly INativeAllocator DefaultAllocator = new CoTaskMemAllocator(); public readonly void* Data; public readonly int Size; internal readonly INativeAllocator Allocator; private readonly bool _zeroOnFree; private readonly object _disposeLock = new(); private bool _valid; public NativeStruct(T structure, bool zeroOnFree = false, INativeAllocator allocator = null) { Size = Marshal.SizeOf<T>(); Allocator = allocator ?? DefaultAllocator; IntPtr ptr = Allocator.Allocate(Size); GC.AddMemoryPressure(Size); Marshal.StructureToPtr(structure, ptr, false); Data = ptr.ToPointer(); _valid = Data != null; _zeroOnFree = zeroOnFree; } private void Free() { lock (_disposeLock) { if (!_valid) return; IntPtr ptr = new(Data); Marshal.DestroyStructure<T>(ptr); if (_zeroOnFree) new Span<byte>(Data, Size).Clear(); Allocator.Free(ptr); GC.RemoveMemoryPressure(Size); _valid = false; } } public void Dispose() { Free(); GC.SuppressFinalize(this); } ~NativeStruct() { Free(); } } }
20.257576
94
0.691847
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Freddson/Poltergeist
Poltergeist.Core/Memory/NativeStruct.cs
1,339
C#
// // ICacneable.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2008 Alan McGovern // // 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.Text; namespace OctoTorrent.Common { interface ICacheable { void Initialise(); } }
33.341463
73
0.743965
[ "BSD-3-Clause" ]
bietiekay/sonos-podcast-service
Libraries/OctoTorrent/OctoTorrent/Common/ICacheable.cs
1,367
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace XPlaneGenConsole.Linq { public abstract class QueryProvider : IQueryProvider { public IQueryable CreateQuery(Expression exp) { Type elementType = TypeSystem.GetElementType(exp.Type); try { return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(elementType), new object[] { this, exp }); } catch (TargetInvocationException ex) { throw ex.InnerException; } } public IQueryable<T> CreateQuery<T>(Expression exp) { return new Query<T>(this, exp); } public T Execute<T>(Expression exp) { return (T)this.Execute(exp); } object IQueryProvider.Execute(Expression expression) { return this.Execute(expression); } public abstract string GetQueryText(Expression expression); public abstract object Execute(Expression expression); } internal static class TypeSystem { internal static Type GetElementType(Type seqType) { Type ienum = FindIEnumerable(seqType); if (ienum == null) return seqType; return ienum.GetGenericArguments()[0]; } private static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; } } }
30.465909
134
0.532637
[ "MIT" ]
DefectiveCube/FlightDataAnalyzer
src/AnalysisLib/Linq/Provider.cs
2,683
C#
using System.Collections; using System.IO; using UnityEngine; namespace GLTF { class GLTFComponentStreamingAssets : MonoBehaviour { [Tooltip("This file should be in the StreamingAssets folder. Please include the file extension.")] public string GLTFName; public bool Multithreaded = true; public int MaximumLod = 300; public UnityEngine.Material ColorMaterial; public UnityEngine.Material NoColorMaterial; [HideInInspector] public byte[] GLTFData; private void Start() { if (!string.IsNullOrEmpty(GLTFName)) { if (File.Exists(Path.Combine(Application.streamingAssetsPath, GLTFName))) { GLTFData = File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, GLTFName)); StartCoroutine(LoadModel()); } else { Debug.Log("The glTF file specified on " + name + " does not exist in the StreamingAssets folder."); } } } public IEnumerator LoadModel() { var loader = new GLTFLoader( GLTFData, gameObject.transform ); loader.ColorMaterial = ColorMaterial; loader.NoColorMaterial = NoColorMaterial; loader.Multithreaded = Multithreaded; loader.MaximumLod = MaximumLod; yield return loader.Load(); } } }
30.7
119
0.565472
[ "MIT" ]
JulienPlouvier/Hololens_BouncingBall
Bouncing Ball/Assets/DesignLabs_Unity/Assets/HoloToolkit/Utilities/Scripts/GLTFComponentStreamingAssets.cs
1,537
C#
#region License /* MIT License Copyright (c) 2020 Americus Maximus 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 namespace ImageBox.Coloring { public enum ColorerMatrixType { Achromatomaly = 0, Achromatopsia = 1, AverageGrayScale = 2, BlackAndWhite = 3, Brightness = 4, Cold = 5, Contrast = 6, Deuteranomaly = 7, Deuteranopia = 8, Exposure = 9, GrayScale = 10, Inverted = 11, LuminanceToAlpha = 12, Negative = 13, NightVision = 14, Normal = 15, Polaroid = 16, Protanomaly = 17, Protanopia = 18, RGBBGR = 19, Saturation = 20, Sepia = 21, Temperature = 22, Threshold = 23, Tint = 24, Tritanomaly = 25, Tritanopia = 26, Warm = 27, WhiteToAlpha = 28 } }
30.467742
78
0.670196
[ "MIT" ]
americusmaximus/ImageBox
Source/ImageBox/Coloring/ColorerMatrixType.cs
1,891
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("09.TraverseDirectoryXmlWriter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09.TraverseDirectoryXmlWriter")] [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("3d723fde-0850-463c-8416-a52558d17fb8")] // 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")]
38.675676
84
0.749825
[ "MIT" ]
emilti/Telerik-Academy-My-Courses
DataBases/03.Processing Xml/Processing XML/09.TraverseDirectoryXmlWriter/Properties/AssemblyInfo.cs
1,434
C#
namespace Nop.Plugin.Payments.Manual { /// <summary> /// Represents manual payment processor transaction mode /// </summary> public enum TransactMode { /// <summary> /// Pending /// </summary> Pending = 0, /// <summary> /// Authorize /// </summary> Authorize = 1, /// <summary> /// Authorize and capture /// </summary> AuthorizeAndCapture= 2 } }
18.76
60
0.490405
[ "MIT" ]
ASP-WAF/FireWall
Samples/NopeCommerce/Plugins/Nop.Plugin.Payments.Manual/TransactMode.cs
469
C#
using DarkRift; using DarkRift.Client; using UnityEngine; using UnityEngine.SceneManagement; public class LobbyManager : MonoBehaviour { public static LobbyManager Instance; [Header("References")] public Transform RoomListContainerTransform; [Header("Prefabs")] public GameObject RoomListPrefab; private void Awake() { Instance = this; } private void Start() { GlobalManager.Instance.Client.MessageReceived += OnMessage; RefreshRooms(GlobalManager.Instance.LastRecievedLobbyInfoData); } private void OnDestroy() { GlobalManager.Instance.Client.MessageReceived -= OnMessage; } private void OnMessage(object sender, MessageReceivedEventArgs e) { using (Message m = e.GetMessage()) { switch ((Tags)m.Tag) { case Tags.LobbyJoinRoomDenied: OnRoomJoinDenied(m.Deserialize<LobbyInfoData>()); break; case Tags.LobbyJoinRoomAccepted: OnRoomJoinAcepted(); break; } } } /// <summary> /// sends a request to join a certain room /// </summary> /// <param name="roomName"></param> public void SendJoinRoomRequest(string roomName) { using (Message m = Message.Create((ushort)Tags.LobbyJoinRoomRequest, new JoinRoomRequest(roomName))) { GlobalManager.Instance.Client.SendMessage(m, SendMode.Reliable); } } /// <summary> /// If the player can not join the room then refresh the current rooms /// </summary> /// <param name="data"></param> public void OnRoomJoinDenied(LobbyInfoData data) { RefreshRooms(data); } /// <summary> /// If the player can join this room then change to the main game scene /// </summary> public void OnRoomJoinAcepted() { SceneManager.LoadScene("Game"); } /// <summary> /// refreshes the available rooms /// </summary> /// <param name="data"></param> public void RefreshRooms(LobbyInfoData data) { RoomListObject[] roomObjects = RoomListContainerTransform.GetComponentsInChildren<RoomListObject>(); for (int i = 0; i < data.Rooms.Length; i++) { RoomData d = data.Rooms[i]; if (i < roomObjects.Length) { roomObjects[i].Set(d); } else { GameObject go = Instantiate(RoomListPrefab, RoomListContainerTransform); go.GetComponent<RoomListObject>().Set(d); } } } }
27.010101
108
0.585639
[ "MIT" ]
Mrgove10/HouseWars
HouseWars/Assets/_CLIENT/Scripts/Networking/LobbyManager.cs
2,676
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace Snikt { public class Database : IDatabase, IDisposable { public IDbConnectionFactory ConnectionFactory { get; private set; } public IDbConnection Connection { get; private set; } public Database(string nameOrConnectionString) : this(nameOrConnectionString, CreateDefaultConnectionFactory()) { // HINT: Nothing to do here. } public Database(string nameOrConnectionString, IDbConnectionFactory connectionFactory) { ConnectionFactory = connectionFactory; Connection = ConnectionFactory.CreateIfNotExists(nameOrConnectionString); } public static IDbConnectionFactory CreateDefaultConnectionFactory() { return DbConnectionFactory.Get(); } public IEnumerable<T> SqlQuery<T>(string sql) where T : class, new() { return QueryInternal<T>(sql, null); } public IEnumerable<T> SqlQuery<T>(string sql, object parameters) where T : class, new() { return QueryInternal<T>(sql, parameters); } internal IEnumerable<T> QueryInternal<T>(string sql, object parameters) where T : class { // TODO: SOC/SRP violated. Wrap this logic with a different class. Action<IDbCommand, object> paramReader = (command, obj) => { var properties = obj.GetType() .GetProperties() .Select(property => new { Name = property.Name, Value = property.GetValue(obj, null) }) .ToList(); foreach (var propertyMap in properties) { IDbDataParameter dbparam = command.CreateParameter(); dbparam.ParameterName = propertyMap.Name; dbparam.Value = propertyMap.Value; command.Parameters.Add(dbparam); } }; using (IDbCommand command = SetupStoredCommand(null, sql, parameters != null ? paramReader : null, parameters, null)) { Connection.OpenIfNot(); using (IDataReader reader = command.ExecuteReader()) { Materializer<T> mapper = new Materializer<T>(reader); while (reader.Read()) { yield return (T)mapper.Materialize(reader); } } } } private IDbCommand SetupStoredCommand(IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout) { return SetupCommand(transaction, sql, paramReader, obj, commandTimeout, CommandType.StoredProcedure); } private IDbCommand SetupCommand(IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout, CommandType? commandType) { IDbCommand command = Connection.CreateCommand(); if (transaction != null) { command.Transaction = transaction; } if (commandTimeout.HasValue) { command.CommandTimeout = commandTimeout.Value; } if (commandType.HasValue) { command.CommandType = commandType.Value; } command.CommandText = sql; if (paramReader != null) { paramReader(command, obj); } return command; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (disposing) { using (Connection) { Connection.CloseIfNot(); } } } } }
33.688525
178
0.550365
[ "MIT" ]
alertbox/snikt
Snikt/Database.cs
4,112
C#
 namespace DataAccessLayer.Models { public class LogoutRequest { public string token; } }
11.2
32
0.633929
[ "MIT" ]
CECS-491A/SSO
Backend/DataAccessLayer/Models/LogoutRequest.cs
114
C#
using System; namespace _01._Integer_Operations { class Program { static void Main(string[] args) { int first = int.Parse(Console.ReadLine()); int second = int.Parse(Console.ReadLine()); int third = int.Parse(Console.ReadLine()); int fourth = int.Parse(Console.ReadLine()); int firstOperation = first + second; int secondOperation = firstOperation / third; int thirdOperation = secondOperation * fourth; Console.WriteLine(thirdOperation); } } }
26.409091
58
0.580034
[ "MIT" ]
mertmzzx/SoftUni-Exercises
Programming Fundamentals/Data Types and Variables - Exercise/01. Integer Operations/Program.cs
583
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Client.Http.Serialization { using System; using System.Collections.Generic; using Microsoft.ServiceFabric.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Converter for <see cref="ChaosStartedEvent" />. /// </summary> internal class ChaosStartedEventConverter { /// <summary> /// Deserializes the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param> /// <returns>The object Value.</returns> internal static ChaosStartedEvent Deserialize(JsonReader reader) { return reader.Deserialize(GetFromJsonProperties); } /// <summary> /// Gets the object from Json properties. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param> /// <returns>The object Value.</returns> internal static ChaosStartedEvent GetFromJsonProperties(JsonReader reader) { var eventInstanceId = default(Guid?); var category = default(string); var timeStamp = default(DateTime?); var hasCorrelatedEvents = default(bool?); var maxConcurrentFaults = default(long?); var timeToRunInSeconds = default(double?); var maxClusterStabilizationTimeoutInSeconds = default(double?); var waitTimeBetweenIterationsInSeconds = default(double?); var waitTimeBetweenFautlsInSeconds = default(double?); var moveReplicaFaultEnabled = default(bool?); var includedNodeTypeList = default(string); var includedApplicationList = default(string); var clusterHealthPolicy = default(string); var chaosContext = default(string); do { var propName = reader.ReadPropertyName(); if (string.Compare("EventInstanceId", propName, StringComparison.Ordinal) == 0) { eventInstanceId = reader.ReadValueAsGuid(); } else if (string.Compare("Category", propName, StringComparison.Ordinal) == 0) { category = reader.ReadValueAsString(); } else if (string.Compare("TimeStamp", propName, StringComparison.Ordinal) == 0) { timeStamp = reader.ReadValueAsDateTime(); } else if (string.Compare("HasCorrelatedEvents", propName, StringComparison.Ordinal) == 0) { hasCorrelatedEvents = reader.ReadValueAsBool(); } else if (string.Compare("MaxConcurrentFaults", propName, StringComparison.Ordinal) == 0) { maxConcurrentFaults = reader.ReadValueAsLong(); } else if (string.Compare("TimeToRunInSeconds", propName, StringComparison.Ordinal) == 0) { timeToRunInSeconds = reader.ReadValueAsDouble(); } else if (string.Compare("MaxClusterStabilizationTimeoutInSeconds", propName, StringComparison.Ordinal) == 0) { maxClusterStabilizationTimeoutInSeconds = reader.ReadValueAsDouble(); } else if (string.Compare("WaitTimeBetweenIterationsInSeconds", propName, StringComparison.Ordinal) == 0) { waitTimeBetweenIterationsInSeconds = reader.ReadValueAsDouble(); } else if (string.Compare("WaitTimeBetweenFautlsInSeconds", propName, StringComparison.Ordinal) == 0) { waitTimeBetweenFautlsInSeconds = reader.ReadValueAsDouble(); } else if (string.Compare("MoveReplicaFaultEnabled", propName, StringComparison.Ordinal) == 0) { moveReplicaFaultEnabled = reader.ReadValueAsBool(); } else if (string.Compare("IncludedNodeTypeList", propName, StringComparison.Ordinal) == 0) { includedNodeTypeList = reader.ReadValueAsString(); } else if (string.Compare("IncludedApplicationList", propName, StringComparison.Ordinal) == 0) { includedApplicationList = reader.ReadValueAsString(); } else if (string.Compare("ClusterHealthPolicy", propName, StringComparison.Ordinal) == 0) { clusterHealthPolicy = reader.ReadValueAsString(); } else if (string.Compare("ChaosContext", propName, StringComparison.Ordinal) == 0) { chaosContext = reader.ReadValueAsString(); } else { reader.SkipPropertyValue(); } } while (reader.TokenType != JsonToken.EndObject); return new ChaosStartedEvent( eventInstanceId: eventInstanceId, category: category, timeStamp: timeStamp, hasCorrelatedEvents: hasCorrelatedEvents, maxConcurrentFaults: maxConcurrentFaults, timeToRunInSeconds: timeToRunInSeconds, maxClusterStabilizationTimeoutInSeconds: maxClusterStabilizationTimeoutInSeconds, waitTimeBetweenIterationsInSeconds: waitTimeBetweenIterationsInSeconds, waitTimeBetweenFautlsInSeconds: waitTimeBetweenFautlsInSeconds, moveReplicaFaultEnabled: moveReplicaFaultEnabled, includedNodeTypeList: includedNodeTypeList, includedApplicationList: includedApplicationList, clusterHealthPolicy: clusterHealthPolicy, chaosContext: chaosContext); } /// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, ChaosStartedEvent obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.Kind, "Kind", FabricEventKindConverter.Serialize); writer.WriteProperty(obj.EventInstanceId, "EventInstanceId", JsonWriterExtensions.WriteGuidValue); writer.WriteProperty(obj.TimeStamp, "TimeStamp", JsonWriterExtensions.WriteDateTimeValue); writer.WriteProperty(obj.MaxConcurrentFaults, "MaxConcurrentFaults", JsonWriterExtensions.WriteLongValue); writer.WriteProperty(obj.TimeToRunInSeconds, "TimeToRunInSeconds", JsonWriterExtensions.WriteDoubleValue); writer.WriteProperty(obj.MaxClusterStabilizationTimeoutInSeconds, "MaxClusterStabilizationTimeoutInSeconds", JsonWriterExtensions.WriteDoubleValue); writer.WriteProperty(obj.WaitTimeBetweenIterationsInSeconds, "WaitTimeBetweenIterationsInSeconds", JsonWriterExtensions.WriteDoubleValue); writer.WriteProperty(obj.WaitTimeBetweenFautlsInSeconds, "WaitTimeBetweenFautlsInSeconds", JsonWriterExtensions.WriteDoubleValue); writer.WriteProperty(obj.MoveReplicaFaultEnabled, "MoveReplicaFaultEnabled", JsonWriterExtensions.WriteBoolValue); writer.WriteProperty(obj.IncludedNodeTypeList, "IncludedNodeTypeList", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.IncludedApplicationList, "IncludedApplicationList", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.ClusterHealthPolicy, "ClusterHealthPolicy", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.ChaosContext, "ChaosContext", JsonWriterExtensions.WriteStringValue); if (obj.Category != null) { writer.WriteProperty(obj.Category, "Category", JsonWriterExtensions.WriteStringValue); } if (obj.HasCorrelatedEvents != null) { writer.WriteProperty(obj.HasCorrelatedEvents, "HasCorrelatedEvents", JsonWriterExtensions.WriteBoolValue); } writer.WriteEndObject(); } } }
52.605882
160
0.615342
[ "MIT" ]
MedAnd/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Client.Http/Generated/Serialization/ChaosStartedEventConverter.cs
8,943
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 03.02.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Divide.Complete.DECIMAL_6_1.NUMERIC_6_1{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Decimal; using T_DATA2 =System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields public static class TestSet_001__fields { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_DEC_6_1"; private const string c_NameOf__COL_DATA2 ="COL2_NUM_6_1"; private const int c_RESULT_VCH_LEN=32; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1,TypeName="DECIMAL(6,1)")] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2,TypeName="NUMERIC(6,1)")] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=7; const T_DATA2 c_value2=4; Assert.AreEqual (1.75m, c_value1/c_value2); System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (string)(object)(r.COL_DATA1/r.COL_DATA2)=="1.750000000000000" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST((").N_AS_DBL("t",c_NameOf__COL_DATA1).T(" / ").N("t",c_NameOf__COL_DATA2).T(") AS VARCHAR("+c_RESULT_VCH_LEN+")) = _utf8 '1.750000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //Helper methdods ------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Divide.Complete.DECIMAL_6_1.NUMERIC_6_1
30.206452
227
0.570483
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Divide/Complete/DECIMAL_6_1/NUMERIC_6_1/TestSet_001__fields.cs
4,684
C#
using UnityEngine; using System.Collections; public class HomingAttackControl : MonoBehaviour { public bool HasTarget { get; set; } public static GameObject TargetObject { get; set; } public ActionManager Actions; public float TargetSearchDistance = 10; public Transform Icon; public float IconScale; public static GameObject[] Targets; public GameObject[] TgtDebug; public Transform MainCamera; public float IconDistanceScaling; int HomingCount; public bool HomingAvailable { get; set; } bool firstime = false; void Awake() { Actions = GetComponent<ActionManager>(); } void Start() { var tgt = GameObject.FindGameObjectsWithTag("HomingTarget"); Targets = tgt; TgtDebug = tgt; Icon.parent = null; UpdateHomingTargets(); } void LateUpdate() { if (!firstime) { firstime = true; UpdateHomingTargets(); } } void FixedUpdate() { UpdateHomingTargets(); //Prevent Homing attack spamming HomingCount += 1; if (Actions.Action == 2) { HomingAvailable = false; HomingCount = 0; } if (HomingCount > 3) { HomingAvailable = true; } //SetIconPosition TargetObject = GetClosestTarget(Targets, TargetSearchDistance); if (HasTarget) { Icon.position = TargetObject.transform.position; float camDist = Vector3.Distance(transform.position, MainCamera.position); Icon.localScale = (Vector3.one * IconScale) + (Vector3.one * (camDist * IconDistanceScaling)); } else { Icon.localScale = Vector3.zero; } } //This function will look for every possible homing attack target in the whole level. //And you can call it from other scritps via [ HomingAttackControl.UpdateHomingTargets() ] public static void UpdateHomingTargets() { var tgt = GameObject.FindGameObjectsWithTag("HomingTarget"); Targets = tgt; } GameObject GetClosestTarget(GameObject[] tgts, float maxDistance) { HasTarget = false; GameObject[] gos = tgts; GameObject closest = null; float distance = maxDistance; Vector3 position = transform.position; foreach (GameObject go in gos) { Vector3 diff = go.transform.position - position; float curDistance = diff.sqrMagnitude; if (curDistance < distance) { HasTarget = true; closest = go; distance = curDistance; } } //Debug.Log(closest); return closest; } }
25.107143
106
0.584282
[ "BSD-3-Clause" ]
dudemancart456/HedgePhysics
HedgePhysics/Assets/GameplayScripts/HomingAttackControl.cs
2,814
C#
using System; namespace nats_ui.Data.Scripts { public abstract class AbstractScriptCommand : IScriptCommand { public virtual string ParamName1 { get; } = null; public virtual string ParamName2 { get; } = null; public string Name => GetType().Name; public string Param1 { get; set; } public string Param2 { get; set; } public bool Checked { get; set; } public string Result { get; set; } public ExecutionStatus Status { get; set; } = ExecutionStatus.Unknown; public DateTime TimeStamp { get; set; } public TimeSpan Duration { get; set; } public virtual string Execute(NatsService natsService, ExecutorService executorService) { return "Ok"; } public override string ToString() { return $"{Name}, {ParamName1}: {Param1?.Substring(0, Math.Min(100, Param1.Length))}, {ParamName2}: {Param2?.Substring(0, Math.Min(100, Param2.Length))}"; } } }
33.566667
165
0.613704
[ "Unlicense" ]
fremag/nats-ui
Data/Scripts/AbstractScriptCommand.cs
1,007
C#
using MedianFinder.Managers; using MedianFinder.Services; using Moq; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace MedianFinder.Test.Unit.Managers { public class FolderManagerTest : IDisposable { Mock<IFolderParserService> moqFolderParserService = null; public FolderManagerTest() { moqFolderParserService = new Mock<IFolderParserService>(); } public void Dispose() { moqFolderParserService = null; } public static IEnumerable<object[]> GetFiles() { //THE TEST DATA STRUCTURE //IEnumerable<string> filesList, int countOfFiles //All valid files yield return new object[] { new string[] { "C:\\LP_1.csv", "C:\\LP_2.csv", "C:\\TOU_1.csv" }, 3 }; //All invalid files yield return new object[] { new string[] { "C:\\1.csv", "C:\\2.csv", "C:\\Xyz1.csv" }, 0 }; //Only LP yield return new object[] { new string[] { "C:\\LP_e.csv", "C:\\file2.csv", "C:\\file3.csv", "C:\\file4.csv" }, 1 }; //Only TOU yield return new object[] { new string[] { "C:\\file1.csv", "C:\\file2.csv", "C:\\file3.csv", "C:\\TOU_ff.csv" }, 1 }; //LP, TOU and invalid files yield return new object[] { new string[] { "C:\\file1.csv", "C:\\LP_1.csv", "C:\\file3.csv", "C:\\TOU_1_.csv" }, 2 }; //No files found yield return new object[] { null, 0 }; } [Theory] [MemberData(nameof(GetFiles))] public void GetAllFiles_returns_all_valid_files_based_on_configured_filetypes(IEnumerable<string> filesList, int countOfFiles) { //given moqFolderParserService.Setup(m => m.GetFileNamesFromFolder(It.IsAny<string>(), It.Is<string>(p => p == "*.csv"))).Returns(filesList); var sut = new FolderManager(moqFolderParserService.Object); var fileTypes = new Dictionary<string, string>() { {"TOU","Energy" }, {"LP","Data Value" } }; var sourceFolderPath = "D:\\Sample files"; var fileFormat = "*.csv"; //when var actual = sut.GetAllFiles(sourceFolderPath, fileFormat, fileTypes); //then int countReturned = actual == null ? 0 : actual.Count(); Assert.Equal(countOfFiles, countReturned); moqFolderParserService.Verify(v => v.GetFileNamesFromFolder(It.IsAny<string>(), It.Is<string>(p => p == "*.csv")), Times.Once); } } }
40.166667
145
0.562052
[ "MIT" ]
singhrahulnet/MedianFinder
MedianFinder.Test/Unit/Managers/FolderManagerTest.cs
2,653
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EasyHackerNews { public partial class Form1 : Form { private NotifyIcon trayIcon; private ContextMenu trayMenu; public Form1() { // Create a simple tray menu with only one item. trayMenu = new ContextMenu(); trayMenu.MenuItems.Add("Exit", OnExit); // Create a tray icon. In this example we use a // standard system icon for simplicity, but you // can of course use your own custom icon too. trayIcon = new NotifyIcon(); trayIcon.Text = "MyTrayApp"; trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40); // Add menu to tray icon and show it. trayIcon.ContextMenu = trayMenu; trayIcon.Visible = true; trayIcon.MouseClick += TrayIcon_MouseClick; InitializeComponent(); } private void TrayIcon_MouseClick(object sender, MouseEventArgs e) { this.Show(); this.TopMost = true; this.Focus();// BUG: This is only working for the very first time. After that not in focus } protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); this.Hide(); } protected override void OnLoad(EventArgs e) { Visible = false; // Hide form window. ShowInTaskbar = false; // Remove from taskbar. PlaceLowerRight(); base.OnLoad(e); } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="isDisposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool isDisposing) { if (isDisposing) { if (components != null) { components.Dispose(); } // Release the icon resource. trayIcon.Dispose(); } base.Dispose(isDisposing); } private void OnExit(object sender, EventArgs e) { Application.Exit(); } private void PlaceLowerRight() { //Determine "rightmost" screen //Screen rightmost = Screen.AllScreens[0]; Screen rightmost = Screen.PrimaryScreen; //foreach (Screen screen in Screen.AllScreens) //{ // if (screen.WorkingArea.Right > rightmost.WorkingArea.Right) // rightmost = screen; //} this.Left = rightmost.WorkingArea.Right - this.Width; this.Top = rightmost.WorkingArea.Bottom - this.Height; } } }
29.203883
109
0.551197
[ "MIT" ]
amit-mittal/Easy-HackerNews
src/Form1.cs
3,010
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Numerics; namespace CalcIP { public static class Split { public static int PerformSplit(string[] args) { if (args.Length < 3) { Program.UsageAndExit(); } var ipv4Match = Program.IPv4WithCidrRegex.Match(args[1]); if (ipv4Match.Success) { Tuple<IPv4Address, IPv4Network> addressAndNet = Program.ParseIPv4CidrSpec(ipv4Match); if (addressAndNet == null) { return 1; } Console.WriteLine("Subnet to split:"); ShowNet.OutputIPv4Network(addressAndNet.Item2, addressAndNet.Item2.BaseAddress); Console.WriteLine(); BigInteger[] splits = ParseHostCountSpecs(args); if (splits == null) { return 1; } IPNetwork<IPv4Address>[] subnets = SplitSubnet(addressAndNet.Item2, splits, (addr, cidr) => new IPv4Network(addr, cidr)); if (subnets == null) { Console.WriteLine("Not enough addresses available for this split."); return 0; } foreach (Tuple<BigInteger, IPNetwork<IPv4Address>> splitAndSubnet in splits.Zip(subnets, Tuple.Create)) { Console.WriteLine("Subnet for {0} hosts:", splitAndSubnet.Item1); ShowNet.OutputIPv4Network(splitAndSubnet.Item2); Console.WriteLine(); } Console.WriteLine("Unused networks:"); var maxUsedAddress = subnets .Select(s => s.LastAddressOfSubnet) .Max(); var nextUnusedAddress = maxUsedAddress.Add(1); List<IPNetwork<IPv4Address>> unusedSubnets = Derange.RangeToSubnets(nextUnusedAddress, addressAndNet.Item2.LastAddressOfSubnet, (addr, cidr) => new IPv4Network(addr, cidr)); foreach (IPNetwork<IPv4Address> unusedSubnet in unusedSubnets) { Console.WriteLine("{0}/{1}", unusedSubnet.BaseAddress, unusedSubnet.CidrPrefix.Value); } return 0; } var ipv6Match = Program.IPv6WithCidrRegex.Match(args[1]); if (ipv6Match.Success) { Tuple<IPv6Address, IPv6Network> addressAndNet = Program.ParseIPv6CidrSpec(ipv6Match); if (addressAndNet == null) { return 1; } Console.WriteLine("Subnet to split:"); ShowNet.OutputIPv6Network(addressAndNet.Item2, addressAndNet.Item2.BaseAddress); BigInteger[] splits = ParseHostCountSpecs(args); if (splits == null) { return 1; } IPNetwork<IPv6Address>[] subnets = SplitSubnet(addressAndNet.Item2, splits, (addr, cidr) => new IPv6Network(addr, cidr)); if (subnets == null) { Console.WriteLine("Not enough addresses available for this split."); return 0; } foreach (Tuple<BigInteger, IPNetwork<IPv6Address>> splitAndSubnet in splits.Zip(subnets, Tuple.Create)) { Console.WriteLine("Subnet for {0} hosts:", splitAndSubnet.Item1); ShowNet.OutputIPv6Network(addressAndNet.Item2); Console.WriteLine(); } Console.WriteLine("Unused networks:"); var maxUsedAddress = subnets .Select(s => s.LastAddressOfSubnet) .Max(); var nextUnusedAddress = maxUsedAddress.Add(1); List<IPNetwork<IPv6Address>> unusedSubnets = Derange.RangeToSubnets(nextUnusedAddress, addressAndNet.Item2.SubnetMask, (addr, cidr) => new IPv6Network(addr, cidr)); foreach (IPNetwork<IPv6Address> unusedSubnet in unusedSubnets) { Console.WriteLine("{0}/{1}", unusedSubnet.BaseAddress, unusedSubnet.CidrPrefix.Value); } return 0; } Console.Error.WriteLine("Failed to parse {0} as a subnet specification.", args[1]); return 1; } private static BigInteger[] ParseHostCountSpecs(string[] args) { var ret = new BigInteger[args.Length - 2]; for (int i = 0; i < ret.Length; ++i) { if (!BigInteger.TryParse(args[i+2], NumberStyles.None, CultureInfo.InvariantCulture, out ret[i])) { Console.Error.WriteLine("Failed to parse {0} as a number.", args[i+2]); return null; } if (ret[i] < 0) { Console.Error.WriteLine("Host counts must be greater than zero, got {0}.", ret[i]); return null; } } return ret; } public static IPNetwork<TAddress>[] SplitSubnet<TAddress>(IPNetwork<TAddress> subnet, BigInteger[] hostCounts, Func<TAddress, int, IPNetwork<TAddress>> createSubnet) where TAddress : struct, IIPAddress<TAddress> { var ret = new IPNetwork<TAddress>[hostCounts.Length]; // sort descending by size var indexesAndHostCounts = hostCounts .Select((count, i) => Tuple.Create(i, count)) .OrderByDescending(hc => hc.Item2) .ToList(); IPNetwork<TAddress> currentNet = createSubnet(subnet.BaseAddress, 8*subnet.SubnetMask.Bytes.Length); foreach (Tuple<int, BigInteger> indexAndHostCount in indexesAndHostCounts) { while (currentNet.HostCount < indexAndHostCount.Item2 && currentNet.CidrPrefix.Value >= 0) { currentNet = createSubnet(currentNet.BaseAddress, currentNet.CidrPrefix.Value - 1); } if (currentNet.CidrPrefix.Value == 0) { // this won't fit return null; } // we fit! ret[indexAndHostCount.Item1] = currentNet; currentNet = createSubnet(currentNet.NextSubnetBaseAddress, 8*subnet.SubnetMask.Bytes.Length); } return ret; } } }
38.693182
119
0.520999
[ "CC0-1.0" ]
RavuAlHemio/CalcIP
src/CalcIP/Split.cs
6,810
C#
//=================================================== // ファイル名 :Car.cs // 概要 :ギアの制御 // 作成者 :謝 敬鴻 // 作成日 :2019.03.29 //=================================================== using UnityEngine; namespace AIM { public class Gearbox : MonoBehaviour { [Header("パラメータ")] public float[] gearRatio; public float finalGear; public int currentGear; } }
17.181818
54
0.433862
[ "MIT" ]
17cuA/AimRacing11
AimRacing2019_05_31/AimRacing2019_05_31/Assets/Course/Scripts/Car/Gearbox.cs
440
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("1.Exchange-Values")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1.Exchange-Values")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("26907df4-6aa4-4fab-8a69-850b7a822885")] // 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")]
38.027027
84
0.744136
[ "MIT" ]
bstaykov/Telerik-CSharp-Part-1
Conditional-Statements/1.Exchange-Values/Properties/AssemblyInfo.cs
1,410
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.Formatting; namespace Microsoft.DotNet.Interactive.Events { public class DisplayedValue { private readonly string _displayId; private readonly string _mimeType; private KernelInvocationContext _context; public DisplayedValue(string displayId, string mimeType, KernelInvocationContext context) { if (string.IsNullOrWhiteSpace(displayId)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(displayId)); } if (string.IsNullOrWhiteSpace(mimeType)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(mimeType)); } _displayId = displayId; _mimeType = mimeType; _context = context ?? throw new ArgumentNullException(nameof(context)); } public void Update(object updatedValue) { var formatted = new FormattedValue( _mimeType, updatedValue.ToDisplayString(_mimeType)); if (KernelInvocationContext.Current?.Command is SubmitCode) { _context = KernelInvocationContext.Current; } _context.Publish(new DisplayedValueUpdated(updatedValue, _displayId, _context.Command, new[] { formatted })); } } }
34.93617
121
0.642509
[ "MIT" ]
AngelusGi/interactive
src/Microsoft.DotNet.Interactive/Events/DisplayedValue.cs
1,644
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.ApiManagement.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Api Release details. /// </summary> [Rest.Serialization.JsonTransformation] public partial class ApiReleaseContract : Resource { /// <summary> /// Initializes a new instance of the ApiReleaseContract class. /// </summary> public ApiReleaseContract() { CustomInit(); } /// <summary> /// Initializes a new instance of the ApiReleaseContract class. /// </summary> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type for API Management /// resource.</param> /// <param name="apiId">Identifier of the API the release belongs /// to.</param> /// <param name="createdDateTime">The time the API was released. The /// date conforms to the following format: yyyy-MM-ddTHH:mm:ssZ as /// specified by the ISO 8601 standard.</param> /// <param name="updatedDateTime">The time the API release was /// updated.</param> /// <param name="notes">Release Notes</param> public ApiReleaseContract(string id = default(string), string name = default(string), string type = default(string), string apiId = default(string), System.DateTime? createdDateTime = default(System.DateTime?), System.DateTime? updatedDateTime = default(System.DateTime?), string notes = default(string)) : base(id, name, type) { ApiId = apiId; CreatedDateTime = createdDateTime; UpdatedDateTime = updatedDateTime; Notes = notes; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets identifier of the API the release belongs to. /// </summary> [JsonProperty(PropertyName = "properties.apiId")] public string ApiId { get; set; } /// <summary> /// Gets the time the API was released. The date conforms to the /// following format: yyyy-MM-ddTHH:mm:ssZ as specified by the ISO 8601 /// standard. /// </summary> [JsonProperty(PropertyName = "properties.createdDateTime")] public System.DateTime? CreatedDateTime { get; private set; } /// <summary> /// Gets the time the API release was updated. /// </summary> [JsonProperty(PropertyName = "properties.updatedDateTime")] public System.DateTime? UpdatedDateTime { get; private set; } /// <summary> /// Gets or sets release Notes /// </summary> [JsonProperty(PropertyName = "properties.notes")] public string Notes { get; set; } } }
37.766667
312
0.616652
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SDKs/ApiManagement/Management.ApiManagement/Generated/Models/ApiReleaseContract.cs
3,399
C#
using System; using BEPUphysics.Entities; using BEPUutilities; namespace BEPUphysics.Constraints.SingleEntity { /// <summary> /// Prevents the target entity from moving faster than the specified speeds. /// </summary> public class MaximumLinearSpeedConstraint : SingleEntityConstraint, I3DImpulseConstraint { private float effectiveMassMatrix; private float maxForceDt = float.MaxValue; private float maxForceDtSquared = float.MaxValue; private Vector3 accumulatedImpulse; private float maximumForce = float.MaxValue; private float maximumSpeed; private float maximumSpeedSquared; private float softness = .00001f; private float usedSoftness; /// <summary> /// Constructs a maximum speed constraint. /// Set its Entity and MaximumSpeed to complete the configuration. /// IsActive also starts as false with this constructor. /// </summary> public MaximumLinearSpeedConstraint() { IsActive = false; } /// <summary> /// Constructs a maximum speed constraint. /// </summary> /// <param name="e">Affected entity.</param> /// <param name="maxSpeed">Maximum linear speed allowed.</param> public MaximumLinearSpeedConstraint(Entity e, float maxSpeed) { Entity = e; MaximumSpeed = maxSpeed; } /// <summary> /// Gets and sets the maximum impulse that the constraint will attempt to apply when satisfying its requirements. /// This field can be used to simulate friction in a constraint. /// </summary> public float MaximumForce { get { if (maximumForce > 0) { return maximumForce; } return 0; } set { maximumForce = value >= 0 ? value : 0; } } /// <summary> /// Gets or sets the maximum linear speed that this constraint allows. /// </summary> public float MaximumSpeed { get { return maximumSpeed; } set { maximumSpeed = MathHelper.Max(0, value); maximumSpeedSquared = maximumSpeed * maximumSpeed; } } /// <summary> /// Gets and sets the softness of this constraint. /// Higher values of softness allow the constraint to be violated more. /// Must be greater than zero. /// Sometimes, if a joint system is unstable, increasing the softness of the involved constraints will make it settle down. /// For motors, softness can be used to implement damping. For a damping constant k, the appropriate softness is 1/k. /// </summary> public float Softness { get { return softness; } set { softness = Math.Max(0, value); } } #region I3DImpulseConstraint Members /// <summary> /// Gets the current relative velocity with respect to the constraint. /// For a single entity constraint, this is pretty straightforward as the /// velocity of the entity. /// </summary> Vector3 I3DImpulseConstraint.RelativeVelocity { get { return Entity.LinearVelocity; } } /// <summary> /// Gets the total impulse applied by the constraint. /// </summary> public Vector3 TotalImpulse { get { return accumulatedImpulse; } } #endregion /// <summary> /// Calculates and applies corrective impulses. /// Called automatically by space. /// </summary> public override float SolveIteration() { float linearSpeed = entity.linearVelocity.LengthSquared(); if (linearSpeed > maximumSpeedSquared) { linearSpeed = (float) Math.Sqrt(linearSpeed); Vector3 impulse; //divide by linearSpeed to normalize the velocity. //Multiply by linearSpeed - maximumSpeed to get the 'velocity change vector.' Vector3.Multiply(ref entity.linearVelocity, -(linearSpeed - maximumSpeed) / linearSpeed, out impulse); //incorporate softness Vector3 softnessImpulse; Vector3.Multiply(ref accumulatedImpulse, usedSoftness, out softnessImpulse); Vector3.Subtract(ref impulse, ref softnessImpulse, out impulse); //Transform into impulse Vector3.Multiply(ref impulse, effectiveMassMatrix, out impulse); //Accumulate Vector3 previousAccumulatedImpulse = accumulatedImpulse; Vector3.Add(ref accumulatedImpulse, ref impulse, out accumulatedImpulse); float forceMagnitude = accumulatedImpulse.LengthSquared(); if (forceMagnitude > maxForceDtSquared) { //max / impulse gives some value 0 < x < 1. Basically, normalize the vector (divide by the length) and scale by the maximum. float multiplier = maxForceDt / (float) Math.Sqrt(forceMagnitude); accumulatedImpulse.X *= multiplier; accumulatedImpulse.Y *= multiplier; accumulatedImpulse.Z *= multiplier; //Since the limit was exceeded by this corrective impulse, limit it so that the accumulated impulse remains constrained. impulse.X = accumulatedImpulse.X - previousAccumulatedImpulse.X; impulse.Y = accumulatedImpulse.Y - previousAccumulatedImpulse.Y; impulse.Z = accumulatedImpulse.Z - previousAccumulatedImpulse.Z; } entity.ApplyLinearImpulse(ref impulse); return (Math.Abs(impulse.X) + Math.Abs(impulse.Y) + Math.Abs(impulse.Z)); } return 0; } /// <summary> /// Calculates necessary information for velocity solving. /// Called automatically by space. /// </summary> /// <param name="dt">Time in seconds since the last update.</param> public override void Update(float dt) { usedSoftness = softness / dt; effectiveMassMatrix = 1 / (entity.inverseMass + usedSoftness); //Determine maximum force if (maximumForce < float.MaxValue) { maxForceDt = maximumForce * dt; maxForceDtSquared = maxForceDt * maxForceDt; } else { maxForceDt = float.MaxValue; maxForceDtSquared = float.MaxValue; } } /// <summary> /// Performs any pre-solve iteration work that needs exclusive /// access to the members of the solver updateable. /// Usually, this is used for applying warmstarting impulses. /// </summary> public override void ExclusiveUpdate() { //Can't do warmstarting due to the strangeness of this constraint (not based on a position error, nor is it really a motor). accumulatedImpulse = Toolbox.ZeroVector; } } }
38.130653
146
0.563785
[ "Apache-2.0" ]
Anomalous-Software/BEPUPhysics
BEPUphysics/Constraints/SingleEntity/MaximumLinearVelocityConstraint.cs
7,590
C#
using System; using System.Collections; using System.Collections.Generic; using Intel.RealSense; using UnityEngine; public abstract class RsFrameProvider : MonoBehaviour { public bool Streaming { get; protected set; } public PipelineProfile ActiveProfile { get; protected set; } public abstract event Action<PipelineProfile> OnStart; public abstract event Action OnStop; public abstract event Action<Frame> OnNewSample; }
26.176471
64
0.777528
[ "Apache-2.0" ]
Kare-em/Rsvfx
Assets/RealSenseSDK2.0/Scripts/RsFrameProvider.cs
445
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Exchange.Infrastructure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Exchange.Infrastructure")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("86098f2e-5367-4651-953f-2ea33a56541f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.891892
84
0.747504
[ "MIT" ]
Zabaa/Exchange
Exchange.Infrastructure/Properties/AssemblyInfo.cs
1,404
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Batch { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using Common; using Utils; internal static class UtilitiesInternal { internal static TTo MapEnum<TFrom, TTo>(TFrom otherEnum) where TTo : struct where TFrom : struct { TTo result = (TTo)Enum.Parse(typeof(TTo), otherEnum.ToString(), ignoreCase: true); return result; } internal static TTo? MapNullableEnum<TFrom, TTo>(TFrom? otherEnum) where TTo : struct where TFrom : struct { if (otherEnum == null) { return null; } return UtilitiesInternal.MapEnum<TFrom, TTo>(otherEnum.Value); } /// <summary> /// Convert an enum of type CertificateVisibility to a List of Protocol.Models.CertificateVisibility. /// </summary> /// <param name='value'> /// The value to convert. /// </param> /// <returns> /// The enum value to convert into list format. /// </returns> internal static IList<Protocol.Models.CertificateVisibility?> CertificateVisibilityToList(Common.CertificateVisibility? value) { List<Protocol.Models.CertificateVisibility?> result = new List<Protocol.Models.CertificateVisibility?>(); if (value.HasValue) { IList<Common.CertificateVisibility> enumValues = new List<Common.CertificateVisibility>( (Common.CertificateVisibility[])Enum.GetValues(typeof(Common.CertificateVisibility))); enumValues.Remove(Common.CertificateVisibility.None); //None is an artifact of the OM so skip it foreach (Common.CertificateVisibility enumValue in enumValues) { if (value.Value.HasFlag(enumValue)) { Protocol.Models.CertificateVisibility protoEnumValue = UtilitiesInternal.MapEnum<Common.CertificateVisibility, Protocol.Models.CertificateVisibility>(enumValue); result.Add(protoEnumValue); } } } return result; } /// <summary> /// Convert an enum of type AccessScope to a List of Protocol.Models.AccessScope. /// </summary> /// <param name='value'> /// The value to convert. /// </param> /// <returns> /// The enum value to convert into list format. /// </returns> internal static IList<Protocol.Models.AccessScope?> AccessScopeToList(Common.AccessScope value) { List<Protocol.Models.AccessScope?> result = new List<Protocol.Models.AccessScope?>(); IList<Common.AccessScope> enumValues = new List<Common.AccessScope>((Common.AccessScope[])Enum.GetValues(typeof(Common.AccessScope))); enumValues.Remove(Common.AccessScope.None); //None is an artifact of the OM so skip it foreach (Common.AccessScope enumValue in enumValues) { if (value.HasFlag(enumValue)) { Protocol.Models.AccessScope protoEnumValue = UtilitiesInternal.MapEnum<Common.AccessScope, Protocol.Models.AccessScope>(enumValue); result.Add(protoEnumValue); } } return result; } /// <summary> /// Parse enum values for type CertificateVisibility. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static Common.CertificateVisibility? ParseCertificateVisibility(IList<Protocol.Models.CertificateVisibility?> value) { if (value == null) { return null; } Common.CertificateVisibility flags = CertificateVisibility.None; foreach (Protocol.Models.CertificateVisibility? visibility in value) { Common.CertificateVisibility? convertedEnum = UtilitiesInternal.MapNullableEnum<Protocol.Models.CertificateVisibility, Common.CertificateVisibility>(visibility); if (convertedEnum.HasValue) { flags |= convertedEnum.Value; } } return flags; } /// <summary> /// Parse enum values for type AccessScope. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static Common.AccessScope ParseAccessScope(IList<Protocol.Models.AccessScope?> value) { if (value == null) { return Common.AccessScope.None; } Common.AccessScope flags = AccessScope.None; foreach (Protocol.Models.AccessScope? visibility in value) { Common.AccessScope? convertedEnum = UtilitiesInternal.MapNullableEnum<Protocol.Models.AccessScope, Common.AccessScope>(visibility); if (convertedEnum.HasValue) { flags |= convertedEnum.Value; } } return flags; } internal static void ThrowOnUnbound(BindingState bindingState) { if (BindingState.Unbound == bindingState) { throw OperationForbiddenOnUnboundObjects; } } internal static TWrappedItem CreateObjectWithNullCheck<TItem, TWrappedItem>(TItem item, Func<TItem, TWrappedItem> factory, Func<TWrappedItem> nullFactory = null) where TItem : class where TWrappedItem : class { if (item == null) { if (nullFactory != null) { return nullFactory(); } else { return null; } } else { return factory(item); } } #region Collection conversions /// <summary> /// Converts a collection of object model items into a corresponding collection of transport layer items. /// If the <paramref name="items"/> collection is null, null is returned. /// </summary> /// <returns> /// A collection of type <typeparam name="T"/> generated by calling /// <see cref="ITransportObjectProvider{T}.GetTransportObject"/> on each element of the input collection. /// </returns> internal static IList<T> ConvertToProtocolCollection<T>(IEnumerable<ITransportObjectProvider<T>> items) { if (null == items) { return null; } List<T> protocolItems = new List<T>(); foreach (ITransportObjectProvider<T> item in items) { T protocolItem = item.GetTransportObject(); // add the protocol object to the return collection protocolItems.Add(protocolItem); } return protocolItems; } /// <summary> /// Converts a collection of object model items into a corresponding array of transport layer items. /// If the <paramref name="items"/> collection is null, null is returned. /// </summary> /// <returns> /// A collection of type <typeparam name="T"/> generated by calling /// <see cref="ITransportObjectProvider{T}.GetTransportObject"/> on each element of the input collection. /// </returns> internal static T[] ConvertToProtocolArray<T>(IEnumerable<ITransportObjectProvider<T>> items) { IEnumerable<T> protocolCollection = ConvertToProtocolCollection(items); if (protocolCollection != null) { return protocolCollection.ToArray(); } else { return null; } } internal static IList<TTo> ConvertEnumCollection<TFrom, TTo>(IEnumerable<TFrom> items) where TFrom : struct where TTo : struct { return items?.Select(MapEnum<TFrom, TTo>).ToList(); } internal static IList<TTo?> ConvertEnumCollection<TFrom, TTo>(IEnumerable<TFrom?> items) where TFrom : struct where TTo : struct { return items?.Select(MapNullableEnum<TFrom, TTo>).ToList(); } private static TList ConvertCollection<TIn, TOut, TList>( IEnumerable<TIn> items, Func<TIn, TOut> objectCreationFunc, Func<IEnumerable<TOut>, TList> listCreationFunc) where TList : class, IList<TOut> where TIn : class where TOut : class { if (null == items) { return null; } TList result = listCreationFunc(items.Select(item => item == null ? null : objectCreationFunc(item))); return result; } /// <summary> /// Applies the <paramref name="objectCreationFunc"/> to each item in <paramref name="items"/> and returns a non-threadsafe collection containing the results. /// </summary> /// <typeparam name="TIn">The type of the input collection.</typeparam> /// <typeparam name="TOut">The type of the output collection.</typeparam> /// <param name="items">The collection to convert.</param> /// <param name="objectCreationFunc">The function used to created each <typeparamref name="TOut"/> type object.</param> /// <returns>A non-threadsafe collection containing the results of the conversion, or null if <paramref name="items"/> was null.</returns> internal static List<TOut> CollectionToNonThreadSafeCollection<TIn, TOut>( IEnumerable<TIn> items, Func<TIn, TOut> objectCreationFunc) where TIn : class where TOut : class { List<TOut> result = UtilitiesInternal.ConvertCollection( items, objectCreationFunc, (convertedItemsEnumerable) => new List<TOut>(convertedItemsEnumerable)); return result; } /// <summary> /// Applies the <paramref name="objectCreationFunc"/> to each item in <paramref name="items"/> and returns a threadsafe collection containing the results. /// </summary> /// <typeparam name="TIn">The type of the input collection.</typeparam> /// <typeparam name="TOut">The type of the output collection.</typeparam> /// <param name="items">The collection to convert.</param> /// <param name="objectCreationFunc">The function used to created each <typeparamref name="TOut"/> type object.</param> /// <returns>A threadsafe collection containing the results of the conversion, or null if <paramref name="items"/> was null.</returns> internal static ConcurrentChangeTrackedModifiableList<TOut> CollectionToThreadSafeCollectionIModifiable<TIn, TOut>( IEnumerable<TIn> items, Func<TIn, TOut> objectCreationFunc) where TIn : class where TOut : class, IPropertyMetadata { ConcurrentChangeTrackedModifiableList<TOut> result = UtilitiesInternal.ConvertCollection( items, objectCreationFunc, (convertedItemsEnumerable) => new ConcurrentChangeTrackedModifiableList<TOut>(convertedItemsEnumerable)); return result; } #endregion internal static Exception OperationForbiddenOnUnboundObjects { get { return new InvalidOperationException(BatchErrorMessages.OperationForbiddenOnUnboundObjects); } } internal static Exception OperationForbiddenOnBoundObjects { get { return new InvalidOperationException(BatchErrorMessages.OperationForbiddenOnBoundObjects); } } internal static Exception MonitorRequiresConsistentHierarchyChain { get { return new InvalidOperationException(BatchErrorMessages.MonitorInstancesMustHaveSameServerSideParent); } } internal static Exception IncorrectTypeReturned { get { return new InvalidOperationException(BatchErrorMessages.IncorrectTypeReturned); } } /// <summary> /// Reads entire Stream into a string. When null encoding is provided, UTF8 is used. /// </summary> /// <param name="s"></param> /// <param name="encoding"></param> /// <returns></returns> internal static string StreamToString(Stream s, Encoding encoding) { if (null == encoding) { encoding = Encoding.UTF8; } //Avoid disposing of the underlying stream -- the streams lifetime is not owned by this method //and disposing the reader will dispose the underlying stream. //Note: detectEncodingFromByteOrderMarks default is true, and bufferSize default is 1024, we have to pass those here in order to //get access to the leaveOpen parameter. using (StreamReader reader = new StreamReader(s, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { string txt = reader.ReadToEnd(); return txt; } } /// <summary> /// Enumerates an enumerable asyncronously if required. If the enumerable is of type IPagedCollection(T) then /// ToListAsync is called on it. Otherwise the enumerable is returned as is. /// </summary> internal static async Task<IEnumerable<T>> EnumerateIfNeededAsync<T>(IEnumerable<T> enumerable, CancellationToken cancellationToken) { IEnumerable<T> result; IPagedEnumerable<T> pagedEnumerable = enumerable as IPagedEnumerable<T>; if (pagedEnumerable != null) { result = await pagedEnumerable.ToListAsync(cancellationToken).ConfigureAwait(false); } else { result = enumerable; } return result; } internal static void WaitAndUnaggregateException(this Task task) { task.GetAwaiter().GetResult(); } internal static T WaitAndUnaggregateException<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } internal static void WaitAndUnaggregateException(this Task task, IEnumerable<BatchClientBehavior> rootBehaviors, IEnumerable<BatchClientBehavior> additionalBehaviors) { BehaviorManager bhMgr = new BehaviorManager(rootBehaviors, additionalBehaviors); SynchronousMethodExceptionBehavior exceptionBehavior = bhMgr.GetBehaviors<SynchronousMethodExceptionBehavior>().LastOrDefault(); if (exceptionBehavior != null) { exceptionBehavior.Wait(task); } else { task.WaitAndUnaggregateException(); } } internal static T WaitAndUnaggregateException<T>(this Task<T> task, IEnumerable<BatchClientBehavior> rootBehaviors, IEnumerable<BatchClientBehavior> additionalBehaviors) { BehaviorManager bhMgr = new BehaviorManager(rootBehaviors, additionalBehaviors); SynchronousMethodExceptionBehavior exceptionBehavior = bhMgr.GetBehaviors<SynchronousMethodExceptionBehavior>().LastOrDefault(); T result; if (exceptionBehavior != null) { exceptionBehavior.Wait(task); result = task.Result; } else { result = task.WaitAndUnaggregateException(); } return result; } /// <summary> /// Gets the object if the property has been changed, otherwise returns null. /// </summary> /// <exception cref="InvalidOperationException">When the property was changed to null, since the patch REST verb does not support that today in Batch.</exception> internal static T? GetIfChangedOrNull<T>(this PropertyAccessor<T?> property) where T : struct { if (property.HasBeenModified) { if (property.Value == null) { throw new InvalidOperationException(BatchErrorMessages.CannotPatchNullValue); } return property.Value; } else { return null; } } /// <summary> /// Gets the transport object if the property has been changed, otherwise returns null. /// </summary> /// <exception cref="InvalidOperationException">When the property was changed to null, since the patch REST verb does not support that today in Batch.</exception> internal static TProtocol GetTransportObjectIfChanged<TObjectModel, TProtocol>(this PropertyAccessor<TObjectModel> property) where TObjectModel : class, ITransportObjectProvider<TProtocol> where TProtocol : class { if (property.HasBeenModified) { if (property.Value == null) { throw new InvalidOperationException(BatchErrorMessages.CannotPatchNullValue); } return CreateObjectWithNullCheck(property.Value, item => item.GetTransportObject()); } else { return null; } } /// <summary> /// Gets the transport object if the property has been changed, otherwise returns null. /// </summary> /// <exception cref="InvalidOperationException">When the property was changed to null, since the patch REST verb does not support that today in Batch.</exception> internal static TProtocol[] GetTransportObjectIfChanged<TObjectModel, TProtocol>(this PropertyAccessor<IList<TObjectModel>> property) where TObjectModel : class, ITransportObjectProvider<TProtocol> where TProtocol : class { if (property.HasBeenModified) { if (property.Value == null) { throw new InvalidOperationException(BatchErrorMessages.CannotPatchNullValue); } return ConvertToProtocolArray(property.Value); } else { return null; } } } }
38.305284
185
0.57934
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/Batch/Client/Src/Azure.Batch/UtilitiesInternal.cs
19,576
C#
using DerekHoneycutt.Data.Services.Interface; using MailKit.Net.Smtp; using Microsoft.Extensions.Options; using MimeKit; using MimeKit.Text; using System.Threading.Tasks; namespace DerekHoneycutt.Data.Services.Implementation { /// <summary> /// Email service for sending emails to users /// </summary> public class EmailService : IEmailService { /// <summary> /// SMTP settings for the application /// </summary> private readonly IOptions<Options.SmtpSettings> SmtpSettings; public EmailService(IOptions<Options.SmtpSettings> smtpSettings) { SmtpSettings = smtpSettings; } /// <summary> /// Send an email from the application /// </summary> /// <param name="to">Address to send the email to</param> /// <param name="subject">Subject of the email to send</param> /// <param name="html">HTML Body of the email to send</param> /// <param name="from">Address of the sender for the email</param> public async Task Send(string to, string subject, string html, string from = null) { var settings = SmtpSettings.Value; var email = new MimeMessage(); email.From.Add(MailboxAddress.Parse(from ?? settings.EmailFrom)); email.To.Add(MailboxAddress.Parse(to)); email.Subject = subject; email.Body = new TextPart(TextFormat.Html) { Text = html }; using var smtp = new SmtpClient(); await smtp.ConnectAsync(settings.Server, settings.Port); await smtp.AuthenticateAsync(settings.Username, settings.Password); await smtp.SendAsync(email); await smtp.DisconnectAsync(true); } } }
36.142857
90
0.6262
[ "Unlicense" ]
derekshoneycutt/DerekHoneycu
DerekHoneycutt.Data/Services/Implementation/EmailService.cs
1,773
C#
using Facebook.CSSLayout; using System.Collections.Generic; using System.Linq; namespace ReactNative.UIManager { /// <summary> /// Property keys for React views. /// </summary> public static class ViewProps { #pragma warning disable CS1591 public const string ViewClassName = "RCTView"; // Layout only (only affect positions of children, causes no drawing) // !!! Keep in sync with s_layoutOnlyProperties below !!! public const string AlignItems = "alignItems"; public const string AlignSelf = "alignSelf"; public const string Bottom = "bottom"; public const string Collapsible = "collapsable"; public const string Flex = "flex"; public const string FlexDirection = "flexDirection"; public const string FlexWrap = "flexWrap"; public const string Height = "height"; public const string JustifyContent = "justifyContent"; public const string Left = "left"; public const string Margin = "margin"; public const string MarginVertical = "marginVertical"; public const string MarginHorizontal = "marginHorizontal"; public const string MarginLeft = "marginLeft"; public const string MarginRight = "marginRight"; public const string MarginTop = "marginTop"; public const string MarginBottom = "marginBottom"; public const string Padding = "padding"; public const string PaddingVertical = "paddingVertical"; public const string PaddingHorizontal = "paddingHorizontal"; public const string PaddingLeft = "paddingLeft"; public const string PaddingRight = "paddingRight"; public const string PaddingTop = "paddingTop"; public const string PaddingBottom = "paddingBottom"; public const string PointerEvents = "pointerEvents"; public const string Position = "position"; public const string Right = "right"; public const string Top = "top"; public const string Width = "width"; public const string MinWidth = "minWidth"; public const string MaxWidth = "maxWidth"; public const string MinHeight = "minHeight"; public const string MaxHeight = "maxHeight"; // Properties that affect more than just layout public const string Disabled = "disabled"; public const string BackgroundColor = "backgroundColor"; public const string Color = "color"; public const string FontSize = "fontSize"; public const string FontWeight = "fontWeight"; public const string FontStyle = "fontStyle"; public const string FontFamily = "fontFamily"; public const string LetterSpacing = "letterSpacing"; public const string LineHeight = "lineHeight"; public const string NeedsOffScreenAlphaCompositing = "needsOffscreenAlphaCompositing"; public const string NumberOfLines = "numberOfLines"; public const string Value = "value"; public const string ResizeMode = "resizeMode"; public const string TextAlign = "textAlign"; public const string TextAlignVertical = "textAlignVertical"; public const string TextDecorationLine = "textDecorationLine"; public const string BorderWidth = "borderWidth"; public const string BorderLeftWidth = "borderLeftWidth"; public const string BorderTopWidth = "borderTopWidth"; public const string BorderRightWidth = "borderRightWidth"; public const string BorderBottomWidth = "borderBottomWidth"; public const string BorderRadius = "borderRadius"; public const string BorderTopLeftRadius = "borderTopLeftRadius"; public const string BorderTopRightRadius = "borderTopRightRadius"; public const string BorderBottomLeftRadius = "borderBottomLeftRadius"; public const string BorderBottomRightRadius = "borderBottomRightRadius"; #pragma warning restore CS1591 /// <summary> /// Ordered list of margin spacing types. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "IReadOnlyList is immutable.")] public static readonly IReadOnlyList<CSSSpacingType> PaddingMarginSpacingTypes = new List<CSSSpacingType> { CSSSpacingType.All, CSSSpacingType.Vertical, CSSSpacingType.Horizontal, CSSSpacingType.Left, CSSSpacingType.Right, CSSSpacingType.Top, CSSSpacingType.Bottom, }; /// <summary> /// Ordered list of border spacing types. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "IReadOnlyList is immutable.")] public static readonly IReadOnlyList<CSSSpacingType> BorderSpacingTypes = new List<CSSSpacingType> { CSSSpacingType.All, CSSSpacingType.Left, CSSSpacingType.Right, CSSSpacingType.Top, CSSSpacingType.Bottom, }; private static readonly HashSet<string> s_layoutOnlyProperties = new HashSet<string> { AlignItems, AlignSelf, Collapsible, Flex, FlexDirection, FlexWrap, JustifyContent, /* position */ Position, Right, Top, Bottom, Left, /* dimensions */ Width, Height, MinWidth, MaxWidth, MinHeight, MaxHeight, /* margins */ Margin, MarginVertical, MarginHorizontal, MarginLeft, MarginRight, MarginTop, MarginBottom, /* paddings */ Padding, PaddingVertical, PaddingHorizontal, PaddingLeft, PaddingRight, PaddingTop, PaddingBottom, }; /// <summary> /// Checks if the property key is layout-only. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <b>true</b> if the property is layout-only, <b>false</b> otherwise. /// </returns> public static bool IsLayoutOnly(string key) { return s_layoutOnlyProperties.Contains(key); } } }
39.402299
178
0.603559
[ "MIT" ]
samaleksov/one-script-rule-all
react-native-windows/ReactWindows/ReactNative.Shared/UIManager/ViewProps.cs
6,858
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1016_18c2-3912aee9")] public void Method_1016_18c2() { ii(0x1016_18c2, 5); push(0x20); /* push 0x20 */ ii(0x1016_18c7, 5); call(Definitions.sys_check_available_stack_size, 0x4486);/* call 0x10165d52 */ ii(0x1016_18cc, 1); push(ebx); /* push ebx */ ii(0x1016_18cd, 1); push(ecx); /* push ecx */ ii(0x1016_18ce, 1); push(edx); /* push edx */ ii(0x1016_18cf, 1); push(esi); /* push esi */ ii(0x1016_18d0, 1); push(edi); /* push edi */ ii(0x1016_18d1, 1); push(ebp); /* push ebp */ ii(0x1016_18d2, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x1016_18d4, 6); sub(esp, 4); /* sub esp, 0x4 */ ii(0x1016_18da, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x1016_18dd, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_18e0, 4); cmp(memb[ds, eax + 92], 0); /* cmp byte [eax+0x5c], 0x0 */ ii(0x1016_18e4, 2); if(jz(0x1016_18f5, 0xf)) goto l_0x1016_18f5;/* jz 0x101618f5 */ ii(0x1016_18e6, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_18e9, 3); mov(al, memb[ds, eax + 78]); /* mov al, [eax+0x4e] */ ii(0x1016_18ec, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_18f1, 2); test(eax, eax); /* test eax, eax */ ii(0x1016_18f3, 2); if(jnz(0x1016_18fa, 5)) goto l_0x1016_18fa;/* jnz 0x101618fa */ l_0x1016_18f5: ii(0x1016_18f5, 5); jmp(0x1016_19c3, 0xc9); goto l_0x1016_19c3;/* jmp 0x101619c3 */ l_0x1016_18fa: ii(0x1016_18fa, 2); xor(eax, eax); /* xor eax, eax */ ii(0x1016_18fc, 5); mov(al, memb[ds, 0x101c_37c9]); /* mov al, [0x101c37c9] */ ii(0x1016_1901, 3); cmp(eax, 2); /* cmp eax, 0x2 */ ii(0x1016_1904, 6); if(jz(0x1016_19c3, 0xb9)) goto l_0x1016_19c3;/* jz 0x101619c3 */ ii(0x1016_190a, 2); xor(eax, eax); /* xor eax, eax */ ii(0x1016_190c, 5); mov(al, memb[ds, 0x101c_37c9]); /* mov al, [0x101c37c9] */ ii(0x1016_1911, 2); test(eax, eax); /* test eax, eax */ ii(0x1016_1913, 2); if(jnz(0x1016_192c, 0x17)) goto l_0x1016_192c;/* jnz 0x1016192c */ ii(0x1016_1915, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_1918, 3); mov(al, memb[ds, eax + 38]); /* mov al, [eax+0x26] */ ii(0x1016_191b, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1920, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1016_1922, 6); mov(dl, memb[ds, 0x101c_37c8]); /* mov dl, [0x101c37c8] */ ii(0x1016_1928, 2); cmp(edx, eax); /* cmp edx, eax */ ii(0x1016_192a, 2); if(jnz(0x1016_192e, 2)) goto l_0x1016_192e;/* jnz 0x1016192e */ l_0x1016_192c: ii(0x1016_192c, 2); jmp(0x1016_1933, 5); goto l_0x1016_1933;/* jmp 0x10161933 */ l_0x1016_192e: ii(0x1016_192e, 5); jmp(0x1016_19c3, 0x90); goto l_0x1016_19c3;/* jmp 0x101619c3 */ l_0x1016_1933: ii(0x1016_1933, 7); cmp(memd[ds, 0x101c_5624], 0); /* cmp dword [0x101c5624], 0x0 */ ii(0x1016_193a, 2); if(jz(0x1016_1956, 0x1a)) goto l_0x1016_1956;/* jz 0x10161956 */ ii(0x1016_193c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_193f, 3); mov(al, memb[ds, eax + 38]); /* mov al, [eax+0x26] */ ii(0x1016_1942, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1947, 6); imul(eax, eax, 0x247); /* imul eax, eax, 0x247 */ ii(0x1016_194d, 7); cmp(memb[ds, eax + 0x101c_a491], 0); /* cmp byte [eax+0x101ca491], 0x0 */ ii(0x1016_1954, 2); if(jnz(0x1016_1958, 2)) goto l_0x1016_1958;/* jnz 0x10161958 */ l_0x1016_1956: ii(0x1016_1956, 2); jmp(0x1016_195a, 2); goto l_0x1016_195a;/* jmp 0x1016195a */ l_0x1016_1958: ii(0x1016_1958, 2); jmp(0x1016_19c3, 0x69); goto l_0x1016_19c3;/* jmp 0x101619c3 */ l_0x1016_195a: ii(0x1016_195a, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_195d, 3); mov(al, memb[ds, eax + 38]); /* mov al, [eax+0x26] */ ii(0x1016_1960, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1965, 6); imul(eax, eax, 0x247); /* imul eax, eax, 0x247 */ ii(0x1016_196b, 6); mov(al, memb[ds, eax + 0x101c_a490]); /* mov al, [eax+0x101ca490] */ ii(0x1016_1971, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1976, 3); cmp(eax, 2); /* cmp eax, 0x2 */ ii(0x1016_1979, 2); if(jz(0x1016_199c, 0x21)) goto l_0x1016_199c;/* jz 0x1016199c */ ii(0x1016_197b, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_197e, 3); mov(al, memb[ds, eax + 38]); /* mov al, [eax+0x26] */ ii(0x1016_1981, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1986, 6); imul(eax, eax, 0x247); /* imul eax, eax, 0x247 */ ii(0x1016_198c, 6); mov(al, memb[ds, eax + 0x101c_a490]); /* mov al, [eax+0x101ca490] */ ii(0x1016_1992, 5); and(eax, 0xff); /* and eax, 0xff */ ii(0x1016_1997, 3); cmp(eax, 3); /* cmp eax, 0x3 */ ii(0x1016_199a, 2); if(jnz(0x1016_19a5, 9)) goto l_0x1016_19a5;/* jnz 0x101619a5 */ l_0x1016_199c: ii(0x1016_199c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_199f, 4); mov(memb[ds, eax + 92], 0); /* mov byte [eax+0x5c], 0x0 */ ii(0x1016_19a3, 2); jmp(0x1016_19c3, 0x1e); goto l_0x1016_19c3;/* jmp 0x101619c3 */ l_0x1016_19a5: ii(0x1016_19a5, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_19a8, 5); call(0x1015_26ac, -0xf301); /* call 0x101526ac */ ii(0x1016_19ad, 2); test(eax, eax); /* test eax, eax */ ii(0x1016_19af, 2); if(jnz(0x1016_19b9, 8)) goto l_0x1016_19b9;/* jnz 0x101619b9 */ ii(0x1016_19b1, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_19b4, 5); call(0x100a_9e06, -0xb_7bb3); /* call 0x100a9e06 */ l_0x1016_19b9: ii(0x1016_19b9, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1016_19bb, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x1016_19be, 5); call(0x1015_2605, -0xf3be); /* call 0x10152605 */ l_0x1016_19c3: ii(0x1016_19c3, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x1016_19c5, 1); pop(ebp); /* pop ebp */ ii(0x1016_19c6, 1); pop(edi); /* pop edi */ ii(0x1016_19c7, 1); pop(esi); /* pop esi */ ii(0x1016_19c8, 1); pop(edx); /* pop edx */ ii(0x1016_19c9, 1); pop(ecx); /* pop ecx */ ii(0x1016_19ca, 1); pop(ebx); /* pop ebx */ ii(0x1016_19cb, 1); ret(); /* ret */ } } }
77.284404
112
0.459995
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1016-18c2.cs
8,424
C#
using System; using System.Collections.Generic; using System.Text; namespace Weborb.Writer { class IntegerWriter : AbstractUnreferenceableTypeWriter { public override void write( object obj, IProtocolFormatter writer ) { writer.WriteInteger( Convert.ToInt32(obj) ); } } }
22.333333
76
0.650746
[ "Apache-2.0" ]
Acidburn0zzz/.NET-SDK
Backendless/WebORB/Writer/IntegerWriter.cs
335
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.ContentModerator.AMSComponentClient { /// <summary> /// Represents a FrameGeneratorService. /// </summary> public class FrameGenerator { private AmsConfigurations _amsConfig; /// <summary> /// Instaiates an instance of Frame generator. /// </summary> /// <param name="config"></param> /// <param name="confidenceVal"></param> public FrameGenerator(AmsConfigurations config) { _amsConfig = config; } /// <summary> /// Generates And Submit Frames /// </summary> /// <param name="assetInfo">assetInfo</param> /// <returns>Retruns Review Id</returns> public List<ProcessedFrameDetails> CreateVideoFrames(UploadAssetResult uploadAssetResult) { List<ProcessedFrameDetails> frameEventsList = new List<ProcessedFrameDetails>(); PopulateFrameEvents(uploadAssetResult.ModeratedJson, frameEventsList, uploadAssetResult); return frameEventsList; } /// <summary> /// GetGeneratedFrameList method used for Generating Frames using Moderated Json /// </summary> /// <param name="eventsList">resultDownloaddetailsList</param> /// <param name="assetInfo"></param> public List<ProcessedFrameDetails> GenerateFrameImages(List<ProcessedFrameDetails> eventsList, UploadAssetResult assetInfo, string reviewId) { string frameStorageLocalPath = this._amsConfig.FfmpegFramesOutputPath + reviewId; Directory.CreateDirectory(frameStorageLocalPath); int batchSize = _amsConfig.FrameBatchSize; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\nVideo Frames Creation inprogress..."); var watch = System.Diagnostics.Stopwatch.StartNew(); string ffmpegBlobUrl = string.Empty; if (File.Exists(_amsConfig.FfmpegExecutablePath)) { ffmpegBlobUrl = _amsConfig.FfmpegExecutablePath; } List<string> args = new List<string>(); StringBuilder sb = new StringBuilder(); int frameCounter = 0; int frameProcessedCount = 0; int segmentCount = 0; string dirPath = string.Empty; foreach (var frame in eventsList) { if (frameProcessedCount % batchSize == 0) { segmentCount = frameProcessedCount / batchSize; dirPath = $"{frameStorageLocalPath}\\{segmentCount}"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } } frameProcessedCount++; frame.FrameName = reviewId + frame.FrameName; TimeSpan ts = TimeSpan.FromMilliseconds(Convert.ToDouble(frame.TimeStamp)); var line = "-ss " + ts + " -i \"" + assetInfo.VideoFilePath + "\" -map " + frameCounter + ":v -frames:v 1 -vf scale=320:-1 \"" + dirPath + "\\" + frame.FrameName + "\" "; frameCounter++; sb.Append(line); if (sb.Length > 30000) { args.Add(sb.ToString()); sb.Clear(); frameCounter = 0; } } if (sb.Length != 0) { args.Add(sb.ToString()); } Parallel.ForEach(args, new ParallelOptions { MaxDegreeOfParallelism = 4 }, arg => CreateTaskProcess(arg, ffmpegBlobUrl)); watch.Stop(); Logger.Log($"Frame Creation Elapsed time: {watch.Elapsed}"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Frames(" + eventsList.Count() + ") created successfully."); DirectoryInfo[] diArr = new DirectoryInfo(frameStorageLocalPath).GetDirectories(); Directory.CreateDirectory(frameStorageLocalPath + @"_zip"); foreach (var dir in diArr) { ZipFile.CreateFromDirectory(dir.FullName, frameStorageLocalPath + $"_zip\\{dir.Name}.zip"); } return eventsList; } /// <summary> /// Generates frames based on moderated json source. /// </summary> /// <param name="moderatedJsonstring">moderatedJsonstring</param> /// <param name="resultEventDetailsList">resultEventDetailsList</param> private void PopulateFrameEvents(string moderatedJsonstring, List<ProcessedFrameDetails> resultEventDetailsList, UploadAssetResult uploadResult) { var jsonModerateObject = JsonConvert.DeserializeObject<VideoModerationResult>(moderatedJsonstring); if (jsonModerateObject != null) { var timeScale = Convert.ToInt32(jsonModerateObject.TimeScale); int frameCount = 0; foreach (var item in jsonModerateObject.Fragments) { if (item.Events != null) { foreach (var frameEventDetailList in item.Events) { foreach (FrameEventDetails frameEventDetails in frameEventDetailList) { var eventDetailsObj = new ProcessedFrameDetails { ReviewRecommended = frameEventDetails.ReviewRecommended, TimeStamp = (frameEventDetails.TimeStamp * 1000 / timeScale), IsAdultContent = double.Parse(frameEventDetails.AdultScore) > _amsConfig.AdultFrameThreshold ? true : false, AdultScore = frameEventDetails.AdultScore, IsRacyContent = double.Parse(frameEventDetails.RacyScore) > _amsConfig.RacyFrameThreshold ? true : false, RacyScore = frameEventDetails.RacyScore, TimeScale = timeScale, }; frameCount++; eventDetailsObj.FrameName = "_" + frameCount + ".jpg"; resultEventDetailsList.Add(eventDetailsObj); } } } } } } /// <summary> /// Frame generation using ffmpeg /// </summary> /// <param name="eventTimeStamp"></param> /// <param name="keyframefolderpath"></param> /// <param name="timescale"></param> /// <param name="framename"></param> /// <param name="ffmpegBlobUrl"></param> private void CreateTaskProcess(string arg, string ffmpegBlobUrl) { ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.FileName = ffmpegBlobUrl; processStartInfo.Arguments = arg; var process = Process.Start(processStartInfo); process.WaitForExit(); } } }
44.541176
186
0.556656
[ "MIT" ]
MicrosoftContentModerator/VideoReviewConsoleApp
Microsoft.ContentModerator.AMSComponent/AMSComponentClient/FrameGeneratorService.cs
7,574
C#
using System; namespace LobbyWebServer.Areas.HelpPage.ModelDescriptions { public class ParameterAnnotation { public Attribute AnnotationAttribute { get; set; } public string Documentation { get; set; } } }
21.363636
58
0.702128
[ "MIT" ]
jpate86/WebLobby
src/LobbyWebServer/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs
235
C#
using ActViz.Helpers; using ActViz.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Security.Credentials; using Windows.Storage; namespace ActViz.ViewModels { public class DatabaseConnectionViewModel : ObservableObject { private Logger appLog; private CasasDatabaseService casasDBService; private readonly string dbCredentialKey = "ActViz_DB_Credentials"; private readonly string sshCredentialKey = "ActViz_SSH_Credentials"; private PasswordVault vault; public DatabaseConnectionViewModel(CasasDatabaseService casasDBService) : base() { this.casasDBService = casasDBService; appLog = Logger.Instance; vault = new PasswordVault(); LoadFromLocalSettings(); } private bool _isCredentialsSaved; public bool IsCredentialSaved { get { return _isCredentialsSaved; } set { SetProperty(ref _isCredentialsSaved, value); } } private string _dbServer; public string DbServer { get { return _dbServer; } set { SetProperty(ref _dbServer, value); } } private string _dbPort; public string DbPort { get { return _dbPort; } set { SetProperty(ref _dbPort, value); } } private string _dbUsername; public string DbUsername { get { return _dbUsername; } set { SetProperty(ref _dbUsername, value); } } private string _dbPassword; public string DbPassword { get { return _dbPassword; } set { SetProperty(ref _dbPassword, value); } } private bool _isSshEnabled; public bool IsSshEnabled { get { return _isSshEnabled; } set { SetProperty(ref _isSshEnabled, value); } } private string _sshServer; public string SshServer { get { return _sshServer; } set { SetProperty(ref _sshServer, value); } } private string _sshUsername; public string SshUsername { get { return _sshUsername; } set { SetProperty(ref _sshUsername, value); } } private string _sshPassword; public string SshPassword { get { return _sshPassword; } set { SetProperty(ref _sshPassword, value); } } private T RetrieveFromSettings<T>(string key, T defaultValue, ApplicationDataContainer localSettings = null) { if (localSettings == null) localSettings = ApplicationData.Current.LocalSettings; try { return (T)localSettings.Values[key]; } catch (Exception) { return defaultValue; } } private void LoadFromLocalSettings() { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; DbServer = RetrieveFromSettings("DbServer", "", localSettings); DbPort = RetrieveFromSettings("DbPort", "", localSettings); DbUsername = RetrieveFromSettings("DbUsername", "", localSettings); IsCredentialSaved = RetrieveFromSettings("IsCredentialSaved", false, localSettings); IsSshEnabled = RetrieveFromSettings("IsSshEnabled", false, localSettings); SshServer = RetrieveFromSettings("SshServer", "", localSettings); SshUsername = RetrieveFromSettings("SshUsername", "", localSettings); if (IsCredentialSaved) { PasswordCredential credential = vault.Retrieve(dbCredentialKey, DbUsername); DbPassword = (credential == null) ? "" : credential.Password; if (IsSshEnabled) { credential = vault.Retrieve(sshCredentialKey, SshUsername); SshPassword = (credential == null) ? "" : credential.Password; } } } public void SaveToLocalSettings() { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; localSettings.Values["DbServer"] = DbServer; localSettings.Values["DbPort"] = DbPort; localSettings.Values["DbUsername"] = DbUsername; localSettings.Values["IsSshEnabled"] = IsSshEnabled; if (IsSshEnabled) { localSettings.Values["SshServer"] = SshServer; localSettings.Values["SshUsername"] = SshUsername; } localSettings.Values["IsCredentialSaved"] = IsCredentialSaved; if (IsCredentialSaved) { vault.Add(new PasswordCredential(dbCredentialKey, DbUsername, DbPassword)); if (IsSshEnabled) { vault.Add(new PasswordCredential(sshCredentialKey, SshUsername, SshPassword)); } } else { IReadOnlyList<PasswordCredential> credentialList; credentialList = vault.FindAllByResource(dbCredentialKey); foreach (PasswordCredential credential in credentialList) vault.Remove(credential); credentialList = vault.FindAllByResource(sshCredentialKey); foreach (PasswordCredential credential in credentialList) vault.Remove(credential); } } /// <summary> /// /// </summary> /// <returns> /// Returns true if connection is succeeded. Returns false otherwise. /// </returns> public bool TryDBConnect() { appLog.Info(this.GetType().ToString(), "Connect To Database Asynchronously."); appLog.Debug(this.GetType().ToString(), this.ToString()); casasDBService.IsSshEnabled = IsSshEnabled; casasDBService.SshServer = SshServer; casasDBService.SshPort = 22; casasDBService.SshUsername = SshUsername; casasDBService.SshPassword = SshPassword; casasDBService.DbServer = DbServer; casasDBService.DbPort = int.Parse(DbPort, System.Globalization.NumberStyles.Integer); casasDBService.DbUsername = DbUsername; casasDBService.DbPassword = DbPassword; try { casasDBService.Start(); } catch (Exception e) { appLog.Error(this.GetType().ToString(), "Failed to start DB service with error message: " + e.Message); return false; } return true; } public void CloseConnection() { appLog.Info(this.GetType().ToString(), "Closing Connections to Server..."); casasDBService.Stop(); } public override string ToString() { return string.Format("DB Server: {0} \nDB Port: {1}\nDB Username: {2}\nSSH Enabled: {3}\nSSH Server: {4}\nSSH Username: {5}\n", DbServer, DbPort, DbUsername, IsSshEnabled.ToString(), SshServer, SshUsername ); } } }
36.226601
139
0.582132
[ "MIT" ]
TinghuiWang/ActViz
ActViz/ViewModels/DatabaseConnectionViewModel.cs
7,356
C#
using HL7Data.Contracts.Messages.ScheduleInformationUnsolicitedMessages; using HL7Data.Models.Types; namespace HL7Data.Models.Messages.ScheduleInformationUnsolicitedMessages { public class NotificationAdditionOfServiceResourceOnAppointment : BaseScheduleInformationUnsolicitedMessage, INotificationAdditionOfServiceResourceOnAppointment { public override TriggerEventTypes TriggerEventType => TriggerEventTypes.SIU_S18; } }
44.4
164
0.86036
[ "MIT" ]
amenkes/HL7Parser
Models/Messages/ScheduleInformationUnsolicitedMessages/NotificationAdditionOfServiceResourceOnAppointment.cs
444
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the DescribeContributorInsights operation. /// Returns information about contributor insights, for a given table or global secondary /// index. /// </summary> public partial class DescribeContributorInsightsRequest : AmazonDynamoDBRequest { private string _indexName; private string _tableName; /// <summary> /// Gets and sets the property IndexName. /// <para> /// The name of the global secondary index to describe, if applicable. /// </para> /// </summary> [AWSProperty(Min=3, Max=255)] public string IndexName { get { return this._indexName; } set { this._indexName = value; } } // Check to see if IndexName property is set internal bool IsSetIndexName() { return this._indexName != null; } /// <summary> /// Gets and sets the property TableName. /// <para> /// The name of the table to describe. /// </para> /// </summary> [AWSProperty(Required=true, Min=3, Max=255)] public string TableName { get { return this._tableName; } set { this._tableName = value; } } // Check to see if TableName property is set internal bool IsSetTableName() { return this._tableName != null; } } }
30
106
0.627083
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DynamoDBv2/Generated/Model/DescribeContributorInsightsRequest.cs
2,400
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 Microsoft.AspNet.Mvc; namespace RazorWebSite.Controllers { public class PartialsWithLayoutController : Controller { public IActionResult PartialDoesNotExecuteViewStarts() { return PartialView("PartialThatDoesNotSpecifyLayout"); } // This action demonstrates // (a) _ViewStart does not get executed when executing a partial via RenderPartial // (b) Partials rendered via RenderPartial can execute Layout. public IActionResult PartialsRenderedViaRenderPartial() { return View(); } // This action demonstrates // (a) _ViewStart does not get executed when executing a partial via PartialAsync // (b) Partials rendered via PartialAsync can execute Layout. public IActionResult PartialsRenderedViaPartialAsync() { return View(); } } }
33.5625
111
0.673184
[ "Apache-2.0" ]
VGGeorgiev/Mvc
test/WebSites/RazorWebSite/Controllers/PartialsWithLayoutController.cs
1,074
C#
using System; using System.Collections.Generic; namespace Seif.Rpc.Invoke { public interface IInvocation { string TraceId { get; set; } string ServiceName { get; set; } string MethodName { get; set; } IList<object> Parameters { get; set; } IDictionary<string, string> Attributes { get; set; } } }
25.928571
61
0.600551
[ "MIT" ]
tukzer/Seif
Seif.Rpc/Invoke/IInvocation.cs
365
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class GameDirector : MonoBehaviour { public PauseSystem stateManager; public GameState prevStatate; public int currentJellies; public Transform[] jellyPoints; public GameObject player; public float maxDistance; public float minDistance; public float anxiety; public float intuition; private float[] distanceChecks; private float[] enemyDistanceCheck; private List<GameObject> enemyPoints; private List<GameObject> interestPoints; private void Start() { stateManager.gameState = GameState.Intro; currentJellies = 0; CheckForInterestPoints(); } public Transform GetJellyTarget() { return jellyPoints[currentJellies]; } public void CheckForInterestPoints() { interestPoints = new List<GameObject>(); enemyPoints = new List<GameObject>(); var jellies = GameObject.FindGameObjectsWithTag("Jelly"); var enemies = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject j in jellies) interestPoints.Add(j); foreach (GameObject e in enemies) { interestPoints.Add(e); enemyPoints.Add(e); } enemyDistanceCheck = new float[enemyPoints.Count]; distanceChecks = new float[interestPoints.Count]; } public void CheckDistances() { for(int g = 0; g < interestPoints.Count; g++) { distanceChecks[g] = Vector3.Distance(player.transform.position, interestPoints[g].transform.position); } for (int e = 0; e < enemyPoints.Count; e++) { enemyDistanceCheck[e] = Vector3.Distance(player.transform.position, enemyPoints[e].transform.position); } float closestInterestPoint = distanceChecks.Min(); float anxietyCheck = Mathf.Clamp(closestInterestPoint, minDistance, maxDistance); float anxietyConvertor = anxietyCheck / maxDistance; anxiety = 1 - anxietyConvertor; float closestEnemy = enemyDistanceCheck.Min(); float enemyCheck = Mathf.Clamp(closestEnemy, minDistance, maxDistance); float enemyConvertor = enemyCheck / maxDistance; intuition = 1 - enemyConvertor; } void Update() { switch(stateManager.gameState) { case GameState.Intro: stateManager.gameState = GameState.Playing; break; case GameState.Paused: Time.timeScale = 0; break; case GameState.Playing: if(Time.timeScale != 1) Time.timeScale = 1; CheckDistances(); break; case GameState.GameOver: FindObjectOfType<UiManager>().Activate(UiName.GameOver); if (Time.timeScale != 1) Time.timeScale = 1; break; case GameState.Win: if (Time.timeScale != 1) Time.timeScale = 1; break; } if (Input.GetKeyDown(KeyCode.Escape)){ if (stateManager.gameState != GameState.Paused) { Debug.Log("Game Paused!"); prevStatate = stateManager.gameState; stateManager.gameState = GameState.Paused; } else { Debug.Log("Game Playing!"); stateManager.gameState = prevStatate; } } } }
28.984
115
0.587083
[ "MIT" ]
Lost-Roe/mighty_chancla_ggj_2021
Assets/Enemy AI/scripts/player/GameDirector.cs
3,623
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class hideGrid : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (isHistoryPressed.isPressed) { gameObject.SetActive(true); } else { gameObject.SetActive(false); } } }
18
52
0.577778
[ "MIT" ]
MIT-RH-2/spaceAR
Assets/hideGrid.cs
452
C#
using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Hooks; using System.Collections.Generic; using Xunit; using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using System; using JsonApiDotNetCore.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; namespace UnitTests.ResourceHooks { public sealed class DiscoveryTests { public class Dummy : Identifiable { } public sealed class DummyResourceDefinition : ResourceDefinition<Dummy> { public DummyResourceDefinition() : base(new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).AddResource<Dummy>().Build()) { } public override IEnumerable<Dummy> BeforeDelete(IEntityHashSet<Dummy> affected, ResourcePipeline pipeline) { return affected; } public override void AfterDelete(HashSet<Dummy> entities, ResourcePipeline pipeline, bool succeeded) { } } private IServiceProvider MockProvider<TResource>(object service) where TResource : class, IIdentifiable { var services = new ServiceCollection(); services.AddScoped((_) => (ResourceDefinition<TResource>)service); return services.BuildServiceProvider(); } [Fact] public void HookDiscovery_StandardResourceDefinition_CanDiscover() { // Arrange & act var hookConfig = new HooksDiscovery<Dummy>(MockProvider<Dummy>(new DummyResourceDefinition())); // Assert Assert.Contains(ResourceHook.BeforeDelete, hookConfig.ImplementedHooks); Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); } public class AnotherDummy : Identifiable { } public abstract class ResourceDefinitionBase<T> : ResourceDefinition<T> where T : class, IIdentifiable { protected ResourceDefinitionBase(IResourceGraph resourceGraph) : base(resourceGraph) { } public override IEnumerable<T> BeforeDelete(IEntityHashSet<T> entities, ResourcePipeline pipeline) { return entities; } public override void AfterDelete(HashSet<T> entities, ResourcePipeline pipeline, bool succeeded) { } } public sealed class AnotherDummyResourceDefinition : ResourceDefinitionBase<AnotherDummy> { public AnotherDummyResourceDefinition() : base(new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).AddResource<AnotherDummy>().Build()) { } } [Fact] public void HookDiscovery_InheritanceSubclass_CanDiscover() { // Arrange & act var hookConfig = new HooksDiscovery<AnotherDummy>(MockProvider<AnotherDummy>(new AnotherDummyResourceDefinition())); // Assert Assert.Contains(ResourceHook.BeforeDelete, hookConfig.ImplementedHooks); Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); } public class YetAnotherDummy : Identifiable { } public sealed class YetAnotherDummyResourceDefinition : ResourceDefinition<YetAnotherDummy> { public YetAnotherDummyResourceDefinition() : base(new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).AddResource<YetAnotherDummy>().Build()) { } public override IEnumerable<YetAnotherDummy> BeforeDelete(IEntityHashSet<YetAnotherDummy> affected, ResourcePipeline pipeline) { return affected; } [LoadDatabaseValues(false)] public override void AfterDelete(HashSet<YetAnotherDummy> entities, ResourcePipeline pipeline, bool succeeded) { } } [Fact] public void HookDiscovery_WronglyUsedLoadDatabaseValueAttribute_ThrowsJsonApiSetupException() { // assert Assert.Throws<JsonApiSetupException>(() => { // Arrange & act new HooksDiscovery<YetAnotherDummy>(MockProvider<YetAnotherDummy>(new YetAnotherDummyResourceDefinition())); }); } [Fact] public void HookDiscovery_InheritanceWithGenericSubclass_CanDiscover() { // Arrange & act var hookConfig = new HooksDiscovery<AnotherDummy>(MockProvider<AnotherDummy>(new GenericDummyResourceDefinition<AnotherDummy>())); // Assert Assert.Contains(ResourceHook.BeforeDelete, hookConfig.ImplementedHooks); Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); } public sealed class GenericDummyResourceDefinition<TResource> : ResourceDefinition<TResource> where TResource : class, IIdentifiable<int> { public GenericDummyResourceDefinition() : base(new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).AddResource<TResource>().Build()) { } public override IEnumerable<TResource> BeforeDelete(IEntityHashSet<TResource> entities, ResourcePipeline pipeline) { return entities; } public override void AfterDelete(HashSet<TResource> entities, ResourcePipeline pipeline, bool succeeded) { } } } }
48.509259
180
0.705096
[ "MIT" ]
CrshOverride/JsonApiDotNetCore
test/UnitTests/ResourceHooks/DiscoveryTests.cs
5,239
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("FooBar")] [assembly: AssemblyCopyright("Copyright © Benjamin Nitschke 2018")] [assembly: ComVisible(false)] [assembly: Guid("1c9267eb-8e6a-4600-b6e1-661fbeb83e15")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
33.8
67
0.769231
[ "Apache-2.0" ]
BenjaminNitschke/BibInh18g
FooBar/Properties/AssemblyInfo.cs
341
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Shopper.Core.Entities; using Shopper.Core.Interfaces; using Shopper.Web.ViewModel; using System.Linq; using System.Text.Json; namespace Shopper.Web.Controllers { public class CartController : Controller { private readonly ICartService _cartService; private const string CachedOrder = "Order"; public CartController(ICartService cartService) { _cartService = cartService; } [Authorize] public IActionResult CartItems() { if (HttpContext.Session.GetString(CachedOrder) == null) return View(); var cartViewModel = new CartViewModel(); var order = JsonSerializer.Deserialize<Order>(HttpContext.Session.GetString(CachedOrder)); cartViewModel.Order = order; order!.OrderTotal = order!.OrderItems.Sum(item => (item.Product.ProductPrice * item.OrderItemQuantity)); cartViewModel.ItemLength = cartViewModel.ItemLength = order.OrderItems.Count; ViewData.Model = cartViewModel; return View(); } public IActionResult AddProductToCart(string productId) { if (HttpContext.Session.GetString(CachedOrder) != null) { var order = JsonSerializer.Deserialize<Order>(HttpContext.Session.GetString(CachedOrder)); _cartService.AddProduct(productId, order!.OrderItems); HttpContext.Session.SetString(CachedOrder, JsonSerializer.Serialize(order)); } else { var newOrder = new Order(); _cartService.AddProduct(productId, newOrder.OrderItems); HttpContext.Session.SetString(CachedOrder, JsonSerializer.Serialize(newOrder)); } return RedirectToAction("Index", "Product"); } public IActionResult RemoveProductFromCart(string productId) { if (HttpContext.Session.GetString(CachedOrder) == null) return RedirectToAction("CartItems", "Cart"); var order = JsonSerializer.Deserialize<Order>(HttpContext.Session.GetString(CachedOrder)); _cartService.RemoveProduct(productId, order!.OrderItems); HttpContext.Session.SetString(CachedOrder, JsonSerializer.Serialize(order)); return RedirectToAction("CartItems", "Cart"); } public IActionResult IncreaseCartItemQuantity(string productId) { if (HttpContext.Session.GetString(CachedOrder) == null) return RedirectToAction("CartItems", "Cart"); var order = JsonSerializer.Deserialize<Order>(HttpContext.Session.GetString(CachedOrder)); _cartService.IncreaseProductQuantity(productId, order!.OrderItems); HttpContext.Session.SetString(CachedOrder, JsonSerializer.Serialize(order)); return RedirectToAction("CartItems", "Cart"); } public IActionResult DecreaseCartItemQuantity(string productId) { if (HttpContext.Session.GetString(CachedOrder) == null) return RedirectToAction("CartItems", "Cart"); var order = JsonSerializer.Deserialize<Order>(HttpContext.Session.GetString(CachedOrder)); _cartService.DecreaseProductQuantity(productId, order!.OrderItems); HttpContext.Session.SetString(CachedOrder, JsonSerializer.Serialize(order)); return RedirectToAction("CartItems", "Cart"); } public IActionResult CartSummary() { return View(); } } }
35.640777
116
0.657042
[ "Unlicense" ]
infazrumy/.net-core-mvc-online-shop
Shopper.Web/Controllers/CartController.cs
3,673
C#
using System; using System.Drawing; using BrailleIO.Interface; namespace BrailleIO.Renderer { /// <summary> /// Place a content-matrix in a matrix that fits in a given view with aware of the BoxModel. /// </summary> public class BrailleIOViewMatixRenderer : BrailleIOHookableRendererBase, IBrailleIORendererInterfaces { /// <summary> /// Puts the given content-matrix in a matrix that fits in the given view. /// The content-matrix placement is with aware of the given Box model and panning offsets. /// Borders are not rendered. If the content-matrix don't fit in the /// view, the overlapping content is ignored. /// If the content-matrix is smaller than the view, the rest is set to false. /// This renderer takes also care about the panning, which is set in the view if they is IPannable. /// </summary> /// <param name="view">The view witch holds the BoxModel. If the view is IPannable than the offset is also considered.</param> /// <param name="contentMatrix">The content matrix. Holds the content that should be placed in the view.</param> /// <returns>a bool[view.ViewBox.Width,view.ViewBox.Height] matrix holding the content with aware of the views' BoxModel.</returns> public bool[,] RenderMatrix(IViewBoxModel view, bool[,] contentMatrix) { return RenderMatrix(view, contentMatrix, false); } /// <summary> /// Puts the given content-matrix in a matrix that fits in the given view. /// The content-matrix placement is with aware of the given Box model. /// Borders are not rendered. If the content-matrix don't fit in the /// view, the overlapping content is ignored. /// If the content-matrix is smaller than the view, the rest is set to false. /// This renderer takes also care about the panning, which is set in the view if they is IPannable. /// </summary> /// <param name="view">The view with holds the BoxModel. If the view is IPannable than the offset is also considered.</param> /// <param name="contentMatrix">The content matrix. Holds the content that should be placed in the view.</param> /// <param name="handlePanning">Handle the panning of the content matrix or not</param> /// <returns>a bool[view.ViewBox.Width,view.ViewBox.Height] matrix holding the content with aware of the views' BoxModel.</returns> public bool[,] RenderMatrix(IViewBoxModel view, bool[,] contentMatrix, bool handlePanning) { //call pre hooks object cM = contentMatrix as object; callAllPreHooks(ref view, ref cM, handlePanning); contentMatrix = cM as bool[,]; if (view == null) return null; bool[,] viewMatrix = new bool[view.ViewBox.Height, view.ViewBox.Width]; Rectangle cb = view.ContentBox; int t = cb.Y; int l = cb.X; int r = view.ViewBox.Width - view.ViewBox.Right; int b = Math.Abs(view.ViewBox.Bottom - (cb.Bottom-(cb.Height + cb.Y))); //TODO: semms to be wrong int oX = 0; int oY = 0; if (view is IPannable) { if (handlePanning) { oX = ((IPannable)view).GetXOffset() * -1; oY = ((IPannable)view).GetYOffset() * -1; } if (((IPannable)view).ShowScrollbars) { bool scucess = BrailleIOScrollbarRenderer.DrawScrollbars(view, ref viewMatrix, oX, oY); } } if (contentMatrix != null) { int cw = contentMatrix.GetLength(1); int ch = contentMatrix.GetLength(0); //for (int x = 0; x < cb.Width; x++) System.Threading.Tasks.Parallel.For(0, cb.Width, x => { int cX = oX + x; if (cX >= 0 && contentMatrix.GetLength(1) > cX) { for (int y = 0; y < cb.Height; y++) //System.Threading.Tasks.Parallel.For(0, cb.Height, y => { int cY = oY + y; if (cY >= 0 && contentMatrix.GetLength(0) > cY) { if ((x + l) >= 0 && (y + t) >= 0) { viewMatrix[y + t, x + l] = contentMatrix[cY, cX]; } } }//); } }); } //call post hooks callAllPostHooks(view, contentMatrix, ref viewMatrix, handlePanning); return viewMatrix; } /// <summary> /// Renders a content object into an boolean matrix; /// while <c>true</c> values indicating raised pins and <c>false</c> values indicating lowered pins /// </summary> /// <param name="view">The frame to render in. This gives access to the space to render and other parameters. Normally this is a <see cref="BrailleIOViewRange"/>.</param> /// <param name="content">The content to render.</param> /// <returns> /// A two dimensional boolean M x N matrix (bool[M,N]) where M is the count of rows (this is height) /// and N is the count of columns (which is the width). /// Positions in the Matrix are of type [i,j] /// while i is the index of the row (is the y position) /// and j is the index of the column (is the x position). /// In the matrix <c>true</c> values indicating raised pins and <c>false</c> values indicating lowered pins /// </returns> public bool[,] RenderMatrix(IViewBoxModel view, object content) { return RenderMatrix(view, content as bool[,]); } } }
49.459677
179
0.546878
[ "BSD-2-Clause" ]
TUD-INF-IAI-MCI/BrailleIO
BrailleIO/Renderer/BrailleIOViewMatixRenderer.cs
6,135
C#