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 Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using WorldCities.Data; using WorldCities.Data.Models; using Microsoft.AspNetCore.Identity.UI.Services; using WorldCities.Services; using System; using Serilog; namespace WorldCities { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews() .AddJsonOptions(options => { // set this option to TRUE to indent the JSON output options.JsonSerializerOptions.WriteIndented = true; // set this option to NULL to use PascalCase instead of CamelCase (default) // options.JsonSerializerOptions.PropertyNamingPolicy = null; }); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); // Add ApplicationDbContext and SQL Server support services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection") ) ); // Add ASP.NET Core Identity support services.AddDefaultIdentity<ApplicationUser>(options => { options.SignIn.RequireConfirmedAccount = true; options.Password.RequireLowercase = true; options.Password.RequireUppercase = true; options.Password.RequireDigit = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequiredLength = 8; }) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddIdentityServer() .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(); services.AddAuthentication() .AddIdentityServerJwt(); // IEmailSender implementation using SendGrid // (disabled to avoid conflicts with MailKit-based implementation) /* services.AddTransient<IEmailSender, SendGridEmailSender>(); services.Configure<SendGridEmailSenderOptions>(options => { options.ApiKey = Configuration["ExternalProviders:SendGrid:ApiKey"]; options.Sender_Email = Configuration["ExternalProviders:SendGrid:Sender_Email"]; options.Sender_Name = Configuration["ExternalProviders:SendGrid:Sender_Name"]; }); */ // IEmailSender implementation using MailKit // (disable it if you want to use the SendGrid-based implementation instead) services.AddTransient<IEmailSender, MailKitEmailSender>(); services.Configure<MailKitEmailSenderOptions>(options => { options.Host_Address = Configuration["ExternalProviders:MailKit:SMTP:Address"]; options.Host_Port = Convert.ToInt32(Configuration["ExternalProviders:MailKit:SMTP:Port"]); options.Host_Username = Configuration["ExternalProviders:MailKit:SMTP:Account"]; options.Host_Password = Configuration["ExternalProviders:MailKit:SMTP:Password"]; options.Sender_EMail = Configuration["ExternalProviders:MailKit:SMTP:Sender_Email"]; options.Sender_Name = Configuration["ExternalProviders:MailKit:SMTP:Sender_Name"]; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(new StaticFileOptions() { OnPrepareResponse = (context) => { // Retrieve cache configuration from appsettings.json context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"]; } }); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseRouting(); app.UseAuthentication(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); // Use the Serilog request logging middleware to log HTTP requests. app.UseSerilogRequestLogging(); } } }
39.63354
143
0.596615
[ "MIT" ]
FlorianMeinhart/ASP.NET-Core-5-and-Angular
Chapter_10/WorldCities/Startup.cs
6,381
C#
using ClangAggregator.Types; namespace ClangCaster { class CSEnumTemplate : CSTemplateBase { protected override string TemplateSource => @" // {{ type.Location.Path.Path }}:{{ type.Location.Line }} public enum {{ type.Name }} { {% for value in type.Values -%} {{ value.Name }} = {{ value.Hex }}, {%- endfor -%} } "; public CSEnumTemplate() { DotLiquid.Template.RegisterSafeType(typeof(EnumValue), new string[] { "Name", "Value", "Hex" }); } public string Render(TypeReference reference) { var enumType = reference.Type as EnumType; return m_template.Render(DotLiquid.Hash.FromAnonymousObject( new { type = new { Hash = reference.Hash, Location = reference.Location, Count = reference.Count, Name = enumType.Name, Values = enumType.Values, }, } )); } } }
29.075
116
0.460877
[ "MIT" ]
ousttrue/ClangCaster
ClangCaster/CSEnumTemplate.cs
1,163
C#
using IronBrew2.Bytecode_Library.Bytecode; using IronBrew2.Bytecode_Library.IR; namespace IronBrew2.Obfuscator.Opcodes { public class OpVarArg : VOpcode { public override bool IsInstruction(Instruction instruction) => instruction.OpCode == Opcode.VarArg && instruction.B != 0; public override string GetObfuscated(ObfuscationContext context) => @" local A=Inst[OP_A]; local B=Inst[OP_B]; for Idx=A,B do Stk[Idx]=Vararg[Idx-A]; end; "; public override void Mutate(Instruction instruction) { instruction.B += instruction.A - 1; } } public class OpVarArgB0 : VOpcode { public override bool IsInstruction(Instruction instruction) => instruction.OpCode == Opcode.VarArg && instruction.B == 0; public override string GetObfuscated(ObfuscationContext context) => @" local A=Inst[OP_A]; Top=A+Varargsz-1; for Idx=A,Top do local VA=Vararg[Idx-A]; Stk[Idx]=VA; end; "; } }
22.170732
69
0.726073
[ "MIT" ]
CompilerErrorRBX/ironbrew-2
IronBrew2/Obfuscator/Opcodes/OpVarArg.cs
909
C#
// // ExtAudioFile.cs: ExtAudioFile wrapper class // // Authors: // AKIHIRO Uehara (u-akihiro@reinforce-lab.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2010 Reinforce Lab. // Copyright 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using MonoMac.AudioToolbox; namespace MonoMac.AudioUnit { public enum ExtAudioFileError { OK = 0, CodecUnavailableInputConsumed = -66559, CodecUnavailableInputNotConsumed = -66560, InvalidProperty = -66561, InvalidPropertySize = -66562, NonPCMClientFormat = -66563, InvalidChannelMap = -66564, InvalidOperationOrder = -66565, InvalidDataFormat = -66566, MaxPacketSizeUnknown = -66567, InvalidSeek = -66568, AsyncWriteTooLarge = -66569, AsyncWriteBufferOverflow = -66570, // Shared error codes NotOpenError = -38, EndOfFileError = -39, PositionError = -40, FileNotFoundError = -43 } public class ExtAudioFile : IDisposable { IntPtr _extAudioFile; public uint? ClientMaxPacketSize { get { uint size = sizeof (uint); uint value; if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.ClientMaxPacketSize, ref size, out value) != ExtAudioFileError.OK) return null; return value; } } public uint? FileMaxPacketSize { get { uint size = sizeof (uint); uint value; if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.FileMaxPacketSize, ref size, out value) != ExtAudioFileError.OK) return null; return value; } } public IntPtr? AudioFile { get { uint size = (uint) Marshal.SizeOf (typeof (IntPtr)); IntPtr value; if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.AudioFile, ref size, out value) != ExtAudioFileError.OK) return null; return value; } } public AudioConverter AudioConverter { get { uint size = sizeof (uint); IntPtr value; if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.AudioConverter, ref size, out value) != ExtAudioFileError.OK) return null; return new AudioConverter (value, false); } } public long FileLengthFrames { get { long length; uint size = sizeof (long); var err = ExtAudioFileGetProperty(_extAudioFile, PropertyIDType.FileLengthFrames, ref size, out length); if (err != 0) { throw new InvalidOperationException(String.Format("Error code:{0}", err)); } return length; } } public AudioStreamBasicDescription FileDataFormat { get { AudioStreamBasicDescription dc = new AudioStreamBasicDescription(); uint size = (uint)Marshal.SizeOf(typeof(AudioStreamBasicDescription)); int err = ExtAudioFileGetProperty(_extAudioFile, PropertyIDType.FileDataFormat, ref size, ref dc); if (err != 0) { throw new InvalidOperationException(String.Format("Error code:{0}", err)); } return dc; } } public AudioStreamBasicDescription ClientDataFormat { set { int err = ExtAudioFileSetProperty(_extAudioFile, PropertyIDType.ClientDataFormat, (uint)Marshal.SizeOf(value), ref value); if (err != 0) { throw new InvalidOperationException(String.Format("Error code:{0}", err)); } } } private ExtAudioFile(IntPtr ptr) { _extAudioFile = ptr; } ~ExtAudioFile () { Dispose (false); } public static ExtAudioFile OpenUrl (CFUrl url) { if (url == null) throw new ArgumentNullException ("url"); ExtAudioFileError err; IntPtr ptr; unsafe { err = ExtAudioFileOpenUrl(url.Handle, (IntPtr)(&ptr)); } if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } if (ptr == IntPtr.Zero) { throw new InvalidOperationException("Can not get object instance"); } return new ExtAudioFile(ptr); } public static ExtAudioFile CreateWithUrl (CFUrl url, AudioFileType fileType, AudioStreamBasicDescription inStreamDesc, //AudioChannelLayout channelLayout, AudioFileFlags flag) { if (url == null) throw new ArgumentNullException ("url"); int err; IntPtr ptr = new IntPtr(); unsafe { err = ExtAudioFileCreateWithUrl(url.Handle, fileType, ref inStreamDesc, IntPtr.Zero, (uint)flag, (IntPtr)(&ptr)); } if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } if (ptr == IntPtr.Zero) { throw new InvalidOperationException("Can not get object instance"); } return new ExtAudioFile(ptr); } public static ExtAudioFileError WrapAudioFileID (IntPtr audioFileID, bool forWriting, out ExtAudioFile outAudioFile) { IntPtr ptr; ExtAudioFileError res; unsafe { res = ExtAudioFileWrapAudioFileID (audioFileID, forWriting, (IntPtr)(&ptr)); } if (res != ExtAudioFileError.OK) { outAudioFile = null; return res; } outAudioFile = new ExtAudioFile (ptr); return res; } public void Seek(long frameOffset) { int err = ExtAudioFileSeek(_extAudioFile, frameOffset); if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } } public long FileTell() { long frame = 0; int err = ExtAudioFileTell(_extAudioFile, ref frame); if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } return frame; } [Obsolete ("Use overload with AudioBuffers")] public int Read(int numberFrames, AudioBufferList data) { if (data == null) throw new ArgumentNullException ("data"); int err = ExtAudioFileRead(_extAudioFile, ref numberFrames, data); if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } return numberFrames; } public uint Read (uint numberFrames, AudioBuffers audioBufferList, out ExtAudioFileError status) { if (audioBufferList == null) throw new ArgumentNullException ("audioBufferList"); status = ExtAudioFileRead (_extAudioFile, ref numberFrames, (IntPtr) audioBufferList); return numberFrames; } [Obsolete ("Use overload with AudioBuffers")] public void WriteAsync(int numberFrames, AudioBufferList data) { int err = ExtAudioFileWriteAsync(_extAudioFile, numberFrames, data); if (err != 0) { throw new ArgumentException(String.Format("Error code:{0}", err)); } } public ExtAudioFileError WriteAsync (uint numberFrames, AudioBuffers audioBufferList) { if (audioBufferList == null) throw new ArgumentNullException ("audioBufferList"); return ExtAudioFileWriteAsync (_extAudioFile, numberFrames, (IntPtr) audioBufferList); } public ExtAudioFileError Write (uint numberFrames, AudioBuffers audioBufferList) { if (audioBufferList == null) throw new ArgumentNullException ("audioBufferList"); return ExtAudioFileWrite (_extAudioFile, numberFrames, (IntPtr) audioBufferList); } public ExtAudioFileError SynchronizeAudioConverter () { IntPtr value = IntPtr.Zero; return ExtAudioFileSetProperty (_extAudioFile, PropertyIDType.ConverterConfig, Marshal.SizeOf (value), value); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (_extAudioFile != IntPtr.Zero){ ExtAudioFileDispose (_extAudioFile); _extAudioFile = IntPtr.Zero; } } #region Interop [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileOpenURL")] static extern ExtAudioFileError ExtAudioFileOpenUrl(IntPtr inUrl, IntPtr outExtAudioFile); // caution [DllImport (MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileWrapAudioFileID (IntPtr inFileID, bool inForWriting, IntPtr outExtAudioFile); [Obsolete] [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileRead")] static extern int ExtAudioFileRead(IntPtr inExtAudioFile, ref int ioNumberFrames, AudioBufferList ioData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileRead (IntPtr inExtAudioFile, ref uint ioNumberFrames, IntPtr ioData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileWrite (IntPtr inExtAudioFile, uint inNumberFrames, IntPtr ioData); [Obsolete] [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileWriteAsync")] static extern int ExtAudioFileWriteAsync(IntPtr inExtAudioFile, int inNumberFrames, AudioBufferList ioData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileWriteAsync(IntPtr inExtAudioFile, uint inNumberFrames, IntPtr ioData); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileDispose")] static extern int ExtAudioFileDispose(IntPtr inExtAudioFile); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileSeek")] static extern int ExtAudioFileSeek(IntPtr inExtAudioFile, long inFrameOffset); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileTell")] static extern int ExtAudioFileTell(IntPtr inExtAudioFile, ref long outFrameOffset); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileCreateWithURL")] static extern int ExtAudioFileCreateWithUrl(IntPtr inURL, [MarshalAs(UnmanagedType.U4)] AudioFileType inFileType, ref AudioStreamBasicDescription inStreamDesc, IntPtr inChannelLayout, //AudioChannelLayout inChannelLayout, AudioChannelLayout results in compilation error (error code 134.) UInt32 flags, IntPtr outExtAudioFile); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileGetProperty")] static extern int ExtAudioFileGetProperty( IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, IntPtr outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileGetProperty")] static extern int ExtAudioFileGetProperty( IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, ref AudioStreamBasicDescription outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out IntPtr outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out long outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out uint outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary)] static extern ExtAudioFileError ExtAudioFileSetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, int ioPropertyDataSize, IntPtr outPropertyData); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileSetProperty")] static extern int ExtAudioFileSetProperty( IntPtr inExtAudioFile, PropertyIDType inPropertyID, uint ioPropertyDataSize, ref AudioStreamBasicDescription outPropertyData); enum PropertyIDType { FileDataFormat = 0x66666d74, // 'ffmt' //kExtAudioFileProperty_FileChannelLayout = 'fclo', // AudioChannelLayout ClientDataFormat = 0x63666d74, //'cfmt', // AudioStreamBasicDescription //kExtAudioFileProperty_ClientChannelLayout = 'cclo', // AudioChannelLayout CodecManufacturer = 0x636d616e, // 'cman' // read-only: AudioConverter = 0x61636e76, // 'acnv' AudioFile = 0x6166696c, // 'afil' FileMaxPacketSize = 0x666d7073, // 'fmps' ClientMaxPacketSize = 0x636d7073, // 'cmps' FileLengthFrames = 0x2366726d, // '#frm' // writable: ConverterConfig = 0x61636366, // 'accf' //kExtAudioFileProperty_IOBufferSizeBytes = 'iobs', // UInt32 //kExtAudioFileProperty_IOBuffer = 'iobf', // void * //kExtAudioFileProperty_PacketTable = 'xpti' // AudioFilePacketTableInfo }; #endregion } }
38.703529
174
0.599368
[ "MIT" ]
Terricide/monomac
src/AudioUnit/ExtAudioFile.cs
16,449
C#
// Copyright(c) 2020 Pixel Precision LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Collections; using System.Collections.Generic; using UnityEngine; namespace PxPre { namespace Phonics { public class GenInvert : GenBase { /// <summary> /// The PCM stream to invert. /// </summary> GenBase input; public GenInvert(GenBase input) : base(0.0f, 0) { this.input = input; } unsafe public override void AccumulateImpl(float * data, int start, int size, int prefBuffSz, FPCMFactoryGenLimit pcmFactory) { FPCM fa = pcmFactory.GetZeroedFPCM(start, size); float[] a = fa.buffer; fixed(float * pa = a) { this.input.Accumulate(pa, start, size, prefBuffSz, pcmFactory); for (int i = start; i < start + size; ++i) data[i] += 0.5f - (pa[i] - 0.5f); } } public override PlayState Finished() { if (this.input == null) return PlayState.Finished; return this.input.Finished(); } public override void ReportChildren(List<GenBase> lst) { lst.Add(this.input); } } } }
35.314286
137
0.600728
[ "Unlicense" ]
Reavenk/PxPre-Phonics
GenS/GenInvert.cs
2,474
C#
using MediatR; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Dddify.DependencyInjection; namespace MyCompany.MyProject.Application.Behaviours; public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>, ITransientDependency where TRequest : IRequest<TResponse> { private readonly ILogger<TRequest> _logger; public LoggingBehavior(ILogger<TRequest> logger) { _logger = logger; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { _logger.LogInformation($"[dddify] logging..."); return await next(); } }
28
134
0.752747
[ "MIT" ]
esofar/dddify
samples/MyCompany.MyProject.Application/Behaviours/LoggingBehavior.cs
730
C#
using System; using System.Linq; using System.Threading.Tasks; using Abp.Dependency; namespace Schruted.Authentication.External { public class ExternalAuthManager : IExternalAuthManager, ITransientDependency { private readonly IIocResolver _iocResolver; private readonly IExternalAuthConfiguration _externalAuthConfiguration; public ExternalAuthManager(IIocResolver iocResolver, IExternalAuthConfiguration externalAuthConfiguration) { _iocResolver = iocResolver; _externalAuthConfiguration = externalAuthConfiguration; } public Task<bool> IsValidUser(string provider, string providerKey, string providerAccessCode) { using (var providerApi = CreateProviderApi(provider)) { return providerApi.Object.IsValidUser(providerKey, providerAccessCode); } } public Task<ExternalAuthUserInfo> GetUserInfo(string provider, string accessCode) { using (var providerApi = CreateProviderApi(provider)) { return providerApi.Object.GetUserInfo(accessCode); } } public IDisposableDependencyObjectWrapper<IExternalAuthProviderApi> CreateProviderApi(string provider) { var providerInfo = _externalAuthConfiguration.Providers.FirstOrDefault(p => p.Name == provider); if (providerInfo == null) { throw new Exception("Unknown external auth provider: " + provider); } var providerApi = _iocResolver.ResolveAsDisposable<IExternalAuthProviderApi>(providerInfo.ProviderApiType); providerApi.Object.Initialize(providerInfo); return providerApi; } } }
36.367347
119
0.672278
[ "MIT" ]
KaanYilmazz/Schruted
aspnet-core/src/Schruted.Web.Core/Authentication/External/ExternalAuthManager.cs
1,784
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BLToolkit.Data; using bv.model.BLToolkit; namespace bv.model.Model.Extenders { public class GetNextNumberExtender<T> : IGetScalarExtender<T, string> { #region IGetScalarExtender<T,R> Members public string GetScalar(DbManagerProxy manager, T t, params object[] pars) { return manager.SetSpCommand("dbo.spGetNextNumber", pars[0], DBNull.Value, DBNull.Value).ExecuteScalar<string>(ScalarSourceType.OutputParameter); } #endregion } }
27.772727
157
0.685761
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v5/bv.model/Model/Extenders/GetNextNumberExtender.cs
613
C#
using MixERP.Net.ApplicationState.Cache; using MixERP.Net.i18n.Resources; using MixERP.Net.WebControls.AttachmentFactory; using System.Web.UI; using System.Web.UI.HtmlControls; namespace MixERP.Net.WebControls.StockTransactionFactory { public partial class StockTransactionForm { private static void CreateAttachmentPanel(Control container) { using (HtmlGenericControl header = new HtmlGenericControl("h2")) { header.ID = "attachmentToggler"; header.InnerText = Titles.AttachmentsPlus; container.Controls.Add(header); } using (HtmlGenericControl attachmentContainer = new HtmlGenericControl("div")) { attachmentContainer.ID = "attachment"; attachmentContainer.Attributes.Add("class", "ui segment initially hidden"); using (Attachment attachment = new Attachment(AppUsers.GetCurrentUserDB())) { attachment.ShowSaveButton = false; attachmentContainer.Controls.Add(attachment); } container.Controls.Add(attachmentContainer); } } } }
35.028571
91
0.619086
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/Server Controls/Project/MixERP.Net.WebControls.StockTransactionFactory/Control/Form/Attachment.cs
1,228
C#
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // -------------------------------------------------------------------------------------------- // NOTE: DO NOT IMPORT ANYTHING BESIDES SYSTEM IMPORTS INTO THIS FILE. using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Microsoft.Terrapin.Worker.PrebuildLogic { /// <summary> /// A class that contains the logic need to execute before starting a build for an NPM package. /// The program looks for the files in the directory in which it was invoked, not necessarily where the prebuild logic is. /// As stated above, don't import non-system imports into this file. This is because this file gets uploaded to the docker Oryx build /// in the GitHub Actions Pipeline, and it doesn't contain any other files or libraries to import from. /// </summary> public static class PrebuildNpm { public const string LockFileName = "package-lock.json"; public const string PackageFileName = "package.json"; public const string NpmrcFileName = ".npmrc"; public const string VersionField = "version"; public const string IntegrityField = "integrity"; public const string PrivateField = "private"; public const string NameField = "name"; public const string SectionSeparator = "######"; public const string ExceptionSeparator = "#!#!#!"; public const string MissingNameErrorMessage = "Missing name field in package.json"; public const string IncorrectNameErrorMessage = "Incorrect name field in package.json"; public const string MissingVersionErrorMessage = "Missing version field in package.json"; public const string IncorrectVersionErrorMessage = "Incorrect version field in package.json"; /// <summary> /// Removes the field `private` from a package.json file because it prevents us from running `npm publish` on the resulting tarball. /// </summary> public static void RemovePrivateField() { var pkgText = File.ReadAllTextAsync(PackageFileName) .ConfigureAwait(false).GetAwaiter().GetResult(); var packageData = JsonSerializer.Deserialize<Dictionary<string, object>>(pkgText); if (!packageData.ContainsKey(PrivateField)) { Console.WriteLine($"{SectionSeparator} {PackageFileName} does not contain '{PrivateField}' field."); return; } packageData.Remove(PrivateField); Console.WriteLine($"{SectionSeparator} Removed '{PrivateField}' field from {PackageFileName}."); File.WriteAllTextAsync(PackageFileName, JsonSerializer.Serialize(packageData)) .ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Checks to see if there is a 'name' field in the package.json file. /// </summary> /// <param name="packageName">The name of the package to build.</param> public static void CheckPackageJsonName(string packageName) { var pkgText = File.ReadAllTextAsync(PackageFileName) .ConfigureAwait(false).GetAwaiter().GetResult(); var packageData = JsonSerializer.Deserialize<Dictionary<string, object>>(pkgText); if (!packageData.ContainsKey(NameField)) { Console.WriteLine($"{SectionSeparator} {PackageFileName} does not contain '{NameField}' field."); throw new PackageJsonException(MissingNameErrorMessage); } else { var jsonNameValue = packageData[NameField].ToString(); if (string.Equals(jsonNameValue, packageName, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains correct '{NameField}' field."); } else { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains incorrect '{NameField}' field: expected '{packageName}', got '{jsonNameValue}'."); throw new PackageJsonException(IncorrectNameErrorMessage); } } } /// <summary> /// Cleans the .npmrc file in case it contains 'package-lock=false'. /// If this parameter is set, it prevents Terrapin from executing validations properly. /// </summary> public static void RemovePackageLockFalse() { const string packageLockFalse = "package-lock=false"; const string packageLockFalseRx = @"package-lock\s?=\s?false\r?\n?"; Regex rx = new Regex(packageLockFalseRx, RegexOptions.Compiled); Console.WriteLine($"Checking if {NpmrcFileName} contains '{packageLockFalse}'."); var fileText = File.ReadAllTextAsync(NpmrcFileName) .ConfigureAwait(false).GetAwaiter().GetResult(); var matches = rx.Matches(fileText); if (matches.Count == 0) { Console.WriteLine($"{SectionSeparator} {NpmrcFileName} did not contain {packageLockFalse}."); return; } Console.WriteLine($"Trying to remove '{packageLockFalse}'"); var cleanText = rx.Replace(fileText, string.Empty); File.WriteAllTextAsync(NpmrcFileName, cleanText) .ConfigureAwait(false).GetAwaiter().GetResult(); Console.WriteLine($"{SectionSeparator} Successfully rewrote {NpmrcFileName} without {packageLockFalse}."); } /// <summary> /// Checks if the 'version' field in the package.json exists, and if so is it a placeholder version (0.0.0-*) then replace it with /// the correct package version to enable a correctly name tarball file from 'npm pack'. /// If it is the wrong version, or it is missing, it throws an exception. /// </summary> /// <param name="packageVersion">The version of the package to build.</param> public static void CheckPackageJsonVersion(string packageVersion) { var pkgText = File.ReadAllTextAsync(PackageFileName) .ConfigureAwait(false).GetAwaiter().GetResult(); var packageData = JsonSerializer.Deserialize<Dictionary<string, object>>(pkgText); if (packageData.ContainsKey(VersionField)) { var jsonVersionValue = packageData[VersionField].ToString(); if (string.Equals(jsonVersionValue, packageVersion, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains correct '{VersionField}' field."); } else if (jsonVersionValue.StartsWith("0.0.0")) { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains placeholder for '{VersionField}' field."); packageData[VersionField] = packageVersion; } else { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains incorrect '{VersionField}' field: expected '{packageVersion}', got '{jsonVersionValue}'."); throw new PackageJsonException(IncorrectVersionErrorMessage); } } else { Console.WriteLine($"{SectionSeparator} {PackageFileName} contains no '{VersionField}' field."); throw new PackageJsonException(MissingVersionErrorMessage); } File.WriteAllTextAsync(PackageFileName, JsonSerializer.Serialize(packageData)) .ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Orchestrates all the required pre-build steps for NPM packages. /// </summary> public static void Main(string[] args) { string packageVersion = string.Empty; string packageName = string.Empty; if (args == null || args.Length == 0) { Console.WriteLine($"{SectionSeparator} No arguments provided, skipping package.json version check."); } else { packageName = args[0]; packageVersion = args[1]; } if (File.Exists(PackageFileName)) { Console.WriteLine($"{SectionSeparator} Removing {PrivateField} from {PackageFileName}, to resolve the build issues caused by private packages"); TryRunActionAndHandleException(RemovePrivateField); TryRunActionAndHandleException(() => CheckPackageJsonName(packageName)); if (!string.IsNullOrEmpty(packageVersion)) { Console.WriteLine($"{SectionSeparator} Verifying that {VersionField} is present and correct in {PackageFileName}."); TryRunActionAndHandleException(() => CheckPackageJsonVersion(packageVersion)); } } else { Console.WriteLine($"{SectionSeparator} {PackageFileName} file not found"); } if (File.Exists(NpmrcFileName)) { Console.WriteLine($"{SectionSeparator} Found {NpmrcFileName}, attempting a cleanup..."); TryRunActionAndHandleException(RemovePackageLockFalse); } else { Console.WriteLine($"{SectionSeparator} {NpmrcFileName} file not found"); } } /// <summary> /// Tries to run a given action, handling any exception thrown and writing it out to the console. /// </summary> /// <param name="action">The action to be run.</param> private static void TryRunActionAndHandleException(Action action) { try { action(); } catch (Exception exc) when (!(exc is PackageJsonException)) { Console.WriteLine($"{ExceptionSeparator} {exc.Message}"); } } /// <summary> /// Exception used for the Prebuild script that gets thrown if the package.json has invalid properties/formatting/missing an entry. /// Or throws it if the package.json differs from the package that was queued to build. /// </summary> public class PackageJsonException : Exception { public PackageJsonException(string message) : base(message) { } } } }
46.995708
177
0.597534
[ "MIT" ]
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-leritwo
VSCode-win32-x64-1.53.2/resources/app/extensions/typescript-language-features/node_modules/typescript-vscode-sh-plugin/.github/workflows/PrebuildSteps.cs
10,950
C#
using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.Mvc; namespace Miru.Mvc { public abstract class ExceptionResultConfiguration { public readonly List<ExceptionResultExpression> Rules = new List<ExceptionResultExpression>(); public ExceptionResultExpression When(Func<ExceptionResultContext, bool> condition) { var rule = new ExceptionResultExpression { When = condition }; Rules.Add(rule); return rule; } } }
24.458333
102
0.626917
[ "MIT" ]
MiruFx/Miru
src/Miru/Mvc/ExceptionResultConfiguration.cs
587
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.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.EntityFrameworkCore.Design.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
88.142857
408
0.901135
[ "Apache-2.0" ]
EasonDongH/EntityFrameworkCore
src/EFCore.Design/Properties/InternalsVisibleTo.cs
617
C#
using UnityEngine; public class TE_ObjectManipulator : MonoBehaviour { EntityAlive _EntityAlive; EntityPlayerLocal _Player; PlayerMoveController _PlayerMoveController; Animator _Animator; AvatarLocalPlayerController _AvatarLocalPlayerController; Transform _currentTarget; string _LocalPosX; string _LocalPosY; string _LocalPosZ; string _LocalRotX; string _LocalRotY; string _LocalRotZ; string _MoveAmount; string _FindTransformText; string _FoundResult; Transform _FindTransform; Translate _TranslateSel; string[] _TranslateTypes; GameObject _Cube; bool _CursorEnabled; public Transform CurrentTarget { get { return _currentTarget; } set { _currentTarget = value; var rootEntityT = RootTransformRefEntity.FindEntityUpwards(_currentTarget); if (rootEntityT != null) { foreach (var c in rootEntityT.GetComponentsInChildren<Component>()) { if (c is Animator) { _Animator = c as Animator; break; } } } UpdatePrimitive(); } } public void Init(EntityAlive entityAlive) { _EntityAlive = entityAlive; if (_currentTarget == null) { _currentTarget = _EntityAlive.transform; } if (_Player == null && GameManager.Instance.World != null) { _Player = GameManager.Instance.World.GetPrimaryPlayer(); var playerRagdoll = _currentTarget.FindInChilds("player_" + (_Player.IsMale ? "male" : "female") + "Ragdoll", false); _Animator = playerRagdoll.GetComponent<Animator>(); _AvatarLocalPlayerController = _currentTarget.GetComponent<AvatarLocalPlayerController>(); } if (_Cube == null) { _Cube = AddPrimitive(PrimitiveType.Cube, 0.2f, Color.blue); _Cube.transform.parent = _currentTarget; _Cube.transform.position = _currentTarget.position; } } public void ToggleActive(bool active) { gameObject.SetActive(active); _Cube.SetActive(active); } void Awake() { _MoveAmount = "0.1"; _TranslateSel = Translate.PosX; _TranslateTypes = new string[] { "Pos X", "Pos Y", "Pos Z", "Rot X", "Rot Y", "Rot Z", "Scale X", "Scale Y", "Scale Z", "Scale All", }; _FindTransformText = "Find"; _FoundResult = ""; _CursorEnabled = false; } void Update() { if (Input.GetKeyUp(KeyCode.F2) && _Player != null) { _CursorEnabled = !_CursorEnabled; GameManager.Instance.SetCursorEnabledOverride(_CursorEnabled, _CursorEnabled); _Player.SetControllable(!_CursorEnabled); _Player.playerInput.Enabled = !_CursorEnabled; } if (_CursorEnabled && Cursor.visible == false) { GameManager.Instance.SetCursorEnabledOverride(_CursorEnabled, _CursorEnabled); } } private void OnGUI() { if (GameManager.Instance.World == null) { return; } if (_currentTarget != null) { GUILayout.TextField(_currentTarget.GetThisPath()); GUI.Box(new Rect(5, 185, 500, 1000), ""); if (GUI.Button(new Rect(8, 580, 100, 25), "Increase")) { TranslatePos(_MoveAmount, _TranslateSel); GUI.changed = false; } if (GUI.Button(new Rect(108, 580, 100, 25), "Decrease")) { TranslatePos("-" + _MoveAmount, _TranslateSel); GUI.changed = false; } if (GUI.Button(new Rect(8, 190, 50, 25), "Root")) { ChangeTargetToRoot(); GUI.changed = false; } if (GUI.Button(new Rect(58, 190, 50, 25), "Parent")) { ChangeTargetToParent(); GUI.changed = false; } if (GUI.Button(new Rect(108, 190, 50, 25), "Sibling")) { ChangeTargetToNextSibling(); GUI.changed = false; } if (GUI.Button(new Rect(158, 190, 50, 25), "Child 0")) { ChangeTargetToFirstChild(); GUI.changed = false; } if (GUI.Button(new Rect(220, 190, 80, 25), "Primitive")) { _Cube.SetActive(!_Cube.activeSelf); GUI.changed = false; } if (GUI.Button(new Rect(310, 190, 80, 25), "Animator")) { if (_Animator != null) _Animator.enabled = !_Animator.enabled; GUI.changed = false; } if (GUI.Button(new Rect(8, 650, 80, 25), "Find")) { _FindTransform = FindTransform(_FindTransformText); if (_FindTransform != null) { _FoundResult = _FindTransform.GetThisPath(); } else { _FoundResult = "Not Found"; } GUI.changed = false; } if (GUI.Button(new Rect(89, 650, 80, 25), "Set") && _FindTransform != null) { _currentTarget = _FindTransform; GUI.changed = false; } GUI.Label(new Rect(8, 215, 1000, 25), "Current Transform: " + _currentTarget.ToString()); GUI.TextField(new Rect(8, 240, 500, 25), " Position: " + _currentTarget.position.ToString("N5")); GUI.TextField(new Rect(8, 265, 500, 25), " Local Position: " + _currentTarget.localPosition.ToString("N5")); GUI.TextField(new Rect(8, 290, 500, 25), " Local Rotation: " + _currentTarget.localRotation.eulerAngles.ToString("N5")); GUI.TextField(new Rect(8, 315, 500, 25), " Local Scale: " + _currentTarget.localScale.ToString("N5")); if (_currentTarget.parent != null) { GUI.Label(new Rect(8, 340, 500, 25), "Parent: " + _currentTarget.parent.ToString()); GUI.TextField(new Rect(8, 365, 500, 25), " Local Pos: " + _currentTarget.parent.localPosition.ToString("N5")); GUI.TextField(new Rect(8, 390, 500, 25), " Local Rot: " + _currentTarget.parent.localRotation.eulerAngles.ToString("N5")); } if (_currentTarget.root != null) { GUI.Label(new Rect(8, 415, 500, 25), "Root Transform: " + _currentTarget.root.ToString()); } _TranslateSel = (Translate)GUI.SelectionGrid(new Rect(8, 445, 300, 100), (int)_TranslateSel, _TranslateTypes, 3); _MoveAmount = GUI.TextField(new Rect(10, 550, 100, 25), _MoveAmount); _FindTransformText = GUI.TextField(new Rect(8, 625, 200, 25), _FindTransformText); GUI.TextField(new Rect(210, 626, 200, 22), _FoundResult); GUI.Label(new Rect(8, 680, 300, 25), "Press F2 to toggle cursor"); } } void ChangeTargetToParent() { if (_currentTarget.parent != null) { Log.Out($"Changing target to parent: {_currentTarget.parent}"); _currentTarget = _currentTarget.parent; UpdatePrimitive(); } } void ChangeTargetToNextSibling() { var curParent = _currentTarget.parent; var curIndex = _currentTarget.GetSiblingIndex(); var siblingCount = curParent != null ? curParent.childCount : 1; var nextIndex = curIndex + 1 >= siblingCount ? 0 : curIndex + 1; if (curParent != null) { Log.Out($"Changing target to sibling at index: {nextIndex}, Sibling count: {siblingCount}"); _currentTarget = curParent.GetChild(nextIndex); UpdatePrimitive(); } } void ChangeTargetToFirstChild() { var childCount = _currentTarget.childCount; if (childCount > 0) { _currentTarget = _currentTarget.GetChild(0); Log.Out($"Changing target to first child {_currentTarget}"); UpdatePrimitive(); } else { Log.Out($"Transform {_currentTarget} has no children."); } } void ChangeTargetToRoot() { if (_currentTarget.root != null) { Log.Out($"Changing target to root: {_currentTarget.root}"); _currentTarget = _currentTarget.root; UpdatePrimitive(); } } void TranslatePos(string input, Translate t) { float newVal = 0f; if (float.TryParse(input, out newVal)) { Log.Out($"Adjusting: {t} by {newVal}"); var lpos = _currentTarget.localPosition; var lrot = _currentTarget.localRotation.eulerAngles; var lscale = _currentTarget.localScale; switch (t) { case Translate.PosX: { _currentTarget.localPosition = new Vector3(lpos.x + newVal, lpos.y, lpos.z); break; } case Translate.PosY: { _currentTarget.localPosition = new Vector3(lpos.x, lpos.y + newVal, lpos.z); break; } case Translate.PosZ: { _currentTarget.localPosition = new Vector3(lpos.x, lpos.y, lpos.z + newVal); break; } case Translate.RotX: { _currentTarget.localRotation = Quaternion.Euler(lrot.x + newVal, lrot.y, lrot.z); break; } case Translate.RotY: { _currentTarget.localRotation = Quaternion.Euler(lrot.x, lrot.y + newVal, lrot.z); break; } case Translate.RotZ: { _currentTarget.localRotation = Quaternion.Euler(lrot.x, lrot.y, lrot.z + newVal); break; } case Translate.ScaleX: { _currentTarget.localScale = new Vector3(lscale.x + newVal, lscale.y, lscale.z); break; } case Translate.ScaleY: { _currentTarget.localScale = new Vector3(lscale.x, lscale.y + newVal, lscale.z); break; } case Translate.ScaleZ: { _currentTarget.localScale = new Vector3(lscale.x, lscale.y, lscale.z + newVal); break; } case Translate.ScaleAll: { _currentTarget.localScale = new Vector3(lscale.x + newVal, lscale.y + newVal, lscale.z + newVal); break; } } } } Transform FindTransform(string input) { return _currentTarget.FindInChilds(input, false); } void UpdatePrimitive() { if (_currentTarget != null && _Cube != null) { _Cube.transform.parent = _currentTarget; _Cube.transform.position = _currentTarget.position; _Cube.transform.localPosition = _currentTarget.localPosition; _Cube.transform.rotation = _currentTarget.rotation; _Cube.transform.localRotation = _currentTarget.localRotation; _Cube.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f); } } enum Translate { PosX, PosY, PosZ, RotX, RotY, RotZ, ScaleX, ScaleY, ScaleZ, ScaleAll, } public static GameObject AddPrimitive(PrimitiveType primitiveType, float scale, Color color) { GameObject prim = GameObject.CreatePrimitive(primitiveType); Object.Destroy(prim.transform.GetComponent<Collider>()); prim.layer = 0; var renderer = prim.GetComponent<Renderer>(); renderer.material = Resources.Load<Material>("Materials/TerrainSmoothing"); color.a = 0.2f; renderer.material.color = color; prim.transform.localPosition = Vector3.zero; prim.transform.localScale = Vector3.one * scale; return prim; } }
27.561713
139
0.611131
[ "MIT" ]
TormentedEmu/7DTD-A19-DMTMods
TE_ObjectManipulator/Scripts/TE_ObjectManipulator.cs
10,944
C#
namespace CodeCamp.Domain { using Magnum.ObjectExtensions; using MassTransit; using Microsoft.Practices.ServiceLocation; public static class DomainContext { private static IServiceBus _serviceBus; private static IServiceLocator _serviceLocator; public static IServiceLocator ServiceLocator { get { return _serviceLocator; } } public static void Publish<T>(T message) where T : class { _serviceBus.Publish(message); } public static void Initialize(IServiceBus bus, IServiceLocator serviceLocator) { bus.MustNotBeNull(); serviceLocator.MustNotBeNull(); _serviceBus = bus; _serviceLocator = serviceLocator; } } }
26.709677
87
0.603865
[ "Apache-2.0" ]
DavidChristiansen/MassTransit
src/Samples/Audit/CodeCamp.Domain/DomainContext.cs
828
C#
using AutoMapper; using Pokebook.core.Data; using Pokebook.core.Models; using Pokebook.core.Models.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pokebook.core.Repositories.Specific { public class FriendshipRepository : MappingRepository<Friendship>, IFriendshipRepository { public FriendshipRepository(PokebookContext context, IMapper mapper) : base(context, mapper) { this.context = context; } private PokebookContext context; public List<Friendship> GetByUserId(Guid userid) { return context.Friendships .Where(f => f.IdRequester == userid || f.IdApprover == userid).ToList(); } public Friendship GetFriendship(Guid userId, Guid friendId) { return context.Friendships.Where ( f => (f.IdRequester == userId && f.IdApprover == friendId) || (f.IdRequester == friendId && f.IdApprover == userId) ).FirstOrDefault(); } public List<FriendshipDTO> GetFriendIdWithFriendshipDTOs (Guid userid) { List<Friendship> friendshipsForUser = GetByUserId(userid); List<FriendshipDTO> friendshipDTOs = new List<FriendshipDTO>(); foreach (var friendship in friendshipsForUser) { Guid friendId = new Guid(); if (friendship.IdApprover == userid) friendId = friendship.IdRequester; else friendId = friendship.IdApprover; friendshipDTOs.Add(new FriendshipDTO() { FriendId = friendId, Friendship = friendship }); } return friendshipDTOs; } } }
34.431373
105
0.615034
[ "MIT" ]
PhilibertJens/Pokebook
Pokebook.core/Repositories/Specific/FriendshipRepository.cs
1,758
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class gamestateMachineTransitionDefinition : graphGraphConnectionDefinition { [Ordinal(0)] [RED("priority")] public CFloat Priority { get; set; } public gamestateMachineTransitionDefinition(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
27.5625
123
0.743764
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/gamestateMachineTransitionDefinition.cs
426
C#
namespace Amazon.Route53; public sealed class TestDNSAnswerRequest { }
19
45
0.776316
[ "MIT" ]
TheJVaughan/Amazon
src/Amazon.Route53/Actions/TestDNSAnswerRequest.cs
78
C#
using System.Collections.Generic; using System.Linq; using ESFA.DC.Data.AppsEarningsHistory.Model; using ESFA.DC.ILR.FundingService.FM36.FundingOutput.Model.Output; using ESFA.DC.ILR1819.DataStore.Interface; using ESFA.DC.ILR1819.DataStore.Interface.Mappers; using ESFA.DC.ILR1819.DataStore.Model.History; namespace ESFA.DC.ILR1819.DataStore.PersistData.Mapper { public class FM36HistoryMapper : IFM36HistoryMapper { public FM36HistoryData MapData(FM36Global fm36Global, IDataStoreContext dataStoreContext) { return new FM36HistoryData() { AppsEarningsHistories = MapAppsEarningsHistory(fm36Global, dataStoreContext.ReturnCode, dataStoreContext.CollectionYear).ToList(), }; } public IEnumerable<AppsEarningsHistory> MapAppsEarningsHistory(FM36Global fm36Global, string returnCode, string year) { var fullreturnCode = "R" + returnCode; return fm36Global? .Learners? .SelectMany(l => l.HistoricEarningOutputValues.Select(ho => new AppsEarningsHistory { UKPRN = fm36Global.UKPRN, CollectionReturnCode = fullreturnCode, CollectionYear = year, LatestInYear = true, LearnRefNumber = l.LearnRefNumber, ULN = l.ULN, AppIdentifier = ho.AppIdentifierOutput, AppProgCompletedInTheYearInput = ho.AppProgCompletedInTheYearOutput, BalancingProgAimPaymentsInTheYear = ho.BalancingProgAimPaymentsInTheYear, CompletionProgaimPaymentsInTheYear = ho.CompletionProgAimPaymentsInTheYear, DaysInYear = ho.HistoricDaysInYearOutput, FworkCode = ho.HistoricFworkCodeOutput, HistoricEffectiveTNPStartDateInput = ho.HistoricEffectiveTNPStartDateOutput, HistoricEmpIdEndWithinYear = ho.HistoricEmpIdEndWithinYearOutput, HistoricEmpIdStartWithinYear = ho.HistoricEmpIdStartWithinYearOutput, HistoricLearnDelProgEarliestACT2DateInput = ho.HistoricLearnDelProgEarliestACT2DateOutput, HistoricLearner1618StartInput = ho.HistoricLearner1618AtStartOutput, HistoricPMRAmount = ho.HistoricPMRAmountOutput, HistoricTNP1Input = ho.HistoricTNP1Output, HistoricTNP2Input = ho.HistoricTNP2Output, HistoricTNP3Input = ho.HistoricTNP3Output, HistoricTNP4Input = ho.HistoricTNP4Output, HistoricTotal1618UpliftPaymentsInTheYearInput = ho.HistoricTotal1618UpliftPaymentsInTheYear, HistoricVirtualTNP3EndOfTheYearInput = ho.HistoricVirtualTNP3EndofThisYearOutput, HistoricVirtualTNP4EndOfTheYearInput = ho.HistoricVirtualTNP4EndofThisYearOutput, OnProgProgAimPaymentsInTheYear = ho.OnProgProgAimPaymentsInTheYear, ProgrammeStartDateIgnorePathway = ho.HistoricProgrammeStartDateIgnorePathwayOutput, ProgrammeStartDateMatchPathway = ho.HistoricProgrammeStartDateMatchPathwayOutput, ProgType = ho.HistoricProgTypeOutput, PwayCode = ho.HistoricPwayCodeOutput, STDCode = ho.HistoricSTDCodeOutput, TotalProgAimPaymentsInTheYear = ho.HistoricTotalProgAimPaymentsInTheYear, UptoEndDate = ho.HistoricUptoEndDateOutput })) ?? new List<AppsEarningsHistory>(); } } }
55.044776
146
0.661334
[ "MIT" ]
SkillsFundingAgency/DC-ILR-1819-DataStore
src/ESFA.DC.ILR1819.DataStore.PersistData/Mapper/FM36HistoryMapper.cs
3,690
C#
// <copyright file="LoggingEventSourceTests.cs" company="Marc A. Modrow"> // Copyright (c) 2018 All Rights Reserved // <author>Marc A. Modrow</author> // </copyright> using CoreSkills.Examples.Project.Logging; using Xunit; namespace CoreSkills.Examples.Project.LoggingTests { /// <summary> /// Tests the correct behaviour of the LoggingEventSource. /// </summary> public class LoggingEventSourceTests { /// <summary> /// Tests the SourceNewLine with event-handlers set. /// </summary> /// <param name="input">The input.</param> [Theory] [InlineData("input")] [InlineData(null)] [InlineData("")] public void SourceNewLine_EventSet(string input) { LoggingEventSource source = new LoggingEventSource(); string output = "this is not the input value"; source.NewLineSourced += (sender, eventInput) => output = eventInput; source.SourceNewLine(input); Assert.Equal(input, output); } } }
32.382353
82
0.594005
[ "MIT" ]
mmodrow/CoreSkills-Examples
2018/03/28_dependency-injection/CoreSkills.Examples.Project.LoggingTests/LoggingEventSourceTests.cs
1,103
C#
//////////////////////////////////////////////////////////////////////////////// // // @module Texture Packer Plugin for Unity3D // @author Osipov Stanislav lacost.st@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class TexturePackerEditor : EditorWindow { private TexturePackerAtlasEditor _atlasEditor; public static bool IsCtrlPressed = false; public static bool isShiftPressed = false; //-------------------------------------- // INITIALIZE //-------------------------------------- [MenuItem("Window/Texture Packer")] public static void init() { EditorWindow.GetWindow<TexturePackerEditor>(); } //-------------------------------------- // PUBLIC METHODS //-------------------------------------- void OnGUI() { title = "Texture Packer"; atlasEditor.render(); processInput (); } //-------------------------------------- // GET / SET //-------------------------------------- private TPAtlas getAtlas(string atlasName) { string path = TPAtlasesData.getAtlasPath(atlasName); return TPackManager.getAtlas(path); } private TexturePackerAtlasEditor atlasEditor { get { if(_atlasEditor == null) { _atlasEditor = new TexturePackerAtlasEditor (); _atlasEditor.editor = this; } return _atlasEditor; } } //-------------------------------------- // EVENTS //-------------------------------------- //-------------------------------------- // PRIVATE METHODS //-------------------------------------- private void processInput() { Event e = Event.current;; if (e.type == EventType.MouseDown) { Vector2 pos = Event.current.mousePosition; pos.y -= TexturePackerStyles.TOOLBAR_HEIGHT; if(Event.current.button == 0) { atlasEditor.OnLeftMouseClick (pos); } if(Event.current.button == 1) { atlasEditor.OnRightMouseClick (pos); } } isShiftPressed = e.shift; IsCtrlPressed = e.command || e.control; } }
19.183486
81
0.499283
[ "Apache-2.0" ]
eaheckert/Asteroid
Assets/Extensions/TexturePacker/TPCore/Editor/TexturePackerEditor/TexturePackerEditor.cs
2,093
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Challenge2_Library { public class ClaimRepo { // FIELD to use in CRUD methods private Queue<Claim> _queuOfClaims = new Queue<Claim>(); //Functions needed - 1- Create/Add, 2- Read/Show list of claims, 3- Update/Pull Claim from top of Queu //CRUD //Create(ADD) new Claim public void AddClaimToQueue(Claim newClaim) { _queuOfClaims.Enqueue(newClaim); } //Read //Display the LIST of CLAIMs public Queue<Claim> ShowQueueofClaims() { return _queuOfClaims; } //Update //Update Claim from List - functionality not required //Delete //Remove Claim from List - functionality not required //Helper Methods //Get next CLAIM from Queue -- > in console (dequeue or peek) // Below can be used to give a total of entries in queue since there is not indexing ability for queues: // int claimCount= queueOfClaims.ToArray().ToList().IndexOf(claim); } }
23.333333
112
0.616807
[ "Unlicense", "MIT" ]
JoshuaCHartman/GoldBadge_Challenges
Challenge2_Library/ClaimRepo.cs
1,192
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Compass : MonoBehaviour { private RectTransform _rectTransform; private Camera _camera; private float _first; // Start is called before the first frame update void Start() { _rectTransform = GetComponent<RectTransform>(); _camera = Camera.main; _first = transform.eulerAngles.z; } private void Rotate() { _rectTransform.rotation = Quaternion.Euler(0, 0, -_camera.transform.eulerAngles.y + _first); } // Update is called once per frame void Update() { Rotate(); } }
20.896552
94
0.712871
[ "Unlicense" ]
kurokurogamer/MAKINAS
MACHINA/Assets/Scripts/Compass.cs
608
C#
using TMPro; using UnityEngine; using UnityEngine.Events; using UnitySceneLoaderManager; namespace SonarSpaceship.Controllers { public class ProfileNameInputFieldUIControllerScript : MonoBehaviour, IProfileNameInputFieldUIController { [SerializeField] private TMP_InputField profileNameInputField = default; [SerializeField] private UnityEvent onProfileNameInputFailed = default; [SerializeField] private UnityEvent onProfileNameInputSucceeded = default; public TMP_InputField ProfileNameInputField { get => profileNameInputField; set => profileNameInputField = value; } public event ProfileNameInputFailedDelegate OnProfileNameInputFailed; public event ProfileNameInputSucceededDelegate OnProfileNameInputSucceeded; private void InvokeProfileNameInputFailedEvent() { if (onProfileNameInputFailed != null) { onProfileNameInputFailed.Invoke(); } OnProfileNameInputFailed?.Invoke(); } public void CreateNewProfile() { if (profileNameInputField) { string profile_name = profileNameInputField.text.Trim(); if (string.IsNullOrEmpty(profile_name)) { InvokeProfileNameInputFailedEvent(); } else { Profiles.CreateNewProfile(GameManager.SelectedProfileIndex, profile_name); GameManager.ReloadSelectedProfile(); if (onProfileNameInputSucceeded != null) { onProfileNameInputSucceeded.Invoke(); } OnProfileNameInputSucceeded?.Invoke(profile_name); SceneLoaderManager.LoadScenes("LevelSelectionMenuScene"); } } else { InvokeProfileNameInputFailedEvent(); } } } }
31.5
108
0.589226
[ "MIT" ]
BigETI/SonarSpaceship
Assets/SonarSpaceship/Scripts/Controllers/ProfileNameInputFieldUIControllerScript.cs
2,081
C#
using System; using Nirvana.Configuration; using Nirvana.CQRS; namespace TechFu.Nirvana.EventStoreSample.Services.Shared.Services.Infrastructure.UiNotifications { [InfrastructureRoot(typeof(TestUiEvent))] public class TestUiEvent : UiEvent<TestUiEvent> { public string Message { get; set; } public override Guid AggregateRoot => NirvanaSetup.ApplicationLevelViewModelKey; } }
31.461538
97
0.762836
[ "MIT" ]
nirvana-framework/Samples
src/EventStore/TechFu.Nirvana.EventStoreSample.Services/Services/Infrastructure/UiNotifications/TestUiEvent.cs
411
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 globalaccelerator-2018-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.GlobalAccelerator.Model { /// <summary> /// Container for the parameters to the ListCustomRoutingListeners operation. /// List the listeners for a custom routing accelerator. /// </summary> public partial class ListCustomRoutingListenersRequest : AmazonGlobalAcceleratorRequest { private string _acceleratorArn; private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property AcceleratorArn. /// <para> /// The Amazon Resource Name (ARN) of the accelerator to list listeners for. /// </para> /// </summary> [AWSProperty(Required=true, Max=255)] public string AcceleratorArn { get { return this._acceleratorArn; } set { this._acceleratorArn = value; } } // Check to see if AcceleratorArn property is set internal bool IsSetAcceleratorArn() { return this._acceleratorArn != null; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The number of listener objects that you want to return with this call. The default /// value is 10. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The token for the next set of results. You receive this token from a previous call. /// </para> /// </summary> [AWSProperty(Max=255)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
31.08
115
0.616152
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/GlobalAccelerator/Generated/Model/ListCustomRoutingListenersRequest.cs
3,108
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System.Globalization; using System.Linq; using System.Runtime.Caching; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Sportradar.OddsFeed.SDK.Common.Internal; using Sportradar.OddsFeed.SDK.Entities.REST.Internal.Caching; using Sportradar.OddsFeed.SDK.Entities.REST.Internal.Caching.Events; using Sportradar.OddsFeed.SDK.Test.Shared; namespace Sportradar.OddsFeed.SDK.Entities.REST.Test { [TestClass] public class SportEventCacheItemTests { const string SportEventSummary = "GetSportEventSummaryAsync"; const string SportEventFixture = "GetSportEventFixtureAsync"; private SportEventCache _sportEventCache; private MemoryCache _memoryCache; private TestTimer _timer; private CacheManager _cacheManager; private TestDataRouterManager _dataRouterManager; [TestInitialize] public void Init() { _memoryCache = new MemoryCache("sportEventCache"); _cacheManager = new CacheManager(); _dataRouterManager = new TestDataRouterManager(_cacheManager); _timer = new TestTimer(false); _sportEventCache = new SportEventCache(_memoryCache, _dataRouterManager, new SportEventCacheItemFactory(_dataRouterManager, new SemaphorePool(5), TestData.Cultures.First(), new MemoryCache("FixtureTimestampCache")), _timer, TestData.Cultures, _cacheManager); } [TestMethod] public void fixture_provider_is_called_only_once_for_each_locale() { var cacheItem = (IMatchCI) _sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetBookingStatusAsync(); await cacheItem.GetScheduledAsync(); await cacheItem.GetScheduledEndAsync(); await cacheItem.GetCompetitorsIdsAsync(TestData.Cultures); await cacheItem.GetTournamentRoundAsync(TestData.Cultures); await cacheItem.GetSeasonAsync(TestData.Cultures); await cacheItem.GetTournamentIdAsync(); await cacheItem.GetVenueAsync(TestData.Cultures); await cacheItem.GetFixtureAsync(TestData.Cultures); await cacheItem.GetReferenceIdsAsync(); }); Task.WaitAll(task); Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly {TestData.Cultures.Count} times."); Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly {TestData.Cultures.Count} times."); } [TestMethod] public void details_provider_is_called_only_once_for_each_locale() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var cultures = new[] {new CultureInfo("en")}; var task = Task.Run(async () => { await cacheItem.GetConditionsAsync(cultures); await cacheItem.GetConditionsAsync(cultures); await cacheItem.GetConditionsAsync(cultures); }); Task.WaitAll(task); Assert.AreEqual(cultures.Length, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly {cultures.Length} times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void get_booking_status_calls_provider_with_default_locale() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetBookingStatusAsync(); await cacheItem.GetVenueAsync(new[] { new CultureInfo("de") }); }); Task.WaitAll(task); Assert.AreEqual(1, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 1 times."); Assert.AreEqual(1, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 1 times."); } [TestMethod] public void get_booking_status_calls_provider_calls_only_once() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetBookingStatusAsync(); await cacheItem.GetVenueAsync(TestData.Cultures); }); Task.WaitAll(task); Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly {TestData.Cultures.Count} times."); Assert.AreEqual(1, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 1 times."); } [TestMethod] public void get_schedule_async_calls_provider_with_default_locale() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetScheduledAsync(); await cacheItem.GetVenueAsync(new[] { new CultureInfo("de") }); }); Task.WaitAll(task); Assert.AreEqual(2, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 2 times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void get_schedule_end_async_calls_provider_with_default_locale() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetScheduledEndAsync(); await cacheItem.GetVenueAsync(new[] { new CultureInfo("de") }); }); Task.WaitAll(task); Assert.AreEqual(2, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 2 times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void get_tournament_id_async_calls_provider_with_default_locale() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetTournamentIdAsync(); await cacheItem.GetVenueAsync(new[] { new CultureInfo("de") }); }); Task.WaitAll(task); Assert.AreEqual(2, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 2 times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void number_of_calls_to_fixture_provider_is_equal_to_number_of_locals_when_accessing_the_same_property() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetVenueAsync(TestData.Cultures); }); Task.WaitAll(task); Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly {TestData.Cultures.Count} times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void number_of_calls_to_summary_provider_is_equal_number_of_locals() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetVenueAsync(new[] { new CultureInfo("en") }); await cacheItem.GetVenueAsync(new[] { new CultureInfo("de") }); await cacheItem.GetVenueAsync(new[] { new CultureInfo("fr") }); }); Task.WaitAll(task); Assert.AreEqual(3, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 3 times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void number_of_calls_to_summary_provider_for_non_translatable_property() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.FetchSportEventStatusAsync(); await cacheItem.FetchSportEventStatusAsync(); await cacheItem.FetchSportEventStatusAsync(); }); Task.WaitAll(task); Assert.AreEqual(3, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 1 times."); Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 0 times."); } [TestMethod] public void number_of_calls_to_fixture_provider_is_equal_to_number_of_locals_when_accessing_different_properties() { var cacheItem = (IMatchCI)_sportEventCache.GetEventCacheItem(TestData.EventId); var task = Task.Run(async () => { await cacheItem.GetVenueAsync(new[] { new CultureInfo("en") }); await cacheItem.GetFixtureAsync(new[] { new CultureInfo("de") }); await cacheItem.GetTournamentRoundAsync(new[] { new CultureInfo("fr") }); }); Task.WaitAll(task); Assert.AreEqual(2, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 2 times."); Assert.AreEqual(1, _dataRouterManager.GetCallCount(SportEventFixture), $"{SportEventFixture} should be called exactly 1 times."); } } }
44.751037
270
0.6586
[ "Apache-2.0" ]
Honore-Gaming/UnifiedOddsSdkNetCore
src/Tests/Sportradar.OddsFeed.SDK.Entities.REST.Test/SportEventCacheItemTests.cs
10,787
C#
// <copyright file="GoogleSignInImpl.cs" company="Google Inc."> // Copyright (C) 2017 Google 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. // </copyright> namespace Google.Impl { using System; using System.Collections.Generic; using System.Runtime.InteropServices; internal class GoogleSignInImpl : BaseObject, ISignInImpl { #if UNITY_ANDROID private const string DllName = "native-googlesignin"; #else private const string DllName = "__Internal"; #endif internal GoogleSignInImpl(GoogleSignInConfiguration configuration) : base(GoogleSignIn_Create(GetPlayerActivity())) { if (configuration != null) { List<string> scopes = new List<string>(); if (configuration.AdditionalScopes != null) { scopes.AddRange(configuration.AdditionalScopes); } GoogleSignIn_Configure(SelfPtr(), configuration.UseGameSignIn, configuration.WebClientId, configuration.RequestAuthCode, configuration.ForceTokenRefresh, configuration.RequestEmail, configuration.RequestIdToken, configuration.HidePopups, scopes.ToArray(), scopes.Count, configuration.AccountName); } } /// <summary>Enables/Disables verbose logging to help troubleshooting</summary> public void EnableDebugLogging(bool flag) { GoogleSignIn_EnableDebugLogging(SelfPtr(), flag); } /// <summary> /// Starts the authentication process. /// </summary> /// <remarks> /// The authenication process is started and may display account picker /// popups and consent prompts based on the state of authentication and /// the requested elements. /// </remarks> public Future<GoogleSignInUser> SignIn() { IntPtr nativeFuture = GoogleSignIn_SignIn(SelfPtr()); return new Future<GoogleSignInUser>(new NativeFuture(nativeFuture)); } public bool SignInCanBeSilent { get { return GoogleSignIn_CanBeSilent(SelfPtr()); } } /// <summary> /// Starts the authentication process. /// </summary> /// <remarks> /// The authenication process is started and may display account picker /// popups and consent prompts based on the state of authentication and /// the requested elements. /// </remarks> public Future<GoogleSignInUser> SignInSilently() { IntPtr nativeFuture = GoogleSignIn_SignInSilently(SelfPtr()); return new Future<GoogleSignInUser>(new NativeFuture(nativeFuture)); } /// <summary> /// Signs out the User. /// </summary> public void SignOut() { GoogleSignIn_Signout(SelfPtr()); } /// <summary> /// Disconnects the user from the application and revokes all consent. /// </summary> public void Disconnect() { GoogleSignIn_Disconnect(SelfPtr()); } /// <summary> /// Creates an instance of the native Google Sign-In implementation. /// </summary> /// <remarks> /// For Android this must be the JNI raw object for the parentActivity. /// For iOS it is ignored. /// </remarks> /// <returns>The pointer to the instance.</returns> /// <param name="data">Data used in creating the instance.</param> [DllImport(DllName)] static extern IntPtr GoogleSignIn_Create(IntPtr data); [DllImport(DllName)] static extern void GoogleSignIn_EnableDebugLogging(HandleRef self, bool flag); [DllImport(DllName)] static extern bool GoogleSignIn_Configure(HandleRef self, bool useGameSignIn, string webClientId, bool requestAuthCode, bool forceTokenRefresh, bool requestEmail, bool requestIdToken, bool hidePopups, string[] additionalScopes, int scopeCount, string accountName); [DllImport(DllName)] static extern IntPtr GoogleSignIn_SignIn(HandleRef self); [DllImport(DllName)] static extern IntPtr GoogleSignIn_SignInSilently(HandleRef self); [DllImport(DllName)] static extern void GoogleSignIn_Signout(HandleRef self); [DllImport(DllName)] static extern void GoogleSignIn_Disconnect(HandleRef self); [DllImport(DllName)] internal static extern void GoogleSignIn_DisposeFuture(HandleRef self); [DllImport(DllName)] internal static extern bool GoogleSignIn_Pending(HandleRef self); [DllImport(DllName)] internal static extern bool GoogleSignIn_CanBeSilent(HandleRef self); [DllImport(DllName)] internal static extern IntPtr GoogleSignIn_Result(HandleRef self); [DllImport(DllName)] internal static extern int GoogleSignIn_Status(HandleRef self); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetServerAuthCode( HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetDisplayName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetEmail(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetFamilyName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetGivenName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetIdToken(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetImageUrl(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); [DllImport(DllName)] internal static extern UIntPtr GoogleSignIn_GetUserId(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); // Gets the Unity player activity. // For iOS, this returns Zero. private static IntPtr GetPlayerActivity() { #if UNITY_ANDROID UnityEngine.AndroidJavaClass jc = new UnityEngine.AndroidJavaClass( "com.unity3d.player.UnityPlayer"); return jc.GetStatic<UnityEngine.AndroidJavaObject>("currentActivity") .GetRawObject(); #else return IntPtr.Zero; #endif } } }
34.761421
83
0.688084
[ "Apache-2.0" ]
strike-zero/google-signin-unity
GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs
6,850
C#
using DCSoft.Common; using DCSoft.Drawing; using DCSoft.Printing; using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace DCSoft.Writer.Controls { /// <summary> /// 支持文本编辑的分页视图控件 /// </summary> [Guid("00012345-6789-ABCD-EF01-234567890004")] [ToolboxItem(false)] [DCInternal] [DocumentComment] [ComVisible(true)] public class TextPageViewControl : PageViewControl { protected bool bool_16 = true; private static Keys[] keys_0 = new Keys[10] { Keys.Left, Keys.Up, Keys.Right, Keys.Down, Keys.Tab, Keys.Return, Keys.ShiftKey, Keys.Back, Keys.BrowserBack, Keys.Control }; private bool bool_17 = false; protected bool bool_18 = true; private bool bool_19 = true; private bool bolCaretCreated = false; public static int int_6 = 2; public static int int_7 = 6; private Rectangle rectangle_2 = Rectangle.Empty; /// <summary> /// 获取或设置一个值,该值指示在控件中按 TAB 键时,是否在控件中键入一个 TAB 字符,而不是按选项卡的顺序将焦点移动到下一个控件。 /// </summary> [Category("Behavior")] [DefaultValue(true)] public bool AcceptsTab { get { return bool_16; } set { bool_16 = value; } } /// <summary> /// 是否强制显示光标而不管控件是否获得输入焦点 /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] public bool ForceShowCaret { get { return bool_17; } set { bool_17 = value; } } /// <summary> /// 移动光标时是否自动滚动到光标区域 /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool MoveCaretWithScroll { get { return bool_18; } set { bool_18 = value; } } /// <summary> /// 当前是否处于插入模式,若处于插入模式,则光标比较细,否则处于改写模式,光标比较粗 /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] public virtual bool InsertMode { get { return bool_19; } set { bool_19 = value; } } /// <summary> /// 光标已经创建标志 /// </summary> [Browsable(false)] public bool CaretCreated => bolCaretCreated; /// <summary> /// 光标控制对象 /// </summary> [DCInternal] [Browsable(false)] public virtual ICaretProvider Caret => null; /// <summary> /// 重写键盘字符处理函数,保证控件能处理一些功能键 /// </summary> /// <param name="keyData">按键数据</param> /// <returns>控件是否能处理按键数据</returns> protected override bool IsInputKey(Keys keyData) { if (keyData != (Keys)131137) { } if (keyData == Keys.Tab && !AcceptsTab) { return base.IsInputKey(keyData); } int num = 0; while (true) { if (num < keys_0.Length) { Keys keys = keys_0[num]; if ((keys & keyData) == keys) { break; } num++; continue; } return base.IsInputKey(keyData); } return true; } [Browsable(false)] [DCInternal] public virtual IImmProvider vmethod_33() { return null; } /// <summary> /// 显示插入点光标 /// </summary> public void ShowCaret() { if (CaretCreated && !rectangle_2.IsEmpty && Caret != null) { Caret.Create(1, rectangle_2.Width, rectangle_2.Height); Caret.SetPos(rectangle_2.X, rectangle_2.Y); Caret.Show(); } } /// <summary> /// 已重载:失去焦点,隐藏光标 /// </summary> /// <param name="e"> /// </param> protected override void OnLostFocus(EventArgs eventArgs_0) { if (CaretCreated && Caret != null) { Caret.Hide(); } base.OnLostFocus(eventArgs_0); } public bool MoveCaretTo(int vLeft, int vTop, int vWidth, int vHeight, int 横向偏移量) { if (base.IsUpdating || !base.IsHandleCreated) { return false; } if (!ForceShowCaret && !Focused) { if (CaretCreated && Caret != null) { Caret.Hide(); } return false; } int num = (int)((float)GraphicsUnitConvert.Convert(vHeight, GraphicsUnit, GraphicsUnit.Pixel) * base.YZoomRate); if (vWidth > 0 && vHeight > 0) { if (Caret == null) { bolCaretCreated = false; } else { bolCaretCreated = Caret.Create(0, vWidth, num); } if (CaretCreated) { if (MoveCaretWithScroll) { method_28(vLeft, vTop, Math.Max(vWidth, 横向偏移量), vHeight); } Point empty = Point.Empty; empty = ViewPointToClient(vLeft, vTop); if (Caret != null) { Caret.SetPos(empty.X, empty.Y); Caret.Show(); } IImmProvider immProvider = vmethod_33(); if (immProvider != null && immProvider.IsImmOpen()) { immProvider.SetImmPos(empty.X, empty.Y); } rectangle_2 = new Rectangle(empty.X, empty.Y, vWidth, num); if (MoveCaretWithScroll) { return true; } } } return false; } public bool MoveTextCaretTo(int left, int bottom, int height, int 横向偏移量) { return MoveCaretTo(left, bottom - height, bool_19 ? int_6 : int_7, height, 横向偏移量); } public void method_58() { if (base.IsHandleCreated) { Caret.Hide(); } } } }
19.364662
115
0.605708
[ "MIT" ]
h1213159982/HDF
Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoft.Writer.Controls/TextPageViewControl.cs
5,613
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 macie2-2020-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Macie2.Model { /// <summary> /// Specifies an S3 bucket to export data classification results to, and the encryption /// settings to use when storing results in that bucket. /// </summary> public partial class S3Destination { private string _bucketName; private string _keyPrefix; private string _kmsKeyArn; /// <summary> /// Gets and sets the property BucketName. /// <para> /// The Amazon Resource Name (ARN) of the bucket. This must be the ARN of an existing /// bucket. /// </para> /// </summary> [AWSProperty(Required=true)] public string BucketName { get { return this._bucketName; } set { this._bucketName = value; } } // Check to see if BucketName property is set internal bool IsSetBucketName() { return this._bucketName != null; } /// <summary> /// Gets and sets the property KeyPrefix. /// <para> /// The path prefix to use in the path to the location in the bucket. This prefix specifies /// where to store classification results in the bucket. /// </para> /// </summary> public string KeyPrefix { get { return this._keyPrefix; } set { this._keyPrefix = value; } } // Check to see if KeyPrefix property is set internal bool IsSetKeyPrefix() { return this._keyPrefix != null; } /// <summary> /// Gets and sets the property KmsKeyArn. /// <para> /// The Amazon Resource Name (ARN) of the AWS Key Management Service master key to use /// for encryption of the exported results. This must be the ARN of an existing KMS key. /// In addition, the key must be in the same AWS Region as the bucket. /// </para> /// </summary> [AWSProperty(Required=true)] public string KmsKeyArn { get { return this._kmsKeyArn; } set { this._kmsKeyArn = value; } } // Check to see if KmsKeyArn property is set internal bool IsSetKmsKeyArn() { return this._kmsKeyArn != null; } } }
31.411765
104
0.607366
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/Macie2/Generated/Model/S3Destination.cs
3,204
C#
using System; using Bunit.TestAssets.SampleComponents; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Bunit.Extensions.WaitForHelpers { public class RenderedFragmentWaitForHelperExtensionsTest : TestContext { public RenderedFragmentWaitForHelperExtensionsTest(ITestOutputHelper testOutput) { Services.AddXunitLogger(testOutput); } [Fact(DisplayName = "WaitForAssertion can wait for multiple renders and changes to occur")] public void Test110() { // Initial state is stopped var cut = RenderComponent<TwoRendersTwoChanges>(); var stateElement = cut.Find("#state"); stateElement.TextContent.ShouldBe("Stopped"); // Clicking 'tick' changes the state, and starts a task cut.Find("#tick").Click(); cut.Find("#state").TextContent.ShouldBe("Started"); // Clicking 'tock' completes the task, which updates the state // This click causes two renders, thus something is needed to await here. cut.Find("#tock").Click(); cut.WaitForAssertion( () => cut.Find("#state").TextContent.ShouldBe("Stopped") ); } [Fact(DisplayName = "WaitForAssertion throws assertion exception after timeout")] public void Test011() { var cut = RenderComponent<Simple1>(); var expected = Should.Throw<WaitForFailedException>(() => cut.WaitForAssertion(() => cut.Markup.ShouldBeEmpty(), TimeSpan.FromMilliseconds(10)) ); expected.Message.ShouldBe(WaitForAssertionHelper.TIMEOUT_MESSAGE); expected.InnerException.ShouldBeOfType<ShouldAssertException>(); } [Fact(DisplayName = "WaitForState throws exception after timeout")] public void Test012() { var cut = RenderComponent<Simple1>(); var expected = Should.Throw<WaitForFailedException>(() => cut.WaitForState(() => string.IsNullOrEmpty(cut.Markup), TimeSpan.FromMilliseconds(100)) ); expected.Message.ShouldBe(WaitForStateHelper.TIMEOUT_BEFORE_PASS); } [Fact(DisplayName = "WaitForState throws exception if statePredicate throws on a later render")] public void Test013() { const string expectedInnerMessage = "INNER MESSAGE"; var cut = RenderComponent<TwoRendersTwoChanges>(); cut.Find("#tick").Click(); cut.Find("#tock").Click(); var expected = Should.Throw<WaitForFailedException>(() => cut.WaitForState(() => { if (cut.Find("#state").TextContent == "Stopped") throw new InvalidOperationException(expectedInnerMessage); return false; }) ); expected.Message.ShouldBe(WaitForStateHelper.EXCEPTION_IN_PREDICATE); expected.InnerException.ShouldBeOfType<InvalidOperationException>() .Message.ShouldBe(expectedInnerMessage); } [Fact(DisplayName = "WaitForState can wait for multiple renders and changes to occur")] public void Test100() { // Initial state is stopped var cut = RenderComponent<TwoRendersTwoChanges>(); var stateElement = cut.Find("#state"); stateElement.TextContent.ShouldBe("Stopped"); // Clicking 'tick' changes the state, and starts a task cut.Find("#tick").Click(); cut.Find("#state").TextContent.ShouldBe("Started"); // Clicking 'tock' completes the task, which updates the state // This click causes two renders, thus something is needed to await here. cut.Find("#tock").Click(); cut.WaitForState(() => cut.Find("#state").TextContent == "Stopped"); cut.Find("#state").TextContent.ShouldBe("Stopped"); } [Fact(DisplayName = "WaitForState can detect async changes to properties in the CUT")] public void Test200() { var cut = RenderComponent<AsyncRenderChangesProperty>(); cut.Instance.Counter.ShouldBe(0); // Clicking 'tick' changes the counter, and starts a task cut.Find("#tick").Click(); cut.Instance.Counter.ShouldBe(1); // Clicking 'tock' completes the task, which updates the counter // This click causes two renders, thus something is needed to await here. cut.Find("#tock").Click(); cut.WaitForState(() => cut.Instance.Counter == 2); cut.Instance.Counter.ShouldBe(2); } } }
32.885246
98
0.715852
[ "MIT" ]
HamedMoghadasi/bUn
tests/bunit.core.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs
4,012
C#
//----------------------------------------------------------------------- // <copyright file="SqlReadJournalProvider.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; using Hocon; namespace Akka.Persistence.Query.Sql { public class SqlReadJournalProvider : IReadJournalProvider { private readonly ExtendedActorSystem _system; private readonly Config _config; public SqlReadJournalProvider(ExtendedActorSystem system, Config config) { _system = system; _config = config; } public IReadJournal GetReadJournal() { return new SqlReadJournal(_system, _config); } } }
31
87
0.554839
[ "Apache-2.0" ]
hueifeng/akka.net
src/contrib/persistence/Akka.Persistence.Query.Sql/SqlReadJournalProvider.cs
932
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class SRequiredSwitch : CVariable { [Ordinal(1)] [RED("requiredSwitchTag")] public CName RequiredSwitchTag { get; set;} [Ordinal(2)] [RED("switchState")] public CEnum<ERequiredSwitchState> SwitchState { get; set;} public SRequiredSwitch(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new SRequiredSwitch(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.111111
123
0.72549
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/SRequiredSwitch.cs
841
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.ExtractInterface { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.ExtractInterface)] internal class ExtractInterfaceCommandHandler : AbstractExtractInterfaceCommandHandler { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ExtractInterfaceCommandHandler(IThreadingContext threadingContext) : base(threadingContext) { } } }
43.592593
194
0.784197
[ "MIT" ]
BertanAygun/roslyn
src/EditorFeatures/CSharp/ExtractInterface/ExtractInterfaceCommandHandler.cs
1,179
C#
// // MustUnderstandBehavior.cs // // Author: Atsushi Enomoto (atsushi@ximian.com) // // Copyright (C) 2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; namespace System.ServiceModel.Description { public class MustUnderstandBehavior : IEndpointBehavior { bool validate; public MustUnderstandBehavior (bool validate) { this.validate = validate; } public bool ValidateMustUnderstand { get { return validate; } set { validate = value; } } void IEndpointBehavior.AddBindingParameters (ServiceEndpoint endpoint, BindingParameterCollection parameters) { throw new NotImplementedException (); } void IEndpointBehavior.ApplyDispatchBehavior (ServiceEndpoint endpoint, EndpointDispatcher dispatcher) { dispatcher.DispatchRuntime.ValidateMustUnderstand = validate; } void IEndpointBehavior.ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime proxy) { proxy.ValidateMustUnderstand = validate; } void IEndpointBehavior.Validate (ServiceEndpoint endpoint) { } } }
32.058824
73
0.761927
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.ServiceModel/System.ServiceModel.Description/MustUnderstandBehavior.cs
2,180
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.XRSDK.Input; using UnityEngine; using UnityEngine.Profiling; using UnityEngine.XR; #if WMR_ENABLED using Unity.XR.WindowsMR; #endif // WMR_ENABLED namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality { /// <summary> /// A Windows Mixed Reality source instance. /// </summary> public abstract class BaseWindowsMixedRealityXRSDKSource : GenericXRSDKController { /// <summary> /// Constructor. /// </summary> protected BaseWindowsMixedRealityXRSDKSource(TrackingState trackingState, Handedness sourceHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null) : base(trackingState, sourceHandedness, inputSource, interactions) { } #if WMR_ENABLED private Vector3 currentPointerPosition = Vector3.zero; private Quaternion currentPointerRotation = Quaternion.identity; private MixedRealityPose currentPointerPose = MixedRealityPose.ZeroIdentity; /// <summary> /// Update spatial pointer and spatial grip data. /// </summary> protected override void UpdatePoseData(MixedRealityInteractionMapping interactionMapping, InputDevice inputDevice) { Profiler.BeginSample("[MRTK] BaseWindowsMixedRealitySource.UpdatePoseData"); Debug.Assert(interactionMapping.AxisType == AxisType.SixDof); base.UpdatePoseData(interactionMapping, inputDevice); // Update the interaction data source switch (interactionMapping.InputType) { case DeviceInputType.SpatialPointer: if (inputDevice.TryGetFeatureValue(WindowsMRUsages.PointerPosition, out currentPointerPosition)) { currentPointerPose.Position = MixedRealityPlayspace.TransformPoint(currentPointerPosition); } if (inputDevice.TryGetFeatureValue(WindowsMRUsages.PointerRotation, out currentPointerRotation)) { currentPointerPose.Rotation = MixedRealityPlayspace.Rotation * currentPointerRotation; } interactionMapping.PoseData = currentPointerPose; // If our value changed raise it. if (interactionMapping.Changed) { // Raise input system event if it's enabled CoreServices.InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, interactionMapping.MixedRealityInputAction, interactionMapping.PoseData); } break; default: Profiler.EndSample(); // UpdatePoseData return; } Profiler.EndSample(); // UpdatePoseData } #endif // WMR_ENABLED } }
40.402597
209
0.653809
[ "MIT" ]
AMUZA668/MixedRealityToolkit-Unity
Assets/MRTK/Providers/WindowsMixedReality/XRSDK/Controllers/BaseWindowsMixedRealityXRSDKSource.cs
3,113
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_CustomTables_FormControls_CustomTableItemSelector { /// <summary> /// pnlUpdate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdate; /// <summary> /// uniSelector control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSAdminControls_UI_UniSelector_UniSelector uniSelector; }
33.0625
84
0.541588
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/CustomTables/FormControls/CustomTableItemSelector.ascx.designer.cs
1,060
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Adv.Class02.Exercise.Entities { public class Student : User, IStudent { public List<int> Grades { get; set; } public void PringGrades() { foreach (int grade in Grades) { Console.WriteLine(grade); } } public override void PrintUser() { Console.WriteLine($"Student: {Name} with username {Username} and average grade of {Grades.Sum() / Grades.Count}"); } } }
19.52
117
0.688525
[ "MIT" ]
sedc-codecademy/skwd8-06-csharpadv
g4/03-Abstracting/Adv.Class01/Adv.Class01.Exercise/Entities/Student.cs
490
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("DefiningClasses_Exercise")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DefiningClasses_Exercise")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e66bec95-a200-4b8a-a6b7-2159118a38d9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.314286
84
0.749273
[ "MIT" ]
mayapeneva/C-Sharp-OOP-Basic
01.DefiningClasses/DefiningClasses_Exercise/Properties/AssemblyInfo.cs
1,379
C#
namespace CDSPracticalTests { using System.Diagnostics.CodeAnalysis; using System.Linq; using CDSPractical; using Xunit; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Unit test class")] public sealed class GenerateListTests { [Fact] public void CanGenerateListOfNumbers() { // Arrange // Act var actual = Questions.GenerateList(0); // Assert Assert.Equal(Enumerable.Range(1, 100), actual); } } }
21.777778
129
0.612245
[ "Apache-2.0" ]
ciprian-vilcan/interview-questions
csharp/CDSPracticalTests/GenerateListTests.cs
588
C#
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see LICENSE */ using System; using System.Collections.Generic; namespace Thinktecture.IdentityModel.Client { public class AuthorizeResponse { public enum ResponseTypes { AuthorizationCode, Token, Error }; public ResponseTypes ResponseType { get; protected set; } public string Raw { get; protected set; } public Dictionary<string, string> Values { get; protected set; } public string Code { get { return TryGet(OAuth2Constants.Code); } } public string AccessToken { get { return TryGet(OAuth2Constants.AccessToken); } } public string IdentityToken { get { return TryGet(OAuth2Constants.IdentityToken); } } public string Error { get { return TryGet(OAuth2Constants.Error); } } public long ExpiresIn { get { var value = TryGet(OAuth2Constants.ExpiresIn); long longValue = 0; long.TryParse(value, out longValue); return longValue; } } public string Scope { get { return TryGet(OAuth2Constants.Scope); } } public string TokenType { get { return TryGet(OAuth2Constants.TokenType); } } public string State { get { return TryGet(OAuth2Constants.State); } } public AuthorizeResponse(string raw) { Raw = raw; Values = new Dictionary<string, string>(); ParseRaw(); } private void ParseRaw() { var queryParameters = new Dictionary<string, string>(); string[] fragments = null; if (Raw.Contains("#")) { fragments = Raw.Split('#'); ResponseType = ResponseTypes.Token; } else if (Raw.Contains("?")) { fragments = Raw.Split('?'); ResponseType = ResponseTypes.AuthorizationCode; } else { throw new InvalidOperationException("Malformed callback URL"); } if (Raw.Contains(OAuth2Constants.Error)) { ResponseType = ResponseTypes.Error; } var qparams = fragments[1].Split('&'); foreach (var param in qparams) { var parts = param.Split('='); if (parts.Length == 2) { Values.Add(parts[0], parts[1]); } else { throw new InvalidOperationException("Malformed callback URL."); } } } private string TryGet(string type) { string value; if (Values.TryGetValue(type, out value)) { return value; } return null; } } }
22.862745
83
0.435678
[ "BSD-3-Clause" ]
BadriL/Thinktecture.IdentityModel
source/Client/AuthorizeResponse.cs
3,500
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("TaskManager.ServiceBus.WinService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TaskManager.ServiceBus.WinService")] [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("fe3a5b21-e346-4607-bbbd-a3cea2b8dfc1")] // 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.891892
84
0.749826
[ "MIT" ]
AxelUser/dis-final-work
TaskManager/TaskManager.ServiceBus.WinService/Properties/AssemblyInfo.cs
1,442
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ajkControls { public partial class TextView : UserControl { public TextView() { InitializeComponent(); } private StringBuilder sBuilder = new StringBuilder(); public override string Text { set { sBuilder.Clear(); AppendText(value); } get { return sBuilder.ToString(); } } public void AppendText(string text) { sBuilder.Append(text); dBDrawBox.Invalidate(); } private void dBDrawBox_DoubleBufferedPaint(PaintEventArgs e) { System.Windows.Forms.TextRenderer.DrawText(e.Graphics, Text, Font, new Point(0, 0), Color.Gray); } } }
22.106383
108
0.564004
[ "MIT" ]
ajkfds/ajkControls
TextView/TextView.cs
1,041
C#
using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; namespace RogueGame.GameSystems.Items { public class ItemTemplateLoader: IItemTemplateLoader { private const string ItemTemplateXml = "Content\\ItemTemplates.xml"; public Dictionary<string, ItemTemplate> Load() { var serializer = new XmlSerializer(typeof(ItemTemplates)); using var file = System.IO.File.OpenRead(ItemTemplateXml); return ((List<ItemTemplate>)serializer.Deserialize(file)) .ToDictionary( item => item.Id, item => item); } } [XmlRoot("ItemTemplates")] public class ItemTemplates : List<ItemTemplate> { } }
31.333333
76
0.636968
[ "MIT" ]
bzz445/RogueGame
GameSystems/Items/ItemTemplateLoader.cs
752
C#
using Assistant.Logging; using Assistant.Logging.Interfaces; using System.Threading.Tasks; using Unosquare.RaspberryIO; using static Assistant.Logging.Enums; namespace Assistant.Gpio { /// <summary> /// This class is only allowed to be used if we have the Generic driver (RaspberryIO driver) /// </summary> public class BluetoothController { private readonly ILogger Logger = new Logger("PI-BLUETOOTH"); private readonly PiController? PiController; public bool IsBluetoothControllerInitialized { get; private set; } public BluetoothController(Gpio gpioCore) => PiController = gpioCore.GpioController; public BluetoothController InitBluetoothController() { if (PiController == null || PiController.IsAllowedToExecute) { IsBluetoothControllerInitialized = false; return this; } if (!PiController.IsControllerProperlyInitialized) { return this; } if (PiController.GetPinController()?.CurrentGpioDriver != PiController.EGPIO_DRIVERS.RaspberryIODriver) { IsBluetoothControllerInitialized = false; return this; } IsBluetoothControllerInitialized = true; return this; } public async Task<bool> FetchControllers() { if (!IsBluetoothControllerInitialized) { return false; } Logger.Log("Fetching blue-tooth controllers..."); foreach (string i in await Pi.Bluetooth.ListControllers().ConfigureAwait(false)) { Logger.Log($"FOUND > {i}"); } Logger.Log("Finished fetching controllers."); return true; } public async Task<bool> FetchDevices() { if (!IsBluetoothControllerInitialized) { return false; } Logger.Log("Fetching blue-tooth devices..."); foreach (string dev in await Pi.Bluetooth.ListDevices().ConfigureAwait(false)) { Logger.Log($"FOUND > {dev}"); } Logger.Log("Finished fetching devices."); return true; } public async Task<bool> TurnOnBluetooth() { if (!IsBluetoothControllerInitialized) { return false; } if (await Pi.Bluetooth.PowerOn().ConfigureAwait(false)) { Logger.Log("Blue-tooth has been turned on."); return true; } Logger.Log("Failed to turn on blue-tooth.", LogLevels.Warn); return false; } public async Task<bool> TurnOffBluetooth() { if (!IsBluetoothControllerInitialized) { return false; } if (await Pi.Bluetooth.PowerOff().ConfigureAwait(false)) { Logger.Log("Blue-tooth has been turned off."); return true; } Logger.Log("Failed to turn off blue-tooth.", LogLevels.Warn); return false; } } }
25.484848
108
0.70868
[ "MIT" ]
k3nw4y/HomeAssistant
Assistant.Gpio/BluetoothController.cs
2,523
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.Add, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssDataDisk", SupportsShouldProcess = true)] [OutputType(typeof(PSVirtualMachineScaleSet))] public partial class AddAzureRmVmssDataDiskCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public string Name { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public int Lun { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public CachingTypes? Caching { get; set; } [Parameter( Mandatory = false)] public SwitchParameter WriteAccelerator { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string CreateOption { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int DiskSizeGB { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] [PSArgumentCompleter("Standard_LRS", "Premium_LRS", "StandardSSD_LRS", "UltraSSD_LRS")] public string StorageAccountType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string DiskEncryptionSetId { get; set; } protected override void ProcessRecord() { if (ShouldProcess("VirtualMachineScaleSet", "Add")) { Run(); } } private void Run() { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile(); } // DataDisks if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks = new List<VirtualMachineScaleSetDataDisk>(); } var vDataDisks = new VirtualMachineScaleSetDataDisk(); vDataDisks.Name = this.IsParameterBound(c => c.Name) ? this.Name : null; vDataDisks.Lun = this.Lun; vDataDisks.Caching = this.IsParameterBound(c => c.Caching) ? this.Caching : (CachingTypes?)null; vDataDisks.WriteAcceleratorEnabled = this.WriteAccelerator.IsPresent; vDataDisks.CreateOption = this.IsParameterBound(c => c.CreateOption) ? this.CreateOption : null; vDataDisks.DiskSizeGB = this.IsParameterBound(c => c.DiskSizeGB) ? this.DiskSizeGB : (int?)null; if (this.IsParameterBound(c => c.StorageAccountType)) { // ManagedDisk vDataDisks.ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters(); vDataDisks.ManagedDisk.StorageAccountType = this.StorageAccountType; } if (this.IsParameterBound(c => c.DiskEncryptionSetId)) { if (vDataDisks.ManagedDisk == null) { vDataDisks.ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters(); } // DiskEncryptionSet vDataDisks.ManagedDisk.DiskEncryptionSet = new DiskEncryptionSetParameters(); vDataDisks.ManagedDisk.DiskEncryptionSet.Id = this.DiskEncryptionSetId; } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Add(vDataDisks); WriteObject(this.VirtualMachineScaleSet); } } }
40.496552
137
0.631812
[ "MIT" ]
Cesarfgc/azure-powershell
src/Compute/Compute/Generated/VirtualMachineScaleSet/Config/AddAzureRmVmssDataDiskCommand.cs
5,728
C#
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security; // 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: AssemblyCompany("umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyTitle("UmbracoExamine")] [assembly: AssemblyDescription("Umbraco index & search providers based on the Examine model using Lucene.NET 2.9.2")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("UmbracoExamine")] // 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("31c5b048-cfa8-49b4-8983-bdba0f99eef5")] [assembly: NeutralResourcesLanguage("en-US")] //NOTE: WE cannot make change the major version to be the same as Umbraco because of backwards compatibility, however we // will make the minor version the same as the umbraco version [assembly: AssemblyVersion("0.6.0.*")] [assembly: AssemblyFileVersion("0.6.0.*")] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Umbraco.Tests")]
42.594595
122
0.760787
[ "MIT" ]
AndyButland/Umbraco-CMS
src/UmbracoExamine/Properties/AssemblyInfo.cs
1,579
C#
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Linq.Expressions; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { public class CqlUpdate : CqlCommand { private readonly MapperFactory _mapperFactory; internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData, MapperFactory mapperFactory) : base(expression, table, stmtFactory, pocoData) { _mapperFactory = mapperFactory; } protected internal override string GetCql(out object[] values) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); return visitor.GetUpdate(Expression, out values, _ttl, _timestamp, _mapperFactory); } public override string ToString() { object[] _; return GetCql(out _); } } }
33.822222
141
0.679369
[ "Apache-2.0" ]
CassOnMars/csharp-driver
src/Cassandra/Data/Linq/CqlUpdate.cs
1,522
C#
using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Sfa.Tl.ResultsAndCertification.Common.Helpers; using Sfa.Tl.ResultsAndCertification.Web.ViewModel.Result; using System.Linq; using Xunit; using BreadcrumbContent = Sfa.Tl.ResultsAndCertification.Web.Content.ViewComponents.Breadcrumb; namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.ResultControllerTests.UploadResultsFileGet { public class When_Action_Called : TestSetup { public override void Given() { } [Fact] public void Then_Returns_Expected_Results() { Result.Should().NotBeNull(); (Result as ViewResult).Model.Should().NotBeNull(); var model = (Result as ViewResult).Model as UploadResultsRequestViewModel; model.Should().NotBeNull(); model.Breadcrumb.Should().NotBeNull(); model.Breadcrumb.BreadcrumbItems.Should().NotBeNull(); model.Breadcrumb.BreadcrumbItems.Count().Should().Be(3); model.Breadcrumb.BreadcrumbItems[0].RouteName.Should().Be(RouteConstants.Home); model.Breadcrumb.BreadcrumbItems[0].DisplayName.Should().Be(BreadcrumbContent.Home); model.Breadcrumb.BreadcrumbItems[1].RouteName.Should().Be(RouteConstants.ResultsDashboard); model.Breadcrumb.BreadcrumbItems[1].DisplayName.Should().Be(BreadcrumbContent.Result_Dashboard); model.Breadcrumb.BreadcrumbItems[2].DisplayName.Should().Be(BreadcrumbContent.Upload_Results_File); } } }
43.857143
111
0.718567
[ "MIT" ]
SkillsFundingAgency/tl-result-and-certification
src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/ResultControllerTests/UploadResultsFileGet/When_Action_Called.cs
1,537
C#
/* * Overture API * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Yaksa.OrckestraCommerce.Client.Client.OpenAPIDateConverter; namespace Yaksa.OrckestraCommerce.Client.Model { /// <summary> /// InventorySchedule /// </summary> [DataContract(Name = "InventorySchedule")] public partial class InventorySchedule : IEquatable<InventorySchedule>, IValidatableObject { /// <summary> /// The status of product inventory /// </summary> /// <value>The status of product inventory</value> [JsonConverter(typeof(StringEnumConverter))] public enum InventoryStatusEnum { /// <summary> /// Enum InStock for value: InStock /// </summary> [EnumMember(Value = "InStock")] InStock = 1, /// <summary> /// Enum OutOfStock for value: OutOfStock /// </summary> [EnumMember(Value = "OutOfStock")] OutOfStock = 2, /// <summary> /// Enum PreOrder for value: PreOrder /// </summary> [EnumMember(Value = "PreOrder")] PreOrder = 3, /// <summary> /// Enum BackOrder for value: BackOrder /// </summary> [EnumMember(Value = "BackOrder")] BackOrder = 4 } /// <summary> /// The status of product inventory /// </summary> /// <value>The status of product inventory</value> [DataMember(Name = "inventoryStatus", EmitDefaultValue = false)] public InventoryStatusEnum? InventoryStatus { get; set; } /// <summary> /// Initializes a new instance of the <see cref="InventorySchedule" /> class. /// </summary> [JsonConstructorAttribute] protected InventorySchedule() { } /// <summary> /// Initializes a new instance of the <see cref="InventorySchedule" /> class. /// </summary> /// <param name="id">The unique identifier of the entity. (required).</param> /// <param name="propertyBag">propertyBag.</param> /// <param name="dateRange">dateRange.</param> /// <param name="inventoryLocationId">The inventory location identifier.</param> /// <param name="inventoryStatus">The status of product inventory.</param> /// <param name="lastModified">The last modified date time of product inventory.</param> /// <param name="lastModifiedBy">The identifier of the operator who last modified the entity.</param> /// <param name="sku">The associated product sku.</param> public InventorySchedule(string id = default(string), Dictionary<string, Object> propertyBag = default(Dictionary<string, Object>), DateRange dateRange = default(DateRange), string inventoryLocationId = default(string), InventoryStatusEnum? inventoryStatus = default(InventoryStatusEnum?), DateTime lastModified = default(DateTime), string lastModifiedBy = default(string), string sku = default(string)) { // to ensure "id" is required (not null) this.Id = id ?? throw new ArgumentNullException("id is a required property for InventorySchedule and cannot be null"); this.PropertyBag = propertyBag; this.DateRange = dateRange; this.InventoryLocationId = inventoryLocationId; this.InventoryStatus = inventoryStatus; this.LastModified = lastModified; this.LastModifiedBy = lastModifiedBy; this.Sku = sku; } /// <summary> /// The unique identifier of the entity. /// </summary> /// <value>The unique identifier of the entity.</value> [DataMember(Name = "id", IsRequired = true, EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets PropertyBag /// </summary> [DataMember(Name = "propertyBag", EmitDefaultValue = false)] public Dictionary<string, Object> PropertyBag { get; set; } /// <summary> /// Gets or Sets DateRange /// </summary> [DataMember(Name = "dateRange", EmitDefaultValue = false)] public DateRange DateRange { get; set; } /// <summary> /// The inventory location identifier /// </summary> /// <value>The inventory location identifier</value> [DataMember(Name = "inventoryLocationId", EmitDefaultValue = false)] public string InventoryLocationId { get; set; } /// <summary> /// The last modified date time of product inventory /// </summary> /// <value>The last modified date time of product inventory</value> [DataMember(Name = "lastModified", EmitDefaultValue = false)] public DateTime LastModified { get; set; } /// <summary> /// The identifier of the operator who last modified the entity /// </summary> /// <value>The identifier of the operator who last modified the entity</value> [DataMember(Name = "lastModifiedBy", EmitDefaultValue = false)] public string LastModifiedBy { get; set; } /// <summary> /// The associated product sku /// </summary> /// <value>The associated product sku</value> [DataMember(Name = "sku", EmitDefaultValue = false)] public string Sku { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InventorySchedule {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PropertyBag: ").Append(PropertyBag).Append("\n"); sb.Append(" DateRange: ").Append(DateRange).Append("\n"); sb.Append(" InventoryLocationId: ").Append(InventoryLocationId).Append("\n"); sb.Append(" InventoryStatus: ").Append(InventoryStatus).Append("\n"); sb.Append(" LastModified: ").Append(LastModified).Append("\n"); sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as InventorySchedule); } /// <summary> /// Returns true if InventorySchedule instances are equal /// </summary> /// <param name="input">Instance of InventorySchedule to be compared</param> /// <returns>Boolean</returns> public bool Equals(InventorySchedule input) { if (input == null) return false; return ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.PropertyBag == input.PropertyBag || this.PropertyBag != null && input.PropertyBag != null && this.PropertyBag.SequenceEqual(input.PropertyBag) ) && ( this.DateRange == input.DateRange || (this.DateRange != null && this.DateRange.Equals(input.DateRange)) ) && ( this.InventoryLocationId == input.InventoryLocationId || (this.InventoryLocationId != null && this.InventoryLocationId.Equals(input.InventoryLocationId)) ) && ( this.InventoryStatus == input.InventoryStatus || this.InventoryStatus.Equals(input.InventoryStatus) ) && ( this.LastModified == input.LastModified || (this.LastModified != null && this.LastModified.Equals(input.LastModified)) ) && ( this.LastModifiedBy == input.LastModifiedBy || (this.LastModifiedBy != null && this.LastModifiedBy.Equals(input.LastModifiedBy)) ) && ( this.Sku == input.Sku || (this.Sku != null && this.Sku.Equals(input.Sku)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.PropertyBag != null) hashCode = hashCode * 59 + this.PropertyBag.GetHashCode(); if (this.DateRange != null) hashCode = hashCode * 59 + this.DateRange.GetHashCode(); if (this.InventoryLocationId != null) hashCode = hashCode * 59 + this.InventoryLocationId.GetHashCode(); hashCode = hashCode * 59 + this.InventoryStatus.GetHashCode(); if (this.LastModified != null) hashCode = hashCode * 59 + this.LastModified.GetHashCode(); if (this.LastModifiedBy != null) hashCode = hashCode * 59 + this.LastModifiedBy.GetHashCode(); if (this.Sku != null) hashCode = hashCode * 59 + this.Sku.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
40.531915
411
0.562992
[ "MIT" ]
Yaksa-ca/eShopOnWeb
src/Yaksa.OrckestraCommerce.Client/Model/InventorySchedule.cs
11,430
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2018-06-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DefaultCacheBehavior Object /// </summary> public class DefaultCacheBehaviorUnmarshaller : IUnmarshaller<DefaultCacheBehavior, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public DefaultCacheBehavior Unmarshall(XmlUnmarshallerContext context) { DefaultCacheBehavior unmarshalledObject = new DefaultCacheBehavior(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("AllowedMethods", targetDepth)) { var unmarshaller = AllowedMethodsUnmarshaller.Instance; unmarshalledObject.AllowedMethods = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Compress", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.Compress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DefaultTTL", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.DefaultTTL = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FieldLevelEncryptionId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.FieldLevelEncryptionId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ForwardedValues", targetDepth)) { var unmarshaller = ForwardedValuesUnmarshaller.Instance; unmarshalledObject.ForwardedValues = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LambdaFunctionAssociations", targetDepth)) { var unmarshaller = LambdaFunctionAssociationsUnmarshaller.Instance; unmarshalledObject.LambdaFunctionAssociations = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MaxTTL", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.MaxTTL = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MinTTL", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.MinTTL = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SmoothStreaming", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.SmoothStreaming = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TargetOriginId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.TargetOriginId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TrustedSigners", targetDepth)) { var unmarshaller = TrustedSignersUnmarshaller.Instance; unmarshalledObject.TrustedSigners = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ViewerProtocolPolicy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ViewerProtocolPolicy = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } private static DefaultCacheBehaviorUnmarshaller _instance = new DefaultCacheBehaviorUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DefaultCacheBehaviorUnmarshaller Instance { get { return _instance; } } } }
43.230263
115
0.551058
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/DefaultCacheBehaviorUnmarshaller.cs
6,571
C#
using System; using System.Collections.Generic; using log4net; namespace CKAN.NetKAN.Services { internal sealed class CachingHttpService : IHttpService { private readonly NetFileCache _cache; private HashSet<Uri> _requestedURLs = new HashSet<Uri>(); private bool _overwriteCache = false; private Dictionary<Uri, StringCacheEntry> _stringCache = new Dictionary<Uri, StringCacheEntry>(); // Re-use string value URLs within 2 minutes private static readonly TimeSpan stringCacheLifetime = new TimeSpan(0, 2, 0); public CachingHttpService(NetFileCache cache, bool overwrite = false) { _cache = cache; _overwriteCache = overwrite; } public string DownloadPackage(Uri url, string identifier, DateTime? updated) { if (_overwriteCache && !_requestedURLs.Contains(url)) { // Discard cached file if command line says so, // but only the first time in each run _cache.Remove(url); } _requestedURLs.Add(url); var cachedFile = _cache.GetCachedFilename(url, updated); if (!string.IsNullOrWhiteSpace(cachedFile)) { return cachedFile; } else { var downloadedFile = Net.Download(url); string extension; switch (FileIdentifier.IdentifyFile(downloadedFile)) { case FileType.ASCII: extension = "txt"; break; case FileType.GZip: extension = "gz"; break; case FileType.Tar: extension = "tar"; break; case FileType.TarGz: extension = "tar.gz"; break; case FileType.Zip: extension = "zip"; string invalidReason; if (!NetFileCache.ZipValid(downloadedFile, out invalidReason)) { log.Debug($"{downloadedFile} is not a valid ZIP file: {invalidReason}"); throw new Kraken($"{url} is not a valid ZIP file: {invalidReason}"); } break; default: extension = "ckan-package"; break; } return _cache.Store( url, downloadedFile, string.Format("netkan-{0}.{1}", identifier, extension), move: true ); } } public string DownloadText(Uri url) { return TryGetCached(url, () => Net.DownloadText(url)); } public string DownloadText(Uri url, string authToken, string mimeType = null) { return TryGetCached(url, () => Net.DownloadText(url, authToken, mimeType)); } private string TryGetCached(Uri url, Func<string> uncached) { if (_stringCache.TryGetValue(url, out StringCacheEntry entry)) { if (DateTime.Now - entry.Timestamp < stringCacheLifetime) { // Re-use recent cached request of this URL return entry.Value; } else { // Too old, purge it _stringCache.Remove(url); } } string val = uncached(); _stringCache.Add(url, new StringCacheEntry() { Value = val, Timestamp = DateTime.Now }); return val; } public IEnumerable<Uri> RequestedURLs { get { return _requestedURLs; } } public void ClearRequestedURLs() { _requestedURLs?.Clear(); } private static readonly ILog log = LogManager.GetLogger(typeof(CachingHttpService)); } public class StringCacheEntry { public string Value; public DateTime Timestamp; } }
33.295455
105
0.480091
[ "MIT" ]
blowfishpro/CKAN
Netkan/Services/CachingHttpService.cs
4,397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; namespace vroom.Areas.Identity.Pages.Account { public class AccessDeniedModel : PageModel { public void OnGet() { } } }
16.666667
46
0.693333
[ "MPL-2.0" ]
kvolodymyr/Clout-It-C-19-04
Students/OleksandrP/CourseProject/BikeShopProject/vroom/Areas/Identity/Pages/Account/AccessDenied.cshtml.cs
302
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Collections_Generic_Dictionary_2_String_List_1_ILTypeInstance_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>); args = new Type[]{typeof(System.String)}; method = type.GetMethod("ContainsKey", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ContainsKey_0); args = new Type[]{typeof(System.String), typeof(System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>)}; method = type.GetMethod("Add", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Add_1); args = new Type[]{typeof(System.String)}; method = type.GetMethod("get_Item", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Item_2); args = new Type[]{typeof(System.String), typeof(System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>).MakeByRefType()}; method = type.GetMethod("TryGetValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, TryGetValue_3); args = new Type[]{}; method = type.GetMethod("Clear", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Clear_4); args = new Type[]{}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static StackObject* ContainsKey_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>)typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.ContainsKey(@key); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* Add_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance> @value = (System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>)typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Add(@key, @value); return __ret; } static StackObject* get_Item_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>)typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method[key]; object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* TryGetValue_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance> @value = (System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>)typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.TryGetValue(@key, out @value); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = *(StackObject**)&ptr_of_this_method->Value; object ___obj = @value; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @value; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @value); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @value; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @value); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @value; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); __intp.Free(ptr_of_this_method); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* Clear_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>> instance_of_this_method = (System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>)typeof(System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Clear(); return __ret; } static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<ILRuntime.Runtime.Intepreter.ILTypeInstance>>(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
59.004425
516
0.668841
[ "MIT" ]
594270461/LandlordsCore
Unity/Assets/Model/ILBinding/System_Collections_Generic_Dictionary_2_String_List_1_ILTypeInstance_Binding.cs
13,335
C#
// Copyright © 2017 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using ExtCore.Infrastructure; namespace ExtCore.Data.Dapper { /// <summary> /// Overrides the <see cref="ExtensionBase">ExtensionBase</see> class and provides the /// ExtCore.Data.Dapper extension information. /// </summary> public class Extension : ExtensionBase { /// <summary> /// Gets the name of the extension. /// </summary> public override string Name => "ExtCore.Data.Dapper"; /// <summary> /// Gets the URL of the extension. /// </summary> public override string Url => "http://extcore.net/"; /// <summary> /// Gets the version of the extension. /// </summary> public override string Version => "5.0.0"; /// <summary> /// Gets the authors of the extension (separated by commas). /// </summary> public override string Authors => "Dmitry Sikorsky"; } }
29.794118
111
0.653504
[ "Apache-2.0" ]
masums/ExtCore
src/ExtCore.Data.Dapper/Extension.cs
1,016
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("Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Core")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("2bf9827a-bb59-42e2-be60-feab78041b89")] // 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.324324
84
0.742216
[ "Apache-2.0" ]
DefectiveCube/IDE
IDE/Core/Properties/AssemblyInfo.cs
1,384
C#
#pragma checksum "..\..\..\..\Components\ProjectView\ProjectManager.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "617F76E4B53F542C5CF85E01FEE955FE" //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using ACS.Creator.Components.ProjectView; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace ACS.Creator.Components.ProjectView { /// <summary> /// ProjectManager /// </summary> public partial class ProjectManager : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/ACS Creator;component/components/projectview/projectmanager.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\Components\ProjectView\ProjectManager.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
39.657895
150
0.673192
[ "MIT" ]
Asixa/ACS-Creator
ACS-Creator/ACS-Creator/obj/Debug/Components/ProjectView/ProjectManager.g.i.cs
3,122
C#
namespace StatTracker.Areas.HelpPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
29.142857
65
0.730392
[ "MIT" ]
mdewey/StatTracker
StatTracker/StatTracker/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs
204
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cube : MonoBehaviour { // enum SlotDir { // x = 0, // _x = 1, // z = 2, // _z = 3, // }; public Slot[] slots = new Slot[4]; void OnDrawGizmos() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = Color.green; Gizmos.DrawSphere (Vector3.zero, 0.2f); Gizmos.matrix = Matrix4x4.identity; foreach (var s in slots) { if (s.matched) { Gizmos.DrawLine (s.transform.position, transform.position); } } } }
16.90625
63
0.648799
[ "MIT" ]
wdmir/MonumentVally-Demo
Assets/Script/Cube.cs
543
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace MicroElements.Metadata.SampleApp { 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.666667
70
0.589981
[ "MIT" ]
micro-elements/MicroElements.Metadata
sample/MicroElements.Metadata.SampleApp/Program.cs
539
C#
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Quasardb.Exceptions; using Quasardb.TimeSeries; namespace Quasardb.Tests.Entry.Table.Double { [TestClass] public class Max { readonly QdbDoublePointCollection _points = new QdbDoublePointCollection { {new DateTime(2012, 11, 02), 0}, {new DateTime(2014, 06, 30), 42}, {new DateTime(2016, 02, 04), 666} // <- max is here }; [TestMethod] public void ThrowsColumnNotFound() { var col = QdbTestCluster.GetNonExistingDoubleColumn(); try { col.Max(); Assert.Fail("No exception thrown"); } catch (QdbColumnNotFoundException e) { Assert.AreEqual(col.Series.Alias, e.Alias); Assert.AreEqual(col.Name, e.Column); } } [TestMethod] public void GivenNoArgument_ReturnsMaxPointOfTable() { var col = QdbTestCluster.CreateEmptyDoubleColumn(); col.Insert(_points); var result = col.Max(); Assert.AreEqual(_points[2], result); } [TestMethod] public void GivenInRangeInterval_ReturnsMinPointOfInterval() { var col = QdbTestCluster.CreateEmptyDoubleColumn(); col.Insert(_points); var interval = new QdbTimeInterval(_points[0].Time, _points[2].Time); var result = col.Max(interval); Assert.AreEqual(_points[1], result); } [TestMethod] public void GivenOutOfRangeInterval_ReturnsNull() { var col = QdbTestCluster.CreateEmptyDoubleColumn(); col.Insert(_points); var interval = new QdbTimeInterval(new DateTime(3000, 1, 1), new DateTime(4000, 1, 1)); var result = col.Max(interval); Assert.IsNull(result); } [TestMethod] public void GivenSeveralIntervals_ReturnsMaxOfEach() { var col = QdbTestCluster.CreateEmptyDoubleColumn(); col.Insert(_points); var intervals = new[] { new QdbTimeInterval(new DateTime(2012, 1, 1), new DateTime(2015, 12, 31)), new QdbTimeInterval(new DateTime(2014, 1, 1), new DateTime(2017, 12, 31)), new QdbTimeInterval(new DateTime(2016, 6, 1), new DateTime(2018, 12, 31)) }; var results = col.Max(intervals).ToArray(); Assert.AreEqual(3, results.Length); Assert.AreEqual(_points[1], results[0]); Assert.AreEqual(_points[2], results[1]); Assert.IsNull(results[2]); } [TestMethod] public void ThrowsEmptyColumn() { var col = QdbTestCluster.CreateEmptyDoubleColumn(); try { col.Max(); Assert.Fail("No exception thrown"); } catch (QdbEmptyColumnException e) { Assert.AreEqual(col.Series.Alias, e.Alias); Assert.AreEqual(col.Name, e.Column); } } } }
29.590909
99
0.547158
[ "BSD-3-Clause" ]
bureau14/qdb-api-dotnet
Quasardb.Tests/Entry/Table/Double/Max.cs
3,257
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteSemanticClassificationService : BrokeredServiceBase, IRemoteSemanticClassificationService { internal sealed class Factory : FactoryBase<IRemoteSemanticClassificationService> { protected override IRemoteSemanticClassificationService CreateService(in ServiceConstructionArguments arguments) => new RemoteSemanticClassificationService(arguments); } public RemoteSemanticClassificationService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<SerializableClassifiedSpans> GetSemanticClassificationsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, TextSpan span, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { using (UserOperationBooster.Boost()) { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId); using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var temp); await AbstractClassificationService.AddSemanticClassificationsInCurrentProcessAsync( document, span, temp, cancellationToken).ConfigureAwait(false); return SerializableClassifiedSpans.Dehydrate(temp.ToImmutable()); } }, cancellationToken); } } }
42.020408
124
0.70034
[ "MIT" ]
IanKemp/roslyn
src/Workspaces/Remote/ServiceHub/Services/SemanticClassification/RemoteSemanticClassificationService.cs
2,061
C#
using System.Collections.Generic; using MiniPay.App.User; namespace MiniPay.App.Requests { public sealed class AppActor { public string Id { get; } public IEnumerable<UserRoles> Roles { get; } public AppActor(string id, HashSet<UserRoles> roles) { Id = id; Roles = roles; } } }
19.833333
60
0.582633
[ "MIT" ]
SilasReinagel/MiniPay
src/MiniPay.App/Requests/AppActor.cs
359
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace AutomationTool { [Help("Merge one or more remote DDC shares into a local share, taking files with the newest timestamps and keeping the size below a certain limit")] [Help("LocalDir=<Path>", "The local DDC directory to add/remove files from")] [Help("RemoteDir=<Path>", "The remote DDC directory to pull from. May be specified multiple times.")] [Help("MaxSize=<Size>", "Maximum size of the local DDC directory. TB/MB/GB/KB units are allowed.")] [Help("MaxDays=<Num>", "Only copies files with modified timestamps in the past number of days.")] [Help("TimeLimit=<Time>", "Maximum time to run for. h/m/s units are allowed.")] class SyncDDC : BuildCommand { /// <summary> /// Stores information about a file in the DDC /// </summary> class CacheFile { /// <summary> /// Relative path from the root of the DDC store /// </summary> public string RelativePath; /// <summary> /// Full path to the actual location on the store /// </summary> public string FullName; /// <summary> /// Size of the file /// </summary> public long Length; /// <summary> /// Last time the file was written to /// </summary> public DateTime LastWriteTimeUtc; /// <summary> /// Constructor /// </summary> /// <param name="RelativePath">Relative path for this file</param> /// <param name="File">File information</param> public CacheFile(string RelativePath, string FullName, long Length, DateTime LastWriteTimeUtc) { this.RelativePath = RelativePath; this.FullName = FullName; this.Length = Length; this.LastWriteTimeUtc = LastWriteTimeUtc; } /// <summary> /// Format this object as a string for debugging /// </summary> /// <returns>Relative path to the file</returns> public override string ToString() { return RelativePath; } } /// <summary> /// Statistics for copying files /// </summary> class CopyStats { /// <summary> /// The number of files transferred /// </summary> public int NumFiles; /// <summary> /// The number of bytes transferred /// </summary> public long NumBytes; } /// <summary> /// Execute the command /// </summary> public override void ExecuteBuild() { Console.WriteLine(); // Parse the command line arguments string LocalDirName = ParseParamValue("LocalDir", null); if(LocalDirName == null) { throw new AutomationException("Missing -LocalDir=... argument"); } long MaxSize; if(!TryParseSize(ParseParamValue("MaxSize", "0mb"), out MaxSize)) { throw new AutomationException("Invalid -MaxSize=... argument"); } string[] RemoteDirNames = ParseParamValues("RemoteDir"); if(RemoteDirNames.Length == 0) { throw new AutomationException("Missing -RemoteDir=... argument"); } int MaxDays; if(!int.TryParse(ParseParamValue("MaxDays", "3"), out MaxDays)) { throw new AutomationException("Invalid -MaxDays=... argument"); } int TimeLimit; if(!TryParseTime(ParseParamValue("TimeLimit", "0m"), out TimeLimit)) { throw new AutomationException("Invalid -TimeLimit=... argument"); } bool bPreview = ParseParam("Preview"); // Make sure the source directory exists List<DirectoryInfo> RemoteDirs = new List<DirectoryInfo>(); foreach(string RemoteDirName in RemoteDirNames) { DirectoryInfo RemoteDir = new DirectoryInfo(RemoteDirName); if(!RemoteDir.Exists) { throw new AutomationException("Remote directory '{0}' does not exist", RemoteDirName); } RemoteDirs.Add(RemoteDir); } // Get the local directory DirectoryInfo LocalDir = new DirectoryInfo(LocalDirName); if(!LocalDir.Exists) { LocalDir.Create(); } // Create all the base DDC directory names. These are three entries deep, each numbered 0-9. List<string> BasePathPrefixes = new List<string>(); for(int IndexA = 0; IndexA <= 9; IndexA++) { for(int IndexB = 0; IndexB <= 9; IndexB++) { for(int IndexC = 0; IndexC <= 9; IndexC++) { BasePathPrefixes.Add(String.Format("{0}{3}{1}{3}{2}{3}", IndexA, IndexB, IndexC, Path.DirectorySeparatorChar)); } } } // Find all the local files ConcurrentBag<CacheFile> LocalFiles = new ConcurrentBag<CacheFile>(); Console.WriteLine("Enumerating local files from {0}", LocalDir.FullName); ForEach(BasePathPrefixes, (BasePath, Messages) => (() => EnumerateFiles(LocalDir, BasePath, LocalFiles)), "Enumerating files..."); Console.WriteLine("Found {0} files, {1}mb.", LocalFiles.Count, LocalFiles.Sum(x => x.Length) / (1024 * 1024)); Console.WriteLine(); // Find all the remote files ConcurrentBag<CacheFile> RemoteFiles = new ConcurrentBag<CacheFile>(); foreach(DirectoryInfo RemoteDir in RemoteDirs) { Console.WriteLine("Enumerating remote files from {0}", RemoteDir.FullName); ForEach(BasePathPrefixes, (BasePath, Messages) => (() => EnumerateFiles(RemoteDir, BasePath, RemoteFiles)), "Enumerating files..."); Console.WriteLine("Found {0} files, {1}mb.", RemoteFiles.Count, RemoteFiles.Sum(x => x.Length) / (1024 * 1024)); Console.WriteLine(); } // Get the oldest file that we want to copy DateTime OldestLastWriteTimeUtc = DateTime.Now - TimeSpan.FromDays(MaxDays); // Build a lookup of remote files by name Dictionary<string, CacheFile> RelativePathToRemoteFile = new Dictionary<string, CacheFile>(StringComparer.InvariantCultureIgnoreCase); foreach(CacheFile RemoteFile in RemoteFiles) { if(RemoteFile.LastWriteTimeUtc > OldestLastWriteTimeUtc) { RelativePathToRemoteFile[RemoteFile.RelativePath] = RemoteFile; } } // Build a lookup of local files by name Dictionary<string, CacheFile> RelativePathToLocalFile = LocalFiles.ToDictionary(x => x.RelativePath, x => x, StringComparer.InvariantCultureIgnoreCase); // Build a list of target files that we want in the DDC long TotalSize = 0; Dictionary<string, CacheFile> RelativePathToTargetFile = new Dictionary<string, CacheFile>(StringComparer.InvariantCultureIgnoreCase); foreach(CacheFile TargetFile in Enumerable.Concat<CacheFile>(RelativePathToLocalFile.Values, RelativePathToRemoteFile.Values).OrderByDescending(x => x.LastWriteTimeUtc)) { if(MaxSize > 0 && TotalSize + TargetFile.Length > MaxSize) { break; } if(!RelativePathToTargetFile.ContainsKey(TargetFile.RelativePath)) { RelativePathToTargetFile.Add(TargetFile.RelativePath, TargetFile); TotalSize += TargetFile.Length; } } // Print measure of how coherent the cache is double CoherencyPct = RelativePathToTargetFile.Values.Count(x => RelativePathToLocalFile.ContainsKey(x.RelativePath)) * 100.0 / RelativePathToTargetFile.Count; Console.WriteLine("Cache is {0:0.0}% coherent with remote.", CoherencyPct); Console.WriteLine(); // Remove any outdated files List<CacheFile> FilesToRemove = RelativePathToLocalFile.Values.Where(x => !RelativePathToTargetFile.ContainsKey(x.RelativePath)).ToList(); if(bPreview) { Console.WriteLine("Sync would remove {0} files ({1}mb)", FilesToRemove.Count, FilesToRemove.Sum(x => x.Length) / (1024 * 1024)); } else if(FilesToRemove.Count > 0) { Console.WriteLine("Deleting {0} files ({1}mb)...", FilesToRemove.Count, FilesToRemove.Sum(x => x.Length) / (1024 * 1024)); ForEach(FilesToRemove, (File, Messages) => (() => RemoveFile(LocalDir, File.RelativePath, Messages)), "Deleting files"); Console.WriteLine(); } // Add any new files List<CacheFile> FilesToAdd = RelativePathToTargetFile.Values.Where(x => !RelativePathToLocalFile.ContainsKey(x.RelativePath)).ToList(); if(bPreview) { Console.WriteLine("Sync would add {0} files ({1}mb)", FilesToAdd.Count, FilesToAdd.Sum(x => x.Length) / (1024 * 1024)); } else if(FilesToAdd.Count > 0) { Console.WriteLine("Copying {0} files ({1}mb)...", FilesToAdd.Count, FilesToAdd.Sum(x => x.Length) / (1024 * 1024)); CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); if (TimeLimit > 0) { CancellationTokenSource.CancelAfter(TimeLimit * 1000); } DateTime StartTime = DateTime.UtcNow; CopyStats Stats = new CopyStats(); ForEach(FilesToAdd, (File, Messages) => (() => CopyFile(File, LocalDir, Messages, Stats)), "Copying files...", CancellationTokenSource.Token); double TotalSizeMb = Stats.NumBytes / (1024.0 * 1024.0); Console.WriteLine("Copied {0} files totalling {1:0.0}mb ({2:0.00}mb/s).", Stats.NumFiles, TotalSizeMb, TotalSizeMb / (DateTime.UtcNow - StartTime).TotalSeconds); double FinalCoherencyPct = (RelativePathToTargetFile.Values.Count(x => RelativePathToLocalFile.ContainsKey(x.RelativePath)) + Stats.NumFiles) * 100.0 / RelativePathToTargetFile.Count; Console.WriteLine(); Console.WriteLine("Final cache is {0:0.0}% coherent with remote.", FinalCoherencyPct); if (CancellationTokenSource.IsCancellationRequested) { Console.WriteLine("Halting due to expired time limit."); } } Console.WriteLine(); } /// <summary> /// Execute a command for each item in the given list, printing progress messages and queued up error strings /// </summary> /// <typeparam name="T">Type of the item to process</typeparam> /// <param name="Items">List of items</param> /// <param name="CreateAction">Delegate which will create an action to execute for an item</param> /// <param name="Message">Prefix to add to progress messages</param> static void ForEach<T>(IList<T> Items, Func<T, ConcurrentQueue<string>, Action> CreateAction, string Message, CancellationToken? CancellationToken = null) { using (ThreadPoolWorkQueue Queue = new ThreadPoolWorkQueue()) { ConcurrentQueue<string> Warnings = new ConcurrentQueue<string>(); foreach(T Item in Items) { Action ThisAction = CreateAction(Item, Warnings); if(CancellationToken.HasValue) { Action OriginalAction = ThisAction; CancellationToken Token = CancellationToken.Value; ThisAction = () => { if (!Token.IsCancellationRequested) OriginalAction(); }; } Queue.Enqueue(ThisAction); } DateTime StartTime = DateTime.UtcNow; DateTime NextUpdateTime = DateTime.UtcNow + TimeSpan.FromSeconds(0.5); for(;;) { bool bResult = Queue.Wait(2000); if (!CancellationToken.HasValue || !CancellationToken.Value.IsCancellationRequested) { DateTime CurrentTime = DateTime.UtcNow; if (CurrentTime >= NextUpdateTime || bResult) { int NumRemaining = Queue.NumRemaining; Console.WriteLine("{0} ({1}/{2}; {3}%)", Message, Items.Count - NumRemaining, Items.Count, (int)((Items.Count - NumRemaining) * 100.0f / Items.Count)); NextUpdateTime = CurrentTime + TimeSpan.FromSeconds(10.0); } } if(bResult) { break; } } List<string> WarningsList = new List<string>(Warnings); if(WarningsList.Count > 0) { const int MaxWarnings = 50; if (WarningsList.Count > MaxWarnings) { Console.WriteLine("{0} warnings, showing first {1}:", WarningsList.Count, MaxWarnings); } else { Console.WriteLine("{0} {1}:", WarningsList.Count, (WarningsList.Count == 1) ? "warning" : "warnings"); } for(int Idx = 0; Idx < WarningsList.Count && Idx < MaxWarnings; Idx++) { Console.WriteLine(" {0}", WarningsList[Idx]); } } } } /// <summary> /// Enumerates all the files in a given directory, and adds them to a bag /// </summary> /// <param name="BaseDir">Base directory to enumerate</param> /// <param name="PathPrefix">Path from the base directory containing files to enumerate</param> /// <param name="Files">Collection of found files</param> static void EnumerateFiles(DirectoryInfo BaseDir, string PathPrefix, ConcurrentBag<CacheFile> Files) { DirectoryInfo SearchDir = new DirectoryInfo(Path.Combine(BaseDir.FullName, PathPrefix)); if(SearchDir.Exists) { foreach(FileInfo File in SearchDir.EnumerateFiles("*.udd")) { CacheFile CacheFile = new CacheFile(PathPrefix + File.Name, File.FullName, File.Length, File.LastAccessTimeUtc); Files.Add(CacheFile); } } } /// <summary> /// Copies a file from one DDC to another /// </summary> /// <param name="SourceFile">File to copy</param> /// <param name="TargetDir">Target DDC directory</param> /// <param name="Messages">Queue to receieve error messages</param> /// <param name="Stats">Stats for the files copied</param> static void CopyFile(CacheFile SourceFile, DirectoryInfo TargetDir, ConcurrentQueue<string> Messages, CopyStats Stats) { int NumRetries = 0; for (;;) { // Try to copy the file, and return if we succeed string Message; if (TryCopyFile(SourceFile, TargetDir, out Message)) { Interlocked.Increment(ref Stats.NumFiles); Interlocked.Add(ref Stats.NumBytes, SourceFile.Length); break; } // Increment the number of retries NumRetries++; // Give up after retrying 5 times, and report the last error if (NumRetries >= 3) { // Check that the source file still actually exists. If it doesn't, we'll ignore the errors. try { if (!File.Exists(SourceFile.FullName)) { Interlocked.Increment(ref Stats.NumFiles); break; } } catch { } // Otherwise queue up the error message Messages.Enqueue(Message); break; } } } /// <summary> /// Tries to copy a file from one DDC to another /// </summary> /// <param name="SourceFile">File to copy</param> /// <param name="TargetDir">Target DDC directory</param> /// <param name="Message">Queue to receieve error messages</param> /// <returns>True if the file was copied successfully, false otherwise</returns> static bool TryCopyFile(CacheFile SourceFile, DirectoryInfo TargetDir, out string Message) { string TargetFileName = Path.Combine(TargetDir.FullName, SourceFile.RelativePath); string IntermediateFileName = TargetFileName + ".temp"; string IntermediateDir = Path.GetDirectoryName(IntermediateFileName); // Create the target directory try { Directory.CreateDirectory(IntermediateDir); } catch (Exception Ex) { Message = String.Format("Unable to create {0}: {1}", IntermediateDir, Ex.Message.TrimEnd()); return false; } // Copy the file from the remote location to the intermediate file try { File.Copy(SourceFile.FullName, IntermediateFileName); } catch (Exception Ex) { Message = String.Format("Unable to copy {0} to {1}: {2}", SourceFile.FullName, IntermediateFileName, Ex.Message.TrimEnd()); return false; } // Rename the file into place as a transactional operation try { File.Move(IntermediateFileName, TargetFileName); } catch (Exception Ex) { Message = String.Format("Unable to rename {0} to {1}: {2}", IntermediateFileName, TargetFileName, Ex.Message.TrimEnd()); return false; } Message = null; return true; } /// <summary> /// Removes a file from the DDC /// </summary> /// <param name="BaseDir">Base directory for the DDC</param> /// <param name="RelativePath">Relative path for the file to remove</param> /// <param name="Messages">Queue to receieve error messages</param> static void RemoveFile(DirectoryInfo BaseDir, string RelativePath, ConcurrentQueue<string> Messages) { string FileName = Path.Combine(BaseDir.FullName, RelativePath); try { File.Delete(FileName); } catch(Exception Ex) { Messages.Enqueue(String.Format("Unable to delete {0}: {1}", FileName, Ex.Message.TrimEnd())); } } /// <summary> /// Parses a size argument as number of bytes, which may be specified in tb/gb/mb/kb units. /// </summary> /// <param name="Text">Text to parse</param> /// <param name="Size">Receives the parsed argument, in bytes</param> /// <returns>True if a size could be parsed</returns> static bool TryParseSize(string Text, out long Size) { Match Match = Regex.Match(Text, "^(\\d+)(tb|gb|mb|kb)$"); if(!Match.Success) { Size = 0; return false; } Size = long.Parse(Match.Groups[1].Value); switch(Match.Groups[2].Value.ToLowerInvariant()) { case "tb": Size *= 1024 * 1024 * 1024 * 1024L; break; case "gb": Size *= 1024 * 1024 * 1024L; break; case "mb": Size *= 1024 * 1024L; break; case "kb": Size *= 1024L; break; } return true; } /// <summary> /// Parses a time argument as number of seconds, which may be specified in h/m/s units. /// </summary> /// <param name="Text">Text to parse</param> /// <param name="TimeSection">Receives the parsed argument, in seconds</param> /// <returns>True if a size could be parsed</returns> static bool TryParseTime(string Text, out int TimeSeconds) { Match Match = Regex.Match(Text, "^(\\d+)(h|m|s)$"); if (!Match.Success) { TimeSeconds = 0; return false; } TimeSeconds = int.Parse(Match.Groups[1].Value); switch (Match.Groups[2].Value.ToLowerInvariant()) { case "h": TimeSeconds *= 60 * 60; break; case "m": TimeSeconds *= 60; break; } return true; } } }
33.537143
187
0.673198
[ "MIT" ]
CaptainUnknown/UnrealEngine_NVIDIAGameWorks
Engine/Source/Programs/AutomationTool/Scripts/SyncDDC.cs
17,609
C#
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.IO; namespace DotSpatial.Data.Forms { /// <summary> /// FolderItem. /// </summary> internal class FolderItem : DirectoryItem { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="FolderItem"/> class. /// </summary> public FolderItem() { } /// <summary> /// Initializes a new instance of the <see cref="FolderItem"/> class that points to the specified path. /// </summary> /// <param name="path">The string path that this FolderItem should be identified with.</param> public FolderItem(string path) : base(path) { ItemType = ItemType.Folder; Info = new DirectoryInfo(path); } #endregion #region Properties /// <summary> /// Gets or sets the directory info. /// </summary> public DirectoryInfo Info { get; set; } #endregion } }
27.522727
112
0.553262
[ "MIT" ]
eapbokma/DotSpatial
Source/DotSpatial.Data.Forms/FolderItem.cs
1,211
C#
using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using SmartSorting.Algorithms; using SmartSorting.Structure; using SmartSorting.Tests.Extensions; namespace SmartSorting.Tests.Algorithms { [TestClass] public class MergeSortTests { [TestMethod] public void Should_Sort_Int_Array_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<int>(); int[] numbers = { 1, 3, 5, 2, 4 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Ascending); Assert.IsTrue(numbers[0] == 1); Assert.IsTrue(numbers[1] == 2); Assert.IsTrue(numbers[2] == 3); Assert.IsTrue(numbers[3] == 4); Assert.IsTrue(numbers[4] == 5); } [TestMethod] public void Should_Sort_Int_Array_With_Descending_Direction() { var sortAlgorithm = new MergeSort<int>(); int[] numbers = { 1, 3, 5, 2, 4 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Descending); Assert.IsTrue(numbers[0] == 5); Assert.IsTrue(numbers[1] == 4); Assert.IsTrue(numbers[2] == 3); Assert.IsTrue(numbers[3] == 2); Assert.IsTrue(numbers[4] == 1); } [TestMethod] public void Should_Sort_Float_Array_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<float>(); float[] numbers = { 1.1f, 1.8f, 1.2f, 2.1f, 0 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Ascending); Assert.IsTrue(numbers[0] == 0); Assert.IsTrue(numbers[1] == 1.1f); Assert.IsTrue(numbers[2] == 1.2f); Assert.IsTrue(numbers[3] == 1.8f); Assert.IsTrue(numbers[4] == 2.1f); } [TestMethod] public void Should_Sort_Float_Array_With_Descending_Direction() { var sortAlgorithm = new MergeSort<float>(); float[] numbers = { 1.1f, 1.8f, 1.2f, 2.1f, 0 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Descending); Assert.IsTrue(numbers[0] == 2.1f); Assert.IsTrue(numbers[1] == 1.8f); Assert.IsTrue(numbers[2] == 1.2f); Assert.IsTrue(numbers[3] == 1.1f); Assert.IsTrue(numbers[4] == 0); } [TestMethod] public void Should_Sort_Decimal_Array_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<decimal>(); decimal[] numbers = { 1.1M, 1.8M, 1.2M, 2.1M, 0 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Ascending); Assert.IsTrue(numbers[0] == 0); Assert.IsTrue(numbers[1] == 1.1M); Assert.IsTrue(numbers[2] == 1.2M); Assert.IsTrue(numbers[3] == 1.8M); Assert.IsTrue(numbers[4] == 2.1M); } [TestMethod] public void Should_Sort_Decimal_Array_With_Descending_Direction() { var sortAlgorithm = new MergeSort<decimal>(); decimal[] numbers = { 1.1M, 1.8M, 1.2M, 2.1M, 0 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Descending); Assert.IsTrue(numbers[0] == 2.1M); Assert.IsTrue(numbers[1] == 1.8M); Assert.IsTrue(numbers[2] == 1.2M); Assert.IsTrue(numbers[3] == 1.1M); Assert.IsTrue(numbers[4] == 0); } [TestMethod] public void Should_Sort_Double_Array_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<double>(); double[] numbers = { 1.1214, 1.8125, 1.1215, 2.101, 1 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Ascending); Assert.IsTrue(numbers[0] == 1); Assert.IsTrue(numbers[1] == 1.1214); Assert.IsTrue(numbers[2] == 1.1215); Assert.IsTrue(numbers[3] == 1.8125); Assert.IsTrue(numbers[4] == 2.101); } [TestMethod] public void Should_Sort_Double_Array_With_Descending_Direction() { var sortAlgorithm = new MergeSort<double>(); double[] numbers = { 1.1214, 1.8125, 1.1215, 2.101, 1 }; numbers = sortAlgorithm.Sort(numbers, ESortOrder.Descending); Assert.IsTrue(numbers[0] == 2.101); Assert.IsTrue(numbers[1] == 1.8125); Assert.IsTrue(numbers[2] == 1.1215); Assert.IsTrue(numbers[3] == 1.1214); Assert.IsTrue(numbers[4] == 1); } [TestMethod] public void Should_Sort_String_Array_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<string>(); string[] strings = { "acb", "abc", "cab", "eeg", "eef" }; strings = sortAlgorithm.Sort(strings, ESortOrder.Ascending); Assert.IsTrue(strings[0] == "abc"); Assert.IsTrue(strings[1] == "acb"); Assert.IsTrue(strings[2] == "cab"); Assert.IsTrue(strings[3] == "eef"); Assert.IsTrue(strings[4] == "eeg"); } [TestMethod] public void Should_Sort_String_Array_With_Descending_Direction() { var sortAlgorithm = new MergeSort<string>(); string[] strings = { "acb", "abc", "cab", "eeg", "eef" }; strings = sortAlgorithm.Sort(strings, ESortOrder.Descending); Assert.IsTrue(strings[0] == "eeg"); Assert.IsTrue(strings[1] == "eef"); Assert.IsTrue(strings[2] == "cab"); Assert.IsTrue(strings[3] == "acb"); Assert.IsTrue(strings[4] == "abc"); } [TestMethod] public void Should_Sort_IEnumerable_With_Ascending_Direction() { var sortAlgorithm = new MergeSort<int>(); IEnumerable<int> enumerable = new List<int> { 1, 3, 5, 2, 4 }; enumerable = sortAlgorithm.Sort(enumerable, ESortOrder.Ascending); Assert.IsTrue(enumerable.ElementAt(0) == 1); Assert.IsTrue(enumerable.ElementAt(1) == 2); Assert.IsTrue(enumerable.ElementAt(2) == 3); Assert.IsTrue(enumerable.ElementAt(3) == 4); Assert.IsTrue(enumerable.ElementAt(4) == 5); } [TestMethod] public void Should_Sort_IEnumerable_With_Descending_Direction() { var sortAlgorithm = new MergeSort<int>(); IEnumerable<int> enumerable = new List<int> { 1, 3, 5, 2, 4 }; enumerable = sortAlgorithm.Sort(enumerable, ESortOrder.Descending); Assert.IsTrue(enumerable.ElementAt(0) == 5); Assert.IsTrue(enumerable.ElementAt(1) == 4); Assert.IsTrue(enumerable.ElementAt(2) == 3); Assert.IsTrue(enumerable.ElementAt(3) == 2); Assert.IsTrue(enumerable.ElementAt(4) == 1); } [TestMethod] public void Should_Sort_IEnumerable_Of_Custom_Type_Witch_Ascending_Direction() { var sortAlgorithm = new MergeSort<TodoItem>(); var enumeration = new List<TodoItem> { new TodoItem(1), new TodoItem(5), new TodoItem(3), new TodoItem(2), new TodoItem(4), }; enumeration = sortAlgorithm.Sort(enumeration, ESortOrder.Ascending).ToList(); Assert.IsTrue(enumeration[0].Id == 1); Assert.IsTrue(enumeration[1].Id == 2); Assert.IsTrue(enumeration[2].Id == 3); Assert.IsTrue(enumeration[3].Id == 4); Assert.IsTrue(enumeration[4].Id == 5); } [TestMethod] public void Should_Sort_IEnumerable_Of_Custom_Type_Witch_Descending_Direction() { var sortAlgorithm = new MergeSort<TodoItem>(); var enumeration = new List<TodoItem> { new TodoItem(1), new TodoItem(5), new TodoItem(3), new TodoItem(2), new TodoItem(4), }; enumeration = sortAlgorithm.Sort(enumeration, ESortOrder.Descending).ToList(); Assert.IsTrue(enumeration[0].Id == 5); Assert.IsTrue(enumeration[1].Id == 4); Assert.IsTrue(enumeration[2].Id == 3); Assert.IsTrue(enumeration[3].Id == 2); Assert.IsTrue(enumeration[4].Id == 1); } } }
35.514644
90
0.553605
[ "MIT" ]
evgomes/smart-sorting
SmartSorting.Tests/Algorithms/MergeSortTests.cs
8,488
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.YamlSerialization.ObjectFactories { using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using YamlDotNet.Serialization; public class DefaultEmitObjectFactory : IObjectFactory { private readonly Dictionary<Type, Func<object>> _cache = new Dictionary<Type, Func<object>>(); private static Type[] EmptyTypes => Type.EmptyTypes; public object Create(Type type) { if (!_cache.TryGetValue(type, out Func<object> func)) { if (type.IsVisible) { var realType = type; if (type.IsInterface && type.IsGenericType) { var def = type.GetGenericTypeDefinition(); var args = type.GetGenericArguments(); if (def == typeof(IDictionary<,>) || def == typeof(IReadOnlyDictionary<,>)) { realType = typeof(Dictionary<,>).MakeGenericType(args); } if (def == typeof(IList<>) || def == typeof(IReadOnlyList<>) || def == typeof(ICollection<>) || def == typeof(IReadOnlyCollection<>) || def == typeof(IEnumerable<>)) { realType = typeof(List<>).MakeGenericType(args); } if (def == typeof(ISet<>)) { realType = typeof(HashSet<>).MakeGenericType(args); } } var ctor = realType.GetConstructor(Type.EmptyTypes); if (ctor != null) { func = CreateReferenceTypeFactory(ctor); } else if (type.IsValueType) { func = CreateValueTypeFactory(type); } } if (func == null) { var typeName = type.FullName; func = () => throw new NotSupportedException(typeName); } _cache[type] = func; } return func(); } private static Func<object> CreateReferenceTypeFactory(ConstructorInfo ctor) { var dm = new DynamicMethod(string.Empty, typeof(object), EmptyTypes); var il = dm.GetILGenerator(); il.Emit(OpCodes.Newobj, ctor); if (ctor.DeclaringType.IsValueType) { il.Emit(OpCodes.Box, ctor.DeclaringType); } il.Emit(OpCodes.Ret); return (Func<object>)dm.CreateDelegate(typeof(Func<object>)); } private static Func<object> CreateValueTypeFactory(Type type) { var dm = new DynamicMethod(string.Empty, typeof(object), EmptyTypes); var il = dm.GetILGenerator(); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Box, type); il.Emit(OpCodes.Ret); return (Func<object>)dm.CreateDelegate(typeof(Func<object>)); } } }
40.078652
102
0.477152
[ "MIT" ]
Algorithman/docfx
src/Microsoft.DocAsCode.YamlSerialization/ObjectFactories/DefaultEmitObjectFactory.cs
3,481
C#
// Copyright (c) 2021 Salzschneider and others // // 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 MetalWeightCalculator { using System; /// <summary> /// Represents an error item occured during the argument validation. /// </summary> public class ValidationError { /// <summary> /// Gets the name of the argument. /// </summary> public string ArgumentName { get; private set; } /// <summary> /// Gets the error message. /// </summary> public string ErrorMessage { get; private set; } /// <summary> /// Gets the error code. /// </summary> public ErrorCodes ErrorCode { get; private set; } public ValidationError(string argumentName, string errorMessage, ErrorCodes errorCode) { if(string.IsNullOrEmpty(argumentName)) { throw new ArgumentException("Argument name can't be null."); } ArgumentName = argumentName; ErrorMessage = errorMessage ?? string.Empty; ErrorCode = errorCode; } private ValidationError() { } } }
35.222222
94
0.660658
[ "MIT" ]
salzschneider/Metal.Weight.Calculator
src/MetalWeightCalculator/Validation/ValidationError.cs
2,221
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.Triggered.Internal { public class NonCascadingTriggerContextDiscoveryStrategy : ITriggerContextDiscoveryStrategy { readonly static Action<ILogger, int, string, Exception?> _changesDetected = LoggerMessage.Define<int, string>( LogLevel.Debug, new EventId(1, "Discovered"), "Discovered changes: {changes} for {name}"); readonly string _name; public NonCascadingTriggerContextDiscoveryStrategy(string name) { _name = name ?? throw new ArgumentNullException(nameof(name)); } public IEnumerable<IEnumerable<TriggerContextDescriptor>> Discover(TriggerSessionConfiguration configuration, TriggerContextTracker tracker, ILogger logger) { var changes = tracker.DiscoveredChanges ?? throw new InvalidOperationException("Trigger discovery process has not yet started. Please ensure that TriggerSession.DiscoverChanges() or TriggerSession.RaiseBeforeSaveTriggers() has been called"); if (logger.IsEnabled(LogLevel.Debug)) { _changesDetected(logger, changes.Count(), _name, null); } return Enumerable.Repeat(changes, 1); } } }
38.685714
253
0.697194
[ "MIT" ]
ScriptBox21/EntityFrameworkCore.Triggered
src/EntityFrameworkCore.Triggered/Internal/NonCascadingTriggerContextDiscoveryStrategy.cs
1,356
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Jeelu.KeywordResonator.Client { public partial class ProgressBarForm : Form { private long iSecond = 0; public ProgressBarForm() { InitializeComponent(); } /// <summary> /// 改变进度条 /// </summary> public void SucceedCrawle() { if (progressFecthWord.Value < ((WorkbenchForm)this.Owner).WordsManager.TotalPages) { progressFecthWord.Value++; LableGetedPage.Text = ((WorkbenchForm)this.Owner).WordsManager.GetedPage.ToString(); //TimeSpan timeSpan = DateTime.Now - ((WorkbenchForm)this.Owner).WordsManager.StartCrawlerTime; //lableElapseTime.Text = timeSpan.TotalSeconds.ToString(); lstBoxUrls.Items.Add(((WorkbenchForm)this.Owner).WordsManager.GetedUrls[((WorkbenchForm)this.Owner).WordsManager.GetedUrls.Count - 1]+" :成功"); } } /// <summary> /// 设置进度条最大值 /// </summary> /// <param name="max"></param> public void SetMaxProgress(int max) { progressFecthWord.Maximum = max; } /// <summary> /// 重置进度条 /// </summary> public void ResetProgress() { progressFecthWord.Value = 0; LableGetedPage.Text = "0"; lableElapseTime.Text = "0"; labelFailedPage.Text = "0"; lstBoxUrls.Items.Clear(); } /// <summary> /// 抓取失败时处理 /// </summary> internal void FailCrawle() { if (progressFecthWord.Value < ((WorkbenchForm)this.Owner).WordsManager.TotalPages) { progressFecthWord.Value++; labelFailedPage.Text = ((WorkbenchForm)this.Owner).WordsManager.FailedPage.ToString(); //TimeSpan timeSpan = DateTime.Now - ((WorkbenchForm)this.Owner).WordsManager.StartCrawlerTime; //lableElapseTime.Text = timeSpan.TotalSeconds.ToString(); lstBoxUrls.Items.Add(((WorkbenchForm)this.Owner).WordsManager.FailedUrls[((WorkbenchForm)this.Owner).WordsManager.FailedUrls.Count-1]+" :失败"); } } private void timer_ElapseTime_Tick(object sender, EventArgs e) { iSecond++; lableElapseTime.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", iSecond / 3600, iSecond % 3600 / 60, iSecond % 60); } } }
33.493671
158
0.57483
[ "Apache-2.0" ]
xknife-erian/nknife.jeelusrc
NKnife.App.WebsiteBuilder/KeywordResonator/Client/Win/WordManage/ProgressBarForm.cs
2,706
C#
using System; using UltimaOnline; namespace UltimaOnline.Items { public class GwennosHarp : LapHarp { public override int LabelNumber { get { return 1063480; } } public override int InitMinUses { get { return 1600; } } public override int InitMaxUses { get { return 1600; } } [Constructable] public GwennosHarp() { Hue = 0x47E; Slayer = SlayerName.Repond; Slayer2 = SlayerName.ReptilianDeath; } public GwennosHarp(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
24.410256
68
0.544118
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Minor Artifacts/GwennosHarp.cs
952
C#
// Copyright (c) 2021 Ingenium Software Engineering. All rights reserved. // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. namespace Build { /// <summary> /// Defines the required /// </summary> public interface ITaskHook { } }
20.466667
74
0.697068
[ "MIT" ]
IngeniumSE/Build
apps/Build.Abstractions/Hooks/ITaskHook.cs
309
C#
using Amazon.JSII.JsonModel.Spec; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using NSubstitute; using Xunit; namespace Amazon.JSII.Generator.UnitTests { public class TypeExtensionsTests { const string Prefix = nameof(Generator) + "." + nameof(TypeExtensions) + "."; public class AnyAncestor : GeneratorTestBase { const string _Prefix = Prefix + nameof(TypeExtensions.AnyAncestor); ClassType CreateType(bool includeParent, bool includeGrandparent) { ClassType grandParentType = null; if (includeGrandparent) { grandParentType = new ClassType ( fullyQualifiedName: "myGrandParentTypeFqn", assembly: "myPackage", name: "myGrandParentType", isAbstract: false ); Symbols.MapFullyQualifiedNameToType("myGrandParentTypeFqn", grandParentType); } ClassType parentType = null; if (includeParent) { parentType = new ClassType ( fullyQualifiedName: "myParentTypeFqn", assembly: "myPackage", name: "myParentType", isAbstract: false, @base: includeGrandparent ? new TypeReference("myGrandParentTypeFqn") : null ); Symbols.MapFullyQualifiedNameToType("myParentTypeFqn", parentType); } ClassType classType = new ClassType ( fullyQualifiedName: "myClassFqn", assembly: "myPackage", name: "myClass", isAbstract: false, @base: includeParent ? new TypeReference("myParentTypeFqn") : null ); Symbols.MapFullyQualifiedNameToType("myClassFqn", classType); return classType; } [Fact(DisplayName = _Prefix + nameof(ReturnsFalseIfNoAncestorExists))] public void ReturnsFalseIfNoAncestorExists() { ClassType classType = CreateType(false, false); bool actual = classType.AnyAncestor(Symbols, t => t.Name != string.Empty); Assert.False(actual); } [Fact(DisplayName = _Prefix + nameof(ReturnsFalseIfNoAncestorMatches))] public void ReturnsFalseIfNoAncestorMatches() { ClassType classType = CreateType(true, true); bool actual = classType.AnyAncestor(Symbols, t => t.Name == "myNephewType"); Assert.False(actual); } [Fact(DisplayName = _Prefix + nameof(ReturnsTrueIfBaseMatches))] public void ReturnsTrueIfBaseMatches() { ClassType classType = CreateType(true, true); bool actual = classType.AnyAncestor(Symbols, t => t.Name == "myParentType"); Assert.True(actual); } [Fact(DisplayName = _Prefix + nameof(ReturnsTrueIfAncestorMatches))] public void ReturnsTrueIfAncestorMatches() { ClassType classType = CreateType(true, true); bool actual = classType.AnyAncestor(Symbols, t => t.Name == "myGrandParentType"); Assert.True(actual); } [Fact(DisplayName = _Prefix + nameof(DoesNotAttemptToMatchSelf))] public void DoesNotAttemptToMatchSelf() { ClassType classType = CreateType(true, true); bool actual = classType.AnyAncestor(Symbols, t => t.Name == "myClass"); Assert.False(actual); } [Fact(DisplayName = _Prefix + nameof(DoesNotAttemptToMatchInterfaces))] public void DoesNotAttemptToMatchInterfaces() { InterfaceType interfaceType = new InterfaceType ( fullyQualifiedName: "myInterfaceFqn", assembly: "myPackage", name: "myInterface" ); Symbols.MapFullyQualifiedNameToType("myInterfaceFqn", interfaceType); ClassType classType = new ClassType ( fullyQualifiedName: "myClassFqn", assembly: "myPackage", name: "myClass", isAbstract: false, interfaces: new[] { new TypeReference("myInterfaceFqn") } ); Symbols.MapFullyQualifiedNameToType("myClassFqn", classType); bool actual = classType.AnyAncestor(Symbols, t => t.Name == "myInterface"); Assert.False(actual); } } } }
37.691729
100
0.528027
[ "Apache-2.0" ]
costleya/jsii
packages/jsii-dotnet-generator/src/Amazon.JSII.Generator.UnitTests/TypeExtensionsTests.cs
5,015
C#
using System; using System.Collections.Generic; using System.Text; namespace TowerSoft.HtmlToExcel { internal static class Extensions { internal static string SafeTrim(this string thisString) { if (!string.IsNullOrWhiteSpace(thisString)) { return thisString.Trim(); } return string.Empty; } } }
24.866667
65
0.627346
[ "MIT" ]
JordanMarr/HtmlToExcel
HtmlToExcel/Extensions.cs
375
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PingMessage.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // The "ping" message. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Messaging.Messages { using Kephas.ComponentModel.DataAnnotations; /// <summary> /// The "ping" message. /// </summary> [DisplayInfo(Description = "Sends a 'ping' message to the server.")] public class PingMessage : IMessage { } }
37.318182
120
0.477467
[ "MIT" ]
kephas-software/kephas
src/Kephas.Messaging.Messages/Messages/PingMessage.cs
823
C#
// ----------------------------------------------------------------------- // <copyright file="MsSql2005Dialect.cs" company="MicroLite"> // Copyright 2012 - 2015 Project Contributors // // 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 // // </copyright> // ----------------------------------------------------------------------- namespace MicroLite.Dialect { using System; using System.Data; using System.Globalization; using System.Text; using MicroLite.Characters; using MicroLite.Mapping; /// <summary> /// The implementation of <see cref="ISqlDialect"/> for MsSql Server 2005 or later. /// </summary> internal class MsSql2005Dialect : SqlDialect { /// <summary> /// Initialises a new instance of the <see cref="MsSql2005Dialect"/> class. /// </summary> internal MsSql2005Dialect() : base(MsSqlCharacters.Instance) { } public override bool SupportsSelectInsertedIdentifier { get { return true; } } public override SqlQuery BuildSelectInsertIdSqlQuery(IObjectInfo objectInfo) { return new SqlQuery("SELECT SCOPE_IDENTITY()"); } public override SqlQuery PageQuery(SqlQuery sqlQuery, PagingOptions pagingOptions) { if (sqlQuery == null) { throw new ArgumentNullException("sqlQuery"); } var arguments = new SqlArgument[sqlQuery.Arguments.Count + 2]; Array.Copy(sqlQuery.ArgumentsArray, 0, arguments, 0, sqlQuery.Arguments.Count); arguments[arguments.Length - 2] = new SqlArgument(pagingOptions.Offset + 1, DbType.Int32); arguments[arguments.Length - 1] = new SqlArgument(pagingOptions.Offset + pagingOptions.Count, DbType.Int32); var sqlString = SqlString.Parse(sqlQuery.CommandText, Clauses.Select | Clauses.From | Clauses.Where | Clauses.OrderBy); var whereClause = !string.IsNullOrEmpty(sqlString.Where) ? " WHERE " + sqlString.Where : string.Empty; var orderByClause = !string.IsNullOrEmpty(sqlString.OrderBy) ? sqlString.OrderBy : "(SELECT NULL)"; var stringBuilder = new StringBuilder(sqlQuery.CommandText.Length * 2) .AppendFormat(CultureInfo.InvariantCulture, "SELECT * FROM (SELECT {0},ROW_NUMBER() OVER(ORDER BY {1}) AS RowNumber FROM {2}{3}) AS [MicroLitePagedResults]", sqlString.Select, orderByClause, sqlString.From, whereClause) .AppendFormat(CultureInfo.InvariantCulture, " WHERE (RowNumber >= {0} AND RowNumber <= {1})", this.SqlCharacters.GetParameterName(arguments.Length - 2), this.SqlCharacters.GetParameterName(arguments.Length - 1)); return new SqlQuery(stringBuilder.ToString(), arguments); } } }
43.291667
236
0.603144
[ "Apache-2.0" ]
CollaboratingPlatypus/MicroLite
MicroLite/Dialect/MsSql2005Dialect.cs
3,048
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolChatTeamPlayerEntry /// </summary> [DataContract] public partial class LolChatTeamPlayerEntry : IEquatable<LolChatTeamPlayerEntry>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolChatTeamPlayerEntry" /> class. /// </summary> /// <param name="SummonerId">SummonerId.</param> /// <param name="SummonerInternalName">SummonerInternalName.</param> /// <param name="SummonerName">SummonerName.</param> public LolChatTeamPlayerEntry(long? SummonerId = default(long?), string SummonerInternalName = default(string), string SummonerName = default(string)) { this.SummonerId = SummonerId; this.SummonerInternalName = SummonerInternalName; this.SummonerName = SummonerName; } /// <summary> /// Gets or Sets SummonerId /// </summary> [DataMember(Name="summonerId", EmitDefaultValue=false)] public long? SummonerId { get; set; } /// <summary> /// Gets or Sets SummonerInternalName /// </summary> [DataMember(Name="summonerInternalName", EmitDefaultValue=false)] public string SummonerInternalName { get; set; } /// <summary> /// Gets or Sets SummonerName /// </summary> [DataMember(Name="summonerName", EmitDefaultValue=false)] public string SummonerName { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LolChatTeamPlayerEntry {\n"); sb.Append(" SummonerId: ").Append(SummonerId).Append("\n"); sb.Append(" SummonerInternalName: ").Append(SummonerInternalName).Append("\n"); sb.Append(" SummonerName: ").Append(SummonerName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolChatTeamPlayerEntry); } /// <summary> /// Returns true if LolChatTeamPlayerEntry instances are equal /// </summary> /// <param name="other">Instance of LolChatTeamPlayerEntry to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolChatTeamPlayerEntry other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.SummonerId == other.SummonerId || this.SummonerId != null && this.SummonerId.Equals(other.SummonerId) ) && ( this.SummonerInternalName == other.SummonerInternalName || this.SummonerInternalName != null && this.SummonerInternalName.Equals(other.SummonerInternalName) ) && ( this.SummonerName == other.SummonerName || this.SummonerName != null && this.SummonerName.Equals(other.SummonerName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.SummonerId != null) hash = hash * 59 + this.SummonerId.GetHashCode(); if (this.SummonerInternalName != null) hash = hash * 59 + this.SummonerInternalName.GetHashCode(); if (this.SummonerName != null) hash = hash * 59 + this.SummonerName.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
35.825806
158
0.56618
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolChatTeamPlayerEntry.cs
5,553
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("WebServicesDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebServicesDemo")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1d5d6182-fafd-412c-8993-8d8a181258e1")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.722222
84
0.752577
[ "MIT" ]
ranjithmurthy/CrossPlatfomfeedbackMobileApp
WebServicesDemo/Properties/AssemblyInfo.cs
1,361
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 elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// Summary information about a platform branch. /// </summary> public partial class PlatformBranchSummary { private string _branchName; private int? _branchOrder; private string _lifecycleState; private string _platformName; private List<string> _supportedTierList = new List<string>(); /// <summary> /// Gets and sets the property BranchName. /// <para> /// The name of the platform branch. /// </para> /// </summary> public string BranchName { get { return this._branchName; } set { this._branchName = value; } } // Check to see if BranchName property is set internal bool IsSetBranchName() { return this._branchName != null; } /// <summary> /// Gets and sets the property BranchOrder. /// <para> /// An ordinal number that designates the order in which platform branches have been added /// to a platform. This can be helpful, for example, if your code calls the <code>ListPlatformBranches</code> /// action and then displays a list of platform branches. /// </para> /// /// <para> /// A larger <code>BranchOrder</code> value designates a newer platform branch within /// the platform. /// </para> /// </summary> public int BranchOrder { get { return this._branchOrder.GetValueOrDefault(); } set { this._branchOrder = value; } } // Check to see if BranchOrder property is set internal bool IsSetBranchOrder() { return this._branchOrder.HasValue; } /// <summary> /// Gets and sets the property LifecycleState. /// <para> /// The support life cycle state of the platform branch. /// </para> /// /// <para> /// Possible values: <code>beta</code> | <code>supported</code> | <code>deprecated</code> /// | <code>retired</code> /// </para> /// </summary> public string LifecycleState { get { return this._lifecycleState; } set { this._lifecycleState = value; } } // Check to see if LifecycleState property is set internal bool IsSetLifecycleState() { return this._lifecycleState != null; } /// <summary> /// Gets and sets the property PlatformName. /// <para> /// The name of the platform to which this platform branch belongs. /// </para> /// </summary> public string PlatformName { get { return this._platformName; } set { this._platformName = value; } } // Check to see if PlatformName property is set internal bool IsSetPlatformName() { return this._platformName != null; } /// <summary> /// Gets and sets the property SupportedTierList. /// <para> /// The environment tiers that platform versions in this branch support. /// </para> /// /// <para> /// Possible values: <code>WebServer/Standard</code> | <code>Worker/SQS/HTTP</code> /// </para> /// </summary> public List<string> SupportedTierList { get { return this._supportedTierList; } set { this._supportedTierList = value; } } // Check to see if SupportedTierList property is set internal bool IsSetSupportedTierList() { return this._supportedTierList != null && this._supportedTierList.Count > 0; } } }
31.771812
117
0.58365
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/ElasticBeanstalk/Generated/Model/PlatformBranchSummary.cs
4,734
C#
using FluentNHibernate.MappingModel.ClassBased; namespace FluentNHibernate.Visitors { /// <summary> /// Visitor that performs validation against the mapping model. /// </summary> public class ValidationVisitor : DefaultMappingModelVisitor { public ValidationVisitor() { Enabled = true; } public override void ProcessClass(ClassMapping classMapping) { if (!Enabled) return; if (classMapping.Id == null) throw new ValidationException( string.Format("The entity '{0}' doesn't have an Id mapped.", classMapping.Type.Name), "Use the Id method to map your identity property. For example: Id(x => x.Id)", classMapping.Type ); } /// <summary> /// Gets or sets whether validation is performed. /// </summary> public bool Enabled { get; set; } } }
32.322581
106
0.551896
[ "BSD-3-Clause" ]
JamesKovacs/fluent-nhibernate
src/FluentNHibernate/Visitors/ValidationVisitor.cs
1,002
C#
#region license // Copyright (c) HatTrick Labs, LLC. 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. // // The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex #endregion namespace HatTrick.DbEx.Sql { #pragma warning disable IDE1006 // Naming Styles public interface UpdateEntities #pragma warning restore IDE1006 // Naming Styles { /// <summary> /// Construct a TOP clause for a sql UPDATE query expression to limit the number of records updated. /// <para> /// <see href="https://docs.microsoft.com/en-us/sql/t-sql/queries/update-transact-sql">Microsoft docs on UPDATE</see> /// </para> /// </summary> /// <param name="value">The maximum number of records to update in the database.</param> /// <returns><see cref="UpdateEntities"/>, a fluent continuation for constructing a sql UPDATE query expression for updating records.</returns> UpdateEntities Top(int value); /// <summary> /// Construct the FROM clause of a sql UPDATE query expression for updating <typeparamref name="TEntity"/> entities. /// <para> /// <see href="https://docs.microsoft.com/en-us/sql/t-sql/queries/update-transact-sql">Microsoft docs on UPDATE</see> /// </para> /// </summary> /// <returns><see cref="UpdateEntitiesContinuation{TEntity}"/>, a fluent continuation for the construction of a sql UPDATE query expression for updating <typeparamref name="TEntity"/> entities.</returns> UpdateEntitiesContinuation<TEntity> From<TEntity>(Entity<TEntity> entity) where TEntity : class, IDbEntity; } }
47.717391
211
0.691572
[ "Apache-2.0" ]
HatTrickLabs/dbExpression
src/HatTrick.DbEx.Sql/_api/UpdateEntities.cs
2,197
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Abp.Application.Navigation; using Abp.Runtime.Session; namespace WeixinProject.Web.Views.Shared.Components.SideBarNav { public class SideBarNavViewComponent : WeixinProjectViewComponent { private readonly IUserNavigationManager _userNavigationManager; private readonly IAbpSession _abpSession; public SideBarNavViewComponent( IUserNavigationManager userNavigationManager, IAbpSession abpSession) { _userNavigationManager = userNavigationManager; _abpSession = abpSession; } public async Task<IViewComponentResult> InvokeAsync(string activeMenu = "") { var model = new SideBarNavViewModel { MainMenu = await _userNavigationManager.GetMenuAsync("MainMenu", _abpSession.ToUserIdentifier()), ActiveMenuItemName = activeMenu }; return View(model); } } }
31.090909
113
0.67154
[ "MIT" ]
Yuexs/WeixinProject
src/WeixinProject.Web.Mvc/Views/Shared/Components/SideBarNav/SideBarNavViewComponent.cs
1,028
C#
namespace VkLibrary.Tests.Helpers { /// <summary> /// To get your own constants consider creating a new Vkontakte application /// at https://dev.vk.com/apps, get Application Id from there, procceed OAuth to get /// your access token, change Password and Login constant to your own vkontakte login /// and password. After you are done with this, the tests should be running properly. /// ! WARNING ! /// Ensure this file is being ignored via .gitignore file or erace your /// credentials before pull requesting to not be compromised! /// </summary> public class Constants { public const int OfficialApplicationId = 3502561; public const string OfficialApplicationSecret = "omvP3y2MZmpREFZJDNHd"; #region Per-user configuration public const int ApplicationId = 0; // SET YOUR APP ID HERE public const string AccessToken = "SET_YOUR_TOKEN_HERE"; public const string Password = "SET_YOUR_PASS_HERE"; public const string Login = "SET_YOUR_LOGIN_HERE"; #endregion } }
42.307692
90
0.677273
[ "MIT" ]
FrediKats/VkLibrary
VkLibrary.Tests/Helpers/Constants.cs
1,102
C#
using System; using System.Reflection; namespace ValidationService.Areas.HelpPage.ModelDescriptions { public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); } }
21.833333
60
0.755725
[ "MIT" ]
ongzhixian/credit-card
ValidationService/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs
262
C#
/* * Copyright 2010-2013 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. */ 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.OpsWorks.Model { /// <summary> /// Container for the parameters to the DescribeCommands operation. /// <para>Describes the results of specified commands.</para> <para><b>NOTE:</b>You must specify at least one of the parameters.</para> <para> /// <b>Required Permissions</b> : To use this action, an IAM user must have a Show, Deploy, or Manage permissions level for the stack, or an /// attached policy that explicitly grants permissions. For more information on user permissions, see <a /// href="http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html" >Managing User Permissions</a> .</para> /// </summary> public partial class DescribeCommandsRequest : AmazonOpsWorksRequest { private string deploymentId; private string instanceId; private List<string> commandIds = new List<string>(); /// <summary> /// The deployment ID. If you include this parameter, <c>DescribeCommands</c> returns a description of the commands associated with the /// specified deployment. /// /// </summary> public string DeploymentId { get { return this.deploymentId; } set { this.deploymentId = value; } } // Check to see if DeploymentId property is set internal bool IsSetDeploymentId() { return this.deploymentId != null; } /// <summary> /// The instance ID. If you include this parameter, <c>DescribeCommands</c> returns a description of the commands associated with the specified /// instance. /// /// </summary> public string InstanceId { get { return this.instanceId; } set { this.instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this.instanceId != null; } /// <summary> /// An array of command IDs. If you include this parameter, <c>DescribeCommands</c> returns a description of the specified commands. Otherwise, /// it returns a description of every command. /// /// </summary> public List<string> CommandIds { get { return this.commandIds; } set { this.commandIds = value; } } // Check to see if CommandIds property is set internal bool IsSetCommandIds() { return this.commandIds.Count > 0; } } }
35.425532
151
0.636336
[ "Apache-2.0" ]
virajs/aws-sdk-net
AWSSDK_DotNet35/Amazon.OpsWorks/Model/DescribeCommandsRequest.cs
3,330
C#
using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Html; using System; using System.Collections.Generic; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; namespace Maincotech.Web.Components.DocumentMetadata.Renderers { [Flags] enum RendererFlag { BaseHref = 0, Charset = 1 << 1, Meta = 1 << 2, OpenGraph = 1 << 3, Script = 1 << 4, Title = 1 << 5, TitleFormat = 1 << 6, Stylesheet = 1 << 7, UniqueByType = 1 << 8, UniqueByName = 1 << 9 } [JsonConverter(typeof(RendererJsonConverter))] readonly partial struct Renderer : IEquatable<Renderer> { private readonly RendererFlag _flag; private readonly string _name; private readonly string _mainAttributeValue; private readonly int _optionalAttributes; private Renderer(RendererFlag flag, string mainAttributeValue, string name = null, int optionalAttributes = 0) { _flag = flag; _name = name; _mainAttributeValue = mainAttributeValue; _optionalAttributes = optionalAttributes; } public void Render(IHtmlContentBuilder htmlContentBuilder) { switch (GetTypeFlagValue(_flag)) { case RendererFlag.Charset: CharsetRender(htmlContentBuilder);break; case RendererFlag.BaseHref: BaseHrefRender(htmlContentBuilder); break; case RendererFlag.Meta: MetaRender(htmlContentBuilder); break; case RendererFlag.Script: ScriptRender(htmlContentBuilder); break; case RendererFlag.Stylesheet: StylesheetRender(htmlContentBuilder); break; case RendererFlag.Title: TitleRender(htmlContentBuilder); break; } } public bool IsTitleFormat => GetTypeFlagValue(_flag) == RendererFlag.TitleFormat; public bool IsTitle => GetTypeFlagValue(_flag) == RendererFlag.TitleFormat; public string Value => _mainAttributeValue; public int Render(RenderTreeBuilder renderTreeBuilder, int seq, string titleFormat = "{0}") { switch (GetTypeFlagValue(_flag)) { case RendererFlag.Charset: return CharsetRender(renderTreeBuilder, seq); case RendererFlag.BaseHref: return BaseHrefRender(renderTreeBuilder, seq); case RendererFlag.Meta: return MetaRender(renderTreeBuilder, seq); case RendererFlag.Script: return ScriptRender(renderTreeBuilder, seq); case RendererFlag.Stylesheet: return StylesheetRender(renderTreeBuilder, seq); case RendererFlag.Title: return TitleRender(renderTreeBuilder, seq, titleFormat); } return seq; } public bool Equals(Renderer other) { if ((_flag & RendererFlag.UniqueByName) == 0 && _name != other._name) return false; if (GetTypeFlagValue(_flag) != GetTypeFlagValue(other._flag)) return false; return true; } public override bool Equals(object obj) { return Equals((Renderer)obj); } public override int GetHashCode() { return (_flag, _name).GetHashCode(); } public override string ToString() { return JsonSerializer.Serialize(this); } static RendererFlag GetTypeFlagValue(RendererFlag flag) { return (RendererFlag)(byte)flag; } class RendererJsonConverter : JsonConverter<Renderer> { public override Renderer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return default; } public override void Write(Utf8JsonWriter writer, Renderer value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteNumber("flag", (int)value._flag); if (!string.IsNullOrEmpty(value._name)) writer.WriteString("name", value._name); if (!string.IsNullOrEmpty(value._mainAttributeValue)) writer.WriteString("value", value._mainAttributeValue); if (value._optionalAttributes != 0) writer.WriteNumber("opt", value._optionalAttributes); writer.WriteEndObject(); } } } }
37.45082
119
0.610199
[ "MIT" ]
maincotech/webcomponents
src/Maincotech.Web.Components/DocumentMetadata/Renderers/Renderer.cs
4,571
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.Threading.Tasks; using Contoso.GameNetCore.Server.IntegrationTesting; using Contoso.GameNetCore.Testing.xunit; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; namespace ServerComparison.FunctionalTests { public class HelloWorldTests : LoggedTest { public HelloWorldTests(ITestOutputHelper output) : base(output) { } public static TestMatrix TestVariants => TestMatrix.ForServers(ServerType.IISExpress, ServerType.Kestrel, ServerType.Nginx, ServerType.HttpSys) .WithTfms(Tfm.NetCoreApp30) .WithApplicationTypes(ApplicationType.Portable) .WithAllHostingModels() .WithAllArchitectures(); [ConditionalTheory] [MemberData(nameof(TestVariants))] public async Task HelloWorld(TestVariant variant) { var testName = $"HelloWorld_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}"; using (StartLog(out var loggerFactory, variant.Server == ServerType.Nginx ? LogLevel.Trace : LogLevel.Debug, // https://github.com/aspnet/ServerTests/issues/144 testName)) { var logger = loggerFactory.CreateLogger("HelloWorld"); var deploymentParameters = new DeploymentParameters(variant) { ApplicationPath = Helpers.GetApplicationPath() }; if (variant.Server == ServerType.Nginx) { deploymentParameters.ServerConfigTemplateContent = Helpers.GetNginxConfigContent("nginx.conf"); } using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, loggerFactory)) { var deploymentResult = await deployer.DeployAsync(); // Request to base address and check if various parts of the body are rendered & measure the cold startup time. var response = await RetryHelper.RetryRequest(() => { return deploymentResult.HttpClient.GetAsync(string.Empty); }, logger, deploymentResult.HostShutdownToken); var responseText = await response.Content.ReadAsStringAsync(); try { if (variant.Architecture == RuntimeArchitecture.x64) { Assert.Equal("Hello World X64", responseText); } else { Assert.Equal("Hello World X86", responseText); } } catch (XunitException) { logger.LogWarning(response.ToString()); logger.LogWarning(responseText); throw; } // Make sure it was the right server. var serverHeader = response.Headers.Server.ToString(); switch (variant.Server) { case ServerType.HttpSys: Assert.Equal("Microsoft-HTTPAPI/2.0", serverHeader); break; case ServerType.Nginx: Assert.StartsWith("nginx/", serverHeader); break; case ServerType.Kestrel: Assert.Equal("Kestrel", serverHeader); break; case ServerType.IIS: case ServerType.IISExpress: if (variant.HostingModel == HostingModel.OutOfProcess) { Assert.Equal("Kestrel", serverHeader); } else { Assert.StartsWith("Microsoft-IIS/", serverHeader); } break; default: throw new NotImplementedException(variant.Server.ToString()); } } } } } }
42.972973
138
0.498113
[ "Apache-2.0" ]
bclnet/GameNetCore
src/Servers/test/FunctionalTests/HelloWorldTest.cs
4,770
C#
// // TransactionId.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2019 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Threading; using MonoTorrent.BEncoding; namespace MonoTorrent.Dht { static class TransactionId { static int current; public static BEncodedString NextId() { var value = Interlocked.Increment (ref current); var data = new [] { (byte) (value >> 8), (byte) value }; return new BEncodedString(data); } } }
34.085106
73
0.71161
[ "MIT" ]
Peichoto/monotorrent
src/MonoTorrent/MonoTorrent.Dht/TransactionId.cs
1,602
C#
// Method.cs // jQueryUIGenerator/Model // // Copyright 2012 Ivaylo Gochkov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; namespace Saltarelle.JQueryUI.Generator.Model { public class Method { public IList<Argument> Arguments { get; set; } public string Description { get; set; } public string Name { get; set; } public string ReturnType { get; set; } } }
29.548387
75
0.733624
[ "Apache-2.0" ]
Saltarelle/SaltarelleJQueryUI
Generator/Model/Method.cs
918
C#
using System; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace extractor; /// <summary> /// Certain HTTP calls require an HTTP client that is not authenticated. For instance, calls to download a blob with a SAS token. /// </summary> internal class NonAuthenticatedHttpClient { private readonly HttpClient client; public NonAuthenticatedHttpClient(HttpClient client) { if (client.DefaultRequestHeaders.Authorization is not null) { throw new InvalidOperationException("Client cannot have authorization headers."); } this.client = client; } public async ValueTask<Stream> GetSuccessfulResponseStream(Uri uri, CancellationToken cancellationToken) { var response = await client.GetAsync(uri, cancellationToken); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStreamAsync(cancellationToken); } else { var responseContent = await response.Content.ReadAsStringAsync(cancellationToken); var errorMessage = $"Response was unsuccessful. Status code is {response.StatusCode}. Response content was {responseContent}."; throw new InvalidOperationException(errorMessage); } } }
32.317073
139
0.700377
[ "MIT" ]
Azure/apiops
tools/code/extractor/CommonTypes.cs
1,327
C#
/* Copyright 2015 Shane Lillie 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.Threading.Tasks; namespace EnergonSoftware.BackpackPlanner.Core.HockeyApp { /// <summary> /// Platform interface to HockeyApp /// </summary> public interface IHockeyAppManager { /// <summary> /// Gets the application id. /// </summary> /// <value> /// The application id. /// </value> string AppId { get; } /// <summary> /// Gets a value indicating whether this instance is initialized. /// </summary> /// <value> /// <c>true</c> if this instance is initialized; otherwise, <c>false</c>. /// </value> bool IsInitialized { get; } /// <summary> /// Initializes HockeyApp. /// </summary> Task InitAsync(); /// <summary> /// /// </summary> void Destroy(); /// <summary> /// Shows the feedback form. /// </summary> void ShowFeedback(); } }
27.189655
81
0.590996
[ "Apache-2.0" ]
Luminoth/BackpackPlanner
BackpackPlanner/BackpackPlanner/Core/HockeyApp/HockeyAppManager.cs
1,579
C#
using System.Collections.Generic; using Cheque.DomainClasses.Entities.Common; namespace Cheque.DomainClasses.Entities { /// <summary> /// </summary> public class Status : BaseEntity { #region NavigationProperties /// <summary> /// </summary> public virtual ICollection<Cheque> Cheques { get; set; } #endregion #region Properties /// <summary> /// </summary> public virtual string Title { get; set; } /// <summary> /// </summary> public virtual string CustomCode { get; set; } #endregion } }
20.733333
64
0.569132
[ "Apache-2.0" ]
ImanGit/Cheque
Cheque/Cheque.DomainClasses/Entities/Status.cs
624
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTLib2.Bioinfo { partial class PdbDepreciated { public partial class Struct { public interface IRes { string Name { get; } } // BOND //case 'GLY'; {'N -CA -C -O '} //case 'ALA'; {'N -CA -C -O ','CA -CB '} //case 'PRO'; {'N -CA -C -O ','CA -CB -CG -CD ',... // 'N -CD '} //case 'VAL'; {'N -CA -C -O ','CA -CB -CG1',... // 'CB -CG2'} //case 'CYS'; {'N -CA -C -O ','CA -CB -SG '} // %assert(false); % if it comes here, 'CYS' passes the test. remove assertion code //case 'SER'; {'N -CA -C -O ','CA -CB -OG '} //case 'THR'; {'N -CA -C -O ','CA -CB -OG1',... // 'CB -CG2'} //case 'ILE'; {'N -CA -C -O ','CA -CB -CG2',... // 'CB -CG1-CD1'} //case 'LEU'; {'N -CA -C -O ','CA -CB -CG -CD1',... // 'CG -CD2'} //case 'ASP'; {'N -CA -C -O ','CA -CB -CG -OD1',... // 'CG -OD2'} //case 'ASN'; {'N -CA -C -O ','CA -CB -CG -OD1',... // 'CG -ND2'} //case 'HIS'; {'N -CA -C -O ','CA -CB -CG -CD2-NE2',... // 'CG -ND1-CE1-NE2'} //case 'PHE'; {'N -CA -C -O ','CA -CB -CG -CD1-CE1-CZ ',... // 'CG -CD2-CE2-CZ '} //case 'TYR'; {'N -CA -C -O ','CA -CB -CG -CD1-CE1-CZ -OH ',... // 'CG -CD2-CE2-CZ '} //case 'TRP'; {'N -CA -C -O ','CA -CB -CG -CD2-CE3-CZ3-CH2',... // 'CD2-CE2-CZ2-CH2',... // 'CG -CD1-NE1-CE2' } //case 'MET'; {'N -CA -C -O ','CA -CB -CG -SD -CE '} //case 'GLU'; {'N -CA -C -O ','CA -CB -CG -CD -OE1',... // 'CD -OE2'} //case 'GLN'; {'N -CA -C -O ','CA -CB -CG -CD -OE1',... // 'CD -NE2'} //case 'LYS'; {'N -CA -C -O ','CA -CB -CG -CD -CE -NZ '} //case 'ARG'; {'N -CA -C -O ','CA -CB -CG -CD -NE -CZ -NH1',... // 'CZ -NH2'} //case 'GLY'; buildAnglesFromNamess({'N -CA -C -O '}); //case 'ALA'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB '}); //case 'PRO'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD '}); //case 'VAL'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG1',... // 'CA -CB -CG2'}); //case 'CYS'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -SG '}); // %assert(false); //case 'SER'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -OG '}); //case 'THR'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -OG1',... // 'CA -CB -CG2'}); //case 'ILE'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG2',... // 'CA -CB -CG1-CD1'}); //case 'LEU'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD1',... // 'CB -CG -CD2'}); //case 'ASP'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -OD1',... // 'CB -CG -OD2'}); //case 'ASN'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -OD1',... // 'CB -CG -ND2'}); //case 'HIS'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD2-NE2-CE1',... // 'CB -CG -ND1-CE1-NE2'}); //case 'PHE'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD1-CE1-CZ -CE2',... // 'CB -CG -CD2-CE2-CZ '}); //case 'TYR'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD1-CE1-CZ -OH ',... // 'CB -CG -CD2-CE2-CZ -OH '}); //case 'TRP'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD2-CE3-CZ3-CH2-CZ2',... // 'CG -CD2-CE2-CZ2-CH2',... // 'CB -CG -CD1-NE1' }); //case 'MET'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -SD -CE '}); //case 'GLU'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD -OE1',... // 'CG -CD -OE2'}); //case 'GLN'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD -OE1',... // 'CG -CD -NE2'}); //case 'LYS'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD -CE -NZ '}); //case 'ARG'; buildAnglesFromNamess({'N -CA -C -O ','N -CA -CB -CG -CD -NE -CZ -NH1',... } } }
65.032258
111
0.295139
[ "MIT" ]
htna/HCsbLib
HCsbLib/HCsbLib/HTLib2.Bioinfo/Pdb/Depreciated/Struct.BuildBond/Pdb.Struct.BuildBond.cs
6,050
C#
using System; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AOP API: alipay.marketing.card.query /// </summary> public class AlipayMarketingCardQueryRequest : IAopRequest<AlipayMarketingCardQueryResponse> { /// <summary> /// 会员卡查询 /// </summary> public string BizContent { get; set; } #region IAopRequest 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 AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.marketing.card.query"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.063636
96
0.600709
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Request/AlipayMarketingCardQueryRequest.cs
2,547
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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public sealed class EditAndContinueWorkspaceServiceTests : TestBase { private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Mock<IDiagnosticAnalyzerService> _mockDiagnosticService; private readonly MockDebuggeeModuleMetadataProvider _mockDebugeeModuleMetadataProvider; private readonly Mock<IActiveStatementTrackingService> _mockActiveStatementTrackingService; private readonly MockCompilationOutputsProviderService _mockCompilationOutputsService; private Mock<IActiveStatementProvider> _mockActiveStatementProvider; private readonly List<Guid> _modulesPreparedForUpdate; private readonly List<DiagnosticsUpdatedArgs> _emitDiagnosticsUpdated; private int _emitDiagnosticsClearedCount; private readonly List<string> _telemetryLog; private int _telemetryId; public EditAndContinueWorkspaceServiceTests() { _modulesPreparedForUpdate = new List<Guid>(); _mockDiagnosticService = new Mock<IDiagnosticAnalyzerService>(MockBehavior.Strict); _mockDiagnosticService.Setup(s => s.Reanalyze(It.IsAny<Workspace>(), It.IsAny<IEnumerable<ProjectId>>(), It.IsAny<IEnumerable<DocumentId>>(), It.IsAny<bool>())); _diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); _emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); _diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => _emitDiagnosticsUpdated.Add(args); _diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => _emitDiagnosticsClearedCount++; _mockActiveStatementProvider = new Mock<IActiveStatementProvider>(MockBehavior.Strict); _mockActiveStatementProvider.Setup(p => p.GetActiveStatementsAsync(It.IsAny<CancellationToken>())). Returns(Task.FromResult(ImmutableArray<ActiveStatementDebugInfo>.Empty)); _mockDebugeeModuleMetadataProvider = new MockDebuggeeModuleMetadataProvider { IsEditAndContinueAvailable = (Guid guid, out int errorCode, out string localizedMessage) => { errorCode = 0; localizedMessage = null; return true; }, PrepareModuleForUpdate = mvid => _modulesPreparedForUpdate.Add(mvid) }; _mockActiveStatementTrackingService = new Mock<IActiveStatementTrackingService>(MockBehavior.Strict); _mockActiveStatementTrackingService.Setup(s => s.StartTracking(It.IsAny<EditSession>())); _mockActiveStatementTrackingService.Setup(s => s.EndTracking()); _mockCompilationOutputsService = new MockCompilationOutputsProviderService(); _telemetryLog = new List<string>(); } private EditAndContinueWorkspaceService CreateEditAndContinueService(Workspace workspace) => new EditAndContinueWorkspaceService( workspace, _mockActiveStatementTrackingService.Object, _mockCompilationOutputsService, _mockDiagnosticService.Object, _diagnosticUpdateSource, _mockActiveStatementProvider.Object, _mockDebugeeModuleMetadataProvider, reportTelemetry: data => EditAndContinueWorkspaceService.LogDebuggingSessionTelemetry(data, (id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId)); private void VerifyReanalyzeInvocation(params object[] expectedArgs) => _mockDiagnosticService.Invocations.VerifyAndClear((nameof(IDiagnosticAnalyzerService.Reanalyze), expectedArgs)); internal static Guid ReadModuleVersionId(Stream stream) { using (var peReader = new PEReader(stream)) { var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } } private sealed class DesignTimeOnlyDocumentServiceProvider : IDocumentServiceProvider { private sealed class DesignTimeOnlyDocumentPropertiesService : DocumentPropertiesService { public static readonly DesignTimeOnlyDocumentPropertiesService Instance = new DesignTimeOnlyDocumentPropertiesService(); public override bool DesignTimeOnly => true; } TService IDocumentServiceProvider.GetService<TService>() => DesignTimeOnlyDocumentPropertiesService.Instance is TService documentProperties ? documentProperties : DefaultTextDocumentServiceProvider.Instance.GetService<TService>(); } [Fact] public void ActiveStatementTracking() { using (var workspace = new TestWorkspace()) { var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); _mockActiveStatementTrackingService.Verify(ts => ts.StartTracking(It.IsAny<EditSession>()), Times.Once()); service.EndEditSession(); _mockActiveStatementTrackingService.Verify(ts => ts.EndTracking(), Times.Once()); service.EndDebuggingSession(); _mockActiveStatementTrackingService.Verify(ts => ts.StartTracking(It.IsAny<EditSession>()), Times.Once()); _mockActiveStatementTrackingService.Verify(ts => ts.EndTracking(), Times.Once()); } } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(DummyLanguageService))); using (var workspace = new TestWorkspace(exportProvider: exportProviderFactory.CreateExportProvider())) { var solution = workspace.CurrentSolution; var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); workspace.ChangeSolution(document.Project.Solution); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); // no changes: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // change the source: workspace.ChangeDocument(document1.Id, SourceText.From("dummy2")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); } } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }"); var project = workspace.CurrentSolution.Projects.Single(); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class C2 {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, documentServiceProvider: new DesignTimeOnlyDocumentServiceProvider()); workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path).AddDocument(documentInfo)); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); // update a design-time-only source file: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(d => d.Id == documentInfo.Id); workspace.ChangeDocument(document1.Id, SourceText.From("class UpdatedC2 {}")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(d => d.Id == documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var service = CreateEditAndContinueService(workspace); var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.Empty)); service.StartDebuggingSession(); // no changes: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // change the source: workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); } } [Fact] public async Task RunMode_ErrorReadingFile() { var moduleFile = Temp.CreateFile(); using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); // no changes: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // change the source: workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // validate solution update status and emit - changes made during run mode are ignored: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); Assert.Empty(deltas); } } [Fact] public async Task RunMode_FileAdded() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }"); var project = workspace.CurrentSolution.Projects.Single(); workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path)); var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); // add a source file: var document2 = project.AddDocument("file2.cs", SourceText.From("class C2 {}")); workspace.ChangeSolution(document2.Project.Solution); // no changes in document1: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics1); // update in document2: var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC1003" }, diagnostics2.Select(d => d.Id)); // validate solution update status and emit - changes made during run mode are ignored: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task RunMode_Diagnostics() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path)); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); service.StartDebuggingSession(); // no changes: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); // change the source: workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // validate solution update status and emit - changes made during run mode are ignored: solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); Assert.Empty(deltas); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC1003" }, diagnostics.Select(d => d.Id)); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var workspace = TestWorkspace.CreateCSharp(source); var project = workspace.CurrentSolution.Projects.Single(); workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path)); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); // update the document var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From(source)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); service.EndDebuggingSession(); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(DummyLanguageService))); using (var workspace = new TestWorkspace(exportProvider: exportProviderFactory.CreateExportProvider())) { var solution = workspace.CurrentSolution; var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); workspace.ChangeSolution(document.Project.Solution); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change the source: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("dummy2")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); Assert.Empty(deltas); } } [Fact] public async Task BreakMode_DesignTimeOnlyDocument() { var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(DummyLanguageService))); using var workspace = TestWorkspace.CreateCSharp("class C {}"); var project = workspace.CurrentSolution.Projects.Single(); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, documentServiceProvider: new DesignTimeOnlyDocumentServiceProvider()); var solution = workspace.CurrentSolution.AddDocument(documentInfo); workspace.ChangeSolution(solution); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change the source: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(d => d.Id == documentInfo.Id); workspace.ChangeDocument(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); Assert.Empty(deltas); } [Fact] public async Task BreakMode_ErrorReadingFile() { var moduleFile = Temp.CreateFile(); using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change the source: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); Assert.Empty(diagnostics); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); Assert.Empty(_emitDiagnosticsUpdated); Assert.Equal(0, _emitDiagnosticsClearedCount); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); Assert.Empty(deltas); Assert.Equal(1, _emitDiagnosticsClearedCount); var eventArgs = _emitDiagnosticsUpdated.Single(); Assert.Null(eventArgs.DocumentId); Assert.Equal(project.Id, eventArgs.ProjectId); AssertEx.Equal(new[] { "ENC1001" }, eventArgs.Diagnostics.Select(d => d.Id)); _emitDiagnosticsUpdated.Clear(); _emitDiagnosticsClearedCount = 0; service.EndEditSession(); Assert.Empty(_emitDiagnosticsUpdated); Assert.Equal(0, _emitDiagnosticsClearedCount); service.EndDebuggingSession(); Assert.Empty(_emitDiagnosticsUpdated); Assert.Equal(1, _emitDiagnosticsClearedCount); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task BreakMode_FileAdded() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }"); var project = workspace.CurrentSolution.Projects.Single(); workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path)); var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); _mockDebugeeModuleMetadataProvider.IsEditAndContinueAvailable = (Guid guid, out int errorCode, out string localizedMessage) => { errorCode = 123; localizedMessage = "*message*"; return false; }; _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // add a source file: var document2 = project.AddDocument("file2.cs", SourceText.From("class C2 {}")); workspace.ChangeSolution(document2.Project.Solution); // update in document2: var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC2123" }, diagnostics2.Select(d => d.Id)); // validate solution update status and emit - changes made during run mode are ignored: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); service.EndEditSession(); service.EndDebuggingSession(); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; var expectedMessage = "ENC2123: " + string.Format(FeaturesResources.EditAndContinueDisallowedByProject, "Test", "*message*"); var expectedDiagnostics = new[] { "[17..19): " + expectedMessage, "[66..67): " + expectedMessage, "[101..101): " + expectedMessage, "[136..137): " + expectedMessage, }; string inspectDiagnostic(Diagnostic d) => $"{d.Location.SourceSpan}: {d.Id}: {d.GetMessage()}"; using (var workspace = TestWorkspace.CreateCSharp(source1)) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); bool isEditAndContinueAvailableInvocationAllowed = true; _mockDebugeeModuleMetadataProvider.IsEditAndContinueAvailable = (Guid guid, out int errorCode, out string localizedMessage) => { Assert.True(isEditAndContinueAvailableInvocationAllowed); Assert.Equal(moduleId, guid); errorCode = 123; localizedMessage = "*message*"; return false; }; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source: var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From(source2)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); isEditAndContinueAvailableInvocationAllowed = true; var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(expectedDiagnostics, diagnostics1.Select(inspectDiagnostic)); // the diagnostic should be cached and we should not invoke isEditAndContinueAvailable again: isEditAndContinueAvailableInvocationAllowed = false; var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(expectedDiagnostics, diagnostics2.Select(inspectDiagnostic)); // invalidate cache: service.Test_GetEditSession().ModuleInstanceLoadedOrUnloaded(moduleId); isEditAndContinueAvailableInvocationAllowed = true; var diagnostics3 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(expectedDiagnostics, diagnostics3.Select(inspectDiagnostic)); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); Assert.Empty(deltas); service.EndEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2123" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits() { var moduleId = Guid.NewGuid(); using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source (rude edit): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M1() { System.Console.WriteLine(1); } }")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_will_prevent_the_debug_session_from_continuing, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); Assert.Empty(deltas); service.EndEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source (compilation error): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Empty(diagnostics1); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); Assert.Empty(deltas); service.EndEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source (compilation error): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); Assert.Empty(deltas); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { "CS0266" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); _emitDiagnosticsUpdated.Clear(); _emitDiagnosticsClearedCount = 0; service.EndEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using (var workspace = TestWorkspace.CreateCSharp("class Program { void Main() { System.Console.WriteLine(1); } }")) { var solution = workspace.CurrentSolution; var projectA = solution.Projects.Single(); workspace.ChangeSolution(solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution); var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change C.cs to have a compilation error: var projectC = workspace.CurrentSolution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); workspace.ChangeDocument(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: "Common.cs", CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); // No changes in project containing file B.cs. solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: "B.cs", CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, solutionStatus); // All projects must have no errors. solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); service.EndEditSession(); service.EndDebuggingSession(); } } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = Temp.CreateFile().WriteAllBytes(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); var editSession = service.Test_GetEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Empty(diagnostics1); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "CS8055" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); _emitDiagnosticsUpdated.Clear(); _emitDiagnosticsClearedCount = 0; // no emitted delta: Assert.Empty(deltas); // no pending update: Assert.Null(service.Test_GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => service.CommitSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => service.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); // no open module readers since we didn't defer any module update: Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); // solution update status after discarding an update (still has update ready): var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, commitedUpdateSolutionStatus); service.EndEditSession(); Assert.Empty(_emitDiagnosticsUpdated); Assert.Equal(0, _emitDiagnosticsClearedCount); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); service.EndDebuggingSession(); Assert.Empty(_emitDiagnosticsUpdated); Assert.Equal(1, _emitDiagnosticsClearedCount); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful(bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = Temp.CreateFile().WriteAllBytes(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); var editSession = service.Test_GetEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); // change the source (valid edit): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Empty(diagnostics1); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); AssertEx.Empty(emitDiagnosticsUpdated); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); // check emitted delta: var delta = deltas.Single(); Assert.Empty(delta.ActiveStatementsInUpdatedMethods); Assert.NotEmpty(delta.IL.Value); Assert.NotEmpty(delta.Metadata.Bytes); Assert.NotEmpty(delta.Pdb.Stream); Assert.Equal(0x06000001, delta.Pdb.UpdatedMethods.Single()); Assert.Equal(moduleId, delta.Mvid); Assert.Empty(delta.NonRemappableRegions); Assert.Empty(delta.LineEdits); // the update should be stored on the service: var pendingUpdate = service.Test_GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(deltas, pendingUpdate.Deltas); Assert.Empty(pendingUpdate.ModuleReaders); Assert.Equal(project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { // all update providers either provided updates or had no change to apply: service.CommitSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); // no open module readers since we didn't defer any module update: Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); // verify that baseline is added: Assert.Same(newBaseline, editSession.DebuggingSession.Test_GetProjectEmitBaseline(project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); } else { // another update provider blocked the update: service.DiscardSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, discardedUpdateSolutionStatus); } service.EndEditSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); service.EndDebuggingSession(); VerifyReanalyzeInvocation(workspace, null, ImmutableArray<DocumentId>.Empty, false); AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); } // the debugger disposes the module metadata and SymReader: debuggeeModuleInfo.Dispose(); Assert.True(moduleMetadata.IsDisposed); Assert.Null(debuggeeModuleInfo.SymReader); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0", }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbStream.ToArray()); var moduleId = moduleMetadata.GetModuleVersionId(); using var workspace = TestWorkspace.CreateCSharp(sourceV1); var project = workspace.CurrentSolution.Projects.Single(); var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path, pdbFile.Path)); // set up an active statement in the first method, so that we can test preservation of local signature. _mockActiveStatementProvider = new Mock<IActiveStatementProvider>(MockBehavior.Strict); _mockActiveStatementProvider.Setup(p => p.GetActiveStatementsAsync(It.IsAny<CancellationToken>())). Returns(Task.FromResult(ImmutableArray.Create(new ActiveStatementDebugInfo( new ActiveInstructionId(moduleId, methodToken: 0x06000001, methodVersion: 1, ilOffset: 0), documentNameOpt: document1.Name, linePositionSpan: new LinePositionSpan(new LinePosition(0, 15), new LinePosition(0, 16)), threadIds: ImmutableArray.Create(Guid.NewGuid()), ActiveStatementFlags.IsLeafFrame)))); // module not loaded _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); var editSession = service.Test_GetEditSession(); // change the source (valid edit): workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); // delta to apply: var delta = deltas.Single(); Assert.Empty(delta.ActiveStatementsInUpdatedMethods); Assert.NotEmpty(delta.IL.Value); Assert.NotEmpty(delta.Metadata.Bytes); Assert.NotEmpty(delta.Pdb.Stream); Assert.Equal(0x06000002, delta.Pdb.UpdatedMethods.Single()); Assert.Equal(moduleId, delta.Mvid); Assert.Empty(delta.NonRemappableRegions); Assert.Empty(delta.LineEdits); // the update should be stored on the service: var pendingUpdate = service.Test_GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = pendingUpdate.ModuleReaders; Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { service.CommitSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); // deferred module readers tracked: var baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, editSession.DebuggingSession.Test_GetProjectEmitBaseline(project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); service.EndEditSession(); // make another update: service.StartEditSession(); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); service.EndEditSession(); service.EndDebuggingSession(); // open module readers should be disposed when the debugging session ends: Assert.Throws<ObjectDisposedException>(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); Assert.Throws<ObjectDisposedException>(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); } else { service.DiscardSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // no open module readers since we didn't defer any module update: Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); Assert.Throws<ObjectDisposedException>(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); Assert.Throws<ObjectDisposedException>(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); service.EndEditSession(); service.EndDebuggingSession(); } } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll, assemblyName: "B"); var (peImageA, symReaderA) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationA, DebugInformationFormat.PortablePdb); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var debuggeeModuleInfoA = new DebuggeeModuleInfo(moduleMetadataA, symReaderA); var pdbStreamB = new MemoryStream(); var peImageB = compilationB.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStreamB); pdbStreamB.Position = 0; var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbStreamB.ToArray()); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using (var workspace = TestWorkspace.CreateCSharp(source1)) { var solution = workspace.CurrentSolution; var projectA = solution.Projects.Single(); var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1).Project; workspace.ChangeSolution(projectB.Solution); _mockCompilationOutputsService.Outputs.Add(projectA.Id, new CompilationOutputFiles(moduleFileA.Path)); _mockCompilationOutputsService.Outputs.Add(projectB.Id, new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path)); // only module A is loaded _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => (mvid == moduleIdA) ? debuggeeModuleInfoA : null; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); var editSession = service.Test_GetEditSession(); // // First update. // workspace.ChangeDocument(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); workspace.ChangeDocument(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); var deltaA = deltas.Single(d => d.Mvid == moduleIdA); var deltaB = deltas.Single(d => d.Mvid == moduleIdB); Assert.Equal(2, deltas.Length); // the update should be stored on the service: var pendingUpdate = service.Test_GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = pendingUpdate.ModuleReaders; Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); service.CommitSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); // deferred module readers tracked: var baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); service.EndEditSession(); service.StartEditSession(); editSession = service.Test_GetEditSession(); // // Second update. // workspace.ChangeDocument(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); workspace.ChangeDocument(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); deltaA = deltas.Single(d => d.Mvid == moduleIdA); deltaB = deltas.Single(d => d.Mvid == moduleIdB); Assert.Equal(2, deltas.Length); // the update should be stored on the service: pendingUpdate = service.Test_GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: Assert.Empty(pendingUpdate.ModuleReaders); service.CommitSolutionUpdate(); Assert.Null(service.Test_GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); service.EndEditSession(); service.EndDebuggingSession(); // open deferred module readers should be dispose when the debugging session ends: Assert.Throws<ObjectDisposedException>(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); Assert.Throws<ObjectDisposedException>(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); } } [Fact] public void GetSpansInNewDocument() { // 012345678901234567890 // 012___890_3489____0 var changes = new[] { new TextChange(new TextSpan(3, 5), "___"), new TextChange(new TextSpan(11, 2), "_"), new TextChange(new TextSpan(15, 3), ""), new TextChange(new TextSpan(20, 0), "____"), }; Assert.Equal("012___890_3489____0", SourceText.From("012345678901234567890").WithChanges(changes).ToString()); AssertEx.Equal(new[] { "[3..6)", "[9..10)", "[12..12)", "[14..18)" }, EditAndContinueWorkspaceService.GetSpansInNewDocument(changes).Select(s => s.ToString())); } [Fact] public async Task GetDocumentTextChangesAsync() { var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(source1); var newTree = SyntaxFactory.ParseSyntaxTree(source2); var changes = await EditAndContinueWorkspaceService.GetDocumentTextChangesAsync(oldTree, newTree, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "[17..17) '\r\n'", "[64..65) '9'", "[98..99) ''", "[133..133) '0'" }, changes.Select(s => $"{s.Span} '{s.NewText}'")); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }); // module not loaded _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change the source (valid edit): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC1001" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); } } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) { var project = workspace.CurrentSolution.Projects.Single(); _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException(), }); // module not loaded _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; var service = CreateEditAndContinueService(workspace); service.StartDebuggingSession(); service.StartEditSession(); // change the source (valid edit): var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { "ENC1001" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); service.EndEditSession(); service.EndDebuggingSession(); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } } }
53.012133
227
0.653396
[ "Apache-2.0" ]
bgrainger/roslyn
src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
83,019
C#
using System; using System.Collections; using CMS.Ecommerce; using CMS.Helpers; using CMS.UIControls; public partial class CMSModules_Ecommerce_FormControls_Cloning_Ecommerce_AddressSettings : CloneSettingsControl { #region "Properties" /// <summary> /// Gets properties hashtable. /// </summary> public override Hashtable CustomParameters { get { return GetProperties(); } } /// <summary> /// Hide display name. /// </summary> public override bool HideDisplayName { get { return true; } } #endregion #region "Methods" protected void Page_Load(object sender, EventArgs e) { if (!RequestHelper.IsPostBack()) { AddressInfo address = (AddressInfo)InfoToClone; txtAddress1.Text = address.AddressLine1; txtAddress2.Text = address.AddressLine2; txtPersonalName.Text = address.AddressPersonalName; } } /// <summary> /// Returns properties hashtable. /// </summary> private Hashtable GetProperties() { Hashtable result = new Hashtable(); result[AddressInfo.OBJECT_TYPE + ".address1"] = txtAddress1.Text; result[AddressInfo.OBJECT_TYPE + ".address2"] = txtAddress2.Text; result[AddressInfo.OBJECT_TYPE + ".personalname"] = txtPersonalName.Text; return result; } #endregion }
23.151515
112
0.588351
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/Ecommerce/FormControls/Cloning/Ecommerce_AddressSettings.ascx.cs
1,530
C#
// Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. using System; namespace IdentityServerHost.Quickstart.UI { public class AccountOptions { public static bool AllowLocalLogin = true; public static bool AllowRememberLogin = true; public static TimeSpan RememberMeLoginDuration = TimeSpan.FromDays(30); public static bool ShowLogoutPrompt = true; public static bool AutomaticRedirectAfterSignOut = false; public static string InvalidCredentialsErrorMessage = "Invalid username or password"; } }
29.666667
93
0.731942
[ "Apache-2.0" ]
AthosSchrapett/erudio-microservices-dotnet6
GeekShopping/GeekShopping.IdentityServer/MainModule/Account/AccountOptions.cs
625
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CBTTaskHorseUncontrolableDef : IBehTreeHorseTaskDefinition { public CBTTaskHorseUncontrolableDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskHorseUncontrolableDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.869565
140
0.761232
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CBTTaskHorseUncontrolableDef.cs
779
C#
// Copyright (c) Jan Škoruba. All Rights Reserved. // Licensed under the Apache License, Version 2.0. using System; namespace Skoruba.Duende.IdentityServer.Admin.BusinessLogic.Shared.ExceptionHandling { public class UserFriendlyErrorPageException : Exception { public string ErrorKey { get; set; } public UserFriendlyErrorPageException(string message) : base(message) { } public UserFriendlyErrorPageException(string message, string errorKey) : base(message) { ErrorKey = errorKey; } public UserFriendlyErrorPageException(string message, Exception innerException) : base(message, innerException) { } } }
27.769231
119
0.67313
[ "Apache-2.0" ]
CentauriConsulting/Duende.IdentityServer.Admin
src/Skoruba.Duende.IdentityServer.Admin.BusinessLogic.Shared/ExceptionHandling/UserFriendlyErrorPageException.cs
725
C#
using Newtonsoft.Json; namespace JsonApiDotNetCore.Models.JsonApiDocuments { public sealed class ResourceLinks { /// <summary> /// https://jsonapi.org/format/#document-resource-object-links /// </summary> [JsonProperty("self", NullValueHandling = NullValueHandling.Ignore)] public string Self { get; set; } } }
26
76
0.651099
[ "MIT" ]
bjornharrtell/JsonApiDotNetCore
src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceLinks.cs
364
C#
using System; using CCLLC.Telemetry; namespace CCLLC.Xrm.AppInsights { public class XrmAppInsightsClient : IXrmAppInsightsClient { private IEventLogger logger; public ITelemetryClient TelemetryClient { get; private set; } public ITelemetryFactory TelemetryFactory { get; private set; } internal protected XrmAppInsightsClient(ITelemetryFactory factory, IComponentTelemetryClient client, IEventLogger logger) { this.logger = logger; this.TelemetryFactory = factory; this.TelemetryClient = client; } public IOperationalTelemetryClient<IDependencyTelemetry> StartDependencyOperation(string dependencyType = "Web", string target = "", string dependencyName ="PluginWebRequest") { var dependencyTelemetry = TelemetryFactory.BuildDependencyTelemetry( dependencyType, target, dependencyName, null); return TelemetryClient.StartOperation<IDependencyTelemetry>(dependencyTelemetry); } public void Trace(string message, params object[] args) { Trace(eMessageType.Information, message, args); } public void Trace(eMessageType type, string message, params object[] args) { try { if (this.TelemetryFactory != null && this.TelemetryClient != null && !string.IsNullOrEmpty(message)) { var level = eSeverityLevel.Information; if (type == eMessageType.Warning) { level = eSeverityLevel.Warning; } else if (type == eMessageType.Error) { level = eSeverityLevel.Error; } if (this.TelemetryClient != null && this.TelemetryFactory != null) { var msgTelemetry = this.TelemetryFactory.BuildMessageTelemetry(string.Format(message, args), level); this.TelemetryClient.Track(msgTelemetry); } } } catch(Exception ex) { logger.LogError(ex.Message); } } public void TrackEvent(string name) { try { if (this.TelemetryFactory != null && this.TelemetryClient != null && !string.IsNullOrEmpty(name)) { this.TelemetryClient.Track(this.TelemetryFactory.BuildEventTelemetry(name)); } } catch (Exception ex) { logger.LogError(ex.Message); } } public void TrackException(Exception ex) { try { if (this.TelemetryFactory != null && this.TelemetryClient != null && ex != null) { this.TelemetryClient.Track(this.TelemetryFactory.BuildExceptionTelemetry(ex)); } } catch (Exception e) { logger.LogError(e.Message); } } } }
34.010417
183
0.524043
[ "MIT" ]
ScottColson/CCLCC
XrmAppInsightsConnector/XrmAppInsightsClient.cs
3,267
C#