content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Xunit; using ZKCloud.Extensions; using ZKCloud.Test.Base.Core; using ZKCloud.Test.Base.Core.Model; namespace ZKCloud.Test.Extensions { public class DecimalExtensionTests : CoreTest { [Theory] [InlineData(1.02, 1.02, 3)] [InlineData(1.02, 1.02, 2)] [InlineData(1, 1, 2)] [TestMethod("EqualsDigits_Decimal_Decimal_Int32")] public void EqualsDigits_Decimal_Decimal_Int32_test(decimal value1, decimal value2, int digits) { var result = value1.EqualsDigits(value2, digits); Assert.True(result); } [Theory] [InlineData(1.02, 1.04, 3)] [InlineData(1.02, 1.04, 2)] [InlineData(1, 1.04, 2)] [TestMethod("LessThanDigits_Decimal_Decimal_Int32")] public void LessThanDigits_Decimal_Decimal_Int32_test(decimal value1, decimal value2, int digits) { var result = value1.LessThanDigits(value2, digits); Assert.True(result); } [Theory] [InlineData(1.12, 1.04, 3)] [InlineData(1.12, 1.04, 2)] [InlineData(1.1, 1.04, 2)] [TestMethod("MoreThanDigits_Decimal_Decimal_Int32")] public void MoreThanDigits_Decimal_Decimal_Int32_test(decimal value1, decimal value2, int digits) { var result = value1.MoreThanDigits(value2, digits); Assert.True(result); } /*end*/ } }
31.888889
105
0.615331
[ "MIT" ]
tongxin3267/alabo
src/07.test/01-Alabo.Test/Extensions/DecimalExtensionTests.cs
1,435
C#
 namespace SuperMap.WinRT.REST.SpatialAnalyst { /// <summary> /// <para>${REST_BufferAnalystParameters_Title}</para> /// <para>${REST_BufferAnalystParameters_Description}</para> /// <para><img src="BufferAnalyst.bmp"/></para> /// </summary> public class BufferAnalystParameters { /// <summary>${REST_BufferAnalystParameters_constructor_D}</summary> public BufferAnalystParameters() { } /// <summary>${REST_BufferAnalystParameters_attribute_bufferSetting_D}</summary> public BufferSetting BufferSetting { get; set; } } }
28.909091
88
0.627358
[ "Apache-2.0" ]
SuperMap/iClient-for-Win8
iClient60ForWinRT/SuperMap.WinRT.REST/SpatialAnalyst/BufferAnalystParameters.cs
638
C#
namespace RTLTMPro { public struct TashkeelLocation { public char Tashkeel { get; set; } public int Position { get; set; } public TashkeelLocation(TashkeelCharacters tashkeel, int position) : this() { Tashkeel = (char) tashkeel; Position = position; } } }
23.714286
83
0.575301
[ "MIT" ]
3174N/project-lashon
Assets/RTLTMPro/Scripts/Runtime/TashkeelLocation.cs
332
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace MusicHub.Data.Models { public class Performer { [Key] public int Id { get; set; } [MaxLength(20)] [Required] public string FirstName { get; set; } [MaxLength(20)] [Required] public string LastName { get; set; } [Required] public int Age { get; set; } [Required] public decimal NetWorth { get; set; } public virtual ICollection<SongPerformer> PerformerSongs { get; set; } } }
22.071429
78
0.600324
[ "MIT" ]
GeorgiGradev/CSharp_DataBases
02. Entity Framework Core/06. LINQ/Solutions/P01_MusicHubDatabase/Data/Models/Performer.cs
620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RevoltSharp { public class EmbedBuilder { public string Title { get; set; } public string Url { get; set; } public string IconUrl { get; set; } public string Description { get; set; } public FileAttachment Image { get; set; } public RevoltColor Color { get; set; } public Embed Build() { return new Embed { Title = Title, Url = Url, IconUrl = IconUrl, Description = Description, Image = Image == null ? null : new Attachment(null, null) { Filename = Image.Id }, Color = Color }; } } public class Embed { public EmbedType Type { get; } public string Url { get; internal set; } public string IconUrl { get; internal set; } public string Title { get; internal set; } public string Description { get; internal set; } public string Site { get; } public RevoltColor Color { get; internal set; } public Attachment Image { get; internal set; } public Attachment Video { get; } public EmbedProvider Provider { get; } internal EmbedJson ToJson() { return new EmbedJson { icon_url = IconUrl, url = Url, title = Title, description = Description, media = Image == null ? null : Image.Filename, colour = Color?.Hex }; } } public class EmbedProvider { public EmbedProviderType Type { get; } } public enum EmbedType { None, Website, Image, Text } public enum EmbedProviderType { None, YouTube, Twitch, Spotify, Soundcloud, Bandcamp } }
27.753425
73
0.520237
[ "MIT" ]
xXBuilderBXx/RevoltSharp
RevoltSharp/Core/Messages/Embed.cs
2,028
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; namespace System.Threading { public static partial class ThreadPool { internal static void ReportThreadStatus(bool isWorking) { } private static unsafe void NativeOverlappedCallback(object? obj) { NativeOverlapped* overlapped = (NativeOverlapped*)(IntPtr)obj!; _IOCompletionCallback.PerformIOCompletionCallback(0, 0, overlapped); } [CLSCompliant(false)] public static unsafe bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) { // OS doesn't signal handle, so do it here (CoreCLR does this assignment in ThreadPoolNative::CorPostQueuedCompletionStatus) overlapped->InternalLow = (IntPtr)0; // Both types of callbacks are executed on the same thread pool return UnsafeQueueUserWorkItem(NativeOverlappedCallback, (IntPtr)overlapped); } [Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)] public static bool BindHandle(IntPtr osHandle) { throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle } public static bool BindHandle(SafeHandle osHandle) { throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle } private static long PendingUnmanagedWorkItemCount => 0; } }
39.744186
136
0.698654
[ "MIT" ]
71221-maker/runtime
src/mono/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Mono.cs
1,709
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QDMS.Server.DataSources { public class EODCode { public string Exchange { get; set; } public string TickerSymbol { get; set; } public EODCode(string exchange, string tickerSymbol) { Exchange = exchange; TickerSymbol = tickerSymbol; } } }
19.391304
60
0.636771
[ "BSD-3-Clause" ]
karlcc/qdms
QDMS.Server.DataSources.EODData/EODCode.cs
448
C#
using System.Collections.Generic; using System.Linq; using AncestryDnaClustering.Models.HierarchicalClustering.Distance; namespace AncestryDnaClustering.Models.HierarchicalClustering { /// <summary> /// A type of Node that represents a single match. /// </summary> public class LeafNode : Node { // The index of the match. public int Index { get; set; } public LeafNode(int index, IEnumerable<int> coords, IDistanceMetric distanceMetric) : base(1, distanceMetric) { Index = index; Coords = coords.ToDictionary(coord => coord, _ => 1.0); FirstLeaf = this; SecondLeaf = this; } public LeafNode(int index, IEnumerable<float> coords, IDistanceMetric distanceMetric) : base(1, distanceMetric) { Index = index; Coords = coords.Select((coord, i) => new { i, coord }).Where(pair => pair.coord > 0).ToDictionary(pair => pair.i, pair => (double)pair.coord); FirstLeaf = this; SecondLeaf = this; } // There is nothing to do when reversing a single leaf node. public override void Reverse() { } // Leaf nodes never contain any other clusters. public override IEnumerable<ClusterNode> GetOrderedClusterNodes() => Enumerable.Empty<ClusterNode>(); // A leaf node contains only itself. public override IEnumerable<LeafNode> GetOrderedLeafNodes() { yield return this; } // Get the coordinates in the specified order. public IEnumerable<double> GetCoordsArray(List<int> orderedIndexes) { return orderedIndexes.Select(index => Coords.TryGetValue(index, out var coord) ? coord : 0); } } }
35.62
154
0.623807
[ "MIT" ]
KenSpratlin/sharedclustering
Models/HierarchicalClustering/LeafNode.cs
1,783
C#
namespace Gu.Roslyn.AnalyzerExtensions.Tests.Symbols.KnownSymbol { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CSharp; using NUnit.Framework; public static class QualifiedMethodTests { [Test] public static void SymbolEquality() { var syntaxTree = CSharpSyntaxTree.ParseText( @" namespace N { internal class C { internal object M() { } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var symbol = semanticModel.GetDeclaredSymbol(syntaxTree.FindMethodDeclaration("M")); var qualifiedMethod = new QualifiedMethod(new QualifiedType("N.C"), "M"); Assert.AreEqual(true, symbol == qualifiedMethod); Assert.AreEqual(false, symbol != qualifiedMethod); } } }
30.78125
122
0.631472
[ "MIT" ]
JohanLarsson/Gu.Roslyn.Extensions
Gu.Roslyn.AnalyzerExtensions.Tests/Symbols/KnownSymbol/QualifiedMethodTests.cs
987
C#
using System.Collections.Generic; using System.IO; using Microsoft.AspNet.Builder; using Nancy.Owin; using Nancy; using Nancy.ViewEngines.Razor; namespace Salon { public class Startup { public void Configure(IApplicationBuilder app) { app.UseOwin(x => x.UseNancy()); } } public static class DBConfiguration { public static string ConnectionString = "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=review;Integrated Security=SSPI;"; } public class CustomRootPathProvider : IRootPathProvider { public string GetRootPath() { return Directory.GetCurrentDirectory(); } } public class RazorConfig : IRazorConfiguration { public IEnumerable<string> GetAssemblyNames() { return null; } public IEnumerable<string> GetDefaultNamespaces() { return null; } public bool AutoIncludeModelNamespace { get { return false; } } } }
20.413043
131
0.690096
[ "MIT" ]
TaylorLoftisKim/Hair-Salon
startup.cs
939
C#
using DiscordRPC; using Ryujinx.Common; using System; using System.Linq; namespace Ryujinx.Configuration { static class DiscordIntegrationModule { private static DiscordRpcClient _discordClient; private static string LargeDescription = "PangoNX Debugger is a Nintendo Switch emulator."; public static RichPresence DiscordPresence { get; private set; } public static void Initialize() { DiscordPresence = new RichPresence { Assets = new Assets { LargeImageKey = "ryujinx", LargeImageText = LargeDescription }, Details = "Main Menu", State = "Idling", Timestamps = new Timestamps(DateTime.UtcNow) }; ConfigurationState.Instance.EnableDiscordIntegration.Event += Update; } private static void Update(object sender, ReactiveEventArgs<bool> e) { if (e.OldValue != e.NewValue) { // If the integration was active, disable it and unload everything if (e.OldValue) { _discordClient?.Dispose(); _discordClient = null; } // If we need to activate it and the client isn't active, initialize it if (e.NewValue && _discordClient == null) { _discordClient = new DiscordRpcClient("568815339807309834"); _discordClient.Initialize(); _discordClient.SetPresence(DiscordPresence); } } } public static void SwitchToPlayingState(string titleId, string titleName) { if (SupportedTitles.Contains(titleId)) { DiscordPresence.Assets.LargeImageKey = titleId; } string state = titleId; if (state == null) { state = "PangoNX Debugger"; } else { state = state.ToUpper(); } string details = "Idling"; if (titleName != null) { details = $"Playing {titleName}"; } DiscordPresence.Details = details; DiscordPresence.State = state; DiscordPresence.Assets.LargeImageText = titleName; DiscordPresence.Assets.SmallImageKey = "ryujinx"; DiscordPresence.Assets.SmallImageText = LargeDescription; DiscordPresence.Timestamps = new Timestamps(DateTime.UtcNow); _discordClient?.SetPresence(DiscordPresence); } public static void SwitchToMainMenu() { DiscordPresence.Details = "Main Menu"; DiscordPresence.State = "Idling"; DiscordPresence.Assets.LargeImageKey = "ryujinx"; DiscordPresence.Assets.LargeImageText = LargeDescription; DiscordPresence.Assets.SmallImageKey = null; DiscordPresence.Assets.SmallImageText = null; DiscordPresence.Timestamps = new Timestamps(DateTime.UtcNow); _discordClient?.SetPresence(DiscordPresence); } public static void Exit() { _discordClient?.Dispose(); } private static readonly string[] SupportedTitles = { "0100000000010000", // Super Mario Odyssey™ "01000b900d8b0000", // Cadence of Hyrule – Crypt of the NecroDancer Featuring The Legend of Zelda "01000d200ac0c000", // Bud Spencer & Terence Hill - Slaps And Beans "01000d700be88000", // My Girlfriend is a Mermaid!? "01000dc007e90000", // Sparkle Unleashed "01000e2003fa0000", // MIGHTY GUNVOLT BURST "0100225000fee000", // Blaster Master Zero "010028d0045ce000", // Sparkle 2 "01002b30028f6000", // Celeste "01002fc00c6d0000", // Witch Thief "010034e005c9c000", // Code of Princess EX "010036b0034e4000", // Super Mario Party™ "01003d200baa2000", // Pokémon Mystery Dungeon™: Rescue Team DX "01004f8006a78000", // Super Meat Boy "010051f00ac5e000", // SEGA AGES Sonic The Hedgehog "010055d009f78000", // Fire Emblem™: Three Houses "010056e00853a000", // A Hat in Time "0100574009f9e000", // 嘘つき姫と盲目王子 "01005d700e742000", // DOOM 64 "0100628004bce000", // Nights of Azure 2: Bride of the New Moon "0100633007d48000", // Hollow Knight "010065500b218000", // メモリーズオフ -Innocent Fille- "010068f00aa78000", // FINAL FANTASY XV POCKET EDITION HD "01006bb00c6f0000", // The Legend of Zelda™: Link’s Awakening "01006f8002326000", // Animal Crossing™: New Horizons "01006a800016e000", // Super Smash Bros.™ Ultimate "010072800cbe8000", // PC Building Simulator "01007300020fa000", // ASTRAL CHAIN "01007330027ee000", // Ultra Street Fighter® II: The Final Challengers "0100749009844000", // 20XX "01007a4008486000", // Enchanting Mahjong Match "01007ef00011e000", // The Legend of Zelda™: Breath of the Wild "010080b00ad66000", // Undertale "010082400bcc6000", // Untitled Goose Game "01008db008c2c000", // Pokémon™ Shield "010094e00b52e000", // Capcom Beat 'Em Up Bundle "01009aa000faa000", // Sonic Mania "01009b90006dc000", // Super Mario Maker™ 2 "01009cc00c97c000", // DEAD OR ALIVE Xtreme 3 Scarlet 基本無料版 "0100ea80032ea000", // New Super Mario Bros.™ U Deluxe "0100a4200a284000", // LUMINES REMASTERED "0100a5c00d162000", // Cuphead "0100abf008968000", // Pokémon™ Sword "0100ae000aebc000", // Angels of Death "0100b3f000be2000", // Pokkén Tournament™ DX "0100bc2004ff4000", // Owlboy "0100cf3007578000", // Atari Flashback Classics "0100d5d00c6be000", // Our World Is Ended. "0100d6b00cd88000", // YUMENIKKI -DREAM DIARY- "0100d870045b6000", // Nintendo Entertainment System™ - Nintendo Switch Online "0100e0c00adac000", // SENRAN KAGURA Reflexions "0100e46006708000", // Terraria "0100e7200b272000", // Lanota "0100e9f00b882000", // null "0100eab00605c000", // Poly Bridge "0100efd00a4fa000", // Shantae and the Pirate's Curse "0100f6a00a684000", // ひぐらしのなく頃に奉 "0100f9f00c696000", // Crash™ Team Racing Nitro-Fueled "051337133769a000", // RGB-Seizure }; } }
40.346821
109
0.562321
[ "MIT" ]
davFaithid/pangonx-debugger
Ryujinx/Configuration/DiscordIntegrationModule.cs
7,083
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Apollo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.481481
70
0.642442
[ "Apache-2.0" ]
emre-guler/Apollo
Program.cs
688
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * * * * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Cdn.Model { /// <summary> /// pvItem /// </summary> public class PvItem { ///<summary> /// UTC时间,格式为:yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;,示例:2018-10-21T10:00:00Z ///</summary> public string TimeUtc{ get; set; } ///<summary> /// 总请求量 ///</summary> public int? TotalPv{ get; set; } ///<summary> /// 攻击请求量 ///</summary> public int? AttackPv{ get; set; } } }
23.666667
86
0.622848
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cdn/Model/PvItem.cs
1,314
C#
using Finanzuebersicht.Backend.Core.Contract.Persistence.Modules.Accounting.Categories; using Finanzuebersicht.Backend.Core.Contract.Persistence.Tools.Pagination; using Finanzuebersicht.Backend.Core.Logic.Tests.Tools.Pagination; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace Finanzuebersicht.Backend.Core.Logic.Tests.Modules.Accounting.Categories { internal class DbCategoryTest : IDbCategory { public Guid Id { get; set; } public Guid SuperCategoryId { get; set; } public string Title { get; set; } public string Color { get; set; } public static IDbCategory Default() { return new DbCategoryTest() { Id = CategoryTestValues.IdDefault, SuperCategoryId = CategoryTestValues.SuperCategoryIdDefault, Title = CategoryTestValues.TitleDefault, Color = CategoryTestValues.ColorDefault, }; } public static IDbCategory Default2() { return new DbCategoryTest() { Id = CategoryTestValues.IdDefault2, SuperCategoryId = CategoryTestValues.SuperCategoryIdDefault2, Title = CategoryTestValues.TitleDefault2, Color = CategoryTestValues.ColorDefault2, }; } public static void AssertDefault(IDbCategory dbCategory) { Assert.AreEqual(CategoryTestValues.IdDefault, dbCategory.Id); Assert.AreEqual(CategoryTestValues.SuperCategoryIdDefault, dbCategory.SuperCategoryId); Assert.AreEqual(CategoryTestValues.TitleDefault, dbCategory.Title); Assert.AreEqual(CategoryTestValues.ColorDefault, dbCategory.Color); } public static void AssertDefault2(IDbCategory dbCategory) { Assert.AreEqual(CategoryTestValues.IdDefault2, dbCategory.Id); Assert.AreEqual(CategoryTestValues.SuperCategoryIdDefault2, dbCategory.SuperCategoryId); Assert.AreEqual(CategoryTestValues.TitleDefault2, dbCategory.Title); Assert.AreEqual(CategoryTestValues.ColorDefault2, dbCategory.Color); } public static void AssertCreated(IDbCategory dbCategory) { Assert.AreEqual(CategoryTestValues.IdForCreate, dbCategory.Id); Assert.AreEqual(CategoryTestValues.SuperCategoryIdForCreate, dbCategory.SuperCategoryId); Assert.AreEqual(CategoryTestValues.TitleForCreate, dbCategory.Title); Assert.AreEqual(CategoryTestValues.ColorForCreate, dbCategory.Color); } } }
40.590909
101
0.681224
[ "MIT" ]
shuralw/Finanzuebersicht2.0
Finanzuebersicht.Backends/Finanzuebersicht.Backend.Core/Logic.Tests/Modules/Accounting/Categories/DTOs/DbCategoryTest.cs
2,679
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlogNC.Areas.Blog.Models.ViewComponentModels { public class NavigationViewModel { public IEnumerable<StaticPage> QualifyingStaticPages { get; set; } } }
21.692308
74
0.755319
[ "MIT" ]
nfisher23/BlogNC
BlogNC/Areas/Blog/Models/ViewComponentModels/NavigationViewModel.cs
284
C#
namespace Springboard365.Xrm.Plugins.Core.IntegrationTest { using System; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; public class AssignEntitySpecificationFixture : SpecificationFixtureBase { public AssignRequest AssignRequest { get; private set; } public string MessageName { get; private set; } public void PerformTestSetup() { MessageName = "Assign"; var targetEntity = new Entity("contact") { Id = Guid.NewGuid() }; targetEntity["firstname"] = "DummyFirstName"; OrganizationService.Create(targetEntity); AssignRequest = new AssignRequest { Target = targetEntity.ToEntityReference(), Assignee = CrmReader.GetSystemUser() }; } } }
28.580645
76
0.577878
[ "Apache-2.0" ]
Davesmall28/DSmall.DynamicsCrm.Plugins.Core
Springboard365.Xrm.Plugins.Core.IntegrationTest/PluginTest/Assign/AssignEntitySpecificationFixture.cs
888
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlazorWASMHosted.Server { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.148148
70
0.648725
[ "MIT" ]
sahan91/BlazorWASMHosted
BlazorWASMHosted/Server/Program.cs
708
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SpeedWagon.Interfaces; using SpeedWagon.Runtime.Interfaces; using SpeedWagon.Runtime.Services; using SpeedWagon.Services; using SpeedWagon.Web.Auth; using SpeedWagon.Web.Enum; using SpeedWagon.Web.Interfaces; using SpeedWagon.Web.Services; using System.IO; namespace SpeedWagon.Web.Extension { public static class DependencyInjection { private const string SPEEDWAGON_HOST = "https://reo.speedwagon.me"; public static IServiceCollection AddSpeedWagonCms(this IServiceCollection services, string path, string uploadsPath, IFileProvider contentFileProvider, IFileProvider uploadFileProvider) { IContentService contentService = new CacheLessRuntimeContentService(path, null, contentFileProvider); IEditorService editorService = new EditorService(contentService, SPEEDWAGON_HOST); IContentTypeService contentTypeService = new ContentTypeService(contentService, SPEEDWAGON_HOST); IWebContentService webContentService = new WebContentService(contentService, SPEEDWAGON_HOST); IContentService uploadContentService = new CacheLessRuntimeContentService(uploadsPath, null, uploadFileProvider); IFileUploadService fileUploadService = new FileUploadService(uploadContentService, string.Empty, uploadFileProvider); ISearchService searchService = new LuceneSearchService(contentService, Path.Combine(path, "search")); services.AddSingleton<ISpeedWagonAdminContext>(s => new SpeedWagonAdminContext( path, contentService, contentTypeService, editorService, webContentService, fileUploadService, searchService) ); return services; } public static IServiceCollection AddSpeedWagon(this IServiceCollection services, string path, bool cached, IFileProvider contentFileProvider) { IContentService contentService; if (cached) { services.AddHostedService<CacheRefreshingHostedService>(); contentService = new CachedRuntimeContentService( path, null, contentFileProvider ); } else { contentService = new CacheLessRuntimeContentService( path, null, contentFileProvider ); } ISearchService searchService = new LuceneSearchService(contentService, Path.Combine(path, "search")); services.AddSingleton<ISpeedWagonWebContext>( s => new SpeedWagonWebContext( path, contentService, searchService)); return services; } public static IServiceCollection AddAzureAdAuthentication(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton<IAuthTypeInformationProvider>(s => new AuthTypeInformationProvider(AuthType.AzureAd)); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) // Use Azure AD Login .AddAzureAd(options => configuration.Bind("AzureAd", options)) .AddCookie(); return services; } public static IServiceCollection AddSimpleAuthentication(this IServiceCollection services) { services.AddSingleton<IAuthTypeInformationProvider>(s => new AuthTypeInformationProvider(AuthType.Dummy)); // Dummy Login provider services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = "/SpeedWagonAccount/Login"; options.LogoutPath = "/SpeedWagonAccount/Logout"; }); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }); return services; } } }
40.813559
193
0.647425
[ "MIT" ]
darrenferguson/speedwagon
SpeedWagon.Web/Extension/DependencyInjection.cs
4,818
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceManagementNdesConnectorsCollectionRequest. /// </summary> public partial interface IDeviceManagementNdesConnectorsCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified NdesConnector to the collection via POST. /// </summary> /// <param name="ndesConnector">The NdesConnector to add.</param> /// <returns>The created NdesConnector.</returns> System.Threading.Tasks.Task<NdesConnector> AddAsync(NdesConnector ndesConnector); /// <summary> /// Adds the specified NdesConnector to the collection via POST. /// </summary> /// <param name="ndesConnector">The NdesConnector to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created NdesConnector.</returns> System.Threading.Tasks.Task<NdesConnector> AddAsync(NdesConnector ndesConnector, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceManagementNdesConnectorsCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceManagementNdesConnectorsCollectionPage> GetAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Expand(Expression<Func<NdesConnector, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Select(Expression<Func<NdesConnector, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IDeviceManagementNdesConnectorsCollectionRequest OrderBy(string value); } }
45.240741
153
0.634261
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDeviceManagementNdesConnectorsCollectionRequest.cs
4,886
C#
// Copyright 2007-2014 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Testing.Factories { using System; using Saga; using ScenarioBuilders; using TestInstanceConfigurators; public class SagaTestFactoryImpl<TScenario, TSaga> : SagaTestFactory<TScenario, TSaga> where TSaga : class, ISaga where TScenario : IBusTestScenario { readonly Func<ITestScenarioBuilder<TScenario>> _scenarioBuilderFactory; public SagaTestFactoryImpl(Func<ITestScenarioBuilder<TScenario>> scenarioBuilderFactory) { _scenarioBuilderFactory = scenarioBuilderFactory; } public SagaTest<TScenario, TSaga> New(Action<ISagaTestConfigurator<TScenario, TSaga>> configureTest) { var configurator = new SagaTestConfigurator<TScenario, TSaga>(_scenarioBuilderFactory); configureTest(configurator); return configurator.Build(); } } }
37.785714
109
0.692502
[ "Apache-2.0" ]
Johavale19/Johanna
src/MassTransit/Testing/Factories/SagaTestFactoryImpl.cs
1,587
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. // Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. using System; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Silk.NET.Core.Native; using Silk.NET.Direct3D12; using Silk.NET.DXGI; using Silk.NET.Maths; using InfoQueueFilter = Silk.NET.Direct3D12.InfoQueueFilter; using InfoQueueFilterDesc = Silk.NET.Direct3D12.InfoQueueFilterDesc; namespace D3D12Triangle { public abstract unsafe class DX12Sample : DXSample { private ID3D12Device* _d3dDevice; private IDXGIAdapter1* _dxgiAdapter; private IDXGIFactory4* _dxgiFactory; private IDXGISwapChain3* _swapChain; private ID3D12Resource*[] _renderTargets; private ID3D12Resource* _depthStencil; private ID3D12DescriptorHeap* _rtvHeap; private ID3D12DescriptorHeap* _dsvHeap; private ID3D12CommandQueue* _commandQueue; private ID3D12CommandAllocator*[] _commandAllocators; private Viewport _viewport; private Rectangle<int> _scissorRect; private uint _rtvDescriptorSize; private Silk.NET.Direct3D12.D3D12 _d3d12; private Silk.NET.DXGI.DXGI _dxgi; private ID3D12Fence* _fence; private ulong[] _fenceValues; private IntPtr _fenceEvent; private ID3D12GraphicsCommandList*[] _graphicsCommandLists; private ID3D12RootSignature* _rootSignature; private ID3D12PipelineState* _pipelineState; private bool _debug; private ID3D12InfoQueue* _infoQueue; private Task _infoPump; private CancellationTokenSource _infoPumpCancellationToken; protected DX12Sample(string name) : base(name) { _renderTargets = new ID3D12Resource*[2]; _commandAllocators = new ID3D12CommandAllocator*[2]; _fenceValues = new ulong[2]; _graphicsCommandLists = new ID3D12GraphicsCommandList*[2]; _d3d12 = Silk.NET.Direct3D12.D3D12.GetApi(); _dxgi = DXGI.GetApi(); } public Silk.NET.Direct3D12.D3D12 D3D12 => _d3d12; public Silk.NET.DXGI.DXGI Dxgi => _dxgi; public ID3D12CommandAllocator* CommandAllocator => _commandAllocators[FrameIndex]; public ID3D12CommandQueue* CommandQueue => _commandQueue; public ID3D12Device* D3DDevice => _d3dDevice; public ID3D12Resource* DepthStencil => _depthStencil; public ID3D12DescriptorHeap* DSVHeap => _dsvHeap; public IDXGIAdapter1* DxgiAdapter => _dxgiAdapter; public IDXGIFactory4* DxgiFactory => _dxgiFactory; public ID3D12Fence* Fence => _fence; public IntPtr FenceEvent => _fenceEvent; public ref ulong FenceValue => ref _fenceValues[FrameIndex]; public ID3D12GraphicsCommandList* GraphicsCommandList => _graphicsCommandLists[FrameIndex]; public ID3D12PipelineState* PipelineState => _pipelineState; public ID3D12Resource* RenderTarget => _renderTargets[FrameIndex]; public ID3D12RootSignature* RootSignature => _rootSignature; public uint RTVDescriptorSize => _rtvDescriptorSize; public ID3D12DescriptorHeap* RTVHeap => _rtvHeap; public ref Rectangle<int> ScissorRect => ref _scissorRect; public IDXGISwapChain3* SwapChain => _swapChain; public ref Viewport Viewport => ref _viewport; public override void OnDestroy() { WaitForGpu(moveToNextFrame: false); _infoPumpCancellationToken.Cancel(); base.OnDestroy(); } public override void OnRender() { PopulateGraphicsCommandList(); ExecuteGraphicsCommandList(); SilkMarshal.ThrowHResult(_swapChain->Present(SyncInterval: 1, Flags: 0)); WaitForGpu(moveToNextFrame: true); void PopulateGraphicsCommandList() { WaitForGpu(moveToNextFrame: false); SilkMarshal.ThrowHResult(CommandAllocator->Reset()); SilkMarshal.ThrowHResult(GraphicsCommandList->Reset(CommandAllocator, PipelineState)); SetGraphicsCommandListState(); TransitionForRender(); var backgroundColor = BackgroundColor; // in d3dx12.h: // new CpuDescriptorHandle(RTVHeap->GetCPUDescriptorHandleForHeapStart(), (int)FrameIndex, // RTVDescriptorSize) var rtvHandle = new CpuDescriptorHandle { Ptr = (nuint) ((long) @RTVHeap->GetCPUDescriptorHandleForHeapStart().Ptr + ((long) FrameIndex * (long) RTVDescriptorSize)) }; GraphicsCommandList->ClearRenderTargetView(rtvHandle, (float*) &backgroundColor, 0, null); var dsvHandle = DSVHeap->GetCPUDescriptorHandleForHeapStart(); GraphicsCommandList->ClearDepthStencilView(dsvHandle, ClearFlags.ClearFlagDepth, 1, 0, 0, null); GraphicsCommandList->OMSetRenderTargets(1, &rtvHandle, 0, &dsvHandle); Draw(); TransitionForPresent(); SilkMarshal.ThrowHResult(GraphicsCommandList->Close()); } } protected virtual void CreateAssets() { SilkMarshal.ThrowHResult(GraphicsCommandList->Close()); ExecuteGraphicsCommandList(); WaitForGpu(moveToNextFrame: false); } protected virtual ID3D12Resource* CreateDepthStencil() { ID3D12Resource* depthStencil; var heapProperties = new HeapProperties(HeapType.HeapTypeDefault); var resourceDesc = new ResourceDesc ( ResourceDimension.ResourceDimensionTexture2D, 0ul, (ulong) Size.X, (uint) Size.Y, 1, 1, DepthBufferFormat, new SampleDesc() {Count = 1, Quality = 0}, TextureLayout.TextureLayoutUnknown, ResourceFlags.ResourceFlagAllowDepthStencil ); var clearValue = new ClearValue(DepthBufferFormat, depthStencil: new DepthStencilValue(1.0f, 0)); var iid = ID3D12Resource.Guid; SilkMarshal.ThrowHResult ( D3DDevice->CreateCommittedResource ( &heapProperties, HeapFlags.HeapFlagNone, &resourceDesc, ResourceStates.ResourceStateDepthWrite, &clearValue, &iid, (void**) &depthStencil ) ); var dsvDesc = new DepthStencilViewDesc { Format = DepthBufferFormat, ViewDimension = DsvDimension.DsvDimensionTexture2D }; D3DDevice->CreateDepthStencilView(depthStencil, &dsvDesc, DSVHeap->GetCPUDescriptorHandleForHeapStart()); return depthStencil; } protected virtual void CreateDescriptorHeaps() { _rtvHeap = CreateRTVHeap(out _rtvDescriptorSize); _dsvHeap = CreateDSVHeap(); ID3D12DescriptorHeap* CreateDSVHeap() { var dsvHeapDesc = new DescriptorHeapDesc { NumDescriptors = 1, Type = DescriptorHeapType.DescriptorHeapTypeDsv, }; ID3D12DescriptorHeap* dsvHeap; var iid = ID3D12DescriptorHeap.Guid; SilkMarshal.ThrowHResult(D3DDevice->CreateDescriptorHeap(&dsvHeapDesc, &iid, (void**) &dsvHeap)); return dsvHeap; } ID3D12DescriptorHeap* CreateRTVHeap(out uint rtvDescriptorSize) { var rtvHeapDesc = new DescriptorHeapDesc { NumDescriptors = FrameCount, Type = DescriptorHeapType.DescriptorHeapTypeRtv, }; ID3D12DescriptorHeap* rtvHeap; var iid = ID3D12DescriptorHeap.Guid; SilkMarshal.ThrowHResult(D3DDevice->CreateDescriptorHeap(&rtvHeapDesc, &iid, (void**) &rtvHeap)); rtvDescriptorSize = D3DDevice->GetDescriptorHandleIncrementSize (DescriptorHeapType.DescriptorHeapTypeRtv); return rtvHeap; } } protected override void CreateDeviceDependentResources() { _dxgiFactory = CreateDxgiFactory(); _dxgiAdapter = GetDxgiAdapter(); _d3dDevice = CreateD3DDevice(); StartInfoPump(); _commandQueue = CreateCommandQueue(); CreateDescriptorHeaps(); for (int i = 0; i < FrameCount; i++) { _commandAllocators[i] = CreateCommandAllocator(); } _fence = CreateFence(); _fenceValues = CreateFenceValues(); _fenceEvent = CreateFenceEvent(); _rootSignature = CreateRootSignature(); _pipelineState = CreatePipelineState(); _graphicsCommandLists = CreateGraphicsCommandLists(); SilkMarshal.ThrowHResult(CommandAllocator->Reset()); SilkMarshal.ThrowHResult(GraphicsCommandList->Reset(CommandAllocator, PipelineState)); CreateAssets(); ID3D12CommandAllocator* CreateCommandAllocator() { ID3D12CommandAllocator* commandAllocator; var iid = ID3D12CommandAllocator.Guid; SilkMarshal.ThrowHResult ( D3DDevice->CreateCommandAllocator (CommandListType.CommandListTypeDirect, &iid, (void**) &commandAllocator) ); return commandAllocator; } ID3D12CommandQueue* CreateCommandQueue() { var queueDesc = new CommandQueueDesc(); ID3D12CommandQueue* commandQueue; var iid = ID3D12CommandQueue.Guid; SilkMarshal.ThrowHResult(D3DDevice->CreateCommandQueue(&queueDesc, &iid, (void**) &commandQueue)); return commandQueue; } ID3D12Device* CreateD3DDevice() { ID3D12Device* d3dDevice; var iid = ID3D12Device.Guid; SilkMarshal.ThrowHResult ( D3D12.CreateDevice ((IUnknown*) _dxgiAdapter, D3DFeatureLevel.D3DFeatureLevel110, &iid, (void**) &d3dDevice) ); return d3dDevice; } IDXGIFactory4* CreateDxgiFactory() { var dxgiFactoryFlags = TryEnableDebugLayer() ? 0x01 : 0u; IDXGIFactory4* dxgiFactory; var iid = IDXGIFactory4.Guid; SilkMarshal.ThrowHResult(Dxgi.CreateDXGIFactory2(dxgiFactoryFlags, &iid, (void**) &dxgiFactory)); return dxgiFactory; } ID3D12Fence* CreateFence() { ID3D12Fence* fence; var iid = ID3D12Fence.Guid; SilkMarshal.ThrowHResult (D3DDevice->CreateFence(InitialValue: 0, FenceFlags.FenceFlagNone, &iid, (void**) &fence)); return fence; } IntPtr CreateFenceEvent() { var fenceEvent = SilkMarshal.CreateWindowsEvent(null, false, false, null); if (fenceEvent == IntPtr.Zero) { var hr = Marshal.GetHRForLastWin32Error(); Marshal.ThrowExceptionForHR(hr); } return fenceEvent; } ulong[] CreateFenceValues() { var fenceValues = new ulong[FrameCount]; fenceValues[0] = 1; return fenceValues; } ID3D12GraphicsCommandList*[] CreateGraphicsCommandLists() { var graphicsCommandLists = new ID3D12GraphicsCommandList*[FrameCount]; for (uint i = 0u; i < FrameCount; i++) { ID3D12GraphicsCommandList* graphicsCommandList; var iid = ID3D12GraphicsCommandList.Guid; SilkMarshal.ThrowHResult ( D3DDevice->CreateCommandList ( nodeMask: 0, CommandListType.CommandListTypeDirect, _commandAllocators[i], PipelineState, &iid, (void**) &graphicsCommandList ) ); SilkMarshal.ThrowHResult(graphicsCommandList->Close()); graphicsCommandLists[i] = graphicsCommandList; } return graphicsCommandLists; } IDXGIAdapter1* GetDxgiAdapter() { if (UseWarpDevice) { IDXGIAdapter1* adapter; var iid = IDXGIAdapter.Guid; SilkMarshal.ThrowHResult(_dxgiFactory->EnumWarpAdapter(&iid, (void**) &adapter)); return adapter; } else { return GetHardwareAdapter((IDXGIFactory1*) _dxgiFactory); } } bool TryEnableDebugLayer() { #if DEBUG // Enable the debug layer (requires the Graphics Tools "optional feature"). // NOTE: Enabling the debug layer after device creation will invalidate the active device. using ComPtr<ID3D12Debug> debugController = null; var iid = ID3D12Debug.Guid; var hr = D3D12.GetDebugInterface(&iid, (void**) &debugController); if (HResult.IndicatesSuccess(hr)) { debugController.Get().EnableDebugLayer(); Log.LogInformation("Debug layer enabled"); return _debug = true; } else { Log.LogWarning ( Marshal.GetExceptionForHR(hr), $"Failed to enable debug layer, failed with result {hr} (0x{hr:x8})" ); } #endif return false; } void StartInfoPump() { #if DEBUG if (!_debug) { Log.LogInformation("Skipped creation of info pump due to the debug layer not being enabled."); return; } var iid = ID3D12InfoQueue.Guid; fixed (ID3D12InfoQueue** @out = &_infoQueue) { SilkMarshal.ThrowHResult(D3DDevice->QueryInterface(&iid, (void**) @out)); } _infoPumpCancellationToken = new(); _infoPump = Task.Run ( () => { Log.LogInformation("Info queue pump started"); while (!_infoPumpCancellationToken.Token.IsCancellationRequested) { var numMessages = _infoQueue->GetNumStoredMessages(); if (numMessages == 0) { continue; } for (var i = 0ul; i < numMessages; i++) { nuint msgByteLength; SilkMarshal.ThrowHResult(_infoQueue->GetMessageA(i, null, &msgByteLength)); using var memory = GlobalMemory.Allocate((int) msgByteLength); SilkMarshal.ThrowHResult ( _infoQueue->GetMessageA(i, memory.AsPtr<Message>(), &msgByteLength) ); ref var msg = ref memory.AsRef<Message>(); var descBytes = new Span<byte>(msg.PDescription, (int) msg.DescriptionByteLength); var desc = Encoding.UTF8.GetString(descBytes[..^1]); var eid = new EventId((int) msg.ID, msg.ID.ToString()["MessageID".Length..]); var str = $"{msg.Category.ToString()["MessageCategory".Length..]} (From D3D12): {desc}"; switch (msg.Severity) { case MessageSeverity.MessageSeverityCorruption: { Log.LogCritical(eid, str); break; } case MessageSeverity.MessageSeverityError: { Log.LogError(eid, str); break; } case MessageSeverity.MessageSeverityWarning: { Log.LogWarning(eid, str); break; } case MessageSeverity.MessageSeverityInfo: { Log.LogInformation(eid, str); break; } case MessageSeverity.MessageSeverityMessage: { Log.LogTrace(eid, str); break; } default: throw new ArgumentOutOfRangeException(); } } _infoQueue->ClearStoredMessages(); } Log.LogInformation("Info queue pump stopped"); }, _infoPumpCancellationToken.Token ); #endif } } protected virtual ID3D12PipelineState* CreatePipelineState() => null; protected virtual void CreateRenderTargetViews() { var rtvHandle = RTVHeap->GetCPUDescriptorHandleForHeapStart(); for (var i = 0u; i < FrameCount; i++) { D3DDevice->CreateRenderTargetView(_renderTargets[i], null, rtvHandle); rtvHandle.Ptr = (nuint) ((long) rtvHandle.Ptr + RTVDescriptorSize); } } protected virtual void CreateResourceViews() { FrameIndex = SwapChain->GetCurrentBackBufferIndex(); _renderTargets = CreateRenderTargets(); _depthStencil = CreateDepthStencil(); CreateRenderTargetViews(); ID3D12Resource*[] CreateRenderTargets() { var renderTargets = new ID3D12Resource*[FrameCount]; var iid = ID3D12Resource.Guid; for (var i = 0u; i < FrameCount; i++) { ID3D12Resource* renderTarget; SilkMarshal.ThrowHResult(SwapChain->GetBuffer(i, &iid, (void**) &renderTarget)); renderTargets[unchecked((int) i)] = renderTarget; } return renderTargets; } } protected virtual ID3D12RootSignature* CreateRootSignature() => null; protected override void CreateWindowSizeDependentResources() { // Wait until all previous GPU work is complete. WaitForGpu(moveToNextFrame: false); // Clear the previous window size specific content and update the tracked fence values. for (var i = 0u; i < FrameCount; i++) { _renderTargets[i] = null; _fenceValues[i] = _fenceValues[FrameIndex]; } if (_swapChain != null) { SilkMarshal.ThrowHResult (_swapChain->ResizeBuffers(FrameCount, (uint) Size.X, (uint) Size.Y, BackBufferFormat, 0)); } else { _swapChain = CreateSwapChain(); } CreateResourceViews(); _viewport = new Viewport { TopLeftX = 0, TopLeftY = 0, Width = Size.X, Height = Size.Y, MinDepth = 0, MaxDepth = 1 }; _scissorRect = new(Vector2D<int>.Zero, Size); IDXGISwapChain3* CreateSwapChain() { using ComPtr<IDXGISwapChain1> swapChain = null; var swapChainDesc = new SwapChainDesc1 { BufferCount = FrameCount, Width = (uint) Size.X, Height = (uint) Size.Y, Format = BackBufferFormat, BufferUsage = DXGI.UsageRenderTargetOutput, SwapEffect = SwapEffect.SwapEffectFlipDiscard, SampleDesc = new(1, 0), }; SilkMarshal.ThrowHResult ( Window.CreateDxgiSwapchain ( (IDXGIFactory2*) DxgiFactory, (IUnknown*) _commandQueue, // Swap chain needs the queue so that it can force a flush on it. &swapChainDesc, pFullscreenDesc: null, pRestrictToOutput: null, swapChain.GetAddressOf() ) ); IDXGISwapChain3* swapChain3; var iid = IDXGISwapChain3.Guid; SilkMarshal.ThrowHResult(swapChain.Get().QueryInterface(&iid, (void**) &swapChain3)); return swapChain3; } } protected virtual void DestroyAssets() { } protected virtual void DestroyDescriptorHeaps() { DestroyDSVHeap(); DestroyRTVHeap(); void DestroyDSVHeap() { var dsvHeap = _dsvHeap; if (dsvHeap != null) { _dsvHeap = null; _ = dsvHeap->Release(); } } void DestroyRTVHeap() { var rtvHeap = _rtvHeap; if (rtvHeap != null) { _rtvHeap = null; _ = rtvHeap->Release(); } } } protected override void DestroyDeviceDependentResources() { DestroyAssets(); DestroyGraphicsCommandLists(); DestroyPipelineState(); DestroyRootSignature(); DestroyFenceEvent(); DestroyFence(); DestroyCommandAllocators(); DestroyDescriptorHeaps(); DestroyCommandQueue(); DestroyD3DDevice(); DestroyDxgiAdapter(); DestroyDxgiFactory(); void DestroyCommandAllocators() { for (var i = 0; i < _commandAllocators.Length; i++) { var commandAllocator = _commandAllocators[i]; if (commandAllocator != null) { _commandAllocators[i] = null; _ = commandAllocator->Release(); } } } void DestroyCommandQueue() { var commandQueue = _commandQueue; if (commandQueue != null) { _commandQueue = null; _ = commandQueue->Release(); } } void DestroyD3DDevice() { var d3dDevice = _d3dDevice; if (d3dDevice != null) { _d3dDevice = null; _ = d3dDevice->Release(); } } void DestroyDxgiAdapter() { var dxgiAdapter = _dxgiAdapter; if (dxgiAdapter != null) { _dxgiAdapter = null; _ = dxgiAdapter->Release(); } } void DestroyDxgiFactory() { var dxgiFactory = _dxgiFactory; if (dxgiFactory != null) { _dxgiFactory = null; _ = dxgiFactory->Release(); } } void DestroyFence() { var fence = _fence; if (fence != null) { _fence = null; _ = fence->Release(); } } void DestroyFenceEvent() { var fenceEvent = _fenceEvent; if (fenceEvent != IntPtr.Zero) { _fenceEvent = IntPtr.Zero; _ = SilkMarshal.CloseWindowsHandle(_fenceEvent); } } void DestroyGraphicsCommandLists() { for (var i = 0; i < _graphicsCommandLists.Length; i++) { var graphicsCommandList = _graphicsCommandLists[i]; if (graphicsCommandList != null) { _graphicsCommandLists[i] = null; _ = graphicsCommandList->Release(); } } } void DestroyPipelineState() { var pipelineState = _pipelineState; if (pipelineState != null) { _pipelineState = null; _ = pipelineState->Release(); } } void DestroyRootSignature() { var rootSignature = _rootSignature; if (rootSignature != null) { _rootSignature = null; _ = rootSignature->Release(); } } } protected virtual void DestroyResourceViews() { DestroyDepthStencil(); DestroyRenderTargets(); void DestroyDepthStencil() { var depthStencil = _depthStencil; if (depthStencil != null) { _depthStencil = null; _ = depthStencil->Release(); } } void DestroyRenderTargets() { for (var i = 0; i < _renderTargets.Length; i++) { var renderTarget = _renderTargets[i]; if (renderTarget != null) { _renderTargets[i] = null; _ = renderTarget->Release(); } } } } protected override void DestroyWindowSizeDependentResources() { DestroyResourceViews(); DestroySwapChain(); void DestroySwapChain() { var swapChain = _swapChain; if (swapChain != null) { _swapChain = null; _ = swapChain->Release(); } } } protected abstract void Draw(); protected virtual void SetGraphicsCommandListState() { GraphicsCommandList->SetGraphicsRootSignature(RootSignature); fixed (Viewport* viewport = &Viewport) { GraphicsCommandList->RSSetViewports(1, viewport); } fixed (Rectangle<int>* scissorRect = &ScissorRect) { GraphicsCommandList->RSSetScissorRects(1, scissorRect); } } private static ResourceBarrier InitTransition ( ID3D12Resource* pResource, ResourceStates stateBefore, ResourceStates stateAfter, uint subresource = D3D12.ResourceBarrierAllSubresources, ResourceBarrierFlags flags = ResourceBarrierFlags.ResourceBarrierFlagNone ) { // TODO THIS IS A D3DX12 FUNCTION ResourceBarrier result = default; result.Type = ResourceBarrierType.ResourceBarrierTypeTransition; result.Flags = flags; result.Anonymous.Transition.PResource = pResource; result.Anonymous.Transition.StateBefore = stateBefore; result.Anonymous.Transition.StateAfter = stateAfter; result.Anonymous.Transition.Subresource = subresource; return result; } protected virtual void TransitionForRender() { var barrier = InitTransition (RenderTarget, ResourceStates.ResourceStatePresent, ResourceStates.ResourceStateRenderTarget); GraphicsCommandList->ResourceBarrier(1, &barrier); } protected virtual void TransitionForPresent() { var barrier = InitTransition (RenderTarget, ResourceStates.ResourceStateRenderTarget, ResourceStates.ResourceStatePresent); GraphicsCommandList->ResourceBarrier(1, &barrier); } protected override unsafe bool SupportsRequiredDirect3DVersion(IDXGIAdapter1* adapter) { var iid = ID3D12Device.Guid; return HResult.IndicatesSuccess (D3D12.CreateDevice((IUnknown*) adapter, D3DFeatureLevel.D3DFeatureLevel110, &iid, null)); } private void ExecuteGraphicsCommandList() { const int CommandListsCount = 1; var ppCommandLists = stackalloc ID3D12CommandList*[CommandListsCount] { (ID3D12CommandList*) GraphicsCommandList, }; CommandQueue->ExecuteCommandLists(CommandListsCount, ppCommandLists); } private void WaitForGpu(bool moveToNextFrame) { // Schedule a Signal command in the queue. SilkMarshal.ThrowHResult(CommandQueue->Signal(Fence, FenceValue)); if (moveToNextFrame) { FrameIndex = SwapChain->GetCurrentBackBufferIndex(); } if (!moveToNextFrame || (Fence->GetCompletedValue() < FenceValue)) { // Wait until the fence has been crossed. SilkMarshal.ThrowHResult(Fence->SetEventOnCompletion(FenceValue, FenceEvent.ToPointer())); _ = SilkMarshal.WaitWindowsObjects(FenceEvent); } // Increment the fence value for the current frame. FenceValue++; } } }
34.203644
145
0.505641
[ "MIT" ]
vincenzoml/Silk.NET
src/Lab/D3D12Triangle/DX12Sample.cs
31,915
C#
using System; using System.Web; using Autofac; using Autofac.Integration.Wcf; namespace MoviesService { public class Global : HttpApplication { protected void Application_Start(object sender, EventArgs e) { var builder = new ContainerBuilder(); builder.RegisterType<MoviesService>().AsSelf(); builder.RegisterType<MovieDataSourceProxy>().As<IMovieDataSourceProxy>().SingleInstance(); builder.RegisterType<MoviesCache>().As<IMoviesCache>().SingleInstance(); builder.RegisterType<MoviesRepository>().As<IMoviesRepository>().SingleInstance(); var container = builder.Build(); AutofacHostFactory.Container = container; } } }
32
103
0.648438
[ "MIT" ]
jonathanconway/cbamovieexercise
MoviesService/Global.asax.cs
770
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/objidl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="BIND_OPTS2" /> struct.</summary> public static unsafe class BIND_OPTS2Tests { /// <summary>Validates that the <see cref="BIND_OPTS2" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<BIND_OPTS2>(), Is.EqualTo(sizeof(BIND_OPTS2))); } /// <summary>Validates that the <see cref="BIND_OPTS2" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(BIND_OPTS2).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="BIND_OPTS2" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(BIND_OPTS2), Is.EqualTo(40)); } else { Assert.That(sizeof(BIND_OPTS2), Is.EqualTo(32)); } } } }
34.659091
145
0.620984
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/objidl/BIND_OPTS2Tests.cs
1,527
C#
using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { frm.ShowDialog(); if (frm.DialogResult == DialogResult.OK) { string s = ""; if (frm.chkResident.Checked == true) s = "-ДА-"; else s = "-НЕТ-"; s = "Резидент: " + s + ", страна рождения: " + frm.cmbCountryBirth.Text.Trim() + ", дата рождения: " + frm.dtpBirth.Value.ToShortDateString() + " г., место рождения: " + frm.txtPlaceBorn.Text.Trim() + (char)13 + (char)10; s = s + "тип ДУЛ: " + frm.cmbDUL.Text.Trim() + ", дата выдачи ДУЛ: " + frm.dtpDUL.Value.ToShortDateString() + " г."; if (frm.dtpEndDUL.Value.ToShortDateString() != "01.01.1900") s = s + ", дата окончания ДУЛ: " + frm.dtpEndDUL.Value.ToShortDateString() + " г."; s = s + (char)13 + (char)10; s = s + "Серия и номер ДУЛ: " + frm.txtDUL.Text.Trim() + ", страна выдачи ДУЛ: " + frm.cmbLandDUL.Text.Trim() + ", орган выдачи ДУЛ: " + frm.txtIssue.Text.Trim() + (char)13 + (char)10; if (frm.txtDUL2.Text.Trim() != "") { s = s + "тип ДУЛ2: " + frm.cmbDUL2.Text.Trim() + ", дата выдачи ДУЛ2:" + frm.dtpDUL2.Value.ToShortDateString() + " г."; if (frm.dtpEndDUL2.Value.ToShortDateString() != "01.01.1900") s = s + ", дата окончания ДУЛ2: " + frm.dtpEndDUL2.Value.ToShortDateString() + " г."; s = s + (char)13 + (char)10; s = s + "Серия и номер ДУЛ2: " + frm.txtDUL2.Text.Trim() + ", страна выдачи ДУЛ2: " + frm.cmbLandDUL2.Text.Trim() + ", орган выдачи ДУЛ2: " + frm.txtIssue2.Text.Trim() + (char)13 + (char)10; } s = s + "---------------------------------------------------------------" + (char)13 + (char)10; s = s + "Адрес:" + (char)13 + (char)10; s = s + "Строка 1:" + frm.txtAddress1.Text.Trim() + (char)13 + (char)10; s = s + "Строка 2:" + frm.txtAddress2.Text.Trim() + (char)13 + (char)10; s = s + "Штат: " + frm.txtState.Text.Trim() + ", нас. пункт: " + frm.txtPunkt.Text.Trim() + ", индекс: " + frm.txtPOSTINDEX.Text.Trim() + ", страна: " + frm.cmbLand.Text.Trim() + (char)13 + (char)10; s = s + "Тел. код: " + frm.cmbPhoneCode.Text.Trim() + ", мобильный номер: " + frm.txtPhone.Text.Trim(); } } }
61.071429
237
0.476803
[ "MIT" ]
BorislavVladimirov/C-Software-University
C# ProgrammingBasics September 2018/ForLoops/ConsoleApp1/Program.cs
2,841
C#
using System; using System.Collections.Generic; using System.Linq; using Windows.UI.Xaml.Data; namespace Zafiro.Uno.Converters { public class PipelineConverter : List<IValueConverter>, IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return this.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, language)); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotSupportedException(); } } }
31.5
126
0.692063
[ "MIT" ]
SuperJMN-Zafiro/Zafiro
Source/Zafiro.Uno/Converters/PipelineConverter.cs
630
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TodoApp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; namespace TodoApp.Migrations { [DbContext(typeof(TodoAppMigrationsDbContext))] [Migration("20210323190458_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer) .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.4") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)") .HasColumnName("ApplicationName"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("BrowserInfo"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientId"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientIpAddress"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("ClientName"); b.Property<string>("Comments") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Comments"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("CorrelationId"); b.Property<string>("Exceptions") .HasMaxLength(4000) .HasColumnType("nvarchar(4000)") .HasColumnName("Exceptions"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("HttpMethod") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("HttpMethod"); b.Property<int?>("HttpStatusCode") .HasColumnType("int") .HasColumnName("HttpStatusCode"); b.Property<Guid?>("ImpersonatorTenantId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorTenantId"); b.Property<Guid?>("ImpersonatorUserId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorUserId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Url"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier") .HasColumnName("UserId"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId", "ExecutionTime"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2") .HasColumnName("ExecutionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("MethodName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("MethodName"); b.Property<string>("Parameters") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)") .HasColumnName("Parameters"); b.Property<string>("ServiceName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("ServiceName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime"); b.ToTable("AbpAuditLogActions"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2") .HasColumnName("ChangeTime"); b.Property<byte>("ChangeType") .HasColumnType("tinyint") .HasColumnName("ChangeType"); b.Property<string>("EntityId") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityId"); b.Property<Guid?>("EntityTenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("EntityTypeFullName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityTypeFullName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("EntityChangeId") .HasColumnType("uniqueidentifier"); b.Property<string>("NewValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("NewValue"); b.Property<string>("OriginalValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("OriginalValue"); b.Property<string>("PropertyName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("PropertyName"); b.Property<string>("PropertyTypeFullName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("PropertyTypeFullName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Volo.Abp.BackgroundJobs.BackgroundJobRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsAbandoned") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576) .HasColumnType("nvarchar(max)"); b.Property<string>("JobName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .ValueGeneratedOnAdd() .HasColumnType("tinyint") .HasDefaultValue((byte)15); b.Property<short>("TryCount") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)0); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpFeatureValues"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("Description") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("Regex") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("RegexDescription") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<int>("ValueType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AbpClaimTypes"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityLinkUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("SourceTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("SourceUserId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TargetTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("TargetUserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("SourceUserId", "SourceTenantId", "TargetUserId", "TargetTenantId") .IsUnique() .HasFilter("[SourceTenantId] IS NOT NULL AND [TargetTenantId] IS NOT NULL"); b.ToTable("AbpLinkUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDefault") .HasColumnType("bit") .HasColumnName("IsDefault"); b.Property<bool>("IsPublic") .HasColumnType("bit") .HasColumnName("IsPublic"); b.Property<bool>("IsStatic") .HasColumnType("bit") .HasColumnName("IsStatic"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentitySecurityLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Action") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("Identity") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("TenantId", "Action"); b.HasIndex("TenantId", "ApplicationName"); b.HasIndex("TenantId", "Identity"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpSecurityLogs"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(0) .HasColumnName("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Email"); b.Property<bool>("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("EmailConfirmed"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<bool>("IsExternal") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsExternal"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<bool>("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Name"); b.Property<string>("NormalizedEmail") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedEmail"); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedUserName"); b.Property<string>("PasswordHash") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("PasswordHash"); b.Property<string>("PhoneNumber") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("SecurityStamp"); b.Property<string>("Surname") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Surname"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<bool>("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("TwoFactorEnabled"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("NormalizedEmail"); b.HasIndex("NormalizedUserName"); b.HasIndex("UserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderDisplayName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(196) .HasColumnType("nvarchar(196)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "LoginProvider"); b.HasIndex("LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "UserId"); b.HasIndex("UserId", "OrganizationUnitId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Code") .IsRequired() .HasMaxLength(95) .HasColumnType("nvarchar(95)") .HasColumnName("Code"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("DisplayName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<Guid?>("ParentId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("Code"); b.HasIndex("ParentId"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "RoleId"); b.HasIndex("RoleId", "OrganizationUnitId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("AllowedAccessTokenSigningAlgorithms") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerApiResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiResourceId", "Type"); b.ToTable("IdentityServerApiResourceClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ApiResourceId", "Key", "Value"); b.ToTable("IdentityServerApiResourceProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiResourceId", "Scope"); b.ToTable("IdentityServerApiResourceScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(4000) .HasColumnType("nvarchar(4000)"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ApiResourceId", "Type", "Value"); b.ToTable("IdentityServerApiResourceSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerApiScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b => { b.Property<Guid>("ApiScopeId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiScopeId", "Type"); b.ToTable("IdentityServerApiScopeClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b => { b.Property<Guid>("ApiScopeId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ApiScopeId", "Key", "Value"); b.ToTable("IdentityServerApiScopeProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AbsoluteRefreshTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenType") .HasColumnType("int"); b.Property<bool>("AllowAccessTokensViaBrowser") .HasColumnType("bit"); b.Property<bool>("AllowOfflineAccess") .HasColumnType("bit"); b.Property<bool>("AllowPlainTextPkce") .HasColumnType("bit"); b.Property<bool>("AllowRememberConsent") .HasColumnType("bit"); b.Property<string>("AllowedIdentityTokenSigningAlgorithms") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken") .HasColumnType("bit"); b.Property<bool>("AlwaysSendClientClaims") .HasColumnType("bit"); b.Property<int>("AuthorizationCodeLifetime") .HasColumnType("int"); b.Property<bool>("BackChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("BackChannelLogoutUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("ClientClaimsPrefix") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<int?>("ConsentLifetime") .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int>("DeviceCodeLifetime") .HasColumnType("int"); b.Property<bool>("EnableLocalLogin") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("FrontChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("FrontChannelLogoutUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<int>("IdentityTokenLifetime") .HasColumnType("int"); b.Property<bool>("IncludeJwtId") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("LogoUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("PairWiseSubjectSalt") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ProtocolType") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<int>("RefreshTokenExpiration") .HasColumnType("int"); b.Property<int>("RefreshTokenUsage") .HasColumnType("int"); b.Property<bool>("RequireClientSecret") .HasColumnType("bit"); b.Property<bool>("RequireConsent") .HasColumnType("bit"); b.Property<bool>("RequirePkce") .HasColumnType("bit"); b.Property<bool>("RequireRequestObject") .HasColumnType("bit"); b.Property<int>("SlidingRefreshTokenLifetime") .HasColumnType("int"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh") .HasColumnType("bit"); b.Property<string>("UserCodeType") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<int?>("UserSsoLifetime") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("IdentityServerClients"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Origin") .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.HasKey("ClientId", "Origin"); b.ToTable("IdentityServerClientCorsOrigins"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("GrantType") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.HasKey("ClientId", "GrantType"); b.ToTable("IdentityServerClientGrantTypes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Provider") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ClientId", "Provider"); b.ToTable("IdentityServerClientIdPRestrictions"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("PostLogoutRedirectUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "PostLogoutRedirectUri"); b.ToTable("IdentityServerClientPostLogoutRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "Key", "Value"); b.ToTable("IdentityServerClientProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("RedirectUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "RedirectUri"); b.ToTable("IdentityServerClientRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ClientId", "Scope"); b.ToTable("IdentityServerClientScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(4000) .HasColumnType("nvarchar(4000)"); b.Property<string>("Description") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("DeviceCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("UserCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("Id"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.HasIndex("UserCode"); b.ToTable("IdentityServerDeviceFlowCodes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b => { b.Property<string>("Key") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime?>("ConsumedTime") .HasColumnType("datetime2"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.HasIndex("SubjectId", "SessionId", "Type"); b.ToTable("IdentityServerPersistedGrants"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerIdentityResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("IdentityResourceId", "Type"); b.ToTable("IdentityServerIdentityResourceClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("IdentityResourceId", "Key", "Value"); b.ToTable("IdentityServerIdentityResourceProperties"); }); modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpPermissionGrants"); }); modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2048) .HasColumnType("nvarchar(2048)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.HasKey("Id"); b.HasIndex("Name"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.Property<Guid>("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.HasKey("TenantId", "Name"); b.ToTable("AbpTenantConnectionStrings"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("Actions") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("EntityChanges") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.HasOne("Volo.Abp.AuditLogging.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("OrganizationUnits") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("ParentId"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany("Roles") .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Properties") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null) .WithMany("UserClaims") .HasForeignKey("ApiScopeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b => { b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null) .WithMany("Properties") .HasForeignKey("ApiScopeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("Properties") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.HasOne("Volo.Abp.TenantManagement.Tenant", null) .WithMany("ConnectionStrings") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Navigation("Actions"); b.Navigation("EntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Navigation("PropertyChanges"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Navigation("Claims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Navigation("Claims"); b.Navigation("Logins"); b.Navigation("OrganizationUnits"); b.Navigation("Roles"); b.Navigation("Tokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Navigation("Roles"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Navigation("Properties"); b.Navigation("Scopes"); b.Navigation("Secrets"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b => { b.Navigation("Properties"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Navigation("AllowedCorsOrigins"); b.Navigation("AllowedGrantTypes"); b.Navigation("AllowedScopes"); b.Navigation("Claims"); b.Navigation("ClientSecrets"); b.Navigation("IdentityProviderRestrictions"); b.Navigation("PostLogoutRedirectUris"); b.Navigation("Properties"); b.Navigation("RedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Navigation("Properties"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Navigation("ConnectionStrings"); }); #pragma warning restore 612, 618 } } }
38.542461
117
0.443995
[ "MIT" ]
344089386/abp-samples
TodoApp/Mvc-EfCore/src/TodoApp.EntityFrameworkCore.DbMigrations/Migrations/20210323190458_Initial.Designer.cs
88,958
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.KinesisAnalyticsV2.Outputs { [OutputType] public sealed class ApplicationApplicationConfigurationApplicationCodeConfiguration { /// <summary> /// The location and type of the application code. /// </summary> public readonly Outputs.ApplicationApplicationConfigurationApplicationCodeConfigurationCodeContent? CodeContent; /// <summary> /// Specifies whether the code content is in text or zip format. Valid values: `PLAINTEXT`, `ZIPFILE`. /// </summary> public readonly string CodeContentType; [OutputConstructor] private ApplicationApplicationConfigurationApplicationCodeConfiguration( Outputs.ApplicationApplicationConfigurationApplicationCodeConfigurationCodeContent? codeContent, string codeContentType) { CodeContent = codeContent; CodeContentType = codeContentType; } } }
35.444444
120
0.709248
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/KinesisAnalyticsV2/Outputs/ApplicationApplicationConfigurationApplicationCodeConfiguration.cs
1,276
C#
using Coreflow.Web.Controllers; using Coreflow.Web.Models; using System; using System.Collections.Generic; using System.Linq; namespace Coreflow.Web.Helper { public static class CodeCreatorHelper { public static List<CodeCreatorModel> GetCodeCreatorModels() { return Program.CoreflowInstance.CodeCreatorStorage.GetAllFactories().Select(v => { var cc = v.Create(); var model = CodeCreatorModelHelper.CreateModel(cc, null, null); model.CustomFactory = v.Identifier; model.Identifier = Guid.Empty; model.Arguments = model.Parameters?.Select(p => new ArgumentModel(Guid.Empty, p.Name, p.Type?.AssemblyQualifiedName, "")).ToList() ?? new List<ArgumentModel>(); return model; }).ToList(); } } }
34.68
177
0.618224
[ "MIT" ]
lordmampf/Coreflow
Coreflow.Web/Helper/CodeCreatorHelper.cs
869
C#
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; namespace LinqToDB { using Expressions; using Linq; using Linq.Builder; [PublicAPI] public static class LinqExtensions { #region Table Helpers static readonly MethodInfo _tableNameMethodInfo = MemberHelper.MethodOf(() => TableName<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> TableName<T>([NotNull] this ITable<T> table, [NotNull] string name) { if (table == null) throw new ArgumentNullException("table"); if (name == null) throw new ArgumentNullException("name"); table.Expression = Expression.Call( null, _tableNameMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(name) }); var tbl = table as Table<T>; if (tbl != null) tbl.TableName = name; return table; } static readonly MethodInfo _databaseNameMethodInfo = MemberHelper.MethodOf(() => DatabaseName<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> DatabaseName<T>([NotNull] this ITable<T> table, [NotNull] string name) { if (table == null) throw new ArgumentNullException("table"); if (name == null) throw new ArgumentNullException("name"); table.Expression = Expression.Call( null, _databaseNameMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(name) }); var tbl = table as Table<T>; if (tbl != null) tbl.DatabaseName = name; return table; } static readonly MethodInfo _ownerNameMethodInfo = MemberHelper.MethodOf(() => OwnerName<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> OwnerName<T>([NotNull] this ITable<T> table, [NotNull] string name) { if (table == null) throw new ArgumentNullException("table"); if (name == null) throw new ArgumentNullException("name"); table.Expression = Expression.Call( null, _ownerNameMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(name) }); var tbl = table as Table<T>; if (tbl != null) tbl.SchemaName = name; return table; } static readonly MethodInfo _schemaNameMethodInfo = MemberHelper.MethodOf(() => SchemaName<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> SchemaName<T>([NotNull] this ITable<T> table, [NotNull] string name) { if (table == null) throw new ArgumentNullException("table"); if (name == null) throw new ArgumentNullException("name"); table.Expression = Expression.Call( null, _schemaNameMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(name) }); var tbl = table as Table<T>; if (tbl != null) tbl.SchemaName = name; return table; } static readonly MethodInfo _withTableExpressionMethodInfo = MemberHelper.MethodOf(() => WithTableExpression<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> WithTableExpression<T>([NotNull] this ITable<T> table, [NotNull] string expression) { if (expression == null) throw new ArgumentNullException("expression"); table.Expression = Expression.Call( null, _withTableExpressionMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(expression) }); return table; } static readonly MethodInfo _with = MemberHelper.MethodOf(() => With<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> With<T>([NotNull] this ITable<T> table, [NotNull] string args) { if (args == null) throw new ArgumentNullException("args"); table.Expression = Expression.Call( null, _with.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Constant(args) }); return table; } #endregion #region LoadWith static readonly MethodInfo _loadWithMethodInfo = MemberHelper.MethodOf(() => LoadWith<int>(null, null)).GetGenericMethodDefinition(); [LinqTunnel] public static ITable<T> LoadWith<T>( [NotNull] this ITable<T> table, [NotNull, InstantHandle] Expression<Func<T,object>> selector) { if (table == null) throw new ArgumentNullException("table"); table.Expression = Expression.Call( null, _loadWithMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { table.Expression, Expression.Quote(selector) }); return table; } #endregion #region Scalar Select public static T Select<T>( [NotNull] this IDataContext dataContext, [NotNull, InstantHandle] Expression<Func<T>> selector) { if (dataContext == null) throw new ArgumentNullException("dataContext"); if (selector == null) throw new ArgumentNullException("selector"); var q = new Table<T>(dataContext, selector); foreach (var item in q) return item; throw new InvalidOperationException(); } #endregion #region Delete static readonly MethodInfo _deleteMethodInfo = MemberHelper.MethodOf(() => Delete<int>(null)).GetGenericMethodDefinition(); public static int Delete<T>([NotNull] this IQueryable<T> source) { if (source == null) throw new ArgumentNullException("source"); return source.Provider.Execute<int>( Expression.Call( null, _deleteMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { source.Expression })); } static readonly MethodInfo _deleteMethodInfo2 = MemberHelper.MethodOf(() => Delete<int>(null, null)).GetGenericMethodDefinition(); public static int Delete<T>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,bool>> predicate) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); return source.Provider.Execute<int>( Expression.Call( null, _deleteMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { source.Expression, Expression.Quote(predicate) })); } #endregion #region Update static readonly MethodInfo _updateMethodInfo = MemberHelper.MethodOf(() => Update<int,int>(null, (ITable<int>)null, null)).GetGenericMethodDefinition(); public static int Update<TSource,TTarget>( [NotNull] this IQueryable<TSource> source, [NotNull] ITable<TTarget> target, [NotNull, InstantHandle] Expression<Func<TSource,TTarget>> setter) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<int>( Expression.Call( null, _updateMethodInfo.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { source.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter) })); } static readonly MethodInfo _updateMethodInfo2 = MemberHelper.MethodOf(() => Update<int>(null, null)).GetGenericMethodDefinition(); public static int Update<T>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,T>> setter) { if (source == null) throw new ArgumentNullException("source"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<int>( Expression.Call( null, _updateMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { source.Expression, Expression.Quote(setter) })); } static readonly MethodInfo _updateMethodInfo3 = MemberHelper.MethodOf(() => Update<int>(null, null, null)).GetGenericMethodDefinition(); public static int Update<T>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,bool>> predicate, [NotNull, InstantHandle] Expression<Func<T,T>> setter) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<int>( Expression.Call( null, _updateMethodInfo3.MakeGenericMethod(new[] { typeof(T) }), new[] { source.Expression, Expression.Quote(predicate), Expression.Quote(setter) })); } static readonly MethodInfo _updateMethodInfo4 = MemberHelper.MethodOf(() => Update<int>(null)).GetGenericMethodDefinition(); public static int Update<T>([NotNull] this IUpdatable<T> source) { if (source == null) throw new ArgumentNullException("source"); var query = ((Updatable<T>)source).Query; return query.Provider.Execute<int>( Expression.Call( null, _updateMethodInfo4.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression })); } static readonly MethodInfo _updateMethodInfo5 = MemberHelper.MethodOf(() => Update<int,int>(null, (Expression<Func<int,int>>)null, null)).GetGenericMethodDefinition(); public static int Update<TSource,TTarget>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<TSource,TTarget>> target, [NotNull, InstantHandle] Expression<Func<TSource,TTarget>> setter) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<int>( Expression.Call( null, _updateMethodInfo5.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { source.Expression, Expression.Quote(target), Expression.Quote(setter) })); } class Updatable<T> : IUpdatable<T> { public IQueryable<T> Query; } static readonly MethodInfo _asUpdatableMethodInfo = MemberHelper.MethodOf(() => AsUpdatable<int>(null)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> AsUpdatable<T>([NotNull] this IQueryable<T> source) { if (source == null) throw new ArgumentNullException("source"); var query = source.Provider.CreateQuery<T>( Expression.Call( null, _asUpdatableMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { source.Expression })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo = MemberHelper.MethodOf(() => Set<int,int>((IQueryable<int>)null,null,(Expression<Func<int,int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, [NotNull, InstantHandle] Expression<Func<T,TV>> update) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); if (update == null) throw new ArgumentNullException("update"); var query = source.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { source.Expression, Expression.Quote(extract), Expression.Quote(update) })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo2 = MemberHelper.MethodOf(() => Set<int,int>((IUpdatable<int>)null,null,(Expression<Func<int,int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IUpdatable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, [NotNull, InstantHandle] Expression<Func<T,TV>> update) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); if (update == null) throw new ArgumentNullException("update"); var query = ((Updatable<T>)source).Query; query = query.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo2.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(extract), Expression.Quote(update) })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo3 = MemberHelper.MethodOf(() => Set<int,int>((IQueryable<int>)null,null,(Expression<Func<int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, [NotNull, InstantHandle] Expression<Func<TV>> update) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); if (update == null) throw new ArgumentNullException("update"); var query = source.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo3.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { source.Expression, Expression.Quote(extract), Expression.Quote(update) })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo4 = MemberHelper.MethodOf(() => Set<int,int>((IUpdatable<int>)null,null,(Expression<Func<int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IUpdatable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, [NotNull, InstantHandle] Expression<Func<TV>> update) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); if (update == null) throw new ArgumentNullException("update"); var query = ((Updatable<T>)source).Query; query = query.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo4.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(extract), Expression.Quote(update) })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo5 = MemberHelper.MethodOf(() => Set((IQueryable<int>)null,null,0)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IQueryable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, TV value) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); var query = source.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo5.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { source.Expression, Expression.Quote(extract), Expression.Constant(value, typeof(TV)) })); return new Updatable<T> { Query = query }; } static readonly MethodInfo _setMethodInfo6 = MemberHelper.MethodOf(() => Set((IUpdatable<int>)null,null,0)).GetGenericMethodDefinition(); [LinqTunnel] public static IUpdatable<T> Set<T,TV>( [NotNull] this IUpdatable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> extract, TV value) { if (source == null) throw new ArgumentNullException("source"); if (extract == null) throw new ArgumentNullException("extract"); var query = ((Updatable<T>)source).Query; query = query.Provider.CreateQuery<T>( Expression.Call( null, _setMethodInfo6.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(extract), Expression.Constant(value, typeof(TV)) })); return new Updatable<T> { Query = query }; } #endregion #region Insert static readonly MethodInfo _insertMethodInfo = MemberHelper.MethodOf(() => Insert<int>(null,null)).GetGenericMethodDefinition(); public static int Insert<T>( [NotNull] this ITable<T> target, [NotNull, InstantHandle] Expression<Func<T>> setter) { if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); IQueryable<T> query = target; return query.Provider.Execute<int>( Expression.Call( null, _insertMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression, Expression.Quote(setter) })); } static readonly MethodInfo _insertWithIdentityMethodInfo = MemberHelper.MethodOf(() => InsertWithIdentity<int>(null,null)).GetGenericMethodDefinition(); public static object InsertWithIdentity<T>( [NotNull] this ITable<T> target, [NotNull, InstantHandle] Expression<Func<T>> setter) { if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); IQueryable<T> query = target; return query.Provider.Execute<object>( Expression.Call( null, _insertWithIdentityMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression, Expression.Quote(setter) })); } #region ValueInsertable class ValueInsertable<T> : IValueInsertable<T> { public IQueryable<T> Query; } static readonly MethodInfo _intoMethodInfo = MemberHelper.MethodOf(() => Into<int>(null,null)).GetGenericMethodDefinition(); [LinqTunnel] public static IValueInsertable<T> Into<T>(this IDataContext dataContext, [NotNull] ITable<T> target) { if (target == null) throw new ArgumentNullException("target"); IQueryable<T> query = target; var q = query.Provider.CreateQuery<T>( Expression.Call( null, _intoMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { Expression.Constant(null, typeof(IDataContext)), query.Expression })); return new ValueInsertable<T> { Query = q }; } static readonly MethodInfo _valueMethodInfo = MemberHelper.MethodOf(() => Value<int,int>((ITable<int>)null,null,(Expression<Func<int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IValueInsertable<T> Value<T,TV>( [NotNull] this ITable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> field, [NotNull, InstantHandle] Expression<Func<TV>> value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); if (value == null) throw new ArgumentNullException("value"); var query = (IQueryable<T>)source; var q = query.Provider.CreateQuery<T>( Expression.Call( null, _valueMethodInfo.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(field), Expression.Quote(value) })); return new ValueInsertable<T> { Query = q }; } static readonly MethodInfo _valueMethodInfo2 = MemberHelper.MethodOf(() => Value((ITable<int>)null,null,0)).GetGenericMethodDefinition(); [LinqTunnel] public static IValueInsertable<T> Value<T,TV>( [NotNull] this ITable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> field, TV value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); var query = (IQueryable<T>)source; var q = query.Provider.CreateQuery<T>( Expression.Call( null, _valueMethodInfo2.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(field), Expression.Constant(value, typeof(TV)) })); return new ValueInsertable<T> { Query = q }; } static readonly MethodInfo _valueMethodInfo3 = MemberHelper.MethodOf(() => Value<int,int>((IValueInsertable<int>)null,null,(Expression<Func<int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static IValueInsertable<T> Value<T,TV>( [NotNull] this IValueInsertable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> field, [NotNull, InstantHandle] Expression<Func<TV>> value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); if (value == null) throw new ArgumentNullException("value"); var query = ((ValueInsertable<T>)source).Query; var q = query.Provider.CreateQuery<T>( Expression.Call( null, _valueMethodInfo3.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(field), Expression.Quote(value) })); return new ValueInsertable<T> { Query = q }; } static readonly MethodInfo _valueMethodInfo4 = MemberHelper.MethodOf(() => Value((IValueInsertable<int>)null,null,0)).GetGenericMethodDefinition(); [LinqTunnel] public static IValueInsertable<T> Value<T,TV>( [NotNull] this IValueInsertable<T> source, [NotNull, InstantHandle] Expression<Func<T,TV>> field, TV value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); var query = ((ValueInsertable<T>)source).Query; var q = query.Provider.CreateQuery<T>( Expression.Call( null, _valueMethodInfo4.MakeGenericMethod(new[] { typeof(T), typeof(TV) }), new[] { query.Expression, Expression.Quote(field), Expression.Constant(value, typeof(TV)) })); return new ValueInsertable<T> { Query = q }; } static readonly MethodInfo _insertMethodInfo2 = MemberHelper.MethodOf(() => Insert<int>(null)).GetGenericMethodDefinition(); public static int Insert<T>([NotNull] this IValueInsertable<T> source) { if (source == null) throw new ArgumentNullException("source"); var query = ((ValueInsertable<T>)source).Query; return query.Provider.Execute<int>( Expression.Call( null, _insertMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression })); } static readonly MethodInfo _insertWithIdentityMethodInfo2 = MemberHelper.MethodOf(() => InsertWithIdentity<int>(null)).GetGenericMethodDefinition(); public static object InsertWithIdentity<T>([NotNull] this IValueInsertable<T> source) { if (source == null) throw new ArgumentNullException("source"); var query = ((ValueInsertable<T>)source).Query; return query.Provider.Execute<object>( Expression.Call( null, _insertWithIdentityMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression })); } #endregion #region SelectInsertable static readonly MethodInfo _insertMethodInfo3 = MemberHelper.MethodOf(() => Insert<int,int>(null,null,null)).GetGenericMethodDefinition(); public static int Insert<TSource,TTarget>( [NotNull] this IQueryable<TSource> source, [NotNull] ITable<TTarget> target, [NotNull, InstantHandle] Expression<Func<TSource,TTarget>> setter) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<int>( Expression.Call( null, _insertMethodInfo3.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { source.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter) })); } static readonly MethodInfo _insertWithIdentityMethodInfo3 = MemberHelper.MethodOf(() => InsertWithIdentity<int,int>(null,null,null)).GetGenericMethodDefinition(); public static object InsertWithIdentity<TSource,TTarget>( [NotNull] this IQueryable<TSource> source, [NotNull] ITable<TTarget> target, [NotNull, InstantHandle] Expression<Func<TSource,TTarget>> setter) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); if (setter == null) throw new ArgumentNullException("setter"); return source.Provider.Execute<object>( Expression.Call( null, _insertWithIdentityMethodInfo3.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { source.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter) })); } class SelectInsertable<T,TT> : ISelectInsertable<T,TT> { public IQueryable<T> Query; } static readonly MethodInfo _intoMethodInfo2 = MemberHelper.MethodOf(() => Into<int,int>(null,null)).GetGenericMethodDefinition(); [LinqTunnel] public static ISelectInsertable<TSource,TTarget> Into<TSource,TTarget>( [NotNull] this IQueryable<TSource> source, [NotNull] ITable<TTarget> target) { if (target == null) throw new ArgumentNullException("target"); var q = source.Provider.CreateQuery<TSource>( Expression.Call( null, _intoMethodInfo2.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { source.Expression, ((IQueryable<TTarget>)target).Expression })); return new SelectInsertable<TSource,TTarget> { Query = q }; } static readonly MethodInfo _valueMethodInfo5 = MemberHelper.MethodOf(() => Value<int,int,int>(null,null,(Expression<Func<int,int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static ISelectInsertable<TSource,TTarget> Value<TSource,TTarget,TValue>( [NotNull] this ISelectInsertable<TSource,TTarget> source, [NotNull, InstantHandle] Expression<Func<TTarget,TValue>> field, [NotNull, InstantHandle] Expression<Func<TSource,TValue>> value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); if (value == null) throw new ArgumentNullException("value"); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var q = query.Provider.CreateQuery<TSource>( Expression.Call( null, _valueMethodInfo5.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget), typeof(TValue) }), new[] { query.Expression, Expression.Quote(field), Expression.Quote(value) })); return new SelectInsertable<TSource,TTarget> { Query = q }; } static readonly MethodInfo _valueMethodInfo6 = MemberHelper.MethodOf(() => Value<int,int,int>(null,null,(Expression<Func<int>>)null)).GetGenericMethodDefinition(); [LinqTunnel] public static ISelectInsertable<TSource,TTarget> Value<TSource,TTarget,TValue>( [NotNull] this ISelectInsertable<TSource,TTarget> source, [NotNull, InstantHandle] Expression<Func<TTarget,TValue>> field, [NotNull, InstantHandle] Expression<Func<TValue>> value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); if (value == null) throw new ArgumentNullException("value"); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var q = query.Provider.CreateQuery<TSource>( Expression.Call( null, _valueMethodInfo6.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget), typeof(TValue) }), new[] { query.Expression, Expression.Quote(field), Expression.Quote(value) })); return new SelectInsertable<TSource,TTarget> { Query = q }; } static readonly MethodInfo _valueMethodInfo7 = MemberHelper.MethodOf(() => Value<int,int,int>(null,null,0)).GetGenericMethodDefinition(); [LinqTunnel] public static ISelectInsertable<TSource,TTarget> Value<TSource,TTarget,TValue>( [NotNull] this ISelectInsertable<TSource,TTarget> source, [NotNull, InstantHandle] Expression<Func<TTarget,TValue>> field, TValue value) { if (source == null) throw new ArgumentNullException("source"); if (field == null) throw new ArgumentNullException("field"); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var q = query.Provider.CreateQuery<TSource>( Expression.Call( null, _valueMethodInfo7.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget), typeof(TValue) }), new[] { query.Expression, Expression.Quote(field), Expression.Constant(value, typeof(TValue)) })); return new SelectInsertable<TSource,TTarget> { Query = q }; } static readonly MethodInfo _insertMethodInfo4 = MemberHelper.MethodOf(() => Insert<int,int>(null)).GetGenericMethodDefinition(); public static int Insert<TSource,TTarget>([NotNull] this ISelectInsertable<TSource,TTarget> source) { if (source == null) throw new ArgumentNullException("source"); var query = ((SelectInsertable<TSource,TTarget>)source).Query; return query.Provider.Execute<int>( Expression.Call( null, _insertMethodInfo4.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { query.Expression })); } static readonly MethodInfo _insertWithIdentityMethodInfo4 = MemberHelper.MethodOf(() => InsertWithIdentity<int,int>(null)).GetGenericMethodDefinition(); public static object InsertWithIdentity<TSource,TTarget>([NotNull] this ISelectInsertable<TSource,TTarget> source) { if (source == null) throw new ArgumentNullException("source"); var query = ((SelectInsertable<TSource,TTarget>)source).Query; return query.Provider.Execute<object>( Expression.Call( null, _insertWithIdentityMethodInfo4.MakeGenericMethod(new[] { typeof(TSource), typeof(TTarget) }), new[] { query.Expression })); } #endregion #endregion #region InsertOrUpdate static readonly MethodInfo _insertOrUpdateMethodInfo = MemberHelper.MethodOf(() => InsertOrUpdate<int>(null,null,null)).GetGenericMethodDefinition(); public static int InsertOrUpdate<T>( [NotNull] this ITable<T> target, [NotNull, InstantHandle] Expression<Func<T>> insertSetter, [NotNull, InstantHandle] Expression<Func<T,T>> onDuplicateKeyUpdateSetter) { if (target == null) throw new ArgumentNullException("target"); if (insertSetter == null) throw new ArgumentNullException("insertSetter"); if (onDuplicateKeyUpdateSetter == null) throw new ArgumentNullException("onDuplicateKeyUpdateSetter"); IQueryable<T> query = target; return query.Provider.Execute<int>( Expression.Call( null, _insertOrUpdateMethodInfo.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression, Expression.Quote(insertSetter), Expression.Quote(onDuplicateKeyUpdateSetter) })); } static readonly MethodInfo _insertOrUpdateMethodInfo2 = MemberHelper.MethodOf(() => InsertOrUpdate<int>(null,null,null,null)).GetGenericMethodDefinition(); public static int InsertOrUpdate<T>( [NotNull] this ITable<T> target, [NotNull, InstantHandle] Expression<Func<T>> insertSetter, [NotNull, InstantHandle] Expression<Func<T,T>> onDuplicateKeyUpdateSetter, [NotNull, InstantHandle] Expression<Func<T>> keySelector) { if (target == null) throw new ArgumentNullException("target"); if (insertSetter == null) throw new ArgumentNullException("insertSetter"); if (onDuplicateKeyUpdateSetter == null) throw new ArgumentNullException("onDuplicateKeyUpdateSetter"); if (keySelector == null) throw new ArgumentNullException("keySelector"); IQueryable<T> query = target; return query.Provider.Execute<int>( Expression.Call( null, _insertOrUpdateMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression, Expression.Quote(insertSetter), Expression.Quote(onDuplicateKeyUpdateSetter), Expression.Quote(keySelector) })); } #endregion #region DDL Operations static readonly MethodInfo _dropMethodInfo2 = MemberHelper.MethodOf(() => Drop<int>(null)).GetGenericMethodDefinition(); public static int Drop<T>([NotNull] this ITable<T> target) { if (target == null) throw new ArgumentNullException("target"); IQueryable<T> query = target; return query.Provider.Execute<int>( Expression.Call( null, _dropMethodInfo2.MakeGenericMethod(new[] { typeof(T) }), new[] { query.Expression })); } #endregion #region Take / Skip / ElementAt static readonly MethodInfo _takeMethodInfo = MemberHelper.MethodOf(() => Take<int>(null,null)).GetGenericMethodDefinition(); [LinqTunnel] public static IQueryable<TSource> Take<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<int>> count) { if (source == null) throw new ArgumentNullException("source"); if (count == null) throw new ArgumentNullException("count"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, _takeMethodInfo.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Quote(count) })); } static readonly MethodInfo _takeMethodInfo2 = MemberHelper.MethodOf(() => Take<int>(null,null,TakeHints.Percent)).GetGenericMethodDefinition(); /// <summary> /// <see cref="System.Linq.Enumerable.Take{TSource}(System.Collections.Generic.IEnumerable{TSource}, int)"/> /// Using this method may cause runtime <see cref="LinqException"/> if take hints are not supported by database /// </summary> /// <remarks> /// Hints are not supported with <see cref="System.Linq.Enumerable.Skip{TSource}(System.Collections.Generic.IEnumerable{TSource}, int)"/> /// </remarks> /// <typeparam name="TSource"></typeparam> /// <param name="source">source</param> /// <param name="count">number of records to take</param> /// <param name="hints"><see cref="TakeHints"/> hints for SQL Take expression</param> /// <returns></returns> [LinqTunnel] public static IQueryable<TSource> Take<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<int>> count, [NotNull] TakeHints hints) { if (source == null) throw new ArgumentNullException("source"); if (count == null) throw new ArgumentNullException("count"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, _takeMethodInfo2.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Quote(count), Expression.Constant(hints) })); } static readonly MethodInfo _takeMethodInfo3 = MemberHelper.MethodOf(() => Take<int>(null,0,TakeHints.Percent)).GetGenericMethodDefinition(); /// <summary> /// <see cref="System.Linq.Enumerable.Take{TSource}(System.Collections.Generic.IEnumerable{TSource}, int)"/> /// Using this method may cause runtime <see cref="LinqException"/> if take hints are not supported by database /// </summary> /// <remarks> /// Hints are not supported with <see cref="System.Linq.Enumerable.Skip{TSource}(System.Collections.Generic.IEnumerable{TSource}, int)"/> /// </remarks> /// <typeparam name="TSource"></typeparam> /// <param name="source">source</param> /// <param name="count">number of records to take</param> /// <param name="hints"><see cref="TakeHints"/> hints for SQL Take expression</param> /// <returns></returns> [LinqTunnel] public static IQueryable<TSource> Take<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull] int count, [NotNull] TakeHints hints) { if (source == null) throw new ArgumentNullException("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, _takeMethodInfo3.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Constant(count), Expression.Constant(hints) })); } static readonly MethodInfo _skipMethodInfo = MemberHelper.MethodOf(() => Skip<int>(null,null)).GetGenericMethodDefinition(); [LinqTunnel] public static IQueryable<TSource> Skip<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<int>> count) { if (source == null) throw new ArgumentNullException("source"); if (count == null) throw new ArgumentNullException("count"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, _skipMethodInfo.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Quote(count) })); } static readonly MethodInfo _elementAtMethodInfo = MemberHelper.MethodOf(() => ElementAt<int>(null,null)).GetGenericMethodDefinition(); public static TSource ElementAt<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<int>> index) { if (source == null) throw new ArgumentNullException("source"); if (index == null) throw new ArgumentNullException("index"); return source.Provider.Execute<TSource>( Expression.Call( null, _elementAtMethodInfo.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Quote(index) })); } static readonly MethodInfo _elementAtOrDefaultMethodInfo = MemberHelper.MethodOf(() => ElementAtOrDefault<int>(null,null)).GetGenericMethodDefinition(); public static TSource ElementAtOrDefault<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<int>> index) { if (source == null) throw new ArgumentNullException("source"); if (index == null) throw new ArgumentNullException("index"); return source.Provider.Execute<TSource>( Expression.Call( null, _elementAtOrDefaultMethodInfo.MakeGenericMethod(new[] { typeof(TSource) }), new[] { source.Expression, Expression.Quote(index) })); } #endregion #region Having static readonly MethodInfo _setMethodInfo7 = MemberHelper.MethodOf(() => Having((IQueryable<int>)null,null)).GetGenericMethodDefinition(); [LinqTunnel] public static IQueryable<TSource> Having<TSource>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<TSource,bool>> predicate) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, _setMethodInfo7.MakeGenericMethod(typeof(TSource)), new[] { source.Expression, Expression.Quote(predicate) })); } #endregion #region IOrderedQueryable static readonly MethodInfo _thenOrBy = MemberHelper.MethodOf(() => ThenOrBy((IQueryable<int>)null,(Expression<Func<int, int>>)null)).GetGenericMethodDefinition(); public static IOrderedQueryable<TSource> ThenOrBy<TSource, TKey>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>( Expression.Call( null, _thenOrBy.MakeGenericMethod(new[] { typeof(TSource), typeof(TKey) }), new[] { source.Expression, Expression.Quote(keySelector) })); } static readonly MethodInfo _thenOrByDescending = MemberHelper.MethodOf(() => ThenOrByDescending((IQueryable<int>)null, (Expression<Func<int, int>>)null)).GetGenericMethodDefinition(); public static IOrderedQueryable<TSource> ThenOrByDescending<TSource, TKey>( [NotNull] this IQueryable<TSource> source, [NotNull, InstantHandle] Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>( Expression.Call( null, _thenOrByDescending.MakeGenericMethod(new[] { typeof(TSource), typeof(TKey) }), new[] { source.Expression, Expression.Quote(keySelector) })); } #endregion static readonly MethodInfo _setMethodInfo8 = MemberHelper.MethodOf(() => GetContext((IQueryable<int>)null)).GetGenericMethodDefinition(); internal static ContextParser.Context GetContext<TSource>(this IQueryable<TSource> source) { if (source == null) throw new ArgumentNullException("source"); return source.Provider.Execute<ContextParser.Context>( Expression.Call( null, _setMethodInfo8.MakeGenericMethod(typeof(TSource)), new[] { source.Expression })); } #region Stub helpers internal static TOutput Where<TOutput,TSource,TInput>(this TInput source, Func<TSource,bool> predicate) { throw new InvalidOperationException(); } #endregion } }
38.8
186
0.672255
[ "MIT" ]
jogibear9988/linq2db
Source/LinqExtensions.cs
42,294
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace ItaLog.Api.ViewModels.Level { public class LevelViewModel : IComparable<LevelViewModel> { public int Id { get; set; } public string Description { get; set; } public int CompareTo([AllowNull] LevelViewModel other) { return Description.CompareTo(other.Description); } } }
22.9
62
0.668122
[ "MIT" ]
Cadulox/squad-1-ad-csharp-itau-1
ItaLog/ItaLog.Api/ViewModels/Level/LevelViewModel.cs
460
C#
using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using vt_encrypchat.Domain.Entity; namespace vt_encrypchat.Data.Contracts.Repository { public interface IBaseRepository<T> where T : BaseEntity { Task<IEnumerable<T>> GetAll(FilterDefinition<T> filter = null); Task<T> Get(string id); Task Create(T entity); Task Update(T entity); Task Delete(T entity); } }
27.8125
71
0.696629
[ "Apache-2.0" ]
MarkCDavid/vt-encrypchat
vt-encrypchat.Data/Contracts/Repository/IBaseRepository.cs
445
C#
using System.Collections.Generic; using System.Threading.Tasks; using YC.ApplicationService.ApplicationService.SysUserAppService.Dto; using YC.ApplicationService.Dto; using YC.ApplicationService.SysUserAppService; using YC.ApplicationService.SysUserAppService.Dto; using YC.Core; using YC.Core.Autofac; using YC.Core.Domain; using YC.Core.DynamicApi; using YC.Model.SysDbEntity; namespace YC.ApplicationService { public interface ISysUserAppService : IApplicationService, IDependencyInjectionSupport { List<SysUser> GetAllSysUserList(); IApiResult<SysUser> Login(string userId, string pwd, int TenantId = 0); List<SysUser> GetUserList(object condition); Task<IApiResult> GetPageUserListAsync(PageInput<PageInputDto> input); Task<IApiResult> CreateUserAsync(UserAddOrEditDto input); Task<IApiResult> DeleteUserByIdAsync(long id); Task<IApiResult> UpdateUserAsync(UserAddOrEditDto input); Task<ApiResult<UserAddOrEditDto>> GetAsync(long id); IApiResult<UserRolePermissionDto> GetUserRolePermission(long id); } }
34.625
90
0.767148
[ "Apache-2.0" ]
boozzh/yc.boilerplate
src/Backstage/BasicAppLayer/YC.ApplicationService/ApplicationService/SysUserAppService/ISysUserAppService.cs
1,110
C#
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // ---------------------------------------------------------------------------- namespace AppOwnsData.Services { using AppOwnsData.Models; using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; public class PbiEmbedService { private readonly AadService aadService; private readonly string urlPowerBiServiceApiRoot = "https://api.powerbi.com"; public PbiEmbedService(AadService aadService) { this.aadService = aadService; } /// <summary> /// Get Power BI client /// </summary> /// <returns>Power BI client object</returns> public PowerBIClient GetPowerBIClient() { var tokenCredentials = new TokenCredentials(aadService.GetAccessToken(), "Bearer"); return new PowerBIClient(new Uri(urlPowerBiServiceApiRoot ), tokenCredentials); } /// <summary> /// Get embed params for a report /// </summary> /// <returns>Wrapper object containing Embed token, Embed URL, Report Id, and Report name for single report</returns> public EmbedParams GetEmbedParams(Guid workspaceId, Guid reportId, [Optional] Guid additionalDatasetId) { PowerBIClient pbiClient = this.GetPowerBIClient(); // Get report info var pbiReport = pbiClient.Reports.GetReportInGroup(workspaceId, reportId); // Create list of datasets var datasetIds = new List<Guid>(); // Add dataset associated to the report datasetIds.Add(Guid.Parse(pbiReport.DatasetId)); // Append additional dataset to the list to achieve dynamic binding later if (additionalDatasetId != Guid.Empty) { datasetIds.Add(additionalDatasetId); } // Add report data for embedding var embedReports = new List<EmbedReport>() { new EmbedReport { ReportId = pbiReport.Id, ReportName = pbiReport.Name, EmbedUrl = pbiReport.EmbedUrl } }; // Get Embed token multiple resources var embedToken = GetEmbedToken(reportId, datasetIds, workspaceId); // Capture embed params var embedParams = new EmbedParams { EmbedReport = embedReports, Type = "Report", EmbedToken = embedToken }; return embedParams; } /// <summary> /// Get embed params for multiple reports for a single workspace /// </summary> /// <returns>Wrapper object containing Embed token, Embed URL, Report Id, and Report name for multiple reports</returns> public EmbedParams GetEmbedParams(Guid workspaceId, IList<Guid> reportIds, [Optional] IList<Guid> additionalDatasetIds) { // Note: This method is an example and is not consumed in this sample app PowerBIClient pbiClient = this.GetPowerBIClient(); // Create mapping for reports and Embed URLs var embedReports = new List<EmbedReport>(); // Create list of datasets var datasetIds = new List<Guid>(); // Get datasets and Embed URLs for all the reports foreach (var reportId in reportIds) { // Get report info var pbiReport = pbiClient.Reports.GetReportInGroup(workspaceId, reportId); datasetIds.Add(Guid.Parse(pbiReport.DatasetId)); // Add report data for embedding embedReports.Add(new EmbedReport { ReportId = pbiReport.Id, ReportName = pbiReport.Name, EmbedUrl = pbiReport.EmbedUrl }); } // Append to existing list of datasets to achieve dynamic binding later if (additionalDatasetIds != null) { datasetIds.AddRange(additionalDatasetIds); } // Get Embed token multiple resources var embedToken = GetEmbedToken(reportIds, datasetIds, workspaceId); // Capture embed params var embedParams = new EmbedParams { EmbedReport = embedReports, Type = "Report", EmbedToken = embedToken }; return embedParams; } /// <summary> /// Get Embed token for single report, multiple datasets, and an optional target workspace /// </summary> /// <returns>Embed token</returns> public EmbedToken GetEmbedToken(Guid reportId, IList<Guid> datasetIds, [Optional] Guid targetWorkspaceId) { PowerBIClient pbiClient = this.GetPowerBIClient(); // Create a request for getting Embed token // This method works only with new Power BI V2 workspace experience var tokenRequest = new GenerateTokenRequestV2( reports: new List<GenerateTokenRequestV2Report>() { new GenerateTokenRequestV2Report(reportId) }, datasets: datasetIds.Select(datasetId => new GenerateTokenRequestV2Dataset(datasetId.ToString())).ToList(), targetWorkspaces: targetWorkspaceId != Guid.Empty ? new List<GenerateTokenRequestV2TargetWorkspace>() { new GenerateTokenRequestV2TargetWorkspace(targetWorkspaceId) } : null ); // Generate Embed token var embedToken = pbiClient.EmbedToken.GenerateToken(tokenRequest); return embedToken; } /// <summary> /// Get Embed token for multiple reports, datasets, and an optional target workspace /// </summary> /// <returns>Embed token</returns> public EmbedToken GetEmbedToken(IList<Guid> reportIds, IList<Guid> datasetIds, [Optional] Guid targetWorkspaceId) { // Note: This method is an example and is not consumed in this sample app PowerBIClient pbiClient = this.GetPowerBIClient(); // Convert report Ids to required types var reports = reportIds.Select(reportId => new GenerateTokenRequestV2Report(reportId)).ToList(); // Convert dataset Ids to required types var datasets = datasetIds.Select(datasetId => new GenerateTokenRequestV2Dataset(datasetId.ToString())).ToList(); // Create a request for getting Embed token // This method works only with new Power BI V2 workspace experience var tokenRequest = new GenerateTokenRequestV2( datasets: datasets, reports: reports, targetWorkspaces: targetWorkspaceId != Guid.Empty ? new List<GenerateTokenRequestV2TargetWorkspace>() { new GenerateTokenRequestV2TargetWorkspace(targetWorkspaceId) } : null ); // Generate Embed token var embedToken = pbiClient.EmbedToken.GenerateToken(tokenRequest); return embedToken; } /// <summary> /// Get Embed token for multiple reports, datasets, and optional target workspaces /// </summary> /// <returns>Embed token</returns> public EmbedToken GetEmbedToken(IList<Guid> reportIds, IList<Guid> datasetIds, [Optional] IList<Guid> targetWorkspaceIds) { // Note: This method is an example and is not consumed in this sample app PowerBIClient pbiClient = this.GetPowerBIClient(); // Convert report Ids to required types var reports = reportIds.Select(reportId => new GenerateTokenRequestV2Report(reportId)).ToList(); // Convert dataset Ids to required types var datasets = datasetIds.Select(datasetId => new GenerateTokenRequestV2Dataset(datasetId.ToString())).ToList(); // Convert target workspace Ids to required types IList<GenerateTokenRequestV2TargetWorkspace> targetWorkspaces = null; if (targetWorkspaceIds != null) { targetWorkspaces = targetWorkspaceIds.Select(targetWorkspaceId => new GenerateTokenRequestV2TargetWorkspace(targetWorkspaceId)).ToList(); } // Create a request for getting Embed token // This method works only with new Power BI V2 workspace experience var tokenRequest = new GenerateTokenRequestV2( datasets: datasets, reports: reports, targetWorkspaces: targetWorkspaceIds != null ? targetWorkspaces : null ); // Generate Embed token var embedToken = pbiClient.EmbedToken.GenerateToken(tokenRequest); return embedToken; } } }
39.489083
189
0.60721
[ "MIT" ]
E2517/PowerBI-Developer-Samples
.NET Core/Embed for your customers/AppOwnsData/Services/PbiEmbedService.cs
9,045
C#
using System; namespace MigrateJiraIssuesToGithub { internal class Checker { public static void IsNull(object value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } } public static void IsNull(string value, string parameterName) { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException(parameterName); } } } }
23.26087
69
0.542056
[ "MIT" ]
gBritz/JiraToGithubMigrator
src/MigrateJiraIssuesToGithub/Checker.cs
537
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using NUnit.Framework; using System.Threading; namespace TestingProject { class Program { [SetUp] public void Initializer() { PropertiesFile.Driver = new ChromeDriver(); PropertiesFile.Driver.Manage().Window.Maximize(); PropertiesFile.Driver.Navigate().GoToUrl("http://www.thetestroom.com/webapp/"); Console.WriteLine("Testing Started"); } [Test] public void TrialExecution() { Console.WriteLine("Testing"); } [TearDown] public void TestingDone() { PropertiesFile.Driver.Close(); Console.WriteLine("Done Testing"); } static void Main(string[] args) { } } } /************************************************************************************************ //Thread.Sleep(3000); //List<string> hobbies = new List<string>() { "dance", "reading" }; //DetailsPOM obj = new DetailsPOM(); //obj.Resgister("abcdef", "zyxwvu", "single", hobbies, "India", "11", "23", "1992", "1234567890", "window123", "window123@gmail.com", "I am very smart and very dum \n at same time", "Pass@word", "Pass@word"); //// Storing Title name in String variable //String Title = PropertiesFile.Driver.Title; //// Storing Title length in Int variable //int TitleLength = PropertiesFile.Driver.Title.Length; //// Printing Title name on Console //Console.WriteLine("Title of the page is : " + Title); //// Printing Title length on console //Console.WriteLine("Length of the Title is : " + TitleLength); //// Storing URL in String variable //String PageURL = PropertiesFile.Driver.Url; //// Storing URL length in Int variable //int URLLength = PageURL.Length; //// Printing URL on Console //Console.WriteLine("URL of the page is : " + PageURL); //// Printing URL length on console //Console.WriteLine("Length of the URL is : " + URLLength); //// Storing Page Source in String variable //String PageSource = PropertiesFile.Driver.PageSource; //// Storing Page Source length in Int variable //int PageSourceLength = PropertiesFile.Driver.PageSource.Length; //// Printing Page Source on console //Console.WriteLine("Page Source of the page is : " + PageSource); //// Printing Page SOurce length on console //Console.WriteLine("Length of the Page Source is : " + PageSourceLength); ***********************************************************************************************/
31.431579
219
0.546551
[ "MIT" ]
brahmi92/QATools
TestingProject/Program.cs
2,988
C#
using System; using NServiceBus; using Raven.Client.Documents; class LegacyFindTypeTagName { void ConfigureConvention(IDocumentStore documentStore) { #region 5to6-LegacyDocumentIdConventions Func<Type, string> defaultConvention = documentStore.Conventions.FindCollectionName; documentStore.Conventions.FindCollectionName = type => { if (type == typeof(ShippingSagaData)) { return ""; } if (type == typeof(ShippingPolicy)) { return ""; } return defaultConvention(type); }; #endregion } class ShippingSagaData : ContainSagaData { } class ShippingPolicy : ContainSagaData { } }
24.875
93
0.572864
[ "Apache-2.0" ]
Cogax/docs.particular.net
Snippets/Raven/Raven_6/UpgradeGuides/5to6/LegacyFindTypeTagName.cs
767
C#
// =============================================================================== // Alachisoft (R) NCache Sample Code. // =============================================================================== // Copyright © Alachisoft. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. // =============================================================================== 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("Asynchronous Operations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alachisoft")] [assembly: AssemblyProduct("Alachisoft ® NCache")] [assembly: AssemblyCopyright("Copyright © 2017 Alachisoft")] [assembly: AssemblyTrademark("NCache is a registered trademark of Alachisoft.")] [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("996200d3-af1d-4177-a410-b1f9c79d1715")] // 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")]
43.510638
84
0.662103
[ "Apache-2.0" ]
Alachisoft/NCache-Samples
legacy-api/dotnet/AsynchronousOperations/AsynchronousOperations/Properties/AssemblyInfo.cs
2,050
C#
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; using InWorldz.Phlox.Glue; using InWorldz.Phlox.Types; using OpenSim.Framework; using OpenMetaverse; using Nini.Config; using System.Threading; using OpenSim.Region.Framework; using OpenSim.Region.CoreModules.Capabilities; namespace InWorldz.Phlox.Engine { public delegate void WorkArrivedDelegate(); public class EngineInterface : INonSharedRegionModule, IScriptEngine, IScriptModule { public const System.Threading.ThreadPriority SUBTASK_PRIORITY = System.Threading.ThreadPriority.Lowest; /// <summary> /// Amount of time to wait for state data from the script engine before we give up /// </summary> private const int STATE_REQUEST_TIMEOUT = 10 * 1000; private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Scene _scene; ScriptLoader _scriptLoader; ExecutionScheduler _exeScheduler; MasterScheduler _masterScheduler; SupportedEventList _eventList = new SupportedEventList(); EventRouter _eventRouter; StateManager _stateManager; private IConfigSource _configSource; public IConfig _scriptConfigSource; private bool _enabled; public string Name { get { return "InWorldz.Phlox"; } } public Type ReplaceableInterface { get { return null; } } public void Initialize(Nini.Config.IConfigSource source) { _configSource = source; Preload(); } private static void PreloadMethods(Type type) { foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (method.IsAbstract) continue; if (method.ContainsGenericParameters || method.IsGenericMethod || method.IsGenericMethodDefinition) continue; if ((method.Attributes & MethodAttributes.PinvokeImpl) > 0) continue; try { System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle); } catch { } } } private static void Preload() { foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { PreloadMethods(type); } foreach (var type in Assembly.GetAssembly(typeof(InWorldz.Phlox.VM.Interpreter)).GetTypes()) { PreloadMethods(type); } } public void Close() { } private void WorkArrived() { _masterScheduler.WorkArrived(); } public void AddRegion(Scene scene) { if (ConfigSource.Configs[ScriptEngineName] == null) ConfigSource.AddConfig(ScriptEngineName); _scriptConfigSource = ConfigSource.Configs[ScriptEngineName]; _enabled = _scriptConfigSource.GetBoolean("Enabled", true); if (!_enabled) return; IWorldComm comms = scene.RequestModuleInterface<IWorldComm>(); if (comms == null) { _log.Error("[Phlox]: Script engine can not start, no worldcomm module found"); return; } comms.SetWorkArrivedDelegate(this.WorkArrived); _scene = scene; _exeScheduler = new ExecutionScheduler(this.WorkArrived, this, comms); _stateManager = new StateManager(_exeScheduler); _exeScheduler.StateManager = _stateManager; _scriptLoader = new ScriptLoader(scene.CommsManager.AssetCache, _exeScheduler, this.WorkArrived, this); _scriptLoader.StateManager = _stateManager; _masterScheduler = new MasterScheduler(_exeScheduler, _scriptLoader, _stateManager); _stateManager.MMasterScheduler = _masterScheduler; _eventRouter = new EventRouter(this); _scene.EventManager.OnRezScript += new EventManager.NewRezScript(EventManager_OnRezScript); _scene.EventManager.OnRemoveScript += new EventManager.RemoveScript(EventManager_OnRemoveScript); _scene.EventManager.OnReloadScript += new EventManager.ReloadScript(EventManager_OnReloadScript); _scene.EventManager.OnScriptReset += new EventManager.ScriptResetDelegate(EventManager_OnScriptReset); _scene.EventManager.OnGetScriptRunning += new EventManager.GetScriptRunning(EventManager_OnGetScriptRunning); _scene.EventManager.OnStartScript += new EventManager.StartScript(EventManager_OnStartScript); _scene.EventManager.OnStopScript += new EventManager.StopScript(EventManager_OnStopScript); _scene.EventManager.OnCompileScript += new EventManager.CompileScript(EventManager_OnCompileScript); _scene.EventManager.OnGroupCrossedToNewParcel += new EventManager.GroupCrossedToNewParcelDelegate(EventManager_OnGroupCrossedToNewParcel); _scene.EventManager.OnSOGOwnerGroupChanged += new EventManager.SOGOwnerGroupChangedDelegate(EventManager_OnSOGOwnerGroupChanged); _scene.EventManager.OnCrossedAvatarReady += OnCrossedAvatarReady; _scene.EventManager.OnGroupBeginInTransit += EventManager_OnGroupBeginInTransit; _scene.EventManager.OnGroupEndInTransit += EventManager_OnGroupEndInTransit; _masterScheduler.Start(); _scene.StackModuleInterface<IScriptModule>(this); Phlox.Util.Preloader.Preload(); } void EventManager_OnGroupEndInTransit(SceneObjectGroup sog, bool transitSuccess) { if (!transitSuccess) { sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, EnableDisableFlag.CrossingWaitEnable); } }); } } void EventManager_OnGroupBeginInTransit(SceneObjectGroup sog) { sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, EnableDisableFlag.CrossingWaitDisable); } }); } void EventManager_OnSOGOwnerGroupChanged(SceneObjectGroup sog, UUID oldGroup, UUID newGroup) { ILandObject parcel = _scene.LandChannel.GetLandObject(sog.RootPart.GroupPosition.X, sog.RootPart.GroupPosition.Y); bool scriptsCanRun = ScriptsCanRun(parcel, sog.RootPart); EnableDisableFlag flag = scriptsCanRun ? EnableDisableFlag.ParcelEnable : EnableDisableFlag.ParcelDisable; sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, flag); } }); } public bool ScriptsCanRun(ILandObject parcel, SceneObjectPart hostPart) { if (hostPart.ParentGroup.IsAttachment) return true; if (parcel == null) return false; bool parcelAllowsOtherScripts = (parcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool parcelAllowsGroupScripts = (parcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool parcelMatchesObjectGroup = parcel.landData.GroupID == hostPart.GroupID; bool ownerOwnsParcel = parcel.landData.OwnerID == hostPart.OwnerID; if (ownerOwnsParcel || parcelAllowsOtherScripts || (parcelAllowsGroupScripts && parcelMatchesObjectGroup)) { return true; } return false; } void EventManager_OnGroupCrossedToNewParcel(SceneObjectGroup group, ILandObject oldParcel, ILandObject newParcel) { if (group.IsAttachment) { //attachment scripts always run and are unaffected by crossings return; } bool scriptsCouldRun = false; bool scriptsCanRun = false; bool oldParcelAllowedOtherScripts = oldParcel != null && (oldParcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool oldParcelAllowedGroupScripts = oldParcel != null && (oldParcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool oldParcelMatchesObjectGroup = oldParcel != null && oldParcel.landData.GroupID == group.GroupID; bool ownerOwnedOldParcel = oldParcel != null && oldParcel.landData.OwnerID == group.OwnerID; bool newParcelAllowsOtherScripts = newParcel != null && (newParcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool newParcelAllowsGroupScripts = newParcel != null && (newParcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool newParcelMatchesObjectGroup = newParcel != null && newParcel.landData.GroupID == group.GroupID; bool ownerOwnsNewParcel = newParcel != null && newParcel.landData.OwnerID == group.OwnerID; if (oldParcel == null || ownerOwnedOldParcel || oldParcelAllowedOtherScripts || (oldParcelAllowedGroupScripts && oldParcelMatchesObjectGroup)) { scriptsCouldRun = true; } if (ownerOwnsNewParcel || newParcelAllowsOtherScripts || (newParcelAllowsGroupScripts && newParcelMatchesObjectGroup)) { scriptsCanRun = true; } List<TaskInventoryItem> scripts = new List<TaskInventoryItem>(); if (scriptsCanRun != scriptsCouldRun) { EnableDisableFlag flag = scriptsCanRun ? EnableDisableFlag.ParcelEnable : EnableDisableFlag.ParcelDisable; if (flag == EnableDisableFlag.ParcelDisable) { //do not parcel disable any scripted group that is holding avatar controls if (group.HasAvatarControls) { return; } } group.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, flag); } }); } } void EventManager_OnCompileScript(string scriptSource, OpenSim.Region.Framework.Interfaces.ICompilationListener compListener) { //compile script to get error output only, do not start a run CompilerFrontend frontEnd = new CompilerFrontend(new CompilationListenerAdaptor(compListener), "."); frontEnd.Compile(scriptSource); } void EventManager_OnStopScript(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ChangeEnabledStatus(itemID, EnableDisableFlag.GeneralDisable); } void EventManager_OnStartScript(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ChangeEnabledStatus(itemID, EnableDisableFlag.GeneralEnable); } void EventManager_OnGetScriptRunning(OpenSim.Framework.IClientAPI controllingClient, OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID) { _exeScheduler.PostScriptInfoRequest(new ScriptInfoRequest(itemID, ScriptInfoRequest.Type.ScriptRunningRequest, delegate(ScriptInfoRequest req) { IEventQueue eq = World.RequestModuleInterface<IEventQueue>(); if (eq != null) { eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, req.IsRunning, false), controllingClient.AgentId); } } )); } void EventManager_OnScriptReset(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ResetScript(itemID); } void EventManager_OnRemoveScript(uint localID, OpenMetaverse.UUID itemID, SceneObjectPart part, EventManager.ScriptPostUnloadDelegate callback, bool allowedDrop, bool fireEvents, ReplaceItemArgs replaceArgs) { _scriptLoader.PostLoadUnloadRequest( new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Unload, LocalId = localID, PostUnloadCallback = callback, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = itemID, AllowedDrop = allowedDrop, FireEvents = fireEvents, ReplaceArgs = replaceArgs, } }); } void EventManager_OnRezScript(uint localID, TaskInventoryItem item, string script, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener) { //try to find the prim associated with the localid SceneObjectPart part = _scene.SceneGraph.GetPrimByLocalId(localID); if (part == null) { _log.ErrorFormat("[Phlox]: Unable to load script {0}. Prim {1} no longer exists", item.ItemID, localID); return; } ILandObject parcel = _scene.LandChannel.GetLandObject(part.GroupPosition.X, part.GroupPosition.Y); bool startDisabled = !ScriptsCanRun(parcel, part); _scriptLoader.PostLoadUnloadRequest(new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Load, OldItemId = item.OldItemID, PostOnRez = (startFlags & ScriptStartFlags.PostOnRez) != 0, ChangedRegionStart = (startFlags & ScriptStartFlags.ChangedRegionStart) != 0, StartParam = startParam, StateSource = (OpenSim.Region.Framework.ScriptStateSource)stateSource, Listener = listener, StartLocalDisabled = startDisabled, StartGlobalDisabled = (startFlags & ScriptStartFlags.StartGloballyDisabled) != 0, FromCrossing = (startFlags & ScriptStartFlags.FromCrossing) != 0, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = item.ItemID, ReplaceArgs = null, // signals that it is not used AllowedDrop = false, // not used FireEvents = false, // not used } }); } void EventManager_OnReloadScript(uint localID, OpenMetaverse.UUID itemID, string script, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener) { //try to find the prim associated with the localid SceneObjectPart part = _scene.SceneGraph.GetPrimByLocalId(localID); if (part == null) { _log.ErrorFormat("[Phlox]: Unable to reload script {0}. Prim {1} no longer exists", itemID, localID); return; } ILandObject parcel = _scene.LandChannel.GetLandObject(part.GroupPosition.X, part.GroupPosition.Y); bool startDisabled = !ScriptsCanRun(parcel, part); _scriptLoader.PostLoadUnloadRequest(new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Reload, PostOnRez = (startFlags & ScriptStartFlags.PostOnRez) != 0, ChangedRegionStart = (startFlags & ScriptStartFlags.ChangedRegionStart) != 0, StartParam = startParam, StateSource = (OpenSim.Region.Framework.ScriptStateSource)stateSource, Listener = listener, StartLocalDisabled = startDisabled, StartGlobalDisabled = (startFlags & ScriptStartFlags.StartGloballyDisabled) != 0, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = itemID, ReplaceArgs = null, // signals that it is not used AllowedDrop = false, // not used FireEvents = false, // not used } }); } public void RemoveRegion(Scene scene) { if (_masterScheduler == null) return; // happens under Phlox if disabled _masterScheduler.Stop(); } public void RegionLoaded(Scene scene) { } #region IScriptEngine Members public IScriptWorkItem QueueEventHandler(object parms) { throw new NotImplementedException(); } public OpenSim.Region.Framework.Scenes.Scene World { get { return _scene; } } public IScriptModule ScriptModule { get { return this; } } VM.DetectVariables DetectParamsToDetectVariables(OpenSim.Region.ScriptEngine.Shared.DetectParams parm) { return new VM.DetectVariables { Grab = new Vector3(), Key = parm.Key.ToString(), BotID = parm.BotID.ToString(), Group = parm.Group.ToString(), LinkNumber = parm.LinkNum, Name = parm.Name, Owner = parm.Owner.ToString(), Pos = parm.Position, Rot = parm.Rotation, Type = parm.Type, Vel = parm.Velocity, TouchBinormal = parm.TouchBinormal, TouchFace = parm.TouchFace, TouchNormal = parm.TouchNormal, TouchPos = parm.TouchPos, TouchST = parm.TouchST, TouchUV = parm.TouchUV }; } VM.DetectVariables[] DetectParamsArrayToDetectVariablesArray(OpenSim.Region.ScriptEngine.Shared.DetectParams[] parms) { if (parms == null) { return new VM.DetectVariables[0]; } VM.DetectVariables[] retVars = new VM.DetectVariables[parms.Length]; for (int i = 0; i < parms.Length; i++) { retVars[i] = this.DetectParamsToDetectVariables(parms[i]); } return retVars; } public bool PostScriptEvent(OpenMetaverse.UUID itemID, OpenSim.Region.ScriptEngine.Shared.EventParams parms) { FunctionSig eventInfo = _eventList.GetEventByName(parms.EventName); VM.DetectVariables[] detectVars = this.DetectParamsArrayToDetectVariablesArray(parms.DetectParams); VM.PostedEvent evt = new VM.PostedEvent { EventType = (SupportedEventList.Events) eventInfo.TableIndex, Args = parms.Params, DetectVars = detectVars }; evt.Normalize(); _exeScheduler.PostEvent(itemID, evt); return true; } public bool PostObjectEvent(uint localID, OpenSim.Region.ScriptEngine.Shared.EventParams parms) { SceneObjectPart part = World.SceneGraph.GetPrimByLocalId(localID); if (part != null) { //grab the local ids of all the scripts and send the event to each script IList<TaskInventoryItem> scripts = part.Inventory.GetScripts(); foreach (TaskInventoryItem script in scripts) { this.PostScriptEvent(script.ItemID, parms); } } return false; } public OpenSim.Region.ScriptEngine.Shared.DetectParams GetDetectParams(OpenMetaverse.UUID item, int number) { throw new NotImplementedException(); } public void SetMinEventDelay(OpenMetaverse.UUID itemID, double delay) { throw new NotImplementedException(); } public int GetStartParameter(OpenMetaverse.UUID itemID) { throw new NotImplementedException(); } public void SetScriptState(OpenMetaverse.UUID itemID, bool state) { EnableDisableFlag flag = state ? EnableDisableFlag.GeneralEnable : EnableDisableFlag.GeneralDisable; _exeScheduler.ChangeEnabledStatus(itemID, flag); } /// <summary> /// Should only be called by the LSL api as it directly accesses the scripts /// </summary> /// <param name="itemID"></param> /// <returns></returns> public bool GetScriptState(OpenMetaverse.UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script == null) return false; return script.ScriptState.Enabled; } public void SetState(OpenMetaverse.UUID itemID, string newState) { throw new NotImplementedException(); } public void ApiResetScript(OpenMetaverse.UUID itemID) { _exeScheduler.ResetNow(itemID); } public void ResetScript(OpenMetaverse.UUID itemID) { _exeScheduler.ResetScript(itemID); } public Nini.Config.IConfig Config { get { return _scriptConfigSource; } } public Nini.Config.IConfigSource ConfigSource { get { return _configSource; } } public string ScriptEngineName { get { return "InWorldz.Phlox"; } } public IScriptApi GetApi(OpenMetaverse.UUID itemID, string name) { throw new NotImplementedException(); } public void UpdateTouchData(uint localId, OpenSim.Region.ScriptEngine.Shared.DetectParams[] det) { SceneObjectPart part = World.SceneGraph.GetPrimByLocalId(localId); if (part != null) { //grab the local ids of all the scripts and send the event to each script IList<TaskInventoryItem> scripts = part.Inventory.GetScripts(); foreach (TaskInventoryItem script in scripts) { VM.DetectVariables[] detectVars = this.DetectParamsArrayToDetectVariablesArray(det); _exeScheduler.UpdateTouchData(script.ItemID, detectVars); } } } #endregion #region IScriptModule Members public string GetAssemblyName(OpenMetaverse.UUID itemID) { throw new NotImplementedException(); } public string GetXMLState(OpenMetaverse.UUID itemID, StopScriptReason stopScriptReason) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemID); return String.Empty; } StateDataRequest req = new StateDataRequest(itemID, true); req.DisableScriptReason = stopScriptReason; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (req.SerializedStateData != null) { return Convert.ToBase64String(req.SerializedStateData); } else { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0}, timeout: {1}", itemID, !success); return String.Empty; } } public byte[] GetBinaryStateSnapshot(OpenMetaverse.UUID itemID, StopScriptReason stopScriptReason) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemID); return null; } StateDataRequest req = new StateDataRequest(itemID, true); req.DisableScriptReason = stopScriptReason; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (req.SerializedStateData != null) { return req.SerializedStateData; } else { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0}, timeout: {1}", itemID, !success); return null; } } public ScriptRuntimeInformation GetScriptInformation(UUID itemId) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemId); return null; } StateDataRequest req = new StateDataRequest(itemId, false); req.DisableScriptReason = StopScriptReason.None; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (!success) return null; Serialization.SerializedRuntimeState state = (Serialization.SerializedRuntimeState)req.RawStateData; ScriptRuntimeInformation info = new ScriptRuntimeInformation { CurrentEvent = state.RunningEvent == null ? "none" : state.RunningEvent.EventType.ToString(), CurrentState = state.RunState.ToString() + " | GlobalEnable: " + state.Enabled + " | " + req.CurrentLocalEnableState.ToString(), MemoryUsed = state.MemInfo.MemoryUsed, TotalRuntime = state.TotalRuntime, NextWakeup = state.NextWakeup, StackFrameFunctionName = state.TopFrame == null ? "none" : state.TopFrame.FunctionInfo.Name, TimerInterval = state.TimerInterval, TimerLastScheduledOn = state.TimerLastScheduledOn }; return info; } public bool PostScriptEvent(OpenMetaverse.UUID itemID, string name, object[] args) { return this.PostScriptEvent(itemID, new OpenSim.Region.ScriptEngine.Shared.EventParams(name, args, null)); } public bool PostObjectEvent(uint localId, string name, object[] args) { return this.PostObjectEvent(localId, new OpenSim.Region.ScriptEngine.Shared.EventParams(name, args, null)); } #endregion /// <summary> /// Can only be called from inside the script run thread as it directly accesses script data /// </summary> /// <param name="itemID"></param> /// <returns></returns> public float GetTotalRuntime(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.TotalRuntime; } return 0.0f; } public int GetFreeMemory(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.MemInfo.MemoryFree; } return 0; } public int GetUsedMemory(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.MemInfo.MemoryUsed; } return 0; } public int GetMaxMemory() { // Same for all scripts. return VM.MemoryInfo.MAX_MEMORY; } public float GetAverageScriptTime(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.GetAverageScriptTime(); } return 0.0f; } /// <summary> /// Can only be called from inside the script run thread as it directly accesses script data /// Returns the amount of free space in the event queue (0 - 1.0) /// </summary> /// <param name="itemID"></param> /// <returns></returns> public float GetEventQueueFreeSpacePercentage(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script == null) return 1.0f; if (script.ScriptState.EventQueue.Count >= VM.RuntimeState.MAX_EVENT_QUEUE_SIZE) return 0.0f; // No space else return 1.0f - (float)script.ScriptState.EventQueue.Count / VM.RuntimeState.MAX_EVENT_QUEUE_SIZE; } /// <summary> /// Sets a timer. Can only be called from inside the script run thread as it directly accesses script data /// </summary> /// <param name="itemID"></param> /// <returns></returns> public void SetTimerEvent(uint localID, UUID itemID, float sec) { _exeScheduler.SetTimer(itemID, sec); } public void SysReturn(UUID itemId, object retValue, int delay) { _exeScheduler.PostSyscallReturn(itemId, retValue, delay); } public void ChangeScriptEnabledLandStatus(SceneObjectGroup group, bool enabled) { group.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem item in part.Inventory.GetScripts()) { if (enabled) { _exeScheduler.ChangeEnabledStatus(item.ItemID, EnableDisableFlag.ParcelEnable); } else { _exeScheduler.ChangeEnabledStatus(item.ItemID, EnableDisableFlag.ParcelDisable); } } }); } /// <summary> /// Continues scripted controls of a seated avatar after crossing /// </summary> /// <param name="satOnPart"></param> /// <param name="client"></param> public void OnCrossedAvatarReady(SceneObjectPart satPart, UUID agentId) { if (satPart == null) return; SceneObjectGroup satOnGroup = satPart.ParentGroup; List<TaskInventoryItem> allScripts = new List<TaskInventoryItem>(); if (satOnGroup != null) { satOnGroup.ForEachPart(delegate(SceneObjectPart part) { allScripts.AddRange(part.Inventory.GetScripts()); }); } foreach (TaskInventoryItem item in allScripts) { _exeScheduler.QueueCrossedAvatarReady(item.ItemID, agentId); } } public void DisableScriptTraces() { _exeScheduler.QueueCommand(new PendingCommand { CommandType = PendingCommand.PCType.StopAllTraces }); } /// <summary> /// Returns serialized compiled script instances given a set of script asset ids /// </summary> /// <param name="assetIds"></param> /// <returns></returns> public Dictionary<UUID, byte[]> GetBytecodeForAssets(IEnumerable<UUID> assetIds) { if (!_masterScheduler.IsRunning) { _log.Error("[Phlox]: Unable to retrieve bytecode data for scripts, master scheduler has died"); return new Dictionary<UUID,byte[]>(); } const int DATA_WAIT_TIMEOUT = 3000; RetrieveBytecodeRequest rbRequest = new RetrieveBytecodeRequest { ScriptIds = assetIds }; _scriptLoader.PostRetrieveByteCodeRequest(rbRequest); rbRequest.WaitForData(DATA_WAIT_TIMEOUT); return rbRequest.Bytecodes; } } }
38.371585
215
0.591398
[ "BSD-3-Clause" ]
ConnectionMaster/halcyon
InWorldz/InWorldz.Phlox.Engine/EngineInterface.cs
35,110
C#
namespace EAMapping { partial class SelectTargetForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SelectTargetForm)); this.elementsListView = new BrightIdeasSoftware.ObjectListView(); this.nameColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.ownerColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.fqnColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.elementsListView)).BeginInit(); this.SuspendLayout(); // // elementsListView // this.elementsListView.AllColumns.Add(this.nameColumn); this.elementsListView.AllColumns.Add(this.ownerColumn); this.elementsListView.AllColumns.Add(this.fqnColumn); this.elementsListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.elementsListView.CellEditUseWholeCell = false; this.elementsListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.nameColumn, this.ownerColumn, this.fqnColumn}); this.elementsListView.Cursor = System.Windows.Forms.Cursors.Default; this.elementsListView.FullRowSelect = true; this.elementsListView.Location = new System.Drawing.Point(12, 12); this.elementsListView.MultiSelect = false; this.elementsListView.Name = "elementsListView"; this.elementsListView.ShowGroups = false; this.elementsListView.Size = new System.Drawing.Size(486, 246); this.elementsListView.TabIndex = 0; this.elementsListView.UseCompatibleStateImageBehavior = false; this.elementsListView.View = System.Windows.Forms.View.Details; this.elementsListView.DoubleClick += new System.EventHandler(this.elementsListView_DoubleClick); // // nameColumn // this.nameColumn.AspectName = "name"; this.nameColumn.Text = "Name"; this.nameColumn.Width = 200; // // ownerColumn // this.ownerColumn.AspectName = "owner.name"; this.ownerColumn.Text = "Owner"; this.ownerColumn.Width = 200; // // fqnColumn // this.fqnColumn.AspectName = "fqn"; this.fqnColumn.FillsFreeSpace = true; this.fqnColumn.Text = "FQN"; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.Cursor = System.Windows.Forms.Cursors.Default; this.okButton.Location = new System.Drawing.Point(342, 264); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 1; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.Cursor = System.Windows.Forms.Cursors.Default; this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(423, 264); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // SelectTargetForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(510, 299); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.elementsListView); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(526, 338); this.Name = "SelectTargetForm"; this.Text = "Select Target Element"; ((System.ComponentModel.ISupportInitialize)(this.elementsListView)).EndInit(); this.ResumeLayout(false); } #endregion private BrightIdeasSoftware.ObjectListView elementsListView; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private BrightIdeasSoftware.OLVColumn nameColumn; private BrightIdeasSoftware.OLVColumn ownerColumn; private BrightIdeasSoftware.OLVColumn fqnColumn; } }
48.589928
165
0.622002
[ "BSD-2-Clause" ]
CuchulainX/Enterprise-Architect-Toolpack
EAMapping/SelectTargetForm.Designer.cs
6,756
C#
// Copyright (c) MASA Stack All rights reserved. // Licensed under the Apache License. See LICENSE.txt in the project root for license information. namespace Masa.Auth.Service.Admin.Infrastructure.Repositories; public class UserRepository : Repository<AuthDbContext, User>, IUserRepository { public UserRepository(AuthDbContext context, IUnitOfWork unitOfWork) : base(context, unitOfWork) { } public async Task<List<User>> GetAllAsync() { return await Context.Set<User>().ToListAsync(); } public async Task<User?> GetDetailAsync(Guid id) { var user = await Context.Set<User>() .Include(u => u.Roles) .Include(u => u.Permissions) .Include(u => u.ThirdPartyUsers) .FirstOrDefaultAsync(u => u.Id == id); return user; } }
30.793103
100
0.612542
[ "Apache-2.0" ]
masastack/MASA.Auth
src/Services/Masa.Auth.Service.Admin/Infrastructure/Repositories/UserRepository.cs
895
C#
namespace BlockRun.Enum { public enum GameState { Menu, Play, GameOver } }
10.181818
25
0.5
[ "Unlicense" ]
guigsc/block-run
Assets/Scripts/Enum/GameState.cs
112
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Flurl; using Flurl.Http; using Microsoft.Extensions.DependencyInjection; using NBitcoin; using Stratis.Bitcoin.Base; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Consensus.Rules; using Stratis.Bitcoin.Features.Miner.Interfaces; using Stratis.Bitcoin.Features.Miner.Staking; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.IntegrationTests.Common; using Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Stratis.Bitcoin.IntegrationTests.Common.ReadyData; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Tests.Common; using Stratis.Bitcoin.Utilities; using Xunit; namespace Stratis.Bitcoin.IntegrationTests { public class ConsensusManagerTests { private const string Password = "password"; private const string WalletName = "mywallet"; private const string Passphrase = "passphrase"; private const string Account = "account 0"; private readonly Network powNetwork; public ConsensusManagerTests() { this.powNetwork = new BitcoinRegTest(); } private class ConsensusOptionsTest : PosConsensusOptions { public ConsensusOptionsTest() : base( maxBlockBaseSize: 1_000_000, maxStandardVersion: 2, maxStandardTxWeight: 100_000, maxBlockSigopsCost: 20_000, maxStandardTxSigopsCost: 20_000 / 5) { } public override int GetStakeMinConfirmations(int height, Network network) { return height < 55 ? 50 : 60; } } public class StratisConsensusOptionsOverrideTest : StratisRegTest { public StratisConsensusOptionsOverrideTest() { this.Name = Guid.NewGuid().ToString(); } } public class BitcoinMaxReorgOverrideTest : BitcoinRegTest { public BitcoinMaxReorgOverrideTest() { this.Name = Guid.NewGuid().ToString(); Type consensusType = typeof(NBitcoin.Consensus); consensusType.GetProperty("MaxReorgLength").SetValue(this.Consensus, (uint)20); } } public class BitcoinOverrideRegTest : BitcoinRegTest { public BitcoinOverrideRegTest() : base() { this.Name = Guid.NewGuid().ToString(); } } public class FailValidation : FullValidationConsensusRule { private readonly int failheight; private int failcount; public FailValidation(int failheight, int failcount = 1) { this.failheight = failheight; this.failcount = failcount; } public override Task RunAsync(RuleContext context) { if (this.failcount > 0) { if (context.ValidationContext.ChainedHeaderToValidate.Height == this.failheight) { this.failcount -= 1; throw new ConsensusErrorException(new ConsensusError("error", "error")); } } return Task.CompletedTask; } } [Fact] public void ConsensusManager_Fork_Occurs_Node_Reorgs_AndResyncs_ToBestHeight() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-1-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-1-minerB").WithDummyWallet().Start(); var syncer = builder.CreateStratisPowNode(this.powNetwork, "cm-1-syncer").Start(); // Sync the network to height 10. TestHelper.ConnectAndSync(syncer, minerA); TestHelper.ConnectAndSync(syncer, minerB); // Disconnect Miner A and B. TestHelper.Disconnect(syncer, minerA); TestHelper.Disconnect(syncer, minerB); // Ensure syncer does not have any connections. TestBase.WaitLoop(() => !TestHelper.IsNodeConnected(syncer)); // Miner A continues to mine to height 15 whilst disconnected. TestHelper.MineBlocks(minerA, 5); // Miner B continues to mine to height 12 whilst disconnected. TestHelper.MineBlocks(minerB, 2); // Syncer now connects to both miners causing a re-org to occur for Miner B back to height 10 TestHelper.Connect(minerA, syncer); TestHelper.Connect(minerB, minerA); // Ensure that Syncer has synced with Miner A and Miner B. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(minerA, syncer)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(minerB, minerA)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerB)); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 15)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 15)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 15)); } } [Fact] public void ConsensusManager_Fork_Occurs_Node_Gets_Disconnected_Due_To_InvalidStakeDepth() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new StratisConsensusOptionsOverrideTest(); // MinerA requires a physical wallet to stake with. var minerA = builder.CreateStratisPosNode(network, "cm-2-minerA").OverrideDateTimeProvider().WithWallet().Start(); var minerB = builder.CreateStratisPosNode(network, "cm-2-minerB").OverrideDateTimeProvider().Start(); // MinerA mines to height 55. TestHelper.MineBlocks(minerA, 55); // Connect and sync minerA and minerB. TestHelper.ConnectAndSync(minerA, minerB); // Disconnect Miner A and B. TestHelper.Disconnect(minerA, minerB); // Miner A stakes a coin that increases the network height to 56. var minter = minerA.FullNode.NodeService<IPosMinting>(); minter.Stake(new WalletSecret() { WalletName = "mywallet", WalletPassword = "password" }); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 56)); minter.StopStake(); // Update the network consensus options so that the GetStakeMinConfirmations returns a higher value // to ensure that the InvalidStakeDepth exception can be thrown. minerB.FullNode.Network.Consensus.Options = new ConsensusOptionsTest(); // Ensure the correct height before the connect. Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 56)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 55)); // Connect minerA to minerB, this will cause an InvalidStakeDepth exception to be thrown on minerB. TestHelper.ConnectNoCheck(minerA, minerB); // Wait until minerA has disconnected minerB due to the InvalidStakeDepth exception. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(minerA, minerB)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 56)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 55)); } } [Fact] public void ConsensusManager_Fork_Occurs_Node_Gets_Disconnected_Due_To_MaxReorgViolation() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new BitcoinMaxReorgOverrideTest(); var minerA = builder.CreateStratisPowNode(network, "cm-3-minerA").WithDummyWallet().Start(); var minerB = builder.CreateStratisPowNode(network, "cm-3-minerB").WithDummyWallet().Start(); // MinerA mines height 10. TestHelper.MineBlocks(minerA, 10); // Connect and sync minerA and minerB. TestHelper.ConnectAndSync(minerA, minerB); // Disconnect minerA from minerB. TestHelper.Disconnect(minerA, minerB); // MinerA continues to mine to height 20 (10 + 10). TestHelper.MineBlocks(minerA, 10); // MinerB continues to mine to height 40 (10 + 30). TestHelper.MineBlocks(minerB, 30); // Ensure the correct height before the connect. Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 20)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 40)); // Connect minerA to minerB. TestHelper.ConnectNoCheck(minerA, minerB); // Wait until the nodes become disconnected due to the MaxReorgViolation. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(minerA, minerB)); // Check that the heights did not change. Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 20)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 40)); } } [Fact] public void ConsensusManager_Reorgs_Then_Old_Chain_Becomes_Longer_Then_Reorg_Back() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-4-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-4-minerB").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start(); var syncer = builder.CreateStratisPowNode(this.powNetwork, "cm-4-syncer").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start(); // Sync the network to height 10. TestHelper.ConnectAndSync(syncer, minerA, minerB); // Disable syncer from sending blocks to miner B TestHelper.DisableBlockPropagation(syncer, minerB); // Miner A and syncer continues to mine to height 15. TestHelper.MineBlocks(minerA, 5); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA)); // Enable syncer to send blocks to miner B TestHelper.EnableBlockPropagation(syncer, minerB); // Disable syncer from sending blocks to miner A TestHelper.DisableBlockPropagation(syncer, minerA); // Miner B continues to mine to height 20 on a new and longer chain whilst disconnected. TestHelper.MineBlocks(minerB, 10); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerB)); // Enable syncer to send blocks to miner B TestHelper.EnableBlockPropagation(syncer, minerA); // Miner A mines to height 25. TestHelper.MineBlocks(minerA, 10); TestBase.WaitLoopMessage(() => TestHelper.AreNodesSyncedMessage(syncer, minerA), waitTimeSeconds: 120); TestBase.WaitLoopMessage(() => TestHelper.AreNodesSyncedMessage(syncer, minerB), waitTimeSeconds: 120); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 25)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 25)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 25)); } } [Fact] public void ConsensusManager_Reorgs_Then_Try_To_Connect_Longer_Chain_With_Connected_Blocks_And_Fail_Then_Revert_Back() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var syncerNetwork = new BitcoinOverrideRegTest(); var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-5-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-5-minerB").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start(); var syncer = builder.CreateStratisPowNode(syncerNetwork, "cm-5-syncer").Start(); // Sync the network to height 10. TestHelper.ConnectAndSync(syncer, minerA, minerB); // Disable syncer from sending blocks to miner B TestHelper.DisableBlockPropagation(syncer, minerB); // Miner A and syncer continues to mine to height 20. TestHelper.MineBlocks(minerA, 10); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 20)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 10)); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 20)); // Inject a rule that will fail at block 15 of the new chain. var engine = syncer.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine; syncerNetwork.Consensus.FullValidationRules.Insert(1, new FailValidation(15)); engine.Register(); // Miner B continues to mine to height 30 on a new and longer chain. TestHelper.MineBlocks(minerB, 20); // check miner B at height 30. Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 30)); // Miner B should become disconnected. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(syncer, minerB)); // Make sure syncer rolled back. TestBase.WaitLoop(() => syncer.FullNode.ConsensusManager().Tip.Height == 20); // Check syncer is still synced with Miner A. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA)); } } [Fact] public void ConsensusManager_Reorgs_Then_Try_To_Connect_Longer_Chain_With_No_Connected_Blocks_And_Fail_Then_Revert_Back() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var syncerNetwork = new BitcoinOverrideRegTest(); var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-6-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-6-minerB").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start(); var syncer = builder.CreateStratisPowNode(syncerNetwork, "cm-6-syncer").Start(); // Sync the network to height 10. TestHelper.ConnectAndSync(syncer, minerA, minerB); // Disable syncer from sending blocks to miner B TestHelper.DisableBlockPropagation(syncer, minerB); // Miner A and syncer continues to mine to height 20. TestHelper.MineBlocks(minerA, 10); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA)); // Inject a rule that will fail at block 11 of the new chain ConsensusRuleEngine engine = syncer.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine; syncerNetwork.Consensus.FullValidationRules.Insert(1, new FailValidation(11)); engine.Register(); // Miner B continues to mine to height 30 on a new and longer chain. TestHelper.MineBlocks(minerB, 20); // check miner B at height 30. Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 30)); // Miner B should become disconnected. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(syncer, minerB)); // Make sure syncer rolled back Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 20)); // Check syncer is still synced with Miner A TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA)); } } [Fact] public void ConsensusManager_Reorg_To_Longest_Chain_Multiple_Times_Without_Invalid_Blocks() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-7-minerA").WithDummyWallet().WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-7-minerB").WithDummyWallet().Start(); var syncer = builder.CreateStratisPowNode(this.powNetwork, "cm-7-syncer"); void flushCondition(IServiceCollection services) { ServiceDescriptor service = services.FirstOrDefault(s => s.ServiceType == typeof(IBlockStoreQueueFlushCondition)); if (service != null) services.Remove(service); services.AddSingleton<IBlockStoreQueueFlushCondition>((serviceprovider) => { var chainState = serviceprovider.GetService<IChainState>(); return new BlockStoreQueueFlushConditionReorgTests(chainState, 10); }); }; syncer.OverrideService(flushCondition).Start(); // Sync the network to height 10. TestHelper.ConnectAndSync(syncer, minerA, minerB); TestHelper.DisableBlockPropagation(syncer, minerA); TestHelper.DisableBlockPropagation(syncer, minerB); // Syncer syncs to minerA's block of 11 TestHelper.MineBlocks(minerA, 1); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 11)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 10)); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 11)); // Syncer jumps chain and reorgs to minerB's longer chain of 12 TestHelper.MineBlocks(minerB, 2); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 11)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 12)); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 12)); // Syncer jumps chain and reorg to minerA's longer chain of 18 TestHelper.MineBlocks(minerA, 2); TestHelper.TriggerSync(syncer); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 13)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 12)); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 13)); } } [Fact] public void ConsensusManager_Connect_New_Block_Failed() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var syncerNetwork = new BitcoinOverrideRegTest(); var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-8-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); var syncer = builder.CreateStratisPowNode(syncerNetwork, "cm-8-syncer").Start(); // Miner A mines to height 11. TestHelper.MineBlocks(minerA, 1); // Inject a rule that will fail at block 11 of the new chain ConsensusRuleEngine engine = syncer.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine; syncerNetwork.Consensus.FullValidationRules.Insert(1, new FailValidation(11)); engine.Register(); // Connect syncer to Miner A, reorg should fail. TestHelper.ConnectNoCheck(syncer, minerA); // Syncer should disconnect from miner A after the failed block. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(syncer, minerA)); // Make sure syncer rolled back Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 10)); } } [Fact] public void ConsensusManager_Fork_Of_100_Blocks_Occurs_Node_Reorgs_And_Resyncs_ToBestHeight() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var minerA = builder.CreateStratisPowNode(this.powNetwork, "cm-9-minerA").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest100Miner).Start(); var minerB = builder.CreateStratisPowNode(this.powNetwork, "cm-9-minerB").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest100Listener).Start(); var syncer = builder.CreateStratisPowNode(this.powNetwork, "cm-9-syncer").WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest100Listener).Start(); // Sync the network to height 100. TestHelper.ConnectAndSync(syncer, minerA, minerB); TestHelper.DisableBlockPropagation(syncer, minerA); TestHelper.DisableBlockPropagation(syncer, minerB); // Miner A mines 105 blocks to height 115. TestHelper.MineBlocks(minerA, 5); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(syncer, minerA), waitTimeSeconds: 120); // Miner B continues mines 110 blocks to a longer chain at height 120. TestHelper.MineBlocks(minerB, 10); TestBase.WaitLoopMessage(() => TestHelper.AreNodesSyncedMessage(syncer, minerB), waitTimeSeconds: 120); // Miner A mines an additional 10 blocks to height 125 that will create the longest chain. TestHelper.MineBlocks(minerA, 10); TestBase.WaitLoopMessage(() => TestHelper.AreNodesSyncedMessage(syncer, minerA), waitTimeSeconds: 120); Assert.True(TestHelper.IsNodeSyncedAtHeight(syncer, 115)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, 115)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, 110)); } } /// <remarks>This test assumes CoinbaseMaturity is 10 and at block 2 there is a huge premine, adjust the test if this changes.</remarks> [Fact] public void ConsensusManager_Fork_Occurs_When_Stake_Coins_Are_Spent_And_Found_In_Rewind_Data() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new StratisRegTest(); var sharedMnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve).ToString(); // MinerA requires an physical wallet to stake with. var minerA = builder.CreateStratisPosNode(network, "cm-10-minerA").OverrideDateTimeProvider().WithWallet(walletMnemonic: sharedMnemonic).Start(); var minerB = builder.CreateStratisPosNode(network, "cm-10-minerB").OverrideDateTimeProvider().WithWallet(walletMnemonic: sharedMnemonic).Start(); // MinerA mines 2 blocks to get the big premine coin and mature them (regtest maturity is 10). TestHelper.MineBlocks(minerA, 12); // Sync the peers A and B (height 3) TestHelper.ConnectAndSync(minerA, minerB); // Miner A will spend the coins WalletSendTransactionModel walletSendTransactionModel = $"http://localhost:{minerA.ApiPort}/api" .AppendPathSegment("wallet/splitcoins") .PostJsonAsync(new SplitCoinsRequest { WalletName = minerA.WalletName, AccountName = "account 0", WalletPassword = minerA.WalletPassword, TotalAmountToSplit = network.Consensus.PremineReward.ToString(), UtxosCount = 2 }) .ReceiveJson<WalletSendTransactionModel>().Result; TestBase.WaitLoop(() => minerA.FullNode.MempoolManager().InfoAll().Count > 0); TestHelper.MineBlocks(minerA, 12); TestBase.WaitLoop(() => minerA.FullNode.ConsensusManager().Tip.Height == 24); Assert.Empty(minerA.FullNode.MempoolManager().InfoAll()); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(minerA, minerB)); // Disconnect Miner A and B. TestHelper.Disconnect(minerA, minerB); // Miner A stakes one coin. (height 13) var minterA = minerA.FullNode.NodeService<IPosMinting>(); minterA.Stake(new WalletSecret() { WalletName = "mywallet", WalletPassword = "password" }); TestBase.WaitLoop(() => minerA.FullNode.ConsensusManager().Tip.Height == 25); minterA.StopStake(); TestHelper.MineBlocks(minerB, 2); // this will push minerb total work to be highest var minterB = minerB.FullNode.NodeService<IPosMinting>(); minterB.Stake(new WalletSecret() { WalletName = WalletName, WalletPassword = Password }); TestBase.WaitLoop(() => minerB.FullNode.ConsensusManager().Tip.Height == 27); minterB.StopStake(); var expectedValidChainHeight = minerB.FullNode.ConsensusManager().Tip.Height; // Sync the network, minerA should switch to minerB. TestHelper.Connect(minerA, minerB); TestBase.WaitLoop(() => TestHelper.IsNodeSyncedAtHeight(minerA, expectedValidChainHeight)); TestBase.WaitLoop(() => TestHelper.IsNodeSyncedAtHeight(minerB, expectedValidChainHeight)); } } /// <summary>We test that two chains that used the same UTXO to stake, the shorter chain can still swap to the longer chain.</summary> [Fact] public void ConsensusManager_Fork_Occurs_When_Stake_Coins_Are_Mined_And_Found_In_Rewind_Data() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new StratisRegTest(); var sharedMnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve).ToString(); // MinerA requires an physical wallet to stake with. var minerA = builder.CreateStratisPosNode(network, "cm-10-minerA").OverrideDateTimeProvider().WithWallet(walletMnemonic: sharedMnemonic).Start(); var minerB = builder.CreateStratisPosNode(network, "cm-10-minerB").OverrideDateTimeProvider().WithWallet(walletMnemonic: sharedMnemonic).Start(); // MinerA mines 2 blocks to get the big premine coin and mature them (regtest maturity is 10). TestHelper.MineBlocks(minerA, 12); // Sync the peers A and B (height 12) TestHelper.ConnectAndSync(minerA, minerB); // Disconnect Miner A and B. TestHelper.DisconnectAll(minerA, minerB); // Miner A stakes one coin. (height 13) var minterA = minerA.FullNode.NodeService<IPosMinting>(); minterA.Stake(new WalletSecret() { WalletName = "mywallet", WalletPassword = "password" }); TestBase.WaitLoop(() => minerA.FullNode.ConsensusManager().Tip.Height == 13); minterA.StopStake(); TestHelper.MineBlocks(minerB, 2); // this will push minerb total work to be highest var minterB = minerB.FullNode.NodeService<IPosMinting>(); minterB.Stake(new WalletSecret() { WalletName = WalletName, WalletPassword = Password }); TestBase.WaitLoop(() => minerB.FullNode.ConsensusManager().Tip.Height == 15); minterB.StopStake(); var expectedValidChainHeight = minerB.FullNode.ConsensusManager().Tip.Height; // Sync the network, minerA should switch to minerB. TestHelper.ConnectAndSync(minerA, minerB); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, expectedValidChainHeight)); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, expectedValidChainHeight)); } } [Fact] public void ConsensusManager_Fork_Occurs_When_Same_Coins_Are_Staked_On_Different_Chains() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new StratisRegTest(); var minerA = builder.CreateStratisPosNode(network, "cm-11-minerA").OverrideDateTimeProvider().WithWallet().Start(); var minerB = builder.CreateStratisPosNode(network, "cm-11-minerB").OverrideDateTimeProvider().Start(); minerB.FullNode.WalletManager().CreateWallet(Password, WalletName, Passphrase, minerA.Mnemonic); var coinbaseMaturity = (int)network.Consensus.CoinbaseMaturity; // MinerA mines maturity +2 blocks to get the big premine coin and make it stakable. TestHelper.MineBlocks(minerA, coinbaseMaturity + 2); // Sync the peers A and B (height 12) TestHelper.ConnectAndSync(minerA, minerB); // Disconnect Miner A and B. TestHelper.DisconnectAll(minerA, minerB); // Miner A stakes one coin. (height 13) var minterA = minerA.FullNode.NodeService<IPosMinting>(); var minterAHeigh = minerA.FullNode.ConsensusManager().Tip.Height; minterA.Stake(new WalletSecret() { WalletName = WalletName, WalletPassword = Password }); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerA, minterAHeigh + 1)); minterA.StopStake(); var minterB = minerB.FullNode.NodeService<IPosMinting>(); var minterBHeigh = minerB.FullNode.ConsensusManager().Tip.Height; minterB.Stake(new WalletSecret() { WalletName = WalletName, WalletPassword = Password }); Assert.True(TestHelper.IsNodeSyncedAtHeight(minerB, minterBHeigh + 1)); minterB.StopStake(); // MinerB mines 1 block on its own fork. (heightB 13) TestHelper.MineBlocks(minerA, 2); TestHelper.MineBlocks(minerB, 3); TestHelper.ConnectAndSync(minerA, minerB); TestBase.WaitLoop(() => minerA.FullNode.ConsensusManager().Tip.HashBlock == minerB.FullNode.ConsensusManager().Tip.HashBlock); Assert.True(minerA.FullNode.ConsensusManager().Tip.HashBlock == minerB.FullNode.ConsensusManager().Tip.HashBlock); } } [Fact] public void ConsensusManager_Block_That_Failed_Partial_Validation_Is_Rejected() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new StratisRegTest(); // MinerA requires a physical wallet to stake with. var minerA = builder.CreateStratisPosNode(network, "minerA").WithWallet().Start(); var minerB = builder.CreateStratisPosNode(network, "minerB").Start(); var minerC = builder.CreateStratisPosNode(network, "minerC").Start(); // MinerA mines to height 5. TestHelper.MineBlocks(minerA, 5); // Connect and sync minerA and minerB. TestHelper.ConnectAndSync(minerA, minerB); TestHelper.Disconnect(minerA, minerB); // Mark block 5 as invalid by changing the signature of the block in memory. (minerB.FullNode.ChainIndexer.GetHeader(5).Block as PosBlock).BlockSignature.Signature = new byte[] { 0 }; // Connect and sync minerB and minerC. TestHelper.ConnectNoCheck(minerB, minerC); // TODO: when signaling failed blocks is enabled we should check this here. // Wait for the nodes to disconnect due to invalid block. TestBase.WaitLoop(() => !TestHelper.IsNodeConnectedTo(minerB, minerC)); Assert.True(minerC.FullNode.NodeService<IPeerBanning>().IsBanned(minerB.Endpoint)); minerC.FullNode.NodeService<IPeerBanning>().UnBanPeer(minerA.Endpoint); TestHelper.ConnectAndSync(minerC, minerA); TestBase.WaitLoop(() => TestHelper.AreNodesSyncedMessage(minerA, minerC).Passed); } } private static Transaction CreateTransactionThatSpendCoinstake(StratisRegTest network, CoreNode minerA, CoreNode minerB, TxIn coinstake, Transaction txWithBigPremine) { Transaction txThatSpendCoinstake = network.CreateTransaction(); txThatSpendCoinstake.AddInput(new TxIn(new OutPoint(txWithBigPremine, 0), PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(minerA.MinerSecret.PubKey))); txThatSpendCoinstake.AddOutput(new TxOut { Value = txWithBigPremine.Outputs[0].Value - new Money(1, MoneyUnit.BTC), ScriptPubKey = minerB.MinerHDAddress.ScriptPubKey }); var dateTimeProvider = minerA.FullNode.NodeService<IDateTimeProvider>(); txThatSpendCoinstake.Time = (uint)dateTimeProvider.GetAdjustedTimeAsUnixTimestamp(); Coin spentCoin = new Coin(txWithBigPremine, 0); List<ICoin> coins = new List<ICoin> { spentCoin }; txThatSpendCoinstake.Sign(minerA.FullNode.Network, minerA.MinerSecret, coins[0]); return txThatSpendCoinstake; } } public class BlockStoreQueueFlushConditionReorgTests : IBlockStoreQueueFlushCondition { private readonly IChainState chainState; private readonly int interceptAtBlockHeight; public BlockStoreQueueFlushConditionReorgTests(IChainState chainState, int interceptAtBlockHeight) { this.chainState = chainState; this.interceptAtBlockHeight = interceptAtBlockHeight; } public bool ShouldFlush { get { if (this.chainState.ConsensusTip.Height >= this.interceptAtBlockHeight) return false; return this.chainState.IsAtBestChainTip; } } } }
47.849315
179
0.621672
[ "MIT" ]
AmsterdamCoin/AmsterdamCoinBitcoinFullNode
src/Stratis.Bitcoin.IntegrationTests/ConsensusManagerTests.cs
34,932
C#
//********************************************************************* //xCAD //Copyright(C) 2021 Xarial Pty Limited //Product URL: https://www.xcad.net //License: https://xcad.xarial.com/license/ //********************************************************************* using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xarial.XCad.Reflection; using Xarial.XCad.UI; using Xarial.XCad.UI.Structures; using Xarial.XCad.UI.TaskPane; using Xarial.XCad.UI.TaskPane.Attributes; namespace Xarial.XCad.Extensions { /// <summary> /// Additional methods for the <see cref="IXExtension"/> /// </summary> public static class XExtensionExtension { /// <summary> /// Creates Task Pane from the enumeration definition /// </summary> /// <typeparam name="TControl">Type of control</typeparam> /// <typeparam name="TEnum">Enumeration defining the commands for Task Pane</typeparam> /// <param name="ext">Extension</param> /// <returns>Task Pane instance</returns> public static IXEnumTaskPane<TControl, TEnum> CreateTaskPane<TControl, TEnum>(this IXExtension ext) where TEnum : Enum { var spec = new TaskPaneSpec(); spec.InitFromEnum<TEnum>(); spec.Buttons = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select( c => { var btn = new TaskPaneEnumButtonSpec<TEnum>(Convert.ToInt32(c)); btn.InitFromEnum(c); btn.Value = c; c.TryGetAttribute<TaskPaneStandardIconAttribute>(a => btn.StandardIcon = a.StandardIcon); return btn; }).ToArray(); return new EnumTaskPane<TControl, TEnum>(ext.CreateTaskPane<TControl>(spec)); } } }
36.490196
109
0.5669
[ "MIT" ]
EddyAlleman/xcad
src/Base/Extensions/XExtensionExtension.cs
1,863
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class gamedataPassiveProficiencyBonusUIData_Record : gamedataTweakDBRecord { public gamedataPassiveProficiencyBonusUIData_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
25.066667
131
0.771277
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/gamedataPassiveProficiencyBonusUIData_Record.cs
362
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.ForecastQueryService")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Forecast Query Service. Amazon Forecast is a fully managed machine learning service that makes it easy for customers to generate accurate forecasts using their historical time-series data")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.118")]
48.40625
274
0.757908
[ "Apache-2.0" ]
ianb888/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/ForecastQueryService/Properties/AssemblyInfo.cs
1,549
C#
using System.Linq; using NUnit.Framework; using SKBKontur.SeleniumTesting.Tests.Helpers; using SKBKontur.SeleniumTesting.Tests.TestEnvironment; namespace SKBKontur.SeleniumTesting.Tests.KebabTests { [DefaultWaitInterval(2000)] public class KebabTest : TestBase { public KebabTest(string reactVersion, string retailUiVersion) : base(reactVersion, retailUiVersion, "0.9.0") { } [SetUp] public void SetUp() { page = OpenUrl("Kebab").GetPageAs<KebabTestPage>(); } [Test] public void TestPresence() { page.DisabledKebab.IsPresent.Wait().That(Is.True); } [Test] public void TestDisabled() { page.DisabledKebab.IsDisabled.Wait().That(Is.True); page.SimpleKebab.IsDisabled.Wait().That(Is.False); } [Test] public void TestMenuExpects() { page.SimpleKebab.Menu.ExpectTo().BeAbsent(); page.SimpleKebab.Click(); page.SimpleKebab.Menu.ExpectTo().BePresent(); page.SimpleKebab.Menu.ExpectTo().Count.EqualTo(3); } [Test] public void TestCheckItems() { page.SimpleKebab.Menu.IsPresent.Wait().That(Is.False); page.SimpleKebab.Click(); page.SimpleKebab.Menu.IsPresent.Wait().That(Is.True); page.SimpleKebab.Menu.Count.Wait().That(Is.EqualTo(3)); page.SimpleKebab.Menu.Select(x => x.Text).Wait().That(Is.EqualTo(new[] {"First", "Second", "Third"})); } [Test] public void TestSelectItemByIndex() { page.Output.Text.Wait().That(Is.EqualTo("none")); page.SimpleKebab.SelectItemByIndex(1); page.Output.Text.Wait().That(Is.EqualTo("second")); } [Test] public void TestSelectItemByText() { page.Output.Text.Wait().That(Is.EqualTo("none")); page.SimpleKebab.SelectItem(x => x.Text.Assert(Is.EqualTo("Second"))); page.Output.Text.Wait().That(Is.EqualTo("second")); } private KebabTestPage page; } }
29.662162
114
0.576765
[ "MIT" ]
ArkadiyVoronov/react-ui-testing
SeleniumTesting/Tests/KebabTests/KebabTest.cs
2,197
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("12. USDtoBGN")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12. USDtoBGN")] [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("69909b95-bd23-446f-8dc0-22903477e0e6")] // 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.756757
84
0.742305
[ "MIT" ]
sevdalin/Software-University-SoftUni
Programming-Basics/02. Simple Calculations/12. USDtoBGN/Properties/AssemblyInfo.cs
1,400
C#
/* * ORY Keto * * Ory Keto is a cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs. * * The version of the OpenAPI document: v0.6.0-alpha.5 * Contact: hi@ory.sh * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; using RestSharp.Deserializers; using RestSharpMethod = RestSharp.Method; using Polly; namespace Ory.Keto.Client.Client { /// <summary> /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// </summary> internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; public CustomJsonCodec(IReadableConfiguration configuration) { _configuration = configuration; } public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) { _serializerSettings = serializerSettings; _configuration = configuration; } /// <summary> /// Serialize the object into a JSON string. /// </summary> /// <param name="obj">Object to be serialized.</param> /// <returns>A JSON string.</returns> public string Serialize(object obj) { if (obj != null && obj is Ory.Keto.Client.Model.AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema return ((Ory.Keto.Client.Model.AbstractOpenAPISchema)obj).ToJson(); } else { return JsonConvert.SerializeObject(obj, _serializerSettings); } } public T Deserialize<T>(IRestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> internal object Deserialize(IRestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { return response.RawBytes; } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { var bytes = response.RawBytes; if (response.Headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in response.Headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(bytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } public string RootElement { get; set; } public string Namespace { get; set; } public string DateFormat { get; set; } public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } } /// <summary> /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), /// encapsulating general REST accessor use cases. /// </summary> public partial class ApiClient : ISynchronousClient, IAsynchronousClient { private readonly String _baseUrl; /// <summary> /// Specifies the settings on a <see cref="JsonSerializer" /> object. /// These settings can be adjusted to accomodate custom serialization rules. /// </summary> public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// </summary> public ApiClient() { _baseUrl = Ory.Keto.Client.Client.GlobalConfiguration.Instance.BasePath; } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> /// </summary> /// <param name="basePath">The target service's base path in URL format.</param> /// <exception cref="ArgumentException"></exception> public ApiClient(String basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); _baseUrl = basePath; } /// <summary> /// Constructs the RestSharp version of an http method /// </summary> /// <param name="method">Swagger Client Custom HttpMethod</param> /// <returns>RestSharp's HttpMethod instance.</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> private RestSharpMethod Method(HttpMethod method) { RestSharpMethod other; switch (method) { case HttpMethod.Get: other = RestSharpMethod.GET; break; case HttpMethod.Post: other = RestSharpMethod.POST; break; case HttpMethod.Put: other = RestSharpMethod.PUT; break; case HttpMethod.Delete: other = RestSharpMethod.DELETE; break; case HttpMethod.Head: other = RestSharpMethod.HEAD; break; case HttpMethod.Options: other = RestSharpMethod.OPTIONS; break; case HttpMethod.Patch: other = RestSharpMethod.PATCH; break; default: throw new ArgumentOutOfRangeException("method", method, null); } return other; } /// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, String path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) throw new ArgumentNullException("path"); if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.Data is Stream stream) { var contentType = "application/octet-stream"; if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; contentType = contentTypes[0]; } var bytes = ClientUtils.ReadAsBytes(stream); request.AddParameter(contentType, bytes, ParameterType.RequestBody); } else { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); else request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return request; } private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) { T result = response.Data; string rawContent = response.Content; var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent) { ErrorText = response.ErrorMessage, Cookies = new List<Cookie>() }; if (response.Headers != null) { foreach (var responseHeader in response.Headers) { transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); } } if (response.Cookies != null) { foreach (var responseCookies in response.Cookies) { transformed.Cookies.Add( new Cookie( responseCookies.Name, responseCookies.Value, responseCookies.Path, responseCookies.Domain) ); } } return transformed; } private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = client.Execute<T>(req); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Ory.Keto.Client.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Ory.Keto.Client.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } #region IAsynchronousClient /// <summary> /// Make a HTTP GET request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP POST request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PUT request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP DELETE request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP HEAD request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP OPTION request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PATCH request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); } #endregion IAsynchronousClient #region ISynchronousClient /// <summary> /// Make a HTTP GET request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config); } /// <summary> /// Make a HTTP POST request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config); } /// <summary> /// Make a HTTP PUT request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config); } /// <summary> /// Make a HTTP DELETE request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config); } /// <summary> /// Make a HTTP HEAD request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config); } /// <summary> /// Make a HTTP OPTION request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config); } /// <summary> /// Make a HTTP PATCH request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config); } #endregion ISynchronousClient } }
45.527231
233
0.57941
[ "Apache-2.0" ]
extraymond/sdk
clients/keto/dotnet/src/Ory.Keto.Client/Client/ApiClient.cs
39,290
C#
using RRHH.BL; 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 RRHHPlanilla { public partial class Busquedas : Form { CargosBL _cargosBL; TrabajadoresBL _trabajoresBL; public Busquedas() { InitializeComponent(); _cargosBL = new CargosBL(); listaCargosBindingSource.DataSource = _cargosBL.ObtenerCargos(); _trabajoresBL = new TrabajadoresBL(); listaTrabajadoresBindingSource.DataSource = _trabajoresBL.ObtenerTrabajador(); } BusquedaBL sql = new BusquedaBL(); private void dvg_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridViewRow filas = dataGridView1.Rows[e.RowIndex]; //textBox1.Text = Convert.ToString(filas.Cells[0].Value); //textBox2.Text = Convert.ToString(filas.Cells[2].Value); //textBox3.Text = Convert.ToString(filas.Cells[3].Value); } private void Busquedas_Load(object sender, EventArgs e) { cargoIdComboBox.SelectedItem = null; dataGridView1.DataSource = sql.MostrarDatos(); //dataGridView1.DataSource = _cargosBL.ObtenerCargos(); //DataGridViewColumn Column1 = dataGridView1.Columns[1]; //Column1.Visible = false; //DataGridViewColumn Column8 = dataGridView1.Columns[8]; //Column8.Visible = false; //DataGridViewColumn Column9 = dataGridView1.Columns[9]; //Column9.Visible = true; //DataGridViewColumn Column10 = dataGridView1.Columns[10]; //Column10.Visible = false; //DataGridViewColumn Column11 = dataGridView1.Columns[11]; //Column11.Visible = false; //DataGridViewColumn Column12 = dataGridView1.Columns[12]; //Column12.Visible = false; } private void textBox4_TextChanged_1(object sender, EventArgs e) { if (textBox4.Text != "") { cargoIdComboBox.SelectedItem = null; dataGridView1.DataSource = sql.Buscar(textBox4.Text, textBox4.Text); } else { dataGridView1.DataSource = sql.MostrarDatos(); } } private void cargoIdComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (cargoIdComboBox.Text != "") { dataGridView1.DataSource = sql.Buscar2(cargoIdComboBox.Text); } else { dataGridView1.DataSource = sql.MostrarDatos(); } } private void piccerrar_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { //listaTrabajadoresBindingSource.EndEdit(); //var trabajador = (Trabajador)listaTrabajadoresBindingSource.Current; //var resultado = _trabajoresBL.GuardarTrabajador(trabajador); //if (resultado.Exitoso == true) //{ // listaTrabajadoresBindingSource.ResetBindings(false); // DialogResult resul = MessageBox.Show("Usuario Guardado", "Exitoso...!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //} dataGridView1.DataSource = sql.MostrarDatos(); } } }
31.946903
141
0.596676
[ "MIT" ]
germanm27/PlanillaRRHHL3
RRHHPlanilla/RRHHPlanilla/Mantenimiento/Busqueda.cs
3,612
C#
using System.Collections.Generic; using System.Linq; namespace DerConverter.Asn.KnownTypes { public class DerAsnSet : DerAsnType<DerAsnType[]> { internal DerAsnSet(IDerAsnDecoder decoder, DerAsnIdentifier identifier, Queue<byte> rawData) : base(decoder, identifier, rawData) { } public DerAsnSet(DerAsnIdentifier identifier, DerAsnType[] value) : base(identifier, value) { } public DerAsnSet(DerAsnType[] value) : base(DerAsnIdentifiers.Constructed.Set, value) { } protected override DerAsnType[] DecodeValue(IDerAsnDecoder decoder, Queue<byte> rawData) { var items = new List<DerAsnType>(); while (rawData.Any()) items.Add(decoder.Decode(rawData)); return items.ToArray(); } protected override IEnumerable<byte> EncodeValue(IDerAsnEncoder encoder, DerAsnType[] value) { return value .Select(x => encoder.Encode(x)) .SelectMany(x => x) .ToArray(); } } }
28.820513
100
0.588968
[ "Apache-2.0" ]
RichardRanft/pem-utils
src/DerConverter/Asn/KnownTypes/DerAsnSet.cs
1,126
C#
using System; using System.Configuration; using System.IdentityModel.Tokens; using System.Security.Claims; using System.Threading.Tasks; using System.Web.Hosting; using DotvvmAuthSample; using DotVVM.Framework.Hosting; using Microsoft.IdentityModel.Protocols; using Microsoft.Owin; using Microsoft.Owin.FileSystems; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Microsoft.Owin.StaticFiles; using Owin; [assembly: OwinStartup(typeof(Startup))] namespace DotvvmAuthSample { public class Startup { public void Configuration(IAppBuilder app) { var applicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath; ConfigureAuth(app); // use DotVVM var dotvvmConfiguration = app.UseDotVVM<DotvvmStartup>(applicationPhysicalPath); #if !DEBUG dotvvmConfiguration.Debug = false; #endif // use static files app.UseStaticFiles(new StaticFileOptions { FileSystem = new PhysicalFileSystem(applicationPhysicalPath) }); } private void ConfigureAuth(IAppBuilder app) { // we need the Cookie Authentication middleware to persist the authentication token app.UseCookieAuthentication(new CookieAuthenticationOptions { ExpireTimeSpan = TimeSpan.FromHours(12), AuthenticationType = CookieAuthenticationDefaults.AuthenticationType }); // set cookie authentication type as default app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); // configure Azure AD authentication var authority = new Uri("https://login.microsoftonline.com/" + ConfigurationManager.AppSettings["ida:TenantId"] + "/"); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["ida:ClientId"], Authority = authority.ToString(), MetadataAddress = new Uri(authority, ".well-known/openid-configuration").ToString(), TokenValidationParameters = new TokenValidationParameters { // we cannot validate issuer in multi-tenant scenarios ValidateIssuer = ConfigurationManager.AppSettings["ida:TenantId"] != "common" }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { // redirect to error page if the authentication fails context.OwinContext.Response.Redirect("/error"); context.HandleResponse(); return Task.FromResult(0); }, RedirectToIdentityProvider = context => { // determines the base URL of the application (useful when the app can run on multiple domains) var appBaseUrl = GetApplicationBaseUrl(context.Request); context.ProtocolMessage.RedirectUri = appBaseUrl; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl; if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest) { // we need to handle the redirect to the login page ourselves because redirects cannot use HTTP 302 in DotVVM var redirectUri = context.ProtocolMessage.CreateAuthenticationRequestUrl(); DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, redirectUri); context.HandleResponse(); } else if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { // we need to handle the redirect to the logout page ourselves because redirects cannot use HTTP 302 in DotVVM var redirectUri = context.ProtocolMessage.CreateLogoutRequestUrl(); DotvvmAuthenticationHelper.ApplyRedirectResponse(context.OwinContext, redirectUri); context.HandleResponse(); } return Task.FromResult(0); }, SecurityTokenValidated = context => { var claimsPrincipal = new ClaimsPrincipal(context.AuthenticationTicket.Identity); // TODO: load custom data and add them in the claims identity (e.g. load user id, roles etc.) // store the identity in the HTTP request context so it can be persisted using the Cookie authentication middleware context.OwinContext.Request.User = claimsPrincipal; return Task.FromResult(0); } } }); } private static string GetApplicationBaseUrl(IOwinRequest contextRequest) => contextRequest.Scheme + "://" + contextRequest.Host + contextRequest.PathBase; } }
44.471545
139
0.599269
[ "Apache-2.0" ]
riganti/dotvvm-samples-azuread-auth
Owin/DotvvmAuthSample/DotvvmAuthSample/Startup.cs
5,470
C#
//------------------------------------------------------------------------------ // <copyright file="PrologToken.cs" company="Axiom"> // // Copyright (c) 2006 Ali Hodroj. All rights reserved. // // The use and distribution terms for this source code are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // </copyright> //------------------------------------------------------------------------------ namespace Axiom.Compiler.Framework { using System; using System.Text; public class PrologToken { /// <summary> /// Token codes. /// </summary> public const int NONE = 0, // Error Token EOF = 1, // End of file STRING = 2, // string ATOM = 3, // atom VARIABLE = 4, // variable LPAREN = 5, // ( RPAREN = 6, // ) DOT = 7, // . LBRACKET = 8, // [ RBRACKET = 9, // ] LIST_SEP = 10, // | COMMA = 11; // , /// <summary> /// Token names. /// </summary> public static readonly string[] names = { "?", "End of File", "String", "Atom", "Variable", "Left Paren.", "Right Paren.", "Dot", "Left Bracket", "Right Bracket", "List Sep.", "Comma", }; private int _kind; // token code (NONE, IDENT, ...) public int Kind { get { return _kind; } set { _kind = value; } } private int _line; // token line number (for error messages) public int Line { get { return _line; } set { _line = value; } } private int _col; // token column number (for error messages) public int Column { get { return _col; } set { _col = value; } } private int _intValue; // numerical value (for numbers and character constants) public int IntValue { get { return _intValue; } set { _intValue = value; } } private string _stringValue; // string representation of token (for numbers and identifiers) /* We keep the string representation of numbers for error messages in case the * number literal in the source code is too big to fit into an int. */ public string StringValue { get { return _stringValue; } set { _stringValue = value; } } public PrologToken (int line, int col) : this(NONE, line, col, 0, null) {} public PrologToken (int kind, int line, int col) : this(kind, line, col, 0, null) {} public PrologToken (int kind, int line, int col, int val) : this(kind, line, col, val, null) {} public PrologToken (int kind, int line, int col, string str) : this(kind, line, col, 0, str) {} public PrologToken (int kind, int line, int col, int val, string str) { this._kind = kind; this._line = line; this._col = col; this._intValue = val; this._stringValue = str; } public override string ToString () { StringBuilder sb = new StringBuilder(); sb.AppendFormat("line {0}, col {1}: {2}", _line, _col, names[_kind]); sb.AppendFormat(" Name: {0}", _stringValue); return sb.ToString(); } } }
27.140625
97
0.529073
[ "MIT" ]
FacticiusVir/prologdotnet
Prolog.Compiler/Framework/PrologToken.cs
3,474
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime: 4.0.30319.42000 // // Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si // el código se vuelve a generar. // </auto-generated> //------------------------------------------------------------------------------ namespace Autopista.Properties { /// <summary> /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.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> /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Autopista.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.333333
175
0.616047
[ "Apache-2.0" ]
JCM-19/POO
Unidad2/Autopista/Autopista/Properties/Resources.Designer.cs
2,917
C#
/* * @author Valentin Simonov / http://va.lent.in/ */ namespace TouchScript.InputSources { /// <summary> /// An object which represents an input source. /// </summary> /// <remarks> /// <para>In TouchScript all touch points (<see cref="ITouch"/>) come from input sources.</para> /// <para>If you want to feed the library with touches the best way to do it is to create a custom input source.</para> /// </remarks> public interface IInputSource { /// <summary> /// Gets or sets current coordinates remapper. /// </summary> /// <value>An object used to change coordinates of touch points coming from this input source.</value> ICoordinatesRemapper CoordinatesRemapper { get; set; } } }
33.347826
123
0.633638
[ "MIT" ]
jackgan90/TouchScript
TouchScript/InputSources/IInputSource.cs
767
C#
using System; using Knet.Kudu.Client.Internal; using Knet.Kudu.Client.Protobuf; using Knet.Kudu.Client.Protocol; namespace Knet.Kudu.Client.Scanner; internal static class RowwiseResultSetConverter { // Used to convert the rowwise data to the newer columnar format, // to avoid virtual calls on ResultSet. // This is only used if the Kudu server is 1.11 or older. public static ResultSet Convert( KuduMessage message, KuduSchema schema, RowwiseRowBlockPB rowPb) { var numColumns = schema.Columns.Count; int columnOffsetsSize = numColumns; if (schema.HasNullableColumns) { columnOffsetsSize++; } var columnOffsets = new int[columnOffsetsSize]; int currentOffset = 0; columnOffsets[0] = currentOffset; // Pre-compute the columns offsets in rowData for easier lookups later. // If the schema has nullables, we also add the offset for the null bitmap at the end. for (int i = 1; i < columnOffsetsSize; i++) { ColumnSchema column = schema.GetColumn(i - 1); int previousSize = column.Size; columnOffsets[i] = previousSize + currentOffset; currentOffset += previousSize; } var rowData = GetRowData(message, rowPb); var indirectData = GetIndirectData(message, rowPb); int nonNullBitmapOffset = columnOffsets[columnOffsets.Length - 1]; int rowSize = schema.RowSize; int numRows = rowPb.NumRows; var dataSidecarOffsets = new SidecarOffset[numColumns]; var varlenDataSidecarOffsets = new SidecarOffset[numColumns]; var nonNullBitmapSidecarOffsets = new SidecarOffset[numColumns]; int nonNullBitmapSize = KuduEncoder.BitsToBytes(numRows); int offset = 0; for (int i = 0; i < numColumns; i++) { var column = schema.GetColumn(i); var dataSize = column.IsFixedSize ? column.Size * numRows : (4 * numRows) + 4; dataSidecarOffsets[i] = new SidecarOffset(offset, dataSize); offset += dataSize; if (column.IsNullable) { nonNullBitmapSidecarOffsets[i] = new SidecarOffset(offset, nonNullBitmapSize); offset += nonNullBitmapSize; } else { nonNullBitmapSidecarOffsets[i] = new SidecarOffset(-1, 0); } } var buffer = new ArrayPoolBuffer<byte>(offset + indirectData.Length); var data = buffer.Buffer; data.AsSpan().Clear(); var varlenData = data.AsSpan(offset); int currentDataOffset = 0; int currentVarlenOffset = 0; for (int columnIndex = 0; columnIndex < numColumns; columnIndex++) { var column = schema.GetColumn(columnIndex); var isFixedSize = column.IsFixedSize; var columnarSize = isFixedSize ? column.Size : 4; var rowwiseSize = column.Size; var dataOffset = dataSidecarOffsets[columnIndex]; var nonNullOffset = nonNullBitmapSidecarOffsets[columnIndex].Start; var dataOutput = data.AsSpan(dataOffset.Start, dataOffset.Length); for (int rowIndex = 0; rowIndex < numRows; rowIndex++) { bool isSet = true; var rowSlice = rowData.Slice(rowSize * rowIndex, rowSize); if (nonNullOffset > 0) { isSet = !rowSlice.GetBit(nonNullBitmapOffset, columnIndex); if (isSet) { data.SetBit(nonNullOffset, rowIndex); } } if (isSet) { if (isFixedSize) { var rawData = rowSlice.Slice(currentDataOffset, columnarSize); rawData.CopyTo(dataOutput); } else { var offsetData = rowSlice.Slice(currentDataOffset, 8); var lengthData = rowSlice.Slice(currentDataOffset + 8, 8); int start = (int)KuduEncoder.DecodeInt64(offsetData); int length = (int)KuduEncoder.DecodeInt64(lengthData); var indirectSlice = indirectData.Slice(start, length); indirectSlice.CopyTo(varlenData); varlenData = varlenData.Slice(length); KuduEncoder.EncodeInt32(dataOutput, currentVarlenOffset); currentVarlenOffset += length; } } dataOutput = dataOutput.Slice(columnarSize); } currentDataOffset += rowwiseSize; if (!isFixedSize) { KuduEncoder.EncodeInt32(dataOutput, currentVarlenOffset); varlenDataSidecarOffsets[columnIndex] = new SidecarOffset(offset, currentVarlenOffset); offset += currentVarlenOffset; currentVarlenOffset = 0; } } return new ResultSet( buffer, schema, numRows, dataSidecarOffsets, varlenDataSidecarOffsets, nonNullBitmapSidecarOffsets); } private static ReadOnlySpan<byte> GetRowData(KuduMessage message, RowwiseRowBlockPB rowPb) { if (rowPb.HasRowsSidecar) { var offset = message.GetSidecarOffset(rowPb.RowsSidecar); return message.Buffer.AsSpan(offset.Start, offset.Length); } return default; } private static ReadOnlySpan<byte> GetIndirectData(KuduMessage message, RowwiseRowBlockPB rowPb) { if (rowPb.HasIndirectDataSidecar) { var offset = message.GetSidecarOffset(rowPb.IndirectDataSidecar); return message.Buffer.AsSpan(offset.Start, offset.Length); } return default; } }
35.017143
103
0.568538
[ "Apache-2.0" ]
xqrzd/kudu
src/Knet.Kudu.Client/Scanner/RowwiseResultSetConverter.cs
6,128
C#
// Copyright (c) Samuel Cragg. // // Licensed under the MIT license. See LICENSE file in the project root for // full license information. namespace SharpKml.Dom.GX { using SharpKml.Base; /// <summary> /// Allows the tour to be paused until a user takes action to continue the tour. /// </summary> /// <remarks>This is not part of the OGC KML 2.2 standard.</remarks> [KmlElement("TourControl", KmlNamespaces.GX22Namespace)] public class TourControl : TourPrimitive { /// <summary> /// Gets or sets whether to pause the tour. /// </summary> [KmlElement("playMode", KmlNamespaces.GX22Namespace)] public PlayMode? Mode { get; set; } } }
30.666667
85
0.623641
[ "MIT" ]
D-Bullock/sharpkml
SharpKml/Dom/GX/TourControl.cs
738
C#
using System.IO; using Cardbooru.Application.Configurations; using Cardbooru.Application.Helpers; using Cardbooru.Application.Interfaces; using Cardbooru.Application.Managers; using Cardbooru.Application.Services; using MvvmCross.Plugins.Messenger; using Ninject; namespace Cardbooru.Application.Infrastructure { public static class Extensions { public static void ConfigureIoc(this IKernel kernel) { kernel.Bind<IMvxMessenger>() .To<MvxMessengerHub>() .InSingletonScope(); kernel.Bind<IBooruHttpClient>() .To<SystemHttpClient>() .InTransientScope(); kernel.Bind<PostFetcherServiceHelper>() .ToSelf() .InSingletonScope(); kernel.Bind<IImageCachingService>() .To<ImageCachingService>() .InSingletonScope(); kernel.Bind<IImageFetcherService>() .To<ImageFetcherService>() .InSingletonScope(); kernel.Bind<IPostFetcherService>() .To<PostFetcherService>() .InSingletonScope(); kernel.Bind<IPostCollectionManager>() .To<BooruCollectionManager>() .InSingletonScope(); kernel.Bind<IBooruConfiguration>() .To<JsonBooruConfiguration>() .InSingletonScope(); kernel.Bind<IBooruPostManager>() .To<BooruPostManager>() .InSingletonScope(); kernel.Bind<CustomJsonSerializer>() .ToSelf() .InSingletonScope(); kernel.Bind<IBooruPostsProviderFactory>() .To<DefaultBooruPostsProviderFactory>() .InSingletonScope(); kernel.Bind<IBooruFullImageViewerFactory>() .To<DefaultBooruFullImageViewerFactory>() .InSingletonScope(); } public static void EnsureCacheDirectoryCreated(this IBooruConfiguration configuration) { var cache = Path.Combine(Directory.GetCurrentDirectory(), configuration.CachePath); if (Directory.Exists(cache)) return; Directory.CreateDirectory(cache); } } }
32.175676
96
0.566149
[ "MIT" ]
matryosha/cardbooru
Cardbooru.Application/Infrastructure/Extensions.cs
2,310
C#
using UnityEngine; public class GameResult : MonoBehaviour { public int score = 0; }
12.857143
39
0.722222
[ "MIT" ]
VitorSoaresSilva/keep-falling-chicken
Assets/Scripts/Data/GameResult.cs
90
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GIDX.SDK.Models { public interface ICustomerDetails { string MerchantCustomerID { get; set; } string Salutation { get; set; } string FirstName { get; set; } string MiddleName { get; set; } string LastName { get; set; } string Suffix { get; set; } string FullName { get; set; } DateTime? DateOfBirth { get; set; } string EmailAddress { get; set; } string CitizenshipCountryCode { get; set; } string IdentificationTypeCode { get; set; } string IdentificationNumber { get; set; } string PhoneNumber { get; set; } string MobilePhoneNumber { get; set; } string AddressLine1 { get; set; } string AddressLine2 { get; set; } string City { get; set; } string StateCode { get; set; } string PostalCode { get; set; } string CountryCode { get; set; } string CustomerIpAddressCountryCode { get; set; } List<string> AdditionalCustomerData { get; set; } /// <summary> /// Optional registration date for customer. Used if you are importing historical customers into the system. /// </summary> DateTime? DateRegistered { get; set; } string Username { get; set; } } }
30.085106
117
0.608204
[ "MIT" ]
TSEVOLLC/GIDX.SDK-csharp
src/GIDX.SDK/Models/ICustomerDetails.cs
1,416
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Hazelcast.Core { internal sealed class TerminatedLifecycleService : ILifecycleService { public bool IsRunning() { return false; } public void Shutdown() { } public void Terminate() { } public string AddLifecycleListener(ILifecycleListener lifecycleListener) { throw new HazelcastInstanceNotActiveException(); } public bool RemoveLifecycleListener(string registrationId) { throw new HazelcastInstanceNotActiveException(); } } }
29.309524
80
0.666125
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.Core/TerminatedLifecycleService.cs
1,231
C#
namespace AirNavigationRaceLive.Properties { // This class allows you to handle specific events on the settings class: // The SettingChanging event is raised before a setting's value is changed. // The PropertyChanged event is raised after a setting's value is changed. // The SettingsLoaded event is raised after the setting values are loaded. // The SettingsSaving event is raised before the setting values are saved. internal sealed partial class Settings { public Settings() { // // To add event handlers for saving and changing settings, uncomment the lines below: // // this.SettingChanging += this.SettingChangingEventHandler; // // this.SettingsSaving += this.SettingsSavingEventHandler; // } private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) { // Add code to handle the SettingChangingEvent event here. } private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) { // Add code to handle the SettingsSaving event here. } } }
42.758621
114
0.659677
[ "MIT" ]
ArminZ/ANR_Scoring_And_Visualisation
AirNavigationRaceLive/Settings.cs
1,242
C#
using System.ComponentModel.DataAnnotations; using Abp.Authorization.Users; namespace HeProject.Models.TokenAuth { public class AuthenticateModel { [Required] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string UserNameOrEmailAddress { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] public string Password { get; set; } public bool RememberClient { get; set; } } }
25.473684
58
0.677686
[ "MIT" ]
hemiaoio/abp-alain
aspnet-core/src/HeProject.Web.Core/Models/TokenAuth/AuthenticateModel.cs
486
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glue.Model { /// <summary> /// Container for the parameters to the StartJobRun operation. /// Starts a job run using a job definition. /// </summary> public partial class StartJobRunRequest : AmazonGlueRequest { private int? _allocatedCapacity; private Dictionary<string, string> _arguments = new Dictionary<string, string>(); private string _jobName; private string _jobRunId; private double? _maxCapacity; private NotificationProperty _notificationProperty; private int? _numberOfWorkers; private string _securityConfiguration; private int? _timeout; private WorkerType _workerType; /// <summary> /// Gets and sets the property AllocatedCapacity. /// <para> /// This field is deprecated. Use <code>MaxCapacity</code> instead. /// </para> /// /// <para> /// The number of AWS Glue data processing units (DPUs) to allocate to this JobRun. From /// 2 to 100 DPUs can be allocated; the default is 10. A DPU is a relative measure of /// processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. /// For more information, see the <a href="https://docs.aws.amazon.com/https:/aws.amazon.com/glue/pricing/">AWS /// Glue pricing page</a>. /// </para> /// </summary> [Obsolete("This property is deprecated, use MaxCapacity instead.")] public int AllocatedCapacity { get { return this._allocatedCapacity.GetValueOrDefault(); } set { this._allocatedCapacity = value; } } // Check to see if AllocatedCapacity property is set internal bool IsSetAllocatedCapacity() { return this._allocatedCapacity.HasValue; } /// <summary> /// Gets and sets the property Arguments. /// <para> /// The job arguments specifically for this run. For this job run, they replace the default /// arguments set in the job definition itself. /// </para> /// /// <para> /// You can specify arguments here that your own job-execution script consumes, as well /// as arguments that AWS Glue itself consumes. /// </para> /// /// <para> /// For information about how to specify and consume your own Job arguments, see the <a /// href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html">Calling /// AWS Glue APIs in Python</a> topic in the developer guide. /// </para> /// /// <para> /// For information about the key-value pairs that AWS Glue consumes to set up your job, /// see the <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html">Special /// Parameters Used by AWS Glue</a> topic in the developer guide. /// </para> /// </summary> public Dictionary<string, string> Arguments { get { return this._arguments; } set { this._arguments = value; } } // Check to see if Arguments property is set internal bool IsSetArguments() { return this._arguments != null && this._arguments.Count > 0; } /// <summary> /// Gets and sets the property JobName. /// <para> /// The name of the job definition to use. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string JobName { get { return this._jobName; } set { this._jobName = value; } } // Check to see if JobName property is set internal bool IsSetJobName() { return this._jobName != null; } /// <summary> /// Gets and sets the property JobRunId. /// <para> /// The ID of a previous <code>JobRun</code> to retry. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string JobRunId { get { return this._jobRunId; } set { this._jobRunId = value; } } // Check to see if JobRunId property is set internal bool IsSetJobRunId() { return this._jobRunId != null; } /// <summary> /// Gets and sets the property MaxCapacity. /// <para> /// The number of AWS Glue data processing units (DPUs) that can be allocated when this /// job runs. A DPU is a relative measure of processing power that consists of 4 vCPUs /// of compute capacity and 16 GB of memory. For more information, see the <a href="https://docs.aws.amazon.com/https:/aws.amazon.com/glue/pricing/">AWS /// Glue pricing page</a>. /// </para> /// /// <para> /// Do not set <code>Max Capacity</code> if using <code>WorkerType</code> and <code>NumberOfWorkers</code>. /// </para> /// /// <para> /// The value that can be allocated for <code>MaxCapacity</code> depends on whether you /// are running a Python shell job, or an Apache Spark ETL job: /// </para> /// <ul> <li> /// <para> /// When you specify a Python shell job (<code>JobCommand.Name</code>="pythonshell"), /// you can allocate either 0.0625 or 1 DPU. The default is 0.0625 DPU. /// </para> /// </li> <li> /// <para> /// When you specify an Apache Spark ETL job (<code>JobCommand.Name</code>="glueetl"), /// you can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job type cannot /// have a fractional DPU allocation. /// </para> /// </li> </ul> /// </summary> public double MaxCapacity { get { return this._maxCapacity.GetValueOrDefault(); } set { this._maxCapacity = value; } } // Check to see if MaxCapacity property is set internal bool IsSetMaxCapacity() { return this._maxCapacity.HasValue; } /// <summary> /// Gets and sets the property NotificationProperty. /// <para> /// Specifies configuration properties of a job run notification. /// </para> /// </summary> public NotificationProperty NotificationProperty { get { return this._notificationProperty; } set { this._notificationProperty = value; } } // Check to see if NotificationProperty property is set internal bool IsSetNotificationProperty() { return this._notificationProperty != null; } /// <summary> /// Gets and sets the property NumberOfWorkers. /// <para> /// The number of workers of a defined <code>workerType</code> that are allocated when /// a job runs. /// </para> /// /// <para> /// The maximum number of workers you can define are 299 for <code>G.1X</code>, and 149 /// for <code>G.2X</code>. /// </para> /// </summary> public int NumberOfWorkers { get { return this._numberOfWorkers.GetValueOrDefault(); } set { this._numberOfWorkers = value; } } // Check to see if NumberOfWorkers property is set internal bool IsSetNumberOfWorkers() { return this._numberOfWorkers.HasValue; } /// <summary> /// Gets and sets the property SecurityConfiguration. /// <para> /// The name of the <code>SecurityConfiguration</code> structure to be used with this /// job run. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string SecurityConfiguration { get { return this._securityConfiguration; } set { this._securityConfiguration = value; } } // Check to see if SecurityConfiguration property is set internal bool IsSetSecurityConfiguration() { return this._securityConfiguration != null; } /// <summary> /// Gets and sets the property Timeout. /// <para> /// The <code>JobRun</code> timeout in minutes. This is the maximum time that a job run /// can consume resources before it is terminated and enters <code>TIMEOUT</code> status. /// The default is 2,880 minutes (48 hours). This overrides the timeout value set in the /// parent job. /// </para> /// </summary> [AWSProperty(Min=1)] public int Timeout { get { return this._timeout.GetValueOrDefault(); } set { this._timeout = value; } } // Check to see if Timeout property is set internal bool IsSetTimeout() { return this._timeout.HasValue; } /// <summary> /// Gets and sets the property WorkerType. /// <para> /// The type of predefined worker that is allocated when a job runs. Accepts a value of /// Standard, G.1X, or G.2X. /// </para> /// <ul> <li> /// <para> /// For the <code>Standard</code> worker type, each worker provides 4 vCPU, 16 GB of memory /// and a 50GB disk, and 2 executors per worker. /// </para> /// </li> <li> /// <para> /// For the <code>G.1X</code> worker type, each worker provides 4 vCPU, 16 GB of memory /// and a 64GB disk, and 1 executor per worker. /// </para> /// </li> <li> /// <para> /// For the <code>G.2X</code> worker type, each worker provides 8 vCPU, 32 GB of memory /// and a 128GB disk, and 1 executor per worker. /// </para> /// </li> </ul> /// </summary> public WorkerType WorkerType { get { return this._workerType; } set { this._workerType = value; } } // Check to see if WorkerType property is set internal bool IsSetWorkerType() { return this._workerType != null; } } }
36.232258
160
0.56989
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/StartJobRunRequest.cs
11,232
C#
using System; using System.Globalization; using System.Text; namespace Ps3DiscDumper.Utils { public static class HexExtensions { public static byte[] ToByteArray(this string hexString) { if (hexString == null) return null; if (hexString.Length == 0) return new byte[0]; if (hexString.Length % 2 != 0) throw new FormatException("Not a valid hex string"); var result = new byte[hexString.Length / 2]; for (int i = 0; i < hexString.Length; i += 2) result[i / 2] = byte.Parse(hexString.Substring(i, 2), NumberStyles.HexNumber); return result; } public static string ToHexString(this byte[] bytes) { if (bytes == null) return null; if (bytes.Length == 0) return ""; var result = new StringBuilder(bytes.Length*2); foreach (var b in bytes) result.Append(b.ToString("x2")); return result.ToString(); } } }
27.097561
94
0.521152
[ "MIT" ]
13xforever/ps3-disc-dumper
Ps3DiscDumper/Utils/HexExtensions.cs
1,113
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("GetAllReadMoreUrls")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GetAllReadMoreUrls")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("c9e599c6-6da0-4e16-936d-2362c088df7c")] // 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.918919
84
0.750535
[ "MIT" ]
joselabster/GetAllReadMoreUrls
GetAllReadMoreUrls/GetAllReadMoreUrls/Properties/AssemblyInfo.cs
1,404
C#
using Ed_Fi.Credential.Domain.Enums; using Ed_Fi.Credential.Domain.Model; using System; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ed_Fi.Credential.Business { public interface IVendorSubscriptionBusiness { void Unsubscribe(string wamsId, int edOrgId, int apiClientId); EmailToSend Subscribe(string wamsId, int edOrgId, string vendorName, string claimSetName, int?[] selectedSchoolIds = null); void Modify(string wamsId, int apiClientId, string claimSetName, int?[] selectedSchoolIds = null); } public class VendorSubscriptionBusiness : IVendorSubscriptionBusiness { private readonly IEdFiAdminDbContext _adminDbContext; private readonly IClaimSetBusiness _claimSetBusiness; private readonly IVendorBusiness _vendorBusiness; private readonly IApplicationEducationOrganizationBusiness _applicationEducationOrganizationBusiness; private readonly IAgencyBusiness _agencyBusiness; private readonly IApiClientBusiness _apiClientBusiness; private readonly IUserBusiness _userBusiness; private readonly IApplicationBusiness _applicationBusiness; public VendorSubscriptionBusiness( IEdFiAdminDbContext adminDbContext, IVendorBusiness vendorBusiness, IApplicationEducationOrganizationBusiness applicationLeaBusiness, IApiClientBusiness apiClientBusiness, IUserBusiness userBusiness, IApplicationBusiness applicationBusiness, IAgencyBusiness agencyBusiness, IClaimSetBusiness claimSetBusiness) { _adminDbContext = adminDbContext; _claimSetBusiness = claimSetBusiness; _applicationBusiness = applicationBusiness; _agencyBusiness = agencyBusiness; _vendorBusiness = vendorBusiness; _applicationEducationOrganizationBusiness = applicationLeaBusiness; _apiClientBusiness = apiClientBusiness; _userBusiness = userBusiness; } public void Unsubscribe(string wamsId, int edOrgId, int apiClientId) { var apiClient = _apiClientBusiness.GetApiClient(apiClientId); var vendorId = apiClient?.Application?.VendorVendorId; if (!vendorId.HasValue) return; _adminDbContext.Subscriptions.Add(new Subscription { EducationOrganizationId = edOrgId, SubscriptionActionId = (int)SubscriptionActionEnum.Unsubscribe, VendorId = vendorId.Value, WamsId = wamsId, CreatedDate = DateTime.Now }); _adminDbContext.SaveChanges(wamsId); _apiClientBusiness.TryDestroy(wamsId, apiClientId); } public EmailToSend Subscribe(string wamsId, int edOrgId, string vendorName, string claimSetName, int?[] selectedSchoolIds = null) { var agency = _agencyBusiness.GetCurrentYearImpersonatableAgencyByKey(edOrgId); var vendor = _vendorBusiness.GetVendorByName(vendorName); var users = _userBusiness.GetUsers(vendor.VendorId).Where(u => !string.IsNullOrEmpty(u.Email)).ToList(); int? userId = users.Any() ? users.FirstOrDefault()?.UserId : null; var applications = _applicationBusiness.GetApplicationsByVendor(vendor.VendorId); if (applications.All(a => a.ClaimSetName != claimSetName)) { throw new Exception(string.Format("User can't subscribe to a vendor '{0}' because no application exists for the vendor '{0}' and claim set '{1}'", vendor.VendorName, claimSetName)); } var claimsetDetail = _claimSetBusiness.GetClaimSetDetails(claimSetName); if (claimsetDetail.SchoolLevelClaimset && selectedSchoolIds == null) { throw new Exception("At least one school must be selected."); } Application application = applications.FirstOrDefault(a => a.ClaimSetName == claimSetName); if (application == null) { application = _applicationBusiness.GetOrCreateApplication(wamsId, vendor.VendorId, claimSetName, claimsetDetail.ProfileId.GetValueOrDefault(), $"{vendor.VendorName} {claimSetName}"); } var key = $"{vendor.VendorName} - {agency.EducationOrganizationId} - {agency.Name}"; key = key.Substring(0, Math.Min(key.Length, 50)); var secret = Guid.NewGuid().ToString().Replace("-", ""); if (_apiClientBusiness.DoesKeyExist(0, key)) { key = key.Substring(0, Math.Min(key.Length, 50)- (claimSetName.Length+4)) + " - " +claimSetName + " "; if (_apiClientBusiness.DoesKeyExist(0, key)) { int i = 0; while (_apiClientBusiness.DoesKeyExist(0, key) && i<10) { key = key.Substring(0, Math.Min(key.Length, 47)); key = key + " x" +i.ToString(); i++; } if (i == 10) { throw new Exception("Please contact DPI to subscribe to this vendor again."); } } } var apiClient = new ApiClient { Key = key, Secret = secret, Name = key, IsApproved = true, UseSandbox = false, SandboxType = 1, ApplicationApplicationId = application?.ApplicationId, UserUserId = userId }; if (claimsetDetail.SchoolLevelClaimset && selectedSchoolIds != null && selectedSchoolIds.Length > 0) { var schoolIds = ""; foreach (var schoolId in selectedSchoolIds) { if (!schoolId.HasValue) continue; schoolIds = schoolIds + schoolId.ToString().PadLeft(6, '0') + ","; var schoolApplicationEdOrg = _applicationEducationOrganizationBusiness.GetOrCreateApplicationEducationOrganization(wamsId, schoolId.Value, vendor.VendorId, application?.ApplicationId ?? 0); apiClient.ApplicationEducationOrganizations.Add(schoolApplicationEdOrg); } key = $"{vendor.VendorName} - {schoolIds} {agency.Name}"; key = key.Substring(0, Math.Min(key.Length, 50)); apiClient.Key = key; } else { var applicationEdOrg = _applicationEducationOrganizationBusiness.GetOrCreateApplicationEducationOrganization(wamsId, edOrgId, vendor.VendorId, application?.ApplicationId ?? 0); apiClient.ApplicationEducationOrganizations.Add(applicationEdOrg); } _apiClientBusiness.Create(wamsId, apiClient); _adminDbContext.Subscriptions.Add(new Subscription { EducationOrganizationId = edOrgId, SubscriptionActionId = (int)SubscriptionActionEnum.Subscribe, VendorId = vendor.VendorId, WamsId = wamsId, CreatedDate = DateTime.Now }); _adminDbContext.SaveChanges(wamsId); var edCredUrl = ConfigurationManager.AppSettings["EdCredUrl"]; var bodySb = new StringBuilder(); bodySb.Append("<div>" + agency.Name + " has subscribed to your student information system (SIS). This subscription provides the security credentials needed for WISEdata Ed-Fi integration between their SIS implementation and the Wisconsin DPI Ed-Fi API resources.</div>"); bodySb.Append("<br/>"); bodySb.Append("<div>" + "Login to the <a href='" + edCredUrl + "'>Ed-Fi Credential application</a> to view your credentials. Please <a href='http://dpi.wi.gov/wisedata/vendors/contact-us'>contact us</a> with any issues or questions.</div>"); bodySb.Append("<br/>"); bodySb.Append("<div>Thanks!</div>"); bodySb.Append("<br/>"); bodySb.Append("<div>System Administrator</div>"); bodySb.Append("<div>Division For Libraries and Technology</div>"); bodySb.Append("<div>Wisconsin Department of Public Instruction</div>"); EmailToSend email= new EmailToSend { From = "EdFi.Credential.DoNotReply@dpi.wi.gov", To = users.Select(u => u.Email), Subject = "WISEdata Ed-Fi Integration - Agency Credentials Issued", Body = bodySb.ToString(), ApplicationName = "EdFi.Credential" }; return email; } public void Modify(string wamsId, int apiClientId, string claimSetName, int?[] selectedSchoolIds = null) { var client = _apiClientBusiness.GetApiClient(apiClientId); int applicationId = client.ApplicationApplicationId.GetValueOrDefault(); int vendorId = client.Application.VendorVendorId.GetValueOrDefault(); int profileId = client.Application.Profiles.Select(p => p.ProfileId).FirstOrDefault(); //claimset change will mean choosing/adding new application if (client.Application.ClaimSetName != claimSetName) { Application app = _applicationBusiness.GetOrCreateApplication(wamsId, vendorId, claimSetName, profileId, $"{client.Application.Vendor.VendorName} {claimSetName}"); applicationId = app.ApplicationId; //keep applicationids aligned client.ApplicationApplicationId = applicationId; foreach (var clientApplicationEducationOrganization in client.ApplicationEducationOrganizations.Where(e => e.Application.VendorVendorId == vendorId)) { clientApplicationEducationOrganization.ApplicationApplicationId = applicationId; } _apiClientBusiness.Update(wamsId, client); _apiClientBusiness.SaveChanges(wamsId); } //the only other update would be new or fewer schools if (selectedSchoolIds != null && selectedSchoolIds.Length > 0) { bool changes = false; //schools not in the current list of edorgs foreach (var schoolId in selectedSchoolIds.AsQueryable().Except(client.ApplicationEducationOrganizations.Select(a => (int?)a.EducationOrganizationId))) { if (schoolId > 0) { var schoolApplicationEdOrg = _applicationEducationOrganizationBusiness.GetOrCreateApplicationEducationOrganization(wamsId, schoolId.Value, vendorId, applicationId); client.ApplicationEducationOrganizations.Add(schoolApplicationEdOrg); changes = true; } } //edorgs not in the current list of schools IQueryable<int?> currentOrgs = client.ApplicationEducationOrganizations.Select(a => (int?)a.EducationOrganizationId).ToArray().AsQueryable(); foreach (var schoolId in currentOrgs.Except(selectedSchoolIds)) { var org = client.ApplicationEducationOrganizations.FirstOrDefault(e => e.EducationOrganizationId == schoolId); if (org != null) { client.ApplicationEducationOrganizations.Remove(org); changes = true; } } if (changes) { _apiClientBusiness.Update(wamsId, client); _apiClientBusiness.SaveChanges(wamsId); } } } } }
46.94697
288
0.591012
[ "Apache-2.0" ]
Ed-Fi-Exchange-OSS/Credential-Manager
Ed-Fi.Credential.Business/VendorSubscriptionBusiness.cs
12,396
C#
using System; using System.Collections.Generic; namespace FastState.Test { internal class TestClass { public TestClass(string v) { Value = v; } public string Value { get; } public override bool Equals(object? obj) { return obj is TestClass @class && Value == @class.Value; } public override int GetHashCode() { return HashCode.Combine(Value); } public static bool operator ==(TestClass? left, TestClass? right) { return EqualityComparer<TestClass>.Default.Equals(left, right); } public static bool operator !=(TestClass? left, TestClass? right) { return !(left == right); } } }
22.305556
75
0.534247
[ "MIT" ]
snargledorf/FastState
FastState.Test/TestClass.cs
805
C#
// <copyright file="ReverseLatLonHiCoordinateInterpretationStrategy.cs" company="Eötvös Loránd University (ELTE)"> // Copyright 2016-2019 Roberto Giachetta. Licensed under the // Educational Community 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://opensource.org/licenses/ECL-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 AEGIS.Reference.Strategies { using System; using AEGIS.Reference; /// <summary> /// Represents a reverse coordinate interpretation for (latitude, longitude, height) representation. /// </summary> public class ReverseLatLonHiCoordinateInterpretationStrategy : ReverseLatLonCoordinateInterpretationStrategy { /// <summary> /// The unit of measurement of the height. This field is read-only. /// </summary> private readonly UnitOfMeasurement heightUnit; /// <summary> /// Initializes a new instance of the <see cref="ReverseLatLonHiCoordinateInterpretationStrategy" /> class. /// </summary> /// <param name="referenceSystem">The reference system.</param> /// <exception cref="System.ArgumentNullException">The reference system is null.</exception> /// <exception cref="System.ArgumentException">The dimension of the coordinate system is less than expected.</exception> public ReverseLatLonHiCoordinateInterpretationStrategy(CoordinateReferenceSystem referenceSystem) : base(referenceSystem) { this.heightUnit = this.referenceSystem.CoordinateSystem.GetAxis(2).Unit; } /// <summary> /// Applies the strategy on the specified coordinate. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <returns>The transformed coordinate.</returns> public override GeoCoordinate Apply(Coordinate coordinate) { return new GeoCoordinate(new Angle(coordinate.X, this.latitudeUnit), new Angle(coordinate.Y, this.longitudeUnit), new Length(coordinate.Z, this.heightUnit)); } } }
47.169811
169
0.6928
[ "ECL-2.0" ]
AegisSpatial/aegis
src/Core.Reference/Strategies/ReverseLatLonHiCoordinateInterpretationStrategy.cs
2,505
C#
using MinerPlugin; using NHM.Common; using NHMCore.Configs; using NHMCore.Configs.Data; using NHMCore.Mining.Plugins; using NHMCore.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NHMCore.Mining { public class Miner { public static Miner CreateMinerForMining(List<MiningPair> miningPairs, string groupKey) { var pair = miningPairs.FirstOrDefault(); if (pair == null || pair.Algorithm == null) return null; var algorithm = pair.Algorithm; var plugin = MinerPluginsManager.GetPluginWithUuid(algorithm.MinerID); if (plugin != null) { return new Miner(plugin, miningPairs, groupKey); } return null; } // used to identify miner instance protected readonly long MinerID; private string _minerTag; private string MinerDeviceName { get; set; } // mining algorithm stuff protected bool IsInit { get; private set; } public List<MiningPair> MiningPairs { get; private set; } public string GroupKey { get; protected set; } = ""; CancellationTokenSource _endMiner; private bool IsUpdatingApi { get; set; } = false; private object _lock = new object(); private Task _minerWatchdogTask; public Task MinerWatchdogTask { get { lock (_lock) { return _minerWatchdogTask; } } set { lock (_lock) { _minerWatchdogTask = value; } } } // Now every single miner is based from the Plugins private readonly PluginContainer _plugin; private readonly List<AlgorithmContainer> _algos; private readonly IMinerAsyncExtensions _miner; private readonly SemaphoreSlim _apiSemaphore = new SemaphoreSlim(1, 1); // you must use protected Miner(PluginContainer plugin, List<MiningPair> miningPairs, string groupKey) { _plugin = plugin; // TODO this is now a must be of type IMinerAsyncExtensions _miner = _plugin.CreateMiner() as IMinerAsyncExtensions; // just so we can set algorithms states _algos = new List<AlgorithmContainer>(); foreach (var pair in miningPairs) { var cDev = AvailableDevices.GetDeviceWithUuid(pair.Device.UUID); if (cDev == null) continue; var algoContainer = cDev.AlgorithmSettings.FirstOrDefault(a => a.Algorithm == pair.Algorithm); if (algoContainer == null) continue; _algos.Add(algoContainer); } MiningPairs = miningPairs; IsInit = MiningPairs != null && MiningPairs.Count > 0; GroupKey = groupKey; MinerDeviceName = plugin.PluginUUID; Logger.Info(MinerTag(), "NEW MINER CREATED"); } // TAG for identifying miner private string MinerTag() { if (_minerTag == null) { const string mask = "{0}-MINER_ID({1})-DEVICE_IDs({2})"; // no devices set if (!IsInit) { return string.Format(mask, MinerDeviceName, MinerID, "NOT_SET"); } // contains ids var ids = MiningPairs.Select(cdevs => cdevs.Device.ID.ToString()).ToList(); _minerTag = string.Format(mask, MinerDeviceName, MinerID, string.Join(",", ids)); } return _minerTag; } private async Task<ApiData> GetSummaryAsync() { var apiData = new ApiData(); if (!IsUpdatingApi) { IsUpdatingApi = true; await _apiSemaphore.WaitAsync(); try { apiData = await _miner.GetMinerStatsDataAsync(); } catch (Exception e) { Logger.Error(MinerTag(), $"GetSummaryAsync error: {e.Message}"); } finally { IsUpdatingApi = false; _apiSemaphore.Release(); foreach (var apiDev in apiData.AlgorithmSpeedsPerDevice) { foreach (var kvp in apiDev.Value) { if (kvp.Speed < 0) { await StopTask(); await StartMinerTask(new CancellationToken(), StratumService.Instance.SelectedServiceLocation, CredentialsSettings.Instance.BitcoinAddress); } } } } } UpdateApiTimestamp(apiData); // TODO workaround plugins should return this info // create empty stub if it is null if (apiData == null) { Logger.Debug(MinerTag(), "GetSummary returned null... Will create ZERO fallback"); apiData = new ApiData(); } if (apiData.AlgorithmSpeedsPerDevice == null) { apiData = new ApiData(); var perDevicePowerDict = new Dictionary<string, int>(); var perDeviceSpeedsDict = new Dictionary<string, IReadOnlyList<AlgorithmTypeSpeedPair>>(); var perDeviceSpeeds = MiningPairs.Select(pair => (pair.Device.UUID, pair.Algorithm.IDs.Select(type => new AlgorithmTypeSpeedPair(type, 0d)))); foreach (var kvp in perDeviceSpeeds) { var uuid = kvp.Item1; // kvp.UUID compiler doesn't recognize ValueTypes lib??? perDeviceSpeedsDict[uuid] = kvp.Item2.ToList(); perDevicePowerDict[uuid] = 0; } apiData.AlgorithmSpeedsPerDevice = perDeviceSpeedsDict; apiData.PowerUsagePerDevice = perDevicePowerDict; apiData.PowerUsageTotal = 0; apiData.AlgorithmSpeedsTotal = perDeviceSpeedsDict.First().Value; } else if (apiData.AlgorithmSpeedsPerDevice != null && apiData.PowerUsagePerDevice.Count == 0) { var perDevicePowerDict = new Dictionary<string, int>(); foreach (var kvp in MiningPairs) { var uuid = kvp.Device.UUID; perDevicePowerDict[uuid] = 0; } apiData.PowerUsagePerDevice = perDevicePowerDict; apiData.PowerUsageTotal = 0; } // TODO temporary here move it outside later MiningDataStats.UpdateGroup(apiData, _plugin.PluginUUID, _plugin.Name); return apiData; } private async Task<object> StartAsync(CancellationToken stop, string miningLocation, string username) { _miner.InitMiningLocationAndUsername(miningLocation, username); _miner.InitMiningPairs(MiningPairs); EthlargementIntegratedPlugin.Instance.Start(MiningPairs); var ret = await _miner.StartMiningTask(stop); var maxTimeout = _plugin.GetApiMaxTimeout(MiningPairs); MinerApiWatchdog.AddGroup(GroupKey, maxTimeout, DateTime.UtcNow); _algos.ForEach(a => a.IsCurrentlyMining = true); return ret; } private async Task StopAsync() { // TODO thing about this case, closing opening on switching EthlargementIntegratedPlugin.Instance.Stop(MiningPairs); MinerApiWatchdog.RemoveGroup(GroupKey); MiningDataStats.RemoveGroup(MiningPairs.Select(pair => pair.Device.UUID), _plugin.PluginUUID); await _miner.StopMiningTask(); _algos.ForEach(a => a.IsCurrentlyMining = false); //if (_miner is IDisposable disposableMiner) //{ // disposableMiner.Dispose(); //} } public Task StartMinerTask(CancellationToken stop, string miningLocation, string username) { var tsc = new TaskCompletionSource<object>(); var wdTask = MinerWatchdogTask; if (wdTask == null || wdTask.IsCompleted) { MinerWatchdogTask = Task.Run(() => RunMinerWatchDogLoop(tsc, stop, miningLocation, username)); } else { Logger.Error(MinerTag(), $"Trying to start an already started miner"); tsc.SetResult("TODO error trying to start already started miner"); } return tsc.Task; } private async Task RunMinerWatchDogLoop(TaskCompletionSource<object> tsc, CancellationToken stop, string miningLocation, string username) { // if we fail 3 times in a row under certain conditions mark on of them const int maxRestartCount = 3; int restartCount = 0; const int minRestartTimeInSeconds = 15; try { var firstStart = true; using (_endMiner = new CancellationTokenSource()) using (var linkedEndMiner = CancellationTokenSource.CreateLinkedTokenSource(stop, _endMiner.Token)) { Logger.Info(MinerTag(), $"Starting miner watchdog task"); while (!linkedEndMiner.IsCancellationRequested && (restartCount < maxRestartCount)) { var startTime = DateTime.UtcNow; try { if (!firstStart) { Logger.Info(MinerTag(), $"Restart Mining in {MiningSettings.Instance.MinerRestartDelayMS}ms"); } await TaskHelpers.TryDelay(MiningSettings.Instance.MinerRestartDelayMS, linkedEndMiner.Token); var result = await StartAsync(linkedEndMiner.Token, miningLocation, username); if (firstStart) { firstStart = false; tsc.SetResult(result); } if (result is bool ok && ok) { var runningMinerTask = _miner.MinerProcessTask; _ = MinerStatsLoop(runningMinerTask, linkedEndMiner.Token); await runningMinerTask; // TODO log something here Logger.Info(MinerTag(), $"Running Miner Task Completed"); } else { // TODO check if the miner file is missing or locked and blacklist the algorithm for a certain period of time Logger.Error(MinerTag(), $"StartAsync result: {result}"); } } catch (TaskCanceledException e) { Logger.Debug(MinerTag(), $"RunMinerWatchDogLoop TaskCanceledException: {e.Message}"); return; } catch (Exception e) { Logger.Error(MinerTag(), $"RunMinerWatchDogLoop Exception: {e.Message}"); } finally { var endTime = DateTime.UtcNow; var elapsedSeconds = (endTime - startTime).TotalSeconds - (MiningSettings.Instance.MinerRestartDelayMS); if (elapsedSeconds < minRestartTimeInSeconds) { restartCount++; } else { restartCount = 0; } if(restartCount >= maxRestartCount) { var firstAlgo = _algos.FirstOrDefault(); Random randWait = new Random(); firstAlgo.IgnoreUntil = DateTime.UtcNow.AddMinutes(randWait.Next(20, 30)); await MiningManager.MinerRestartLoopNotify(); } } } } } finally { Logger.Info(MinerTag(), $"Exited miner watchdog"); } } private async Task MinerStatsLoop(Task runningTask, CancellationToken stop) { try { // TODO make sure this interval is per miner plugin instead of a global one var minerStatusElapsedTimeChecker = new ElapsedTimeChecker( () => TimeSpan.FromSeconds(MiningSettings.Instance.MinerAPIQueryInterval), true); var checkWaitTime = TimeSpan.FromMilliseconds(50); Func<bool> isOk = () => !runningTask.IsCompleted && !stop.IsCancellationRequested; Logger.Info(MinerTag(), $"MinerStatsLoop START"); while (isOk()) { try { if (isOk()) await TaskHelpers.TryDelay(checkWaitTime, stop); if (isOk() && minerStatusElapsedTimeChecker.CheckAndMarkElapsedTime()) await GetSummaryAsync(); // check if stagnated and restart var restartGroups = MinerApiWatchdog.GetTimedoutGroups(DateTime.UtcNow); if (isOk() && (restartGroups?.Contains(GroupKey) ?? false)) { Logger.Info(MinerTag(), $"Restarting miner group='{GroupKey}' API timestamp exceeded"); await StopAsync(); return; } } catch (TaskCanceledException e) { Logger.Debug(MinerTag(), $"MinerStatsLoop TaskCanceledException: {e.Message}"); return; } catch (Exception e) { Logger.Error(MinerTag(), $"Exception {e.Message}"); } } } finally { Logger.Info(MinerTag(), $"MinerStatsLoop END"); } } public async Task StopTask() { try { _endMiner?.Cancel(); await StopAsync(); } catch (Exception e) { Logger.Info(MinerTag(), $"Stop: {e.Message}"); } } #region MinerApiWatchdog private double _lastSpeedsTotalSum = 0d; private double _lastPerDevSpeedsTotalSum = 0d; // TODO this can be moved in MinerApiWatchdog private void UpdateApiTimestamp(ApiData apiData) { // we will not update api timestamps if we have no data or speeds are zero if (apiData == null) { // TODO debug log no api data return; } if (apiData.AlgorithmSpeedsTotal == null && apiData.AlgorithmSpeedsPerDevice == null) { // TODO debug log cannot get speeds return; } var speedsTotalSum = apiData.AlgorithmSpeedsTotal?.Select(p => p.Speed).Sum() ?? 0d; var perDevSpeedsTotalSum = apiData.AlgorithmSpeedsPerDevice?.Values.SelectMany(pl => pl).Select(p => p.Speed).Sum() ?? 0d; if (speedsTotalSum == 0d && perDevSpeedsTotalSum == 0d) { // TODO debug log speeds are zero return; } if (speedsTotalSum == _lastSpeedsTotalSum && perDevSpeedsTotalSum == _lastPerDevSpeedsTotalSum) { // TODO debug log speeds seem to be stuck return; } // update _lastSpeedsTotalSum = speedsTotalSum; _lastPerDevSpeedsTotalSum = perDevSpeedsTotalSum; MinerApiWatchdog.UpdateApiTimestamp(GroupKey, DateTime.UtcNow); } #endregion MinerApiWatchdog } }
40.725537
172
0.501348
[ "MIT" ]
6paklata/NiceHashMiner
src/NHMCore/Mining/Miner.cs
17,066
C#
using Autodesk.Revit.DB; namespace RevitSetLevelSection.Models.LevelDefinitions { internal class BBPositionTop : IBBPosition { public double GetPosition(Outline outline) { return outline.MaximumPoint.Z; } } }
27.333333
56
0.695122
[ "MIT" ]
dosymep/RevitPlugins
RevitSetLevelSection/Models/LevelDefinitions/BBPositionTop.cs
248
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace DP4_FacadePattern { class Television { private readonly String description; public Television(String description) { this.description = description; } public void On() { Console.WriteLine(description + " on"); } public void Off() { Console.WriteLine(description + " off"); } public void WideScreenMode() { Console.WriteLine(description + " in widescreen mode (16x9 aspect ratio)"); } public void TvMode() { Console.WriteLine(description + " in tv mode (4x3 aspect ratio)"); } public override string ToString() { return description; } } }
21.022222
87
0.567653
[ "Unlicense" ]
avandam/TrainingVietnam
SOLID/DP4_FacadePattern/Television.cs
948
C#
using apophis.Lexer.Tokens; namespace Messerli.VsSolution.Token { internal class NewLineToken : IToken, ILineBreakToken { public override string ToString() { return "\r\n"; } } }
17.538462
57
0.600877
[ "MIT" ]
messerli-informatik-ag/MetaGenerator
VsSolution/Token/NewLineToken.cs
228
C#
using Dapper; using EdaSample.Common.Events; using EdaSample.Services.Common.Events; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Threading.Tasks; namespace EdaSample.Services.Customer.Controllers { [Route("api/[controller]")] public class CustomersController : Controller { private readonly IConfiguration configuration; private readonly string connectionString; private readonly IEventBus eventBus; private readonly ILogger logger; public CustomersController(IConfiguration configuration, IEventBus eventBus, ILogger<CustomersController> logger) { this.configuration = configuration; this.connectionString = configuration["mssql:connectionString"]; this.eventBus = eventBus; this.logger = logger; } // 获取指定ID的客户信息 [HttpGet("{id}")] public async Task<IActionResult> Get(Guid id) { const string sql = "SELECT [CustomerId] AS Id, [CustomerName] AS Name FROM [dbo].[Customers] WHERE [CustomerId]=@id"; using (var connection = new SqlConnection(connectionString)) { var customer = await connection.QueryFirstOrDefaultAsync<Model.Customer>(sql, new { id }); if (customer == null) { return NotFound(); } return Ok(customer); } } // 创建新的客户信息 [HttpPost] public async Task<IActionResult> Create([FromBody] dynamic model) { this.logger.LogInformation($"开始创建客户信息。"); var name = (string)model.Name; if (string.IsNullOrEmpty(name)) { return BadRequest("请指定客户名称。"); } var email = (string)model.Email; if (string.IsNullOrEmpty(email)) { return BadRequest("电子邮件地址不能为空。"); } // 由于数据库更新需要通过事件处理器进行异步更新,因此无法在Controller中得到 // 数据库更新后的Customer ID。此处通过Guid.NewGuid获得,实际中可以使用独立 // 的Identity Service产生。 var customerId = Guid.NewGuid(); await this.eventBus.PublishAsync(new CustomerCreatedEvent(customerId, name, email)); return Created(Url.Action("Get", new { id = customerId }), customerId); } } }
32.175
129
0.601399
[ "MIT" ]
dk20170906/EventDriverStudy
src/services/EdaSample.Services.Customer/Controllers/CustomersController.cs
2,784
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.InvalidAssemblyName); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
40.468254
213
0.619533
[ "Apache-2.0" ]
HaloFour/roslyn
src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs
10,200
C#
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Configuration; using MovescountBackup.Lib.Dto; using MovescountBackup.Lib.Services; using Strava.Upload; using StravaUpload.Lib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace StravaUpload.StravaUploadFunction { // ReSharper disable once UnusedMember.Global public static class Function { [FunctionName("StravaUploadFunction")] // ReSharper disable once UnusedParameter.Global // ReSharper disable once UnusedMember.Global public static async Task Run([TimerTrigger("0 0 3 * * *", RunOnStartup = true, UseMonitor = true)] TimerInfo myTimer, TraceWriter log, ExecutionContext context) { log.Info($"C# Timer trigger MovescountBackup function executed at: {DateTime.UtcNow.ToIsoString()}."); await Execute(log, context); log.Info($"Done at: {DateTime.UtcNow.ToIsoString()}."); } private static async Task Execute(TraceWriter log, ExecutionContext context) { log.Info("Running."); var configuration = SetupConfiguration(context); var backupFullPath = Path.Combine(context.FunctionAppDirectory, configuration.BackupDir); if (!Directory.Exists(backupFullPath)) { Directory.CreateDirectory(backupFullPath); } var mailService = new MailService(configuration); var client = new Client(configuration, new TraceWriterLogger<Client>(log)); var storage = new CloudStorage(configuration.StorageConnectionString, configuration.ContainerName); var downloader = new Downloader(configuration, client, storage, new TraceWriterLogger<Downloader>(log)); IList<(Move move, string filePath, DataFormat fileFormat)> movesData = null; try { log.Info("Trying to backup new Movescount moves and upload them to Strava."); var moves = await downloader.DownloadLastUserMoves(configuration.MovescountMemberName); var uploader = new MovescountUploader(configuration.StravaAccessToken, new TraceWriterLogger<MovescountUploader>(log)); const DataFormat fileFormat = DataFormat.Tcx; movesData = moves.Select(move => (move, filePath: Path.Combine(backupFullPath, move.MoveId.ToString(), MovescountUploader.CreateGpsFileMapName(fileFormat)), fileFormat)) .ToList(); // Load data from Cloud storage and store them locally foreach (var moveItem in movesData) { Directory.CreateDirectory(Path.Combine(backupFullPath, moveItem.move.MoveId.ToString())); var blobStorageFilePath = Path.Combine(configuration.BackupDir, moveItem.move.MoveId.ToString(), MovescountUploader.CreateGpsFileMapName(fileFormat)); if (!File.Exists(moveItem.filePath)) { log.Info($"Storing gps data file in {moveItem.filePath}."); File.WriteAllText(moveItem.filePath, await storage.LoadData(blobStorageFilePath)); } } await uploader.AddOrUpdateMovescountMovesToStravaActivities(movesData); var processedMoves = moves.Any() ? string.Join("<br />", moves.Select(move => { var link = $"http://www.movescount.com/moves/move{move.MoveId}"; return $"<p><a href=\"{link}\" target=\"_blank\">{link}</a></p>"; })) : "No moves"; await mailService.SendEmail( configuration.EmailFrom, configuration.EmailTo, $"<div><div><strong>Following moves were uploaded or updated: </strong></div>{processedMoves}</div>" ); } catch (Exception ex) { log.Error("Error while downloading Movescount data and uploading them to Strava."); log.Error(ex.Message); log.Error(ex.StackTrace); await mailService.SendEmail( configuration.EmailFrom, configuration.EmailTo, $"<div><div><strong>Error while downloading Movescount data and uploading them to Strava:</strong></div><p>{ex.StackTrace}</p></div>" ); } finally { // Clean backup directory Directory.Delete(backupFullPath, true); } } private static IConfiguration SetupConfiguration(ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); return new Configuration { MovescountAppKey = config["MovescountAppKey"], MovescountUserEmail = config["MovescountUserEmail"], MovescountUserKey = config["MovescountUserKey"], BackupDir = config["BackupDir"], CookieValue = config["CookieValue"], StorageConnectionString = config["StorageConnectionString"], ContainerName = config["ContainerName"], MovescountMemberName = config["MovescountMemberName"], SendGridApiKey = config["SendGridApiKey"], EmailFrom = config["EmailFrom"], EmailTo = config["EmailTo"], StravaAccessToken = config["StravaAccessToken"], }; } } }
45.37594
170
0.589395
[ "MIT" ]
marazt/strava-upload
StravaUpload.StravaUploadFunction/Function.cs
6,035
C#
namespace AggregateConsistency.Infrastructure { public class Snapshot { public Snapshot(long streamRevision, long snapshotRevision, object value) { StreamRevision = streamRevision; SnapshotRevision = snapshotRevision; Value = value; } public object Value { get; } public long StreamRevision { get; } public long SnapshotRevision { get; } } }
24.333333
77
0.742466
[ "MIT" ]
jageall/BuildStuff2018
AggregateConsistency/Infrastructure/Snapshot.cs
367
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("ReactorUI.WinForms.DemoApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReactorUI.WinForms.DemoApp")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("d1340d73-01c9-43fc-a07c-7d24a832510d")] // 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.378378
84
0.75
[ "MIT" ]
adospace/experimental-reactorui
src/ReactorUI.WinForms.DemoApp/Properties/AssemblyInfo.cs
1,423
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml; using JetBrains.Annotations; using JetBrains.Diagnostics; using JetBrains.Metadata.Reader.API; using JetBrains.Metadata.Reader.Impl; using JetBrains.ReSharper.Psi; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity { public class ApiXml { private readonly IDictionary<string, IClrTypeName> myTypeNames = new Dictionary<string, IClrTypeName>(); private readonly IDictionary<string, Version> myVersions = new Dictionary<string, Version>(); private readonly JetHashSet<string> myIdentifiers = new JetHashSet<string>(); public UnityTypes LoadTypes() { var types = new List<UnityType>(); var ns = GetType().Namespace; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ns + @".api.xml")) { Assertion.AssertNotNull(stream, "stream != null"); var document = new XmlDocument(); document.Load(stream); var apiNode = document.DocumentElement?.SelectSingleNode("/api"); Assertion.AssertNotNull(apiNode, "apiNode != null"); var minimumVersion = apiNode.Attributes?["minimumVersion"]?.Value; var maximumVersion = apiNode.Attributes?["maximumVersion"]?.Value; Assertion.Assert(minimumVersion != null && maximumVersion != null, "minimumVersion != null && maximumVersion != null"); var nodes = document.DocumentElement?.SelectNodes(@"/api/type"); Assertion.AssertNotNull(nodes, "nodes != null"); foreach (XmlNode type in nodes) types.Add(CreateUnityType(type, minimumVersion, maximumVersion)); return new UnityTypes(types, GetInternedVersion(minimumVersion), GetInternedVersion(maximumVersion)); } } private IClrTypeName GetInternedClrTypeName(string typeName) { if (!myTypeNames.TryGetValue(typeName, out var clrTypeName)) { clrTypeName = new ClrTypeName(typeName); myTypeNames.Add(typeName, clrTypeName); } return clrTypeName; } private UnityType CreateUnityType(XmlNode type, string defaultMinimumVersion, string defaultMaximumVersion) { var name = type.Attributes?["name"].Value; var ns = type.Attributes?["ns"].Value; var minimumVersion = ParseVersionAttribute(type, "minimumVersion", defaultMinimumVersion); var maximumVersion = ParseVersionAttribute(type, "maximumVersion", defaultMaximumVersion); var typeName = GetInternedClrTypeName($"{ns}.{name}"); var messageNodes = type.SelectNodes("message"); var messages = EmptyArray<UnityEventFunction>.Instance; if (messageNodes != null) { messages = messageNodes.OfType<XmlNode>() .Select(node => CreateUnityMessage(node, typeName, defaultMinimumVersion, defaultMaximumVersion)) .OrderBy(m => m.Name).ToArray(); } return new UnityType(typeName, messages, minimumVersion, maximumVersion); } private Version ParseVersionAttribute(XmlNode node, string attributeName, string defaultValue) { var attributeValue = node.Attributes?[attributeName]?.Value ?? defaultValue; return GetInternedVersion(attributeValue); } private Version GetInternedVersion(string versionString) { if (!myVersions.TryGetValue(versionString, out var version)) { version = Version.Parse(versionString); myVersions.Add(versionString, version); } return version; } private string GetInternedIdentifier(string identifier) { return myIdentifiers.Intern(identifier); } private UnityEventFunction CreateUnityMessage(XmlNode node, IClrTypeName typeName, string defaultMinimumVersion, string defaultMaximumVersion) { var name = node.Attributes?["name"].Value; Assertion.AssertNotNull(name, "name != null"); var description = node.Attributes?["description"]?.Value; var isStatic = bool.Parse(node.Attributes?["static"]?.Value ?? "false"); var canBeCoroutine = bool.Parse(node.Attributes?["coroutine"]?.Value ?? "false"); var isUndocumented = bool.Parse(node.Attributes?["undocumented"]?.Value ?? "false"); var minimumVersion = ParseVersionAttribute(node, "minimumVersion", defaultMinimumVersion); var maximumVersion = ParseVersionAttribute(node, "maximumVersion", defaultMaximumVersion); var parameters = EmptyArray<UnityEventFunctionParameter>.Instance; var parameterNodes = node.SelectNodes("parameters/parameter"); if (parameterNodes != null) { parameters = parameterNodes.OfType<XmlNode>().Select(LoadParameter).ToArray(); } var returnsArray = false; var returnType = PredefinedType.VOID_FQN; var returns = node.SelectSingleNode("returns"); if (returns != null) { returnsArray = bool.Parse(returns.Attributes?["array"].Value ?? "false"); var type = returns.Attributes?["type"]?.Value ?? "System.Void"; returnType = GetInternedClrTypeName(type); } return new UnityEventFunction(GetInternedIdentifier(name), typeName, returnType, returnsArray, isStatic, canBeCoroutine, description, isUndocumented, minimumVersion, maximumVersion, parameters); } private UnityEventFunctionParameter LoadParameter([NotNull] XmlNode node, int i) { var type = node.Attributes?["type"]?.Value; var name = node.Attributes?["name"].Value; var description = node.Attributes?["description"]?.Value; var isArray = bool.Parse(node.Attributes?["array"]?.Value ?? "false"); var isByRef = bool.Parse(node.Attributes?["byRef"]?.Value ?? "false"); var isOptional = bool.Parse(node.Attributes?["optional"]?.Value ?? "false"); var justification = node.Attributes?["justification"]?.Value; var parameterType = type != null ? GetInternedClrTypeName(type) : PredefinedType.INT_FQN; var parameterName = GetInternedIdentifier(name ?? $"arg{i + 1}"); return new UnityEventFunctionParameter(parameterName, parameterType, description, isArray, isByRef, isOptional, justification); } } public class UnityTypes { private readonly Version myMinimumVersion; private readonly Version myMaximumVersion; public UnityTypes(IList<UnityType> types, Version minimumVersion, Version maximumVersion) { Types = types; myMinimumVersion = minimumVersion; myMaximumVersion = maximumVersion; } public Version NormaliseSupportedVersion(Version actualVersion) { if (actualVersion < myMinimumVersion) return myMinimumVersion; if (actualVersion > myMaximumVersion) return myMaximumVersion; return actualVersion; } public IList<UnityType> Types { get; } } }
41.961749
120
0.622086
[ "Apache-2.0" ]
20chan/resharper-unity
resharper/resharper-unity/src/ApiXml.cs
7,681
C#
// OData .NET Libraries ver. 5.6.3 // 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. namespace Microsoft.Data.OData.Query.SyntacticAst { #region Namespaces using System; using System.Collections.Generic; using Microsoft.Data.OData.Query.SemanticAst; #endregion Namespaces /// <summary> /// Lexical token representing a segment in a path. /// </summary> /// internal sealed class NonSystemToken : PathSegmentToken { /// <summary> /// Any named values for this NonSystemToken /// </summary> private readonly IEnumerable<NamedValue> namedValues; /// <summary> /// The identifier for this token. /// </summary> private readonly string identifier; /// <summary> /// Build a NonSystemToken /// </summary> /// <param name="identifier">the identifier of this token</param> /// <param name="namedValues">a list of named values for this token</param> /// <param name="nextToken">the next token in the path</param> public NonSystemToken(string identifier, IEnumerable<NamedValue> namedValues, PathSegmentToken nextToken) : base(nextToken) { ExceptionUtils.CheckArgumentNotNull(identifier, "identifier"); this.identifier = identifier; this.namedValues = namedValues; } /// <summary> /// Get the list of named values for this token. /// </summary> public IEnumerable<NamedValue> NamedValues { get { return this.namedValues; } } /// <summary> /// Get the identifier for this token. /// </summary> public override string Identifier { get { return this.identifier; } } /// <summary> /// Is this token namespace or container qualified. /// </summary> /// <returns>true if this token is namespace or container qualified.</returns> public override bool IsNamespaceOrContainerQualified() { return this.identifier.Contains("."); } /// <summary> /// Accept a <see cref="IPathSegmentTokenVisitor{T}"/> to walk a tree of <see cref="PathSegmentToken"/>s. /// </summary> /// <typeparam name="T">Type that the visitor will return after visiting this token.</typeparam> /// <param name="visitor">An implementation of the visitor interface.</param> /// <returns>An object whose type is determined by the type parameter of the visitor.</returns> public override T Accept<T>(IPathSegmentTokenVisitor<T> visitor) { ExceptionUtils.CheckArgumentNotNull(visitor, "visitor"); return visitor.Visit(this); } /// <summary> /// Accept a <see cref="IPathSegmentTokenVisitor"/> to walk a tree of <see cref="PathSegmentToken"/>s. /// </summary> /// <param name="visitor">An implementation of the visitor interface.</param> public override void Accept(IPathSegmentTokenVisitor visitor) { ExceptionUtils.CheckArgumentNotNull(visitor, "visitor"); visitor.Visit(this); } } }
41.036697
114
0.626872
[ "Apache-2.0" ]
tapika/choco
lib/Microsoft.Data.Services.Client/ODataLib/OData/Desktop/.Net4.0/Data/OData/Query/SyntacticAst/NonSystemToken.cs
4,473
C#
using System; using System.Linq; using ZzukBot.Game.Statics; namespace ZzukBot.Mem { /// <summary> /// Class for a simple hack (read: changing bytes in memory) /// </summary> internal class Hack { // address where the bytes will be changed private IntPtr _address = IntPtr.Zero; // old bytes private byte[] _originalBytes; /// <summary> /// Constructor: addr and the new bytes /// </summary> internal Hack(IntPtr parAddress, byte[] parCustomBytes, string parName) { Address = parAddress; _customBytes = parCustomBytes; _originalBytes = Memory.Reader.ReadBytes(Address, _customBytes.Length); Name = parName; } /// <summary> /// Constructor: addr, new bytes aswell old bytes /// </summary> internal Hack(IntPtr parAddress, byte[] parCustomBytes, byte[] parOriginalBytes, string parName) { Address = parAddress; _customBytes = parCustomBytes; _originalBytes = parOriginalBytes; Name = parName; } internal Hack(uint offset, byte[] parCustomBytes, string parName) { _address = (IntPtr) offset; _customBytes = parCustomBytes; Name = parName; } internal bool DynamicHide { get; set; } = false; // is the hack applied //internal bool IsApplied { get; private set; } internal bool RelativeToPlayerBase { get; set; } = false; internal IntPtr Address { get { return !RelativeToPlayerBase ? _address : IntPtr.Add(ObjectManager.Instance.Player.Pointer, (int) _address); } private set { _address = value; } } // new bytes private byte[] _customBytes { get; set; } // name of hack internal string Name { get; private set; } internal bool IsActivated { get { if (RelativeToPlayerBase) { if (!ObjectManager.Instance.IsIngame) return false; if (ObjectManager.Instance.Player == null) return false; } var curBytes = Memory.Reader.ReadBytes(Address, _originalBytes.Length); return !curBytes.SequenceEqual(_originalBytes); } } internal bool IsWithinScan(IntPtr scanStartAddress, int size) { var scanStart = (int) scanStartAddress; var scanEnd = (int) IntPtr.Add(scanStartAddress, size); var hackStart = (int) Address; var hackEnd = (int) Address + _customBytes.Length; if (hackStart >= scanStart && hackStart < scanEnd) return true; if (hackEnd > scanStart && hackEnd <= scanEnd) return true; return false; } /// <summary> /// Apply the new bytes to address /// </summary> internal void Apply() { if (RelativeToPlayerBase) { if (!ObjectManager.Instance.IsIngame) return; if (ObjectManager.Instance.Player == null) return; if (_originalBytes == null) _originalBytes = Memory.Reader.ReadBytes(Address, _customBytes.Length); } Memory.Reader.WriteBytes(Address, _customBytes); } /// <summary> /// Restore the old bytes to the address /// </summary> internal void Remove() { if (RelativeToPlayerBase) { if (!ObjectManager.Instance.IsIngame) return; if (ObjectManager.Instance.Player == null) return; } if (DynamicHide && IsActivated) _customBytes = Memory.Reader.ReadBytes(Address, _originalBytes.Length); Memory.Reader.WriteBytes(Address, _originalBytes); } } }
31.646154
104
0.535002
[ "Unlicense" ]
Bia10/ZzukBot_V3
ZzukBot_WPF/Mem/Hacks.cs
4,116
C#
using System.Threading.Tasks; using Tweetinvi.Iterators; using Tweetinvi.Models.V2; using Tweetinvi.Parameters.V2; namespace Tweetinvi.Client.V2 { public interface ISearchV2Client { /// <inheritdoc cref="GetSearchTweetsV2Iterator(ISearchTweetsV2Parameters)"/> Task<SearchTweetsV2Response> SearchTweetsAsync(string query); /// <summary> /// Search for tweets /// </summary> /// <para> Read more : https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent </para> /// <returns>First page of search results</returns> Task<SearchTweetsV2Response> SearchTweetsAsync(ISearchTweetsV2Parameters parameters); /// <inheritdoc cref="GetSearchTweetsV2Iterator(ISearchTweetsV2Parameters)"/> ITwitterRequestIterator<SearchTweetsV2Response, string> GetSearchTweetsV2Iterator(string query); /// <summary> /// Search for tweets /// </summary> /// <para> Read more : https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent </para> /// <returns>Iterator over the search results</returns> ITwitterRequestIterator<SearchTweetsV2Response, string> GetSearchTweetsV2Iterator(ISearchTweetsV2Parameters parameters); } }
44.3
141
0.714823
[ "MIT" ]
IEvangelist/tweetinvi
src/Tweetinvi.Core/Public/Client/Clients/V2/ISearchV2Client.cs
1,329
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ical.Net; using Ical.Net.DataTypes; using Ical.Net.Interfaces.DataTypes; using Ical.Net.Serialization; using Ical.Net.Serialization.iCalendar.Serializers; using CalendarDll.Data; using Ical.Net.Interfaces.Components; using Ical.Net.Interfaces.Serialization; using Ical.Net.Interfaces; namespace CalendarDll { /// <summary> /// Calendar Utils /// </summary> /// <remarks>2012/12/11 by CA2S (Static version), 2012/12/21 by RM (Dynamic version)</remarks> public class CalendarUtils { #region Calendar - Get an Instance /// <summary> /// Gets an Instance of the Calendar Library /// </summary> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public Calendar GetCalendarLibraryInstance() { const string Calendar_VERSION = "2.0"; Calendar newCalendar = new Calendar() { Version = Calendar_VERSION }; return newCalendar; } #endregion #region Get Free Events /// <summary> /// Get Free Events /// /// It includes both dates, full date times (not limited by the time in startDate and endDate) /// </summary> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="currentDateForAdvanceTime">Currend Date-Time for Calculating Advance Time. /// We consider the time BEFORE this parameter + Advance Time as unavailable. /// For two reasons: It is in the past, or we have to wait for the Advance Time to pass</param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public List<ProviderAvailabilityResult> GetFreeEvents( CalendarUser user, DateTimeOffset startDate, DateTimeOffset endDate, DateTimeOffset currentDateTimeForAdvanceTime) // currentDateTime is to add the Advance Time to { //---------------------------------------------------------------------- // Time Slices Size (in Minutes) // That can be Free or Busy //---------------------------------------------------------------------- const int TIME_SLICE_SIZE = 15; // in Minutes // IagoSRL: presaving the last date time slice (23:45:00 for a time_slice of 15) for later computations TimeSpan lastDayTimeSlice = new TimeSpan(24, 0, 0).Subtract(new TimeSpan(0, TIME_SLICE_SIZE, 0)); //---------------------------------------------------------------------- // For purposes of showing all the Time Slices of a day // we start on 0:00 AM and we end x minutes before the end of the day // (x minutes is the size of each Time Slice - see TIME_SLICE_SIZE above) // // What we do to get the endDate is // Add a Day and then Subtract the Time Slice size //---------------------------------------------------------------------- DateTimeOffset startDateTime = startDate; // To get to the Start of the last Time Slice of the day // First, it goes to the Next Day ( .AddDays(1) ) // and then reverses by the size of the Time Slice // ( .AddMinutes(-TIME_SLICE_SIZE) ) // We want to stop short of the TIME_SLICE_SIZE // as this is the last iteration for all the Timeslices in the Date Range DateTimeOffset endDateTime = endDate. AddDays(1). // Goes to the Next Day AddMinutes(-TIME_SLICE_SIZE); // Goes back by the Time Slice size //---------------------------------------------------------------------- // Advance Time // // The Providers (Users) have an Advance Time. // They aren't available for Jobs before that. // We calculate this non-available time from the Current Time on. //---------------------------------------------------------------------- var advanceTime = currentDateTimeForAdvanceTime + user.AdvanceTime; //---------------------------------------------------------------------- List<DataContainer> ldates = new List<DataContainer>(); var refDate = startDateTime; TimeSpan stamp = new TimeSpan(0, 0, 0); //---------------------------------------------------------------------- // new Calendar instance // filled with Events //---------------------------------------------------------------------- // IagoSRL: using optimized methods //Calendar iCal = GetCalendarEventsFromDBByUserDateRange(user, startDate, endDate); Calendar iCal = OptimizedGetCalendarEventsFromDBByUserDateRange(user, startDate, endDate); //---------------------------------------------------------------------- // Loop to generate all the Time Slices // for the Date Range //---------------------------------------------------------------------- // Iago: Since we get calculated the last day time slice in endDateTime // previously, we need to check lower than or equal to don't lost that last // time slice, as previously happens by checking only 'less than' while (refDate <= endDateTime) { var newTimeSliceStart = refDate.AddMinutes( TIME_SLICE_SIZE); ////---------------------------------------------------------------------- //// REMARKED ORIGINAL LDATES.ADD 2013/01/03 CA2S RM //// I DID THIS TO REFACTOR IT, //// SO IT IS EASIER TO DEBUG LINE BY LINE //// INSTEAD OF DOING EVERYTHING IN A SINGLE LDATES.ADD //// IT BUILDS THE NECESSARY VALUES FIRST, AND THEN ADDS THEM TO LDATES ////---------------------------------------------------------------------- //ldates.Add( // (newTimeSliceStart <= advanceTime) ? // new DataContainer() // Not Available because of Advance Time // { // Ocurrences = new List<Occurrence>(), // TimeBlock = stamp, // DT = refDate, // AddBusyTime = new TimeSpan() // } : // new DataContainer() // Timeslices after Advance Time // { // Ocurrences = iCal.GetOccurrences(refDate, newTimeSliceStart), // TimeBlock = stamp, // DT = refDate, // AddBusyTime = user.BetweenTime // }); //---------------------------------------------------------------------- DataContainer tempDataContainer = new DataContainer(); if (newTimeSliceStart <= advanceTime) { // TimeSlice Not Available because it is inside of the Advance Time tempDataContainer.Ocurrences = new HashSet<Occurrence>(); tempDataContainer.TimeBlock = stamp; tempDataContainer.DT = refDate; tempDataContainer.AddBusyTime = new TimeSpan(); } else { // Timeslices after Advance Time //---------------------------------------------------------------------- // iCal.GetOcurrence recovers the Ocurrences between two dates // but it is "INCLUSIVE these two dates" // // We want the events just before the ending date, // but NOT including the ending date. // // So, we did this Hack where // we subtract 1 Millisecond to the Ending Date // 2013/01/02 CA2S RM //---------------------------------------------------------------------- var TimeSliceEndJust1MillisecondBefore = newTimeSliceStart.AddMilliseconds(-1); //---------------------------------------------------------------------- tempDataContainer.Ocurrences = iCal.GetOccurrences( new CalDateTime(refDate.UtcDateTime, "UTC"), new CalDateTime(TimeSliceEndJust1MillisecondBefore.UtcDateTime, "UTC") ); tempDataContainer.TimeBlock = stamp; tempDataContainer.DT = refDate; tempDataContainer.AddBusyTime = user.BetweenTime; } ldates.Add(tempDataContainer); //---------------------------------------------------------------------- // Prepare for Next TimeSlice //---------------------------------------------------------------------- refDate = newTimeSliceStart; //---------------------------------------------------------------------- // If we are getting to the Last Time Slice of the Day // (24:00:00 minus the Time Slice size) // then we start anew from 00:00:00 //---------------------------------------------------------------------- stamp = (stamp == lastDayTimeSlice) ? stamp = new TimeSpan() : // Starting anew from 00:00:00 stamp.Add(new TimeSpan(0, TIME_SLICE_SIZE, 0)); // Continue with next Time Slice } /* IagoSRL: one-step, don't waste iteration cycles! List<ProviderAvailability> ocurrences = new List<ProviderAvailability>(); //---------------------------------------------------------------------- // Gets the TimeSlices with Availability // depending on the Ocurrences inside each TimeSlice //---------------------------------------------------------------------- ocurrences = ldates.Select( dts => new ProviderAvailability(dts)).ToList(); //---------------------------------------------------------------------- // Returns the Results //---------------------------------------------------------------------- return ocurrences. Select(av => av.result).ToList(); */ return ldates.Select( dts => new ProviderAvailability(dts).result ).ToList(); } #endregion #region Get the Calendar filled with the Events for the User /// <summary> /// Get the Calendar, filled with the Events for the User /// </summary> /// <param name="user"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public Calendar GetCalendarEventsFromDBByUser(CalendarUser user) { Calendar iCal = GetCalendarLibraryInstance(); iCal.Events.Clear(); if (user != null) { foreach (var currEvent in GetEventsByUser(user)) { iCal.Events.Add(currEvent); } } return iCal; } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public Calendar GetCalendarEventsFromDBByUserDateRange( CalendarUser user, DateTimeOffset startDate, DateTimeOffset endDate) { if (user == null) throw new ArgumentNullException("user"); return GetCalendarForEvents(GetEventsByUserDateRange( user, startDate, endDate)); } public Calendar GetCalendarForEvents(IEnumerable<iEvent> events) { Calendar iCal = GetCalendarLibraryInstance(); foreach (var ievent in events) { iCal.Events.Add(ievent); } return iCal; } public Calendar GetCalendarForEvents(IEnumerable<CalendarEvents> events) { Calendar iCal = GetCalendarLibraryInstance(); foreach (var ievent in events) { iCal.Events.Add(CreateEvent(ievent)); } return iCal; } /// <summary> /// Get Calendar Events, for Export, by User /// /// It only takes into account the Events /// with UIDs starting with Asterisk (*) /// </summary> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public Calendar GetCalendarByUserForExport( CalendarUser user) { Calendar iCalForExport = GetCalendarLibraryInstance(); iCalForExport.Events.Clear(); /* IagoSRL: We add some properties to the exported calendar for best interoperability * with other programs, some standard and some other not: */ // By default, ical is Gregorian, but for best result be explicit iCalForExport.AddProperty("CALSCALE", "GREGORIAN"); // Calendar name to display (Google Calendar property) iCalForExport.AddProperty("X-WR-CALNAME", "Loconomics"); // Time Zone if (user.DefaultTimeZone != null) { // Calendar Time Zone information in standard format // used by objects contained in the file (events, vfreebusy..) var vt = new VTimeZone(user.DefaultTimeZone); iCalForExport.AddTimeZone(vt); // Default calendar TimeZone (Google Calendar property) -used for objets without // a specific time-zone, but non standard- iCalForExport.AddProperty("X-WR-TIMEZONE", user.DefaultTimeZone); } if (user != null) { foreach (var currEvent in GetEventsByUserForExport(user, user.DefaultTimeZone)) { iCalForExport.Events.Add(currEvent); /* IagoSRL: filtering per "*" removed because is now events are filtered by EventType * that works better and more extensively, and has not the problem of events without saved GUID // Only add Events that have an UID with a "*" in front if (currEvent.UID.Length > 0 && currEvent.UID.Substring(0, 1) == "*") { iCalForExport.Events.Add(currEvent); } */ } } return iCalForExport; } #endregion #region DateTime - Offsets - Timezone private Dictionary<string, NodaTime.DateTimeZone> cachedTimeZones = new Dictionary<string, NodaTime.DateTimeZone>(); private NodaTime.DateTimeZone GetTimeZone(string tzid) { NodaTime.DateTimeZone timezone = NodaTime.DateTimeZone.Utc; if (cachedTimeZones.ContainsKey(tzid)) { timezone = cachedTimeZones[tzid]; } else { timezone = NodaTime.DateTimeZoneProviders.Tzdb.GetZoneOrNull(tzid) ?? timezone; cachedTimeZones.Add(tzid, timezone); } return timezone; } private CalDateTime CalDateTimeFromOffsetAndTimeZone(DateTimeOffset dto, string tzid) { var timezone = GetTimeZone(tzid); if (timezone == null) throw new Exception(String.Format("Time zone does not found ({0})", tzid)); var zdt = NodaTime.Instant .FromDateTimeOffset(dto) .InZone(timezone); // Do this conversion very carefully: it's different to call the 'LocalDateTime' at the ZonedDateTime object // than in a DateTimeOffset, and CalDateDime expects a DateTime as the 'time as in that offset / offset' to be provided // with a tzid to manage date correctly; while a ZonedDateTime.LocalDateTime returns the date part 'as is' in the // object time zone, not in the 'system' time zone, so this one is what we want; BUT the DateTime object // must NOT include reference to the system time or UTC, must be of Kind.Unspecified, otherwise CalDateTime // will try some conversions from system time to offset or discard the tzid when is a Kind.UTC. return new CalDateTime(zdt.LocalDateTime.ToDateTimeUnspecified(), tzid); } #endregion #region Create Event (iCal Format, having the Loconomics DB Record) /// <summary> /// Create Event /// /// In iCal format, from the Loconomics DB /// </summary> /// <param name="eventFromDB"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public iEvent CreateEvent( CalendarDll.Data.CalendarEvents eventFromDB) { // Get TZID or fallback in UTC. Process properly the datetimes stored, they include offset so we can get it's offseted datetime // and left CalDateTime to process it as in the appropiated time zone. var tzid = eventFromDB.TimeZone; var hasTz = !String.IsNullOrEmpty(tzid); if (!hasTz) { tzid = "UTC"; } var eventStart = CalDateTimeFromOffsetAndTimeZone(eventFromDB.StartTime, tzid); var eventEnd = CalDateTimeFromOffsetAndTimeZone(eventFromDB.EndTime, tzid); var eventRecurrenceId = eventFromDB.RecurrenceId.HasValue ? CalDateTimeFromOffsetAndTimeZone(eventFromDB.RecurrenceId.Value, tzid) : null; // DTStamp, per iCalendar standard, "MUST be in UTC" // It represents the creation of the VEVENT record. var eventStamp = CalDateTimeFromOffsetAndTimeZone(eventFromDB.StampTime ?? DateTimeOffset.UtcNow, "UTC"); iEvent iCalEvent = new iEvent { Summary = eventFromDB.Summary ?? null, Start = eventStart, //Duration = (eventFromDB.EndTime - eventFromDB.StartTime), End = eventEnd, Location = eventFromDB.Location ?? null, AvailabilityID = eventFromDB.CalendarAvailabilityTypeID, EventType = eventFromDB.EventType, IsAllDay = eventFromDB.IsAllDay, Status = GetEventStatus(eventFromDB.CalendarAvailabilityTypeID), Priority = eventFromDB.Priority ?? 0, Uid = (string.IsNullOrEmpty(eventFromDB.UID)) ? "*" + Guid.NewGuid().ToString() + "@loconomics.com" : eventFromDB.UID, Class = eventFromDB.Class, Organizer = eventFromDB.Organizer != null ? new Organizer(eventFromDB.Organizer) : null, Transparency = (TransparencyType)(eventFromDB.Transparency ? 1 : 0), Created = CalDateTimeFromOffsetAndTimeZone(eventFromDB.CreatedDate ?? DateTime.Now, "UTC"), DtEnd = eventEnd, DtStamp = eventStamp, DtStart = eventStart, LastModified = CalDateTimeFromOffsetAndTimeZone(eventFromDB.UpdatedDate ?? DateTime.Now, "UTC"), Sequence = eventFromDB.Sequence ?? 0, RecurrenceId = eventRecurrenceId, GeographicLocation = eventFromDB.Geo != null ? new GeographicLocation(eventFromDB.Geo) : null/*"+-####;+-####"*/, Description = eventFromDB.Description ?? null }; //---------------------------------------------------------------------- // Additional Processing //---------------------------------------------------------------------- FillExceptionsDates( iCalEvent, eventFromDB, tzid); FillRecurrencesDates(iCalEvent, eventFromDB, tzid); FillContacts( iCalEvent, eventFromDB); FillAttendees( iCalEvent, eventFromDB); FillComments( iCalEvent, eventFromDB); FillRecurrences( iCalEvent, eventFromDB); //---------------------------------------------------------------------- return iCalEvent; } #endregion #region Create Between Events /// <summary> /// Create Between Events /// /// It takes the Original iCal Event /// and creates another iCal Event /// following the original, /// and with the duration of the Between Event of the User /// </summary> /// <param name="originalICalEvent"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA</remarks> private iEvent CreateBetweenEvent(iEvent originalICalEvent,CalendarUser user) { //CultureInfo.CreateSpecificCulture("es-ES"); var resources = new System.Resources.ResourceManager( typeof(CalendarDll.Resources)); string descriptionBetweenTime = resources.GetString( "BetweenTime", System.Threading.Thread.CurrentThread.CurrentCulture); // "Between Time" - Localized iEvent events = new iEvent() { Summary = descriptionBetweenTime, Uid = "*" + Guid.NewGuid().ToString(), // * at the start dennotes a Loconomics (not external) Event Start = originalICalEvent.DtEnd, Duration = user.BetweenTime, AvailabilityID = originalICalEvent.AvailabilityID, Status = originalICalEvent.Status, Priority = originalICalEvent.Priority, Description = originalICalEvent.Description + " - " + descriptionBetweenTime, Organizer = originalICalEvent.Organizer, Transparency = originalICalEvent.Transparency, Created = originalICalEvent.Created, DtStamp = originalICalEvent.DtEnd, DtStart = originalICalEvent.DtEnd, DtEnd = originalICalEvent.DtEnd.Add(user.BetweenTime), Sequence = originalICalEvent.Sequence, RecurrenceId = originalICalEvent.RecurrenceId, //RecurrenceRules = evt.RecurrenceRules, }; //---------------------------------------------------------------------- // If there are Recurrence Rules in the Original // add them to the "Between Event" too //---------------------------------------------------------------------- foreach(var a in originalICalEvent.RecurrenceRules) events.RecurrenceRules.Add(a); //---------------------------------------------------------------------- return events; } #endregion #region Get Event Status /// <summary> /// Get Event Status /// </summary> /// <param name="statusID"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private EventStatus GetEventStatus(int statusID) { //TODO // // Tentative = 0, // Confirmed = 1, // Cancelled = 2, // //cancelled excluded if (statusID == 3) return EventStatus.Tentative; else if (statusID == 1 || statusID == 4) return EventStatus.Confirmed; else if (statusID == 2 || statusID == 0) return EventStatus.Confirmed; return EventStatus.Confirmed; } #endregion #region Get Transparency /// <summary> /// Get Transparency /// </summary> /// <param name="eventStatus"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA</remarks> private static bool getTransparency(int eventStatus) { if (eventStatus == 0) return true; return false; } #endregion #region Get Availability Id private int getAvailabilityId(Event currEvent) { var Status = currEvent.Status; var Transparency = currEvent.Transparency; if (Transparency == null) Transparency = TransparencyType.Opaque; var returnValue = AvailabilityTypes.TRANSPARENT; if (Transparency == TransparencyType.Transparent) { returnValue = AvailabilityTypes.TRANSPARENT; } else { switch (Status) { case EventStatus.Confirmed: { returnValue = AvailabilityTypes.BUSY; break; } case EventStatus.Tentative: { returnValue = AvailabilityTypes.TENTATIVE; break; } case EventStatus.Cancelled: { returnValue = AvailabilityTypes.TRANSPARENT; break; } default: { returnValue = AvailabilityTypes.TENTATIVE; break; } } } return (Int32)returnValue; } /// <summary> /// Get the Database AvailabilityID based on the /// FreeBusyEntry status, that has one-to-one equivalencies /// </summary> /// <param name="fbentry"></param> /// <returns></returns> /// <remarks>IagoSRL 2013/05/08</remarks> private AvailabilityTypes getAvailabilityId(IFreeBusyEntry fbentry) { switch (fbentry.Status) { case FreeBusyStatus.Free: return AvailabilityTypes.FREE; default: case FreeBusyStatus.Busy: return AvailabilityTypes.BUSY; case FreeBusyStatus.BusyTentative: return AvailabilityTypes.TENTATIVE; case FreeBusyStatus.BusyUnavailable: return AvailabilityTypes.UNAVAILABLE; } } /// <summary> /// Get Availability Id /// </summary> /// <param name="eventStatus"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private int getAvailabilityId( int eventStatus) { if (eventStatus == 0) { return 4; } return 2; } /// <summary> /// Availabilty when Importing /// /// It calculates the Availability /// depending on the Status (which could be Confirmed, Tentative, Cancelled) /// and the Transparency (which could be Opaque or Transparent) /// </summary> /// <param name="Status"></param> /// <param name="Transparency"></param> /// <returns></returns> /// <remarks>2013/01/02 CA2S RM</remarks> private int getAvailabilityId(string Status, string Transparency) { // Event Availability (Return Values) // (See table: CalendarAvailabilityType) // //const Int32 AVAILABILITY_UNAVAILABLE = 0; const Int32 AVAILABILITY_FREE = 1; const Int32 AVAILABILITY_BUSY = 2; const Int32 AVAILABILITY_TENTATIVE = 3; const Int32 AVAILABILITY_TRANSPARENT = 4; const string TRANSPARENCY_OPAQUE = "OPAQUE"; const string TRANSPARENCY_TRANSPARENT = "TRANSPARENT"; const string STATUS_CONFIRMED = "CONFIRMED"; const string STATUS_TENTATIVE = "TENTATIVE"; const string STATUS_CANCELLED = "CANCELLED"; //---------------------------------------------------------------------- // Clean Up of Parameters //---------------------------------------------------------------------- Status = Status.Trim().ToUpper(); Transparency = Transparency.Trim().ToUpper(); //---------------------------------------------------------------------- // Default Values for the Parameters //---------------------------------------------------------------------- if (Status == "") { Status = STATUS_CONFIRMED; } if (Transparency == "") { Transparency = TRANSPARENCY_OPAQUE; } ////---------------------------------------------------------------------- //// If Both Parameters are empty ////---------------------------------------------------------------------- //if ((Status=="") && (Transparency=="")) //{ // return 2; // 2 == Busy //} ////---------------------------------------------------------------------- //// If Status Parameter is empty ////---------------------------------------------------------------------- //if ((Status == "") && (Transparency != "")) //{ // if (Transparency == "") // { // } // else // { // } //} //---------------------------------------------------------------------- // Default Value for the Return Value: Transparent // (Doesn't take part in Free/Busy calculations) //---------------------------------------------------------------------- Int32 returnValue = AVAILABILITY_TRANSPARENT; //---------------------------------------------------------------------- // Check which Combination of Parameters applies //---------------------------------------------------------------------- if (Transparency == TRANSPARENCY_OPAQUE) { switch (Status) { case STATUS_CONFIRMED: { returnValue = AVAILABILITY_BUSY; break; } case STATUS_TENTATIVE: { returnValue = AVAILABILITY_TENTATIVE; break; } case STATUS_CANCELLED: { returnValue = AVAILABILITY_TRANSPARENT; break; } } // switch (Status) } else if (Transparency == TRANSPARENCY_TRANSPARENT) { switch (Status) { case STATUS_CONFIRMED: { returnValue = AVAILABILITY_FREE; break; } case STATUS_TENTATIVE: { // Case Free, but Tentative - Don't take part in calculations returnValue = AVAILABILITY_TRANSPARENT; break; } case STATUS_CANCELLED: { // Case Free, but Cancelled - Don't take part in calculations returnValue = AVAILABILITY_TRANSPARENT; break; } } // switch (Status) } // else if (Transparency == TRANSPARENCY_TRANSPARENT) //---------------------------------------------------------------------- // Return Value //---------------------------------------------------------------------- return returnValue; } #endregion #region Get Events by User /// <summary> /// Get Events by User /// </summary> /// <param name="user"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private IEnumerable<iEvent> GetEventsByUser(CalendarUser user) { using (var db = new CalendarDll.Data.loconomicsEntities()) { var listEventsFromDB = db.CalendarEvents. Where(c => c.UserId == user.Id && c.Deleted == null).ToList(); var iCalEvents = new List<iEvent>(); foreach (var currEventFromDB in listEventsFromDB) { var iCalEvent = CreateEvent(currEventFromDB); iCalEvents.Add(iCalEvent); //---------------------------------------------------------------------- // If the Event is a Busy Event // that is Work of a Provider, // it adds a "Between Time" or buffer time // so that the next Job is not completely next in the Calendar. // // This is to give some preparation or transportation time // between Jobs to the Provider //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Event types //---------------------------------------------------------------------- // // 1 booking - GENERATES BETWEEN TIME // 2 work hours // 3 availibility events // 4 imported // 5 other // //---------------------------------------------------------------------- if (iCalEvent.EventType == 1) { var evExt = CreateBetweenEvent(iCalEvent,user); iCalEvents.Add(evExt); } //var newEv = CreateEvent(c); //yield return newEv; //---------------------------------------------------------------------- } return iCalEvents; } } /// <summary> /// Based on GetEventsByUser, it filter events by type to only that required in /// the export task. /// </summary> /// <param name="user"></param> /// <param name="defaultTZID"></param> /// <returns></returns> /// <remarks>IagoSRL</remarks> private IEnumerable<iEvent> GetEventsByUserForExport(CalendarUser user, string defaultTZID) { using (var db = new CalendarDll.Data.loconomicsEntities()) { var listEventsFromDB = db.CalendarEvents. // We filter by user and Where(c => c.UserId == user.Id && c.Deleted == null && // By type NOT being free-hours (2) or imported (4). Commented on issue #228 2013-05-13 !(new int[]{2, 4}).Contains(c.EventType)).ToList(); var iCalEvents = new List<iEvent>(); foreach (var currEventFromDB in listEventsFromDB) { var iCalEvent = CreateEvent(currEventFromDB); iCalEvents.Add(iCalEvent); /* As requested by Josh on issue #228 2013-05-11 * we don't want now the 'buffer event' be exported if (iCalEvent.EventType == 1) { var evExt = CreateBetweenEvent(iCalEvent,user); iCalEvents.Add(evExt); }*/ } return iCalEvents; } } /// <summary> /// Get Events By User /// (overloads another version without Dates parameters) /// /// And also by Range of Dates /// Note: Because recurrence events are more complicated, /// they are recovered regardless of dates /// </summary> /// <param name="user"></param> /// <param name="startEvaluationDate"></param> /// <param name="endEvaluationDate"></param> /// <returns></returns> /// <remarks>2012/12 by CA2S FA</remarks> public IEnumerable<iEvent> GetEventsByUserDateRange( CalendarUser user, DateTimeOffset startEvaluationDate, DateTimeOffset endEvaluationDate) { // For the Ending of the Range // We'll get the Next Day // And the comparisson will be: Less than this Next Day DateTimeOffset nextDayFromEndEvaluationDay = endEvaluationDate.Date.AddDays(1); using (var db = new CalendarDll.Data.loconomicsEntities()) { // Recovers Events // for a particular User // and a particular Date Range // OR, if they are Recurrence, any Date Range var listEventsFromDB = db.CalendarEvents.Where( c => c.UserId == user.Id && c.Deleted == null && ( // IagoSRL: Date Ranges query updated from being // 'only events that are completely included' (next commented code from CASS): //(c.EndTime < nextDayFromEndEvaluationDay && //c.StartTime >=startEvaluationDate) || // to be 'all events complete or partially inside the range: complete included or with a previous // start or with a posterior end'. // This fix a bug found on #463 described on comment https://github.com/joshdanielson/Loconomics/issues/463#issuecomment-36936782 and nexts. ( c.StartTime < nextDayFromEndEvaluationDay && c.EndTime >= startEvaluationDate ) || // OR, if they are Recurrence, any Date Range c.CalendarReccurrence.Any() ) ).ToList(); foreach (var currEventFromDB in listEventsFromDB) { var iCalEvent = CreateEvent(currEventFromDB); yield return iCalEvent; //---------------------------------------------------------------------- // If the Event is a Busy Event // that is Work of a Provider, // it adds a "Between Time" or buffer time // so that the next Job is not completely next in the Calendar. // // This is to give some preparation or transportation time // between Jobs to the Provider //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Event types //---------------------------------------------------------------------- // // 1 booking - GENERATES BETWEEN TIME // 2 work hours // 3 availibility events // 4 imported // 5 other // //---------------------------------------------------------------------- if (iCalEvent.EventType == 1 && user.BetweenTime > TimeSpan.Zero) { yield return CreateBetweenEvent(iCalEvent,user); } //var newEv = CreateEvent(c); //yield return newEv; //---------------------------------------------------------------------- } } } #endregion #region IAGO: New, faster, optimized fetch event and occurrences (don't fetch unneeded data, use SQL, time filtering, faster) /// <summary> /// Create Event /// /// In iCal format, from the Loconomics DB /// </summary> /// <param name="eventFromDB"></param> /// <returns></returns> /// <remarks>2015-09 by iago</remarks> public iEvent OptimizedCreateEvent( CalendarDll.Data.CalendarEvents eventFromDB, System.Data.Entity.DbContext db) { // Get TZID or fallback in UTC. Process properly the datetimes stored, they include offset so we can get it's offseted datetime // and left CalDateTime to process it as in the appropiated time zone. var tzid = eventFromDB.TimeZone; var hasTz = !String.IsNullOrEmpty(tzid); if (!hasTz) { tzid = "UTC"; } var eventStart = CalDateTimeFromOffsetAndTimeZone(eventFromDB.StartTime, tzid); var eventEnd = CalDateTimeFromOffsetAndTimeZone(eventFromDB.EndTime, tzid); var eventRecurrenceId = eventFromDB.RecurrenceId.HasValue ? CalDateTimeFromOffsetAndTimeZone(eventFromDB.RecurrenceId.Value, tzid) : null; // DTStamp, per Calendar standard, "MUST be in UTC" // It represents the creation of the VEVENT record. var eventStamp = CalDateTimeFromOffsetAndTimeZone(eventFromDB.StampTime ?? DateTime.UtcNow, "UTC"); iEvent iCalEvent = new iEvent() { Summary = eventFromDB.Summary ?? null, Start = eventStart, //Duration = (eventFromDB.EndTime - eventFromDB.StartTime), End = eventEnd, Location = eventFromDB.Location ?? null, AvailabilityID = eventFromDB.CalendarAvailabilityTypeID, EventType = eventFromDB.EventType, IsAllDay = eventFromDB.IsAllDay, Status = GetEventStatus(eventFromDB.CalendarAvailabilityTypeID), Priority = eventFromDB.Priority ?? 0, Uid = (string.IsNullOrEmpty(eventFromDB.UID)) ? "*" + Guid.NewGuid().ToString() + "@loconomics.com" : eventFromDB.UID, Class = eventFromDB.Class, Organizer = eventFromDB.Organizer != null ? new Organizer(eventFromDB.Organizer) : null, Transparency = (TransparencyType)(eventFromDB.Transparency ? 1 : 0), Created = CalDateTimeFromOffsetAndTimeZone(eventFromDB.CreatedDate ?? DateTime.Now, "UTC"), DtEnd = eventEnd, DtStamp = eventStamp, DtStart = eventStart, LastModified = CalDateTimeFromOffsetAndTimeZone(eventFromDB.UpdatedDate ?? DateTime.Now, "UTC"), Sequence = eventFromDB.Sequence ?? 0, RecurrenceId = eventRecurrenceId, GeographicLocation = eventFromDB.Geo != null ? new GeographicLocation(eventFromDB.Geo) : null/*"+-####;+-####"*/, Description = eventFromDB.Description ?? null }; // Additional data loading, references eventFromDB.CalendarEventExceptionsPeriodsList = db.Database.SqlQuery<CalendarEventExceptionsPeriodsList>("SELECT * FROM CalendarEventExceptionsPeriodsList WHERE IdEvent = {0}", eventFromDB.Id).ToList(); eventFromDB.CalendarEventRecurrencesPeriodList = db.Database.SqlQuery<CalendarEventRecurrencesPeriodList>("SELECT * FROM CalendarEventRecurrencesPeriodList WHERE IdEvent = {0}", eventFromDB.Id).ToList(); eventFromDB.CalendarReccurrence = db.Database.SqlQuery<CalendarReccurrence>("SELECT * FROM CalendarReccurrence WHERE EventID = {0}", eventFromDB.Id).ToList(); foreach (var r in eventFromDB.CalendarEventExceptionsPeriodsList) { r.CalendarEventExceptionsPeriod = db.Database.SqlQuery<CalendarEventExceptionsPeriod>("SELECT * FROM CalendarEventExceptionsPeriod WHERE IdException = {0}", r.Id).ToList(); } foreach (var r in eventFromDB.CalendarEventRecurrencesPeriodList) { r.CalendarEventRecurrencesPeriod = db.Database.SqlQuery<CalendarEventRecurrencesPeriod>("SELECT * FROM CalendarEventRecurrencesPeriod WHERE IdRecurrence = {0}", r.Id).ToList(); } //---------------------------------------------------------------------- // Additional Processing //---------------------------------------------------------------------- FillExceptionsDates(iCalEvent, eventFromDB, tzid); FillRecurrencesDates(iCalEvent, eventFromDB, tzid); FillRecurrences(iCalEvent, eventFromDB); // Unneeded, commented out (we just want times, occurrences, not meta data records) //FillContacts( iCalEvent, eventFromDB); //FillAttendees( iCalEvent, eventFromDB); //FillComments( iCalEvent, eventFromDB); //---------------------------------------------------------------------- return iCalEvent; } public Calendar OptimizedGetCalendarEventsFromDBByUserDateRange( CalendarUser user, DateTimeOffset startDate, DateTimeOffset endDate) { if (user == null) throw new ArgumentNullException("user"); return GetCalendarForEvents(OptimizedGetEventsByUserDateRange( user, startDate, endDate)); } /// <summary> /// Get Events By User and by Range of Dates /// Note: Because recurrence events are more complicated, /// they are recovered regardless of dates /// </summary> /// <param name="user"></param> /// <param name="startEvaluationDate">Included (more than or equals)</param> /// <param name="endEvaluationDate">Excluded (less than)</param> /// <returns></returns> /// <remarks>2015-09 Iago</remarks> public IEnumerable<iEvent> OptimizedGetEventsByUserDateRange( CalendarUser user, DateTimeOffset startEvaluationDate, DateTimeOffset endEvaluationDate) { using (var db = new CalendarDll.Data.loconomicsEntities()) { // Recovers Events // for a particular User // and a particular Date Range // OR, if they are Recurrence, any Date Range (cannot be filtered out at database) // Filtering is 'all events complete or partially inside the range: complete included or with a previous // start or with a posterior end'. // As of #463, comment https://github.com/joshdanielson/Loconomics/issues/463#issuecomment-36936782 and nexts. var listEventsFromDB = db.Database.SqlQuery<CalendarEvents>(@" SELECT [Id] ,[UserId] ,[EventType] ,[Summary] ,[UID] ,[CalendarAvailabilityTypeID] ,[Transparency] ,[StartTime] ,[EndTime] ,[IsAllDay] ,[StampTime] ,[TimeZone] ,[Priority] ,[Location] ,[UpdatedDate] ,[CreatedDate] ,[ModifyBy] ,[Class] ,[Organizer] ,[Sequence] ,[Geo] ,[RecurrenceId] ,[TimeBlock] ,[DayofWeek] ,[Description] ,[Deleted] FROM [CalendarEvents] WHERE userId = {2} AND ( (StartTime < {0} AND EndTime >= {1}) OR EXISTS (SELECT id from CalendarReccurrence AS R where R.EventID = CalendarEvents.Id) ) AND Deleted is null ", endEvaluationDate, startEvaluationDate, user.Id); foreach (var currEventFromDB in listEventsFromDB) { // IT LOADS RELATED DATA TOO, like recurrence // MUST BE BEFORE the CreateBetweenEvent (but can be yielded later if order must change, // with change on CreateBetweenEvent on where time is applied; right now is after) var iCalEvent = OptimizedCreateEvent(currEventFromDB, db); yield return iCalEvent; //---------------------------------------------------------------------- // If the Event is a Busy Event // that is Work of a Provider, // it adds a "Between Time" or buffer time // so that the next Job is not completely next in the Calendar. // // This is to give some preparation or transportation time // between Jobs to the Provider //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Event types //---------------------------------------------------------------------- // // 1 booking - GENERATES BETWEEN TIME // 2 work hours // 3 availibility events // 4 imported // 5 other // //---------------------------------------------------------------------- if (iCalEvent.EventType == 1 && user.BetweenTime > TimeSpan.Zero) { yield return CreateBetweenEvent(iCalEvent, user); } //var newEv = CreateEvent(c); //yield return newEv; //---------------------------------------------------------------------- } } } /// <summary> /// Represents a slot of time (a range of two dates) /// for a type of availability. /// </summary> public class AvailabilitySlot { public DateTimeOffset StartTime; public DateTimeOffset EndTime; public int AvailabilityTypeID; public override bool Equals(object obj) { var other = obj as AvailabilitySlot; if (other != null) { return StartTime == other.StartTime && EndTime == other.EndTime && AvailabilityTypeID == other.AvailabilityTypeID; } return false; } } /// <summary> /// Compute the occurrences of all events, normal and recurrents, from the filled in Calendar given between the dates /// as of the internal logic of the Calendar component. /// Results are in UTC /// </summary> /// <param name="ical"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <returns></returns> public IEnumerable<AvailabilitySlot> GetEventsOccurrencesInAvailabilitySlotsUtc(Calendar ical, DateTimeOffset startTime, DateTimeOffset endTime) { // IMPORTANT: The GetOccurrences API discards the time part of the passed datetimes, it means that the endtime // gets discarded, to be included in the results we need to add almost 1 day to the value. // In the loop, we filter out occurrences out of the original endTime limit var queryEndTime = endTime.AddDays(1); foreach (var ev in ical.Events) { foreach (var occ in ev.GetOccurrences(startTime.UtcDateTime, queryEndTime.UtcDateTime)) { var slotStart = new DateTimeOffset(occ.Period.StartTime.AsUtc, TimeSpan.Zero); var slotEnd = new DateTimeOffset(occ.Period.EndTime.AsUtc, TimeSpan.Zero); // Filter out occurrences out of the original endTime if (slotStart >= endTime) { continue; } yield return new AvailabilitySlot { StartTime = slotStart, EndTime = slotEnd, AvailabilityTypeID = ((iEvent)ev).AvailabilityID }; } } } public DateTimeOffset DateTimeOffsetFromCalDateTime(IDateTime time) { var utc = new DateTimeOffset(time.AsUtc, TimeSpan.Zero); var zone = String.IsNullOrEmpty(time.TimeZoneName) ? null : GetTimeZone(time.TimeZoneName); if (zone == null) { return utc; } else { return NodaTime.ZonedDateTime.FromDateTimeOffset(utc).WithZone(zone).ToDateTimeOffset(); } } public IEnumerable<AvailabilitySlot> SortDateRange(IEnumerable<AvailabilitySlot> dateRanges) { return dateRanges.OrderBy(dr => dr.StartTime); } /// <summary> /// For the given user and included in the given dates, returns all the /// availability slots for the computed event occurrences, complete or partial. /// Results are event occurrences in the format of availability slots, so overlapping of /// slots will happen, and holes. Results are sorted by start time. /// Another method must perform the computation of put all this slots in a single, consecutive /// and complete timeline, where some availabilities takes precedence over others to don't have overlapping. /// Results may include slots that goes beyond the given filter dates, but it ensures that all that, partial or complete /// happens in that dates will be returned. /// /// Resulting dates are given in UTC. /// </summary> /// <param name="userID"></param> /// <param name="startTime">Included (more than or equals)</param> /// <param name="endTime">Excluded (less than)</param> /// <returns></returns> public IEnumerable<AvailabilitySlot> GetEventsOccurrencesInUtcAvailabilitySlotsByUser(int userID, DateTimeOffset startTime, DateTimeOffset endTime) { // We need an Calendar to include events and being able to compute occurrences Calendar data = GetCalendarLibraryInstance(); var events = OptimizedGetEventsByUserDateRange(new CalendarUser(userID), startTime, endTime); foreach (var ievent in events) data.Events.Add(ievent); var occurrences = GetEventsOccurrencesInAvailabilitySlotsUtc(data, startTime, endTime).OrderBy(dr => dr.StartTime); return occurrences; } #endregion #region Fill Exceptions Dates /// <summary> /// Fill Exceptions Dates /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillExceptionsDates( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB, string defaultTZID) { var tzid = defaultTZID ?? "UTC"; var exceptionDates = eventFromDB.CalendarEventExceptionsPeriodsList; if (!exceptionDates.Any()) { return; } var periodsList = new List<PeriodList>(); foreach (var prd in exceptionDates) { var period = new PeriodList(); foreach (var dates in prd.CalendarEventExceptionsPeriod) { if (dates.DateEnd.HasValue) period.Add( new Period( CalDateTimeFromOffsetAndTimeZone(dates.DateStart, tzid), CalDateTimeFromOffsetAndTimeZone(dates.DateEnd.Value, tzid))); else period.Add( new Period( CalDateTimeFromOffsetAndTimeZone(dates.DateStart, tzid))); } iCalEvent.ExceptionDates.Add(period); } } private void FillExceptionsDatesToDB(Event iCalEvent, CalendarDll.Data.CalendarEvents eventForDB) { var exceptionDates = iCalEvent.ExceptionDates; if (!exceptionDates.Any()) { return; } var periodsList = new List<PeriodList>(); var periods = new CalendarEventExceptionsPeriodsList(); foreach (var prd in exceptionDates) { foreach (var dates in prd) { periods.CalendarEventExceptionsPeriod.Add(new CalendarEventExceptionsPeriod() { DateStart = new DateTimeOffset(dates.StartTime.AsUtc, TimeSpan.Zero), DateEnd = dates.EndTime != null ? (DateTimeOffset?)new DateTimeOffset(dates.EndTime.AsUtc, TimeSpan.Zero) : null, }); } } eventForDB.CalendarEventExceptionsPeriodsList.Add(periods); } #endregion #region Fill Recurrence Dates /// <summary> /// Fill Recurrence Dates /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillRecurrencesDates( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB, string defaultTZID) { var tzid = defaultTZID ?? "UTC"; var recurrenceDates = eventFromDB.CalendarEventRecurrencesPeriodList; if (!recurrenceDates.Any()) return; var periodsList = new List<PeriodList>(); foreach (var prd in recurrenceDates) { var period = new PeriodList(); foreach (var dates in prd.CalendarEventRecurrencesPeriod) { if (dates.DateEnd.HasValue) period.Add( new Period( CalDateTimeFromOffsetAndTimeZone(dates.DateStart, tzid), CalDateTimeFromOffsetAndTimeZone(dates.DateEnd.Value, tzid))); else period.Add( new Period( CalDateTimeFromOffsetAndTimeZone(dates.DateStart, tzid))); } iCalEvent.RecurrenceDates.Add(period); } } private void FillRecurrencesDatesToDB( Event iCalEvent, CalendarEvents eventForDB) { var recurrenceDates = iCalEvent.RecurrenceDates; if (!recurrenceDates.Any()) return; var periodsList = new CalendarEventRecurrencesPeriodList(); foreach (var prd in recurrenceDates) { foreach (var dates in prd) { periodsList.CalendarEventRecurrencesPeriod.Add(new CalendarEventRecurrencesPeriod{ DateStart = new DateTimeOffset(dates.StartTime.AsUtc, TimeSpan.Zero), DateEnd = dates.EndTime != null ? (DateTimeOffset?)new DateTimeOffset(dates.EndTime.AsUtc, TimeSpan.Zero) : null }); } } eventForDB.CalendarEventRecurrencesPeriodList.Add(periodsList); } #endregion #region Fill Contacts /// <summary> /// Fill Contacts /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillContacts( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB) { if (eventFromDB.CalendarEventsContacts.Any()) foreach(var ct in eventFromDB.CalendarEventsContacts) iCalEvent.Contacts.Add(ct.Contact); } /// <summary> /// /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventForDB"></param> private void FillContactsToDB(Event iCalEvent, CalendarEvents eventForDB) { if (!iCalEvent.Contacts.Any()) return; foreach(var contact in iCalEvent.Contacts){ eventForDB.CalendarEventsContacts.Add(new CalendarEventsContacts(){ Contact = contact, IdEvent = eventForDB.Id}); } } #endregion #region Fill Attendees /// <summary> /// Fill Attendees /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillAttendees( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB) { //cass attendee[0] type: 'MAILTO:myid@mymaildomain.com' //cass attendee[1] type: 'John Doe' //cass attemdee[2] type: 'Admin, Administrator' if (!eventFromDB.CalendarEventsAttendees.Any()) return; foreach (var att in eventFromDB.CalendarEventsAttendees) { iCalEvent.Attendees.Add(new Attendee(att.Uri){ CommonName = att.Attendee, Role = att.Role}); } } /// <summary> /// /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventForDB"></param> /// <remarks>Changed by IagoSRL on 2013/05/08 to be generic, accepting any IUniqueComponent. /// This allow using the method not only for Events, like originally, else for vfreebusy objects /// and others.</remarks> private void FillAttendeesToDB(IUniqueComponent iCalObject, CalendarEvents eventForDB) { if (!iCalObject.Attendees.Any()) return; foreach (var atts in iCalObject.Attendees) { eventForDB.CalendarEventsAttendees.Add(new CalendarEventsAttendees { Attendee = atts.CommonName, IdEvent = eventForDB.Id, Role = atts.Role, Uri = atts.Value.ToString() }); } } #endregion #region Fill Comments /// <summary> /// Fill Comments /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillComments( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB) { if (eventFromDB.CalendarEventComments.Any()) foreach(var cmts in eventFromDB.CalendarEventComments) iCalEvent.Comments.Add(cmts.Comment); } /// <summary> /// /// </summary> /// <param name="iCalObject"></param> /// <param name="objectForDB"></param> /// <remarks>Changed by IagoSRL on 2013/05/08 to be generic, accepting any IUniqueComponent /// This allow using the method not only for Events, like originally, else for vfreebusy objects /// and others.</remarks> private void FillCommentsToDB(IUniqueComponent iCalObject, CalendarEvents eventForDB) { if (!iCalObject.Comments.Any()) return; foreach(var comment in iCalObject.Comments) eventForDB.CalendarEventComments.Add(new CalendarEventComments { Comment = comment, IdEvent = eventForDB.Id }); } #endregion #region Fill Recurrences /// <summary> /// Fill Recurrences /// </summary> /// <param name="iCalEvent"></param> /// <param name="eventFromDB"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private void FillRecurrences( Event iCalEvent, CalendarDll.Data.CalendarEvents eventFromDB) { var recur = eventFromDB.CalendarReccurrence; if (!recur.Any()) return; foreach (var rec in recur) { var recPattern = new RecurrencePattern(); recPattern.Frequency = (FrequencyType)rec.Frequency; if (rec.Count != null) recPattern.Count = (Int32)rec.Count; if (rec.Until != null) recPattern.Until = rec.Until.Value.UtcDateTime; if (rec.Interval != null) recPattern.Interval = (Int32)rec.Interval; SetFrequencies(rec, recPattern); iCalEvent.RecurrenceRules.Add(recPattern); } } private void FillRecurrencesToDB( Event iCalEvent, CalendarEvents eventforDB) { if (!iCalEvent.RecurrenceRules.Any()) return; foreach (var rec in iCalEvent.RecurrenceRules) { var newrec = new CalendarReccurrence { EventID = eventforDB.Id, Count = rec.Count, EvaluationMode = rec.EvaluationMode.ToString(), Frequency = Convert.ToInt32(rec.Frequency), Interval = rec.Interval, RestristionType = Convert.ToInt32(rec.RestrictionType), FirstDayOfWeek = Convert.ToInt32(rec.FirstDayOfWeek), }; if (rec.Until != null && rec.Until.Year > 1900) newrec.Until = rec.Until; SetFrequenciesToDB(rec, newrec); eventforDB.CalendarReccurrence.Add(newrec); } /*eventFromDB.CalendarReccurrence; if (!recur.Any()) return; foreach (var rec in recur) { var recPattern = new RecurrencePattern(); recPattern.Frequency = (FrequencyType)rec.Frequency; if (rec.Count != null) recPattern.Count = (Int32)rec.Count; if (rec.Until != null) recPattern.Until = (DateTime)rec.Until; if (rec.Interval != null) recPattern.Interval = (Int32)rec.Interval; SetFrecuencies(rec, recPattern); iCalEvent.RecurrenceRules.Add(recPattern); }*/ } #endregion #region Set Frecuencies - for Recurrences /// <summary> /// Set Frecuencies - for Recurrences /// </summary> /// <param name="rec"></param> /// <param name="recPattern"></param> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> private static void SetFrequenciesToDB(IRecurrencePattern rec, CalendarReccurrence newrec) { if (rec.ByDay.Any()) { foreach (var dy in rec.ByDay) { newrec.CalendarReccurrenceFrequency.Add(new CalendarReccurrenceFrequency() { ByDay = true, DayOfWeek = Convert.ToInt32(dy.DayOfWeek), FrequencyDay = dy.Offset, }); } } if (rec.ByWeekNo.Any()) { foreach (var wk in rec.ByWeekNo) { newrec.CalendarReccurrenceFrequency.Add(new CalendarReccurrenceFrequency() { ByWeekNo = true, ExtraValue = wk }); } } if (rec.ByMonth.Any()) { foreach (var mnt in rec.ByMonth) { newrec.CalendarReccurrenceFrequency.Add(new CalendarReccurrenceFrequency() { ByMonth = true, ExtraValue = mnt }); } } if (rec.ByYearDay.Any()) { foreach (var yr in rec.ByMonth) { newrec.CalendarReccurrenceFrequency.Add(new CalendarReccurrenceFrequency() { ByYearDay = true, ExtraValue = yr }); } } } private void SetFrequencies( CalendarDll.Data.CalendarReccurrence rec, RecurrencePattern recPattern) { var frec = rec.CalendarReccurrenceFrequency.ToList(); foreach (var fr in frec) { if (fr.ByDay ?? false) { //var frecDay = fr.FrequencyDay??-2147483648; // Bugfix: @IagoSRL: DayOfWeek > -1 instead of buggy '> 0', because // Sunday is value 0, and was discarted for recurrence because of this: if (fr.DayOfWeek != null && fr.DayOfWeek > -1) recPattern.ByDay.Add( new WeekDay((DayOfWeek)fr.DayOfWeek, (FrequencyOccurrence)(fr.FrequencyDay ?? -2147483648))); } else if (fr.ByHour ?? false) { recPattern.ByHour.Add(fr.ExtraValue ?? 0); } else if (fr.ByMinute ?? false) { recPattern.ByMinute.Add(fr.ExtraValue ?? 0); } else if (fr.ByMonth ?? false) { recPattern.ByMonth.Add(fr.ExtraValue ?? 0); } else if (fr.ByMonthDay ?? false) { recPattern.ByMonthDay.Add(fr.ExtraValue ?? 0); } else if (fr.BySecond ?? false) { recPattern.BySecond.Add(fr.ExtraValue ?? 0); } else if (fr.BySetPosition ?? false) { recPattern.BySetPosition.Add(fr.ExtraValue ?? 0); } else if (fr.ByWeekNo ?? false) { recPattern.ByWeekNo.Add(fr.ExtraValue ?? 0); } else if (fr.ByYearDay ?? false) { recPattern.ByYearDay.Add(fr.ExtraValue ?? 0); } } } #endregion #region Prepare Data for Export /// <summary> /// Prepare Data for Export /// </summary> /// <param name="user"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public Tuple<byte[], string> PrepareExportDataForUser( CalendarUser user) { Calendar iCalForExport = GetCalendarByUserForExport(user); var ctx = new SerializationContext(); var factory = new Ical.Net.Serialization.iCalendar.Factory.SerializerFactory(); // Get a serializer for our object var serializer = factory.Build( iCalForExport.GetType(), ctx) as IStringSerializer; var output = serializer.SerializeToString( iCalForExport); var contentType = "text/calendar"; var bytes = Encoding.UTF8.GetBytes(output); return new Tuple<byte[], string>( bytes, contentType); } #endregion #region Import Calendar public Srl.Timeline LastImportTimeline; /// <summary> /// This property allows limit (when greater than zero) the FreeBusy items /// to be imported by setting the limit in number of months of future items /// allowed. /// This allows avoid the overload of import excessive future items. /// In other words: don't import freebusy events from x months and greater in the future. /// IMPORTANT: Zero value has special meaning, being 'no limit' (all will get imported) /// </summary> public uint FutureMonthsLimitForImportingFreeBusy = 0; /// <summary> /// Import Calendar. /// /// STRATEGIES: /// When importing an iCalendar there are several precautions we need to take. /// /// 1: not import our exported events. /// Just in case the user sofware is reading our exported calendar and merging with /// user defined events, we need to prevent importing events originally generated by us /// (because we have them in database with a different types, to not duplicate, because /// we do not let arbitrary editions of that events -even we completely lock them depending /// on booking rules-, and at the same time we lock edition of imported events, since /// do not export them). /// Strategies to that: /// A- check the UID of the imported event and verify it's not at our database /// Costly operation, one read attempt for each record, usually with negative results /// B- check a pattern at the UID that we know is generated by us /// Quick. Still do not prevent that others use the same pattern, so we have false positives /// when filtering that events. /// -a check if starts with an asterisk (in use). /// Quick and dirty, too vague. Easy of false positives. /// ACTUALLY IN USE. TO REPLACE /// -b check if ends with @loconomics.com suffix /// Better approach, difficult of false positives (still positive, but if other follow /// good practices must not happen). /// /// TODO switch to strategy B-b. /// /// 2: insert/update/remove existing imported events /// After the first read, we need to maintain the already imported events, updating them if /// any change or removing them if no more exists at the source. /// /// Strategies: /// A- Keep list of imported identifiers. /// - Detect if an imported record (using UID) exists at DB: choose insert or update /// - When finishing importing, remove from database all user (@UserID) imported events (EventType=4) /// that do not exists at the list of imported identifiers (AND NOT IN (@list)) /// More memory consumption; depends on the number of events, can be a lot, to keep the list /// and for the large SQL to generate, or several calls to prevent some length limits. /// B- Delete records first. /// Idea: since we don't allow editions, we can safely start by removing previous imported /// records and then insert all others /// - Delete with: (DELETE CalendarEvents WHERE @UserID AND EventType=4) /// - Insert every record from import file. /// Quick (to implement and execute), more writes to database (all the removals, even unneded ones), /// database IDs increase quickly (ID is an auto-increment; risk to reach limit depending on how /// often importing is done). /// ACTUALLY IN USE. TO REPLACE /// C- Insert-update, then delete by UpdatedDate /// - Create variable with current date-time as the updatedDate timestamp. /// - Detect if an imported record (using UID) exists at DB: choose insert or update. Use the /// value of updatedDate or newer for the UpdatedDate field of each record. /// - Remove from database all the user (@UserID) imported events (EventType=4) with an /// UpdatedDate older than variable udpatedDate. /// Less memory than A, less writtings to database than B, IDs are kept for updated records. /// Needs analysis: could be slower than B because the check about if an event exists or not (to insert/update), /// but the non removal of records that then are re-created may be faster. /// /// TODO switch to strategy C /// </summary> /// <param name="calendar"></param> /// <param name="user"></param> /// <returns></returns> /// <remarks>2012/11 by CA2S FA, 2012/12/20 by CA2S RM dynamic version</remarks> public bool ImportCalendar(IICalendarCollection calendar, CalendarUser user) { //try { #if DEBUG if (LastImportTimeline == null) LastImportTimeline = new Srl.Timeline(); #endif //---------------------------------------------------------------------- // Loop that adds the Imported Events to a List of CalendarEvents // which are compatible in their fields with the Loconomics database //---------------------------------------------------------------------- using ( var db = new loconomicsEntities() ) { //---------------------------------------------------------------------- // Delete Previously Imported Events // // This was Iago Lorenzo Salgueiro's recommendation // as it simplifies dealing with Events created externally. // In particular, he was concerned when an Event was deleted // outside Loconomics (for example, Google Calendar) // // Note: EventType = 4 are the Imported Events // // 2013/01/15 CA2S RM //---------------------------------------------------------------------- #if DEBUG // PERF:: LastImportTimeline.SetTime("Deleting previous events: " + user.Id); #endif /** IMPORTANT:IagoSRL: Changed the deletion of user imported events from being done * through EntityFramework to be done with a manual SQL command **/ /* // read the Events for the Specified User and EventType==4 (Imported) var previouslyImportedEventsToDelete = db.CalendarEvents.Where(x => (x.UserId == user.Id) && (x.EventType == 4)); // Mark the Events as Deleted foreach (var eventToDelete in previouslyImportedEventsToDelete) { db.CalendarEvents.Remove(eventToDelete); } // Send the Changes (Deletes) to the Database db.SaveChanges(); */ db.Database.ExecuteSqlCommand("DELETE FROM CalendarEvents WHERE UserID={0} AND EventType={1}", user.Id, 4); #if DEBUG // PERF:: LastImportTimeline.StopTime("Deleting previous events: " + user.Id); // PERF:: LastImportTimeline.SetTime("Importing Calendars: " + user.Id); #endif // Loop for every calendar in the imported file (it must be only one really) foreach (var currentCalendar in calendar) { //---------------------------------------------------------------------- // Loop to Import the Events //---------------------------------------------------------------------- #if DEBUG // PERF:: LastImportTimeline.SetTime("Importing:: events: " + user.Id); #endif foreach (Event currEvent in currentCalendar.Events.Where(evs => !evs.Uid.StartsWith("*"))) { // Event Types // (See table: CalendarEventType) // // 1 booking - GENERATES BETWEEN TIME // 2 work hours // 3 availibility events // 4 imported <-- As we are currently Importing, we will use this Type // 5 other //---------------------------------------------------------------------- // See if an Event with the same UID already Exists in the DB // If it Exists, don't import, or there will be duplicates //---------------------------------------------------------------------- //bool eventAlreadyExists=false; //---------------------------------------------------------------------- //// Delete old event //// This won't be necessary anymore, //// as the Imported Events are deleted beforehand now //// 2013/01/15 CA2S RM //---------------------------------------------------------------------- //var eventExist = db.CalendarEvents.FirstOrDefault( // ev => ev.UID == currEvent.UID); //if (eventExist != null) //{ // db.CalendarEvents.Remove(eventExist); // // db.SaveChanges(); //} //---------------------------------------------------------------------- // TZ This may not be needed, or done in a different way, to support Time Zones properly //// Convert the whole event to our System Time Zone before being inserted. //UpdateEventDatesToSystemTimeZone(currEvent); var startTime = DateTimeOffsetFromCalDateTime(currEvent.Start); // Calculate the end date basing in the real End date set or the Start date // plus the event Duration. For case of error (no dates) gets as default // the minimum date (and will be discarded) var calculatedEndDate = currEvent.End != null && currEvent.End.HasDate ? DateTimeOffsetFromCalDateTime(currEvent.End) : startTime.Add(currEvent.Duration); // Check if this is a past event that doesn't need to be imported (only non recurrent ones) if (calculatedEndDate < DateTime.Now && currEvent.RecurrenceDates.Count == 0 && currEvent.RecurrenceRules.Count == 0) { // Old event, discarded, continue with next: continue; } // Create event var eventForDB = new CalendarEvents() { CreatedDate = DateTimeOffset.Now, UID = currEvent.Uid, UserId = user.Id, StartTime = startTime, // IagoSRL @Loconomics: Added TimeZone based on the StartTime TZID (we suppose endtime use the same, is the most common, // and our back-end calendar doesn't support one timezone per start-end date) TimeZone = currEvent.Start.TzId, EndTime = calculatedEndDate, Organizer = (currEvent.Organizer != null) ? currEvent.Organizer.CommonName : string.Empty, CalendarAvailabilityTypeID = getAvailabilityId(currEvent), Transparency = getTransparency((int)currEvent.Status), Summary = currEvent.Summary, EventType = 4, // 4 = Imported IsAllDay = false }; FillExceptionsDatesToDB(currEvent, eventForDB); FillRecurrencesDatesToDB(currEvent, eventForDB); FillContactsToDB(currEvent, eventForDB); FillAttendeesToDB(currEvent, eventForDB); FillCommentsToDB(currEvent, eventForDB); FillRecurrencesToDB(currEvent, eventForDB); // Add to the DB db.CalendarEvents.Add(eventForDB); } // foreach (Event currEvent in... #if DEBUG // PERF:: LastImportTimeline.StopTime("Importing:: events: " + user.Id); #endif // By IagoSRL @Loconomics: // To support Public Calendars, that mainly provide VFREEBUSY (and most of times only that kind of elements), // we need import too the VFREEBUSY blocks, and we will create a single and simple event for each of that, // with automatic name/summary and the given availability: // Calculate the future date limit to avoid recalculate on every item var futureDateLimit = DateTime.Now.AddMonths((int)FutureMonthsLimitForImportingFreeBusy); #if DEBUG // PERF:: LastImportTimeline.SetTime("Importing:: freebusy: " + user.Id); #endif foreach (var fb in currentCalendar.FreeBusy.Where(fb => !fb.Uid.StartsWith("*"))) { //// Convert the whole freebusy to our System Time Zone before being inserted //// (it updates too all the freebusy.entries) //UpdateFreeBusyDatesToSystemTimeZone(fb); // If the FreeBusy block contains Entries, one event must be created for each entry if (fb.Entries != null && fb.Entries.Count > 0) { int ientry = 0; foreach (var fbentry in fb.Entries) { ientry++; var startTime = DateTimeOffsetFromCalDateTime(fbentry.StartTime); // Calculate the end date basing in the real End date set or the Start date // plus the entry Duration. For case of error (no dates) gets as default // the minimum date (and will be discarded) var calculatedEndDate = fbentry.EndTime.HasDate ? DateTimeOffsetFromCalDateTime(fbentry.EndTime) : startTime.Add(fbentry.Duration); // Check if this is a past entry that doesn't need to be imported if (calculatedEndDate < DateTime.Now) { // Old, discarded, continue with next: continue; } // Check if there is a limit and is exceeded if (FutureMonthsLimitForImportingFreeBusy > 0 && calculatedEndDate > futureDateLimit) { // Exceed the 'future' limit, discard: continue; } var availID = getAvailabilityId(fbentry); var dbevent = new CalendarEvents() { CreatedDate = DateTimeOffset.Now, UpdatedDate = DateTimeOffset.Now, ModifyBy = "importer", UID = fb.Uid + "_freebusyentry:" + ientry.ToString(), UserId = user.Id, StartTime = startTime, TimeZone = fbentry.StartTime.TzId, EndTime = calculatedEndDate, Organizer = (fb.Organizer != null) ? fb.Organizer.CommonName : string.Empty, CalendarAvailabilityTypeID = (int)availID, Transparency = false, Summary = (fb.Properties["SUMMARY"] != null ? fb.Properties["SUMMARY"].Value : availID).ToString(), EventType = 4, // 4 = Imported IsAllDay = false }; // Linked records FillCommentsToDB(fb, dbevent); FillAttendeesToDB(fb, dbevent); // Add to database db.CalendarEvents.Add(dbevent); } } // If there is no entries, the event is created for the vfreebusy dtstart-dtend dates: else { // Calculate the end date basing in the real End date set or the Start date. // For case of error (no dates) gets as default // the minimum date (and will be discarded) var calculatedEndDate = fb.DtEnd.HasDate ? fb.DtEnd.Value : fb.DtStart.HasDate ? fb.DtStart.Value : DateTime.MinValue; // Check if this is a past entry that doesn't need to be imported if (calculatedEndDate < DateTime.Now) { // Old, discarded, continue with next: continue; } // Check if there is a limit and is exceeded if (FutureMonthsLimitForImportingFreeBusy > 0 && calculatedEndDate > futureDateLimit) { // Exceed the 'future' limit, discard: continue; } // The availability for a VFREEBUSY is ever 'Busy', because the object doesn't // allow set the availability/status information, it goes inside freebusy-entries when // there are some. var availID = AvailabilityTypes.BUSY; var dbevent = new CalendarEvents() { CreatedDate = DateTimeOffset.Now, UpdatedDate = DateTimeOffset.Now, ModifyBy = "importer", UID = fb.Uid, UserId = user.Id, StartTime = fb.DtStart.Value, TimeZone = fb.DtStart.TzId, EndTime = calculatedEndDate, //fb.DTEnd.Value, Organizer = (fb.Organizer != null) ? fb.Organizer.CommonName : string.Empty, CalendarAvailabilityTypeID = (int)availID, Transparency = false, Summary = (fb.Properties["SUMMARY"] != null ? fb.Properties["SUMMARY"].Value : availID).ToString(), EventType = 4, // 4 = Imported IsAllDay = false }; // Linked records FillCommentsToDB(fb, dbevent); FillAttendeesToDB(fb, dbevent); // Add to database db.CalendarEvents.Add(dbevent); } } #if DEBUG // PERF:: LastImportTimeline.StopTime("Importing:: freebusy: " + user.Id); #endif } // Ends foreach calendar //---------------------------------------------------------------------- // Saves the Events to the Database //---------------------------------------------------------------------- #if DEBUG // PERF:: LastImportTimeline.SetTime("Importing:: saving to db: " + user.Id); #endif db.SaveChanges(); #if DEBUG // PERF:: LastImportTimeline.StopTime("Importing:: saving to db: " + user.Id); // PERF:: LastImportTimeline.StopTime("Importing Calendars: " + user.Id); #endif } // using ( var db = new CalendarDll.Data.loconomicsEntities() ) //---------------------------------------------------------------------- // Reports Import was successful //---------------------------------------------------------------------- return true; } //catch (Exception ex) //{ // return false; //} } /* /// <summary> /// Modify the passed @anEvent updating its date-time fields from its /// original time zone to the current system time zone (we are using California /// TimeZone in our server and database data). /// It updates every elements collection inside it (ExceptionDates, RecurrenceDates) /// /// IagoSRL @Loconomics /// </summary> /// <param name="anEvent"></param> public void UpdateEventDatesToSystemTimeZone(IEvent anEvent) { // IMPORTANT:IagoSRL@2015-12-10: Assigning new values is being problematic, since there are some // underlying calculations that overwrite the assigned values. // Discovered while in issue #851, where any value assigned to End/DTEnd gets discarded and // a new one, that has the original value and UTC mark, is put in place, resulting in no-change and // the bug commented on that issue. // After testing, it seems only affects to property End/DTEnd, but applying to both Start and End to ensure no more side-effects, // with exceptions: check for null values and use assignement to force some internal calculations but still do a manual calculation with Duration // (covering lot of cases; paranoid?) // EXAMPLE TO BE CLEAR, doing next is BUGGY // anEvent.End = UpdateDateToSystemTimeZone(anEvent.End); // GETS FIXED USING NEXT // anEvent.End.CopyFrom(UpdateDateToSystemTimeZone(anEvent.End)); //new CalDateTime(datetime.AsUtc, "UTC"); //var start = UpdateDateToSystemTimeZone(anEvent.Start); //var end = UpdateDateToSystemTimeZone(anEvent.End); /*if (start != null && end != null) { anEvent.Start.CopyFrom(start); anEvent.End.CopyFrom(end); } else if (start != null) // end is null { anEvent.Start = start; anEvent.End = start.Add(anEvent.Duration); } else // start is null (unique possibility here) { anEvent.End = end; anEvent.Start = end.Subtract(anEvent.Duration); }* / anEvent.DtStamp = UpdateDateToSystemTimeZone(anEvent.DtStamp); anEvent.Created = UpdateDateToSystemTimeZone(anEvent.Created); anEvent.LastModified = UpdateDateToSystemTimeZone(anEvent.LastModified); //anEvent.RecurrenceId = UpdateDateToSystemTimeZone(anEvent.RecurrenceId); foreach (var exDate in anEvent.ExceptionDates) { foreach (var d in exDate) { d.StartTime = UpdateDateToSystemTimeZone(d.StartTime); d.EndTime = UpdateDateToSystemTimeZone(d.EndTime); } } //foreach (var exRule in anEvent.ExceptionRules) //{ // NOTHING to update //} foreach (var reDate in anEvent.RecurrenceDates) { foreach (var d in reDate) { d.EndTime = UpdateDateToSystemTimeZone(d.EndTime); d.StartTime = UpdateDateToSystemTimeZone(d.StartTime); } } //foreach (var reRule in anEvent.RecurrenceRules) //{ // NOTHING to update //} }*/ /* /// <summary> /// Modify the passed @freebusy updating its date-time fields from its /// original time zone to the current system time zone (we are using California /// TimeZone in our server and database data). /// It updates every elements collection inside it (freebusyentries) /// /// IagoSRL @Loconomics /// </summary> /// <param name="freebusy"></param> public void UpdateFreeBusyDatesToSystemTimeZone(IFreeBusy freebusy) { // IFreeBusy.Start is an alias for DTStart. //freebusy.Start = UpdateDateToSystemTimeZone(freebusy.Start); // IFreeBusy.End is an alias for DTEnd. //freebusy.End = UpdateDateToSystemTimeZone(freebusy.End); freebusy.DtStamp = UpdateDateToSystemTimeZone(freebusy.DtStamp); // Update all its entries foreach (var freebusyentry in freebusy.Entries) { freebusyentry.EndTime = UpdateDateToSystemTimeZone(freebusyentry.EndTime); freebusyentry.StartTime = UpdateDateToSystemTimeZone(freebusyentry.StartTime); } }*/ /* /// <summary> /// Returns an updated datetime object converting the given one /// to the system time zone (we are using California TimeZone in our /// server and database data). /// /// IagoSRL @Loconomics /// /// IMPORTANT: only needed for fields that in database are saved as DateTime /// but not as DateTimeOffset /// </summary> /// <param name="datetime"></param> /// <returns></returns> public IDateTime UpdateDateToSystemTimeZone(IDateTime datetime) { if (datetime == null) return null; // We use a combination of DDay conversion and .Net conversion. // The DDay method IDateTime.Local is 'supposed' to do just what we // want, BUT FAILS (tested a log, is buggy). // But, its IDateTime.UTC works fine, it detects properly the // TimeZone of the imported DateTime and converts fine to UTC. // After that, we use the .Net conversion to local time (server time, // we use server at California, what we wants, then all goes fine :-). return new CalDateTime(datetime.AsUtc.ToLocalTime()); // And done! (fiuu... some debug, tests and notes following, it was // time spending because DDay buggy 'Local', but ended simple and working). /* DEBUGING, testing buggy 'Local' and looking for correct way: System.IO.File.AppendAllText(@"E:\web\loconomi\beta\_logs\calendardll.log", String.Format( "{3:s}Z:: UpdateDateToSystemTimeZone {4} A Source {0} ; Converted to Local: {1} ; Converted to UTC: {2} \n", datetime, datetime.Value.ToLocalTime(), datetime.Value.ToUniversalTime(), DateTime.Now.ToUniversalTime(), TimeZoneInfo.Local.Id )); //datetime.IsUniversalTime = true; System.IO.File.AppendAllText(@"E:\web\loconomi\beta\_logs\calendardll.log", String.Format( "{3:s}Z:: UpdateDateToSystemTimeZone {4} B Source {0} ; Converted to Local: {1} ; Converted to icalLocal: {2} \n", datetime, datetime.Local, datetime.UTC, datetime.Local.ToLocalTime(), DateTime.Now )); * / /* Alternative guide-lines for conversion: //var timeZone = datetime.Calendar.GetTimeZone(datetime.TZID); // Find what TimeZoneInfo we must use: // -- //timeZone.TimeZoneInfos[0] // Convert from object TimeZoneInfo to the system TimeZone // -- // Returns the updated datetime //return datetime; * / }*/ #endregion } }
42.132265
215
0.481012
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
joshdanielson/loconomics
iCalendarLib/CalendarDll/CalendarUtils.cs
105,120
C#
using System; using System.Collections.Generic; using AerisWeather.Net.Clients; using AerisWeather.Net.Models.Exceptions; using AerisWeather.Net.Models.Responses; using Moq; namespace AerisWeather.Net.Tests.Unit.SunMoonUnitTests { public class BaseSunMoonUnitTests : BaseTest { public ISunMoon sunMoon; public BaseSunMoonUnitTests() : base() { this.sunMoon = new SunMoon(this.mockAerisClient.Object); } public void HappySetUp() { var x = new List<SunMoonResponse>(); x.Add(new SunMoonResponse() { Sun = new Models.BaseModels.Sun() { }, Moon = new Models.BaseModels.Moon() { } }); this.mockAerisClient.Setup(moq => moq.Request<List<SunMoonResponse>>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>())) .ReturnsAsync(x); } public override void MockResponseIsEmptyList() { var x = new List<SunMoonResponse>(); this.mockAerisClient.Setup(moq => moq.Request<List<SunMoonResponse>>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>())) .ReturnsAsync(x); } public override void MockResponseIsNull() { List<SunMoonResponse> x = null; this.mockAerisClient.Setup(moq => moq.Request<List<SunMoonResponse>>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>())) .ReturnsAsync(x); } public void LocationNotFoundSetUp() { this.mockAerisClient.Setup(moq => moq.Request<List<SunMoonResponse>>(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>())) .ThrowsAsync(new LocationNotFoundException("test")); } } }
30.35
141
0.594728
[ "MIT" ]
EasyIntegration/AerisWeather.Net
AerisWeather.Net.Tests.Unit/SunMoonUnitTests/BaseSunMoonUnitTests.cs
1,823
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace ContosoUniversity.Contracts { public class PaginatedList<T> : List<T> { public int PageIndex { get; } public int TotalPages { get; } public PaginatedList(List<T> items, int count, int pageIndex, int pageSize) { PageIndex = pageIndex; TotalPages = (int)Math.Ceiling(count / (double)pageSize); this.AddRange(items); } public bool HasPreviousPage => PageIndex > 1; public bool HasNextPage => PageIndex < TotalPages; public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize) { var count = await source.CountAsync().ConfigureAwait(false); var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync().ConfigureAwait(false); return new PaginatedList<T>(items, count, pageIndex, pageSize); } } }
32.606061
121
0.651487
[ "Apache-2.0" ]
savanna-projects/test-application-mvc
src/csharp/ContosoUniversity/ContosoUniversity/Contracts/PaginatedList.cs
1,078
C#
 using HelpMyStreet.Utils.Enums; using HelpMyStreet.Utils.Models; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Newtonsoft.Json; using RequestService.Repo.EntityFramework.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Question = RequestService.Repo.EntityFramework.Entities.Question; using SupportActivities = HelpMyStreet.Utils.Enums.SupportActivities; namespace RequestService.Repo.Helpers { public static class QuestionExtenstions { public static void SetQuestionData(this EntityTypeBuilder<Question> entity) { entity.HasData(new Question { Id = (int)Questions.SupportRequesting, Name = "Please tell us more about the help or support you're requesting", QuestionType = (int)QuestionType.MultiLineText, AdditionalData = GetAdditionalData(Questions.SupportRequesting), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.FaceMask_SpecificRequirements, Name = "Please tell us about any specific requirements (e.g. size, colour, style etc.)", QuestionType = (int)QuestionType.MultiLineText, AdditionalData = GetAdditionalData(Questions.FaceMask_SpecificRequirements), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.FaceMask_Amount, Name = "How many face coverings do you need?", QuestionType = (int)QuestionType.Number, AdditionalData = GetAdditionalData(Questions.FaceMask_Amount), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.FaceMask_Recipient, Name = "Who will be using the face coverings?", QuestionType = (int)QuestionType.Radio, AdditionalData = GetAdditionalData(Questions.FaceMask_Recipient), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.FaceMask_Cost, Name = "Are you able to pay the cost of materials for your face covering (usually £2 - £3 each)?", QuestionType = (int)QuestionType.Radio, AdditionalData = GetAdditionalData(Questions.FaceMask_Cost), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.IsHealthCritical, Name = "Is this request critical to someone's health or wellbeing?", QuestionType = (int)QuestionType.Radio, AdditionalData = GetAdditionalData(Questions.IsHealthCritical), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.WillYouCompleteYourself, Name = "Will you complete this request yourself?", QuestionType = (int)QuestionType.Radio, AdditionalData = GetAdditionalData(Questions.WillYouCompleteYourself), AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.FtlosDonationInformation, Name = "Please donate to the For the Love of Scrubs GoFundMe <a href=\"https://www.gofundme.com/f/for-the-love-of-scrubs-face-coverings\" target=\"_blank\">here</a> to help pay for materials and to help us continue our good work. Recommended donation £3 - £4 per face covering.", QuestionType = (int)QuestionType.LabelOnly, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.CommunicationNeeds, Name = "Are there any communication needs that volunteers need to know about before they contact you or the person who needs help?", QuestionType = (int)QuestionType.MultiLineText, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.AnythingElseToTellUs, Name = "Is there anything else you would like to tell us about the request?", QuestionType = (int)QuestionType.MultiLineText, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.AgeUKReference, Name = "AgeUK Reference", QuestionType = (int)QuestionType.Text, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int) Questions.Shopping_List, Name = "Please tell us what you need from the shop", QuestionType = (int) QuestionType.MultiLineText, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.Prescription_PharmacyAddress, Name = "Where does the prescription need collecting from?", QuestionType = (int)QuestionType.Text, AdditionalData = string.Empty, AnswerContainsSensitiveData = false }); entity.HasData(new Question { Id = (int)Questions.SensitiveInformation, Name = "Is there any other personal or sensitive information the volunteer needs to know to complete the request?", QuestionType = (int)QuestionType.MultiLineText, AdditionalData = string.Empty, AnswerContainsSensitiveData = true }); } private static string GetAdditionalData(Questions question) { List<AdditonalQuestionData> additionalData = new List<AdditonalQuestionData>(); switch (question) { case Questions.FaceMask_Recipient: additionalData = new List<AdditonalQuestionData> { new AdditonalQuestionData { Key = "keyworkers", Value = "Key workers" }, new AdditonalQuestionData { Key = "somonekeyworkers", Value = "Someone helping key workers stay safe in their role (e.g. care home residents, visitors etc.)" }, new AdditonalQuestionData { Key = "memberspublic", Value = "Members of the public" }, }; break; case Questions.FaceMask_Cost: additionalData = new List<AdditonalQuestionData> { new AdditonalQuestionData { Key = "Yes", Value = "Yes" }, new AdditonalQuestionData { Key = "No", Value = "No" }, new AdditonalQuestionData { Key = "Contribution", Value = "I can make a contribution" }, }; break; case Questions.IsHealthCritical: additionalData = new List<AdditonalQuestionData> { new AdditonalQuestionData { Key = "true", Value = "Yes" }, new AdditonalQuestionData { Key = "false", Value = "No" } }; break; case Questions.WillYouCompleteYourself: additionalData = new List<AdditonalQuestionData> { new AdditonalQuestionData { Key = "true", Value = "Yes" }, new AdditonalQuestionData { Key = "false", Value = "No, please make it visible to other volunteers" } }; break; } return JsonConvert.SerializeObject(additionalData); } public static void SetActivityQuestionData(this EntityTypeBuilder<ActivityQuestions> entity) { var requestFormVariants = Enum.GetValues(typeof(RequestHelpFormVariant)).Cast<RequestHelpFormVariant>(); string subText_anythingElse = "This information will be visible to volunteers deciding whether to accept the request"; foreach (var form in requestFormVariants) { foreach (var activity in GetSupportActivitiesForRequestFormVariant(form)) { if (activity == SupportActivities.FaceMask) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.FaceMask_SpecificRequirements, Location = "pos2", Order = 2, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "Don’t forget to tell us how many of each size you need. If you have very specific style requirements it may take longer to find a volunteer to help with your request. Please don’t include personal information such as name or address in this box, we’ll ask for that later.", Subtext = "Size guide:<br />&nbsp;- Men’s (Small / Medium / Large)<br />&nbsp;- Ladies’ (Small / Medium / Large)<br />&nbsp;- Children’s (One Size - under 12)" }); entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.FaceMask_Amount, Location = "pos3", Order = 1, RequestFormVariantId = (int)form, Required = true, Subtext = "Remember they’re washable and reusable, so only request what you need between washes." }); entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.FaceMask_Recipient, Location = "pos3", Order = 3, RequestFormVariantId = (int)form, Required = false }); if (form != RequestHelpFormVariant.FtLOS) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.FaceMask_Cost, Location = "pos3", Order = 4, RequestFormVariantId = (int)form, Required = false, Subtext = "Volunteers are providing their time and skills free of charge." }); } else { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.FtlosDonationInformation, Location = "pos3", Order = 4, RequestFormVariantId = (int)form, Required = false }); } } else if (activity == SupportActivities.ColdWeatherArmy) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.SupportRequesting, Location = "pos1", Order = 1, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "Please be aware that information in this section is visible to prospective volunteers" }); entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Detail, QuestionId = (int)Questions.AnythingElseToTellUs, Location = "details2", Order = 2, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "For example, any special instructions for the volunteer.", Subtext = subText_anythingElse }); } else if (activity == SupportActivities.Shopping) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.Shopping_List, Location = "pos1", Order = 1, RequestFormVariantId = (int)form, Required = true, PlaceholderText = "For example, Hovis wholemeal bread, 2 pints semi-skimmed milk, 6 large eggs.", Subtext = "Make sure to include the size, brand, and any other important details" }); string anythingElseToTellUs_placeholderText = form switch { RequestHelpFormVariant.Ruddington => "For example, let us know if you’re struggling to find help elsewhere.", _ => "For example, any mobility or communication needs, or special instructions for the volunteer. Please don’t include any personal or sensitive information in this box." }; entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Detail, QuestionId = (int)Questions.AnythingElseToTellUs, Location = "details2", Order = 2, RequestFormVariantId = (int)form, Required = false, PlaceholderText = anythingElseToTellUs_placeholderText, Subtext= subText_anythingElse }); } else if (activity == SupportActivities.CollectingPrescriptions) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.Prescription_PharmacyAddress, Location = "pos1", Order = 1, RequestFormVariantId = (int)form, Required = true, PlaceholderText = "Please give the name and address of the pharmacy, e.g. Boots Pharmacy, Victoria Centre, Nottingham." }); entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Detail, QuestionId = (int)Questions.AnythingElseToTellUs, Location = "details2", Order = 2, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "For example, let us know if the prescription needs to be paid for, or if there are any mobility or communication needs or special instructions for the volunteer. Please don’t include any personal or sensitive information in this box.", Subtext = subText_anythingElse }); } else { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.SupportRequesting, Location = "pos1", Order = 1, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "Please don’t include any sensitive details that aren’t needed in order for us to help you" }); string anythingElseToTellUs_placeholderText = form switch { RequestHelpFormVariant.HLP_CommunityConnector => "Is there a specific issue you would like to discuss with the Community Connector, e.g. dealing with a bereavement (please don’t include personal details here)", RequestHelpFormVariant.Ruddington => "For example, let us know if you’re struggling to find help elsewhere.", _ => "For example, any special instructions for the volunteer." }; entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Detail, QuestionId = (int)Questions.AnythingElseToTellUs, Location = "details2", Order = 2, RequestFormVariantId = (int)form, Required = false, PlaceholderText = anythingElseToTellUs_placeholderText, Subtext = subText_anythingElse }); } if (form == RequestHelpFormVariant.VitalsForVeterans) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.AgeUKReference, Location = "pos1", Order = 2, RequestFormVariantId = (int)form, Required = false }); } if (form != RequestHelpFormVariant.HLP_CommunityConnector && form != RequestHelpFormVariant.Ruddington && form != RequestHelpFormVariant.AgeUKWirral && form != RequestHelpFormVariant.VitalsForVeterans && activity != SupportActivities.FaceMask) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.IsHealthCritical, Location = "pos3", Order = 2, RequestFormVariantId = (int)form, Required = true }); } if (form == RequestHelpFormVariant.DIY) { entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Request, QuestionId = (int)Questions.WillYouCompleteYourself, Location = "pos3", Order = 3, RequestFormVariantId = (int)form, Required = true }); } entity.HasData(new ActivityQuestions { ActivityId = (int)activity, RequestFormStageId = (int)RequestHelpFormStage.Detail, QuestionId = (int)Questions.SensitiveInformation, Location = "details2", Order = 3, RequestFormVariantId = (int)form, Required = false, PlaceholderText = "For example, a door entry code, or contact details for a friend / relative / caregiver.", Subtext = "We will only share this information with a volunteer after they have accepted your request" }); } } } private static IEnumerable<SupportActivities> GetSupportActivitiesForRequestFormVariant(RequestHelpFormVariant form) { IEnumerable<SupportActivities> activites; IEnumerable<SupportActivities> genericSupportActivities = Enum.GetValues(typeof(SupportActivities)).Cast<SupportActivities>() .Where(sa => sa != SupportActivities.WellbeingPackage && sa != SupportActivities.CommunityConnector && sa != SupportActivities.ColdWeatherArmy && sa != SupportActivities.Transport); switch (form) { case RequestHelpFormVariant.FtLOS: activites = new List<SupportActivities>() { SupportActivities.FaceMask }; break; case RequestHelpFormVariant.HLP_CommunityConnector: activites = new List<SupportActivities>() { SupportActivities.CommunityConnector }; break; case RequestHelpFormVariant.VitalsForVeterans: activites = new List<SupportActivities>(genericSupportActivities); ((List<SupportActivities>)activites).Add(SupportActivities.WellbeingPackage); break; case RequestHelpFormVariant.Ruddington: activites = new List<SupportActivities>(genericSupportActivities); ((List<SupportActivities>)activites).Remove(SupportActivities.HomeworkSupport); break; case RequestHelpFormVariant.AgeUKWirral: activites = new List<SupportActivities>() { SupportActivities.Shopping, SupportActivities.CollectingPrescriptions, SupportActivities.Other }; ((List<SupportActivities>)activites).Add(SupportActivities.Transport); ((List<SupportActivities>)activites).Add(SupportActivities.ColdWeatherArmy); break; case RequestHelpFormVariant.AgeUKNottsBalderton: activites = new List<SupportActivities>() { SupportActivities.Shopping, SupportActivities.CollectingPrescriptions, SupportActivities.PhoneCalls_Friendly, SupportActivities.Other }; break; default: activites = genericSupportActivities; break; }; return activites; } } }
59.162304
744
0.564027
[ "MIT" ]
Magicianred/request-service
RequestService/RequestService.Repo/Helpers/QuestionExtenstions.cs
22,634
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.open.public.content.cancel /// </summary> public class AlipayOpenPublicContentCancelRequest : IAlipayRequest<AlipayOpenPublicContentCancelResponse> { /// <summary> /// 生活号素材内容撤回接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.open.public.content.cancel"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.521739
109
0.539125
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayOpenPublicContentCancelRequest.cs
3,270
C#
using System.Linq; using NUnit.Framework; using UniTool.Editor; namespace UniTool.Tests.EditMode { public class UnityPackageExporterTest { [Test] public void ExportTest() { UnityPackageExporter.Export(); } [Test] public void GetExportPathTest() { var exportPath = UnityPackageExporter.GetExportPath(); Assert.AreEqual("Dist/UniTool.unitypackage", exportPath); } [Test] public void GetAssetsTest() { var assets = UnityPackageExporter.GetAssets(); Assert.True(assets.Any(it => it.Equals("Assets/UniTool/EngineEx.meta"))); Assert.True(assets.Any(it => it.Equals("Assets/UniTool/Event.meta"))); Assert.True(assets.Any(it => it.Equals("Assets/UniTool/ObjectEx.meta"))); Assert.True(assets.Any(it => it.Equals("Assets/UniTool/X.meta"))); } [Test] public void ExportPackageTest() { var path = UnityPackageExporter.ExportPackage("Temp/test", new[]{ "Assets/UniTool.Sample/UnitoolSampleScene.unity" }); Assert.False(path.Equals("")); } [Test] public void ExportVersionTest() { var path = UnityPackageExporter.ExportVersion("Temp/test"); Assert.False(path.Equals("")); } } }
30.255319
130
0.566807
[ "MIT" ]
TakenokoTech/UniTool
Assets/UniTool.Tests/EditMode/UnityPackageExporterTest.cs
1,422
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AbsoluteDifferenceWideningLower_Vector64_SByte() { var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<SByte> _fld1; public Vector64<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector64<SByte> _clsVar1; private static Vector64<SByte> _clsVar2; private Vector64<SByte> _fld1; private Vector64<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AbsoluteDifferenceWideningLower( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AbsoluteDifferenceWideningLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AbsoluteDifferenceWideningLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); var result = AdvSimd.AbsoluteDifferenceWideningLower(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AbsoluteDifferenceWideningLower(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AbsoluteDifferenceWidening(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsoluteDifferenceWideningLower)}<UInt16>(Vector64<SByte>, Vector64<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
43.030132
189
0.594074
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/AbsoluteDifferenceWideningLower.Vector64.SByte.cs
22,849
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; //using Mediwatch.Shared.Models; /*public class FormationTemplate { [Required] public string Name { get; set; } [Required] public DateTime StartDate { get; set; } = DateTime.Today; [Required] public DateTime EndDate { get; set; } = DateTime.Today; [Required] public string Location { get; set; } [Required] public string Contact { get; set; } [Required] public string OrganizationName { get; set; } [Required] public decimal Price { get; set; } [Required] public string Former { get; set; } [Required] public string Description { get; set; } [Required] public List<string> Target { get; set; } public bool IsRegistered { get; set; } public FormationTemplate() {} public FormationTemplate(FormationTemplateTab1 tab1, FormationTemplateTab2 tab2, FormationTemplateTab3 tab3) { Name = tab1.Name; StartDate = tab1.StartDate; EndDate = tab1.EndDate; Description = tab1.Description; OrganizationName = tab2.OrganizationName; Price = tab2.Price; Former = tab2.Former; Location = tab3.Location; Contact = tab3.Contact; } } */ public class FormationTemplateTab1 { [Required] public string Name { get; set; } [Required] public DateTime StartDate { get; set; } = DateTime.Today; [Required] public DateTime EndDate { get; set; } = DateTime.Today; [Required] public string Description { get; set; } } public class FormationTemplateTab2 { [Required] public string OrganizationName { get; set; } [Required] public decimal Price { get; set; } [Required] public string Former { get; set; } } public class FormationTemplateTab3 { [Required] public string Location { get; set; } [Required] [Phone] public string Contact { get; set; } }
19.290323
111
0.712375
[ "CC0-1.0" ]
Mediwatch/BlazyWatch
Client/Pages/_FormationTemplate.cs
1,794
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.Traces.ConeLib { /// <summary> /// The HoverLabel class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [JsonConverter(typeof(PlotlyConverter))] [Serializable] public class HoverLabel : IEquatable<HoverLabel> { /// <summary> /// Sets the background color of the hover labels for this trace /// </summary> [JsonPropertyName(@"bgcolor")] public object BgColor { get; set;} /// <summary> /// Sets the background color of the hover labels for this trace /// </summary> [JsonPropertyName(@"bgcolor")] [Array] public IList<object> BgColorArray { get; set;} /// <summary> /// Sets the border color of the hover labels for this trace. /// </summary> [JsonPropertyName(@"bordercolor")] public object BorderColor { get; set;} /// <summary> /// Sets the border color of the hover labels for this trace. /// </summary> [JsonPropertyName(@"bordercolor")] [Array] public IList<object> BorderColorArray { get; set;} /// <summary> /// Sets the font used in hover labels. /// </summary> [JsonPropertyName(@"font")] public Plotly.Blazor.Traces.ConeLib.HoverLabelLib.Font Font { get; set;} /// <summary> /// Sets the horizontal alignment of the text content within hover label box. /// Has an effect only if the hover label text spans more two or more lines /// </summary> [JsonPropertyName(@"align")] public Plotly.Blazor.Traces.ConeLib.HoverLabelLib.AlignEnum? Align { get; set;} /// <summary> /// Sets the horizontal alignment of the text content within hover label box. /// Has an effect only if the hover label text spans more two or more lines /// </summary> [JsonPropertyName(@"align")] [Array] public IList<Plotly.Blazor.Traces.ConeLib.HoverLabelLib.AlignEnum?> AlignArray { get; set;} /// <summary> /// Sets the default length (in number of characters) of the trace name in the /// hover labels for all traces. -1 shows the whole name regardless of length. /// 0-3 shows the first 0-3 characters, and an integer &gt;3 will show the whole /// name if it is less than that many characters, but if it is longer, will /// truncate to &#39;namelength - 3&#39; characters and add an ellipsis. /// </summary> [JsonPropertyName(@"namelength")] public int? NameLength { get; set;} /// <summary> /// Sets the default length (in number of characters) of the trace name in the /// hover labels for all traces. -1 shows the whole name regardless of length. /// 0-3 shows the first 0-3 characters, and an integer &gt;3 will show the whole /// name if it is less than that many characters, but if it is longer, will /// truncate to &#39;namelength - 3&#39; characters and add an ellipsis. /// </summary> [JsonPropertyName(@"namelength")] [Array] public IList<int?> NameLengthArray { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for bgcolor . /// </summary> [JsonPropertyName(@"bgcolorsrc")] public string BgColorSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for bordercolor . /// </summary> [JsonPropertyName(@"bordercolorsrc")] public string BorderColorSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for align . /// </summary> [JsonPropertyName(@"alignsrc")] public string AlignSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for namelength . /// </summary> [JsonPropertyName(@"namelengthsrc")] public string NameLengthSrc { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is HoverLabel other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] HoverLabel other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( BgColor == other.BgColor || BgColor != null && BgColor.Equals(other.BgColor) ) && ( Equals(BgColorArray, other.BgColorArray) || BgColorArray != null && other.BgColorArray != null && BgColorArray.SequenceEqual(other.BgColorArray) ) && ( BorderColor == other.BorderColor || BorderColor != null && BorderColor.Equals(other.BorderColor) ) && ( Equals(BorderColorArray, other.BorderColorArray) || BorderColorArray != null && other.BorderColorArray != null && BorderColorArray.SequenceEqual(other.BorderColorArray) ) && ( Font == other.Font || Font != null && Font.Equals(other.Font) ) && ( Align == other.Align || Align != null && Align.Equals(other.Align) ) && ( Equals(AlignArray, other.AlignArray) || AlignArray != null && other.AlignArray != null && AlignArray.SequenceEqual(other.AlignArray) ) && ( NameLength == other.NameLength || NameLength != null && NameLength.Equals(other.NameLength) ) && ( Equals(NameLengthArray, other.NameLengthArray) || NameLengthArray != null && other.NameLengthArray != null && NameLengthArray.SequenceEqual(other.NameLengthArray) ) && ( BgColorSrc == other.BgColorSrc || BgColorSrc != null && BgColorSrc.Equals(other.BgColorSrc) ) && ( BorderColorSrc == other.BorderColorSrc || BorderColorSrc != null && BorderColorSrc.Equals(other.BorderColorSrc) ) && ( AlignSrc == other.AlignSrc || AlignSrc != null && AlignSrc.Equals(other.AlignSrc) ) && ( NameLengthSrc == other.NameLengthSrc || NameLengthSrc != null && NameLengthSrc.Equals(other.NameLengthSrc) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (BgColor != null) hashCode = hashCode * 59 + BgColor.GetHashCode(); if (BgColorArray != null) hashCode = hashCode * 59 + BgColorArray.GetHashCode(); if (BorderColor != null) hashCode = hashCode * 59 + BorderColor.GetHashCode(); if (BorderColorArray != null) hashCode = hashCode * 59 + BorderColorArray.GetHashCode(); if (Font != null) hashCode = hashCode * 59 + Font.GetHashCode(); if (Align != null) hashCode = hashCode * 59 + Align.GetHashCode(); if (AlignArray != null) hashCode = hashCode * 59 + AlignArray.GetHashCode(); if (NameLength != null) hashCode = hashCode * 59 + NameLength.GetHashCode(); if (NameLengthArray != null) hashCode = hashCode * 59 + NameLengthArray.GetHashCode(); if (BgColorSrc != null) hashCode = hashCode * 59 + BgColorSrc.GetHashCode(); if (BorderColorSrc != null) hashCode = hashCode * 59 + BorderColorSrc.GetHashCode(); if (AlignSrc != null) hashCode = hashCode * 59 + AlignSrc.GetHashCode(); if (NameLengthSrc != null) hashCode = hashCode * 59 + NameLengthSrc.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left HoverLabel and the right HoverLabel. /// </summary> /// <param name="left">Left HoverLabel.</param> /// <param name="right">Right HoverLabel.</param> /// <returns>Boolean</returns> public static bool operator == (HoverLabel left, HoverLabel right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left HoverLabel and the right HoverLabel. /// </summary> /// <param name="left">Left HoverLabel.</param> /// <param name="right">Right HoverLabel.</param> /// <returns>Boolean</returns> public static bool operator != (HoverLabel left, HoverLabel right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>HoverLabel</returns> public HoverLabel DeepClone() { return this.Copy(); } } }
40.49004
104
0.529666
[ "MIT" ]
valu8/Plotly.Blazor
Plotly.Blazor/Traces/ConeLib/HoverLabel.cs
10,163
C#
using System; using System.Collections.Generic; using System.Text; namespace InheritanceAndPolymorphism { public class LocalCourse : Course { private string lab; public LocalCourse(string courseName, string teacherName, IList<string> students, string lab) : base(courseName, teacherName, students) { this.Lab = lab; } public string Lab { get { return this.lab; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Lab name cannot be null or empty."); } this.lab = value; } } public override string ToString() { StringBuilder result = new StringBuilder(); result.AppendLine(base.ToString()); result.AppendLine("Lab = " + this.Lab); return result.ToString(); } } }
22.911111
101
0.504365
[ "MIT" ]
GAlex7/TA
10. High-Quality-Code/08. High-quality Classes/Inheritance-and-Polymorphism/LocalCourse.cs
1,033
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2020 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallWorkshop; using DaggerfallWorkshop.Game.UserInterface; using DaggerfallWorkshop.Game.Entity; namespace DaggerfallWorkshop.Game.UserInterfaceWindows { /// <summary> /// Implements race select window. /// </summary> public class CreateCharRaceSelect : DaggerfallPopupWindow { const string nativeImgName = "TMAP00I0.IMG"; const string racePickerImgName = "TAMRIEL2.IMG"; Texture2D nativeTexture; TextLabel promptLabel; DFBitmap racePickerBitmap; RaceTemplate selectedRace; Dictionary<int, RaceTemplate> raceDict = RaceTemplate.GetRaceDictionary(); public RaceTemplate SelectedRace { get { return selectedRace; } } public CreateCharRaceSelect(IUserInterfaceManager uiManager) : base(uiManager) { } protected override void Setup() { // Load native texture nativeTexture = DaggerfallUI.GetTextureFromImg(nativeImgName); if (!nativeTexture) throw new Exception("CreateCharRaceSelect: Could not load native texture."); // Load picker colours racePickerBitmap = DaggerfallUI.GetImgBitmap(racePickerImgName); // Setup native panel background NativePanel.BackgroundTexture = nativeTexture; // Add "Please select your home province..." prompt promptLabel = DaggerfallUI.AddTextLabel(DaggerfallUI.DefaultFont, new Vector2(0, 16), HardStrings.pleaseSelectYourHomeProvince, NativePanel); promptLabel.HorizontalAlignment = HorizontalAlignment.Center; promptLabel.TextColor = DaggerfallUI.DaggerfallDefaultTextColor; promptLabel.ShadowColor = DaggerfallUI.DaggerfallDefaultShadowColor; promptLabel.ShadowPosition = DaggerfallUI.DaggerfallDefaultShadowPos; // Handle clicks NativePanel.OnMouseClick += ClickHandler; } public override void Update() { base.Update(); if (Input.GetKeyDown(exitKey)) { selectedRace = null; CancelWindow(); } } public void Reset() { selectedRace = null; if (promptLabel != null) promptLabel.Enabled = true; } void ClickHandler(BaseScreenComponent sender, Vector2 position) { int offset = (int)position.y * racePickerBitmap.Width + (int)position.x; if (offset < 0 || offset >= racePickerBitmap.Data.Length) return; int id = racePickerBitmap.Data[offset]; if (raceDict.ContainsKey(id)) { promptLabel.Enabled = false; selectedRace = raceDict[id]; TextFile.Token[] textTokens = DaggerfallUnity.Instance.TextProvider.GetRSCTokens(selectedRace.DescriptionID); DaggerfallMessageBox messageBox = new DaggerfallMessageBox(uiManager, this); messageBox.SetTextTokens(textTokens); messageBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.Yes); Button noButton = messageBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.No); noButton.ClickSound = DaggerfallUI.Instance.GetAudioClip(SoundClips.ButtonClick); messageBox.OnButtonClick += ConfirmRacePopup_OnButtonClick; messageBox.OnCancel += ConfirmRacePopup_OnCancel; uiManager.PushWindow(messageBox); DaggerfallAudioSource source = DaggerfallUI.Instance.GetComponent<DaggerfallAudioSource>(); source.PlayOneShot((uint)selectedRace.ClipID); } } void ConfirmRacePopup_OnButtonClick(DaggerfallMessageBox sender, DaggerfallMessageBox.MessageBoxButtons messageBoxButton) { if (messageBoxButton == DaggerfallMessageBox.MessageBoxButtons.Yes) { CloseWindow(); } else if (messageBoxButton == DaggerfallMessageBox.MessageBoxButtons.No) { sender.CancelWindow(); } } void ConfirmRacePopup_OnCancel(DaggerfallPopupWindow sender) { Reset(); } } }
35.934307
153
0.636604
[ "MIT" ]
BibleUs/daggerfall-unity
Assets/Scripts/Game/UserInterfaceWindows/CreateCharRaceSelect.cs
4,923
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.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteTable operation /// </summary> public class DeleteTableResponseUnmarshaller : 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) { DeleteTableResponse response = new DeleteTableResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("TableDescription", targetDepth)) { var unmarshaller = TableDescriptionUnmarshaller.Instance; response.TableDescription = 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("InternalServerError")) { return InternalServerErrorExceptionUnmarshaller.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("ResourceInUseException")) { return ResourceInUseExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonDynamoDBException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteTableResponseUnmarshaller _instance = new DeleteTableResponseUnmarshaller(); internal static DeleteTableResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteTableResponseUnmarshaller Instance { get { return _instance; } } } }
40.122951
192
0.626762
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DynamoDBv2/Generated/Model/Internal/MarshallTransformations/DeleteTableResponseUnmarshaller.cs
4,895
C#
namespace Fan.Settings { public enum EPreferredDomain { /// <summary> /// use whatever the url is given, will not do forward /// </summary> Auto, /// <summary> /// forward root domain to www subdomain, e.g. fanray.com -> www.fanray.com /// </summary> Www, /// <summary> /// forward www subdomain to root domain, e.g. www.fanray.com -> fanray.com /// </summary> NonWww, } }
26.722222
83
0.517672
[ "Apache-2.0" ]
FanrayMedia/Fanray
src/Core/Fan/Settings/EPreferredDomain.cs
483
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Todo.Core.Data; namespace Todo.Core.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20210114174235_InitialSqlServer")] partial class InitialSqlServer { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Todo.Core.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Todo.Core.Models.TodoList", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.HasKey("Id"); b.ToTable("TodoLists"); }); modelBuilder.Entity("Todo.Core.Models.TodoListUser", b => { b.Property<string>("ApplicationUserId") .HasColumnType("nvarchar(450)"); b.Property<Guid>("TodoListId") .HasColumnType("uniqueidentifier"); b.Property<int>("Role") .HasColumnType("int"); b.HasKey("ApplicationUserId", "TodoListId"); b.HasIndex("TodoListId"); b.ToTable("TodoListUser"); }); modelBuilder.Entity("Todo.Core.Models.TodoTask", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasMaxLength(2048) .HasColumnType("nvarchar(2048)"); b.Property<DateTime?>("DueAt") .HasColumnType("datetime2"); b.Property<bool>("IsCompleted") .HasColumnType("bit"); b.Property<bool>("IsImportant") .HasColumnType("bit"); b.Property<Guid>("TodoListId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("TodoListId"); b.ToTable("TodoTasks"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Todo.Core.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Todo.Core.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Todo.Core.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Todo.Core.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Todo.Core.Models.TodoListUser", b => { b.HasOne("Todo.Core.Models.ApplicationUser", "ApplicationUser") .WithMany("TodoListUsers") .HasForeignKey("ApplicationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Todo.Core.Models.TodoList", "TodoList") .WithMany("TodoListUsers") .HasForeignKey("TodoListId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ApplicationUser"); b.Navigation("TodoList"); }); modelBuilder.Entity("Todo.Core.Models.TodoTask", b => { b.HasOne("Todo.Core.Models.TodoList", "TodoList") .WithMany("Tasks") .HasForeignKey("TodoListId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("TodoList"); }); modelBuilder.Entity("Todo.Core.Models.ApplicationUser", b => { b.Navigation("TodoListUsers"); }); modelBuilder.Entity("Todo.Core.Models.TodoList", b => { b.Navigation("Tasks"); b.Navigation("TodoListUsers"); }); #pragma warning restore 612, 618 } } }
36.079487
95
0.447658
[ "MIT" ]
oskvr/TodoApp
Todo.Core/Migrations/20210114174235_InitialSqlServer.Designer.cs
14,073
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using NuGet.Common; using NuGet.Frameworks; using NuGet.Packaging.Core; namespace NuGet.Packaging { /// <summary> /// Reads a development nupkg /// </summary> public class PackageArchiveReader : PackageReaderBase { private readonly ZipArchive _zipArchive; /// <summary> /// Nupkg package reader /// </summary> /// <param name="stream">Nupkg data stream.</param> public PackageArchiveReader(Stream stream) : this(stream, false, DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) { } /// <summary> /// Nupkg package reader /// </summary> /// <param name="stream">Nupkg data stream.</param> /// <param name="frameworkProvider">Framework mapping provider for NuGetFramework parsing.</param> /// <param name="compatibilityProvider">Framework compatibility provider.</param> public PackageArchiveReader(Stream stream, IFrameworkNameProvider frameworkProvider, IFrameworkCompatibilityProvider compatibilityProvider) : this(stream, false) { } /// <summary> /// Nupkg package reader /// </summary> /// <param name="stream">Nupkg data stream.</param> /// <param name="leaveStreamOpen">If true the nupkg stream will not be closed by the zip reader.</param> public PackageArchiveReader(Stream stream, bool leaveStreamOpen) : this(new ZipArchive(stream, ZipArchiveMode.Read, leaveStreamOpen), DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) { } /// <summary> /// Nupkg package reader /// </summary> /// <param name="stream">Nupkg data stream.</param> /// <param name="leaveStreamOpen">leave nupkg stream open</param> /// <param name="frameworkProvider">Framework mapping provider for NuGetFramework parsing.</param> /// <param name="compatibilityProvider">Framework compatibility provider.</param> public PackageArchiveReader(Stream stream, bool leaveStreamOpen, IFrameworkNameProvider frameworkProvider, IFrameworkCompatibilityProvider compatibilityProvider) : this(new ZipArchive(stream, ZipArchiveMode.Read, leaveStreamOpen), frameworkProvider, compatibilityProvider) { } /// <summary> /// Nupkg package reader /// </summary> /// <param name="zipArchive">ZipArchive containing the nupkg data.</param> public PackageArchiveReader(ZipArchive zipArchive) : this(zipArchive, DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) { } /// <summary> /// Nupkg package reader /// </summary> /// <param name="zipArchive">ZipArchive containing the nupkg data.</param> /// <param name="frameworkProvider">Framework mapping provider for NuGetFramework parsing.</param> /// <param name="compatibilityProvider">Framework compatibility provider.</param> public PackageArchiveReader(ZipArchive zipArchive, IFrameworkNameProvider frameworkProvider, IFrameworkCompatibilityProvider compatibilityProvider) : base(frameworkProvider, compatibilityProvider) { if (zipArchive == null) { throw new ArgumentNullException(nameof(zipArchive)); } _zipArchive = zipArchive; } public PackageArchiveReader(string filePath, IFrameworkNameProvider frameworkProvider = null, IFrameworkCompatibilityProvider compatibilityProvider = null) : base(frameworkProvider ?? DefaultFrameworkNameProvider.Instance, compatibilityProvider ?? DefaultCompatibilityProvider.Instance) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } // Since this constructor owns the stream, the responsibility falls here to dispose the stream of an // invalid .zip archive. If this constructor succeeds, the disposal of the stream is handled by the // disposal of this instance. Stream stream = null; try { stream = File.OpenRead(filePath); _zipArchive = new ZipArchive(stream, ZipArchiveMode.Read); } catch { stream?.Dispose(); throw; } } public override IEnumerable<string> GetFiles() { return _zipArchive.GetFiles(); } public override IEnumerable<string> GetFiles(string folder) { return GetFiles().Where(f => f.StartsWith(folder + "/", StringComparison.OrdinalIgnoreCase)); } public override Stream GetStream(string path) { Stream stream = null; path = path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); if (!string.IsNullOrEmpty(path)) { stream = _zipArchive.OpenFile(path); } return stream; } protected override void Dispose(bool disposing) { if (disposing) { _zipArchive.Dispose(); } } public override IEnumerable<string> CopyFiles( string destination, IEnumerable<string> packageFiles, ExtractPackageFileDelegate extractFile, ILogger logger, CancellationToken token) { var filesCopied = new List<string>(); foreach (var packageFile in packageFiles) { token.ThrowIfCancellationRequested(); var entry = GetEntry(packageFile); var packageFileName = entry.FullName; // An entry in a ZipArchive could start with a '/' based on how it is zipped // Remove it if present if (packageFileName.StartsWith("/", StringComparison.Ordinal)) { packageFileName = packageFileName.Substring(1); } // ZipArchive always has forward slashes in them. By replacing them with DirectorySeparatorChar; // in windows, we get the windows-style path var normalizedPath = Uri.UnescapeDataString(packageFileName.Replace('/', Path.DirectorySeparatorChar)); var targetFilePath = Path.Combine(destination, normalizedPath); if (!targetFilePath.StartsWith(destination, StringComparison.OrdinalIgnoreCase)) { continue; } using (var stream = entry.Open()) { var copiedFile = extractFile(packageFileName, targetFilePath, stream); if (copiedFile != null) { entry.UpdateFileTimeFromEntry(copiedFile, logger); entry.UpdateFilePermissionsFromEntry(copiedFile, logger); filesCopied.Add(copiedFile); } } } return filesCopied; } public string ExtractFile(string packageFile, string targetFilePath, ILogger logger) { var entry = GetEntry(packageFile); var copiedFile = entry.SaveAsFile(targetFilePath, logger); return copiedFile; } private ZipArchiveEntry GetEntry(string packageFile) { return _zipArchive.LookupEntry(packageFile); } public IEnumerable<ZipFilePair> EnumeratePackageEntries(IEnumerable<string> packageFiles, string packageDirectory) { foreach (var packageFile in packageFiles) { var packageFileFullPath = Path.Combine(packageDirectory, packageFile); var entry = GetEntry(packageFile); yield return new ZipFilePair(packageFileFullPath, entry); } } } }
38.981567
169
0.608464
[ "Apache-2.0" ]
clairernovotny/NuGet.Client
src/NuGet.Core/NuGet.Packaging/PackageArchiveReader.cs
8,459
C#
/* Copyright 2009 HPDI, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Text; namespace Hpdi.VssPhysicalLib { /// <summary> /// Represents a file containing VSS project entry records. /// </summary> /// <author>Trevor Robinson</author> public class ProjectEntryFile : VssRecordFile { public ProjectEntryFile(string filename, Encoding encoding) : base(filename, encoding) { } public ProjectEntryRecord GetFirstEntry() { reader.Offset = 0; return GetNextEntry(); } public ProjectEntryRecord GetNextEntry() { var record = new ProjectEntryRecord(); return ReadNextRecord(record) ? record : null; } } }
29.477273
75
0.653045
[ "ECL-2.0", "Apache-2.0" ]
esskar/vss2git
VssPhysicalLib/ProjectEntryFile.cs
1,299
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Tomighty.Windows.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.666667
151
0.582633
[ "Apache-2.0" ]
dogfuntom/Fermented-Tomighty
Tomighty.Windows/Properties/Settings.Designer.cs
1,073
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; //Eigene Usings using Model = MeisterGeister.Model; namespace MeisterGeister.Model.Service { public class VorNachteilService : ServiceBase { #region //----- EIGENSCHAFTEN ---- public List<Model.VorNachteil> VorNachteilListe { get { return Liste<VorNachteil>() .Where(vn => vn.Regelsystem == Global.Regeledition).Where(t => Setting.AktiveSettings.Any(s => (t.Setting ?? "Aventurien").Contains(s.Name))).ToList(); } } public List<Model.VorNachteil_Auswahl> VorNachteilAuswahlListe { get { return Liste<VorNachteil_Auswahl>() .Where(vn => vn.Regelsystem == Global.Regeledition).ToList(); } } #endregion #region //----- KONSTRUKTOR ---- public VorNachteilService() { } #endregion #region //----- DATENBANKABFRAGEN ---- public List<Model.VorNachteil_Auswahl> VorNachteilAuswahlListeByKategorie(string kat) { return Liste<VorNachteil_Auswahl>() .Where(vn => vn.Regelsystem == Global.Regeledition && vn.Kategorie == kat).OrderBy(vn => vn.Name).ToList(); } #endregion } }
24.596491
170
0.558488
[ "Apache-2.0" ]
Constructor0987/MeisterGeister
Model/Service/VorNachteilService.cs
1,404
C#
using System; using Foundation; using StoreKit; using TrueLogicMobile.API; using TrueLogicMobile.API.Interfaces; using TrueLogicMobile.iOS.Services; using UIKit; [assembly: Xamarin.Forms.Dependency(typeof(AppRating))] namespace TrueLogicMobile.iOS.Services { public class AppRating : IAppRating { public void RateApp() { if ( UIDevice.CurrentDevice.CheckSystemVersion(10, 3) ) SKStoreReviewController.RequestReview(); else { string storeUrl = $@"itms-apps://itunes.apple.com/app/{Api.DeviceInfo.PackageName}?action=write-review"; try { using var uri = new NSUrl(storeUrl); UIApplication.SharedApplication.OpenUrl(uri); } catch ( Exception ex ) { // Here you could show an alert to the user telling that App Store was unable to launch Console.WriteLine(ex.Message); } } } } }
23.638889
108
0.712103
[ "MIT" ]
Jakar510/Jakar.Api
Services/AppRatiing.cs
853
C#