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
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ // This C# code was generated by XmlSchemaClassGenerator version 1.0.0.0. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.CodeDom.Compiler; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics; using System.Xml.Serialization; namespace Models.XsdConvert.genericRailML { [GeneratedCodeAttribute("XmlSchemaClassGenerator", "1.0.0.0")] [SerializableAttribute()] [XmlTypeAttribute("tOperationControlPoint", Namespace="https://www.railml.org/schemas/2018")] [DebuggerStepThroughAttribute()] [DesignerCategoryAttribute("code")] [XmlIncludeAttribute(typeof(genericRailML.EOcp))] internal partial class TOperationControlPoint : TOcpWithIDAndName { [XmlIgnoreAttribute()] private Collection<genericRailML.TElementRefInGroup> _controllerRef; /// <summary> /// <para>reference from OCP to a Controller</para> /// </summary> [XmlElementAttribute("controllerRef", Order=0)] public Collection<genericRailML.TElementRefInGroup> ControllerRef { get { return this._controllerRef; } private set { this._controllerRef = value; } } /// <summary> /// <para xml:lang="de">Ruft einen Wert ab, der angibt, ob die ControllerRef-Collection leer ist.</para> /// <para xml:lang="en">Gets a value indicating whether the ControllerRef collection is empty.</para> /// </summary> [XmlIgnoreAttribute()] [NotMappedAttribute()] public bool ControllerRefSpecified { get { return (this.ControllerRef.Count != 0); } } /// <summary> /// <para xml:lang="de">Initialisiert eine neue Instanz der <see cref="TOperationControlPoint" /> Klasse.</para> /// <para xml:lang="en">Initializes a new instance of the <see cref="TOperationControlPoint" /> class.</para> /// </summary> public TOperationControlPoint() { this._controllerRef = new Collection<genericRailML.TElementRefInGroup>(); } /// <summary> /// <para>DEPRECATED: use the 'designator' with its parameters 'register' and 'entry' instead</para> /// </summary> [XmlAttributeAttribute("number")] public string Number { get; set; } /// <summary> /// <para>DEPRECATED: use the 'designator' with its parameters 'register' and 'entry' instead</para> /// </summary> [XmlAttributeAttribute("abbrevation")] public string Abbrevation { get; set; } /// <summary> /// <para>timezone as defined in the tz database, e.g. "America/New_York"</para> /// </summary> [XmlAttributeAttribute("timezone")] public string Timezone { get; set; } /// <summary> /// <para>references the one and only parent ocp of this ocp</para> /// <para>an XML-side constrained reference to one xs:ID value, acts across an XML file including its outsourced components (xi:include mechanism)</para> /// </summary> [XmlAttributeAttribute("parentOcpRef")] public string ParentOcpRef { get; set; } } }
38.09901
161
0.595374
[ "Apache-2.0" ]
LightosLimited/RailML
v2.4/Models/XsdConvert/genericRailML/TOperationControlPoint.cs
3,848
C#
using ESR.Global; using System.ComponentModel; namespace ESR.UI { public class ToastMessageItem : INotifyPropertyChanged { public ESRState State { get; set; } = ESRState.Stop; public string ToastMessage { get; set; } = string.Empty; public string ToastImageSource { get; set; } = string.Empty; public string ToastBGColor { get; set; } = string.Empty; public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } public void UpdateProperties() { this.NotifyPropertyChanged("ToastImageSource"); this.NotifyPropertyChanged("ToastMessage"); this.NotifyPropertyChanged("ToastBGColor"); } } }
28.53125
83
0.644031
[ "MIT" ]
scanhand/EasyRecorder
Src/EasyRecorder/UI/ToastMessageItem.cs
915
C#
namespace WinIO.FluentWPF.Utility { sealed class VersionInfos { public static VersionInfo Windows7 { get { return new VersionInfo(6, 1, 7600); } } public static VersionInfo Windows7_SP1 { get { return new VersionInfo(6, 1, 7601); } } public static VersionInfo Windows8 { get { return new VersionInfo(6, 2, 9200); } } public static VersionInfo Windows8_1 { get { return new VersionInfo(6, 3, 9600); } } public static VersionInfo Windows10 { get { return new VersionInfo(10, 0, 10240); } } public static VersionInfo Windows10_1511 { get { return new VersionInfo(10, 0, 10586); } } public static VersionInfo Windows10_1607 { get { return new VersionInfo(10, 0, 14393); } } public static VersionInfo Windows10_1703 { get { return new VersionInfo(10, 0, 15063); } } public static VersionInfo Windows10_1709 { get { return new VersionInfo(10, 0, 16299); } } public static VersionInfo Windows10_1803 { get { return new VersionInfo(10, 0, 17134); } } public static VersionInfo Windows10_1809 { get { return new VersionInfo(10, 0, 17763); } } public static VersionInfo Windows10_1903 { get { return new VersionInfo(10, 0, 18362); } } public static VersionInfo Windows10_1909 { get { return new VersionInfo(10, 0, 18363); } } public static VersionInfo Windows10_2004 { get { return new VersionInfo(10, 0, 19041); } } public static VersionInfo Windows10_20H2 { get { return new VersionInfo(10, 0, 19042); } } public static VersionInfo Windows10_21H1 { get { return new VersionInfo(10, 0, 19043); } } public static VersionInfo Windows11_Preview { get { return new VersionInfo(10, 0, 21327); } } // TBD } }
67.153846
110
0.678121
[ "Apache-2.0" ]
sak9188/WinIO2
WinIO/WinIO/FluentWPF/Utility/VersionInfos.cs
1,746
C#
using Signals.Aspects.DI.Attributes; using Signals.Core.Processes.Base; using Signals.Core.Processing.Results; namespace Signals.Core.Processes.Business { /// <summary> /// Represents a business process /// </summary> public interface IBusinessProcess { } /// <summary> /// Represents a business process /// </summary> public abstract class BusinessProcess<TResponse> : BaseProcess<TResponse>, IBusinessProcess where TResponse : VoidResult, new() { /// <summary> /// Business process context /// </summary> [Import] protected virtual IBusinessProcessContext Context { get => _context; set { (value as BusinessProcessContext).SetProcess(this); _context = value; } } private IBusinessProcessContext _context; /// <summary> /// Base process context upcasted from Business process context /// </summary> internal override IBaseProcessContext BaseContext => Context; /// <summary> /// Authentication and authorization layer /// </summary> /// <returns></returns> public abstract TResponse Auth(); /// <summary> /// Validation layer /// </summary> /// <returns></returns> public abstract TResponse Validate(); /// <summary> /// Execution layer /// </summary> /// <returns></returns> public abstract TResponse Handle(); /// <summary> /// Execution using base strategy /// </summary> /// <returns></returns> internal virtual TResponse Execute() { var result = Auth(); if (result.IsFaulted) return result; result = Validate(); if (result.IsFaulted) return result; result = Handle(); return result; } /// <summary> /// Entry point executed by the factory /// </summary> /// <param name="args"></param> /// <returns></returns> internal override TResponse ExecuteProcess(params object[] args) { return Execute(); } } /// <summary> /// Represents a business process /// </summary> public abstract class BusinessProcess<T1, TResponse> : BaseProcess<TResponse>, IBusinessProcess where TResponse : VoidResult, new() { /// <summary> /// Business process context /// </summary> [Import] protected virtual IBusinessProcessContext Context { get => _context; set { (value as BusinessProcessContext).SetProcess(this); _context = value; } } private IBusinessProcessContext _context; /// <summary> /// Base process context upcasted from Business process context /// </summary> internal override IBaseProcessContext BaseContext => Context; /// <summary> /// Authentication and authorization layer /// </summary> /// <param name="obj1"></param> /// <returns></returns> public abstract TResponse Auth(T1 obj1); /// <summary> /// Validation layer /// </summary> /// <param name="obj1"></param> /// <returns></returns> public abstract TResponse Validate(T1 obj1); /// <summary> /// Execution layer /// </summary> /// <param name="obj1"></param> /// <returns></returns> public abstract TResponse Handle(T1 obj1); /// <summary> /// Execution using base strategy /// </summary> /// <param name="obj1"></param> /// <returns></returns> internal virtual TResponse Execute(T1 obj1) { var result = Auth(obj1); if (result.IsFaulted) return result; result = Validate(obj1); if (result.IsFaulted) return result; result = Handle(obj1); return result; } /// <summary> /// Entry point executed by the factory /// </summary> /// <param name="args"></param> /// <returns></returns> internal override TResponse ExecuteProcess(params object[] args) { var obj1 = (T1)args[0]; return Execute(obj1); } } /// <summary> /// Represents a business process /// </summary> public abstract class BusinessProcess<T1, T2, TResponse> : BaseProcess<TResponse>, IBusinessProcess where TResponse : VoidResult, new() { /// <summary> /// Business process context /// </summary> [Import] protected virtual IBusinessProcessContext Context { get => _context; set { (value as BusinessProcessContext).SetProcess(this); _context = value; } } private IBusinessProcessContext _context; /// <summary> /// Base process context upcasted from Business process context /// </summary> internal override IBaseProcessContext BaseContext => Context; /// <summary> /// Authentication and authorization layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> public abstract TResponse Auth(T1 obj1, T2 obj2); /// <summary> /// Validation layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> public abstract TResponse Validate(T1 obj1, T2 obj2); /// <summary> /// Execution layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> public abstract TResponse Handle(T1 obj1, T2 obj2); /// <summary> /// Execution using base strategy /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> internal virtual TResponse Execute(T1 obj1, T2 obj2) { var result = Auth(obj1, obj2); if (result.IsFaulted) return result; result = Validate(obj1, obj2); if (result.IsFaulted) return result; result = Handle(obj1, obj2); return result; } /// <summary> /// Entry point executed by the factory /// </summary> /// <param name="args"></param> /// <returns></returns> internal override TResponse ExecuteProcess(params object[] args) { var obj1 = (T1)args[0]; var obj2 = (T2)args[1]; return Execute(obj1, obj2); } } /// <summary> /// Represents a business process /// </summary> public abstract class BusinessProcess<T1, T2, T3, TResponse> : BaseProcess<TResponse>, IBusinessProcess where TResponse : VoidResult, new() { /// <summary> /// Business process context /// </summary> [Import] protected virtual IBusinessProcessContext Context { get => _context; set { (value as BusinessProcessContext).SetProcess(this); _context = value; } } private IBusinessProcessContext _context; /// <summary> /// Base process context upcasted from Business process context /// </summary> internal override IBaseProcessContext BaseContext => Context; /// <summary> /// Authentication and authorization layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <param name="obj3"></param> /// <returns></returns> public abstract TResponse Auth(T1 obj1, T2 obj2, T3 obj3); /// <summary> /// Validation layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <param name="obj3"></param> /// <returns></returns> public abstract TResponse Validate(T1 obj1, T2 obj2, T3 obj3); /// <summary> /// Execution layer /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <param name="obj3"></param> /// <returns></returns> public abstract TResponse Handle(T1 obj1, T2 obj2, T3 obj3); /// <summary> /// Execution using base strategy /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <param name="obj3"></param> /// <returns></returns> internal virtual TResponse Execute(T1 obj1, T2 obj2, T3 obj3) { var result = Auth(obj1, obj2, obj3); if (result.IsFaulted) return result; result = Validate(obj1, obj2, obj3); if (result.IsFaulted) return result; result = Handle(obj1, obj2, obj3); return result; } /// <summary> /// Entry point executed by the factory /// </summary> /// <param name="args"></param> /// <returns></returns> internal override TResponse ExecuteProcess(params object[] args) { var obj1 = (T1)args[0]; var obj2 = (T2)args[1]; var obj3 = (T3)args[2]; return Execute(obj1, obj2, obj3); } } }
30.578275
90
0.533382
[ "MIT" ]
acid996/Signals
src/10 Core/Signals.Core/Processes/Business/BusinessProcess.cs
9,573
C#
namespace FileUtils { public interface IAppConfig { } public class AppConfig { public string User; public string Pass; public string Domain; public string Path; public bool IsLocalFileSystem; public string DBConnectionString; } }
15.611111
41
0.661922
[ "MIT" ]
valueduser/FileUtils
FileUtils/AppConfig.cs
283
C#
using API.Configurations; using API.Middlewares; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Domain; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Microsoft.Extensions.FileProviders; using System.IO; using Microsoft.AspNetCore.Http; namespace API { public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; Environment = env; } public IConfiguration Configuration { get; } public IWebHostEnvironment Environment { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddJsonOptionsConfiguration(); services.AddConnectionProviders(Configuration, Environment) .AddJsonWebTokenConfiguration(Configuration) .AddAuthorizationConfiguration() .AddCorsConfiguration(Configuration) .AddApiBehaviorOptionsConfiguration() .AddSupervisorConfiguration() .AddIdentityConfiguration(Configuration) .AddHttpContextAccessor() .AddEmailServiceConfiguration() .AddRemoveNull204FormatterConfigration() .AddSpaStaticFiles(spa => { spa.RootPath = "wwwroot"; }); services.Configure<MvcOptions>(ApiDefaults.Configure); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // if request does not contain api it will also work app.UsePathBase("/api"); if (env.IsDevelopment()) { app.UseCors(ApiConstants.Cors.AllowAll); } else { app.UseCors(ApiConstants.Cors.WithOrigins); // 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.UseDefaultFiles(); app.UseSpaStaticFiles(); app.UseSpaStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets", "fonts")), RequestPath = "/wwwroot/assets/fonts", OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "private, max-age=86400, stale-while-revalidate=604800"); } }); app.UseSpaStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets", "iconfont")), RequestPath = "/wwwroot/assets/iconfont", OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "private, max-age=86400, stale-while-revalidate=604800"); } }); app.UseMiddleware<ErrorHandlingMiddleware>(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseSerilogRequestLogging(); app.SeedDatabase(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSpa(spa => { spa.Options.SourcePath = "wwwroot"; }); } } }
34.302521
143
0.580353
[ "MIT" ]
omikolaj/odiam-dot-net-api-starter
API/Startup.cs
4,082
C#
namespace CallTargetNativeTest { // *** With3Arguments class With3Arguments { public void VoidMethod(string arg1, int arg2, object arg3) { } public int ReturnValueMethod(string arg1, int arg2, object arg3) => 42; public string ReturnReferenceMethod(string arg, int arg21, object arg3) => "Hello World"; public T ReturnGenericMethod<T, TArg1, TArg3>(TArg1 arg1, int arg2, TArg3 arg3) => default; } class With3ArgumentsGeneric<T> { public void VoidMethod(string arg1, int arg2, object arg3) { } public int ReturnValueMethod(string arg1, int arg2, object arg3) => 42; public string ReturnReferenceMethod(string arg1, int arg2, object arg3) => "Hello World"; public T ReturnGenericMethod<TArg1, TArg3>(TArg1 arg1, int arg2, TArg3 arg3) => default; } class With3ArgumentsInherits : With3Arguments { } class With3ArgumentsInheritsGeneric : With3ArgumentsGeneric<int> { } struct With3ArgumentsStruct { public void VoidMethod(string arg1, int arg2, object arg3) { } public int ReturnValueMethod(string arg1, int arg2, object arg3) => 42; public string ReturnReferenceMethod(string arg1, int arg2, object arg3) => "Hello World"; public T ReturnGenericMethod<T, TArg1, TArg3>(TArg1 arg1, int arg2, TArg3 arg3) => default; } static class With3ArgumentsStatic { public static void VoidMethod(string arg1, int arg2, object arg3) { } public static int ReturnValueMethod(string arg1, int arg2, object arg3) => 42; public static string ReturnReferenceMethod(string arg1, int arg2, object arg3) => "Hello World"; public static T ReturnGenericMethod<T, TArg1, TArg3>(TArg1 arg1, int arg2, TArg3 arg3) => default; } }
51.057143
106
0.689424
[ "Apache-2.0" ]
backjo/dd-trace-dotnet
test/test-applications/instrumentation/CallTargetNativeTest/With3Arguments.cs
1,787
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Hanselman.Portable.Views { public partial class TwitterPage : ContentPage { private TwitterViewModel ViewModel { get { return BindingContext as TwitterViewModel; } } public TwitterPage() { InitializeComponent(); BindingContext = new TwitterViewModel(); listView.ItemTapped += (sender, args) => { if (listView.SelectedItem == null) return; var tweet = listView.SelectedItem as Tweet; this.Navigation.PushAsync(new WebsiteView("http://m.twitter.com/janninamusic/status/" + tweet.StatusID, tweet.Date)); listView.SelectedItem = null; }; } protected override void OnAppearing() { base.OnAppearing(); if (ViewModel == null || !ViewModel.CanLoadMore || ViewModel.IsBusy || ViewModel.Tweets.Count > 0) return; ViewModel.LoadTweetsCommand.Execute(null); } } }
27.860465
133
0.581803
[ "MIT" ]
wk-j/hanselman-forms
Hanselman.Portable/Views/TwitterPage.xaml.cs
1,200
C#
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using EventFeed.Producer.EventFeed; using EventFeed.Producer.EventFeed.Atom; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; namespace EventFeed.Producer.Controllers { [ApiController] public class EventFeedController: ControllerBase, IEventFeedUriProvider { [HttpGet("events/latest")] public async Task<IActionResult> GetLatestEventsAsync() { if (!ClientAcceptsAtomResponse()) return StatusCode(StatusCodes.Status406NotAcceptable); var page = _storage.GetLatestEvents(); return await RenderFeedAsync(page); } private bool ClientAcceptsAtomResponse() { var acceptHeader = Request.GetTypedHeaders().Accept; return acceptHeader == null || !acceptHeader.Any() || acceptHeader.Any(h => _atomMediaType.IsSubsetOf(h)); } private async Task<IActionResult> RenderFeedAsync(EventFeedPage page) { var renderer = new AtomRenderer(page, _storage, this); var stream = new MemoryStream(); await renderer.RenderAsync(stream); stream.Position = 0; return File(stream, contentType: AtomContentType); } [HttpGet("events/{pageId}")] public async Task<IActionResult> GetArchivedEventsAsync(string pageId) { if (!ClientAcceptsAtomResponse()) return StatusCode(StatusCodes.Status406NotAcceptable); EventFeedPage page; try { page = _storage.GetArchivedEvents(pageId); } catch (EventFeedPageNotFoundException) { return NotFound(); } return await RenderFeedAsync(page); } [NonAction] public Uri GetLatestEventsUri() => new Uri( Url.Action( action: "GetLatestEvents", controller: "EventFeed", values: null, protocol: Request.Scheme ) ); [NonAction] public Uri GetArchivedPageUri(string pageId) => new Uri( Url.Action( action: "GetArchivedEvents", controller: "EventFeed", values: new { pageId = pageId }, protocol: Request.Scheme ) ); [NonAction] public Uri? GetNotificationsUri() => _settings.Value.EnableSignalR ? new Uri(new Uri(Request.GetEncodedUrl()), Url.Content("~/events/notification")) : null; public EventFeedController( IReadEventStorage storage, IOptions<Settings> settings ) { _storage = storage; _settings = settings; } private readonly IReadEventStorage _storage; private readonly IOptions<Settings> _settings; private const string AtomContentType = "application/atom+xml"; private static readonly MediaTypeHeaderValue _atomMediaType = new MediaTypeHeaderValue(AtomContentType); } }
31.254545
112
0.578243
[ "MIT" ]
heemskerkerik/EventFeedDemo
EventFeed.Producer/Controllers/EventFeedController.cs
3,438
C#
using System; using UnityEngine; namespace AnilTools { // an object pool system for components public class ComponentPool<C> where C : Component { private readonly C[] components; private int index; // Pops a component in pool public C Get() { if ((++index) == components.Length) index = 0; return components[index]; } public ComponentPool(in int size, Transform parent, Action<C> OnSpawn = null) { this.components = new C[size]; for (; index < size; index++) { components[index] = new GameObject(typeof(C).Name).AddComponent<C>(); components[index].transform.parent = parent; OnSpawn?.Invoke(components[index]); } index = 0; } public ComponentPool(in int size, Action<C> OnSpawn = null) : this(size, new GameObject($"{typeof(C).Name} Pool").transform, OnSpawn) { } public ComponentPool(in int size, C prefab, Action<C> onSpawn = null) { this.components = new C[size]; var parent = new GameObject($"{prefab.name} Pool").transform; for (; index < components.Length; index++) { components[index] = UnityEngine.Object.Instantiate(prefab, parent); onSpawn?.Invoke(components[index]); } index = 0; } } }
32.934783
146
0.524752
[ "MIT" ]
benanil/Bukra_Game
Utils/heleper/ComponentPool.cs
1,517
C#
namespace SampleWebApi.Inheritance.WebApi.Areas.HelpPage { /// <summary> /// Indicates whether the sample is used for request or response /// </summary> public enum SampleDirection { Request = 0, Response } }
22.545455
68
0.633065
[ "MIT" ]
ERobishaw/trackable-entities
Samples/VS2013/WebApiSample.Inheritance/SampleWebApi.Inheritance.WebApi/Areas/HelpPage/SampleGeneration/SampleDirection.cs
248
C#
using System; using Client.UI; namespace Server.Actions { /// <summary> /// 单机版,读取内圈有钱有闲随机卡牌 /// </summary> public class RelaxAction : ActionBase { protected override void _OnStart() { // var list = CardManager.Instance.innerRelaxList; // var id = MathUtility.Random(list.ToArray()); var player = Client.PlayerManager.Instance.GetPlayerInfo (owner.PlayerID); var sendcard = false; if (Client.GameModel.GetInstance.isPlayNet == false) { sendcard = true; } else { if (player.playerID == Client.PlayerManager.Instance.HostPlayerInfo.playerID) { } sendcard = true; } if (sendcard == true) { Client.GameModel.GetInstance.sendCardType = (int)SpecialCardType.richRelax; var id = Client.CardOrderHandler.Instance.GetRelaxCardId(); VirtualServer.Instance.Send_NewSelectState(id); } } } }
24.025
82
0.616025
[ "Apache-2.0" ]
rusmass/wealthland_client
arpg_prg/client_prg/Assets/Code/Client/VirtualServer/BattleVirtualServer/Behaviour/Actions/Inner/RelaxAction.cs
995
C#
using ProjetoFilmes.Domains; using ProjetoFilmes.Interfaces; using System.Collections.Generic; using System.Linq; namespace ProjetoFilmes.Repositories { /// <summary> /// Repositório que implementa os métodos de usuários /// </summary> public class UsuarioRepository : IUsuarioRepository { /// <summary> /// Instancia um novo contexto para utilizar os métodos do EF Core /// </summary> FilmesContext ctx = new FilmesContext(); /// <summary> /// Atualiza um usuario existente /// </summary> /// <param name="idAtualizar">ID do usuario que será atualizado</param> /// <param name="usuarioAtualizado">Objeto com as novas informações</param> public void Atualizar(int idAtualizar, Usuario usuarioAtualizado) { Usuario usuarioAtual = BuscarPorId(idAtualizar); if (usuarioAtual != null) { usuarioAtual = usuarioAtualizado; } ctx.Usuarios.Update(usuarioAtual); ctx.SaveChanges(); } /// <summary> /// Busca um usuario através do seu ID /// </summary> /// <param name="idBuscar">ID do usuario que será buscado</param> /// <returns>Retorna um usuario buscado</returns> public Usuario BuscarPorId(int idBuscar) { Usuario usuarioBuscado = ctx.Usuarios.Find(idBuscar); return usuarioBuscado; } /// <summary> /// Cadastra um novo usuario /// </summary> /// <param name="novoUsuario">Objeto com as informações que serão cadastradas</param> public void Cadastrar(Usuario novoUsuario) { ctx.Usuarios.Add(novoUsuario); ctx.SaveChanges(); } /// <summary> /// Deleta um usuario existente /// </summary> /// <param name="idDeletar">ID do usuario que será deletado</param> public void Deletar(int idDeletar) { ctx.Usuarios.Remove(BuscarPorId(idDeletar)); ctx.SaveChanges(); } /// <summary> /// Lista todos os usuarios /// </summary> /// <returns>Retorna uma lista de usuarios</returns> public List<Usuario> Listar() { return ctx.Usuarios.ToList(); } /// <summary> /// Valida o usuário /// </summary> /// <param name="email">E-mail do usuário</param> /// <param name="senha">Senha do usuário</param> /// <returns>Retorna um usuário autenticado</returns> public Usuario Login(string email, string senha) { // Busca um usuário através do e-mail e senha informados Usuario usuarioAutenticado = ctx.Usuarios .FirstOrDefault(u => u.Email == email && u.Senha == senha); // Caso seja encontrado, retorna todos os dados deste usuário if (usuarioAutenticado != null) { return usuarioAutenticado; } // Caso não, retorna nulo return null; } } }
30.592233
93
0.563631
[ "MIT" ]
Carlos-Henrique98/React-ListaFilme
backend/01.filmes/backend/ProjetoFilmes/ProjetoFilmes/Repositories/UsuarioRepository.cs
3,174
C#
using System; using System.Windows.Forms; using EAValidator; namespace EAValidatorApp { public partial class frmEAValidator : Form { private EAValidatorController controller { get; set; } public frmEAValidator(EAValidatorController controller) { InitializeComponent(); this.controller = controller; this.ucEAValidator.setController(this.controller); } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { new SettingsForm(this.controller.settings).ShowDialog(this); //re-initialize this.ucEAValidator.setController(this.controller); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new AboutWindow().ShowDialog(this); } } }
28.366667
80
0.647474
[ "BSD-2-Clause" ]
CuchulainX/Enterprise-Architect-Toolpack
EAValidationFramework/frmEAValidator.cs
853
C#
// <auto-generated /> using System; using LearningAbp.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace LearningAbp.Migrations { [DbContext(typeof(LearningAbpDbContext))] [Migration("20190208051931_Upgrade_ABP_4_2_0")] partial class Upgrade_ABP_4_2_0 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.1-servicing-10028") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ReturnValue"); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .HasMaxLength(256); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime"); b.Property<byte>("ChangeType"); b.Property<long>("EntityChangeSetId"); b.Property<string>("EntityId") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<string>("ExtensionData"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("Reason") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId"); b.Property<string>("NewValue") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasMaxLength(512); b.Property<string>("PropertyName") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "RoleId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("LearningAbp.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("LearningAbp.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("LearningAbp.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("LearningAbp.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("LearningAbp.Authorization.Roles.Role", b => { b.HasOne("LearningAbp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("LearningAbp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("LearningAbp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("LearningAbp.Authorization.Users.User", b => { b.HasOne("LearningAbp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("LearningAbp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("LearningAbp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("LearningAbp.MultiTenancy.Tenant", b => { b.HasOne("LearningAbp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("LearningAbp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("LearningAbp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("LearningAbp.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("LearningAbp.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.626947
125
0.461125
[ "MIT" ]
IAmWhoAmI007/LearningAbp
aspnet-core/src/LearningAbp.EntityFrameworkCore/Migrations/20190208051931_Upgrade_ABP_4_2_0.Designer.cs
43,179
C#
// DO NOT EDIT: GENERATED BY BitCountFromRangeTestGenerator.cs using System; using System.Collections; using Mirage.Serialization; using Mirage.Tests.Runtime.ClientServer; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Mirage.Tests.Runtime.Generated.BitCountFromRangeAttributeTests.short_N10_10 { public class BitPackBehaviour : NetworkBehaviour { [BitCountFromRange(-10, 10)] [SyncVar] public short myValue; public event Action<short> onRpc; [ClientRpc] public void RpcSomeFunction([BitCountFromRange(-10, 10)] short myParam) { onRpc?.Invoke(myParam); } // Use BitPackStruct in rpc so it has writer generated [ClientRpc] public void RpcOtherFunction(BitPackStruct myParam) { // nothing } } [NetworkMessage] public struct BitPackMessage { [BitCountFromRange(-10, 10)] public short myValue; } [Serializable] public struct BitPackStruct { [BitCountFromRange(-10, 10)] public short myValue; } public class BitPackTest : ClientServerSetup<BitPackBehaviour> { const short value = 3; [Test] public void SyncVarIsBitPacked() { serverComponent.myValue = value; using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { serverComponent.SerializeSyncVars(writer, true); Assert.That(writer.BitPosition, Is.EqualTo(5)); using (PooledNetworkReader reader = NetworkReaderPool.GetReader(writer.ToArraySegment())) { clientComponent.DeserializeSyncVars(reader, true); Assert.That(reader.BitPosition, Is.EqualTo(5)); Assert.That(clientComponent.myValue, Is.EqualTo(value)); } } } [UnityTest] public IEnumerator RpcIsBitPacked() { int called = 0; clientComponent.onRpc += (v) => { called++; Assert.That(v, Is.EqualTo(value)); }; client.MessageHandler.UnregisterHandler<RpcMessage>(); int payloadSize = 0; client.MessageHandler.RegisterHandler<RpcMessage>((player, msg) => { // store value in variable because assert will throw and be catch by message wrapper payloadSize = msg.payload.Count; clientObjectManager.OnRpcMessage(msg); }); serverComponent.RpcSomeFunction(value); yield return null; yield return null; Assert.That(called, Is.EqualTo(1)); // this will round up to nearest 8 int expectedPayLoadSize = (5 + 7) / 8; Assert.That(payloadSize, Is.EqualTo(expectedPayLoadSize), $"5 bits is 1 bytes in payload"); } [UnityTest] public IEnumerator StructIsBitPacked() { var inMessage = new BitPackMessage { myValue = value, }; int payloadSize = 0; int called = 0; BitPackMessage outMessage = default; server.MessageHandler.RegisterHandler<BitPackMessage>((player, msg) => { // store value in variable because assert will throw and be catch by message wrapper called++; outMessage = msg; }); Action<NetworkDiagnostics.MessageInfo> diagAction = (info) => { if (info.message is BitPackMessage) { payloadSize = info.bytes; } }; NetworkDiagnostics.OutMessageEvent += diagAction; client.Player.Send(inMessage); NetworkDiagnostics.OutMessageEvent -= diagAction; yield return null; yield return null; Assert.That(called, Is.EqualTo(1)); // this will round up to nearest 8 // +2 for message header int expectedPayLoadSize = ((5 + 7) / 8) + 2; Assert.That(payloadSize, Is.EqualTo(expectedPayLoadSize), $"5 bits is {expectedPayLoadSize - 2} bytes in payload"); Assert.That(outMessage, Is.EqualTo(inMessage)); } [Test] public void MessageIsBitPacked() { var inStruct = new BitPackStruct { myValue = value, }; using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { // generic write, uses generated function that should include bitPacking writer.Write(inStruct); Assert.That(writer.BitPosition, Is.EqualTo(5)); using (PooledNetworkReader reader = NetworkReaderPool.GetReader(writer.ToArraySegment())) { var outStruct = reader.Read<BitPackStruct>(); Assert.That(reader.BitPosition, Is.EqualTo(5)); Assert.That(outStruct, Is.EqualTo(inStruct)); } } } } }
31.718563
127
0.555598
[ "MIT" ]
GTextreme169/Mirage
Assets/Tests/Generated/BitCountFromRangeTests/BitCountFromRange_short_N10_10.cs
5,297
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the user level data associated with Third-Party Voice Mail Support. /// The response is either a UserThirdPartyVoiceMailSupportGetResponse13mp16 or an /// ErrorResponse. /// Replaced by: UserThirdPartyVoiceMailSupportGetRequest17 /// <see cref="UserThirdPartyVoiceMailSupportGetResponse13mp16"/> /// <see cref="ErrorResponse"/> /// <see cref="UserThirdPartyVoiceMailSupportGetRequest17"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:17749""}]")] public class UserThirdPartyVoiceMailSupportGetRequest13mp16 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:17749")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } } }
32.108696
131
0.660799
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserThirdPartyVoiceMailSupportGetRequest13mp16.cs
1,477
C#
namespace AutoMapper.QueryableExtensions.Impl { using System.Collections.Generic; using System.Linq.Expressions; public class CustomProjectionExpressionBinder : IExpressionBinder { public bool IsMatch(PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionResolutionResult result) { return propertyTypeMap?.CustomProjection != null; } public MemberAssignment Build(IConfigurationProvider configuration, PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionRequest request, ExpressionResolutionResult result, IDictionary<ExpressionRequest, int> typePairCount) { return BindCustomProjectionExpression(propertyMap, propertyTypeMap, result); } private static MemberAssignment BindCustomProjectionExpression(PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionResolutionResult result) { return Expression.Bind(propertyMap.DestinationProperty, propertyTypeMap.CustomProjection.ReplaceParameters(result.ResolutionExpression)); } } }
46.782609
238
0.765799
[ "MIT" ]
hegemon70/AutoMapper
src/AutoMapper/QueryableExtensions/Impl/CustomProjectionExpressionBinder.cs
1,076
C#
using System.Collections.Generic; using System.Globalization; using BenchmarkDotNet.Analysers; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Filters; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Order; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Validators; namespace StringPrefixSearchBenchmark { internal class BenchmarkConfig : IConfig { private readonly IConfig _defaultConfig = DefaultConfig.Instance; public IEnumerable<IColumnProvider> GetColumnProviders() { return _defaultConfig.GetColumnProviders(); } public IEnumerable<IExporter> GetExporters() { yield return AsciiDocExporter.Default; } public IEnumerable<ILogger> GetLoggers() { yield return ConsoleLogger.Default; } public IEnumerable<IDiagnoser> GetDiagnosers() { return _defaultConfig.GetDiagnosers(); } public IEnumerable<IAnalyser> GetAnalysers() { return _defaultConfig.GetAnalysers(); } public IEnumerable<Job> GetJobs() { return _defaultConfig.GetJobs(); } public IEnumerable<IValidator> GetValidators() { return _defaultConfig.GetValidators(); } public IEnumerable<HardwareCounter> GetHardwareCounters() { return _defaultConfig.GetHardwareCounters(); } public IEnumerable<IFilter> GetFilters() { return _defaultConfig.GetFilters(); } public IEnumerable<BenchmarkLogicalGroupRule> GetLogicalGroupRules() { return _defaultConfig.GetLogicalGroupRules(); } public IOrderer? Orderer => _defaultConfig.Orderer; public SummaryStyle SummaryStyle => _defaultConfig.SummaryStyle; public ConfigUnionRule UnionRule => _defaultConfig.UnionRule; public string ArtifactsPath => _defaultConfig.ArtifactsPath; public CultureInfo? CultureInfo => _defaultConfig.CultureInfo; public ConfigOptions Options => _defaultConfig.Options; } }
27.27381
76
0.670886
[ "MIT" ]
skarllot/StringPrefixSearchBenchmark
perf/StringPrefixSearchBenchmark/BenchmarkConfig.cs
2,291
C#
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Prep.Problems.DataStructures; //https://leetcode.com/problems/number-of-distinct-islands-ii/ namespace Prep.Problems.Problems.number_of_islands_hard { public class Solution { public IList<int> NumIslands2(int m, int n, int[][] positions) { var directions = new List<(int, int)>(){(-1,0), (0,1), (1,0), (0,-1)}; var uniqueCounts = new List<int>(); //initialize set var ds=new SimpleDisjointSet(); foreach (var position in positions) { var row = position[0]; var column = position[1]; //3 x 4. Row 1, column 2 = position 6 // 0 1 2 3 // 4 5 6 7 var index = row * n + column; ds.AddSet(index); //Look in all directions for additional land, union foreach (var t in directions) { var searchRow = row + t.Item1; var searchColumn = column + t.Item2; if (searchRow < 0 || searchRow >= m || searchColumn < 0 || searchColumn >= n) continue; var searchIndex = searchRow * n + searchColumn; if (ds.SetExists(searchIndex)) { ds.Union(index, searchIndex); } } uniqueCounts.Add(ds.UniqueSets()); } return uniqueCounts; } } }
30.875
97
0.500289
[ "MIT" ]
michaelwda/Prep
Prep.Problems/Problems/number_of_islands_hard/Solution.cs
1,731
C#
using MediatR; using SS.Organizations.Application.Configuration.Services; using SS.Organizations.Domain.Exceptions; using SS.Organizations.Domain.Repositories; using System.Threading; using System.Threading.Tasks; namespace SS.Organizations.Application.Commands.AddUserToOrganization { public class AddUserToOrganizationCommandHandler : ICommandHandler<AddUserToOrganizationCommand> { private readonly IOrganizationRepository _organizationRepository; private readonly IUserService _service; public AddUserToOrganizationCommandHandler(IOrganizationRepository repository, IUserService service) { _organizationRepository = repository; _service = service; } public async Task<Unit> Handle(AddUserToOrganizationCommand request, CancellationToken cancellationToken) { var user = await _service.GetbyEmail(request.Email); if (user == null) { throw new OrganizationException("User doesn't exists", HttpErrorCodes.ResourceNotFound, InternalErrorCodes.UserDoesntExists); } var organization = await _organizationRepository.GetbyId(request.OrganizationId); if (organization == null) { throw new OrganizationException("Organization doesn't exists", HttpErrorCodes.ResourceNotFound,InternalErrorCodes.OrganizationDoesntExits); } organization.AddUser(user.Id, user.Email, user.DisplayName); await _organizationRepository.Update(organization); return Unit.Value; } } }
41.974359
155
0.703115
[ "MIT" ]
KamilKarpus/SecretStorage
src/SS.Organization.Application/Commands/AddUserToOrganization/AddUserToOrganizationCommandHandler.cs
1,639
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VeurmaClassifier { public class C45Algorithm { private DecisionTree tree; private int maximumHeight; private int step; //split step private double[][] thresholds; private Range<int>[] inputRanges; private int inputVariables; private int outputClasses; private int join = 1; private int[] attributeUsageCount; private IList<Attribute> attributes; public int MaximumHeight { get { return maximumHeight; } set { maximumHeight = value; } } public IList<Attribute> Attributes { //attributes for tree induction get { return attributes; } set { attributes = value; } } public int MaxVariables { get; set; } //maximum number of variables in a tree public int SplitStep //new splitting step: Default is one (root). { get { return step; } set { step = value; } } public DecisionTree ClassificationModel //The Classification model, which in this case is a decision tree. { get { return tree; } set { tree = value; } } public C45Algorithm() //constructor { this.step = 1; //default split step is 1. } /// <summary> /// C45 Algorithm /// </summary> /// <param name="attributes">Attributes that would be used in learning</param> public C45Algorithm(Attribute[] attributes) { this.attributes = new List<Attribute>(attributes); } private void initialize(DecisionTree tree) { this.tree = tree; inputVariables = tree.Inputs; outputClasses = tree.Outputs; attributeUsageCount = new int[inputVariables]; inputRanges = new Range<int>[inputVariables]; maximumHeight = inputVariables; attributes = tree.Attributes; for (int i = 0; i < inputRanges.Length; i++) inputRanges[i] = tree.Attributes[i].Range.ToIntRange(); } /// <summary> /// Induces the decision tree /// </summary> /// /// <param name="x">The inputs.</param> /// <param name="y">The class labels.</param> /// /// <returns>A decision tree</returns> /// public DecisionTree Learn(double[][] x, int[] y) { if (tree == null) { if (attributes == null) attributes = Attribute.FromData(x); int classes = y.Max() + 1; initialize(new DecisionTree(this.attributes, classes)); } this.induceTree(x, y); return tree; } /// <summary> /// Induces the decision tree /// </summary> /// /// <param name="x">The inputs.</param> /// <param name="y">The class labels.</param> /// /// <returns>A decision tree</returns> /// public DecisionTree Learn(int[][] x, int[] y) { if (tree == null) { var variables = Attribute.FromData(x); int classes = y.Max() + 1; initialize(new DecisionTree(variables, classes)); } induceTree(Converter(x), y); return tree; } /// <summary> /// Convert Integer Jagged Array to Double Jagged Array /// </summary> /// <param name="value">integer array</param> /// <returns>Newly converted double array</returns> public double[][] Converter(int[][] value) { double[][] result = new double[value.Length][]; for (int i = 0; i < result.Length; i++) result[i] = new double[value[i].Length]; for (int i = 0; i < value.Length; i++) for (int j = 0; j < value[i].Length; j++) result[i][j] = (Double)value[i][j]; return result; } private void induceTree(double[][] inputs, int[] outputs) { //reset for (int i = 0; i < attributeUsageCount.Length; i++) { attributeUsageCount[i] = 0; } thresholds = new double[tree.Attributes.Count][]; var candidates = new List<double>(inputs.Length); // create split thresholds for (int i = 0; i < tree.Attributes.Count; i++) { if (tree.Attributes[i].Nature == AttributeType.Continuous) { double[] v = inputs.GetColumn(i); int[] o = (int[])outputs.Clone(); IGrouping<double, int>[] sortedValueMapping = v. Select((value, index) => new KeyValuePair<double, int>(value, o[index])). GroupBy(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value). OrderBy(keyValuePair => keyValuePair.Key). ToArray(); for (int j = 0; j < sortedValueMapping.Length - 1; j++) { IGrouping<double, int> currentValueToClasses = sortedValueMapping[j]; IGrouping<double, int> nextValueToClasses = sortedValueMapping[j + 1]; double a = nextValueToClasses.Key; double b = currentValueToClasses.Key; if (a - b > 1.11022302462515654042e-16 && currentValueToClasses.Union(nextValueToClasses).Count() > 1) candidates.Add((currentValueToClasses.Key + nextValueToClasses.Key) / 2.0); } thresholds[i] = candidates.ToArray(); candidates.Clear(); } } // Create a root node for the tree tree.Root = new Node(tree); // Recursively split the tree nodes split(tree.Root, inputs, outputs, 0); } private void split(Node root, double[][] input, int[] output, int height) { double entropy = Entropy(output, outputClasses); if (entropy == 0) { if (output.Length > 0) root.Output = output[0]; return; } int[] candidates = Matrix.Find(attributeUsageCount, x => x < join); if (candidates.Length == 0 || (maximumHeight > 0 && height == maximumHeight)) { root.Output = output.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key; return; } if (MaxVariables > 0) { var random = new Random(); var a = Range(MaxVariables); var x = new double[a.Length]; for (int i = 0; i < x.Length; i++) x[i] = random.NextDouble(); Array.Sort(x, a); int[] idx2 = a; candidates = candidates.Sub(idx2); } var scores = new double[candidates.Length]; var thresholds = new double[candidates.Length]; var partitions = new int[candidates.Length][][]; // For each attribute in the data set for (int i = 0; i < scores.Length; i++) { scores[i] = calculateGainRatio(input, output, candidates[i], entropy, out partitions[i], out thresholds[i]); } // Select the attribute with maximum gain ratio int maxGainRatio; scores.MaxElement(out maxGainRatio); var maxGainPartition = partitions[maxGainRatio]; var maxGainAttribute = candidates[maxGainRatio]; var maxGainRange = inputRanges[maxGainAttribute]; var maxGainThreshold = thresholds[maxGainRatio]; // Mark this attribute as already used attributeUsageCount[maxGainAttribute]++; double[][] inputSublist; int[] outputSublist; if (tree.Attributes[maxGainAttribute].Nature == AttributeType.Discrete) { Node[] children = new Node[maxGainPartition.Length]; // Create a branch for each possible value for (int i = 0; i < children.Length; i++) { children[i] = new Node(tree) { Parent = root, Value = i + maxGainRange.Min, Comparison = "==", }; inputSublist = input.Sub(maxGainPartition[i]); outputSublist = output.Sub(maxGainPartition[i]); split(children[i], inputSublist, outputSublist, height + 1); // recursion } root.Branches.Index = maxGainAttribute; root.Branches.AddChildren(children); } else if (maxGainPartition.Length > 1) { Node[] children = { new Node(tree) { Parent = root, Value = maxGainThreshold, Comparison = "<=" }, new Node(tree) { Parent = root, Value = maxGainThreshold, Comparison = ">" } }; // Create a branch for lower values inputSublist = input.Sub(maxGainPartition[0]); outputSublist = output.Sub(maxGainPartition[0]); split(children[0], inputSublist, outputSublist, height + 1); // Create a branch for higher values inputSublist = input.Sub(maxGainPartition[1]); outputSublist = output.Sub(maxGainPartition[1]); split(children[1], inputSublist, outputSublist, height + 1); root.Branches.Index = maxGainAttribute; root.Branches.AddChildren(children); } else { outputSublist = output.Sub(maxGainPartition[0]); root.Output = output.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key; } attributeUsageCount[maxGainAttribute]--; } private double calculateGainRatio(double[][] input, int[] output, int attributeIndex, double entropy, out int[][] partitions, out double threshold) { double infoGain = calculateInformationGain(input, output, attributeIndex, entropy, out partitions, out threshold); double splitInfo = SplitInformation(output.Length, partitions); return infoGain == 0 || splitInfo == 0 ? 0 : infoGain / splitInfo; } public static double SplitInformation(int samples, int[][] partitions) { //calculate split information double info = 0; for (int i = 0; i < partitions.Length; i++) { double p = (double)partitions[i].Length / samples; if (p != 0) info -= p * Math.Log(p, 2); } return info; } private double calculateInformationGain(double[][] input, int[] output, int attributeIndex, double entropy, out int[][] partitions, out double threshold) { threshold = 0; if (tree.Attributes[attributeIndex].Nature == AttributeType.Discrete) return entropy - InformationGainNominal(input, output, attributeIndex, out partitions); return entropy + InformationGainNumeric(input, output, attributeIndex, out partitions, out threshold); } private double InformationGainNominal(double[][] input, int[] output, int attributeIndex, out int[][] partitions) { double info = 0; Range<int> valueRange = inputRanges[attributeIndex]; partitions = new int[(valueRange.Max - valueRange.Min) + 1][]; for (int i = 0; i < partitions.Length; i++) { int value = valueRange.Min + i; partitions[i] = input.Find(x => x[attributeIndex] == value); int[] outputSubset = output.Sub(partitions[i]); double e = Entropy(outputSubset, outputClasses); info += ((double)outputSubset.Length / output.Length) * e; } return info; } private double InformationGainNumeric(double[][] input, int[] output, int attributeIndex, out int[][] partitions, out double threshold) { // use this current attribute as the next decision node. double[] t = thresholds[attributeIndex]; double bestGain = Double.NegativeInfinity; // no thresholds for split? if (t.Length == 0) { // Then they all belong to the same partition partitions = new int[][] { Range(input.Length) }; threshold = Double.NegativeInfinity; return bestGain; } double bestThreshold = t[0]; partitions = null; List<int> a1 = new List<int>(input.Length); List<int> a2 = new List<int>(input.Length); List<int> output1 = new List<int>(input.Length); List<int> output2 = new List<int>(input.Length); double[] values = new double[input.Length]; for (int i = 0; i < values.Length; i++) values[i] = input[i][attributeIndex]; // For each possible splitting point of the attribute for (int i = 0; i < t.Length; i += step) { // Partition the remaining data set // according to the threshold value double value = t[i]; a1.Clear(); a2.Clear(); output1.Clear(); output2.Clear(); for (int j = 0; j < values.Length; j++) { double x = values[j]; if (x <= value) { a1.Add(j); output1.Add(output[j]); } else if (x > value) { a2.Add(j); output2.Add(output[j]); } } double p1 = (double)output1.Count / output.Length; double p2 = (double)output2.Count / output.Length; double splitGain = -p1 * Entropy(output1.ToArray(), outputClasses) + -p2 * Entropy(output2.ToArray(), outputClasses); if (splitGain > bestGain) { bestThreshold = value; bestGain = splitGain; if (a1.Count > 0 && a2.Count > 0) partitions = new int[][] { a1.ToArray(), a2.ToArray() }; else if (a1.Count > 0) partitions = new int[][] { a1.ToArray() }; else if (a2.Count > 0) partitions = new int[][] { a2.ToArray() }; else partitions = new int[][] { }; } } threshold = bestThreshold; return bestGain; } /// <summary> /// Entropy Calculator /// </summary> /// /// <param name="values">An array of integer symbols.</param> /// <param name="classes">The number of classes.</param> /// <returns>The evaluated entropy.</returns> private static double Entropy(int[] values, int classes) { double entropy = 0; double total = values.Length; // For each class for (int c = 0; c < classes; c++) { int count = 0; // Count the number of instances inside foreach (int v in values) if (v == c) count++; if (count > 0) { double p = count / total; entropy -= p * Math.Log(p, 2); } } return entropy; } public static int[] Range(int n) { int[] r = new int[(int)n]; for (int i = 0; i < r.Length; i++) r[i] = i; return r; } } }
34.271845
127
0.466799
[ "MIT" ]
AdoraNwodo/AI-Concepts
VeurmaClassifier/C45Algorithm.cs
17,652
C#
// Copyright (C) 2008 Jesse Jones // // 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 MObjc; using MObjc.Helpers; using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; namespace MCocoa { public partial class NSView : NSResponder { /// <exclude/> public delegate int SortFunction(NSObject lhs, NSObject rhs, IntPtr context); /// <exclude/> public void sortSubviewsUsingFunction_context(SortFunction function, IntPtr context) { Action<IntPtr, IntPtr, IntPtr> thunk = (IntPtr lhs, IntPtr rhs, IntPtr ctxt) => function(NSObject.Lookup(lhs), NSObject.Lookup(rhs), ctxt); IntPtr fp = Marshal.GetFunctionPointerForDelegate(thunk); Call("sortSubviewsUsingFunction:context:", fp, context); GC.KeepAlive(thunk); } /// <exclude/> [Pure] public NSView[] subviews() { NSArray items = (NSArray) Call("subviews"); NSView[] result = new NSView[items.count()]; for (int i = 0; i < items.count(); ++i) result[i] = items.objectAtIndex((uint) i).To<NSView>(); return result; } /// <exclude/> [ThreadModel(ThreadModel.MainThread)] public void setSubviews(NSView[] newSubviews) { NSMutableArray array = NSMutableArray.Create(); foreach (NSView view in newSubviews) array.addObject(view); Unused.Value = Call("setSubviews:", array); } } }
33.068493
86
0.720795
[ "MIT" ]
afrog33k/mcocoa
source/appkit/NSView.cs
2,414
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace LB15 { public partial class Form1 : Form { public Graph graph = new Graph(); public Graph graph_topological; public List<int> topogicalSort = new List<int>(); //сортировка public int drag = -1;//перемещ узел public int drage = -1; // узел из которого происходит добавление/удаление ребер //координаты двух точек для отображения линии, public int dx1 = 0; public int dy1 = 0; //---------------------------- //при добавлении и удалении ребре public int dx2 = 0; public int dy2 = 0; //------------------------------ //для второго графа //координаты двух точек для отображения линии, public int d2x1 = 0; public int d2y1 = 0; //---------------------------- //при добавлении и удалении ребре public int d2x2 = 0; public int d2y2 = 0; //------------------------------ public bool action_bypass = false; // запущен ли обход графа public bool cycle = false; // цикла нет public bool searchCycle_complete = false; // поиск цикла не завершен public int length = 0; // для анимации при топологической сортировки public Form1() { InitializeComponent(); checkBox3.Enabled = false; button3.Enabled = false; } private void Form1_Load(object sender, EventArgs e) { this.DoubleBuffered = true; } private void Form1_Paint(object sender, PaintEventArgs e) { //устанавливаем размеры формы pictureBox1.Width = this.Width - 16; pictureBox1.Height = this.Height - pictureBox1.Location.Y - 39; //------------------------------------ //уст координат появления новых узлов graph.x = pictureBox1.Width / 2; graph.y = pictureBox1.Height / 2; //---------------------------- Bitmap buffer = new Bitmap(Width, Height); // extra buf Graphics paint_graph = Graphics.FromImage(buffer);//двойная буферизация gfx //Кисти и ручки SolidBrush brush_text = new SolidBrush(Color.Blue); //myBrush SolidBrush brush_animation = new SolidBrush(Color.White); //myBrush2 Pen pen_node = new Pen(Color.Black);//myPen Pen pen_edge = new Pen(Color.Red);//myPen2 //---------------------------------- //настройки по умолчанию paint_graph.Clear(Color.Gray); // очистка поверхности pen_edge.Color = Color.Red; brush_animation.Color = Color.Red; foreach(Graph.Node v in graph.nodes) { foreach(int eg in v.edges) // check all edge { foreach(Graph.Node v2 in graph.nodes) // найти все узлы находящиесе в сп смежности { if(v2.id == eg) { double direction = Match.point_direction(v.x, v.y, v2.x, v2.y); // направление между узлами double distantion = Match.point_distance(v.x, v.y, v2.x, v2.y); // дистанция между узлами paint_graph.DrawLine(pen_edge, point1(v.x, v.y, direction, distantion), point2(v.x, v.y, direction, distantion)); // рисовка ребра paint_graph.FillEllipse(brush_animation, paint_endEdge(v.x, v.y, distantion, direction)); // рисовка конца ребра } } } } foreach(Graph.Node v in graph.nodes) { brush_animation.Color = Color.White; // обычное состояние узла if(v.active==1) brush_animation.Color = Color.SteelBlue; // обрабатывается if(v.active==2) brush_animation.Color = Color.Gray;//обработан if(v.active==3) brush_animation.Color = Color.Gold; // узел сохр(не обр в дан момент и до конца еще не обработан) DFS paint_graph.FillEllipse(brush_animation, new Rectangle(v.x - graph.size / 2, v.y - graph.size / 2, graph.size, graph.size));//фон paint_graph.DrawEllipse(pen_node, new Rectangle(v.x - graph.size / 2, v.y - graph.size / 2, graph.size, graph.size));// контур paint_graph.DrawString(v.name, new Font("Arial", 8, FontStyle.Italic), brush_text, new PointF(v.x - graph.size / 3, v.y - 10)); // название } if(drage!=-1)// в каком то узле доб/уд ребра { brush_animation.Color = Color.Red; if(checkBox2.Checked==true)// удалении { pen_edge.Color = Color.Yellow; brush_animation.Color = Color.Yellow; } double direction_mouse = Match.point_direction(dx1, dy1, dx2, dy2); // направление от узла к указателю мыши double distantion_mouse = Match.point_distance(dx1, dy1, dx2, dy2);// расстояние между узлом и указателем мыши paint_graph.DrawLine(pen_edge, point1_mouse(dx1, dy1, direction_mouse, distantion_mouse),point2_mouse(dx1,dy1,direction_mouse,distantion_mouse)); paint_graph.FillEllipse(brush_animation, new Rectangle(dx1 + (int)Match.lengthdir_x(distantion_mouse, direction_mouse) - 4, dy1 + (int)Match.lengthdir_y(distantion_mouse, direction_mouse) - 4, 8, 8)); } pictureBox1.Image = buffer; // убирает мерцание brush_animation.Dispose(); brush_text.Dispose(); pen_edge.Dispose(); pen_node.Dispose(); if (graph_topological != null && checkBox3.Checked==true) { //уст координат появления новых узлов graph_topological.x = pictureBox1.Width / 2; graph_topological.y = pictureBox1.Height / 2; //---------------------------- Bitmap buffer2 = new Bitmap(Width, Height); // extra buf Graphics paint_graph_toplogical = Graphics.FromImage(buffer2);//двойная буферизация gfx //Кисти и ручки SolidBrush brush_text2 = new SolidBrush(Color.Blue); //myBrush SolidBrush brush_animation2 = new SolidBrush(Color.Yellow); //myBrush2 Pen pen_node2 = new Pen(Color.Black);//myPen Pen pen_edge2 = new Pen(Color.Red);//myPen2 //---------------------------------- //настройки по умолчанию paint_graph_toplogical.Clear(Color.Gray); // очистка поверхности pen_edge2.Color = Color.Green; brush_animation2.Color = Color.Green; foreach (Graph.Node v in graph_topological.nodes) { foreach (int eg in v.edges) // check all edge { foreach (Graph.Node v2 in graph_topological.nodes) // найти все узлы находящиесе в сп смежности { if (v2.id == eg) { double direction = Match.point_direction(v.x, v.y, v2.x, v2.y); // направление между узлами double distantion = Match.point_distance(v.x, v.y, v2.x, v2.y); // дистанция между узлами paint_graph_toplogical.DrawLine(pen_edge2, point1_topological(v.x, v.y, direction, distantion), point2_topological(v.x, v.y, direction, distantion)); // рисовка ребра paint_graph_toplogical.FillEllipse(brush_animation2, paint_endEdge_topological(v.x, v.y, distantion, direction)); // рисовка конца ребра } } } } foreach (Graph.Node v in graph_topological.nodes) { brush_animation2.Color = Color.White; // обычное состояние узла if (v.active == 1) brush_animation2.Color = Color.SteelBlue; // обрабатывается if (v.active == 2) brush_animation2.Color = Color.Gray;//обработан if (v.active == 3) brush_animation2.Color = Color.Gold; // узел сохр(не обр в дан момент и до конца еще не обработан) DFS paint_graph_toplogical.FillEllipse(brush_animation2, new Rectangle(v.x - graph_topological.size / 2, v.y - graph_topological.size / 2, graph_topological.size, graph_topological.size));//фон paint_graph_toplogical.DrawEllipse(pen_node2, new Rectangle(v.x - graph_topological.size / 2, v.y - graph_topological.size / 2, graph_topological.size, graph_topological.size));// контур paint_graph_toplogical.DrawString(v.name, new Font("Arial", 8, FontStyle.Italic), brush_text2, new PointF(v.x - graph_topological.size / 3, v.y - 10)); // название } if (drage != -1)// в каком то узле доб/уд ребра { brush_animation2.Color = Color.Red; if (checkBox2.Checked == true)// удалении { pen_edge2.Color = Color.Yellow; brush_animation2.Color = Color.Yellow; } double direction_mouse = Match.point_direction(d2x1, d2y1, d2x2, d2y2); // направление от узла к указателю мыши double distantion_mouse = Match.point_distance(d2x1, d2y1, d2x2, d2y2);// расстояние между узлом и указателем мыши paint_graph_toplogical.DrawLine(pen_edge2, point1_mouse_topological(d2x1, d2y1, direction_mouse, distantion_mouse), point2_mouse_topological(d2x1, d2y1, direction_mouse, distantion_mouse)); paint_graph_toplogical.FillEllipse(brush_animation2, new Rectangle(d2x1 + (int)Match.lengthdir_x(distantion_mouse, direction_mouse) - 4, d2y1 + (int)Match.lengthdir_y(distantion_mouse, direction_mouse) - 4, 8, 8)); } pictureBox1.Image = buffer2; // убирает мерцание brush_animation2.Dispose(); brush_text2.Dispose(); pen_edge2.Dispose(); pen_node2.Dispose(); } } private Point point1(int x, int y, double direction,double distance) { Point p = new Point(x + (int)Match.lengthdir_x(graph.size / 2, direction), y + (int)Match.lengthdir_y(graph.size / 2, direction)); return p; } private Point point2(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(distance - (graph.size / 2), direction), y + (int)Match.lengthdir_y(distance - (graph.size / 2), direction)); return p; } private Rectangle paint_endEdge(int x,int y, double distance,double direction) { Rectangle c = new Rectangle(x+(int)Match.lengthdir_x(distance-(graph.size/2), direction)-4, y+(int)Match.lengthdir_y(distance-(graph.size/2),direction)-4,8,8); return c; } private Point point1_mouse(int x,int y,double direction,double distance) { Point p = new Point(x + (int)Match.lengthdir_x(graph.size / 2, direction), y + (int)Match.lengthdir_y(graph.size / 2, direction)); return p; } private Point point2_mouse(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(distance,direction), y + (int)Match.lengthdir_y(distance, direction)); return p; } private Point point1_topological(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(graph_topological.size / 2, direction), y + (int)Match.lengthdir_y(graph_topological.size / 2, direction)); return p; } private Point point2_topological(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(distance - (graph_topological.size / 2), direction), y + (int)Match.lengthdir_y(distance - (graph_topological.size / 2), direction)); return p; } private Rectangle paint_endEdge_topological(int x, int y, double distance, double direction) { Rectangle c = new Rectangle(x + (int)Match.lengthdir_x(distance - (graph_topological.size / 2), direction) - 4, y + (int)Match.lengthdir_y(distance - (graph_topological.size / 2), direction) - 4, 8, 8); return c; } private Point point1_mouse_topological(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(graph_topological.size / 2, direction), y + (int)Match.lengthdir_y(graph_topological.size / 2, direction)); return p; } private Point point2_mouse_topological(int x, int y, double direction, double distance) { Point p = new Point(x + (int)Match.lengthdir_x(distance, direction), y + (int)Match.lengthdir_y(distance, direction)); return p; } //Добавление вершин в граф private void Button4_Click(object sender, EventArgs e) //add { if (action_bypass == false) { if(length!=0) graph.size = graph.size-length; string[] sNums = textBox1.Text.Split(' '); if (textBox1.Text != null && sNums.Length == 1) { if (graph.bypass_topologicalsort_complete == true) { graph.bypass_topologicalsort_complete = false; foreach (Graph.Node v in graph.nodes) { string temp = Convert.ToString(v.name[0]); v.name = "" + temp; } cycle = false; searchCycle_complete = false; button5.Enabled = true; button3.Enabled = false; } graph.AddNode(sNums[0]); }else { if(sNums.Length>1) { if (checkBox1.Checked == false) //добавить неориентированное ребро { List<int> L = new List<int>(); foreach (string eg in sNums) L.Add(int.Parse(eg)); if (graph.bypass_topologicalsort_complete == true) { graph.bypass_topologicalsort_complete = false; foreach (Graph.Node v in graph.nodes) { string temp = Convert.ToString(v.name[0]); v.name = "" + temp; } } cycle = true; searchCycle_complete = true; button5.Enabled = false; button3.Enabled = false; button6.Enabled = false; checkBox1.Enabled = false; label3.Text = "Добавлено неориентрованное ребро\n в этом случае это уже цикл\n. Для топологической сортировки очистите область\n"; graph.AddNode(L[0], "", L,false); } else //или ориентированное { List<int> L = new List<int>(); foreach (string eg in sNums) L.Add(int.Parse(eg)); if (graph.bypass_topologicalsort_complete == true) { graph.bypass_topologicalsort_complete = false; foreach (Graph.Node v in graph.nodes) { string temp = Convert.ToString(v.name[0]); v.name = "" + temp; } } cycle = false; searchCycle_complete = false; button5.Enabled = true; button3.Enabled = false; checkBox1.Enabled = false; graph.AddNode(L[0], "", L,true); } } } } } private void Timer1_Tick(object sender, EventArgs e) { if(action_bypass==false) { progressBar1.Visible = false; trackBar1.Enabled = false; button4.Enabled = false; button1.Enabled =false; button6.Text = "Stop"; } else { button6.Text = "Обход графа"; trackBar1.Enabled = true; button4.Enabled = true; progressBar1.Visible = true; button1.Enabled = true; } //недоступна кнопка сохранения в файл if (graph.nodes.Count == 0 || action_bypass == false) button2.Enabled = false; else button2.Enabled = true; graph.size = trackBar1.Value;//регулировка размера узлов для отрисовки if(checkBox3.Checked == false) { for (int i = 0; i < graph.nodes.Count; i++) { for (int j = 0; j < graph.nodes.Count; j++) { if (i != j) // узел не выталкивает сам себя { double distance = Match.point_distance(graph.nodes[i].x, graph.nodes[i].y, graph.nodes[j].x, graph.nodes[j].y); int dist_extra = 10;//доп расст между узлами if (distance <= (graph.size + dist_extra))//если два разных узла оказались внутри друг друга => придадим случ расст { if (graph.nodes[i].x == graph.nodes[j].x) { graph.nodes[i].x = extra_distantion(graph.nodes[i].x); } if (graph.nodes[i].y == graph.nodes[j].y) { graph.nodes[i].y = extra_distantion(graph.nodes[i].y); } //узлы выталкивают в противоположных направлениях if (graph.nodes[i].x < graph.nodes[j].x) { graph.nodes[i].x -= (int)(graph.size + dist_extra - distance); graph.nodes[j].x += (int)(graph.size + dist_extra - distance); } else { graph.nodes[i].x += (int)(graph.size + dist_extra - distance); graph.nodes[j].x -= (int)(graph.size + dist_extra - distance); } if (graph.nodes[i].y < graph.nodes[j].y) { graph.nodes[i].y -= (int)(graph.size + dist_extra - distance); graph.nodes[j].y += (int)(graph.size + dist_extra - distance); } else { graph.nodes[i].y += (int)(graph.size + dist_extra - distance); graph.nodes[j].y -= (int)(graph.size + dist_extra - distance); } } } } //не позволит выйти за пределы экрана go_off_screen(ref graph.nodes, i); } } if (graph_topological != null && checkBox3.Checked == true) { graph_topological.size = trackBar1.Value;//регулировка размера узлов для отрисовки for (int i = 0; i < graph_topological.nodes.Count; i++) { for (int j = 0; j < graph_topological.nodes.Count; j++) { if (i != j) // узел не выталкивает сам себя { double distance = Match.point_distance(graph_topological.nodes[i].x, graph_topological.nodes[i].y, graph_topological.nodes[j].x, graph_topological.nodes[j].y); int dist_extra = 10;//доп расст между узлами if (distance <= (graph_topological.size + dist_extra))//если два разных узла оказались внутри друг друга => придадим случ расст { if (graph_topological.nodes[i].x == graph_topological.nodes[j].x) { graph_topological.nodes[i].x = extra_distantion_topological(graph_topological.nodes[i].x); } if (graph_topological.nodes[i].y == graph_topological.nodes[j].y) { graph_topological.nodes[i].y = extra_distantion_topological(graph_topological.nodes[i].y); } //узлы выталкивают в противоположных направлениях if (graph_topological.nodes[i].x < graph_topological.nodes[j].x) { graph_topological.nodes[i].x -= (int)(graph_topological.size + dist_extra - distance); graph_topological.nodes[j].x += (int)(graph_topological.size + dist_extra - distance); } else { graph_topological.nodes[i].x += (int)(graph_topological.size + dist_extra - distance); graph_topological.nodes[j].x -= (int)(graph_topological.size + dist_extra - distance); } if (graph_topological.nodes[i].y < graph_topological.nodes[j].y) { graph_topological.nodes[i].y -= (int)(graph_topological.size + dist_extra - distance); graph_topological.nodes[j].y += (int)(graph_topological.size + dist_extra - distance); } else { graph_topological.nodes[i].y += (int)(graph_topological.size + dist_extra - distance); graph_topological.nodes[j].y -= (int)(graph_topological.size + dist_extra - distance); } } } } //не позволит выйти за пределы экрана go_off_screen_topological(ref graph_topological.nodes, i); } for (int i = 0; i < graph_topological.nodes.Count; i++) { double distance = Match.point_distance(graph_topological.nodes[i].x, graph_topological.nodes[i].y, graph.nodes[i].x, graph.nodes[i].y); int dist_extra = 10;//доп расст между узлами if (distance <= (graph_topological.size + dist_extra))//если два разных узла оказались внутри друг друга => придадим случ расст { if (graph_topological.nodes[i].x == graph.nodes[i].x) { graph_topological.nodes[i].x = extra_distantion_topological(graph_topological.nodes[i].x); } if (graph_topological.nodes[i].y == graph.nodes[i].y) { graph_topological.nodes[i].y = extra_distantion_topological(graph_topological.nodes[i].y); } //узлы выталкивают в противоположных направлениях if (graph_topological.nodes[i].x < graph.nodes[i].x) { graph_topological.nodes[i].x -= (int)(graph_topological.size + dist_extra - distance); graph.nodes[i].x += (int)(graph.size + dist_extra - distance); } else { graph_topological.nodes[i].x += (int)(graph_topological.size + dist_extra - distance); graph.nodes[i].x -= (int)(graph.size + dist_extra - distance); } if (graph_topological.nodes[i].y < graph.nodes[i].y) { graph_topological.nodes[i].y -= (int)(graph_topological.size + dist_extra - distance); graph.nodes[i].y += (int)(graph.size + dist_extra - distance); } else { graph_topological.nodes[i].y += (int)(graph_topological.size + dist_extra - distance); graph.nodes[i].y -= (int)(graph.size + dist_extra - distance); } } } } Refresh(); // перерисовка формы } private void go_off_screen(ref List<Graph.Node> gr,int i) { if (graph.nodes[i].x - graph.size / 2 < 0) graph.nodes[i].x = graph.size / 2; if (graph.nodes[i].y - graph.size / 2 < 0) graph.nodes[i].y = graph.size / 2; if (graph.nodes[i].x + graph.size / 2 > pictureBox1.Width) graph.nodes[i].x = pictureBox1.Width - graph.size / 2 - 1; if (graph.nodes[i].y + graph.size / 2 > pictureBox1.Height) graph.nodes[i].y = pictureBox1.Height - graph.size / 2 - 1; } private int extra_distantion(int x_y) { var rand = new Random(); if (rand.Next(2) == 1) return x_y += 1; else return x_y -= 1; } private void go_off_screen_topological(ref List<Graph.Node> gr, int i) { if (graph_topological.nodes[i].x - graph_topological.size / 2 < 0) graph_topological.nodes[i].x = graph_topological.size / 2; if (graph_topological.nodes[i].y - graph_topological.size / 2 < 0) graph_topological.nodes[i].y = graph_topological.size / 2; if (graph_topological.nodes[i].x + graph_topological.size / 2 > pictureBox1.Width) graph_topological.nodes[i].x = pictureBox1.Width - graph_topological.size / 2 - 1; if (graph_topological.nodes[i].y + graph_topological.size / 2 > pictureBox1.Height) graph_topological.nodes[i].y = pictureBox1.Height - graph_topological.size / 2 - 1; } private int extra_distantion_topological(int x_y) { var rand = new Random(); if (rand.Next(2) == 1) return x_y += 1; else return x_y -= 1; } //Движение мышью---------------------------------- private void PictureBox1_MouseMove(object sender, MouseEventArgs e) { if(checkBox3.Checked==false) { if (drag != -1) // если перемещается какой то узел { foreach (Graph.Node v in graph.nodes) { if (drag == v.id) { //переместить узел по координам мыши v.x = e.X; v.y = e.Y; break; } } } if (drage != -1) // если из какого узла происходит добавление/уд ребер { foreach (Graph.Node v in graph.nodes) { if (drage == v.id) { //запомнить коорд узла и указ мыши dx1 = v.x; dy1 = v.y; dx2 = e.X; dy2 = e.Y; break; } } } } if(graph_topological!=null && checkBox3.Checked==true) { if (drag != -1) // если перемещается какой то узел { foreach (Graph.Node v in graph_topological.nodes) { if (drag == v.id) { //переместить узел по координам мыши v.x = e.X; v.y = e.Y; break; } } } if (drage != -1) // если из какого узла происходит добавление/уд ребер { foreach (Graph.Node v in graph_topological.nodes) { if (drage == v.id) { //запомнить коорд узла и указ мыши d2x1 = v.x; d2y1 = v.y; d2x2 = e.X; d2y2 = e.Y; break; } } } } } private void PictureBox1_MouseDown(object sender, MouseEventArgs e) { if(checkBox3.Checked==false) { if (e.Button == MouseButtons.Left) { drage = -1;//off add/del edge if (drag == -1) { foreach (Graph.Node v in graph.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph.size / 2) // найти узел на который нажали { drag = v.id; // захват v.x = e.X; // переместить v.y = e.Y; // по координатам мыши break; } } } } if (action_bypass == false) { if (e.Button == MouseButtons.Middle) { drag = -1;//off move drage = -1;//of add/del edge foreach (Graph.Node v in graph.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph.size / 2) { if (checkBox2.Checked == true) graph.removeNode(v.id); //del node break; } } } if (e.Button == MouseButtons.Right) { //сброс координат drag = -1; dx1 = 0; dy1 = 0; dx2 = 0; dy2 = 0; //----------------- foreach (Graph.Node v in graph.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph.size / 2) { //начать добавление/уд ребер из него drage = v.id; dx1 = v.x; dy1 = v.y; dx2 = e.X; dy2 = e.Y; break; } } } } } if (graph_topological != null && checkBox3.Checked==true) { if (e.Button == MouseButtons.Left) { drage = -1;//off add/del edge if (drag == -1) { foreach (Graph.Node v in graph_topological.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph_topological.size / 2) // найти узел на который нажали { drag = v.id; // захват v.x = e.X; // переместить v.y = e.Y; // по координатам мыши break; } } } } if (action_bypass == false) { if (e.Button == MouseButtons.Middle) { drag = -1;//off move drage = -1;//of add/del edge foreach (Graph.Node v in graph_topological.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph_topological.size / 2) { if (checkBox2.Checked == true) graph_topological.removeNode(v.id); //del node break; } } } if (e.Button == MouseButtons.Right) { //сброс координат drag = -1; d2x1 = 0; d2y1 = 0; d2x2 = 0; d2y2 = 0; //----------------- foreach (Graph.Node v in graph_topological.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph_topological.size / 2) { //начать добавление/уд ребер из него drage = v.id; d2x1 = v.x; d2y1 = v.y; d2x2 = e.X; d2y2 = e.Y; break; } } } } } } private void PictureBox1_MouseUp(object sender, MouseEventArgs e) { if(checkBox3.Checked==false) { if (e.Button == MouseButtons.Left) drag = -1; if (e.Button == MouseButtons.Right) { if (drage != -1)//если из какого то узла начато добавление/удаление рёбер { foreach (Graph.Node v in graph.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph.size / 2) // найти узел на котором отпустили кнопку { if (v.id != drage) // если это не тот же самый узел { foreach (Graph.Node v2 in graph.nodes) { if (v2.id == drage) // Найти узел из которого было запущено добавление/уд ребер { if (checkBox2.Checked == true)//удаление { v2.removeEdge(v.id); if (checkBox1.Checked == false) v.removeEdge(v2.id); // если неориент удалить в обоих узлах } else { v2.addEdge(v.id); if (checkBox1.Checked == false) v.addEdge(v2.id); } break; } } } } } } drage = -1; } } if (graph_topological != null && checkBox3.Checked==true) { if (e.Button == MouseButtons.Left) drag = -1; if (e.Button == MouseButtons.Right) { if (drage != -1)//если из какого то узла начато добавление/удаление рёбер { foreach (Graph.Node v in graph_topological.nodes) { if (Match.point_distance(v.x, v.y, e.X, e.Y) < graph_topological.size / 2) // найти узел на котором отпустили кнопку { if (v.id != drage) // если это не тот же самый узел { foreach (Graph.Node v2 in graph_topological.nodes) { if (v2.id == drage) // Найти узел из которого было запущено добавление/уд ребер { if (checkBox2.Checked == true)//удаление { v2.removeEdge(v.id); if (checkBox1.Checked == false) v.removeEdge(v2.id); // если неориент удалить в обоих узлах } else { v2.addEdge(v.id); if (checkBox1.Checked == false) v.addEdge(v2.id); } break; } } } } } } drage = -1; } } } //------------------------------Мышь---------------------- private void Timer2_Tick(object sender, EventArgs e) { timer2.Interval = trackBar2.Value; // регулировка скорости //DFS--------- DFS(false); //------------DFS---- //обнов полосы прогресса в зависимости от кол обработ узлов int k = 0; foreach (Graph.Node v in graph.nodes) if (v.active == 2) k += 1; progressBar1.Maximum = Math.Abs(k-graph.nodes.Count); progressBar1.PerformStep(); } public List<int> cycle_list = new List<int>(); private void DFS(bool cycle) { bool activeNode = false; // если в графе есть активные узлы for (int i = 0; i < graph.nodes.Count; i++) { if (graph.nodes[i].active == 1) // найти активный узел { if (graph.nodes[i].chk == -1) { if(cycle==true) { if (cycle_list.Contains(graph.nodes[i].id) == false) cycle_list.Add(graph.nodes[i].id); } //do something //(данный узел впервые обрабатывается, т.е. при повторной обработке(напр яв-я корнем) сюда не попадет) } bool unprocessedNode = false; // есть ли необработанные узлы в списке смежности //перебрать все узлы в списке while (!unprocessedNode && (graph.nodes[i].chk < graph.nodes[i].edges.Count - 1)) { graph.nodes[i].chk++;//менять проверяемый элемент списка смежности foreach (Graph.Node ed in graph.nodes) { if (ed.id == graph.nodes[i].edges[graph.nodes[i].chk])//найти проверяемый узел { if (ed.active == 0) //если он не активный { ed.active = 1; ed.prev = graph.nodes[i].id;//указать себя в качестве родительского узла graph.nodes[i].active = 3;//запомнить unprocessedNode = true;//в списке смежности есть необработанные узлы break; } } } } if (!(graph.nodes[i].chk < graph.nodes[i].edges.Count - 1)) // если список смежности закончился { bool notfindActoveNode = true;//в списке смежности нет активных узлов foreach (Graph.Node ed in graph.nodes) { if (graph.nodes[i].edges.Contains(ed.id) && ed.active == 1) // найти активный узел из списка notfindActoveNode = false; // найден активный узел } if (notfindActoveNode) // если в списке больше нет активных узлов { if(cycle==false) { textBox2.Text += graph.nodes[i].id.ToString() + " "; topogicalSort.Add(graph.nodes[i].id); }else { bool complete = false; // данную вершину проверили на цикл foreach (Graph.Node v in graph.nodes) { if (v.edges.Count != 0) { for (int k = 0; k < cycle_list.Count; k++) { if (v.id == cycle_list[k]&& cycle_list != null) { for (int j = 0; j < v.edges.Count; j++) if (v.edges[j] == cycle_list[0]) { foreach(Graph.Node v2 in graph.nodes) { if (v2.id == cycle_list[0] && cycle_list != null) { if (graph.dfs(v2.id, 0, cycle_list[0]) > 0) { this.cycle = true; for (int h = 0; h < graph.Get_list_cycle.Count; h++) label3.Text += Convert.ToString(graph.Get_list_cycle[h]); graph.Get_list_cycle.Clear(); } complete = true; } } } } } if (cycle_list != null && complete == true) { complete = false; cycle_list.RemoveAt(0); } } else cycle_list.Remove(v.id); } } //do somthing //(вызов при выходе из узла, когда он был уже полностью обработан) //когда полностью обработан graph.nodes[i].active = 2;//узел был обработан if (graph.nodes[i].prev != -1) // если родитель { foreach (Graph.Node ed in graph.nodes) if (ed.id == graph.nodes[i].prev)//найти его ed.active = 1;//активировать предыдущий узел } } } activeNode = true;//активный узел найден break; } } if (!activeNode) // если нет активных узлов { activeNode = false;//в графе все еще есть необработанные узлы for (int i = 0; i < graph.nodes.Count; i++) { if (graph.nodes[i].active == 0) // попытаться найти все еще необработанные узлы на случай если в гр есть узлы не связ с первым { graph.nodes[i].active = 1; activeNode = true; break; } } if (!activeNode) // если 100% узлы обр { if(cycle==false) { foreach (Graph.Node vert in graph.nodes) vert.active = 0;//вернуться в обычное состояние timer2.Stop(); }else { foreach (Graph.Node vert in graph.nodes) vert.active = 0;//вернуться в обычное состояние searchCycle_complete = true; timer3.Stop(); } action_bypass = false; } } } private void Button6_Click(object sender, EventArgs e) // обход { textBox2.Clear(); if(graph.bypass_topologicalsort_complete==false) { if (trackBar2.Value == 0) { trackBar2.Value = 1; timer2.Interval = trackBar2.Value; } else timer2.Interval = trackBar2.Value; drag = -1; drage = -1; foreach (Graph.Node v in graph.nodes) { v.active = 0; v.prev = -1; v.chk = -1; } if (timer2.Enabled==false && action_bypass==false) { if (graph.nodes.Count > 0) { graph.nodes[0].active = 1; timer2.Start(); action_bypass = true; progressBar1.Value = 0; } } else { timer2.Stop(); action_bypass = false; } } } //Топологическая сортировка private void Button3_Click(object sender, EventArgs e) //topological { try { if(topogicalSort != null) { graph_topological = (Graph)graph.Clone(); checkBox3.Enabled = true; graph.bypass_topologicalsort_complete = true; if (topogicalSort != null) { topogicalSort.Reverse(); for (int i = 0; i < topogicalSort.Count; i++) { foreach (Graph.Node vert in graph.nodes) { if (vert.id == topogicalSort[i]) { vert.name = i.ToString() + "(" + vert.name + ")"; if (length < vert.name.Length) length = vert.name.Length; } } } topogicalSort.Clear(); graph.size = graph.size + length; int sizebool = graph.MaxID; foreach (Graph.Node node in graph.nodes) { bool[] find = new bool[sizebool * 4 + 1]; for (int i = 0; i < node.edges.Count * 4; i++) find[i] = false; List<int> edg = new List<int>(node.edges.Count); for (int i = 0; i < node.edges.Count; i++) { foreach (Graph.Node v in graph.nodes) { string name = ""; bool met_bracket = false; for (int j = 0; j < v.name.Length; j++) { if (met_bracket == false && v.name[j] == '(') { met_bracket = true; } if (met_bracket == true && ((v.name[j] >= '0' && v.name[j] <= '9') || (v.name[j] >= '0' && v.name[j] <= '9'))) { name += v.name[j]; } if (v.name[j] == ')') break; } if (node.edges[i] == Convert.ToInt32(Convert.ToString(name))) { string id_v = ""; for (int j = 0; j < v.name.Length; j++) { if (v.name[j] == '(') { break; } if ((v.name[j] > '0' && v.name[j] < '9') || (v.name[j] > '0' && v.name[j] < '9')) { id_v += v.name[j]; } } edg.Add(Convert.ToInt32(Convert.ToString(id_v))); find[Convert.ToInt32(Convert.ToString(id_v))] = true; break; } } } node.edges.Clear(); string s = Convert.ToString(node.name[0]); node.id = Convert.ToInt32(s); for (int i = 0; i < edg.Count; i++) { node.edges.Add(edg[i]); } } } else MessageBox.Show("Сначала выполните обход графа!!"); } textBox2.Clear(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } /* private void topological_sort(bool[] used) { for (int i = 0; i < graph.nodes.Count;i++) { used[i] = false; } ans.Clear(); foreach(Graph.Node vert in graph.nodes) { if (!used[vert.id]) dfs(vert.id, ref used); ; } ans.Reverse(); string s = ""; for (int i = 0; i < ans.Count; i++) s += "" + ans[i].ToString() + " "; textBox2.Text = s; } /*private void dfs(int v,ref bool[]used) { used[v] = true; if(v<graph.nodes.Count) { if (v!=0) { for (int i = graph.nodes[v - 1].edges.Count - 1; i >= 0; i--) { int nextv = graph.nodes[v - 1].edges[i]; if (!used[nextv]) dfs(nextv, ref used); } }else { for (int i = graph.nodes[v].edges.Count - 1; i >= 0; i--) { int nextv = graph.nodes[v].edges[i]; if (!used[nextv]) dfs(nextv, ref used); } } } ans.Add(v); }*/ //--------------------------Топ сортировка------------------------------- //Загрузка из файла---------------------------------- private void Button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void OpenFileDialog1_FileOk(object sender, CancelEventArgs e) { bool noWord = true; graph.nodes.Clear(); StreamReader file = File.OpenText(openFileDialog1.FileName); while(!file.EndOfStream) { noWord = true; string s = file.ReadLine(); for (int i = 0; i < s.Length; i++) { if (s[i] >= 'a' && s[i] <= 'z') { noWord = false; break; } } if (noWord == false) continue; string[] ss = s.Split(','); List<int> L = new List<int>(); if(ss[3]!="") { string[] sse = ss[3].Split(';'); foreach (string eg in sse) L.Add(int.Parse(eg)); } graph.loadgraph(id: int.Parse(ss[0]), x: int.Parse(ss[1]), y: int.Parse(ss[2]), name: ss[4], edge: L); } file.Close(); } //Сохранение в файл private void Button2_Click(object sender, EventArgs e)//save { if (graph.nodes.Count != 0) saveFileDialog1.ShowDialog(); } private void SaveFileDialog1_FileOk(object sender, CancelEventArgs e) { //перезапись файла if (File.Exists(saveFileDialog1.FileName)) File.Delete(saveFileDialog1.FileName); FileStream file = File.OpenWrite(saveFileDialog1.FileName); string data = " id , x, y, v1;v2;...vn, name \n"; byte[] info = new UTF8Encoding(true).GetBytes(data); file.Write(info, 0, info.Length); //id узел который связана с ; ; // id, x, y, v1;v2..;vn,name foreach(Graph.Node vert in graph.nodes) { data = ""; data += vert.id.ToString() + ","; data += vert.x.ToString() + ","; data += vert.y.ToString() + ","; if(vert.edges.Count!=0) { foreach (int edg in vert.edges) data += edg.ToString()+";"; data = data.Remove(data.Length - 1, 1); } data += "," + vert.name + "\n"; info = new UTF8Encoding(true).GetBytes(data); file.Write(info, 0, info.Length); } file.SetLength(file.Length - 1); // удалить последний \n file.Close(); } //-----------------------------------------Save file-------------- //Проверка на цикл----------------------------- private void Button5_Click(object sender, EventArgs e) { //FIXME: if (trackBar2.Value == 0) { trackBar2.Value = 1; timer3.Interval = trackBar2.Value; } else timer3.Interval = trackBar2.Value; drag = -1; drage = -1; foreach (Graph.Node v in graph.nodes) { v.active = 0; v.prev = -1; v.chk = -1; } if (timer3.Enabled == false && action_bypass == false) { if (graph.nodes.Count > 0) { graph.nodes[0].active = 1; timer3.Start(); action_bypass = true; progressBar1.Value = 0; } } else { timer3.Stop(); action_bypass = false; } } private void Timer3_Tick(object sender, EventArgs e) { timer3.Interval = trackBar2.Value; // регулировка скорости //DFS--------- DFS(true); //------------DFS---- //обнов полосы прогресса в зависимости от кол обработ узлов int k = 0; foreach (Graph.Node v in graph.nodes) if (v.active == 2) k += 1; progressBar1.Maximum = 0+k; progressBar1.PerformStep(); if (this.cycle == false && searchCycle_complete == true) { button3.Enabled = true; button5.Enabled = false; } else if(searchCycle_complete == true) MessageBox.Show("В графе есть цикл!"); }//---------------------Cycle----------------- //Clear--------------------------------------- private void Button7_Click(object sender, EventArgs e) { graph.nodes.Clear(); graph.clear(); checkBox1.Enabled = true; checkBox3.Enabled = false; button6.Enabled = true; button5.Enabled = true; }//--------------------------------------Clear---------------- }//конец класса Form }//конец пространства имен
46.022529
235
0.380849
[ "Apache-2.0" ]
StrongerProgrammer7/Graph_topologicalSort
LB15/Form1.cs
67,300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Services.Functions; namespace Domain.Entity { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using IntlTexto; using IntlTexto.Intl; public partial class Dashboard { /// <summary> /// Tipo = {int} | Nome {CD_DEPARTAMENTO} /// Campo Obrigatorio /// </summary> [Key, Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Editable(false)] [ScaffoldColumn(false)] [Required(ErrorMessageResourceType = typeof(strings), ErrorMessageResourceName = "CampoRequerido")] public int ID { get; set; } public decimal VLR_FATURAMENTO { get; set; } public decimal VLR_ST { get; set; } public decimal VLR_IPI { get; set; } public decimal VLR_DEVOLUCAO { get; set; } public decimal VLR_META { get; set; } } }
24.840909
107
0.653248
[ "MIT" ]
shpsyte/CRMFx
Libraries/Domain/Entity/Dashboard.cs
1,095
C#
using ObjectManager.Rest.Tests.Integration.Common.TestFixtures; using Xunit; namespace ObjectManager.Rest.V1.Tests.Integration { [CollectionDefinition(CollectionName)] public class WorkspaceSetupFixture : WorkspaceSetupFixtureHelper, ICollectionFixture<WorkspaceSetupFixture> { } }
27.272727
111
0.806667
[ "MIT" ]
Heretik-Corp/Objectmanager-Rest
ObjectManager.Integration/WorkspaceSetupFixture.cs
302
C#
using System.Text; namespace Capgemini.Xrm.CdsDataMigratorLibrary.Models { public class DeserializationSettings { public string XmlFolderPath { get; set; } public bool FailedValidation { get; set; } public string FailedValidationMessage { get; set; } public void Validate() { FailedValidation = false; var stringBuilder = new StringBuilder(); if (string.IsNullOrWhiteSpace(XmlFolderPath) || XmlFolderPath == null) { stringBuilder.AppendLine("Enter schema folder path"); FailedValidation = true; } FailedValidationMessage = stringBuilder.ToString(); } } }
27.846154
82
0.603591
[ "MIT" ]
Capgemini/xrm-datamigration-xrmtoolbox
Capgemini.Xrm.CdsDataMigrator/Capgemini.Xrm.CdsDataMigratorLibrary/Models/DeserializationSettings.cs
726
C#
namespace Cacti.Web.Features.Shared.ViewModels { public class BlogPostsRequestViewModel { public int page { get; set; } = 1; public int pageSize { get; set; } = 20; public string tag { get; set; } = string.Empty; public string q { get; set; } = string.Empty; } }
28
55
0.597403
[ "MIT" ]
felsig/Cacti
src/Cacti.Web/Features/Shared/ViewModels/BlogPostsRequestViewModel.cs
308
C#
using Abp.Authorization; using Abp.Localization; using Abp.MultiTenancy; namespace Volo.SqliteDemo.Authorization { public class SqliteDemoAuthorizationProvider : AuthorizationProvider { public override void SetPermissions(IPermissionDefinitionContext context) { context.CreatePermission(PermissionNames.Pages_Users, L("Users")); context.CreatePermission(PermissionNames.Pages_Roles, L("Roles")); context.CreatePermission(PermissionNames.Pages_Tenants, L("Tenants"), multiTenancySides: MultiTenancySides.Host); } private static ILocalizableString L(string name) { return new LocalizableString(name, SqliteDemoConsts.LocalizationSourceName); } } }
34.409091
125
0.718626
[ "MIT" ]
OzBob/aspnetboilerplate-samples
SqliteDemo/aspnet-core/src/Volo.SqliteDemo.Core/Authorization/SqliteDemoAuthorizationProvider.cs
759
C#
using System; using Confuser.Core; namespace Confuser.DynCipher { internal class DynCipherComponent : ConfuserComponent { public const string _ServiceId = "Confuser.DynCipher"; public override string Name { get { return "Dynamic Cipher"; } } public override string Description { get { return "Provides dynamic cipher generation services."; } } public override string Id { get { return _ServiceId; } } public override string FullId { get { return _ServiceId; } } protected override void Initialize(ConfuserContext context) { context.Registry.RegisterService(_ServiceId, typeof(IDynCipherService), new DynCipherService()); } protected override void PopulatePipeline(ProtectionPipeline pipeline) { // } } }
23.65625
99
0.733157
[ "MIT" ]
000x0/neo-ConfuserEx
Confuser.DynCipher/DynCipherComponent.cs
759
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Analysis { /// <summary>Transforms the token stream as per the Porter stemming algorithm. /// Note: the input to the stemming filter must already be in lower case, /// so you will need to use LowerCaseFilter or LowerCaseTokenizer farther /// down the Tokenizer chain in order for this to work properly! /// <P> /// To use this filter with other analyzers, you'll want to write an /// Analyzer class that sets up the TokenStream chain as you want it. /// To use this with LowerCaseTokenizer, for example, you'd write an /// analyzer like this: /// <P> /// <PRE> /// class MyAnalyzer extends Analyzer { /// public final TokenStream tokenStream(String fieldName, Reader reader) { /// return new PorterStemFilter(new LowerCaseTokenizer(reader)); /// } /// } /// </PRE> /// </summary> public sealed class PorterStemFilter : TokenFilter { private PorterStemmer stemmer; public PorterStemFilter(TokenStream in_Renamed) : base(in_Renamed) { stemmer = new PorterStemmer(); } /// <summary>Returns the next input Token, after being stemmed </summary> public override Token Next() { Token token = input.Next(); if (token == null) return null; else { System.String s = stemmer.Stem(token.termText); if ((System.Object) s != (System.Object) token.termText) // Yes, I mean object reference comparison here token.termText = s; return token; } } } }
37.893939
82
0.644142
[ "MIT" ]
baohaojun/beagrep
beagrepd/Lucene.Net/Analysis/PorterStemFilter.cs
2,501
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Storage { using System.Threading.Tasks; /// <summary> /// Document database service /// </summary> public interface IDatabaseServer { /// <summary> /// Opens a named or default database /// </summary> /// <param name="id"></param> /// <param name="options"></param> /// <returns></returns> Task<IDatabase> OpenAsync(string id = null, DatabaseOptions options = null); } }
32.833333
99
0.510152
[ "MIT" ]
Azure/Industrial-IoT
common/src/Microsoft.Azure.IIoT.Abstractions/src/Storage/IDatabaseServer.cs
788
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Commands.Common.MSGraph.Version1_0.DirectoryObjects.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// entity /// </summary> public partial class MicrosoftGraphEntity { /// <summary> /// Initializes a new instance of the MicrosoftGraphEntity class. /// </summary> public MicrosoftGraphEntity() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftGraphEntity class. /// </summary> /// <param name="additionalProperties">Unmatched properties from the /// message are deserialized this collection</param> /// <param name="id">Read-only.</param> public MicrosoftGraphEntity(IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), string id = default(string)) { AdditionalProperties = additionalProperties; Id = id; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets unmatched properties from the message are deserialized /// this collection /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalProperties { get; set; } /// <summary> /// Gets or sets read-only. /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } } }
33.109375
154
0.606418
[ "MIT" ]
Azure/azure-powershell-common
src/Graph.Rbac/MicrosoftGraph/Version1_0/DirectoryObjects/Models/MicrosoftGraphEntity.cs
2,119
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace LuceneNetCzechSupport.WpfClient.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.032258
151
0.588398
[ "MIT" ]
Vavro/Tests
LuceneNetCzechSupport/LuceneNetCzechSupport.WpfClient/Properties/Settings.Designer.cs
1,088
C#
namespace Epam.JDI.Core.Logging { public enum LogLevels { Off =-1, Fatal = 0, Error = 3, Warning = 4, Info = 6, Debug = 7, Trace = 8, All = 100 } }
16.733333
32
0.370518
[ "MIT" ]
elv1s42/jdi-csharp
JDI/Core/Logging/LogLevels.cs
253
C#
using System; using System.Data; using System.Linq; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using LinqToDB.Benchmarks.Mappings; using LinqToDB.Benchmarks.TestProvider; using LinqToDB.Data; using LinqToDB.DataProvider.SqlServer; using LinqToDB.Linq; using LinqToDB.Mapping; namespace LinqToDB.Benchmarks.Queries { public class Issue3268Benchmark { private const int _iterations = 2; private DataConnection _db = null!; private IDbConnection _cn = null!; private Func<DataConnection, int, int> _compiled = null!; private Func<DataConnection, int, int> _compiledNullable = null!; [GlobalSetup] public void Setup() { _cn = new MockDbConnection(new QueryResult() { Return = 1 }, ConnectionState.Open); _db = new DataConnection(new SqlServerDataProvider(ProviderName.SqlServer, SqlServerVersion.v2008, SqlServerProvider.MicrosoftDataSqlClient), _cn); _compiled = CompiledQuery.Compile<DataConnection, int, int>((ctx, i) => ctx.GetTable<MyPOCO>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update()); _compiledNullable = CompiledQuery.Compile<DataConnection, int, int>((ctx, i) => ctx.GetTable<MyPOCON>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update()); } [Benchmark] public void Update_Nullable() { for (var i = 0; i < _iterations; i++) { _db.GetTable<MyPOCON>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update(); } } [Benchmark] public void Update_Nullable_Full() { for (var i = 0; i < _iterations; i++) { using (var db = new DataConnection(new SqlServerDataProvider(ProviderName.SqlServer, SqlServerVersion.v2008, SqlServerProvider.MicrosoftDataSqlClient), _cn)) { db.GetTable<MyPOCON>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update(); } } } [Benchmark] public void Compiled_Update_Nullable() { for (var i = 0; i < _iterations; i++) { _compiledNullable(_db, i); } } [Benchmark] public void Compiled_Update_Nullable_Full() { for (var i = 0; i < _iterations; i++) { using (var db = new DataConnection(new SqlServerDataProvider(ProviderName.SqlServer, SqlServerVersion.v2008, SqlServerProvider.MicrosoftDataSqlClient), _cn)) { _compiledNullable(db, i); } } } [Benchmark] public void Update() { for (var i = 0; i < _iterations; i++) { _db.GetTable<MyPOCO>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update(); } } [Benchmark] public void Update_Full() { for (var i = 0; i < _iterations; i++) { using (var db = new DataConnection(new SqlServerDataProvider(ProviderName.SqlServer, SqlServerVersion.v2008, SqlServerProvider.MicrosoftDataSqlClient), _cn)) { db.GetTable<MyPOCO>() .Where(p => p.Code == "A" + i && p.Currency == "SUR") .Set(p => p.Weight, i * 10) .Set(p => p.Currency, "SUR") .Set(p => p.Value, i * i + 2) .Update(); } } } [Benchmark(Baseline = true)] public void Compiled_Update() { for (var i = 0; i < _iterations; i++) { _compiled(_db, i); } } [Benchmark] public void Compiled_Update_Full() { for (var i = 0; i < _iterations; i++) { using (var db = new DataConnection(new SqlServerDataProvider(ProviderName.SqlServer, SqlServerVersion.v2008, SqlServerProvider.MicrosoftDataSqlClient), _cn)) { _compiled(db, i); } } } [Table] class MyPOCON { [Column] public string? Code { get; set; } [Column] public string? Currency { get; set; } [Column] public decimal Value { get; set; } [Column] public decimal? Weight { get; set; } } [Table] class MyPOCO { [Column] public string? Code { get; set; } [Column] public string? Currency { get; set; } [Column] public decimal Value { get; set; } [Column] public decimal Weight { get; set; } } } }
27.550296
162
0.584407
[ "MIT" ]
Kshitij-Kafle-123/linq2db
Tests/Tests.Benchmarks/Benchmarks/Queries/Issue3268Benchmark.cs
4,490
C#
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved. // 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 full license information. namespace ReactiveUI.Tests { public class ExampleWindowViewModel : ReactiveObject { } }
32.5
77
0.751282
[ "MIT" ]
benchabot2/ReactiveUI
src/ReactiveUI.Tests/Mocks/ExampleWindowViewModel.cs
392
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 Xunit; namespace System.Tests { public static class BadImageFormatExceptionTests { private const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); [Fact] public static void Ctor_Empty() { var exception = new BadImageFormatException(); ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_BADIMAGEFORMAT, validateMessage: false); Assert.Null(exception.FileName); } [Fact] public static void Ctor_String() { string message = "this is not the file you're looking for"; var exception = new BadImageFormatException(message); ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_BADIMAGEFORMAT, message: message); Assert.Null(exception.FileName); } [Fact] public static void Ctor_String_Exception() { string message = "this is not the file you're looking for"; var innerException = new Exception("Inner exception"); var exception = new BadImageFormatException(message, innerException); ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_BADIMAGEFORMAT, innerException: innerException, message: message); Assert.Null(exception.FileName); } [Fact] public static void Ctor_String_String() { string message = "this is not the file you're looking for"; string fileName = "file.txt"; var exception = new BadImageFormatException(message, fileName); ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_BADIMAGEFORMAT, message: message); Assert.Equal(fileName, exception.FileName); } [Fact] public static void Ctor_String_String_Exception() { string message = "this is not the file you're looking for"; string fileName = "file.txt"; var innerException = new Exception("Inner exception"); var exception = new BadImageFormatException(message, fileName, innerException); ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_BADIMAGEFORMAT, innerException: innerException, message: message); Assert.Equal(fileName, exception.FileName); } [Fact] public static void ToStringTest() { string message = "this is not the file you're looking for"; string fileName = "file.txt"; var innerException = new Exception("Inner exception"); var exception = new BadImageFormatException(message, fileName, innerException); var toString = exception.ToString(); Assert.Contains(": " + message, toString); Assert.Contains(": '" + fileName + "'", toString); Assert.Contains("---> " + innerException.ToString(), toString); // set the stack trace try { throw exception; } catch { Assert.False(string.IsNullOrEmpty(exception.StackTrace)); Assert.Contains(exception.StackTrace, exception.ToString()); } } [Fact] public static void FusionLogTest() { string message = "this is not the file you're looking for"; string fileName = "file.txt"; var innerException = new Exception("Inner exception"); var exception = new BadImageFormatException(message, fileName, innerException); Assert.Null(exception.FusionLog); } } }
40.610526
149
0.630638
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Runtime/tests/System/BadImageFormatExceptionTests.cs
3,860
C#
using Chilicki.StarWars.Data.Entities; using Chilicki.StarWars.Data.Helpers.Paging; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Chilicki.StarWars.Data.Repositories { public interface IBaseRepository<TEntity> where TEntity : BaseNamedEntity { Task<IEnumerable<TEntity>> GetAllAsync(); Task<IEnumerable<TEntity>> GetPageAsync(Pager pager); Task<TEntity> FindAsync(Guid id); Task<TEntity> AddAsync(TEntity entity); void Remove(TEntity entity); } }
31.882353
77
0.736162
[ "MIT" ]
mchilicki/star-wars-rest-api
Chilicki.StarWars/Chilicki.StarWars.Data/Repositories/IBaseRepository.cs
544
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnt.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='SE_IMPERSONATION_STATE.xml' path='doc/member[@name="SE_IMPERSONATION_STATE"]/*' /> public unsafe partial struct SE_IMPERSONATION_STATE { /// <include file='SE_IMPERSONATION_STATE.xml' path='doc/member[@name="SE_IMPERSONATION_STATE.Token"]/*' /> [NativeTypeName("PACCESS_TOKEN")] public void* Token; /// <include file='SE_IMPERSONATION_STATE.xml' path='doc/member[@name="SE_IMPERSONATION_STATE.CopyOnOpen"]/*' /> [NativeTypeName("BOOLEAN")] public byte CopyOnOpen; /// <include file='SE_IMPERSONATION_STATE.xml' path='doc/member[@name="SE_IMPERSONATION_STATE.EffectiveOnly"]/*' /> [NativeTypeName("BOOLEAN")] public byte EffectiveOnly; /// <include file='SE_IMPERSONATION_STATE.xml' path='doc/member[@name="SE_IMPERSONATION_STATE.Level"]/*' /> public SECURITY_IMPERSONATION_LEVEL Level; }
45.153846
145
0.740204
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/winnt/SE_IMPERSONATION_STATE.cs
1,176
C#
namespace k8s { /// <summary> /// Object that allows self validation /// </summary> public interface IValidate { /// <summary> /// Validate the object. /// </summary> void Validate(); } }
17.428571
42
0.504098
[ "Apache-2.0" ]
admilazz/csharp
src/KubernetesClient/IValidate.cs
244
C#
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * Copyright (C) 2019 Syngenta * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Tim Shearouse - initial API and implementation * R. Andres Ferreyra - Added MixOrder, as requested for Mix Ticket "Product Group" compatibility. *******************************************************************************/ using AgGateway.ADAPT.ApplicationDataModel.Representations; namespace AgGateway.ADAPT.ApplicationDataModel.Products { public class ProductComponent { public int IngredientId { get; set; } public NumericRepresentationValue Quantity { get; set; } public bool IsProduct { get; set; } public bool IsCarrier { get; set; } public int? MixOrder { get; set; } // In what order was this component added to the mix? (1 = First). // Can have duplicate numbers, representing a situation where two or more components are added simultaneously. } }
41.69697
118
0.625
[ "EPL-1.0" ]
AnkitGupta777/ADAPT
source/ADAPT/Products/ProductComponent.cs
1,378
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.ComponentModel.Design.Serialization { /// <summary> /// This interface may be optionally implemented by the designer loader to provide /// load services to outside components. It provides support for asynchronous loading /// of the designer and allows other objects to initiate a reload of othe /// design surface. Designer loaders do not need to implement this but it is /// recommended. We do not directly put this on DesignerLoader so we can prevent /// outside objects from interacting with the main methods of a designer loader. /// These should only be called by the designer host. /// </summary> public interface IDesignerLoaderService { /// <summary> /// Adds a load dependency to this loader. This indicates that some other /// object is also participating in the load, and that the designer loader /// should not call EndLoad on the loader host until all load dependencies /// have called DependentLoadComplete on the designer loader. /// </summary> void AddLoadDependency(); /// <summary> /// This is called by any object that has previously called /// AddLoadDependency to signal that the dependent load has completed. /// The caller should pass either an empty collection or null to indicate /// a successful load, or a collection of exceptions that indicate the /// reason(s) for failure. /// </summary> void DependentLoadComplete(bool successful, ICollection errorCollection); /// <summary> /// This can be called by an outside object to request that the loader /// reload the design document. If it supports reloading and wants to /// comply with the reload, the designer loader should return true. Otherwise /// it should return false, indicating that the reload will not occur. /// Callers should not rely on the reload happening immediately; the /// designer loader may schedule this for some other time, or it may /// try to reload at once. /// </summary> bool Reload(); } }
48.479167
89
0.681994
[ "MIT" ]
2m0nd/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/IDesignerLoaderService.cs
2,327
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Text; using static _3dprobe.Bridge.DXGI; using static _3dprobe.Bridge.Direct3D11; using BOOL = System.Int32; using UINT = System.UInt32; namespace _3dprobe.Bridge { public static class Direct3D12 { public static readonly Guid IID_D3D12Device = new Guid("189819f1-1db6-4b57-be54-1821339b85f7"); [DllImport("d3d12.dll", CallingConvention = CallingConvention.StdCall)] public static extern int D3D12CreateDevice([MarshalAs(UnmanagedType.Interface)] object pAdapter, D3D_FEATURE_LEVEL MinimumFeatureLevel, Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppDevice); [ComImport, SuppressUnmanagedCodeSecurity, Guid("c4fec28f-7966-4e95-9f94-f431cb56c3b8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ID3D12Object { [PreserveSig] int GetPrivateData(); [PreserveSig] int SetPrivateData(); [PreserveSig] int SetPrivateDataInterface(); [PreserveSig] int SetName(); } [ComImport, SuppressUnmanagedCodeSecurity, Guid("189819f1-1db6-4b57-be54-1821339b85f7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ID3D12Device : ID3D12Object { [PreserveSig] new int GetPrivateData(); [PreserveSig] new int SetPrivateData(); [PreserveSig] new int SetPrivateDataInterface(); [PreserveSig] new int SetName(); [PreserveSig] uint GetNodeCount(); [PreserveSig] int CreateCommandQueue(); [PreserveSig] int CreateCommandAllocator(); [PreserveSig] int CreateGraphicsPipelineState(); [PreserveSig] int CreateComputePipelineState(); [PreserveSig] int CreateCommandList(); [PreserveSig] int CheckFeatureSupport(D3D12_FEATURE Feature, IntPtr pFeatureSupportData, uint FeatureSupportDataSize); [PreserveSig] int CreateDescriptorHeap(); [PreserveSig] int GetDescriptorHandleIncrementSize(); [PreserveSig] int CreateRootSignature(); [PreserveSig] int CreateConstantBufferView(); [PreserveSig] int CreateShaderResourceView(); [PreserveSig] int CreateUnorderedAccessView(); [PreserveSig] int CreateRenderTargetView(); [PreserveSig] int CreateDepthStencilView(); [PreserveSig] int CreateSampler(); [PreserveSig] int CopyDescriptors(); [PreserveSig] int CopyDescriptorsSimple(); [PreserveSig] void GetResourceAllocationInfo(); [PreserveSig] void GetCustomHeapProperties(); [PreserveSig] int CreateCommittedResource(); [PreserveSig] int CreateHeap(); [PreserveSig] int CreatePlacedResource(); [PreserveSig] int CreateReservedResource(); [PreserveSig] int CreateSharedHandle(); [PreserveSig] int OpenSharedHandle(); [PreserveSig] int OpenSharedHandleByName(); [PreserveSig] int MakeResident(); [PreserveSig] int Evict(); [PreserveSig] int CreateFence(); [PreserveSig] int GetDeviceRemovedReason(); [PreserveSig] int GetCopyableFootprints(); [PreserveSig] int CreateQueryHeap(); [PreserveSig] int SetStablePowerState(); [PreserveSig] int CreateCommandSignature(); [PreserveSig] int GetResourceTiling(); [PreserveSig] void GetAdapterLuid(); } public enum D3D12_FEATURE { D3D12_FEATURE_D3D12_OPTIONS = 0, D3D12_FEATURE_ARCHITECTURE = 1, D3D12_FEATURE_FEATURE_LEVELS = 2, D3D12_FEATURE_FORMAT_SUPPORT = 3, D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = 4, D3D12_FEATURE_FORMAT_INFO = 5, D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = 6, D3D12_FEATURE_SHADER_MODEL = 7, D3D12_FEATURE_D3D12_OPTIONS1 = 8, D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT = 10, D3D12_FEATURE_ROOT_SIGNATURE = 12, D3D12_FEATURE_ARCHITECTURE1 = 16, D3D12_FEATURE_D3D12_OPTIONS2 = 18, D3D12_FEATURE_SHADER_CACHE = 19, D3D12_FEATURE_COMMAND_QUEUE_PRIORITY = 20, D3D12_FEATURE_D3D12_OPTIONS3 = 21, D3D12_FEATURE_EXISTING_HEAPS = 22, D3D12_FEATURE_D3D12_OPTIONS4 = 23, D3D12_FEATURE_SERIALIZATION = 24, D3D12_FEATURE_CROSS_NODE = 25, D3D12_FEATURE_D3D12_OPTIONS5 = 27, D3D12_FEATURE_D3D12_OPTIONS6 = 30, D3D12_FEATURE_QUERY_META_COMMAND = 31 } public enum D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS { D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE = 0, D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE = 0x1 } public enum D3D12_CROSS_NODE_SHARING_TIER { D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED = 0, D3D12_CROSS_NODE_SHARING_TIER_1_EMULATED = 1, D3D12_CROSS_NODE_SHARING_TIER_1 = 2, D3D12_CROSS_NODE_SHARING_TIER_2 = 3, D3D12_CROSS_NODE_SHARING_TIER_3 = 4 } public enum D3D12_RESOURCE_HEAP_TIER { D3D12_RESOURCE_HEAP_TIER_1 = 1, D3D12_RESOURCE_HEAP_TIER_2 = 2 } public enum D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER { D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED = 0, D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1 = 1, D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2 = 2 } public enum D3D12_VIEW_INSTANCING_TIER { D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0, D3D12_VIEW_INSTANCING_TIER_1 = 1, D3D12_VIEW_INSTANCING_TIER_2 = 2, D3D12_VIEW_INSTANCING_TIER_3 = 3 } public enum D3D12_SHADER_MIN_PRECISION_SUPPORT { D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE = 0, D3D12_SHADER_MIN_PRECISION_SUPPORT_10_BIT = 0x1, D3D12_SHADER_MIN_PRECISION_SUPPORT_16_BIT = 0x2 } public enum D3D12_TILED_RESOURCES_TIER { D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED = 0, D3D12_TILED_RESOURCES_TIER_1 = 1, D3D12_TILED_RESOURCES_TIER_2 = 2, D3D12_TILED_RESOURCES_TIER_3 = 3, D3D12_TILED_RESOURCES_TIER_4 = 4 } public enum D3D12_RESOURCE_BINDING_TIER { D3D12_RESOURCE_BINDING_TIER_1 = 1, D3D12_RESOURCE_BINDING_TIER_2 = 2, D3D12_RESOURCE_BINDING_TIER_3 = 3 } public enum D3D12_CONSERVATIVE_RASTERIZATION_TIER { D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED = 0, D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, D3D12_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 = 3 } public enum D3D_ROOT_SIGNATURE_VERSION { D3D_ROOT_SIGNATURE_VERSION_1 = 0x1, D3D_ROOT_SIGNATURE_VERSION_1_0 = 0x1, D3D_ROOT_SIGNATURE_VERSION_1_1 = 0x2 } public enum D3D_SHADER_MODEL { D3D_SHADER_MODEL_5_1 = 0x51, D3D_SHADER_MODEL_6_0 = 0x60, D3D_SHADER_MODEL_6_1 = 0x61, D3D_SHADER_MODEL_6_2 = 0x62, D3D_SHADER_MODEL_6_3 = 0x63, D3D_SHADER_MODEL_6_4 = 0x64, D3D_SHADER_MODEL_6_5 = 0x65 } [Flags] public enum D3D12_SHADER_CACHE_SUPPORT_FLAGS { D3D12_SHADER_CACHE_SUPPORT_NONE = 0, D3D12_SHADER_CACHE_SUPPORT_SINGLE_PSO = 0x1, D3D12_SHADER_CACHE_SUPPORT_LIBRARY = 0x2, D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_INPROC_CACHE = 0x4, D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_DISK_CACHE = 0x8 } public enum D3D12_COMMAND_LIST_TYPE { D3D12_COMMAND_LIST_TYPE_DIRECT = 0, D3D12_COMMAND_LIST_TYPE_BUNDLE = 1, D3D12_COMMAND_LIST_TYPE_COMPUTE = 2, D3D12_COMMAND_LIST_TYPE_COPY = 3, D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE = 4, D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS = 5, D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE = 6 } public enum D3D12_COMMAND_LIST_SUPPORT_FLAGS { D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0, D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT), D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_BUNDLE), D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_COMPUTE), D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_COPY), D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_DECODE = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE), D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_PROCESS = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS), D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_ENCODE = (1 << D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE) } public enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER { D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0 = 0, D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1 = (D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0 + 1), D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_2 = (D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1 + 1), } public enum D3D12_HEAP_SERIALIZATION_TIER { D3D12_HEAP_SERIALIZATION_TIER_0 = 0, D3D12_HEAP_SERIALIZATION_TIER_10 = 10 } public enum D3D12_RENDER_PASS_TIER { D3D12_RENDER_PASS_TIER_0 = 0, D3D12_RENDER_PASS_TIER_1 = 1, D3D12_RENDER_PASS_TIER_2 = 2 } public enum D3D12_RAYTRACING_TIER { D3D12_RAYTRACING_TIER_NOT_SUPPORTED = 0, D3D12_RAYTRACING_TIER_1_0 = 10, D3D12_RAYTRACING_TIER_1_1 = 11 } public enum D3D12_VARIABLE_SHADING_RATE_TIER { D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED = 0, D3D12_VARIABLE_SHADING_RATE_TIER_1 = 1, D3D12_VARIABLE_SHADING_RATE_TIER_2 = 2 } [Flags] public enum D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS { D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE = 0, D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_SUPPORTED = 0x1 } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("64비트 부동소수점 셰이더 연산", null)] public bool DoublePrecisionFloatShaderOps; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("출력 병합기 논리 연산", null)] public bool OutputMergerLogicOp; [ItemDescription("지원하는 최소 정밀도", null)] public D3D12_SHADER_MIN_PRECISION_SUPPORT MinPrecisionSupport; [ItemDescription("타일 리소스 단계", null)] public D3D12_TILED_RESOURCES_TIER TiledResourcesTier; [ItemDescription("리소스 바인딩 단계", null)] public D3D12_RESOURCE_BINDING_TIER ResourceBindingTier; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("픽셀 셰이더의 지정된 스텐실 참조 지원", null)] public bool PSSpecifiedStencilRefSupported; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("타입이 지정된 정렬되지 않은 접근 뷰 추가 포맷 지원", null)] public bool TypedUAVLoadAdditionalFormats; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("정렬된 래스터라이저 뷰 지원", null)] public bool ROVsSupported; [ItemDescription("보수적 래스터라이제이션 단계", null)] public D3D12_CONSERVATIVE_RASTERIZATION_TIER ConservativeRasterizationTier; [ItemDescription("리소스 당 최대 GPU 가상 주소 비트 수", null)] public int MaxGPUVirtualAddressBitsPerResource; [MarshalAs(UnmanagedType.Bool)] public bool StandardSwizzle64KBSupported; public D3D12_CROSS_NODE_SHARING_TIER CrossNodeSharingTier; [MarshalAs(UnmanagedType.Bool)] public bool CrossAdapterRowMajorTextureSupported; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("지오메트리 셰이더 에뮬레이션을 제외한 셰이더 피딩 래스터라이저 지원을 통한 뷰포트 및 렌더타겟 배열 색인", null)] public bool VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation; [ItemDescription("리소스 힙 단계", null)] public D3D12_RESOURCE_HEAP_TIER ResourceHeapTier; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("HLSL 6.0의 Wave 연산 지원", null)] public bool WaveOps; [ItemDescription("최소 Wave 레인 수", null)] public int WaveLaneCountMin; [ItemDescription("최대 Wave 레인 수", null)] public int WaveLaneCountMax; [ItemDescription("총 레인 수", null)] public int TotalLaneCount; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("확장된 컴퓨트 리소스 상태", null)] public bool ExpandedComputeResourceStates; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("64비트 정수 셰이더 연산", null)] public bool Int64ShaderOps; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS2 { [MarshalAs(UnmanagedType.Bool)] public bool DepthBoundsTestSupported; public D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER ProgrammableSamplePositionsTier; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS3 { [MarshalAs(UnmanagedType.Bool)] public bool CopyQueueTimestampQueriesSupported; [MarshalAs(UnmanagedType.Bool)] public bool CastingFullyTypedFormatSupported; public D3D12_COMMAND_LIST_SUPPORT_FLAGS WriteBufferImmediateSupportFlags; [ItemDescription ("뷰 인스턴싱 단계", null)] public D3D12_VIEW_INSTANCING_TIER ViewInstancingTier; [ItemDescription ("질량중심 지원", null)] public bool BarycentricsSupported; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS4 { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("MSAA 64KB 정렬된 텍스처 지원", null)] public bool MSAA64KBAlignedTextureSupported; [ItemDescription("공유 메모리 호환성 단계", null)] public D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("네이티브 16비트 셰이더 연산 지원", null)] public bool Native16BitShaderOpsSupported; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS5 { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("셰이더 리소스 뷰의 타일 리소스 단계 3", null)] public bool SRVOnlyTiledResourceTier3; public D3D12_RENDER_PASS_TIER RenderPassesTier; [ItemDescription("레이트레이싱 단계", null)] public D3D12_RAYTRACING_TIER RaytracingTier; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_D3D12_OPTIONS6 { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("추가적 셰이딩 단계 지원", null)] public bool AdditionalShadingRatesSupported; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("뷰포트 색인으로 지원하는 프리미티브별 셰이딩 비율", null)] public bool PerPrimitiveShadingRateSupportedWithViewportIndexing; [ItemDescription("가변 셰이딩 비율 단계", null)] public D3D12_VARIABLE_SHADING_RATE_TIER VariableShadingRateTier; [ItemDescription("셰이딩 비율 이미지 타일 크기", null)] public UINT ShadingRateImageTileSize; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("백그라운드 처리 지원", null)] public bool BackgroundProcessingSupported; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_ROOT_SIGNATURE { [ItemDescription("지원하는 가장 높은 버전", null)] public D3D_ROOT_SIGNATURE_VERSION HighestVersion; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_ARCHITECTURE { [ItemDescription("쿼리 할 어댑터 색인", null)] public int NodeIndex; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("타일 기반 렌더러", null)] public bool TileBasedRenderer; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("통합 메모리 아키텍처", "통합 메모리 아키텍처를 통해 CPU와 GPU 간 데이터를 복사하지 않고 이용할 수 있습니다.")] public bool UMA; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("캐시 일관된 통합 메모리 아키텍처", null)] public bool CacheCoherentUMA; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_ARCHITECTURE1 { [ItemDescription("쿼리 할 어댑터 색인", null)] public int NodeIndex; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("타일 기반 렌더러", null)] public bool TileBasedRenderer; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("통합 메모리 아키텍처", "통합 메모리 아키텍처를 통해 CPU와 GPU 간 데이터를 복사하지 않고 이용할 수 있습니다.")] public bool UMA; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("캐시 일관된 통합 메모리 아키텍처", null)] public bool CacheCoherentUMA; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("독립된 메모리 관리 장치", null)] public bool IsolatedMMU; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_SHADER_MODEL { [ItemDescription("지원하는 최대 셰이더 모델", null)] public D3D_SHADER_MODEL HighestShaderModel; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS { public DXGI_FORMAT Format; public int SampleCount; public D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS Flags; public int NumQualityLevels; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT { [ItemDescription("리소스 당 최대 GPU 가상 주소 비트 수", null)] public int MaxGPUVirtualAddressBitsPerResource; [ItemDescription("프로세스 당 최대 GPU 가상 주소 비트 수", null)] public int MaxGPUVirtualAddressBitsPerProcess; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_SHADER_CACHE { [ItemDescription("지원하는 셰이더 캐시 기능", null)] public D3D12_SHADER_CACHE_SUPPORT_FLAGS SupportFlags; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY { public D3D12_COMMAND_LIST_TYPE CommandListType; public int Priority; [MarshalAs(UnmanagedType.Bool)] public bool PriorityForTypeIsSupported; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_SERIALIZATION { [ItemDescription("쿼리 할 어댑터 색인", null)] public UINT NodeIndex; [ItemDescription("힙 직렬화 단계", null)] public D3D12_HEAP_SERIALIZATION_TIER HeapSerializationTier; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_CROSS_NODE { [ItemDescription("공유 단계", null)] public D3D12_CROSS_NODE_SHARING_TIER SharingTier; [MarshalAs(UnmanagedType.Bool)] [ItemDescription("아토믹 셰이더 명령", null)] public bool AtomicShaderInstructions; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT { [ItemDescription("쿼리 할 어댑터 색인", null)] public UINT NodeIndex; [ItemDescription("보호된 리소스 세션 지원", null)] public D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS Support; } [StructLayout(LayoutKind.Sequential)] public struct D3D12_FEATURE_DATA_EXISTING_HEAPS { [MarshalAs(UnmanagedType.Bool)] [ItemDescription("기존 방식 힙", null)] public bool Supported; } } }
29.547579
111
0.776033
[ "BSD-3-Clause" ]
daramkun/3dprobe
3dprobe/Bridge/Direct3D12.cs
18,895
C#
using UnityEngine; using System.Collections; public class JetpackVisuals : MonoBehaviour { [SerializeField] CharacterControllerBase m_Character = null; [SerializeField] Transform m_JetpackModel = null; [SerializeField] ParticleSystem m_JetpackParticles = null; [SerializeField] SpriteRenderer m_UIBarFill = null; [SerializeField] SpriteRenderer m_UIBarOutline = null; [SerializeField] Gradient m_UIGradient = null; [SerializeField] Transform m_UIBarScaler = null; [SerializeField] Transform m_UITransform = null; [SerializeField] Transform m_UIAnchor = null; JetpackModule m_JetpackModule; float m_LastFuelFullTime; bool m_FuelWasFull; void Start() { m_UIBarFill.color = Color.clear; m_UIBarOutline.color = Color.clear; m_LastFuelFullTime = Time.time - 5.0f; m_FuelWasFull = true; m_JetpackModule = m_Character.GetAbilityModuleManager().GetModuleWithName("Jetpack") as JetpackModule; UpdateVisualsEnabled(); } void Update () { UpdateVisualsEnabled(); UpdateVisuals(); } void UpdateVisualsEnabled() { if (m_JetpackModule == null || m_JetpackModule.IsLocked()) { EnableVisuals(false); } else { EnableVisuals(true); } } void UpdateVisuals() { ParticleSystem.EmissionModule emissionModule = m_JetpackParticles.emission; if (m_Character.GetAbilityModuleManager().GetCurrentModule() != null && m_Character.GetAbilityModuleManager().GetCurrentModule().GetName() == "Jetpack") { emissionModule.enabled = true; } else { emissionModule.enabled = false; } float currentFuelFactor = m_JetpackModule.GetFuelAs01Factor(); float alpha = 1.0f; if (currentFuelFactor == 1.0f) { if (!m_FuelWasFull) { m_LastFuelFullTime = Time.time; m_FuelWasFull = true; } alpha = 1.0f - Mathf.Clamp01((Time.time - m_LastFuelFullTime) * 2.0f); } else { m_FuelWasFull = false; } Color fillColor = m_UIGradient.Evaluate(currentFuelFactor); fillColor.a = alpha; m_UIBarFill.color = fillColor; Color outlineColor = Color.white; outlineColor.a = alpha; m_UIBarOutline.color = outlineColor; m_UIBarScaler.transform.localScale = new Vector3(currentFuelFactor, 1.0f, 1.0f); m_UITransform.position = m_UIAnchor.position; } void EnableVisuals(bool a_Enable) { m_UITransform.gameObject.SetActive(a_Enable); m_JetpackModel.gameObject.SetActive(a_Enable); } }
29.221053
160
0.633285
[ "MIT" ]
StefanZaufl/ggj2022-torn
Assets/CharacterEditorPackage/Code/Game/Equipment/JetpackVisuals.cs
2,778
C#
using System; using System.Collections.Generic; using System.Text; namespace MCSharp { class CmdPlayers : Command { // Constructor public CmdPlayers(CommandGroup g, GroupEnum group, string name) : base(g, group, name) { blnConsoleSupported = false; /* By default no console support*/ } // Command usage help public override void Help(Player p) { p.SendMessage("/players - Shows name and general rank of all players"); } // Code to run when used by a player public override void Use(Player p, string message) { UInt16 playerCount = 0; string strPlayers = ""; foreach (Player pl in Player.players) { if (!pl.hidden || p.Rank > pl.Rank) { strPlayers += pl.color + pl.name + "&e, "; playerCount++; } } if (strPlayers != "") { strPlayers = strPlayers.Remove(strPlayers.Length - 4); } else { strPlayers = "No players online"; } p.SendMessage("There are " + playerCount + " players online"); p.SendMessage("Playerlist: " + strPlayers); } } }
29.577778
162
0.500376
[ "MIT" ]
Hedwig7s/MCSharp-Betacraft
MCSharp/Commands/Information/CmdPlayers.cs
1,331
C#
using UnityEngine; using UnitySteer.Events ; [AddComponentMenu("UnitySteer/Steer/... for Arrive")] public class SteerForArrive : Steering { enum TargetCategory{ point=1,vehi=2}; [SerializeField] TargetCategory tc; [SerializeField] Vector3 _targetPoint = Vector3.zero; [SerializeField] Vehicle.Decelerate dece; [SerializeField] Vehicle _targetvehi; /// <summary> /// The target point. /// </summary> public Vector3 TargetPoint { get { return _targetPoint; } set { _targetPoint = value; ReportedArrival = false; } } public Vehicle TargetVehi { get { return _targetvehi; } set { _targetvehi = value; ReportedArrival = false; } } //相对速度 public Vehicle.Decelerate decel { get { return dece; } set { dece = value; } } public new void Start() { base.Start(); if (TargetPoint == Vector3.zero) { TargetPoint = transform.position; } } /// <summary> ///计算力 /// </returns> protected override Vector3 CalculateForce() { if (tc == TargetCategory.point) return Vehicle.GetArriveVector (TargetPoint, dece); else return Vehicle.GetArriveVector (TargetVehi.Position, dece); } }
15.513158
65
0.666667
[ "MIT" ]
xinghu0164/GroupAnimation
Assets/Code/Steer/SteerForArrive.cs
1,193
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generation date: 11/28/2021 8:55:09 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for BudgetTransactionWorkflowStatus in the schema. /// </summary> public enum BudgetTransactionWorkflowStatus { None = 0, NotSubmitted = 1, Submitted = 2, Approved = 3, Rejected = 4 } }
29.769231
81
0.5
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/BudgetTransactionWorkflowStatus.cs
776
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace SSRD.Audit.Data { public interface IAuditDbContext { DbSet<AuditEntity> Audit { get; set; } int SaveChanges(); Task<int> SaveChangesAsync(); } }
19.294118
46
0.698171
[ "MIT" ]
faizu-619/IdentityUI
src/SSRD.Audit/Data/IAuditDbContext.cs
330
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.LayoutRules { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using StyleCop.Analyzers.LayoutRules; using Xunit; using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier< StyleCop.Analyzers.LayoutRules.SA1502ElementMustNotBeOnASingleLine, StyleCop.Analyzers.LayoutRules.SA1502CodeFixProvider>; /// <summary> /// Unit tests for the type declaration part of <see cref="SA1502ElementMustNotBeOnASingleLine"/>. /// </summary> public partial class SA1502UnitTests { public static IEnumerable<object[]> TokensToTest { get { yield return new[] { "class" }; yield return new[] { "struct" }; } } /// <summary> /// Verifies that a correct empty type will pass without diagnostic. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestValidEmptyTypeAsync(string token) { var testCode = @"public ##PH## Foo { }"; await VerifyCSharpDiagnosticAsync(FormatTestCode(testCode, token), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that an empty type defined on a single line will trigger a diagnostic. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestEmptyTypeOnSingleLineAsync(string token) { var testCode = "public ##PH## Foo { }"; var expected = Diagnostic().WithLocation(1, 13 + token.Length); await VerifyCSharpDiagnosticAsync(FormatTestCode(testCode, token), expected, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that a type definition on a single line will trigger a diagnostic. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeOnSingleLineAsync(string token) { var testCode = "public ##PH## Foo { private int bar; }"; var expected = Diagnostic().WithLocation(1, 13 + token.Length); await VerifyCSharpDiagnosticAsync(FormatTestCode(testCode, token), expected, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that a type with its block defined on a single line will trigger a diagnostic. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeWithBlockOnSingleLineAsync(string token) { var testCode = @"public ##PH## Foo { private int bar; }"; var expected = Diagnostic().WithLocation(2, 1); await VerifyCSharpDiagnosticAsync(FormatTestCode(testCode, token), expected, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that a type definition with only the block start on the same line will pass without diagnostic. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeWithBlockStartOnSameLineAsync(string token) { var testCode = @"public ##PH## Foo { private int bar; }"; await VerifyCSharpDiagnosticAsync(FormatTestCode(testCode, token), DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that the code fix for an empty type element is working properly. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestEmptyTypeOnSingleLineCodeFixAsync(string token) { var testCode = "public ##PH## Foo { }"; var fixedTestCode = @"public ##PH## Foo { } "; var expected = Diagnostic().WithLocation(1, 13 + token.Length); await VerifyCSharpFixAsync(FormatTestCode(testCode, token), expected, FormatTestCode(fixedTestCode, token), CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that the code fix for a type with a statement is working properly. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeOnSingleLineCodeFixAsync(string token) { var testCode = "public ##PH## Foo { private int bar; }"; var fixedTestCode = @"public ##PH## Foo { private int bar; } "; var expected = Diagnostic().WithLocation(1, 13 + token.Length); await VerifyCSharpFixAsync(FormatTestCode(testCode, token), expected, FormatTestCode(fixedTestCode, token), CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that the code fix for a type with multiple statements is working properly. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeOnSingleLineWithMultipleStatementsCodeFixAsync(string token) { var testCode = "public ##PH## Foo { private int bar; private bool baz; }"; var fixedTestCode = @"public ##PH## Foo { private int bar; private bool baz; } "; var expected = Diagnostic().WithLocation(1, 13 + token.Length); await VerifyCSharpFixAsync(FormatTestCode(testCode, token), expected, FormatTestCode(fixedTestCode, token), CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that the code fix for a type with its block defined on a single line is working properly. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeWithBlockOnSingleLineCodeFixAsync(string token) { var testCode = @"public ##PH## Foo { private int bar; }"; var fixedTestCode = @"public ##PH## Foo { private int bar; } "; var expected = Diagnostic().WithLocation(2, 1); await VerifyCSharpFixAsync(FormatTestCode(testCode, token), expected, FormatTestCode(fixedTestCode, token), CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verifies that the code fix for a type with lots of trivia is working properly. /// </summary> /// <param name="token">The type of element to test.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [MemberData(nameof(TokensToTest))] public async Task TestTypeWithLotsOfTriviaCodeFixAsync(string token) { var testCode = @"public ##PH## Foo /* TR1 */ { /* TR2 */ private int bar; /* TR3 */ private int baz; /* TR4 */ } /* TR5 */"; var fixedTestCode = @"public ##PH## Foo /* TR1 */ { /* TR2 */ private int bar; /* TR3 */ private int baz; /* TR4 */ } /* TR5 */ "; var expected = Diagnostic().WithLocation(1, 23 + token.Length); await VerifyCSharpFixAsync(FormatTestCode(testCode, token), expected, FormatTestCode(fixedTestCode, token), CancellationToken.None).ConfigureAwait(false); } } }
43.095694
166
0.630843
[ "Apache-2.0" ]
Andreyul/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1502/SA1502UnitTests.TypeDeclarations.cs
9,009
C#
using System; using System.Collections.Generic; using System.Linq; using QuickGraph; namespace GraphX.Logic.Algorithms { internal class GraphHideHelper<TVertex, TEdge> : ISoftMutableGraph<TVertex, TEdge> where TEdge : IEdge<TVertex> { private readonly IMutableBidirectionalGraph<TVertex, TEdge> _graph; #region Helper Types protected class HiddenCollection { public List<TVertex> hiddenVertices = new List<TVertex>(); public List<TEdge> hiddenEdges = new List<TEdge>(); } #endregion #region Properties, fields, events private readonly List<TVertex> _hiddenVertices = new List<TVertex>(); private readonly List<TEdge> _hiddenEdges = new List<TEdge>(); private readonly IDictionary<string, HiddenCollection> _hiddenCollections = new Dictionary<string, HiddenCollection>(); private readonly IDictionary<TVertex, List<TEdge>> _hiddenEdgesOf = new Dictionary<TVertex, List<TEdge>>(); public event EdgeAction<TVertex, TEdge> EdgeHidden; public event EdgeAction<TVertex, TEdge> EdgeUnhidden; public event VertexAction<TVertex> VertexHidden; public event VertexAction<TVertex> VertexUnhidden; #endregion public GraphHideHelper( IMutableBidirectionalGraph<TVertex, TEdge> managedGraph ) { _graph = managedGraph; } #region Event handlers, helper methods /// <summary> /// Returns every edge connected with the vertex <code>v</code>. /// </summary> /// <param name="v">The vertex.</param> /// <returns>Edges, adjacent to the vertex <code>v</code>.</returns> protected IEnumerable<TEdge> EdgesFor( TVertex v ) { return _graph.InEdges( v ).Concat( _graph.OutEdges( v ) ); } protected HiddenCollection GetHiddenCollection( string tag ) { HiddenCollection h; if ( !_hiddenCollections.TryGetValue( tag, out h ) ) { h = new HiddenCollection(); _hiddenCollections[tag] = h; } return h; } protected void OnEdgeHidden( TEdge e ) { if ( EdgeHidden != null ) EdgeHidden( e ); } protected void OnEdgeUnhidden( TEdge e ) { if ( EdgeUnhidden != null ) EdgeUnhidden( e ); } protected void OnVertexHidden( TVertex v ) { if ( VertexHidden != null ) VertexHidden( v ); } protected void OnVertexUnhidden( TVertex v ) { if ( VertexUnhidden != null ) VertexUnhidden( v ); } #endregion #region ISoftMutableGraph<TVertex,TEdge> Members public IEnumerable<TVertex> HiddenVertices { get { return _hiddenVertices; } } public IEnumerable<TEdge> HiddenEdges { get { return _hiddenEdges; } } /// <summary> /// Hides the vertex <code>v</code>. /// </summary> /// <param name="v">The vertex to hide.</param> public bool HideVertex( TVertex v ) { if ( _graph.ContainsVertex( v ) && !_hiddenVertices.Contains( v ) ) { HideEdges( EdgesFor( v ) ); //hide the vertex _graph.RemoveVertex( v ); _hiddenVertices.Add( v ); OnVertexHidden( v ); return true; } return false; } /// <summary> /// Hides a lot of vertices. /// </summary> /// <param name="vertices">The vertices to hide.</param> public void HideVertices( IEnumerable<TVertex> vertices ) { var verticesToHide = new List<TVertex>( vertices ); foreach ( TVertex v in verticesToHide ) { HideVertex( v ); } } public bool HideVertex( TVertex v, string tag ) { HiddenCollection h = GetHiddenCollection( tag ); var eeh = new EdgeAction<TVertex, TEdge>( e => h.hiddenEdges.Add( e ) ); var veh = new VertexAction<TVertex>( vertex => h.hiddenVertices.Add( vertex ) ); EdgeHidden += eeh; VertexHidden += veh; bool ret = HideVertex( v ); EdgeHidden -= eeh; VertexHidden -= veh; return ret; } public void HideVertices( IEnumerable<TVertex> vertices, string tag ) { foreach ( var v in vertices ) { HideVertex( v, tag ); } } public void HideVerticesIf( Func<TVertex, bool> predicate, string tag ) { var verticesToHide = _graph.Vertices.Where(predicate).ToList(); HideVertices( verticesToHide, tag ); } public bool IsHiddenVertex( TVertex v ) { return ( !_graph.ContainsVertex( v ) && _hiddenVertices.Contains( v ) ); } public bool UnhideVertex( TVertex v ) { //if v not hidden, it's an error if ( !IsHiddenVertex( v ) ) return false; //unhide the vertex _graph.AddVertex( v ); _hiddenVertices.Remove( v ); OnVertexUnhidden( v ); return true; } public void UnhideVertexAndEdges( TVertex v ) { UnhideVertex( v ); List<TEdge> hiddenEdgesList; _hiddenEdgesOf.TryGetValue( v, out hiddenEdgesList ); if ( hiddenEdgesList != null ) UnhideEdges( hiddenEdgesList ); } public bool HideEdge( TEdge e ) { if ( _graph.ContainsEdge( e ) && !_hiddenEdges.Contains( e ) ) { _graph.RemoveEdge( e ); _hiddenEdges.Add( e ); GetHiddenEdgeListOf( e.Source ).Add( e ); GetHiddenEdgeListOf( e.Target ).Add( e ); OnEdgeHidden( e ); return true; } return false; } private List<TEdge> GetHiddenEdgeListOf( TVertex v ) { List<TEdge> hiddenEdgeList; _hiddenEdgesOf.TryGetValue( v, out hiddenEdgeList ); if ( hiddenEdgeList == null ) { hiddenEdgeList = new List<TEdge>(); _hiddenEdgesOf[v] = hiddenEdgeList; } return hiddenEdgeList; } public IEnumerable<TEdge> HiddenEdgesOf( TVertex v ) { return GetHiddenEdgeListOf( v ); } public int HiddenEdgeCountOf( TVertex v ) { return GetHiddenEdgeListOf( v ).Count; } public bool HideEdge( TEdge e, string tag ) { var h = GetHiddenCollection( tag ); var eeh = new EdgeAction<TVertex, TEdge>( edge => h.hiddenEdges.Add( edge ) ); EdgeHidden += eeh; bool ret = HideEdge( e ); EdgeHidden -= eeh; return ret; } public void HideEdges( IEnumerable<TEdge> edges ) { var edgesToHide = new List<TEdge>( edges ); foreach ( var e in edgesToHide ) { HideEdge( e ); } } public void HideEdges( IEnumerable<TEdge> edges, string tag ) { var edgesToHide = new List<TEdge>( edges ); foreach ( var e in edgesToHide ) { HideEdge( e, tag ); } } public void HideEdgesIf( Func<TEdge, bool> predicate, string tag ) { var edgesToHide = _graph.Edges.Where(predicate).ToList(); HideEdges( edgesToHide, tag ); } public bool IsHiddenEdge( TEdge e ) { return ( !_graph.ContainsEdge( e ) && _hiddenEdges.Contains( e ) ); } public bool UnhideEdge( TEdge e ) { if ( IsHiddenVertex( e.Source ) || IsHiddenVertex( e.Target ) || !IsHiddenEdge( e ) ) return false; //unhide the edge _graph.AddEdge( e ); _hiddenEdges.Remove( e ); GetHiddenEdgeListOf( e.Source ).Remove( e ); GetHiddenEdgeListOf( e.Target ).Remove( e ); OnEdgeUnhidden( e ); return true; } public void UnhideEdgesIf( Func<TEdge, bool> predicate ) { var edgesToUnhide = _hiddenEdges.Where(predicate).ToList(); UnhideEdges( edgesToUnhide ); } public void UnhideEdges( IEnumerable<TEdge> edges ) { var edgesToUnhide = new List<TEdge>( edges ); foreach ( var e in edgesToUnhide ) { UnhideEdge( e ); } } public bool Unhide( string tag ) { HiddenCollection h = GetHiddenCollection( tag ); foreach ( TVertex v in h.hiddenVertices ) { UnhideVertex( v ); } foreach ( TEdge e in h.hiddenEdges ) { UnhideEdge( e ); } return _hiddenCollections.Remove( tag ); } public bool UnhideAll() { while ( _hiddenVertices.Count > 0 ) { UnhideVertex( _hiddenVertices[0] ); } while ( _hiddenEdges.Count > 0 ) { UnhideEdge( _hiddenEdges[0] ); } return true; } public int HiddenVertexCount { get { return _hiddenVertices.Count; } } public int HiddenEdgeCount { get { return _hiddenEdges.Count; } } #endregion #region IBidirectionalGraph<TVertex,TEdge> Members public int Degree( TVertex v ) { throw new NotImplementedException(); } public int InDegree( TVertex v ) { throw new NotImplementedException(); } public TEdge InEdge( TVertex v, int index ) { throw new NotImplementedException(); } public IEnumerable<TEdge> InEdges( TVertex v ) { throw new NotImplementedException(); } public bool IsInEdgesEmpty( TVertex v ) { throw new NotImplementedException(); } #endregion #region IIncidenceGraph<TVertex,TEdge> Members public bool ContainsEdge( TVertex source, TVertex target ) { throw new NotImplementedException(); } public bool TryGetEdge( TVertex source, TVertex target, out TEdge edge ) { throw new NotImplementedException(); } public bool TryGetEdges( TVertex source, TVertex target, out IEnumerable<TEdge> edges ) { throw new NotImplementedException(); } #endregion #region IImplicitGraph<TVertex,TEdge> Members public bool IsOutEdgesEmpty( TVertex v ) { throw new NotImplementedException(); } public int OutDegree( TVertex v ) { throw new NotImplementedException(); } public TEdge OutEdge( TVertex v, int index ) { throw new NotImplementedException(); } public IEnumerable<TEdge> OutEdges( TVertex v ) { throw new NotImplementedException(); } #endregion #region IGraph<TVertex,TEdge> Members public bool AllowParallelEdges { get { throw new NotImplementedException(); } } public bool IsDirected { get { throw new NotImplementedException(); } } #endregion #region IVertexSet<TVertex,TEdge> Members public bool ContainsVertex( TVertex vertex ) { throw new NotImplementedException(); } public bool IsVerticesEmpty { get { throw new NotImplementedException(); } } public int VertexCount { get { throw new NotImplementedException(); } } public IEnumerable<TVertex> Vertices { get { throw new NotImplementedException(); } } #endregion #region IEdgeListGraph<TVertex,TEdge> Members public bool ContainsEdge( TEdge edge ) { throw new NotImplementedException(); } public int EdgeCount { get { throw new NotImplementedException(); } } public IEnumerable<TEdge> Edges { get { throw new NotImplementedException(); } } public bool IsEdgesEmpty { get { throw new NotImplementedException(); } } #endregion public bool TryGetInEdges( TVertex v, out IEnumerable<TEdge> edges ) { throw new NotImplementedException(); } public bool TryGetOutEdges( TVertex v, out IEnumerable<TEdge> edges ) { throw new NotImplementedException(); } } }
21.995807
121
0.670034
[ "Apache-2.0" ]
Devangsinh/GraphX
GraphX.Standard.Logic/Algorithms/GraphHideHelper.cs
10,494
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cme.V20191029.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ImportMaterialRequest : AbstractModel { /// <summary> /// 平台名称,指定访问的平台。 /// </summary> [JsonProperty("Platform")] public string Platform{ get; set; } /// <summary> /// 媒体归属者,团队或个人。 /// </summary> [JsonProperty("Owner")] public Entity Owner{ get; set; } /// <summary> /// 媒体名称,不能超过30个字符。 /// </summary> [JsonProperty("Name")] public string Name{ get; set; } /// <summary> /// 导入媒资类型,取值: /// <li>VOD:云点播文件;</li> /// <li>EXTERNAL:媒资绑定。</li> /// /// 注意:如果不填默认为云点播文件,如果媒体存储在非腾讯云点播中,都需要使用媒资绑定。 /// </summary> [JsonProperty("SourceType")] public string SourceType{ get; set; } /// <summary> /// 云点播媒资 FileId,仅当 SourceType 为 VOD 时有效。 /// </summary> [JsonProperty("VodFileId")] public string VodFileId{ get; set; } /// <summary> /// 原始媒资文件信息,当 SourceType 取值 EXTERNAL 的时候必填。 /// </summary> [JsonProperty("ExternalMediaInfo")] public ExternalMediaInfo ExternalMediaInfo{ get; set; } /// <summary> /// 媒体分类路径,形如:"/a/b",层级数不能超过10,每个层级长度不能超过15字符。若不填则默认为根路径。 /// </summary> [JsonProperty("ClassPath")] public string ClassPath{ get; set; } /// <summary> /// 媒体预处理任务模板 ID。取值: /// <li>10:进行编辑预处理。</li> /// </summary> [JsonProperty("PreProcessDefinition")] public long? PreProcessDefinition{ get; set; } /// <summary> /// 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 /// </summary> [JsonProperty("Operator")] public string Operator{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Platform", this.Platform); this.SetParamObj(map, prefix + "Owner.", this.Owner); this.SetParamSimple(map, prefix + "Name", this.Name); this.SetParamSimple(map, prefix + "SourceType", this.SourceType); this.SetParamSimple(map, prefix + "VodFileId", this.VodFileId); this.SetParamObj(map, prefix + "ExternalMediaInfo.", this.ExternalMediaInfo); this.SetParamSimple(map, prefix + "ClassPath", this.ClassPath); this.SetParamSimple(map, prefix + "PreProcessDefinition", this.PreProcessDefinition); this.SetParamSimple(map, prefix + "Operator", this.Operator); } } }
32.847619
97
0.590316
[ "Apache-2.0" ]
kimii/tencentcloud-sdk-dotnet
TencentCloud/Cme/V20191029/Models/ImportMaterialRequest.cs
3,895
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace NewsRssWeb.Entity { public class TuningGenerator { [Key] [ForeignKey("Generator")] public int Id { get; set; } public string UriString { get; set; } public string FormatTime { get; set; } public DateTime DateWrite { get; set; } = DateTime.MinValue; public string TitleLastPost { get; set; } public string LinkLastPost { get; set; } //public int GeneratorId { get; set; } public Generator Generator { get; set; } } }
29.25
68
0.65812
[ "MIT" ]
PiterPoker/NewsRssWeb
NewsRssWeb/Entity/TuningGenerator.cs
704
C#
using System; using System.Threading.Channels; namespace Foreach { class Program { static void Main(string[] args) { string[] vect = new string[] { "Maria", "Alex", "Bob" }; // Método com for para percorrer o vetor for (int i = 0; i < vect.Length; i++) { Console.WriteLine(vect[i]); } Console.WriteLine("-------------------"); // Método com o foreach para percorrer o vetor foreach (string obj in vect) { Console.WriteLine(obj); } } } }
25.791667
68
0.463651
[ "MIT" ]
midnightbr/CSharp
ws-rider/Foreach/Foreach/Program.cs
623
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace WebAddressbookTests { [TestFixture] public class LoginTests : AuthTestBase { [Test] public void LoginWithValidCredentials() { // prepare app.Auth.Logout(); // action AccountData account = new AccountData("admin", "secret"); app.Auth.Login(account); // verification Assert.IsTrue(app.Auth.IsLoggedIn()); } [Test] public void LoginWithInvalidCredentials() { // prepare app.Auth.Logout(); // action AccountData account = new AccountData("admin", "123456"); app.Auth.Login(account); // verification Assert.IsFalse(app.Auth.IsLoggedIn()); } } }
21.976744
69
0.555556
[ "Apache-2.0" ]
kursvelox/csharp_kurs
addressbook-web-tests/addressbook-web-tests/tests/LoginTests.cs
947
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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SemanticModelExtensions { public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, ArgumentListSyntax argumentList, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames( argumentList.Arguments, reservedNames: null, cancellationToken: cancellationToken); } public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames( argumentList.Arguments, reservedNames: null, cancellationToken: cancellationToken); } public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameColon != null)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a, cancellationToken))).ToImmutableArray(); return GenerateNames(reservedNames, isFixed, parameterNames); } public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameColon != null)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a, cancellationToken))).ToImmutableArray(); return GenerateNames(reservedNames, isFixed, parameterNames, parameterNamingRule); } private static ImmutableArray<ParameterName> GenerateNames(IList<string> reservedNames, ImmutableArray<bool> isFixed, ImmutableArray<string> parameterNames) => NameGenerator.EnsureUniqueness(parameterNames, isFixed) .Select((name, index) => new ParameterName(name, isFixed[index])) .Skip(reservedNames.Count).ToImmutableArray(); private static ImmutableArray<ParameterName> GenerateNames(IList<string> reservedNames, ImmutableArray<bool> isFixed, ImmutableArray<string> parameterNames, NamingRule parameterNamingRule) => NameGenerator.EnsureUniqueness(parameterNames, isFixed) .Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule)) .Skip(reservedNames.Count).ToImmutableArray(); public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameEquals != null)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a, cancellationToken))).ToImmutableArray(); return GenerateNames(reservedNames, isFixed, parameterNames); } public static ImmutableArray<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameEquals != null)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a, cancellationToken))).ToImmutableArray(); return GenerateNames(reservedNames, isFixed, parameterNames, parameterNamingRule); } } }
47.862903
196
0.691154
[ "MIT" ]
BertanAygun/roslyn
src/Workspaces/CSharp/Portable/Extensions/SemanticModelExtensions.cs
5,937
C#
using System; using System.Drawing; using System.IO; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using A = DocumentFormat.OpenXml.Drawing; using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; using PIC = DocumentFormat.OpenXml.Drawing.Pictures; namespace Citolab.QConstruction.Logic.HelperClasses { public static class OpenXmlHelper { public static void AddText(this Body body, string text) { var para = body.AppendChild(new Paragraph()); var run = para.AppendChild(new Run()); run.AppendChild(new Text(text)); } public static void InsertAPicture(this MainDocumentPart mainPart, byte[] image, string filename) { var imagePart = mainPart.AddImagePart(GetImagePartTypeByExtension(Path.GetExtension(filename))); using (var stream = new MemoryStream(image)) { imagePart.FeedData(stream); } AddImageToBody(mainPart, mainPart.GetIdOfPart(imagePart), filename, image); } private static ImagePartType GetImagePartTypeByExtension(string extension) { switch (extension) { case ".jpg": case ".jpeg": return ImagePartType.Jpeg; case ".bmp": return ImagePartType.Bmp; case ".png": return ImagePartType.Png; default: return ImagePartType.Jpeg; } } private static void AddImageToBody(MainDocumentPart mainPart, string relationshipId, string fileName, byte[] image) { var img = Image.FromStream(new MemoryStream(image)); var iWidth = (int)Math.Round((decimal)img.Width * 9525); var iHeight = (int)Math.Round((decimal)img.Height * 9525); // Define the reference of the image. var element = new Drawing( new DW.Inline( new DW.Extent() { Cx = iWidth, Cy = iHeight }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = Path.GetFileNameWithoutExtension(fileName) }, new DW.NonVisualGraphicFrameDrawingProperties( new A.GraphicFrameLocks() { NoChangeAspect = true }), new A.Graphic( new A.GraphicData( new PIC.Picture( new PIC.NonVisualPictureProperties( new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = Path.GetFileName(fileName) }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = relationshipId, CompressionState = A.BlipCompressionValues.Print }, new A.Stretch( new A.FillRectangle())), new PIC.ShapeProperties( new A.Transform2D( new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = iWidth, Cy = iHeight }), new A.PresetGeometry( new A.AdjustValueList() ) { Preset = A.ShapeTypeValues.Rectangle })) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" }); // Append the reference to body, the element should be in a Run. mainPart.Document.Body.AppendChild(new Paragraph(new Run(element))); } } }
45.848
123
0.401326
[ "MIT" ]
ST-Cito/Q-Construction
backend/Citolab.QConstruction.Logic/HelperClasses/OpenXmlHelper.cs
5,733
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Application.DTOs.Account { public class AuthenticationResponse { public string Id { get; set; } public string UserName { get; set; } public string Email { get; set; } public List<string> Roles { get; set; } public bool IsVerified { get; set; } public string JWToken { get; set; } [JsonIgnore] public string RefreshToken { get; set; } } }
27.666667
48
0.626506
[ "MIT" ]
chenzuo/CleanArchitecture.WebApi
Application/DTOs/Account/AuthenticationResponse.cs
500
C#
using System.Linq.Expressions; namespace RepoDb.Extensions { /// <summary> /// Contains the extension methods for <see cref="MemberBinding"/> object. /// </summary> internal static class MemberBindingExtension { /// <summary> /// Gets a value from the current instance of <see cref="MemberBinding"/> object. /// </summary> /// <param name="member">The instance of <see cref="MemberBinding"/> object where the value is to be extracted.</param> /// <returns>The extracted value from <see cref="MemberBinding"/> object.</returns> public static object GetValue(this MemberBinding member) { if (member is MemberAssignment memberAssignment) { return memberAssignment.Expression.GetValue(); } return null; } #region Identification and Conversion /// <summary> /// Identify whether the instance of <see cref="MemberBinding"/> is a <see cref="MemberAssignment"/> object. /// </summary> /// <param name="member">The instance of <see cref="MemberBinding"/> object to be identified.</param> /// <returns>Returns true if the expression is a <see cref="MemberAssignment"/>.</returns> public static bool IsMemberAssignment(this MemberBinding member) => member is MemberAssignment; /// <summary> /// Converts the <see cref="MemberBinding"/> object into <see cref="MemberAssignment"/> object. /// </summary> /// <param name="member">The instance of <see cref="MemberBinding"/> object to be converted.</param> /// <returns>A converted instance of <see cref="MemberAssignment"/> object.</returns> public static MemberAssignment ToMemberAssignment(this MemberBinding member) => (MemberAssignment)member; #endregion } }
42.066667
127
0.62916
[ "Apache-2.0" ]
RepoDb/RepoDb
RepoDb.Core/RepoDb/Extensions/MemberBindingExtension.cs
1,895
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Catch.Difficulty.Preprocessing { public class CatchDifficultyHitObject : DifficultyHitObject { private const float normalized_hitobject_radius = 41.0f; public new PalpableCatchHitObject BaseObject => (PalpableCatchHitObject)base.BaseObject; public new PalpableCatchHitObject LastObject => (PalpableCatchHitObject)base.LastObject; public readonly float NormalizedPosition; public readonly float LastNormalizedPosition; /// <summary> /// Milliseconds elapsed since the start time of the previous <see cref="CatchDifficultyHitObject"/>, with a minimum of 40ms. /// </summary> public readonly double StrainTime; public CatchDifficultyHitObject(HitObject hitObject, HitObject lastObject, double clockRate, float halfCatcherWidth) : base(hitObject, lastObject, clockRate) { // We will scale everything by this factor, so we can assume a uniform CircleSize among beatmaps. var scalingFactor = normalized_hitobject_radius / halfCatcherWidth; NormalizedPosition = BaseObject.EffectiveX * scalingFactor; LastNormalizedPosition = LastObject.EffectiveX * scalingFactor; // Every strain interval is hard capped at the equivalent of 375 BPM streaming speed as a safety measure StrainTime = Math.Max(40, DeltaTime); } } }
43.975
134
0.705514
[ "MIT" ]
RocketMaDev/osu
osu.Game.Rulesets.Catch/Difficulty/Preprocessing/CatchDifficultyHitObject.cs
1,720
C#
// // ProjectItemDefinitionElement.cs // // Author: // Leszek Ciesielski (skolima@gmail.com) // // (C) 2011 Leszek Ciesielski // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Microsoft.Build.Internal; namespace Microsoft.Build.Construction { [System.Diagnostics.DebuggerDisplayAttribute ("{ItemType} #Metadata={Count} Condition={Condition}")] public class ProjectItemDefinitionElement : ProjectElementContainer { internal ProjectItemDefinitionElement (string itemType, ProjectRootElement containingProject) { ItemType = itemType; ContainingProject = containingProject; } public string ItemType { get; private set; } public ICollection<ProjectMetadataElement> Metadata { get { return new CollectionFromEnumerable<ProjectMetadataElement> ( new FilteredEnumerable<ProjectMetadataElement> (Children)); } } public ProjectMetadataElement AddMetadata (string name, string unevaluatedValue) { var metadata = ContainingProject.CreateMetadataElement (name); metadata.Value = unevaluatedValue; AppendChild (metadata); return metadata; } internal override string XmlName { get { return ItemType; } } internal override ProjectElement LoadChildElement (XmlReader reader) { return AddMetadata (reader.LocalName, null); } } }
43.090909
109
0.646976
[ "Apache-2.0" ]
121468615/mono
mcs/class/Microsoft.Build/Microsoft.Build.Construction/ProjectItemDefinitionElement.cs
2,846
C#
using System; using umbraco.interfaces; using umbraco.BasePages; using Umbraco.Core; using Umbraco.Core.CodeAnnotations; namespace umbraco.BusinessLogic.Actions { /// <summary> /// This action is used as a security constraint that grants a user the ability to view nodes in a tree /// that has permissions applied to it. /// </summary> /// <remarks> /// This action should not be invoked. It is used as the minimum required permission to view nodes in the content tree. By /// granting a user this permission, the user is able to see the node in the tree but not edit the document. This may be used by other trees /// that support permissions in the future. /// </remarks> [ActionMetadata(Constants.Conventions.PermissionCategories.ContentCategory)] public class ActionBrowse : IAction { //create singleton private static readonly ActionBrowse instance = new ActionBrowse(); private ActionBrowse() { } public static ActionBrowse Instance { get { return instance; } } #region IAction Members public char Letter { get { return 'F'; } } public bool ShowInNotifier { get { return false; } } public bool CanBePermissionAssigned { get { return true; } } public string Icon { get { return ""; } } public string Alias { get { return "browse"; } } public string JsFunctionName { get { return ""; } } public string JsSource { get { return ""; } } #endregion } }
25.342857
145
0.567644
[ "MIT" ]
Abhith/Umbraco-CMS
src/umbraco.cms/Actions/ActionBrowse.cs
1,774
C#
//Write a program that finds how many times a substring is contained in a given text (perform case insensitive search). // Example: The target substring is "in". The text is as follows: //We are living in an yellow submarine. We don't have anything else. Inside the submarine is very tight. //So we are drinking all the day. We will move out of it in 5 days. //Answer - 9 using System; using System.Linq; class HowManyTimesASubstring { static void Main() { //string input = Console.ReadLine(); ORIGINAL string input = "We are living in an yellow submarine. We don't have anything else. Inside the submarine is very tight.So we are drinking all the day. We will move out of it in 5 days."; //for easier testing input = input.ToLower(); int answer = 0; int indexer = input.IndexOf("in",0); while (indexer!=-1) { answer++; indexer = input.IndexOf("in", indexer + 1); } Console.WriteLine(answer); } }
31.9375
193
0.642857
[ "MIT" ]
dzhenko/TelerikAcademy
CSharp Part2/C2-8-StringsTextProcessing-Homework/04. HowManyTimesASubstring/HowManyTimesASubstring.cs
1,024
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// CallbackConversationNotificationDialerPreview /// </summary> [DataContract] public partial class CallbackConversationNotificationDialerPreview : IEquatable<CallbackConversationNotificationDialerPreview> { /// <summary> /// Initializes a new instance of the <see cref="CallbackConversationNotificationDialerPreview" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="ContactId">ContactId.</param> /// <param name="ContactListId">ContactListId.</param> /// <param name="CampaignId">CampaignId.</param> /// <param name="PhoneNumberColumns">PhoneNumberColumns.</param> /// <param name="AdditionalProperties">AdditionalProperties.</param> public CallbackConversationNotificationDialerPreview(string Id = null, string ContactId = null, string ContactListId = null, string CampaignId = null, List<CampaignNotificationPhoneColumns> PhoneNumberColumns = null, Object AdditionalProperties = null) { this.Id = Id; this.ContactId = ContactId; this.ContactListId = ContactListId; this.CampaignId = CampaignId; this.PhoneNumberColumns = PhoneNumberColumns; this.AdditionalProperties = AdditionalProperties; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets ContactId /// </summary> [DataMember(Name="contactId", EmitDefaultValue=false)] public string ContactId { get; set; } /// <summary> /// Gets or Sets ContactListId /// </summary> [DataMember(Name="contactListId", EmitDefaultValue=false)] public string ContactListId { get; set; } /// <summary> /// Gets or Sets CampaignId /// </summary> [DataMember(Name="campaignId", EmitDefaultValue=false)] public string CampaignId { get; set; } /// <summary> /// Gets or Sets PhoneNumberColumns /// </summary> [DataMember(Name="phoneNumberColumns", EmitDefaultValue=false)] public List<CampaignNotificationPhoneColumns> PhoneNumberColumns { get; set; } /// <summary> /// Gets or Sets AdditionalProperties /// </summary> [DataMember(Name="additionalProperties", EmitDefaultValue=false)] public Object AdditionalProperties { 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 CallbackConversationNotificationDialerPreview {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ContactId: ").Append(ContactId).Append("\n"); sb.Append(" ContactListId: ").Append(ContactListId).Append("\n"); sb.Append(" CampaignId: ").Append(CampaignId).Append("\n"); sb.Append(" PhoneNumberColumns: ").Append(PhoneNumberColumns).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).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 CallbackConversationNotificationDialerPreview); } /// <summary> /// Returns true if CallbackConversationNotificationDialerPreview instances are equal /// </summary> /// <param name="other">Instance of CallbackConversationNotificationDialerPreview to be compared</param> /// <returns>Boolean</returns> public bool Equals(CallbackConversationNotificationDialerPreview other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ContactId == other.ContactId || this.ContactId != null && this.ContactId.Equals(other.ContactId) ) && ( this.ContactListId == other.ContactListId || this.ContactListId != null && this.ContactListId.Equals(other.ContactListId) ) && ( this.CampaignId == other.CampaignId || this.CampaignId != null && this.CampaignId.Equals(other.CampaignId) ) && ( this.PhoneNumberColumns == other.PhoneNumberColumns || this.PhoneNumberColumns != null && this.PhoneNumberColumns.SequenceEqual(other.PhoneNumberColumns) ) && ( this.AdditionalProperties == other.AdditionalProperties || this.AdditionalProperties != null && this.AdditionalProperties.Equals(other.AdditionalProperties) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.ContactId != null) hash = hash * 59 + this.ContactId.GetHashCode(); if (this.ContactListId != null) hash = hash * 59 + this.ContactListId.GetHashCode(); if (this.CampaignId != null) hash = hash * 59 + this.CampaignId.GetHashCode(); if (this.PhoneNumberColumns != null) hash = hash * 59 + this.PhoneNumberColumns.GetHashCode(); if (this.AdditionalProperties != null) hash = hash * 59 + this.AdditionalProperties.GetHashCode(); return hash; } } } }
27.229412
260
0.459927
[ "MIT" ]
maxwang/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/CallbackConversationNotificationDialerPreview.cs
9,258
C#
using System.ComponentModel.DataAnnotations; using static OnlineStore.Models.Common.ModelConstants; namespace OnlineStore.Common.ViewModels.Product { public class ProductCreateViewModel { public ProductCreateViewModel(string categoryId) { this.CategoryId = categoryId; } public ProductCreateViewModel() { } [Required] [MinLength(ProductNameMinLength)] public string Name { get; set; } [Required] [MinLength(ProductDescriptionMinLength)] public string Description { get; set; } [Required] [Range(typeof(decimal), ProductPriceMinValueAsString, ProductPriceMaxValueAsString)] public decimal Price { get; set; } [Required] [Range(0, int.MaxValue)] public int Availability { get; set; } [Required] public string CategoryId { get; set; } } }
25.081081
92
0.631466
[ "MIT" ]
msotiroff/Online-Store
src/OnlineStore.Common/ViewModels/Product/ProductCreateViewModel.cs
930
C#
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS"basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The CPR Broker concept was initally developed by * Gentofte Kommune / Municipality of Gentofte, Denmark. * Contributor(s): * Steen Deth * * * The Initial Code for CPR Broker and related components is made in * cooperation between Magenta, Gentofte Kommune and IT- og Telestyrelsen / * Danish National IT and Telecom Agency * * Contributor(s): * Beemen Beshara * * The code is currently governed by IT- og Telestyrelsen / Danish National * IT and Telecom Agency * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CprBroker.Schemas.Part { [AttributeUsage(AttributeTargets.Class)] public class CannotCloseOpenEndIntervalsAttribute : Attribute { public bool Value { get; set; } public CannotCloseOpenEndIntervalsAttribute() : this(true) { } public CannotCloseOpenEndIntervalsAttribute(bool value) { Value = value; } public static bool GetValue(Type t) { var attr = t.GetCustomAttributes(typeof(CannotCloseOpenEndIntervalsAttribute), true).FirstOrDefault() as CannotCloseOpenEndIntervalsAttribute; return attr != null && attr.Value; } } }
36.135135
154
0.707928
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
OS2CPRbroker/CPRbroker
PART/Source/Core/Schemas/Intervals/CannotCloseOpenEndIntervalsAttribute.cs
2,676
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Settings for <see cref="EnvironmentsClient"/> instances.</summary> public sealed partial class EnvironmentsSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="EnvironmentsSettings"/>.</summary> /// <returns>A new instance of the default <see cref="EnvironmentsSettings"/>.</returns> public static EnvironmentsSettings GetDefault() => new EnvironmentsSettings(); /// <summary>Constructs a new <see cref="EnvironmentsSettings"/> object with default settings.</summary> public EnvironmentsSettings() { } private EnvironmentsSettings(EnvironmentsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListEnvironmentsSettings = existing.ListEnvironmentsSettings; GetEnvironmentSettings = existing.GetEnvironmentSettings; CreateEnvironmentSettings = existing.CreateEnvironmentSettings; CreateEnvironmentOperationsSettings = existing.CreateEnvironmentOperationsSettings.Clone(); UpdateEnvironmentSettings = existing.UpdateEnvironmentSettings; UpdateEnvironmentOperationsSettings = existing.UpdateEnvironmentOperationsSettings.Clone(); DeleteEnvironmentSettings = existing.DeleteEnvironmentSettings; LookupEnvironmentHistorySettings = existing.LookupEnvironmentHistorySettings; OnCopy(existing); } partial void OnCopy(EnvironmentsSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.ListEnvironments</c> and <c>EnvironmentsClient.ListEnvironmentsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListEnvironmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.GetEnvironment</c> and <c>EnvironmentsClient.GetEnvironmentAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.CreateEnvironment</c> and <c>EnvironmentsClient.CreateEnvironmentAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary> /// Long Running Operation settings for calls to <c>EnvironmentsClient.CreateEnvironment</c> and /// <c>EnvironmentsClient.CreateEnvironmentAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings CreateEnvironmentOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.UpdateEnvironment</c> and <c>EnvironmentsClient.UpdateEnvironmentAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings UpdateEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary> /// Long Running Operation settings for calls to <c>EnvironmentsClient.UpdateEnvironment</c> and /// <c>EnvironmentsClient.UpdateEnvironmentAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings UpdateEnvironmentOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.DeleteEnvironment</c> and <c>EnvironmentsClient.DeleteEnvironmentAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>EnvironmentsClient.LookupEnvironmentHistory</c> and <c>EnvironmentsClient.LookupEnvironmentHistoryAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings LookupEnvironmentHistorySettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="EnvironmentsSettings"/> object.</returns> public EnvironmentsSettings Clone() => new EnvironmentsSettings(this); } /// <summary> /// Builder class for <see cref="EnvironmentsClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class EnvironmentsClientBuilder : gaxgrpc::ClientBuilderBase<EnvironmentsClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public EnvironmentsSettings Settings { get; set; } partial void InterceptBuild(ref EnvironmentsClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<EnvironmentsClient> task); /// <summary>Builds the resulting client.</summary> public override EnvironmentsClient Build() { EnvironmentsClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<EnvironmentsClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<EnvironmentsClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private EnvironmentsClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return EnvironmentsClient.Create(callInvoker, Settings); } private async stt::Task<EnvironmentsClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return EnvironmentsClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => EnvironmentsClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => EnvironmentsClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => EnvironmentsClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>Environments client wrapper, for convenient use.</summary> /// <remarks> /// Service for managing [Environments][google.cloud.dialogflow.cx.v3.Environment]. /// </remarks> public abstract partial class EnvironmentsClient { /// <summary> /// The default endpoint for the Environments service, which is a host of "dialogflow.googleapis.com" and a port /// of 443. /// </summary> public static string DefaultEndpoint { get; } = "dialogflow.googleapis.com:443"; /// <summary>The default Environments scopes.</summary> /// <remarks> /// The default Environments scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/dialogflow</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/dialogflow", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes); /// <summary> /// Asynchronously creates a <see cref="EnvironmentsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="EnvironmentsClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="EnvironmentsClient"/>.</returns> public static stt::Task<EnvironmentsClient> CreateAsync(st::CancellationToken cancellationToken = default) => new EnvironmentsClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="EnvironmentsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="EnvironmentsClientBuilder"/>. /// </summary> /// <returns>The created <see cref="EnvironmentsClient"/>.</returns> public static EnvironmentsClient Create() => new EnvironmentsClientBuilder().Build(); /// <summary> /// Creates a <see cref="EnvironmentsClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="EnvironmentsSettings"/>.</param> /// <returns>The created <see cref="EnvironmentsClient"/>.</returns> internal static EnvironmentsClient Create(grpccore::CallInvoker callInvoker, EnvironmentsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } Environments.EnvironmentsClient grpcClient = new Environments.EnvironmentsClient(callInvoker); return new EnvironmentsClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC Environments client</summary> public virtual Environments.EnvironmentsClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all environments for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEnvironments(new ListEnvironmentsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all environments for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEnvironmentsAsync(new ListEnvironmentsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all environments for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(AgentName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEnvironments(new ListEnvironmentsRequest { ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all environments for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(AgentName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEnvironmentsAsync(new ListEnvironmentsRequest { ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Environment GetEnvironment(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, st::CancellationToken cancellationToken) => GetEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Environment GetEnvironment(string name, gaxgrpc::CallSettings callSettings = null) => GetEnvironment(new GetEnvironmentRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(string name, gaxgrpc::CallSettings callSettings = null) => GetEnvironmentAsync(new GetEnvironmentRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(string name, st::CancellationToken cancellationToken) => GetEnvironmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Environment GetEnvironment(EnvironmentName name, gaxgrpc::CallSettings callSettings = null) => GetEnvironment(new GetEnvironmentRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(EnvironmentName name, gaxgrpc::CallSettings callSettings = null) => GetEnvironmentAsync(new GetEnvironmentRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Environment> GetEnvironmentAsync(EnvironmentName name, st::CancellationToken cancellationToken) => GetEnvironmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Environment, wkt::Struct> CreateEnvironment(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(CreateEnvironmentRequest request, st::CancellationToken cancellationToken) => CreateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>CreateEnvironment</c>.</summary> public virtual lro::OperationsClient CreateEnvironmentOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateEnvironment</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Environment, wkt::Struct> PollOnceCreateEnvironment(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Environment, wkt::Struct>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateEnvironmentOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>CreateEnvironment</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> PollOnceCreateEnvironmentAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Environment, wkt::Struct>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateEnvironmentOperationsClient, callSettings); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Environment, wkt::Struct> CreateEnvironment(string parent, Environment environment, gaxgrpc::CallSettings callSettings = null) => CreateEnvironment(new CreateEnvironmentRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), }, callSettings); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(string parent, Environment environment, gaxgrpc::CallSettings callSettings = null) => CreateEnvironmentAsync(new CreateEnvironmentRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), }, callSettings); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(string parent, Environment environment, st::CancellationToken cancellationToken) => CreateEnvironmentAsync(parent, environment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Environment, wkt::Struct> CreateEnvironment(AgentName parent, Environment environment, gaxgrpc::CallSettings callSettings = null) => CreateEnvironment(new CreateEnvironmentRequest { ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), }, callSettings); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(AgentName parent, Environment environment, gaxgrpc::CallSettings callSettings = null) => CreateEnvironmentAsync(new CreateEnvironmentRequest { ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), }, callSettings); /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="parent"> /// Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] to create an [Environment][google.cloud.dialogflow.cx.v3.Environment] for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent ID&amp;gt;`. /// </param> /// <param name="environment"> /// Required. The environment to create. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(AgentName parent, Environment environment, st::CancellationToken cancellationToken) => CreateEnvironmentAsync(parent, environment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Environment, wkt::Struct> UpdateEnvironment(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, st::CancellationToken cancellationToken) => UpdateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>UpdateEnvironment</c>.</summary> public virtual lro::OperationsClient UpdateEnvironmentOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>UpdateEnvironment</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Environment, wkt::Struct> PollOnceUpdateEnvironment(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Environment, wkt::Struct>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateEnvironmentOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>UpdateEnvironment</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> PollOnceUpdateEnvironmentAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Environment, wkt::Struct>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateEnvironmentOperationsClient, callSettings); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="environment"> /// Required. The environment to update. /// </param> /// <param name="updateMask"> /// Required. The mask to control which fields get updated. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Environment, wkt::Struct> UpdateEnvironment(Environment environment, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) => UpdateEnvironment(new UpdateEnvironmentRequest { Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)), }, callSettings); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="environment"> /// Required. The environment to update. /// </param> /// <param name="updateMask"> /// Required. The mask to control which fields get updated. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> UpdateEnvironmentAsync(Environment environment, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) => UpdateEnvironmentAsync(new UpdateEnvironmentRequest { Environment = gax::GaxPreconditions.CheckNotNull(environment, nameof(environment)), UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)), }, callSettings); /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="environment"> /// Required. The environment to update. /// </param> /// <param name="updateMask"> /// Required. The mask to control which fields get updated. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Environment, wkt::Struct>> UpdateEnvironmentAsync(Environment environment, wkt::FieldMask updateMask, st::CancellationToken cancellationToken) => UpdateEnvironmentAsync(environment, updateMask, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteEnvironment(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, st::CancellationToken cancellationToken) => DeleteEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteEnvironment(string name, gaxgrpc::CallSettings callSettings = null) => DeleteEnvironment(new DeleteEnvironmentRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(string name, gaxgrpc::CallSettings callSettings = null) => DeleteEnvironmentAsync(new DeleteEnvironmentRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(string name, st::CancellationToken cancellationToken) => DeleteEnvironmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteEnvironment(EnvironmentName name, gaxgrpc::CallSettings callSettings = null) => DeleteEnvironment(new DeleteEnvironmentRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(EnvironmentName name, gaxgrpc::CallSettings callSettings = null) => DeleteEnvironmentAsync(new DeleteEnvironmentRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. The name of the [Environment][google.cloud.dialogflow.cx.v3.Environment] to delete. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteEnvironmentAsync(EnvironmentName name, st::CancellationToken cancellationToken) => DeleteEnvironmentAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistory(LookupEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistoryAsync(LookupEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. Resource name of the environment to look up the history for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistory(string name, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => LookupEnvironmentHistory(new LookupEnvironmentHistoryRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. Resource name of the environment to look up the history for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistoryAsync(string name, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => LookupEnvironmentHistoryAsync(new LookupEnvironmentHistoryRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. Resource name of the environment to look up the history for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistory(EnvironmentName name, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => LookupEnvironmentHistory(new LookupEnvironmentHistoryRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="name"> /// Required. Resource name of the environment to look up the history for. /// Format: `projects/&amp;lt;Project ID&amp;gt;/locations/&amp;lt;Location ID&amp;gt;/agents/&amp;lt;Agent /// ID&amp;gt;/environments/&amp;lt;Environment ID&amp;gt;`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistoryAsync(EnvironmentName name, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => LookupEnvironmentHistoryAsync(new LookupEnvironmentHistoryRequest { EnvironmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); } /// <summary>Environments client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service for managing [Environments][google.cloud.dialogflow.cx.v3.Environment]. /// </remarks> public sealed partial class EnvironmentsClientImpl : EnvironmentsClient { private readonly gaxgrpc::ApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse> _callListEnvironments; private readonly gaxgrpc::ApiCall<GetEnvironmentRequest, Environment> _callGetEnvironment; private readonly gaxgrpc::ApiCall<CreateEnvironmentRequest, lro::Operation> _callCreateEnvironment; private readonly gaxgrpc::ApiCall<UpdateEnvironmentRequest, lro::Operation> _callUpdateEnvironment; private readonly gaxgrpc::ApiCall<DeleteEnvironmentRequest, wkt::Empty> _callDeleteEnvironment; private readonly gaxgrpc::ApiCall<LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse> _callLookupEnvironmentHistory; /// <summary> /// Constructs a client wrapper for the Environments service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="EnvironmentsSettings"/> used within this client.</param> public EnvironmentsClientImpl(Environments.EnvironmentsClient grpcClient, EnvironmentsSettings settings) { GrpcClient = grpcClient; EnvironmentsSettings effectiveSettings = settings ?? EnvironmentsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); CreateEnvironmentOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateEnvironmentOperationsSettings); UpdateEnvironmentOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.UpdateEnvironmentOperationsSettings); _callListEnvironments = clientHelper.BuildApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse>(grpcClient.ListEnvironmentsAsync, grpcClient.ListEnvironments, effectiveSettings.ListEnvironmentsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListEnvironments); Modify_ListEnvironmentsApiCall(ref _callListEnvironments); _callGetEnvironment = clientHelper.BuildApiCall<GetEnvironmentRequest, Environment>(grpcClient.GetEnvironmentAsync, grpcClient.GetEnvironment, effectiveSettings.GetEnvironmentSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetEnvironment); Modify_GetEnvironmentApiCall(ref _callGetEnvironment); _callCreateEnvironment = clientHelper.BuildApiCall<CreateEnvironmentRequest, lro::Operation>(grpcClient.CreateEnvironmentAsync, grpcClient.CreateEnvironment, effectiveSettings.CreateEnvironmentSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateEnvironment); Modify_CreateEnvironmentApiCall(ref _callCreateEnvironment); _callUpdateEnvironment = clientHelper.BuildApiCall<UpdateEnvironmentRequest, lro::Operation>(grpcClient.UpdateEnvironmentAsync, grpcClient.UpdateEnvironment, effectiveSettings.UpdateEnvironmentSettings).WithGoogleRequestParam("environment.name", request => request.Environment?.Name); Modify_ApiCall(ref _callUpdateEnvironment); Modify_UpdateEnvironmentApiCall(ref _callUpdateEnvironment); _callDeleteEnvironment = clientHelper.BuildApiCall<DeleteEnvironmentRequest, wkt::Empty>(grpcClient.DeleteEnvironmentAsync, grpcClient.DeleteEnvironment, effectiveSettings.DeleteEnvironmentSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteEnvironment); Modify_DeleteEnvironmentApiCall(ref _callDeleteEnvironment); _callLookupEnvironmentHistory = clientHelper.BuildApiCall<LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse>(grpcClient.LookupEnvironmentHistoryAsync, grpcClient.LookupEnvironmentHistory, effectiveSettings.LookupEnvironmentHistorySettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callLookupEnvironmentHistory); Modify_LookupEnvironmentHistoryApiCall(ref _callLookupEnvironmentHistory); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListEnvironmentsApiCall(ref gaxgrpc::ApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse> call); partial void Modify_GetEnvironmentApiCall(ref gaxgrpc::ApiCall<GetEnvironmentRequest, Environment> call); partial void Modify_CreateEnvironmentApiCall(ref gaxgrpc::ApiCall<CreateEnvironmentRequest, lro::Operation> call); partial void Modify_UpdateEnvironmentApiCall(ref gaxgrpc::ApiCall<UpdateEnvironmentRequest, lro::Operation> call); partial void Modify_DeleteEnvironmentApiCall(ref gaxgrpc::ApiCall<DeleteEnvironmentRequest, wkt::Empty> call); partial void Modify_LookupEnvironmentHistoryApiCall(ref gaxgrpc::ApiCall<LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse> call); partial void OnConstruction(Environments.EnvironmentsClient grpcClient, EnvironmentsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC Environments client</summary> public override Environments.EnvironmentsClient GrpcClient { get; } partial void Modify_ListEnvironmentsRequest(ref ListEnvironmentsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetEnvironmentRequest(ref GetEnvironmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateEnvironmentRequest(ref CreateEnvironmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_UpdateEnvironmentRequest(ref UpdateEnvironmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteEnvironmentRequest(ref DeleteEnvironmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_LookupEnvironmentHistoryRequest(ref LookupEnvironmentHistoryRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public override gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEnvironmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListEnvironmentsRequest, ListEnvironmentsResponse, Environment>(_callListEnvironments, request, callSettings); } /// <summary> /// Returns the list of all environments in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEnvironmentsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListEnvironmentsRequest, ListEnvironmentsResponse, Environment>(_callListEnvironments, request, callSettings); } /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Environment GetEnvironment(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetEnvironmentRequest(ref request, ref callSettings); return _callGetEnvironment.Sync(request, callSettings); } /// <summary> /// Retrieves the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetEnvironmentRequest(ref request, ref callSettings); return _callGetEnvironment.Async(request, callSettings); } /// <summary>The long-running operations client for <c>CreateEnvironment</c>.</summary> public override lro::OperationsClient CreateEnvironmentOperationsClient { get; } /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Environment, wkt::Struct> CreateEnvironment(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateEnvironmentRequest(ref request, ref callSettings); return new lro::Operation<Environment, wkt::Struct>(_callCreateEnvironment.Sync(request, callSettings), CreateEnvironmentOperationsClient); } /// <summary> /// Creates an [Environment][google.cloud.dialogflow.cx.v3.Environment] in the specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Environment, wkt::Struct>> CreateEnvironmentAsync(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateEnvironmentRequest(ref request, ref callSettings); return new lro::Operation<Environment, wkt::Struct>(await _callCreateEnvironment.Async(request, callSettings).ConfigureAwait(false), CreateEnvironmentOperationsClient); } /// <summary>The long-running operations client for <c>UpdateEnvironment</c>.</summary> public override lro::OperationsClient UpdateEnvironmentOperationsClient { get; } /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Environment, wkt::Struct> UpdateEnvironment(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateEnvironmentRequest(ref request, ref callSettings); return new lro::Operation<Environment, wkt::Struct>(_callUpdateEnvironment.Sync(request, callSettings), UpdateEnvironmentOperationsClient); } /// <summary> /// Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Environment, wkt::Struct>> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateEnvironmentRequest(ref request, ref callSettings); return new lro::Operation<Environment, wkt::Struct>(await _callUpdateEnvironment.Async(request, callSettings).ConfigureAwait(false), UpdateEnvironmentOperationsClient); } /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteEnvironment(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEnvironmentRequest(ref request, ref callSettings); _callDeleteEnvironment.Sync(request, callSettings); } /// <summary> /// Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEnvironmentRequest(ref request, ref callSettings); return _callDeleteEnvironment.Async(request, callSettings); } /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns> public override gax::PagedEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistory(LookupEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LookupEnvironmentHistoryRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse, Environment>(_callLookupEnvironmentHistory, request, callSettings); } /// <summary> /// Looks up the history of the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns> public override gax::PagedAsyncEnumerable<LookupEnvironmentHistoryResponse, Environment> LookupEnvironmentHistoryAsync(LookupEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LookupEnvironmentHistoryRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse, Environment>(_callLookupEnvironmentHistory, request, callSettings); } } public partial class ListEnvironmentsRequest : gaxgrpc::IPageRequest { } public partial class LookupEnvironmentHistoryRequest : gaxgrpc::IPageRequest { } public partial class ListEnvironmentsResponse : gaxgrpc::IPageResponse<Environment> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Environment> GetEnumerator() => Environments.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class LookupEnvironmentHistoryResponse : gaxgrpc::IPageResponse<Environment> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Environment> GetEnumerator() => Environments.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class Environments { public partial class EnvironmentsClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
64.953835
526
0.676166
[ "Apache-2.0" ]
Global19/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3/EnvironmentsClient.g.cs
87,233
C#
namespace TrainSystem.Models { using System.Data.Entity; public class TrainSystemDbContext : DbContext { public virtual IDbSet<Trip> Trips { get; set; } public TrainSystemDbContext() : base("TrainSystem") { } } }
20.230769
59
0.61597
[ "MIT" ]
jeliozver/SoftUni-Software-Technologies
Exams/Retake-Exam-8-January-2018/CSharp/TrainSystem/Models/TrainSystemDbContext.cs
265
C#
using System.Text.RegularExpressions; using Abp.Extensions; namespace AbpCompanyName.AbpProjectName.Validation { public static class ValidationHelper { public const string EmailRegex = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"; public static bool IsEmail(string value) { if (value.IsNullOrEmpty()) { return false; } var regex = new Regex(EmailRegex); return regex.IsMatch(value); } } }
22.565217
91
0.535645
[ "MIT" ]
ngthaiquy/abplus-zero-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Core/Validation/ValidationHelper.cs
521
C#
namespace AS91892.Data.Entities; /// <summary> /// Represents an <see cref="Album"/> in the database /// </summary> public class Album : BaseEntity { /// <summary> /// An image for the album covers /// </summary> [JsonPropertyName("albumCover")] public Image? AlbumCover { get; set; } #nullable disable /// <summary> /// Represents the songs in the album /// </summary> [Required] [Display(Name = "Album Songs")] [JsonPropertyName("albumSongs")] public ICollection<Song> AlbumSongs { get; set; } /// <summary> /// Title of the album /// </summary> [Required] [StringLength(50, MinimumLength = 2)] [JsonPropertyName("title")] public string Title { get; set; } /// <summary> /// Year that the album was released /// </summary> [Required] [JsonPropertyName("year")] public int Year { get; set; } }
24.297297
53
0.602892
[ "MIT" ]
ac111897/AS91892
AS91892.Data/Entities/Album.cs
901
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Storage.Models; namespace Azure.ResourceManager.Storage { internal partial class FileSharesRestOperations { private readonly string _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of FileSharesRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public FileSharesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-08-01"; _userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId); } internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string accountName, string maxpagesize, string filter, string expand) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares", false); uri.AppendQuery("api-version", _apiVersion, true); if (maxpagesize != null) { uri.AppendQuery("$maxpagesize", maxpagesize, true); } if (filter != null) { uri.AppendQuery("$filter", filter, true); } if (expand != null) { uri.AppendQuery("$expand", expand, true); } request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists all shares. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="maxpagesize"> Optional. Specified maximum number of shares that can be included in the list. </param> /// <param name="filter"> Optional. When specified, only share names starting with the filter will be listed. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: deleted, snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FileShareItems>> ListAsync(string subscriptionId, string resourceGroupName, string accountName, string maxpagesize = null, string filter = null, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); using var message = CreateListRequest(subscriptionId, resourceGroupName, accountName, maxpagesize, filter, expand); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FileShareItems value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FileShareItems.DeserializeFileShareItems(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists all shares. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="maxpagesize"> Optional. Specified maximum number of shares that can be included in the list. </param> /// <param name="filter"> Optional. When specified, only share names starting with the filter will be listed. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: deleted, snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FileShareItems> List(string subscriptionId, string resourceGroupName, string accountName, string maxpagesize = null, string filter = null, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); using var message = CreateListRequest(subscriptionId, resourceGroupName, accountName, maxpagesize, filter, expand); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FileShareItems value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FileShareItems.DeserializeFileShareItems(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateCreateRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare, string expand) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); if (expand != null) { uri.AppendQuery("$expand", expand, true); } uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(fileShare); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Creates a new share under the specified account as described by request body. The share resource includes metadata and properties for that share. It does not include a list of the files contained by the share. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="fileShare"> Properties of the file share to create. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="fileShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FileShareData>> CreateAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(fileShare, nameof(fileShare)); using var message = CreateCreateRequest(subscriptionId, resourceGroupName, accountName, shareName, fileShare, expand); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { FileShareData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Creates a new share under the specified account as described by request body. The share resource includes metadata and properties for that share. It does not include a list of the files contained by the share. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="fileShare"> Properties of the file share to create. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="fileShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FileShareData> Create(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(fileShare, nameof(fileShare)); using var message = CreateCreateRequest(subscriptionId, resourceGroupName, accountName, shareName, fileShare, expand); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { FileShareData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(fileShare); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Updates share properties as specified in request body. Properties not mentioned in the request will not be changed. Update fails if the specified share does not already exist. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="fileShare"> Properties to update for the file share. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="fileShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FileShareData>> UpdateAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(fileShare, nameof(fileShare)); using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, accountName, shareName, fileShare); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FileShareData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Updates share properties as specified in request body. Properties not mentioned in the request will not be changed. Update fails if the specified share does not already exist. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="fileShare"> Properties to update for the file share. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="fileShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FileShareData> Update(string subscriptionId, string resourceGroupName, string accountName, string shareName, FileShareData fileShare, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(fileShare, nameof(fileShare)); using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, accountName, shareName, fileShare); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FileShareData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, string expand, string xMsSnapshot) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); uri.AppendQuery("api-version", _apiVersion, true); if (expand != null) { uri.AppendQuery("$expand", expand, true); } request.Uri = uri; if (xMsSnapshot != null) { request.Headers.Add("x-ms-snapshot", xMsSnapshot); } request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets properties of a specified share. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: stats. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="xMsSnapshot"> Optional, used to retrieve properties of a snapshot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FileShareData>> GetAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, string expand = null, string xMsSnapshot = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, accountName, shareName, expand, xMsSnapshot); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FileShareData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((FileShareData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Gets properties of a specified share. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: stats. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="xMsSnapshot"> Optional, used to retrieve properties of a snapshot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FileShareData> Get(string subscriptionId, string resourceGroupName, string accountName, string shareName, string expand = null, string xMsSnapshot = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, accountName, shareName, expand, xMsSnapshot); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FileShareData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FileShareData.DeserializeFileShareData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((FileShareData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, string xMsSnapshot, string include) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); uri.AppendQuery("api-version", _apiVersion, true); if (include != null) { uri.AppendQuery("$include", include, true); } request.Uri = uri; if (xMsSnapshot != null) { request.Headers.Add("x-ms-snapshot", xMsSnapshot); } request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Deletes specified share under its account. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="xMsSnapshot"> Optional, used to delete a snapshot. </param> /// <param name="include"> Optional. Valid values are: snapshots, leased-snapshots, none. The default value is snapshots. For &apos;snapshots&apos;, the file share is deleted including all of its file share snapshots. If the file share contains leased-snapshots, the deletion fails. For &apos;leased-snapshots&apos;, the file share is deleted included all of its file share snapshots (leased/unleased). For &apos;none&apos;, the file share is deleted if it has no share snapshots. If the file share contains any snapshots (leased or unleased), the deletion fails. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, string xMsSnapshot = null, string include = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, accountName, shareName, xMsSnapshot, include); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Deletes specified share under its account. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="xMsSnapshot"> Optional, used to delete a snapshot. </param> /// <param name="include"> Optional. Valid values are: snapshots, leased-snapshots, none. The default value is snapshots. For &apos;snapshots&apos;, the file share is deleted including all of its file share snapshots. If the file share contains leased-snapshots, the deletion fails. For &apos;leased-snapshots&apos;, the file share is deleted included all of its file share snapshots (leased/unleased). For &apos;none&apos;, the file share is deleted if it has no share snapshots. If the file share contains any snapshots (leased or unleased), the deletion fails. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string accountName, string shareName, string xMsSnapshot = null, string include = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, accountName, shareName, xMsSnapshot, include); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateRestoreRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, DeletedShare deletedShare) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); uri.AppendPath("/restore", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(deletedShare); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Restore a file share within a valid retention days if share soft delete is enabled. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="deletedShare"> The DeletedShare to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="deletedShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> RestoreAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, DeletedShare deletedShare, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(deletedShare, nameof(deletedShare)); using var message = CreateRestoreRequest(subscriptionId, resourceGroupName, accountName, shareName, deletedShare); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Restore a file share within a valid retention days if share soft delete is enabled. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="deletedShare"> The DeletedShare to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="shareName"/> or <paramref name="deletedShare"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response Restore(string subscriptionId, string resourceGroupName, string accountName, string shareName, DeletedShare deletedShare, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); Argument.AssertNotNull(deletedShare, nameof(deletedShare)); using var message = CreateRestoreRequest(subscriptionId, resourceGroupName, accountName, shareName, deletedShare); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateLeaseRequest(string subscriptionId, string resourceGroupName, string accountName, string shareName, LeaseShareRequest parameters, string xMsSnapshot) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/fileServices/default/shares/", false); uri.AppendPath(shareName, true); uri.AppendPath("/lease", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; if (xMsSnapshot != null) { request.Headers.Add("x-ms-snapshot", xMsSnapshot); } request.Headers.Add("Accept", "application/json"); if (parameters != null) { request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; } message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> The Lease Share operation establishes and manages a lock on a share for delete operations. The lock duration can be 15 to 60 seconds, or can be infinite. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="parameters"> Lease Share request body. </param> /// <param name="xMsSnapshot"> Optional. Specify the snapshot time to lease a snapshot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<LeaseShareResponse>> LeaseAsync(string subscriptionId, string resourceGroupName, string accountName, string shareName, LeaseShareRequest parameters = null, string xMsSnapshot = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateLeaseRequest(subscriptionId, resourceGroupName, accountName, shareName, parameters, xMsSnapshot); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { LeaseShareResponse value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = LeaseShareResponse.DeserializeLeaseShareResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> The Lease Share operation establishes and manages a lock on a share for delete operations. The lock duration can be 15 to 60 seconds, or can be infinite. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="shareName"> The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param> /// <param name="parameters"> Lease Share request body. </param> /// <param name="xMsSnapshot"> Optional. Specify the snapshot time to lease a snapshot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="accountName"/> or <paramref name="shareName"/> is an empty string, and was expected to be non-empty. </exception> public Response<LeaseShareResponse> Lease(string subscriptionId, string resourceGroupName, string accountName, string shareName, LeaseShareRequest parameters = null, string xMsSnapshot = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); Argument.AssertNotNullOrEmpty(shareName, nameof(shareName)); using var message = CreateLeaseRequest(subscriptionId, resourceGroupName, accountName, shareName, parameters, xMsSnapshot); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { LeaseShareResponse value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = LeaseShareResponse.DeserializeLeaseShareResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string accountName, string maxpagesize, string filter, string expand) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists all shares. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="maxpagesize"> Optional. Specified maximum number of shares that can be included in the list. </param> /// <param name="filter"> Optional. When specified, only share names starting with the filter will be listed. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: deleted, snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FileShareItems>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string accountName, string maxpagesize = null, string filter = null, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, accountName, maxpagesize, filter, expand); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FileShareItems value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FileShareItems.DeserializeFileShareItems(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists all shares. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="maxpagesize"> Optional. Specified maximum number of shares that can be included in the list. </param> /// <param name="filter"> Optional. When specified, only share names starting with the filter will be listed. </param> /// <param name="expand"> Optional, used to expand the properties within share&apos;s properties. Valid values are: deleted, snapshots. Should be passed as a string with delimiter &apos;,&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FileShareItems> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string accountName, string maxpagesize = null, string filter = null, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, accountName, maxpagesize, filter, expand); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FileShareItems value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FileShareItems.DeserializeFileShareItems(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
77.642857
580
0.671376
[ "MIT" ]
KurnakovMaksim/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/src/Generated/RestOperations/FileSharesRestOperations.cs
60,872
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace CommandCraft.Views.ValueConverters { class StringToEnumConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value?.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value?.Equals(true) == true ? parameter : Binding.DoNothing; } } }
27.875
124
0.704036
[ "Apache-2.0" ]
mcw256/CommandCraft
CommandCraft/CommandCraft/Views/ValueConverters/StringToEnumConverter.cs
671
C#
using System; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; using Microsoft.Practices.EnterpriseLibrary.Logging.Database; using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.EnterpriseLibrary.Logging.BVT.Async { [TestClass] public class AsynchronousListenerWrapperFixture : LoggingFixtureBase { [TestMethod] public void AllEntriesAreWrittenWhenUsingAsynchForFlatFile() { string fileName = "AsynchTestingForFlatFile.log"; File.Delete(fileName); var configuration = new LoggingConfiguration(); configuration.AddLogSource("TestAsynchLogging In FlatFile").AddTraceListener(new AsynchronousTraceListenerWrapper( new FlatFileTraceListener(fileName), ownsWrappedTraceListener: true, bufferSize: 10000, disposeTimeout: TimeSpan.FromSeconds(5))); using (var writer = new LogWriter(configuration)) { Parallel.Invoke(Enumerable.Range(0, 10000).Select(i => new Action(() => { writer.Write("Test Asynch Message: " + i); })).ToArray()); } Assert.IsTrue(File.Exists(fileName)); Assert.IsTrue(LogFileReader.ReadFileWithoutLock(fileName).Contains("Test Asynch Message: 0")); Assert.IsTrue(LogFileReader.ReadFileWithoutLock(fileName).Contains("Test Asynch Message: 9999")); } [TestMethod] public void MultipleFilesAreWrittenWhenUsingAsynchForRollingFlatFile() { const string Folder = "AsyncFolder"; const string FileNameWithoutExtension = "AsynchTestingForRollingFlatFile"; const string Extension = ".log"; const string FileName = FileNameWithoutExtension + Extension; LogFileReader.CreateDirectory(Folder); var configuration = new LoggingConfiguration(); configuration.AddLogSource("TestAsynchLogging In RollingFlatFile").AddTraceListener(new AsynchronousTraceListenerWrapper( new RollingFlatFileTraceListener(Path.Combine(Folder, FileName), "----", "----", new TextFormatter(), 8, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Minute, 10), ownsWrappedTraceListener: true, bufferSize: 100)); using (var writer = new LogWriter(configuration)) { Parallel.Invoke(Enumerable.Range(0, 100).Select(i => new Action(() => { writer.Write("Test Asynch Message: " + i); })).ToArray()); } Assert.IsTrue(File.Exists(Path.Combine(Folder, FileName))); Assert.IsTrue(File.Exists(Path.Combine(Folder, FileNameWithoutExtension + "." + DateTime.Now.Year + ".1" + Extension))); Assert.IsTrue(File.Exists(Path.Combine(Folder, FileNameWithoutExtension + "." + DateTime.Now.Year + ".5" + Extension))); } [TestMethod] public void MultipleEntriesAreWrittenWhenUsingAsynchForFormattedEventLog() { string unique = Guid.NewGuid().ToString(); var eventLog = new EventLog("Application", ".", "Enterprise Library Logging"); var configuration = new LoggingConfiguration(); configuration.AddLogSource("TestAsynchLogging In FormattedEventLog").AddTraceListener(new AsynchronousTraceListenerWrapper( new FormattedEventLogTraceListener(eventLog), ownsWrappedTraceListener: true, bufferSize: 10)); using (var writer = new LogWriter(configuration)) { Parallel.Invoke(Enumerable.Range(0, 10).Select(i => new Action(() => { writer.Write(unique + " Test Asynch Message: " + i); })).ToArray()); } Assert.IsTrue(this.CheckForEntryInEventlog(unique + " Test Asynch Message: 0")); Assert.IsTrue(this.CheckForEntryInEventlog(unique + " Test Asynch Message: 9")); } [TestMethod] public void MultipleEntriesAreWrittenWhenUsingAsynchForXML() { string xmlFileName = "XMLFile.xml"; File.Delete(xmlFileName); var configuration = new LoggingConfiguration(); configuration.AddLogSource("TestAsynchLogging In XML file").AddTraceListener(new AsynchronousTraceListenerWrapper( new XmlTraceListener(xmlFileName), ownsWrappedTraceListener: true, bufferSize: 100)); using (var writer = new LogWriter(configuration)) { Parallel.Invoke(Enumerable.Range(0, 200).Select(i => new Action(() => { writer.Write("Test Asynch Message: " + i); })).ToArray()); } Assert.IsTrue(File.Exists(xmlFileName)); Assert.IsTrue(LogFileReader.ReadFileWithoutLock(xmlFileName).Contains("Test Asynch Message: 0")); Assert.IsTrue(LogFileReader.ReadFileWithoutLock(xmlFileName).Contains("Test Asynch Message: 99")); } [TestMethod] public void AllEntriesAreWrittenWhenUsingAsynchForFormattedDatabase() { this.ClearLogs(); string unique = Guid.NewGuid().ToString(); SqlDatabase dbConnection = new SqlDatabase(connectionString); int messageContents = 0; var configuration = new LoggingConfiguration(); configuration.AddLogSource("TestAsynchLogging In FormattedDatabase") .AddTraceListener(new AsynchronousTraceListenerWrapper( new FormattedDatabaseTraceListener(dbConnection, "WriteLog", "AddCategory", null), ownsWrappedTraceListener: true, bufferSize: 10000)); using (var writer = new LogWriter(configuration)) { Parallel.Invoke(Enumerable.Range(0, 10000).Select(i => new Action(() => { writer.Write(unique + " Test Asynch Message: " + i); })).ToArray()); } using (var connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("select COUNT(1) from Log where Message like '" + unique + " Test Asynch Message:%'", connection); messageContents = (Int32)command.ExecuteScalar(); connection.Close(); } Assert.AreEqual(10000, messageContents); } } }
45.703947
150
0.615949
[ "Apache-2.0" ]
Microsoft/logging-application-block
BVT/Logging.BVT/Async/AsynchronousListenerWrapperFixture.cs
6,949
C#
namespace HareDu.Snapshotting.Model { public record DiskSnapshot : Snapshot { public string NodeIdentifier { get; init; } public DiskCapacityDetails Capacity { get; init; } public ulong Limit { get; init; } public bool AlarmInEffect { get; init; } public IO IO { get; init; } } }
22.4375
58
0.576602
[ "Apache-2.0" ]
ahives/HareDu3
src/HareDu.Snapshotting/Model/DiskSnapshot.cs
359
C#
using System; using System.ComponentModel.DataAnnotations.Schema; namespace EIP.System.Models.Entities { /// <summary> /// System_Permission表实体类 /// </summary> [Serializable] [Table("System_Permission")] public class SystemPermission { /// <summary> /// 权限归属(0菜单、1按钮等) /// </summary> public short PrivilegeAccess { get; set; } /// <summary> /// 对应类型主键值(角色id,人员id,组id,岗位id,) /// </summary> public Guid PrivilegeMasterValue { get; set; } /// <summary> /// 对应权限归属主键(菜单id,按钮id等) /// </summary> public Guid PrivilegeAccessValue { get; set; } /// <summary> /// 给予权限类型 /// </summary> public short PrivilegeMaster { get; set; } /// <summary> /// 对应菜单Id /// </summary> public Guid? PrivilegeMenuId { get; set; } } }
23.358974
54
0.531284
[ "MIT" ]
edwinhuish/eipcore2
Api/Service/System/EIP.System.Models/Entities/SystemPermission.cs
1,013
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SettingsTXTPrintOut : MonoBehaviour { public Text GPUAPIText, ResolutionText; void Start() { PrintOut(); } void PrintOut() { ResolutionText.text = "Current Resolution: " + Screen.currentResolution.ToString(); GPUAPIText.text = "Current Rendering API: " + SystemInfo.graphicsDeviceType.ToString(); } }
22.380952
95
0.693617
[ "Unlicense" ]
j-mano/VolvoTruck
Assets/Scripts/SettingsTXTPrintOut.cs
470
C#
using System; using System.Windows; using System.Windows.Shapes; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Instantiate the dialog box private readonly Settings dlg = new() { }; public MainWindow() { InitializeComponent(); } private void About_Click(object sender, RoutedEventArgs e) { _ = MessageBox.Show(new String("Copyright Magnus Hermansson AS"), new String("About")); } private void Inputs_Click(object sender, RoutedEventArgs e) { dlg.Show(); } private void Dlg_PointsChanged(double[][] arr) { this.MakeLines(arr); } private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e) { static double reCalcLine(double x, bool isChanged, double pre, double post) { return isChanged ? x * post / pre : x; } if (IsLoaded) { System.Collections.IEnumerator enumerator = myCanvas.Children.GetEnumerator(); while (enumerator.MoveNext()) { Line line = (Line)enumerator.Current; line.X1 = reCalcLine(line.X1, e.WidthChanged, e.PreviousSize.Width, e.NewSize.Width); line.Y1 = reCalcLine(line.Y1, e.HeightChanged, e.PreviousSize.Height, e.NewSize.Height); line.X2 = reCalcLine(line.X2, e.WidthChanged, e.PreviousSize.Width, e.NewSize.Width); line.Y2 = reCalcLine(line.Y2, e.HeightChanged, e.PreviousSize.Height, e.NewSize.Height); } } } private void Window_Loaded(object sender, RoutedEventArgs e) { // Configure the dialog box dlg.Owner = this; dlg.PointsChanged += new Settings.PointsChangedHandler(Dlg_PointsChanged); } } }
33.048387
108
0.565154
[ "MIT" ]
CMHAS/RealtimeSolver
Dialog/MainWindow.xaml.cs
2,051
C#
using System; namespace _01.BiscuitFactory { class Program { static void Main(string[] args) { int amountOfBiscuits = int.Parse(Console.ReadLine()); // worker produce a day int countWorkers = int.Parse(Console.ReadLine()); // in factory int biscuitsProducedFor30days = int.Parse(Console.ReadLine()); double totalFor30 = 0; double forOneday = 0; double percen = 0; for (int i = 1; i <= 30; i++) { if (i % 3 == 0) { forOneday += Math.Floor(amountOfBiscuits * countWorkers * 0.75); } else { totalFor30 += amountOfBiscuits * countWorkers; } } totalFor30 += forOneday; Console.WriteLine($"You have produced {totalFor30} biscuits for the past month."); if (totalFor30 > biscuitsProducedFor30days) { double need = (int)totalFor30 - biscuitsProducedFor30days; percen = need / biscuitsProducedFor30days * 100; Console.WriteLine($"You produce {percen:f2} percent more biscuits."); } else { double need = biscuitsProducedFor30days - totalFor30; percen = need / biscuitsProducedFor30days * 100; Console.WriteLine($"You produce {percen:f2} percent less biscuits."); } } } }
33.595745
94
0.495883
[ "MIT" ]
martinsivanov/CSharp-Fundamentals---May-2020
Exams/Programming Fundamentals Mid Exam - 2 November 2019 Group 1/01.BiscuitFactory/Program.cs
1,581
C#
using Xamarin.Forms; namespace MobileSnapp.Controls { public enum ShadowType { None = 0, Top, Bottom } public class ShadowBoxView : BoxView { public static readonly BindableProperty ShadowTypeProperty = BindableProperty.Create( nameof(ShadowType), typeof(ShadowType), typeof(ShadowBoxView)); public ShadowType ShadowType { get => (ShadowType)GetValue(ShadowTypeProperty); set => SetValue(ShadowTypeProperty, value); } } }
21.769231
93
0.59364
[ "MIT", "BSD-3-Clause" ]
maidsafe/sn_app_mobile
MobileSnapp/MobileSnapp/Controls/ShadowBoxView.cs
568
C#
using System.IO; using DotnetExlib.Properties; namespace DotnetExlib.Yeckthone.CAP { [Author("Takym", copyright: "Copyright (C) 2017 Takym.")] public class CapAnalyzer : ILexicalAnalyzer, ISyntaxAnalyzer { public CapAnalyzer(string filename) { } public CapAnalyzer(Stream stream) { } public CapAnalyzer(TextReader reader) { } public CapAnalyzer(BinaryReader reader) { } public void Scan() { } public void Parse() { } } }
11.85
61
0.675105
[ "MIT" ]
Takym/DotnetExlib
DotnetExlib/Yeckthone/CAP/CapAnalyzer.cs
476
C#
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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. */ #if !XLUA_GENERAL using UnityEngine; using UnityEditor; #endif using System.Collections.Generic; using System.IO; using XLua; using System; using System.Reflection; using System.Text; using System.Linq; using System.Runtime.CompilerServices; using Utils = XLua.Utils; namespace CSObjectWrapEditor { public static class GeneratorConfig { #if XLUA_GENERAL public static string common_path = "./Gen/"; #else public static string common_path = Application.dataPath + "/XLua/Gen/"; #endif static GeneratorConfig() { foreach(var type in (from type in Utils.GetAllTypes() where type.IsAbstract && type.IsSealed select type)) { foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) { if (field.FieldType == typeof(string) && field.IsDefined(typeof(GenPathAttribute), false)) { common_path = field.GetValue(null) as string; if (!common_path.EndsWith("/")) { common_path = common_path + "/"; } } } foreach (var prop in type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) { if (prop.PropertyType == typeof(string) && prop.IsDefined(typeof(GenPathAttribute), false)) { common_path = prop.GetValue(null, null) as string; if (!common_path.EndsWith("/")) { common_path = common_path + "/"; } } } } } } public struct CustomGenTask { public LuaTable Data; public TextWriter Output; } public struct UserConfig { public IEnumerable<Type> LuaCallCSharp; public IEnumerable<Type> CSharpCallLua; public IEnumerable<Type> ReflectionUse; } public class GenCodeMenuAttribute : Attribute { } public class GenPathAttribute : Attribute { } public struct XLuaTemplate { public string name; public string text; } public struct XLuaTemplates { public XLuaTemplate LuaClassWrap; public XLuaTemplate LuaDelegateBridge; public XLuaTemplate LuaDelegateWrap; public XLuaTemplate LuaEnumWrap; public XLuaTemplate LuaInterfaceBridge; public XLuaTemplate LuaRegister; public XLuaTemplate LuaWrapPusher; public XLuaTemplate PackUnpack; public XLuaTemplate TemplateCommon; } public static class Generator { static LuaEnv luaenv = new LuaEnv(); static List<string> OpMethodNames = new List<string>() { "op_Addition", "op_Subtraction", "op_Multiply", "op_Division", "op_Equality", "op_UnaryNegation", "op_LessThan", "op_LessThanOrEqual", "op_Modulus", "op_BitwiseAnd", "op_BitwiseOr", "op_ExclusiveOr", "op_OnesComplement", "op_LeftShift", "op_RightShift"}; private static XLuaTemplates templateRef; static Generator() { #if !XLUA_GENERAL TemplateRef template_ref = ScriptableObject.CreateInstance<TemplateRef>(); templateRef = new XLuaTemplates() { #if GEN_CODE_MINIMIZE LuaClassWrap = { name = template_ref.LuaClassWrapGCM.name, text = template_ref.LuaClassWrapGCM.text }, #else LuaClassWrap = { name = template_ref.LuaClassWrap.name, text = template_ref.LuaClassWrap.text }, #endif LuaDelegateBridge = { name = template_ref.LuaDelegateBridge.name, text = template_ref.LuaDelegateBridge.text }, LuaDelegateWrap = { name = template_ref.LuaDelegateWrap.name, text = template_ref.LuaDelegateWrap.text }, #if GEN_CODE_MINIMIZE LuaEnumWrap = { name = template_ref.LuaEnumWrapGCM.name, text = template_ref.LuaEnumWrapGCM.text }, #else LuaEnumWrap = { name = template_ref.LuaEnumWrap.name, text = template_ref.LuaEnumWrap.text }, #endif LuaInterfaceBridge = { name = template_ref.LuaInterfaceBridge.name, text = template_ref.LuaInterfaceBridge.text }, #if GEN_CODE_MINIMIZE LuaRegister = { name = template_ref.LuaRegisterGCM.name, text = template_ref.LuaRegisterGCM.text }, #else LuaRegister = { name = template_ref.LuaRegister.name, text = template_ref.LuaRegister.text }, #endif LuaWrapPusher = { name = template_ref.LuaWrapPusher.name, text = template_ref.LuaWrapPusher.text }, PackUnpack = { name = template_ref.PackUnpack.name, text = template_ref.PackUnpack.text }, TemplateCommon = { name = template_ref.TemplateCommon.name, text = template_ref.TemplateCommon.text }, }; #endif luaenv.AddLoader((ref string filepath) => { if (filepath == "TemplateCommon") { return Encoding.UTF8.GetBytes(templateRef.TemplateCommon.text); } else { return null; } }); } static bool IsOverride(MethodBase method) { var m = method as MethodInfo; return m != null && !m.IsConstructor && m.IsVirtual && (m.GetBaseDefinition().DeclaringType != m.DeclaringType); } static int OverloadCosting(MethodBase mi) { int costing = 0; if (!mi.IsStatic) { costing++; } foreach (var paraminfo in mi.GetParameters()) { if ((!paraminfo.ParameterType.IsPrimitive ) && (paraminfo.IsIn || !paraminfo.IsOut)) { costing++; } } costing = costing * 10000 + (mi.GetParameters().Length + (mi.IsStatic ? 0 : 1)); return costing; } static IEnumerable<Type> type_has_extension_methods = null; static IEnumerable<MethodInfo> GetExtensionMethods(Type extendedType) { if (type_has_extension_methods == null) { var gen_types = LuaCallCSharp; type_has_extension_methods = from type in gen_types where type.GetMethods(BindingFlags.Static | BindingFlags.Public) .Any(method => method.IsDefined(typeof(ExtensionAttribute), false)) select type; } return from type in type_has_extension_methods where type.IsSealed && !type.IsGenericType && !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) where isSupportedExtensionMethod(method, extendedType) select method; } static bool isSupportedExtensionMethod(MethodBase method, Type extendedType) { if (!method.IsDefined(typeof(ExtensionAttribute), false)) return false; var methodParameters = method.GetParameters(); if (methodParameters.Length < 1) return false; var hasValidGenericParameter = false; for (var i = 0; i < methodParameters.Length; i++) { var parameterType = methodParameters[i].ParameterType; if (i == 0) { if (parameterType.IsGenericParameter) { var parameterConstraints = parameterType.GetGenericParameterConstraints(); if (parameterConstraints.Length == 0) return false; bool firstParamMatch = false; foreach (var parameterConstraint in parameterConstraints) { if (parameterConstraint != typeof(ValueType) && parameterConstraint.IsAssignableFrom(extendedType)) { firstParamMatch = true; } } if (!firstParamMatch) return false; hasValidGenericParameter = true; } else if (parameterType != extendedType) return false; } else if (parameterType.IsGenericParameter) { var parameterConstraints = parameterType.GetGenericParameterConstraints(); if (parameterConstraints.Length == 0) return false; foreach (var parameterConstraint in parameterConstraints) { if (!parameterConstraint.IsClass || (parameterConstraint == typeof(ValueType)) || Generator.hasGenericParameter(parameterConstraint)) return false; } hasValidGenericParameter = true; } } return hasValidGenericParameter || !method.ContainsGenericParameters; } static bool IsDoNotGen(Type type, string name) { return DoNotGen.ContainsKey(type) && DoNotGen[type].Contains(name); } static void getClassInfo(Type type, LuaTable parameters) { parameters.Set("type", type); var constructors = new List<MethodBase>(); var constructor_def_vals = new List<int>(); if (!type.IsAbstract) { foreach (var con in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase).Cast<MethodBase>() .Where(constructor => !isMethodInBlackList(constructor) && !isObsolete(constructor))) { int def_count = 0; constructors.Add(con); constructor_def_vals.Add(def_count); var ps = con.GetParameters(); for (int i = ps.Length - 1; i >= 0; i--) { if (ps[i].IsOptional || (ps[i].IsDefined(typeof(ParamArrayAttribute), false) && i > 0 && ps[i - 1].IsOptional)) { def_count++; constructors.Add(con); constructor_def_vals.Add(def_count); } else { break; } } } } parameters.Set("constructors", constructors); parameters.Set("constructor_def_vals", constructor_def_vals); var getters = type.GetProperties().Where(prop => prop.CanRead); var setters = type.GetProperties().Where(prop => prop.CanWrite); var methodNames = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly).Select(t=>t.Name).Distinct().ToDictionary(t=>t); foreach (var getter in getters) { methodNames.Remove("get_" + getter.Name); } foreach (var setter in setters) { methodNames.Remove("set_" + setter.Name); } List<string> extension_methods_namespace = new List<string>(); var extension_methods = type.IsInterface ? new MethodInfo[0]:GetExtensionMethods(type).ToArray(); foreach(var extension_method in extension_methods) { if (extension_method.DeclaringType.Namespace != null && extension_method.DeclaringType.Namespace != "System.Collections.Generic" && extension_method.DeclaringType.Namespace != "XLua") { extension_methods_namespace.Add(extension_method.DeclaringType.Namespace); } } parameters.Set("namespaces", extension_methods_namespace.Distinct().ToList()); List<LazyMemberInfo> lazyMemberInfos = new List<LazyMemberInfo>(); //warnning: filter all method start with "op_" "add_" "remove_" may filter some ordinary method parameters.Set("methods", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(method => !method.IsDefined(typeof (ExtensionAttribute), false) || method.GetParameters()[0].ParameterType.IsInterface || method.DeclaringType != type) .Where(method => methodNames.ContainsKey(method.Name)) //GenericMethod can not be invoke becuase not static info available! .Concat(extension_methods) .Where(method => !IsDoNotGen(type, method.Name)) .Where(method => !isMethodInBlackList(method) && (!method.IsGenericMethod || extension_methods.Contains(method) || isSupportedGenericMethod(method)) && !isObsolete(method) && !method.Name.StartsWith("op_") && !method.Name.StartsWith("add_") && !method.Name.StartsWith("remove_")) .GroupBy(method => (method.Name + ((method.IsStatic && (!method.IsDefined(typeof (ExtensionAttribute), false) || method.GetParameters()[0].ParameterType.IsInterface)) ? "_xlua_st_" : "")), (k, v) => { var overloads = new List<MethodBase>(); List<int> def_vals = new List<int>(); bool isOverride = false; foreach (var overload in v.Cast<MethodBase>().OrderBy(mb => OverloadCosting(mb))) { int def_count = 0; overloads.Add(overload); def_vals.Add(def_count); if (!isOverride) { isOverride = IsOverride(overload); } var ps = overload.GetParameters(); for (int i = ps.Length - 1; i >=0; i--) { if(ps[i].IsOptional || (ps[i].IsDefined(typeof(ParamArrayAttribute), false) && i > 0 && ps[i - 1].IsOptional)) { def_count++; overloads.Add(overload); def_vals.Add(def_count); } else { break; } } } #if HOTFIX_ENABLE if (isOverride) { lazyMemberInfos.Add(new LazyMemberInfo { Index = "METHOD_IDX", Name = "<>xLuaBaseProxy_" + k, MemberType = "LazyMemberTypes.Method", IsStatic = "false" }); } #endif return new { Name = k, IsStatic = overloads[0].IsStatic && (!overloads[0].IsDefined(typeof(ExtensionAttribute), false) || overloads[0].GetParameters()[0].ParameterType.IsInterface), Overloads = overloads, DefaultValues = def_vals }; }).ToList()); parameters.Set("getters", type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(prop => prop.CanRead && (prop.GetGetMethod() != null) && prop.Name != "Item" && !isObsolete(prop) && !isObsolete(prop.GetGetMethod()) && !isMemberInBlackList(prop) && !isMemberInBlackList(prop.GetGetMethod())).Select(prop => new { prop.Name, IsStatic = prop.GetGetMethod().IsStatic, ReadOnly = false, Type = prop.PropertyType }) .Concat( type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(field => !isObsolete(field) && !isMemberInBlackList(field)) .Select(field => new { field.Name, field.IsStatic, ReadOnly = field.IsInitOnly || field.IsLiteral, Type = field.FieldType }) ).Where(info => !IsDoNotGen(type, info.Name))/*.Where(getter => !typeof(Delegate).IsAssignableFrom(getter.Type))*/.ToList()); parameters.Set("setters", type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(prop => prop.CanWrite && (prop.GetSetMethod() != null) && prop.Name != "Item" && !isObsolete(prop) && !isObsolete(prop.GetSetMethod()) && !isMemberInBlackList(prop) && !isMemberInBlackList(prop.GetSetMethod())).Select(prop => new { prop.Name, IsStatic = prop.GetSetMethod().IsStatic, Type = prop.PropertyType, IsProperty = true }) .Concat( type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(field => !isObsolete(field) && !isMemberInBlackList(field) && !field.IsInitOnly && !field.IsLiteral) .Select(field => new { field.Name, field.IsStatic, Type = field.FieldType, IsProperty = false }) ).Where(info => !IsDoNotGen(type, info.Name))/*.Where(setter => !typeof(Delegate).IsAssignableFrom(setter.Type))*/.ToList()); parameters.Set("operators", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(method => OpMethodNames.Contains(method.Name)) .GroupBy(method => method.Name, (k, v) => new { Name = k, Overloads = v.Cast<MethodBase>().OrderBy(mb => mb.GetParameters().Length).ToList() }).ToList()); parameters.Set("indexers", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(method => method.Name == "get_Item" && method.GetParameters().Length == 1 && !method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) .ToList()); parameters.Set("newindexers", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(method => method.Name == "set_Item" && method.GetParameters().Length == 2 && !method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) .ToList()); parameters.Set("events", type.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly).Where(e => !isObsolete(e) && !isMemberInBlackList(e)) .Where(ev=> ev.GetAddMethod() != null || ev.GetRemoveMethod() != null) .Where(ev => !IsDoNotGen(type, ev.Name)) .Select(ev => new { IsStatic = ev.GetAddMethod() != null? ev.GetAddMethod().IsStatic: ev.GetRemoveMethod().IsStatic, ev.Name, CanSet = false, CanAdd = ev.GetRemoveMethod() != null, CanRemove = ev.GetRemoveMethod() != null, Type = ev.EventHandlerType}) .ToList()); parameters.Set("lazymembers", lazyMemberInfos); foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) .Where(m => IsDoNotGen(type, m.Name)) .GroupBy(m=>m.Name).Select(g => g.First()) ) { switch(member.MemberType) { case MemberTypes.Method: MethodBase mb = member as MethodBase; lazyMemberInfos.Add(new LazyMemberInfo { Index = mb.IsStatic ? "CLS_IDX" : "METHOD_IDX", Name = member.Name, MemberType = "LazyMemberTypes.Method", IsStatic = mb.IsStatic ? "true" : "false" }); break; case MemberTypes.Event: EventInfo ev = member as EventInfo; if (ev.GetAddMethod() == null && ev.GetRemoveMethod() == null) break; bool eventIsStatic = ev.GetAddMethod() != null ? ev.GetAddMethod().IsStatic : ev.GetRemoveMethod().IsStatic; lazyMemberInfos.Add(new LazyMemberInfo { Index = eventIsStatic ? "CLS_IDX" : "METHOD_IDX", Name = member.Name, MemberType = "LazyMemberTypes.Event", IsStatic = eventIsStatic ? "true" : "false" }); break; case MemberTypes.Field: FieldInfo field = member as FieldInfo; lazyMemberInfos.Add(new LazyMemberInfo { Index = field.IsStatic ? "CLS_GETTER_IDX" : "GETTER_IDX", Name = member.Name, MemberType = "LazyMemberTypes.FieldGet", IsStatic = field.IsStatic ? "true" : "false" }); lazyMemberInfos.Add(new LazyMemberInfo { Index = field.IsStatic ? "CLS_SETTER_IDX" : "SETTER_IDX", Name = member.Name, MemberType = "LazyMemberTypes.FieldSet", IsStatic = field.IsStatic ? "true" : "false" }); break; case MemberTypes.Property: PropertyInfo prop = member as PropertyInfo; if (prop.Name != "Item" || prop.GetIndexParameters().Length == 0) { if (prop.CanRead && prop.GetGetMethod() != null) { var isStatic = prop.GetGetMethod().IsStatic; lazyMemberInfos.Add(new LazyMemberInfo { Index = isStatic ? "CLS_GETTER_IDX" : "GETTER_IDX", Name = member.Name, MemberType = "LazyMemberTypes.PropertyGet", IsStatic = isStatic ? "true" : "false" }); } if (prop.CanWrite && prop.GetSetMethod() != null) { var isStatic = prop.GetSetMethod().IsStatic; lazyMemberInfos.Add(new LazyMemberInfo { Index = isStatic ? "CLS_SETTER_IDX" : "SETTER_IDX", Name = member.Name, MemberType = "LazyMemberTypes.PropertySet", IsStatic = isStatic ? "true" : "false" }); } } break; } } } class LazyMemberInfo { public string Index; public string Name; public string MemberType; public string IsStatic; } static void getInterfaceInfo(Type type, LuaTable parameters) { parameters.Set("type", type); var itfs = new Type[] { type }.Concat(type.GetInterfaces()); parameters.Set("methods", itfs.SelectMany(i => i.GetMethods()) .Where(method => !method.IsSpecialName && !method.IsGenericMethod && !method.Name.StartsWith("op_") && !method.Name.StartsWith("add_") && !method.Name.StartsWith("remove_")) //GenericMethod can not be invoke becuase not static info available! .ToList()); parameters.Set("propertys", itfs.SelectMany(i => i.GetProperties()) .Where(prop => (prop.CanRead || prop.CanWrite) && prop.Name != "Item") .ToList()); parameters.Set("events", itfs.SelectMany(i => i.GetEvents()).ToList()); parameters.Set("indexers", itfs.SelectMany(i => i.GetProperties()) .Where(prop => (prop.CanRead || prop.CanWrite) && prop.Name == "Item") .ToList()); } static bool isObsolete(MemberInfo mb) { if (mb == null) return false; return mb.IsDefined(typeof(System.ObsoleteAttribute), false); } static bool isMemberInBlackList(MemberInfo mb) { if (mb.IsDefined(typeof(BlackListAttribute), false)) return true; foreach (var exclude in BlackList) { if (mb.DeclaringType.FullName == exclude[0] && mb.Name == exclude[1]) { return true; } } return false; } static bool isMethodInBlackList(MethodBase mb) { if (mb.IsDefined(typeof(BlackListAttribute), false)) return true; foreach (var exclude in BlackList) { if (mb.DeclaringType.FullName == exclude[0] && mb.Name == exclude[1]) { var parameters = mb.GetParameters(); if (parameters.Length != exclude.Count - 2) { continue; } bool paramsMatch = true; for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.FullName != exclude[i + 2]) { paramsMatch = false; break; } } if (paramsMatch) return true; } } return false; } static Dictionary<string, LuaFunction> templateCache = new Dictionary<string, LuaFunction>(); static void GenOne(Type type, Action<Type, LuaTable> type_info_getter, XLuaTemplate templateAsset, StreamWriter textWriter) { if (isObsolete(type)) return; LuaFunction template; if (!templateCache.TryGetValue(templateAsset.name, out template)) { template = XLua.TemplateEngine.LuaTemplate.Compile(luaenv, templateAsset.text); templateCache[templateAsset.name] = template; } LuaTable type_info = luaenv.NewTable(); LuaTable meta = luaenv.NewTable(); meta.Set("__index", luaenv.Global); type_info.SetMetaTable(meta); meta.Dispose(); type_info_getter(type, type_info); try { string genCode = XLua.TemplateEngine.LuaTemplate.Execute(template, type_info); //string filePath = save_path + type.ToString().Replace("+", "").Replace(".", "").Replace("`", "").Replace("&", "").Replace("[", "").Replace("]", "").Replace(",", "") + file_suffix + ".cs"; textWriter.Write(genCode); textWriter.Flush(); } catch (Exception e) { #if XLUA_GENERAL System.Console.WriteLine("Error: gen wrap file fail! err=" + e.Message + ", stack=" + e.StackTrace); #else Debug.LogError("gen wrap file fail! err=" + e.Message + ", stack=" + e.StackTrace); #endif } finally { type_info.Dispose(); } } static void GenEnumWrap(IEnumerable<Type> types, string save_path) { string filePath = save_path + "EnumWrap.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); GenOne(null, (type, type_info) => { type_info.Set("types", types.ToList()); }, templateRef.LuaEnumWrap, textWriter); textWriter.Close(); } static void GenInterfaceBridge(IEnumerable<Type> types, string save_path) { foreach (var wrap_type in types) { if (!wrap_type.IsInterface) continue; string filePath = save_path + wrap_type.ToString().Replace("+", "").Replace(".", "") .Replace("`", "").Replace("&", "").Replace("[", "").Replace("]", "").Replace(",", "") + "Bridge.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); GenOne(wrap_type, (type, type_info) => { getInterfaceInfo(type, type_info); }, templateRef.LuaInterfaceBridge, textWriter); textWriter.Close(); } } class ParameterInfoSimulation { public string Name; public bool IsOut; public bool IsIn; public Type ParameterType; public bool IsParamArray; } class MethodInfoSimulation { public Type ReturnType; public ParameterInfoSimulation[] ParameterInfos; public int HashCode; public ParameterInfoSimulation[] GetParameters() { return ParameterInfos; } public Type DeclaringType = null; public string DeclaringTypeName = null; } static MethodInfoSimulation makeMethodInfoSimulation(MethodInfo method) { int hashCode = method.ReturnType.GetHashCode(); List<ParameterInfoSimulation> paramsExpect = new List<ParameterInfoSimulation>(); foreach (var param in method.GetParameters()) { if (param.IsOut) { hashCode++; } hashCode += param.ParameterType.GetHashCode(); paramsExpect.Add(new ParameterInfoSimulation() { Name = param.Name, IsOut = param.IsOut, IsIn = param.IsIn, ParameterType = param.ParameterType, IsParamArray = param.IsDefined(typeof(System.ParamArrayAttribute), false) }); } return new MethodInfoSimulation() { ReturnType = method.ReturnType, HashCode = hashCode, ParameterInfos = paramsExpect.ToArray(), DeclaringType = method.DeclaringType }; } static bool isNotPublic(Type type) { if (type.IsByRef || type.IsArray) { return isNotPublic(type.GetElementType()); } else { if ((!type.IsNested && !type.IsPublic) || (type.IsNested && !type.IsNestedPublic)) { return true; } if (type.IsGenericType) { foreach (var ga in type.GetGenericArguments()) { if (isNotPublic(ga)) { return true; } } } if (type.IsNested) { var parent = type.DeclaringType; while (parent != null) { if ((!parent.IsNested && !parent.IsPublic) || (parent.IsNested && !parent.IsNestedPublic)) { return true; } if (parent.IsNested) { parent = parent.DeclaringType; } else { break; } } } return false; } } static bool hasGenericParameter(Type type) { if (type.IsByRef || type.IsArray) { return hasGenericParameter(type.GetElementType()); } if (type.IsGenericType) { foreach (var typeArg in type.GetGenericArguments()) { if (hasGenericParameter(typeArg)) { return true; } } return false; } return type.IsGenericParameter; } static MethodInfoSimulation makeHotfixMethodInfoSimulation(MethodBase hotfixMethod, HotfixFlag hotfixType) { bool isStateful = hotfixType.HasFlag(HotfixFlag.Stateful); bool ignoreValueType = hotfixType.HasFlag(HotfixFlag.ValueTypeBoxing); //isStateful = false; //ignoreValueType = true; Type retTypeExpect = (isStateful && hotfixMethod.IsConstructor && !hotfixMethod.IsStatic) ? typeof(LuaTable) : (hotfixMethod.IsConstructor ? typeof(void) : (hotfixMethod as MethodInfo).ReturnType); int hashCode = retTypeExpect.GetHashCode(); List<ParameterInfoSimulation> paramsExpect = new List<ParameterInfoSimulation>(); if (!hotfixMethod.IsStatic) // add self { if (isStateful && !hotfixMethod.IsConstructor) { paramsExpect.Add(new ParameterInfoSimulation() { Name = "self", IsOut = false, IsIn = true, ParameterType = typeof(LuaTable), IsParamArray = false }); } else { paramsExpect.Add(new ParameterInfoSimulation() { Name = "self", IsOut = false, IsIn = true, ParameterType = (hotfixMethod.DeclaringType.IsValueType && !ignoreValueType) ? hotfixMethod.DeclaringType : typeof(object), IsParamArray = false }); } hashCode += paramsExpect[0].ParameterType.GetHashCode(); } foreach (var param in hotfixMethod.GetParameters()) { var paramExpect = new ParameterInfoSimulation() { Name = param.Name, IsOut = param.IsOut, IsIn = param.IsIn, ParameterType = (param.ParameterType.IsByRef || (param.ParameterType.IsValueType && !ignoreValueType) || param.IsDefined(typeof(System.ParamArrayAttribute), false)) ? param.ParameterType : typeof(object), IsParamArray = param.IsDefined(typeof(System.ParamArrayAttribute), false) }; if (param.IsOut) { hashCode++; } hashCode += paramExpect.ParameterType.GetHashCode(); paramsExpect.Add(paramExpect); } return new MethodInfoSimulation() { HashCode = hashCode, ReturnType = retTypeExpect, ParameterInfos = paramsExpect.ToArray() }; } class MethodInfoSimulationComparer : IEqualityComparer<MethodInfoSimulation> { public bool Equals(MethodInfoSimulation x, MethodInfoSimulation y) { if (object.ReferenceEquals(x, y)) return true; if (x == null || y == null) { return false; } if (x.ReturnType != y.ReturnType) { return false; } var xParams = x.GetParameters(); var yParams = y.GetParameters(); if (xParams.Length != yParams.Length) { return false; } for (int i = 0; i < xParams.Length; i++) { if (xParams[i].ParameterType != yParams[i].ParameterType || xParams[i].IsOut != yParams[i].IsOut) { return false; } } return true; } public int GetHashCode(MethodInfoSimulation obj) { return obj.HashCode; } } static bool injectByGeneric(MethodBase method, HotfixFlag hotfixType) { bool isStateful = hotfixType.HasFlag(HotfixFlag.Stateful); bool ignoreValueType = hotfixType.HasFlag(HotfixFlag.ValueTypeBoxing); //isStateful = false; //ignoreValueType = true; if (!method.IsConstructor && (isNotPublic((method as MethodInfo).ReturnType) || hasGenericParameter((method as MethodInfo).ReturnType))) return true; if (!method.IsStatic && (!isStateful || method.IsConstructor) &&(((method.DeclaringType.IsValueType && !ignoreValueType) && isNotPublic(method.DeclaringType)) || hasGenericParameter(method.DeclaringType))) { return true; } foreach (var param in method.GetParameters()) { if ((((param.ParameterType.IsValueType && !ignoreValueType) || param.ParameterType.IsByRef) && isNotPublic(param.ParameterType)) || hasGenericParameter(param.ParameterType)) return true; } return false; } static bool HasFlag(this HotfixFlag toCheck, HotfixFlag flag) { return (toCheck != HotfixFlag.Stateless) && ((toCheck & flag) == flag); } static void GenDelegateBridge(IEnumerable<Type> types, string save_path, IEnumerable<Type> hotfix_check_types) { string filePath = save_path + "DelegatesGensBridge.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); types = types.Where(type => !type.GetMethod("Invoke").GetParameters().Any(paramInfo => paramInfo.ParameterType.IsGenericParameter)); var hotfxDelegates = new List<MethodInfoSimulation>(); var comparer = new MethodInfoSimulationComparer(); var bindingAttrOfMethod = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.NonPublic; var bindingAttrOfConstructor = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic; foreach (var type in (from type in hotfix_check_types where type.IsDefined(typeof(HotfixAttribute), false) select type)) { if (type.Name.Contains("<")) { continue; } var hotfixType = ((type.GetCustomAttributes(typeof(HotfixAttribute), false)[0]) as HotfixAttribute).Flag; if (hotfixType.HasFlag(HotfixFlag.Inline)) { continue; } bool ignoreProperty = hotfixType.HasFlag(HotfixFlag.IgnoreProperty); bool ignoreNotPublic = hotfixType.HasFlag(HotfixFlag.IgnoreNotPublic); //ignoreProperty = true; hotfxDelegates.AddRange(type.GetMethods(bindingAttrOfMethod) .Where(method => method.GetMethodBody() != null) .Where(method => !method.Name.Contains("<")) .Where(method => !ignoreNotPublic || method.IsPublic) .Where(method => !ignoreProperty || !method.IsSpecialName || (!method.Name.StartsWith("get_") && !method.Name.StartsWith("set_"))) .Cast<MethodBase>() .Concat(type.GetConstructors(bindingAttrOfConstructor).Cast<MethodBase>()) .Where(method => !injectByGeneric(method, hotfixType)) .Select(method => makeHotfixMethodInfoSimulation(method, hotfixType))); } foreach (var kv in HotfixCfg) { if (kv.Key.Name.Contains("<") || kv.Value.HasFlag(HotfixFlag.Inline)) { continue; } bool ignoreProperty = kv.Value.HasFlag(HotfixFlag.IgnoreProperty); bool ignoreNotPublic = kv.Value.HasFlag(HotfixFlag.IgnoreNotPublic); //ignoreProperty = true; hotfxDelegates.AddRange(kv.Key.GetMethods(bindingAttrOfMethod) .Where(method => method.GetMethodBody() != null) .Where(method => !method.Name.Contains("<")) .Where(method => !ignoreNotPublic || method.IsPublic) .Where(method => !ignoreProperty || !method.IsSpecialName || (!method.Name.StartsWith("get_") && !method.Name.StartsWith("set_"))) .Cast<MethodBase>() .Concat(kv.Key.GetConstructors(bindingAttrOfConstructor).Cast<MethodBase>()) .Where(method => !injectByGeneric(method, kv.Value)) .Select(method => makeHotfixMethodInfoSimulation(method, kv.Value))); } hotfxDelegates = hotfxDelegates.Distinct(comparer).ToList(); for(int i = 0; i < hotfxDelegates.Count; i++) { hotfxDelegates[i].DeclaringTypeName = "__Gen_Hotfix_Delegate" + i; } var delegates_groups = types.Select(delegate_type => makeMethodInfoSimulation(delegate_type.GetMethod("Invoke"))) .Concat(hotfxDelegates) .GroupBy(d => d, comparer).Select((group) => new { Key = group.Key, Value = group.ToList()}); GenOne(typeof(DelegateBridge), (type, type_info) => { type_info.Set("delegates_groups", delegates_groups.ToList()); }, templateRef.LuaDelegateBridge, textWriter); textWriter.Close(); } static void GenWrapPusher(IEnumerable<Type> types, string save_path) { string filePath = save_path + "WrapPusher.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); var emptyMap = new Dictionary<Type, Type>(); GenOne(typeof(ObjectTranslator), (type, type_info) => { type_info.Set("purevaluetypes", types .Where(t => t.IsEnum || (!t.IsPrimitive && SizeOf(t) != -1)) .Select(t => new { Type = t, Size = SizeOf(t), Flag = t.IsEnum ? OptimizeFlag.Default : OptimizeCfg[t], FieldInfos = (t.IsEnum || OptimizeCfg[t] == OptimizeFlag.Default) ? null : getXluaTypeInfo(t, emptyMap).FieldInfos }).ToList()); type_info.Set("tableoptimzetypes", types.Where(t => !t.IsEnum && SizeOf(t) == -1) .Select(t => new { Type = t, Fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) }) .ToList()); }, templateRef.LuaWrapPusher, textWriter); textWriter.Close(); } static void GenWrap(IEnumerable<Type> types, string save_path) { types = types.Where(type=>!type.IsEnum); #if GENERIC_SHARING types = types.GroupBy(t => t.IsGenericType ? t.GetGenericTypeDefinition() : t).Select(g => g.Key); #endif var typeMap = types.ToDictionary(type => { //Debug.Log("type:" + type); return type.ToString(); }); foreach (var wrap_type in types) { string filePath = save_path + wrap_type.ToString().Replace("+", "").Replace(".", "") .Replace("`", "").Replace("&", "").Replace("[", "").Replace("]", "").Replace(",", "") + "Wrap.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); if (wrap_type.IsEnum) { GenOne(wrap_type, (type, type_info) => { type_info.Set("type", type); type_info.Set("fields", type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static) .Where(field => !isObsolete(field)) .ToList()); }, templateRef.LuaEnumWrap, textWriter); } else if (typeof(Delegate).IsAssignableFrom(wrap_type)) { GenOne(wrap_type, (type, type_info) => { type_info.Set("type", type); type_info.Set("delegate", type.GetMethod("Invoke")); }, templateRef.LuaDelegateWrap, textWriter); } else { GenOne(wrap_type, (type, type_info) => { if (type.BaseType != null && typeMap.ContainsKey(type.BaseType.ToString())) { type_info.Set("base", type.BaseType); } getClassInfo(type, type_info); }, templateRef.LuaClassWrap, textWriter); } textWriter.Close(); } } #if !XLUA_GENERAL static void clear(string path) { if (Directory.Exists(path)) { Directory.Delete(path, true); AssetDatabase.DeleteAsset(path.Substring(path.IndexOf("Assets") + "Assets".Length)); AssetDatabase.Refresh(); } } #endif class DelegateByMethodDecComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) { return Utils.IsParamsMatch(x.GetMethod("Invoke"), y.GetMethod("Invoke")); } public int GetHashCode(Type obj) { int hc = 0; var method = obj.GetMethod("Invoke"); hc += method.ReturnType.GetHashCode(); foreach (var pi in method.GetParameters()) { hc += pi.ParameterType.GetHashCode(); } return hc; } } public static void GenDelegateBridges(IEnumerable<Type> hotfix_check_types) { var delegate_types = CSharpCallLua.Where(type => typeof(Delegate).IsAssignableFrom(type)); GenDelegateBridge(delegate_types, GeneratorConfig.common_path, hotfix_check_types); } public static void GenEnumWraps() { var enum_types = LuaCallCSharp.Where(type => type.IsEnum).Distinct(); GenEnumWrap(enum_types, GeneratorConfig.common_path); } static MethodInfo makeGenericMethodIfNeeded(MethodInfo method) { if (!method.ContainsGenericParameters) return method; var genericArguments = method.GetGenericArguments(); var constraintedArgumentTypes = new Type[genericArguments.Length]; for (var i = 0; i < genericArguments.Length; i++) { var argumentType = genericArguments[i]; var parameterConstraints = argumentType.GetGenericParameterConstraints(); Type parameterConstraint = parameterConstraints[0]; foreach(var type in argumentType.GetGenericParameterConstraints()) { if (parameterConstraint.IsAssignableFrom(type)) { parameterConstraint = type; } } constraintedArgumentTypes[i] = parameterConstraint; } return method.MakeGenericMethod(constraintedArgumentTypes); } public static void GenLuaRegister(bool minimum = false) { var wraps = minimum ? new List<Type>() : LuaCallCSharp; var itf_bridges = CSharpCallLua.Where(t => t.IsInterface); string filePath = GeneratorConfig.common_path + "XLuaGenAutoRegister.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); var extension_methods = from t in ReflectionUse where t.IsDefined(typeof(ExtensionAttribute), false) from method in t.GetMethods(BindingFlags.Static | BindingFlags.Public) where method.IsDefined(typeof(ExtensionAttribute), false) where !method.ContainsGenericParameters || isSupportedGenericMethod(method) select makeGenericMethodIfNeeded(method); GenOne(typeof(DelegateBridgeBase), (type, type_info) => { #if GENERIC_SHARING type_info.Set("wraps", wraps.Where(t=>!t.IsGenericType).ToList()); var genericTypeGroups = wraps.Where(t => t.IsGenericType).GroupBy(t => t.GetGenericTypeDefinition()); var typeToArgsList = luaenv.NewTable(); foreach (var genericTypeGroup in genericTypeGroups) { var argsList = luaenv.NewTable(); int i = 1; foreach(var genericType in genericTypeGroup) { argsList.Set(i++, genericType.GetGenericArguments()); } typeToArgsList.Set(genericTypeGroup.Key, argsList); argsList.Dispose(); } type_info.Set("generic_wraps", typeToArgsList); typeToArgsList.Dispose(); #else type_info.Set("wraps", wraps.ToList()); #endif type_info.Set("itf_bridges", itf_bridges.ToList()); type_info.Set("extension_methods", extension_methods.ToList()); }, templateRef.LuaRegister, textWriter); textWriter.Close(); } public static void AllSubStruct(Type type, Action<Type> cb) { if (!type.IsPrimitive && type != typeof(decimal)) { cb(type); foreach(var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { AllSubStruct(fieldInfo.FieldType, cb); } foreach(var propInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if ((AdditionalProperties.ContainsKey(type) && AdditionalProperties[type].Contains(propInfo.Name)) || propInfo.IsDefined(typeof(AdditionalPropertiesAttribute), false)) { AllSubStruct(propInfo.PropertyType, cb); } } } } class XluaFieldInfo { public string Name; public Type Type; public bool IsField; public int Size; } class XluaTypeInfo { public Type Type; public List<XluaFieldInfo> FieldInfos; public List<List<XluaFieldInfo>> FieldGroup; public bool IsRoot; } static XluaTypeInfo getXluaTypeInfo(Type t, Dictionary<Type, Type> set) { var fs = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(fi => new XluaFieldInfo { Name = fi.Name, Type = fi.FieldType, IsField = true, Size = SizeOf(fi.FieldType) }) .Concat(t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(prop => { return (AdditionalProperties.ContainsKey(t) && AdditionalProperties[t].Contains(prop.Name)) || prop.IsDefined(typeof(AdditionalPropertiesAttribute), false); }) .Select(prop => new XluaFieldInfo { Name = prop.Name, Type = prop.PropertyType, IsField = false, Size = SizeOf(prop.PropertyType) })); int float_field_count = 0; bool only_float = true; foreach (var f in fs) { if (f.Type == typeof(float)) { float_field_count++; } else { only_float = false; break; } } List<List<XluaFieldInfo>> grouped_field = null; if (only_float && float_field_count > 1) { grouped_field = new List<List<XluaFieldInfo>>(); List<XluaFieldInfo> group = null; foreach (var f in fs) { if (group == null) group = new List<XluaFieldInfo>(); group.Add(f); if (group.Count >= 6) { grouped_field.Add(group); group = null; } } if (group != null) grouped_field.Add(group); } return new XluaTypeInfo { Type = t, FieldInfos = fs.ToList(), FieldGroup = grouped_field, IsRoot = set.ContainsKey(t) }; } public static void GenPackUnpack(IEnumerable<Type> types, string save_path) { var set = types.ToDictionary(type => type); List<Type> all_types = new List<Type>(); foreach(var type in types) { AllSubStruct(type, (t) => { all_types.Add(t); }); } string filePath = save_path + "PackUnpack.cs"; StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); GenOne(typeof(CopyByValue), (type, type_info) => { type_info.Set("type_infos", all_types.Distinct().Select(t => getXluaTypeInfo(t, set)).ToList()); }, templateRef.PackUnpack, textWriter); textWriter.Close(); } //lua中要使用到C#库的配置,比如C#标准库,或者Unity API,第三方库等。 public static List<Type> LuaCallCSharp = null; //C#静态调用Lua的配置(包括事件的原型),仅可以配delegate,interface public static List<Type> CSharpCallLua = null; //黑名单 public static List<List<string>> BlackList = null; public static List<Type> GCOptimizeList = null; public static Dictionary<Type, List<string>> AdditionalProperties = null; public static List<Type> ReflectionUse = null; public static Dictionary<Type, HotfixFlag> HotfixCfg = null; public static Dictionary<Type, OptimizeFlag> OptimizeCfg = null; public static Dictionary<Type, HashSet<string>> DoNotGen = null; static void AddToList(List<Type> list, Func<object> get, object attr) { object obj = get(); if (obj is Type) { list.Add(obj as Type); } else if (obj is IEnumerable<Type>) { list.AddRange(obj as IEnumerable<Type>); } else { throw new InvalidOperationException("Only field/property with the type IEnumerable<Type> can be marked " + attr.GetType().Name); } if (attr is GCOptimizeAttribute) { var flag = (attr as GCOptimizeAttribute).Flag; if (obj is Type) { OptimizeCfg.Add(obj as Type, flag); } else if (obj is IEnumerable<Type>) { foreach(var type in (obj as IEnumerable<Type>)) { OptimizeCfg.Add(type, flag); } } } } static void MergeCfg(MemberInfo test, Type cfg_type, Func<object> get_cfg) { if (test.IsDefined(typeof(LuaCallCSharpAttribute), false)) { object[] ccla = test.GetCustomAttributes(typeof(LuaCallCSharpAttribute), false); AddToList(LuaCallCSharp, get_cfg, ccla[0]); #pragma warning disable 618 if (ccla.Length == 1 && (((ccla[0] as LuaCallCSharpAttribute).Flag & GenFlag.GCOptimize) != 0)) #pragma warning restore 618 { AddToList(GCOptimizeList, get_cfg, ccla[0]); } } if (test.IsDefined(typeof(CSharpCallLuaAttribute), false)) { AddToList(CSharpCallLua, get_cfg, test.GetCustomAttributes(typeof(CSharpCallLuaAttribute), false)[0]); } if (test.IsDefined(typeof(GCOptimizeAttribute), false)) { AddToList(GCOptimizeList, get_cfg, test.GetCustomAttributes(typeof(GCOptimizeAttribute), false)[0]); } if (test.IsDefined(typeof(ReflectionUseAttribute), false)) { AddToList(ReflectionUse, get_cfg, test.GetCustomAttributes(typeof(ReflectionUseAttribute), false)[0]); } if (test.IsDefined(typeof(HotfixAttribute), false)) { object cfg = get_cfg(); if (cfg is IEnumerable<Type>) { var hotfixType = ((test.GetCustomAttributes(typeof(HotfixAttribute), false)[0]) as HotfixAttribute).Flag; foreach (var type in cfg as IEnumerable<Type>) { if (!HotfixCfg.ContainsKey(type) && !isObsolete(type) && !type.IsEnum && !typeof(Delegate).IsAssignableFrom(type) && (!type.IsGenericType || type.IsGenericTypeDefinition) && (type.Namespace == null || (type.Namespace != "XLua" && !type.Namespace.StartsWith("XLua."))) && (type.Module.Assembly.GetName().Name == "Assembly-CSharp")) { HotfixCfg.Add(type, hotfixType); } } } } if (test.IsDefined(typeof(BlackListAttribute), false) && (typeof(List<List<string>>)).IsAssignableFrom(cfg_type)) { BlackList.AddRange(get_cfg() as List<List<string>>); } if (test.IsDefined(typeof(AdditionalPropertiesAttribute), false) && (typeof(Dictionary<Type, List<string>>)).IsAssignableFrom(cfg_type)) { var cfg = get_cfg() as Dictionary<Type, List<string>>; foreach (var kv in cfg) { if (!AdditionalProperties.ContainsKey(kv.Key)) { AdditionalProperties.Add(kv.Key, kv.Value); } } } if (test.IsDefined(typeof(DoNotGenAttribute), false) && (typeof(Dictionary<Type, List<string>>)).IsAssignableFrom(cfg_type)) { var cfg = get_cfg() as Dictionary<Type, List<string>>; foreach (var kv in cfg) { HashSet<string> set; if (!DoNotGen.TryGetValue(kv.Key, out set)) { set = new HashSet<string>(); DoNotGen.Add(kv.Key, set); } set.UnionWith(kv.Value); } } } public static void GetGenConfig(IEnumerable<Type> check_types) { LuaCallCSharp = new List<Type>(); CSharpCallLua = new List<Type>(); GCOptimizeList = new List<Type>(); AdditionalProperties = new Dictionary<Type, List<string>>(); ReflectionUse = new List<Type>(); BlackList = new List<List<string>>() { }; HotfixCfg = new Dictionary<Type, HotfixFlag>(); OptimizeCfg = new Dictionary<Type, OptimizeFlag>(); DoNotGen = new Dictionary<Type, HashSet<string>>(); foreach (var t in check_types) { MergeCfg(t, null, () => t); if (!t.IsAbstract || !t.IsSealed) continue; var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); for (int i = 0; i < fields.Length; i++) { var field = fields[i]; MergeCfg(field, field.FieldType, () => field.GetValue(null)); } var props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); for (int i = 0; i < props.Length; i++) { var prop = props[i]; MergeCfg(prop, prop.PropertyType, () => prop.GetValue(null, null)); } } LuaCallCSharp = LuaCallCSharp.Distinct() .Where(type=>/*type.IsPublic && */!isObsolete(type) && !type.IsGenericTypeDefinition) .Where(type => !typeof(Delegate).IsAssignableFrom(type)) .Where(type => !type.Name.Contains("<")) .ToList();//public的内嵌Enum(其它类型未测试),IsPublic为false,像是mono的bug CSharpCallLua = CSharpCallLua.Distinct() .Where(type =>/*type.IsPublic && */!isObsolete(type) && !type.IsGenericTypeDefinition) .Where(type => type != typeof(Delegate) && type != typeof(MulticastDelegate)) .ToList(); GCOptimizeList = GCOptimizeList.Distinct() .Where(type =>/*type.IsPublic && */!isObsolete(type) && !type.IsGenericTypeDefinition) .ToList(); ReflectionUse = ReflectionUse.Distinct() .Where(type =>/*type.IsPublic && */!isObsolete(type) && !type.IsGenericTypeDefinition) .ToList(); } static Dictionary<Type, int> type_size = new Dictionary<Type, int>() { { typeof(byte), 1 }, { typeof(sbyte), 1 }, { typeof(short), 2 }, { typeof(ushort), 2 }, { typeof(int), 4 }, { typeof(uint), 4 }, { typeof(long), 8 }, { typeof(ulong), 8 }, { typeof(float), 4 }, { typeof(double), 8 }, { typeof(decimal), 16 } }; static int SizeOf(Type type) { if (type_size.ContainsKey(type)) { return type_size[type]; } if (!CopyByValue.IsStruct(type)) { return -1; } int size = 0; foreach(var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { int t_size = SizeOf(fieldInfo.FieldType); if (t_size == -1) { size = -1; break; } size += t_size; } if (size != -1) { foreach (var propInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if ((AdditionalProperties.ContainsKey(type) && AdditionalProperties[type].Contains(propInfo.Name)) || propInfo.IsDefined(typeof(AdditionalPropertiesAttribute), false)) { int t_size = SizeOf(propInfo.PropertyType); if (t_size == -1) { size = -1; break; } size += t_size; } } } if (!type_size.ContainsKey(type)) { type_size.Add(type, size); } return size; } public static void Gen(IEnumerable<Type> wraps, IEnumerable<Type> gc_optimze_list, IEnumerable<Type> itf_bridges, string save_path) { templateCache.Clear(); Directory.CreateDirectory(save_path); GenWrap(wraps, save_path); GenWrapPusher(gc_optimze_list.Concat(wraps.Where(type=>type.IsEnum)).Distinct(), save_path); GenPackUnpack(gc_optimze_list.Where(type => !type.IsPrimitive && SizeOf(type) != -1), save_path); GenInterfaceBridge(itf_bridges, save_path); } public static void GenCodeForClass(bool minimum = false) { var warp_types = minimum ? new List<Type>() : LuaCallCSharp; var itf_bridges_types = CSharpCallLua.Where(type => type.IsInterface).Distinct(); Gen(warp_types, GCOptimizeList, itf_bridges_types, GeneratorConfig.common_path); } #if XLUA_GENERAL public static void GenAll(XLuaTemplates templates, IEnumerable<Type> all_types) { var start = DateTime.Now; Directory.CreateDirectory(GeneratorConfig.common_path); templateRef = templates; GetGenConfig(all_types.Where(type => !type.IsGenericTypeDefinition)); luaenv.DoString("require 'TemplateCommon'"); var gen_push_types_setter = luaenv.Global.Get<LuaFunction>("SetGenPushAndUpdateTypes"); gen_push_types_setter.Call(GCOptimizeList.Where(t => !t.IsPrimitive && SizeOf(t) != -1).Concat(LuaCallCSharp.Where(t => t.IsEnum)).Distinct().ToList()); var xlua_classes_setter = luaenv.Global.Get<LuaFunction>("SetXLuaClasses"); xlua_classes_setter.Call(Utils.GetAllTypes().Where(t => t.Namespace == "XLua").ToList()); GenDelegateBridges(all_types); GenEnumWraps(); GenCodeForClass(); GenLuaRegister(); Console.WriteLine("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); luaenv.Dispose(); } #endif #if !XLUA_GENERAL static void callCustomGen() { foreach (var method in (from type in Utils.GetAllTypes() from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) where method.IsDefined(typeof(GenCodeMenuAttribute), false) select method)) { method.Invoke(null, new object[] { }); } } [MenuItem("XLua/Generate Code", false, 1)] public static void GenAll() { var start = DateTime.Now; Directory.CreateDirectory(GeneratorConfig.common_path); GetGenConfig(Utils.GetAllTypes()); luaenv.DoString("require 'TemplateCommon'"); var gen_push_types_setter = luaenv.Global.Get<LuaFunction>("SetGenPushAndUpdateTypes"); gen_push_types_setter.Call(GCOptimizeList.Where(t => !t.IsPrimitive && SizeOf(t) != -1).Concat(LuaCallCSharp.Where(t => t.IsEnum)).Distinct().ToList()); var xlua_classes_setter = luaenv.Global.Get<LuaFunction>("SetXLuaClasses"); xlua_classes_setter.Call(Utils.GetAllTypes().Where(t => t.Namespace == "XLua").ToList()); GenDelegateBridges(Utils.GetAllTypes(false)); GenEnumWraps(); GenCodeForClass(); GenLuaRegister(); callCustomGen(); Debug.Log("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); AssetDatabase.Refresh(); } [MenuItem("XLua/Clear Generated Code", false, 2)] public static void ClearAll() { clear(GeneratorConfig.common_path); } public delegate IEnumerable<CustomGenTask> GetTasks(LuaEnv lua_env, UserConfig user_cfg); public static void CustomGen(string template_src, GetTasks get_tasks) { GetGenConfig(Utils.GetAllTypes()); LuaFunction template = XLua.TemplateEngine.LuaTemplate.Compile(luaenv, template_src); foreach (var gen_task in get_tasks(luaenv, new UserConfig() { LuaCallCSharp = LuaCallCSharp, CSharpCallLua = CSharpCallLua, ReflectionUse = ReflectionUse })) { LuaTable meta = luaenv.NewTable(); meta.Set("__index", luaenv.Global); gen_task.Data.SetMetaTable(meta); meta.Dispose(); try { string genCode = XLua.TemplateEngine.LuaTemplate.Execute(template, gen_task.Data); gen_task.Output.Write(genCode); gen_task.Output.Flush(); } catch (Exception e) { Debug.LogError("gen file fail! template=" + template_src + ", err=" + e.Message + ", stack=" + e.StackTrace); } finally { gen_task.Output.Close(); } } } #endif private static bool isSupportedGenericMethod(MethodInfo method) { if (!method.ContainsGenericParameters) return true; var methodParameters = method.GetParameters(); var _hasGenericParameter = false; for (var i = 0; i < methodParameters.Length; i++) { var parameterType = methodParameters[i].ParameterType; if (!isSupportGenericParameter(parameterType, true, ref _hasGenericParameter)) return false; } return _hasGenericParameter; } private static bool isSupportGenericParameter(Type parameterType,bool checkConstraint, ref bool _hasGenericParameter) { if (parameterType.IsGenericParameter) { if (!checkConstraint) return false; var parameterConstraints = parameterType.GetGenericParameterConstraints(); if (parameterConstraints.Length == 0) return false; foreach (var parameterConstraint in parameterConstraints) { if (!parameterConstraint.IsClass || (parameterConstraint == typeof(ValueType)) || Generator.hasGenericParameter(parameterConstraint)) return false; } _hasGenericParameter = true; } else if(parameterType.IsGenericType()) { foreach (var argument in parameterType.GetGenericArguments()) { if (!isSupportGenericParameter(argument,false, ref _hasGenericParameter)) return false; } } return true; } #if !XLUA_GENERAL [UnityEditor.Callbacks.PostProcessScene] public static void CheckGenrate() { if (EditorApplication.isCompiling || Application.isPlaying) { return; } if (!DelegateBridge.Gen_Flag) { throw new InvalidOperationException("Code has not been genrated, may be not work in phone!"); } } #endif } }
45.004164
354
0.510139
[ "BSD-3-Clause" ]
dongyanyan/xLua
Assets/XLua/Src/Editor/Generator.cs
75,790
C#
using LiteDB; namespace ttime { public class DataFormatVersion { public ObjectId Id { get; set; } public int Version { get; set; } } }
16.4
40
0.591463
[ "MIT" ]
nickdurcholz/ttime
ttime/DataFormatVersion.cs
166
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.IO.Ports; using System.IO; namespace Arduno2 { class Program { static void Main(string[] args) { //start here ArduinoControllerApp app = new ArduinoControllerApp(); app.SetComPort(); app.Run(); } } public class ArduinoControllerApp { SerialPort currentPort; public void SetComPort() { string[] ports = SerialPort.GetPortNames(); //for test only: //hardcode: we select 1st port as arduno port if (ports.Length == 0) { return; } //----------------------------------------- // currentPort = new SerialPort(ports[0], 9600); } public void Run() { currentPort.Open(); int j = 20; while (j > 0) { if ((j % 2) == 0) { currentPort.Write("0"); } else { currentPort.Write("1"); } Thread.Sleep(1000); j--; } currentPort.Close(); } } }
21.47619
66
0.408721
[ "MIT" ]
Thitipun/Arduino-AutomaticMedicBox
ArdunoComm/Arduno2/Program.cs
1,355
C#
using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; namespace Onvif.Core.Client.Security { public class SoapSecurityHeaderInspector : IClientMessageInspector { readonly string username; readonly string password; readonly TimeSpan time_shift; public SoapSecurityHeaderInspector (string username, string password, TimeSpan timeShift) { this.username = username; this.password = password; time_shift = timeShift; } public void AfterReceiveReply (ref Message reply, object correlationState) { } public object BeforeSendRequest (ref Message request, IClientChannel channel) { request.Headers.Add (new SoapSecurityHeader (username, password, time_shift)); return null; } } }
24.34375
91
0.774069
[ "MIT" ]
Jazea/Jazea.Edge
Client/Security/SoapSecurityHeaderInspector.cs
779
C#
using System; using System.Collections.Generic; using System.Text; namespace ETModel { [ObjectSystem] public class RayUnitComponentAwakeSystem : AwakeSystem<RayUnitComponent> { public override void Awake(RayUnitComponent self) { self.Awake(); } } public class RayUnitComponent : Component { public static RayUnitComponent Instance { get; set; } public void Awake() { Instance = this; } public Unit target { get; set; } } }
18.793103
76
0.6
[ "MIT" ]
xfs81150082/TumoET
Server/Model/Tumo/Components/Units/RayUnitComponent.cs
547
C#
using System; using System.Linq; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace UITests.Windows_UI_Xaml_Controls.FrameTests; public sealed partial class FrameTests_RedPage : Page { public FrameTests_RedPage() { this.InitializeComponent(); } /// <inheritdoc /> protected override void OnTapped(TappedRoutedEventArgs e) => e.Handled = true; }
19.894737
58
0.769841
[ "Apache-2.0" ]
HavenDV/uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/FrameTests/FrameTests_RedPage.xaml.cs
380
C#
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.IO; using Klocman.Resources; using Klocman.Tools; using UninstallTools.Properties; namespace UninstallTools.Startup.Normal { /// <summary> /// Starup entries stored in Startup folders and Run/RunOnce registry keys /// </summary> public sealed class StartupEntry : StartupEntryBase { internal bool AllUsersStore; internal bool DisabledStore; internal StartupEntry(StartupPointData dataPoint, string fileName, string targetString) { AllUsersStore = dataPoint.AllUsers; IsRegKey = dataPoint.IsRegKey; IsRunOnce = dataPoint.IsRunOnce; EntryLongName = fileName; ParentShortName = dataPoint.Name; ParentLongName = dataPoint.Path?.TrimEnd('\\'); Command = targetString ?? string.Empty; if (!string.IsNullOrEmpty(EntryLongName)) ProgramName = IsRegKey ? EntryLongName : Path.GetFileNameWithoutExtension(EntryLongName); if (!string.IsNullOrEmpty(targetString)) { CommandFilePath = ProcessCommandString(Command); if (CommandFilePath != null) FillInformationFromFile(CommandFilePath); if (string.IsNullOrEmpty(ProgramName)) ProgramName = ProgramNameTrimmed; } if (string.IsNullOrEmpty(ProgramName)) ProgramName = targetString ?? dataPoint.Name ?? CommonStrings.Unknown; if (string.IsNullOrEmpty(ProgramNameTrimmed)) ProgramNameTrimmed = StringTools.StripStringFromVersionNumber(ProgramName); } /// <summary> /// True if the entry is not processed during startup. /// It is stored in the backup reg key and optionally backup directory if it's a link file. /// </summary> public override bool Disabled { get { return DisabledStore; } set { if (value != DisabledStore) { if (value) { StartupEntryManager.Disable(this); } else { StartupEntryManager.Enable(this); } DisabledStore = value; } } } /// <summary> /// True if this entry is executed during logon of all users, false if it is only for the current user. /// </summary> public bool AllUsers { get { return AllUsersStore; } set { if (AllUsersStore != value) { StartupEntryManager.SetAllUsers(this, value); } } } /// <summary> /// True if entry is a registry value, false if it's a link file /// </summary> public bool IsRegKey { get; internal set; } /// <summary> /// True if the entry will be removed after running /// </summary> public bool IsRunOnce { get; internal set; } /// <summary> /// Filename of the link (with extension), or name of the registry value. /// </summary> public override string EntryLongName { get; protected set; } /// <summary> /// Full path to the link file backup /// </summary> internal string BackupPath { get; set; } /// <summary> /// Delete this startup entry from the system /// </summary> public override void Delete() { StartupEntryManager.Delete(this); } /// <summary> /// Check if the startup entry still exists in registry or on disk. /// If the entry is disabled, but it exists in the backup store, this method will return true. /// </summary> public override bool StillExists() { try { if (Disabled) return StartupEntryManager.DisableFunctions.StillExists(this); if (!IsRegKey) return File.Exists(FullLongName); using (var key = RegistryTools.OpenRegistryKey(ParentLongName)) return !string.IsNullOrEmpty(key.GetValue(EntryLongName) as string); } catch { return false; } } //TODO temporary hack internal void SetParentFancyName(string newValue) { ParentShortName = newValue; } //TODO temporary hack internal void SetParentLongName(string newValue) { ParentLongName = newValue; } /// <summary> /// $"{ProgramName} | {Company} | {ParentLongName} | {Command}" /// </summary> public override string ToLongString() { return $"{ProgramName} | {Company} | {ParentLongName} | {Command}"; } public override void CreateBackup(string backupPath) { StartupEntryManager.CreateBackup(this, backupPath); } } }
32.797619
116
0.520327
[ "Apache-2.0" ]
swipswaps/Bulk-Crap-Uninstaller
source/UninstallTools/Startup/Normal/StartupEntry.cs
5,510
C#
using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApp.Operations; using WebApp.Providers.Templates; namespace AzureRenderHub.WebApp.Arm.Deploying { public class DeploymentCoordinator : IDeploymentCoordinator { private readonly ITemplateProvider _templateProvider; private readonly IManagementClientProvider _managementClientProvider; public DeploymentCoordinator( ITemplateProvider templateProvider, IManagementClientProvider managementClientProvider) { _templateProvider = templateProvider; _managementClientProvider = managementClientProvider; } public async Task<Deployment> BeginDeploymentAsync(IDeployable deployment) { using (var client = await _managementClientProvider.CreateResourceManagementClient(deployment.SubscriptionId)) { await client.ResourceGroups.CreateOrUpdateAsync( deployment.ResourceGroupName, new ResourceGroup { Location = deployment.Location }); var templateParams = deployment.DeploymentParameters; var properties = new Microsoft.Azure.Management.ResourceManager.Models.Deployment { Properties = new DeploymentProperties { Template = await _templateProvider.GetTemplate(deployment.TemplateName), Parameters = _templateProvider.GetParameters(templateParams), Mode = DeploymentMode.Incremental } }; // Start the ARM deployment var deploymentResult = await client.Deployments.BeginCreateOrUpdateAsync( deployment.ResourceGroupName, deployment.DeploymentName, properties); return ToDeploymentStatus(deploymentResult); } } public async Task<Deployment> GetDeploymentAsync(IDeployable deployment) { using (var client = await _managementClientProvider.CreateResourceManagementClient(deployment.SubscriptionId)) { return await GetDeploymentInnerAsync(deployment); } } public async Task<Deployment> WaitForCompletionAsync(IDeployable deployment) { using (var client = await _managementClientProvider.CreateResourceManagementClient(deployment.SubscriptionId)) { var deploymentResult = await GetDeploymentInnerAsync(deployment); while (deploymentResult.ProvisioningState == ProvisioningState.Running || deploymentResult.ProvisioningState == ProvisioningState.Accepted) { await Task.Delay(2000); deploymentResult = await GetDeploymentInnerAsync(deployment); } return deploymentResult; } } private async Task<Deployment> GetDeploymentInnerAsync(IDeployable deployment) { using (var client = await _managementClientProvider.CreateResourceManagementClient(deployment.SubscriptionId)) { var deploymentResult = await client.Deployments.GetAsync( deployment.ResourceGroupName, deployment.DeploymentName); IEnumerable<DeploymentOperation> failedOps = null; if (deploymentResult.Properties.ProvisioningState == "Failed") { var operation = await client.DeploymentOperations.ListAsync( deployment.ResourceGroupName, deployment.DeploymentName); failedOps = operation.Where(op => op.Properties.ProvisioningState == "Failed"); } return ToDeploymentStatus(deploymentResult, failedOps); } } private Deployment ToDeploymentStatus(DeploymentExtended deployment, IEnumerable<DeploymentOperation> failedOps = null) { string errors = null; if (failedOps != null && failedOps.Any()) { errors = string.Join("\n", failedOps.Select(ToErrorString)); } Enum.TryParse<ProvisioningState>(deployment.Properties.ProvisioningState, out var deploymentState); return new Deployment { ProvisioningState = deploymentState, Error = errors, }; } private static string ToErrorString(DeploymentOperation op) { return $"Code={op.Properties.StatusCode}; Message={op.Properties.StatusMessage}; Resource={op.Properties.TargetResource}"; } } }
40.707317
134
0.618334
[ "MIT" ]
Azure/azure-render-farm-manager
src/AzureRenderHub/AzureRenderHub.WebApp/Arm/Deploying/DeploymentCoordinator.cs
5,009
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph { using System.Text.Json.Serialization; /// <summary> /// The enum AndroidDeviceOwnerPlayStoreMode. /// </summary> [JsonConverter(typeof(JsonStringEnumConverter))] public enum AndroidDeviceOwnerPlayStoreMode { /// <summary> /// Not Configured /// </summary> NotConfigured = 0, /// <summary> /// Allow List /// </summary> AllowList = 1, /// <summary> /// Block List /// </summary> BlockList = 2, } }
26.307692
153
0.503899
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/AndroidDeviceOwnerPlayStoreMode.cs
1,026
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace Demo.Shared.Models.User { public class RegisterRequest { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] public string Name { get; set; } [Required] public string PhoneNumber { get; set; } } }
28.457143
125
0.631526
[ "MIT" ]
MukeshBisht/Demo
Demo.Shared/Models/User/RegisterRequest.cs
998
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.Immutable; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable { public static readonly MessageProvider Instance = new MessageProvider(); static MessageProvider() { ObjectBinder.RegisterTypeReader(typeof(MessageProvider), r => Instance); } private MessageProvider() { } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance } public override DiagnosticSeverity GetSeverity(int code) { return ErrorFacts.GetSeverity((ErrorCode)code); } public override string LoadMessage(int code, CultureInfo language) { return ErrorFacts.GetMessage((ErrorCode)code, language); } public override LocalizableString GetMessageFormat(int code) { return ErrorFacts.GetMessageFormat((ErrorCode)code); } public override LocalizableString GetDescription(int code) { return ErrorFacts.GetDescription((ErrorCode)code); } public override LocalizableString GetTitle(int code) { return ErrorFacts.GetTitle((ErrorCode)code); } public override string GetHelpLink(int code) { return ErrorFacts.GetHelpLink((ErrorCode)code); } public override string GetCategory(int code) { return ErrorFacts.GetCategory((ErrorCode)code); } public override string CodePrefix { get { return "CS"; } } // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages. public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) { return String.Format(culture, "{0} {1}", severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning", id); } public override int GetWarningLevel(int code) { return ErrorFacts.GetWarningLevel((ErrorCode)code); } public override Type ErrorCodeType { get { return typeof(ErrorCode); } } public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) { var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty); return new CSDiagnostic(info, location); } public override Diagnostic CreateDiagnostic(DiagnosticInfo info) { return new CSDiagnostic(info, Location.None); } public override string GetErrorDisplayString(ISymbol symbol) { // show extra info for assembly if possible such as version, public key token etc. if (symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.Namespace) { return symbol.ToString(); } return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); } public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) { bool hasPragmaSuppression; return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, true, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, diagnosticInfo.Category, options.WarningLevel, ((CSharpCompilationOptions)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, out hasPragmaSuppression); } public override int ERR_FailedToCreateTempFile => (int)ErrorCode.ERR_CantMakeTempFile; public override int ERR_MultipleAnalyzerConfigsInSameDir => (int)ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir; // command line: public override int ERR_ExpectedSingleScript => (int)ErrorCode.ERR_ExpectedSingleScript; public override int ERR_OpenResponseFile => (int)ErrorCode.ERR_OpenResponseFile; public override int ERR_InvalidPathMap => (int)ErrorCode.ERR_InvalidPathMap; public override int FTL_InvalidInputFileName => (int)ErrorCode.FTL_InvalidInputFileName; public override int ERR_FileNotFound => (int)ErrorCode.ERR_FileNotFound; public override int ERR_NoSourceFile => (int)ErrorCode.ERR_NoSourceFile; public override int ERR_CantOpenFileWrite => (int)ErrorCode.ERR_CantOpenFileWrite; public override int ERR_OutputWriteFailed => (int)ErrorCode.ERR_OutputWriteFailed; public override int WRN_NoConfigNotOnCommandLine => (int)ErrorCode.WRN_NoConfigNotOnCommandLine; public override int ERR_BinaryFile => (int)ErrorCode.ERR_BinaryFile; public override int WRN_AnalyzerCannotBeCreated => (int)ErrorCode.WRN_AnalyzerCannotBeCreated; public override int WRN_NoAnalyzerInAssembly => (int)ErrorCode.WRN_NoAnalyzerInAssembly; public override int WRN_UnableToLoadAnalyzer => (int)ErrorCode.WRN_UnableToLoadAnalyzer; public override int INF_UnableToLoadSomeTypesInAnalyzer => (int)ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer; public override int ERR_CantReadRulesetFile => (int)ErrorCode.ERR_CantReadRulesetFile; public override int ERR_CompileCancelled => (int)ErrorCode.ERR_CompileCancelled; // parse options: public override int ERR_BadSourceCodeKind => (int)ErrorCode.ERR_BadSourceCodeKind; public override int ERR_BadDocumentationMode => (int)ErrorCode.ERR_BadDocumentationMode; // compilation options: public override int ERR_BadCompilationOptionValue => (int)ErrorCode.ERR_BadCompilationOptionValue; public override int ERR_MutuallyExclusiveOptions => (int)ErrorCode.ERR_MutuallyExclusiveOptions; // emit options: public override int ERR_InvalidDebugInformationFormat => (int)ErrorCode.ERR_InvalidDebugInformationFormat; public override int ERR_InvalidOutputName => (int)ErrorCode.ERR_InvalidOutputName; public override int ERR_InvalidFileAlignment => (int)ErrorCode.ERR_InvalidFileAlignment; public override int ERR_InvalidSubsystemVersion => (int)ErrorCode.ERR_InvalidSubsystemVersion; public override int ERR_InvalidInstrumentationKind => (int)ErrorCode.ERR_InvalidInstrumentationKind; public override int ERR_InvalidHashAlgorithmName => (int)ErrorCode.ERR_InvalidHashAlgorithmName; // reference manager: public override int ERR_MetadataFileNotAssembly => (int)ErrorCode.ERR_ImportNonAssembly; public override int ERR_MetadataFileNotModule => (int)ErrorCode.ERR_AddModuleAssembly; public override int ERR_InvalidAssemblyMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_InvalidModuleMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningAssemblyFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningModuleFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_MetadataFileNotFound => (int)ErrorCode.ERR_NoMetadataFile; public override int ERR_MetadataReferencesNotSupported => (int)ErrorCode.ERR_MetadataReferencesNotSupported; public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => (int)ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage; public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(), equivalentReference.Display ?? equivalentIdentity.GetDisplayName()); } public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName()); } // signing: public override int ERR_PublicKeyFileFailure => (int)ErrorCode.ERR_PublicKeyFileFailure; public override int ERR_PublicKeyContainerFailure => (int)ErrorCode.ERR_PublicKeyContainerFailure; public override int ERR_OptionMustBeAbsolutePath => (int)ErrorCode.ERR_OptionMustBeAbsolutePath; // resources: public override int ERR_CantReadResource => (int)ErrorCode.ERR_CantReadResource; public override int ERR_CantOpenWin32Resource => (int)ErrorCode.ERR_CantOpenWin32Res; public override int ERR_CantOpenWin32Manifest => (int)ErrorCode.ERR_CantOpenWin32Manifest; public override int ERR_CantOpenWin32Icon => (int)ErrorCode.ERR_CantOpenIcon; public override int ERR_ErrorBuildingWin32Resource => (int)ErrorCode.ERR_ErrorBuildingWin32Resources; public override int ERR_BadWin32Resource => (int)ErrorCode.ERR_BadWin32Res; public override int ERR_ResourceFileNameNotUnique => (int)ErrorCode.ERR_ResourceFileNameNotUnique; public override int ERR_ResourceNotUnique => (int)ErrorCode.ERR_ResourceNotUnique; public override int ERR_ResourceInModule => (int)ErrorCode.ERR_CantRefResource; // pseudo-custom attributes: public override int ERR_PermissionSetAttributeFileReadError => (int)ErrorCode.ERR_PermissionSetAttributeFileReadError; // PDB Writer: public override int ERR_EncodinglessSyntaxTree => (int)ErrorCode.ERR_EncodinglessSyntaxTree; public override int WRN_PdbUsingNameTooLong => (int)ErrorCode.WRN_DebugFullNameTooLong; public override int WRN_PdbLocalNameTooLong => (int)ErrorCode.WRN_PdbLocalNameTooLong; public override int ERR_PdbWritingFailed => (int)ErrorCode.FTL_DebugEmitFailure; // PE Writer: public override int ERR_MetadataNameTooLong => (int)ErrorCode.ERR_MetadataNameTooLong; public override int ERR_EncReferenceToAddedMember => (int)ErrorCode.ERR_EncReferenceToAddedMember; public override int ERR_TooManyUserStrings => (int)ErrorCode.ERR_TooManyUserStrings; public override int ERR_PeWritingFailure => (int)ErrorCode.ERR_PeWritingFailure; public override int ERR_ModuleEmitFailure => (int)ErrorCode.ERR_ModuleEmitFailure; public override int ERR_EncUpdateFailedMissingAttribute => (int)ErrorCode.ERR_EncUpdateFailedMissingAttribute; public override int ERR_InvalidDebugInfo => (int)ErrorCode.ERR_InvalidDebugInfo; public override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } public override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, node.ArgumentList.Arguments[namedArgumentIndex].Location, parameterName); } public override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, node.ArgumentList.Arguments[namedArgumentIndex].Location); } public override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } public override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } public override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, node.Name.Location, parameterName); } public override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, node.Name.Location, parameterName1, parameterName2); } public override int ERR_BadAssemblyName => (int)ErrorCode.ERR_BadAssemblyName; } }
55.333333
245
0.707307
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/CSharp/Portable/Errors/MessageProvider.cs
15,274
C#
using System; using System.Drawing; using System.ComponentModel; using System.Collections.Generic; using FastReport.Utils; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.Drawing.Design; namespace FastReport { /// <summary> /// Base class for all bands. /// </summary> public abstract partial class BandBase : BreakableComponent, IParent { #region Fields private ChildBand child; private ReportComponentCollection objects; private FloatCollection guides; private bool startNewPage; private bool firstRowStartsNewPage; private bool printOnBottom; private bool keepChild; private string outlineExpression; private int rowNo; private int absRowNo; private bool isFirstRow; private bool isLastRow; private bool repeated; private bool updatingLayout; private bool flagUseStartNewPage; private bool flagCheckFreeSpace; private bool flagMustBreak; private int savedOriginalObjectsCount; private float reprintOffset; private string beforeLayoutEvent; private string afterLayoutEvent; private int repeatBandNTimes = 1; #endregion #region Properties /// <summary> /// This event occurs before the band layouts its child objects. /// </summary> public event EventHandler BeforeLayout; /// <summary> /// This event occurs after the child objects layout was finished. /// </summary> public event EventHandler AfterLayout; /// <summary> /// Gets or sets a value indicating that the band should be printed from a new page. /// </summary> /// <remarks> /// New page is not generated when printing very first group or data row. This is made to avoid empty /// first page. /// </remarks> [DefaultValue(false)] [Category("Behavior")] public bool StartNewPage { get { return startNewPage; } set { startNewPage = value; } } /// <summary> /// Gets or sets a value that determines the number of repetitions of the same band. /// </summary> [Category("Behavior")] [DefaultValue(1)] public int RepeatBandNTimes { get { return repeatBandNTimes; } set { repeatBandNTimes = value; } } /// <summary> /// Gets or sets a value indicating that the first row can start a new report page. /// </summary> /// <remarks> /// Use this property if <see cref="StartNewPage"/> is set to <b>true</b>. Normally the new page /// is not started when printing the first data row, to avoid empty first page. /// </remarks> [DefaultValue(true)] [Category("Behavior")] public bool FirstRowStartsNewPage { get { return firstRowStartsNewPage; } set { firstRowStartsNewPage = value; } } /// <summary> /// Gets or sets a value indicating that the band should be printed on the page bottom. /// </summary> [DefaultValue(false)] [Category("Behavior")] public bool PrintOnBottom { get { return printOnBottom; } set { printOnBottom = value; } } /// <summary> /// Gets or sets a value indicating that the band should be printed together with its child band. /// </summary> [DefaultValue(false)] [Category("Behavior")] public bool KeepChild { get { return keepChild; } set { keepChild = value; } } /// <summary> /// Gets or sets an outline expression. /// </summary> /// <remarks> /// <para> /// Outline is a tree control displayed in the preview window. It represents the prepared report structure. /// Each outline node can be clicked to navigate to the item in the prepared report. /// </para> /// <para> /// To create the outline, set this property to any valid expression that represents the outline node text. /// This expression will be calculated when band is about to print, and its value will be added to the /// outline. Thus, nodes' hierarchy in the outline is similar to the bands' hierarchy /// in a report. That means there will be the main and subordinate outline nodes, corresponding /// to the main and subordinate bands in a report (a report with two levels of data or with groups can /// exemplify the point). /// </para> /// </remarks> [Category("Navigation")] [Editor("FastReport.TypeEditors.ExpressionEditor, FastReport", typeof(UITypeEditor))] public string OutlineExpression { get { return outlineExpression; } set { outlineExpression = value; } } /// <summary> /// Gets or sets a child band that will be printed right after this band. /// </summary> /// <remarks> /// Typical use of child band is to print several objects that can grow or shrink. It also can be done /// using the shift feature (via <see cref="ShiftMode"/> property), but in some cases it's not possible. /// </remarks> [Browsable(false)] public ChildBand Child { get { return child; } set { SetProp(child, value); child = value; } } /// <summary> /// Gets a collection of report objects belongs to this band. /// </summary> [Browsable(false)] public ReportComponentCollection Objects { get { return objects; } } /// <summary> /// Gets a value indicating that band is reprinted on a new page. /// </summary> /// <remarks> /// This property is applicable to the <b>DataHeaderBand</b> and <b>GroupHeaderBand</b> only. /// It returns <b>true</b> if its <b>RepeatOnAllPages</b> property is <b>true</b> and band is /// reprinted on a new page. /// </remarks> [Browsable(false)] public bool Repeated { get { return repeated; } set { repeated = value; // set this flag for child bands as well BandBase child = Child; while (child != null) { child.Repeated = value; child = child.Child; } } } /// <summary> /// Gets or sets a script event name that will be fired before the band layouts its child objects. /// </summary> [Category("Build")] public string BeforeLayoutEvent { get { return beforeLayoutEvent; } set { beforeLayoutEvent = value; } } /// <summary> /// Gets or sets a script event name that will be fired after the child objects layout was finished. /// </summary> [Category("Build")] public string AfterLayoutEvent { get { return afterLayoutEvent; } set { afterLayoutEvent = value; } } /// <inheritdoc/> public override float AbsLeft { get { return IsRunning ? base.AbsLeft : Left; } } /// <inheritdoc/> public override float AbsTop { get { return IsRunning ? base.AbsTop : Top; } } /// <summary> /// Gets or sets collection of guide lines for this band. /// </summary> [Browsable(false)] public FloatCollection Guides { get { return guides; } set { guides = value; } } /// <summary> /// Gets a row number (the same value returned by the "Row#" system variable). /// </summary> /// <remarks> /// This property can be used when running a report. It may be useful to print hierarchical /// row numbers in a master-detail report, like this: /// <para/>1.1 /// <para/>1.2 /// <para/>2.1 /// <para/>2.2 /// <para/>To do this, put the Text object on a detail data band with the following text in it: /// <para/>[Data1.RowNo].[Data2.RowNo] /// </remarks> [Browsable(false)] public int RowNo { get { return rowNo; } set { rowNo = value; if (Child != null) Child.RowNo = value; } } /// <summary> /// Gets an absolute row number (the same value returned by the "AbsRow#" system variable). /// </summary> [Browsable(false)] public int AbsRowNo { get { return absRowNo; } set { absRowNo = value; if (Child != null) Child.AbsRowNo = value; } } /// <summary> /// Gets a value indicating that this is the first data row. /// </summary> [Browsable(false)] public bool IsFirstRow { get { return isFirstRow; } set { isFirstRow = value; } } /// <summary> /// Gets a value indicating that this is the last data row. /// </summary> [Browsable(false)] public bool IsLastRow { get { return isLastRow; } set { isLastRow = value; } } internal bool HasBorder { get { return !Border.Equals(new Border()); } } internal bool HasFill { get { return !Fill.IsTransparent; } } internal DataBand ParentDataBand { get { Base c = Parent; while (c != null) { if (c is DataBand) return c as DataBand; if (c is ReportPage && (c as ReportPage).Subreport != null) c = (c as ReportPage).Subreport; c = c.Parent; } return null; } } internal bool FlagUseStartNewPage { get { return flagUseStartNewPage; } set { flagUseStartNewPage = value; } } internal bool FlagCheckFreeSpace { get { return flagCheckFreeSpace; } set { flagCheckFreeSpace = value; // set flag for child bands as well BandBase child = Child; while (child != null) { child.FlagCheckFreeSpace = value; child = child.Child; } } } internal bool FlagMustBreak { get { return flagMustBreak; } set { flagMustBreak = value; } } internal float ReprintOffset { get { return reprintOffset; } set { reprintOffset = value; } } internal float PageWidth { get { ReportPage page = Page as ReportPage; if (page != null) return page.WidthInPixels - (page.LeftMargin + page.RightMargin) * Units.Millimeters; return 0; } } #endregion #region IParent Members /// <inheritdoc/> public virtual void GetChildObjects(ObjectCollection list) { foreach (ReportComponentBase obj in objects) { list.Add(obj); } if (!IsRunning) list.Add(child); } /// <inheritdoc/> public virtual bool CanContain(Base child) { if (IsRunning) return child is ReportComponentBase; return ((child is ReportComponentBase && !(child is BandBase)) || child is ChildBand); } /// <inheritdoc/> public virtual void AddChild(Base child) { if (child is ChildBand && !IsRunning) Child = child as ChildBand; else objects.Add(child as ReportComponentBase); } /// <inheritdoc/> public virtual void RemoveChild(Base child) { if (child is ChildBand && this.child == child as ChildBand) Child = null; else objects.Remove(child as ReportComponentBase); } /// <inheritdoc/> public virtual int GetChildOrder(Base child) { return objects.IndexOf(child as ReportComponentBase); } /// <inheritdoc/> public virtual void SetChildOrder(Base child, int order) { int oldOrder = child.ZOrder; if (oldOrder != -1 && order != -1 && oldOrder != order) { if (order > objects.Count) order = objects.Count; if (oldOrder <= order) order--; objects.Remove(child as ReportComponentBase); objects.Insert(order, child as ReportComponentBase); UpdateLayout(0, 0); } } /// <inheritdoc/> public virtual void UpdateLayout(float dx, float dy) { if (updatingLayout) return; updatingLayout = true; try { RectangleF remainingBounds = new RectangleF(0, 0, Width, Height); remainingBounds.Width += dx; remainingBounds.Height += dy; foreach (ReportComponentBase c in Objects) { if ((c.Anchor & AnchorStyles.Right) != 0) { if ((c.Anchor & AnchorStyles.Left) != 0) c.Width += dx; else c.Left += dx; } else if ((c.Anchor & AnchorStyles.Left) == 0) { c.Left += dx / 2; } if ((c.Anchor & AnchorStyles.Bottom) != 0) { if ((c.Anchor & AnchorStyles.Top) != 0) c.Height += dy; else c.Top += dy; } else if ((c.Anchor & AnchorStyles.Top) == 0) { c.Top += dy / 2; } switch (c.Dock) { case DockStyle.Left: c.Bounds = new RectangleF(remainingBounds.Left, remainingBounds.Top, c.Width, remainingBounds.Height); remainingBounds.X += c.Width; remainingBounds.Width -= c.Width; break; case DockStyle.Top: c.Bounds = new RectangleF(remainingBounds.Left, remainingBounds.Top, remainingBounds.Width, c.Height); remainingBounds.Y += c.Height; remainingBounds.Height -= c.Height; break; case DockStyle.Right: c.Bounds = new RectangleF(remainingBounds.Right - c.Width, remainingBounds.Top, c.Width, remainingBounds.Height); remainingBounds.Width -= c.Width; break; case DockStyle.Bottom: c.Bounds = new RectangleF(remainingBounds.Left, remainingBounds.Bottom - c.Height, remainingBounds.Width, c.Height); remainingBounds.Height -= c.Height; break; case DockStyle.Fill: c.Bounds = remainingBounds; remainingBounds.Width = 0; remainingBounds.Height = 0; break; } } } finally { updatingLayout = false; } } #endregion #region Public Methods /// <inheritdoc/> public override void Assign(Base source) { base.Assign(source); BandBase src = source as BandBase; Guides.Assign(src.Guides); StartNewPage = src.StartNewPage; FirstRowStartsNewPage = src.FirstRowStartsNewPage; PrintOnBottom = src.PrintOnBottom; KeepChild = src.KeepChild; OutlineExpression = src.OutlineExpression; BeforeLayoutEvent = src.BeforeLayoutEvent; AfterLayoutEvent = src.AfterLayoutEvent; RepeatBandNTimes = src.RepeatBandNTimes; } internal virtual void UpdateWidth() { // update band width. It is needed for anchor/dock ReportPage page = Page as ReportPage; if (page != null && !(page.UnlimitedWidth && IsDesigning)) { if (page.Columns.Count <= 1 || !IsColumnDependentBand) Width = PageWidth; } } internal void FixHeight() { float maxHeight = Height; foreach (ReportComponentBase c in Objects) { if (c.Bottom > maxHeight) maxHeight = c.Bottom; } if (maxHeight < 0) maxHeight = 0; Height = maxHeight; } internal void FixHeightWithComponentsShift(float deltaY) { float minTop = Height; float maxBottom = 0; float minHeight = Height; // Calculate minimum top of all components on this band. foreach (ReportComponentBase component in Objects) { if (component.Top < minTop) { minTop = component.Top; } } // Calculate maximum bottom of all components on this band. foreach (ReportComponentBase component in Objects) { if (component.Bottom > maxBottom) { maxBottom = component.Bottom; } } // Calculate minimum height of band with components shift. minHeight = maxBottom - minTop; // Minimum height with compenents shift can't be negative. if (minHeight < 0) { minHeight = 0; } // Prevent incorrect movement of objects when mouse moves too fast. if (minTop < deltaY) { deltaY = minTop; } // Size of band should be decreased. if (deltaY > 0) { // There is enough place to move components up. if (minTop > 0) { // Move all components up. foreach (ReportComponentBase component in Objects) { component.Top -= deltaY; } } } else { // Move all components down. foreach (ReportComponentBase component in Objects) { component.Top -= deltaY; } } // Height can't be less then minHeight. if (Height < minHeight) { Height = minHeight; } } /// <inheritdoc/> public override void Serialize(FRWriter writer) { BandBase c = writer.DiffObject as BandBase; base.Serialize(writer); if (writer.SerializeTo == SerializeTo.Preview) return; if (StartNewPage != c.StartNewPage) writer.WriteBool("StartNewPage", StartNewPage); if (FirstRowStartsNewPage != c.FirstRowStartsNewPage) writer.WriteBool("FirstRowStartsNewPage", FirstRowStartsNewPage); if (PrintOnBottom != c.PrintOnBottom) writer.WriteBool("PrintOnBottom", PrintOnBottom); if (KeepChild != c.KeepChild) writer.WriteBool("KeepChild", KeepChild); if (OutlineExpression != c.OutlineExpression) writer.WriteStr("OutlineExpression", OutlineExpression); if (Guides.Count > 0) writer.WriteValue("Guides", Guides); if (BeforeLayoutEvent != c.BeforeLayoutEvent) writer.WriteStr("BeforeLayoutEvent", BeforeLayoutEvent); if (AfterLayoutEvent != c.AfterLayoutEvent) writer.WriteStr("AfterLayoutEvent", AfterLayoutEvent); if (RepeatBandNTimes != c.RepeatBandNTimes) writer.WriteInt("RepeatBandNTimes", RepeatBandNTimes); } internal bool IsColumnDependentBand { get { BandBase b = this; if (b is ChildBand) { while (b is ChildBand) { b = b.Parent as BandBase; } } if (b is DataHeaderBand || b is DataBand || b is DataFooterBand || b is GroupHeaderBand || b is GroupFooterBand || b is ColumnHeaderBand || b is ColumnFooterBand || b is ReportSummaryBand) return true; return false; } } #endregion #region Report Engine /// <inheritdoc/> public override string[] GetExpressions() { List<string> expressions = new List<string>(); expressions.AddRange(base.GetExpressions()); if (!String.IsNullOrEmpty(OutlineExpression)) expressions.Add(OutlineExpression); return expressions.ToArray(); } /// <inheritdoc/> public override void SaveState() { base.SaveState(); savedOriginalObjectsCount = Objects.Count; SetRunning(true); SetDesigning(false); OnBeforePrint(EventArgs.Empty); foreach (ReportComponentBase obj in Objects) { obj.SaveState(); obj.SetRunning(true); obj.SetDesigning(false); obj.OnBeforePrint(EventArgs.Empty); } // apply even style if (RowNo % 2 == 0) { ApplyEvenStyle(); foreach (ReportComponentBase obj in Objects) { obj.ApplyEvenStyle(); } } } /// <inheritdoc/> public override void RestoreState() { OnAfterPrint(EventArgs.Empty); base.RestoreState(); while (Objects.Count > savedOriginalObjectsCount) { Objects[Objects.Count - 1].Dispose(); } SetRunning(false); foreach (ReportComponentBase obj in Objects) { obj.OnAfterPrint(EventArgs.Empty); obj.RestoreState(); obj.SetRunning(false); } } /// <inheritdoc/> public override float CalcHeight() { OnBeforeLayout(EventArgs.Empty); // sort objects by Top ReportComponentCollection sortedObjects = Objects.SortByTop(); // calc height of each object float[] heights = new float[sortedObjects.Count]; for (int i = 0; i < sortedObjects.Count; i++) { ReportComponentBase obj = sortedObjects[i]; float height = obj.Height; if (obj.Visible && (obj.CanGrow || obj.CanShrink)) { float height1 = obj.CalcHeight(); if ((obj.CanGrow && height1 > height) || (obj.CanShrink && height1 < height)) height = height1; } heights[i] = height; } // calc shift amounts float[] shifts = new float[sortedObjects.Count]; for (int i = 0; i < sortedObjects.Count; i++) { ReportComponentBase parent = sortedObjects[i]; float shift = heights[i] - parent.Height; if (shift == 0) continue; for (int j = i + 1; j < sortedObjects.Count; j++) { ReportComponentBase child = sortedObjects[j]; if (child.ShiftMode == ShiftMode.Never) continue; if (child.Top >= parent.Bottom - 1e-4) { if (child.ShiftMode == ShiftMode.WhenOverlapped && (child.Left > parent.Right - 1e-4 || parent.Left > child.Right - 1e-4)) continue; float parentShift = shifts[i]; float childShift = shifts[j]; if (shift > 0) childShift = Math.Max(shift + parentShift, childShift); else childShift = Math.Min(shift + parentShift, childShift); shifts[j] = childShift; } } } // update location and size of each component, calc max height float maxHeight = 0; for (int i = 0; i < sortedObjects.Count; i++) { ReportComponentBase obj = sortedObjects[i]; DockStyle saveDock = obj.Dock; obj.Dock = DockStyle.None; obj.Height = heights[i]; obj.Top += shifts[i]; if (obj.Visible && obj.Bottom > maxHeight) maxHeight = obj.Bottom; obj.Dock = saveDock; } if ((CanGrow && maxHeight > Height) || (CanShrink && maxHeight < Height)) Height = maxHeight; // perform grow to bottom foreach (ReportComponentBase obj in Objects) { if (obj.GrowToBottom) obj.Height = Height - obj.Top; } OnAfterLayout(EventArgs.Empty); return Height; } public void AddLastToFooter(BreakableComponent breakTo) { float maxTop = (AllObjects[0] as ComponentBase).Top; foreach (ComponentBase obj in AllObjects) if (obj.Top > maxTop && !(obj is DataFooterBand)) maxTop = obj.Top; float breakLine = maxTop; List<ReportComponentBase> pasteList = new List<ReportComponentBase>(); foreach (ReportComponentBase obj in Objects) if (obj.Bottom > breakLine) pasteList.Add(obj); int itemsBefore = breakTo.AllObjects.Count; foreach (ReportComponentBase obj in pasteList) { if (obj.Top < breakLine) { BreakableComponent breakComp = Activator.CreateInstance(obj.GetType()) as BreakableComponent; breakComp.AssignAll(obj); breakComp.Parent = breakTo; breakComp.CanGrow = true; breakComp.CanShrink = false; breakComp.Height -= breakLine - obj.Top; breakComp.Top = 0; obj.Height = breakLine - obj.Top; (obj as BreakableComponent).Break(breakComp); } else { obj.Top -= breakLine; obj.Parent = breakTo; continue; } } float minTop = (breakTo.AllObjects[0] as ComponentBase).Top; float maxBottom = 0; for (int i = itemsBefore; i < breakTo.AllObjects.Count; i++) if ((breakTo.AllObjects[i] as ComponentBase).Top < minTop && breakTo.AllObjects[i] is ReportComponentBase && !(breakTo.AllObjects[i] is Table.TableCell)) minTop = (breakTo.AllObjects[i] as ComponentBase).Top; for (int i = itemsBefore; i < breakTo.AllObjects.Count; i++) if ((breakTo.AllObjects[i] as ComponentBase).Bottom > maxBottom && breakTo.AllObjects[i] is ReportComponentBase && !(breakTo.AllObjects[i] is Table.TableCell)) maxBottom = (breakTo.AllObjects[i] as ComponentBase).Bottom; for (int i = 0; i < itemsBefore; i++) (breakTo.AllObjects[i] as ComponentBase).Top += maxBottom - minTop; breakTo.Height += maxBottom - minTop; Height -= maxBottom - minTop; } /// <inheritdoc/> public override bool Break(BreakableComponent breakTo) { // first we find the break line. It's a minimum Top coordinate of the object that cannot break. float breakLine = Height; bool breakLineFound = true; do { breakLineFound = true; foreach (ReportComponentBase obj in Objects) { bool canBreak = true; if (obj.Top < breakLine && obj.Bottom > breakLine) { canBreak = false; BreakableComponent breakable = obj as BreakableComponent; if (breakable != null && breakable.CanBreak) { using (BreakableComponent clone = Activator.CreateInstance(breakable.GetType()) as BreakableComponent) { clone.AssignAll(breakable); clone.Height = breakLine - clone.Top; // to allow access to the Report clone.Parent = breakTo; canBreak = clone.Break(null); } } } if (!canBreak) { breakLine = Math.Min(obj.Top, breakLine); // enumerate objects again breakLineFound = false; break; } } } while (!breakLineFound); // now break the components int i = 0; while (i < Objects.Count) { ReportComponentBase obj = Objects[i]; if (obj.Bottom > breakLine) { if (obj.Top < breakLine) { BreakableComponent breakComp = Activator.CreateInstance(obj.GetType()) as BreakableComponent; breakComp.AssignAll(obj); breakComp.Parent = breakTo; breakComp.CanGrow = true; breakComp.CanShrink = false; breakComp.Height -= breakLine - obj.Top; breakComp.Top = 0; obj.Height = breakLine - obj.Top; (obj as BreakableComponent).Break(breakComp); } else { obj.Top -= breakLine; obj.Parent = breakTo; continue; } } i++; } Height = breakLine; breakTo.Height -= breakLine; return Objects.Count > 0; } /// <inheritdoc/> public override void GetData() { base.GetData(); foreach (ReportComponentBase obj in Objects) { obj.GetData(); obj.OnAfterData(); // break the component if it is of BreakableComponent an has non-empty BreakTo property if (obj is BreakableComponent && (obj as BreakableComponent).BreakTo != null && (obj as BreakableComponent).BreakTo.GetType() == obj.GetType()) (obj as BreakableComponent).Break((obj as BreakableComponent).BreakTo); } OnAfterData(); } internal virtual bool IsEmpty() { return true; } private void AddBookmark(ReportComponentBase obj) { if (Report != null) Report.Engine.AddBookmark(obj.Bookmark); } internal void AddBookmarks() { AddBookmark(this); foreach (ReportComponentBase obj in Objects) { AddBookmark(obj); } } /// <inheritdoc/> public override void InitializeComponent() { base.InitializeComponent(); AbsRowNo = 0; } /// <summary> /// This method fires the <b>BeforeLayout</b> event and the script code connected to the <b>BeforeLayoutEvent</b>. /// </summary> /// <param name="e">Event data.</param> public void OnBeforeLayout(EventArgs e) { if (BeforeLayout != null) BeforeLayout(this, e); InvokeEvent(BeforeLayoutEvent, e); } /// <summary> /// This method fires the <b>AfterLayout</b> event and the script code connected to the <b>AfterLayoutEvent</b>. /// </summary> /// <param name="e">Event data.</param> public void OnAfterLayout(EventArgs e) { if (AfterLayout != null) AfterLayout(this, e); InvokeEvent(AfterLayoutEvent, e); } #endregion /// <summary> /// Initializes a new instance of the <see cref="BandBase"/> class with default settings. /// </summary> public BandBase() { objects = new ReportComponentCollection(this); guides = new FloatCollection(); beforeLayoutEvent = ""; afterLayoutEvent = ""; outlineExpression = ""; CanBreak = false; ShiftMode = ShiftMode.Never; if (BaseName.EndsWith("Band")) BaseName = ClassName.Remove(ClassName.IndexOf("Band")); SetFlags(Flags.CanMove | Flags.CanChangeOrder | Flags.CanChangeParent | Flags.CanCopy | Flags.CanGroup, false); FlagUseStartNewPage = true; FlagCheckFreeSpace = true; } } }
34.027804
175
0.486349
[ "MIT" ]
ammogcoder/FastReport
FastReport.Base/BandBase.cs
35,491
C#
using System; namespace Umbraco.Core.Services.Changes { [Flags] public enum ContentTypeChangeTypes : byte { None = 0, Create = 1, // item type has been created, no impact RefreshMain = 2, // changed, impacts content (adding property or composition does NOT) RefreshOther = 4, // changed, other changes Remove = 8 // item type has been removed } }
27
94
0.634568
[ "MIT" ]
AndersBrohus/Umbraco-CMS
src/Umbraco.Core/Services/Changes/ContentTypeChangeTypes.cs
407
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiClass(nativeType: typeof(aws.LambdaFunction), fullyQualifiedName: "aws.LambdaFunction", parametersJson: "[{\"name\":\"scope\",\"type\":{\"fqn\":\"constructs.Construct\"}},{\"name\":\"id\",\"type\":{\"primitive\":\"string\"}},{\"name\":\"config\",\"type\":{\"fqn\":\"aws.LambdaFunctionConfig\"}}]")] public class LambdaFunction : HashiCorp.Cdktf.TerraformResource { public LambdaFunction(Constructs.Construct scope, string id, aws.ILambdaFunctionConfig config): base(new DeputyProps(new object?[]{scope, id, config})) { } /// <summary>Used by jsii to construct an instance of this class from a Javascript-owned object reference</summary> /// <param name="reference">The Javascript-owned object reference</param> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] protected LambdaFunction(ByRefValue reference): base(reference) { } /// <summary>Used by jsii to construct an instance of this class from DeputyProps</summary> /// <param name="props">The deputy props</param> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] protected LambdaFunction(DeputyProps props): base(props) { } [JsiiMethod(name: "resetDeadLetterConfig")] public virtual void ResetDeadLetterConfig() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetDescription")] public virtual void ResetDescription() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetEnvironment")] public virtual void ResetEnvironment() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetFilename")] public virtual void ResetFilename() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetFileSystemConfig")] public virtual void ResetFileSystemConfig() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetKmsKeyArn")] public virtual void ResetKmsKeyArn() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetLayers")] public virtual void ResetLayers() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetMemorySize")] public virtual void ResetMemorySize() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetPublish")] public virtual void ResetPublish() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetReservedConcurrentExecutions")] public virtual void ResetReservedConcurrentExecutions() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetS3Bucket")] public virtual void ResetS3Bucket() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetS3Key")] public virtual void ResetS3Key() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetS3ObjectVersion")] public virtual void ResetS3ObjectVersion() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetSourceCodeHash")] public virtual void ResetSourceCodeHash() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetTags")] public virtual void ResetTags() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetTimeout")] public virtual void ResetTimeout() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetTimeouts")] public virtual void ResetTimeouts() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetTracingConfig")] public virtual void ResetTracingConfig() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "resetVpcConfig")] public virtual void ResetVpcConfig() { InvokeInstanceVoidMethod(new System.Type[]{}, new object[]{}); } [JsiiMethod(name: "synthesizeAttributes", returnsJson: "{\"type\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}}", isOverride: true)] protected override System.Collections.Generic.IDictionary<string, object> SynthesizeAttributes() { return InvokeInstanceMethod<System.Collections.Generic.IDictionary<string, object>>(new System.Type[]{}, new object[]{})!; } [JsiiProperty(name: "arn", typeJson: "{\"primitive\":\"string\"}")] public virtual string Arn { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "functionNameInput", typeJson: "{\"primitive\":\"string\"}")] public virtual string FunctionNameInput { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "handlerInput", typeJson: "{\"primitive\":\"string\"}")] public virtual string HandlerInput { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "id", typeJson: "{\"primitive\":\"string\"}")] public virtual string Id { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "invokeArn", typeJson: "{\"primitive\":\"string\"}")] public virtual string InvokeArn { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "lastModified", typeJson: "{\"primitive\":\"string\"}")] public virtual string LastModified { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "qualifiedArn", typeJson: "{\"primitive\":\"string\"}")] public virtual string QualifiedArn { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "roleInput", typeJson: "{\"primitive\":\"string\"}")] public virtual string RoleInput { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "runtimeInput", typeJson: "{\"primitive\":\"string\"}")] public virtual string RuntimeInput { get => GetInstanceProperty<string>()!; } [JsiiProperty(name: "sourceCodeSize", typeJson: "{\"primitive\":\"number\"}")] public virtual double SourceCodeSize { get => GetInstanceProperty<double>()!; } [JsiiProperty(name: "version", typeJson: "{\"primitive\":\"string\"}")] public virtual string Version { get => GetInstanceProperty<string>()!; } [JsiiOptional] [JsiiProperty(name: "deadLetterConfigInput", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionDeadLetterConfig\"},\"kind\":\"array\"}}", isOptional: true)] public virtual aws.ILambdaFunctionDeadLetterConfig[]? DeadLetterConfigInput { get => GetInstanceProperty<aws.ILambdaFunctionDeadLetterConfig[]?>(); } [JsiiOptional] [JsiiProperty(name: "descriptionInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? DescriptionInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "environmentInput", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionEnvironment\"},\"kind\":\"array\"}}", isOptional: true)] public virtual aws.ILambdaFunctionEnvironment[]? EnvironmentInput { get => GetInstanceProperty<aws.ILambdaFunctionEnvironment[]?>(); } [JsiiOptional] [JsiiProperty(name: "filenameInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? FilenameInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "fileSystemConfigInput", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionFileSystemConfig\"},\"kind\":\"array\"}}", isOptional: true)] public virtual aws.ILambdaFunctionFileSystemConfig[]? FileSystemConfigInput { get => GetInstanceProperty<aws.ILambdaFunctionFileSystemConfig[]?>(); } [JsiiOptional] [JsiiProperty(name: "kmsKeyArnInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? KmsKeyArnInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "layersInput", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"array\"}}", isOptional: true)] public virtual string[]? LayersInput { get => GetInstanceProperty<string[]?>(); } [JsiiOptional] [JsiiProperty(name: "memorySizeInput", typeJson: "{\"primitive\":\"number\"}", isOptional: true)] public virtual double? MemorySizeInput { get => GetInstanceProperty<double?>(); } [JsiiOptional] [JsiiProperty(name: "publishInput", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true)] public virtual bool? PublishInput { get => GetInstanceProperty<bool?>(); } [JsiiOptional] [JsiiProperty(name: "reservedConcurrentExecutionsInput", typeJson: "{\"primitive\":\"number\"}", isOptional: true)] public virtual double? ReservedConcurrentExecutionsInput { get => GetInstanceProperty<double?>(); } [JsiiOptional] [JsiiProperty(name: "s3BucketInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? S3BucketInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "s3KeyInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? S3KeyInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "s3ObjectVersionInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? S3ObjectVersionInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "sourceCodeHashInput", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public virtual string? SourceCodeHashInput { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "tagsInput", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"map\"}}", isOptional: true)] public virtual System.Collections.Generic.IDictionary<string, string>? TagsInput { get => GetInstanceProperty<System.Collections.Generic.IDictionary<string, string>?>(); } [JsiiOptional] [JsiiProperty(name: "timeoutInput", typeJson: "{\"primitive\":\"number\"}", isOptional: true)] public virtual double? TimeoutInput { get => GetInstanceProperty<double?>(); } [JsiiOptional] [JsiiProperty(name: "timeoutsInput", typeJson: "{\"fqn\":\"aws.LambdaFunctionTimeouts\"}", isOptional: true)] public virtual aws.ILambdaFunctionTimeouts? TimeoutsInput { get => GetInstanceProperty<aws.ILambdaFunctionTimeouts?>(); } [JsiiOptional] [JsiiProperty(name: "tracingConfigInput", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionTracingConfig\"},\"kind\":\"array\"}}", isOptional: true)] public virtual aws.ILambdaFunctionTracingConfig[]? TracingConfigInput { get => GetInstanceProperty<aws.ILambdaFunctionTracingConfig[]?>(); } [JsiiOptional] [JsiiProperty(name: "vpcConfigInput", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionVpcConfig\"},\"kind\":\"array\"}}", isOptional: true)] public virtual aws.ILambdaFunctionVpcConfig[]? VpcConfigInput { get => GetInstanceProperty<aws.ILambdaFunctionVpcConfig[]?>(); } [JsiiProperty(name: "deadLetterConfig", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionDeadLetterConfig\"},\"kind\":\"array\"}}")] public virtual aws.ILambdaFunctionDeadLetterConfig[] DeadLetterConfig { get => GetInstanceProperty<aws.ILambdaFunctionDeadLetterConfig[]>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "description", typeJson: "{\"primitive\":\"string\"}")] public virtual string Description { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "environment", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionEnvironment\"},\"kind\":\"array\"}}")] public virtual aws.ILambdaFunctionEnvironment[] Environment { get => GetInstanceProperty<aws.ILambdaFunctionEnvironment[]>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "filename", typeJson: "{\"primitive\":\"string\"}")] public virtual string Filename { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "fileSystemConfig", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionFileSystemConfig\"},\"kind\":\"array\"}}")] public virtual aws.ILambdaFunctionFileSystemConfig[] FileSystemConfig { get => GetInstanceProperty<aws.ILambdaFunctionFileSystemConfig[]>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "functionName", typeJson: "{\"primitive\":\"string\"}")] public virtual string FunctionName { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "handler", typeJson: "{\"primitive\":\"string\"}")] public virtual string Handler { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "kmsKeyArn", typeJson: "{\"primitive\":\"string\"}")] public virtual string KmsKeyArn { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "layers", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"array\"}}")] public virtual string[] Layers { get => GetInstanceProperty<string[]>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "memorySize", typeJson: "{\"primitive\":\"number\"}")] public virtual double MemorySize { get => GetInstanceProperty<double>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "publish", typeJson: "{\"primitive\":\"boolean\"}")] public virtual bool Publish { get => GetInstanceProperty<bool>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "reservedConcurrentExecutions", typeJson: "{\"primitive\":\"number\"}")] public virtual double ReservedConcurrentExecutions { get => GetInstanceProperty<double>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "role", typeJson: "{\"primitive\":\"string\"}")] public virtual string Role { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "runtime", typeJson: "{\"primitive\":\"string\"}")] public virtual string Runtime { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "s3Bucket", typeJson: "{\"primitive\":\"string\"}")] public virtual string S3Bucket { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "s3Key", typeJson: "{\"primitive\":\"string\"}")] public virtual string S3Key { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "s3ObjectVersion", typeJson: "{\"primitive\":\"string\"}")] public virtual string S3ObjectVersion { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "sourceCodeHash", typeJson: "{\"primitive\":\"string\"}")] public virtual string SourceCodeHash { get => GetInstanceProperty<string>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "tags", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"map\"}}")] public virtual System.Collections.Generic.IDictionary<string, string> Tags { get => GetInstanceProperty<System.Collections.Generic.IDictionary<string, string>>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "timeout", typeJson: "{\"primitive\":\"number\"}")] public virtual double Timeout { get => GetInstanceProperty<double>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "timeouts", typeJson: "{\"fqn\":\"aws.LambdaFunctionTimeouts\"}")] public virtual aws.ILambdaFunctionTimeouts Timeouts { get => GetInstanceProperty<aws.ILambdaFunctionTimeouts>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "tracingConfig", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionTracingConfig\"},\"kind\":\"array\"}}")] public virtual aws.ILambdaFunctionTracingConfig[] TracingConfig { get => GetInstanceProperty<aws.ILambdaFunctionTracingConfig[]>()!; set => SetInstanceProperty(value); } [JsiiProperty(name: "vpcConfig", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaFunctionVpcConfig\"},\"kind\":\"array\"}}")] public virtual aws.ILambdaFunctionVpcConfig[] VpcConfig { get => GetInstanceProperty<aws.ILambdaFunctionVpcConfig[]>()!; set => SetInstanceProperty(value); } } }
38.787819
307
0.588918
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/LambdaFunction.cs
19,743
C#
 namespace NextGenSoftware.Holochain.HoloNET.Client.MessagePack { public class BoolHandler : ITypeHandler { public object Read(Format format, FormatReader reader) { if(format.IsFalse) return false; if(format.IsTrue) return true; if(format.IsNil) return default(bool); throw new FormatException(this, format, reader); } public void Write(object obj, FormatWriter writer) { writer.Write((bool)obj); } } }
21.75
62
0.726437
[ "CC0-1.0" ]
HirenBodhi/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK
NextGenSoftware.Holochain.HoloNET.Client.MessagePack/TypeHandlers/BoolHandler.cs
437
C#
using Jobs; using NPC; namespace Pipliz.Mods.BaseGame.Construction { using JSON; [AreaJobDefinitionAutoLoader] public class ConstructionAreaDefinition : AbstractAreaJobDefinition { public ConstructionAreaDefinition () : base() { base.UsedNPCType = NPCType.GetByKeyNameOrDefault("pipliz.constructor"); base.Identifier = "pipliz.constructionarea"; MaxGathersPerRun = 5; } // need to parse some additional data that the default one doesn't public override IAreaJob CreateAreaJob (Colony owner, JSONNode node) { Vector3Int min = new Vector3Int() { x = node.GetAsOrDefault("x-", int.MinValue), y = node.GetAsOrDefault("y-", int.MinValue), z = node.GetAsOrDefault("z-", int.MinValue) }; Vector3Int max = min + new Vector3Int() { x = node.GetAsOrDefault("xd", 0), y = node.GetAsOrDefault("yd", 0), z = node.GetAsOrDefault("zd", 0) }; JSONNode args; if (!node.TryGetChild("args", out args)) { return null; } ConstructionArea area = (ConstructionArea)CreateAreaJob(owner, min, max, true); area.SetArgument(args); return area; } public override IAreaJob CreateAreaJob (Colony owner, Vector3Int min, Vector3Int max, bool isLoaded, int npcID = 0) { // there's no npc ID to load - as npcs dont work directly on these areas return new ConstructionArea(this, owner, min, max); } } }
26.538462
117
0.692754
[ "Unlicense" ]
BrightExistence/ColonySurvival
gamedata/mods/Pipliz/BaseGame/src/BuilderDigger/ConstructionAreaDefinition.cs
1,382
C#
namespace Assets.Scripts.Events { using System; using System.Collections; using Assets.Scripts.Components; /// <summary> /// Navigation event arguments. /// </summary> public class NavigationEventArgs : EventArgs { /// <summary> /// Gets or sets the previous view. /// </summary> /// <value>The previous view.</value> public View PreviousView { get; set; } /// <summary> /// Gets or sets the type of the previous view. /// </summary> /// <value>The type of the previous view.</value> public ViewType PreviousViewType { get; set; } /// <summary> /// Gets or sets the next view. /// </summary> /// <value>The next view.</value> public View NextView { get; set; } /// <summary> /// Gets or sets the type of the next view. /// </summary> /// <value>The type of the next view.</value> public ViewType NextViewType { get; set; } } }
24.527778
51
0.636467
[ "MIT" ]
BrettMStory/MatchJoy
MatchJoyUnity/Assets/Scripts/Events/NavigationEventArgs.cs
885
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 translate-2017-07-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Translate.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Translate.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for OutputDataConfig Object /// </summary> public class OutputDataConfigUnmarshaller : IUnmarshaller<OutputDataConfig, XmlUnmarshallerContext>, IUnmarshaller<OutputDataConfig, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> OutputDataConfig IUnmarshaller<OutputDataConfig, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public OutputDataConfig Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; OutputDataConfig unmarshalledObject = new OutputDataConfig(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("EncryptionKey", targetDepth)) { var unmarshaller = EncryptionKeyUnmarshaller.Instance; unmarshalledObject.EncryptionKey = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3Uri", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.S3Uri = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static OutputDataConfigUnmarshaller _instance = new OutputDataConfigUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static OutputDataConfigUnmarshaller Instance { get { return _instance; } } } }
34.663265
161
0.632617
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Translate/Generated/Model/Internal/MarshallTransformations/OutputDataConfigUnmarshaller.cs
3,397
C#
using System; using System.Collections.Generic; using System.Text; namespace BeetleX.ConcurrentTest { public class StatisticTag { public StatisticTag(string label) { ID = label.GetHashCode(); Label = label; mDetail = new long[3600 * 24 * 10]; } private long[] mDetail; private long mCount; private long mLastValue; private long mValue; public int ID { get; set; } public string Label { get; set; } public long Value => mValue; public void Add(long value) { System.Threading.Interlocked.Add(ref mValue, value); } public void Clear() { mCount = 0; mLastValue = 0; mValue = 0; } public string Report(bool last = false) { long concurrent = mValue - mLastValue; mLastValue = mValue; string value = $"{Label.PadLeft(13)}:[{(concurrent).ToString().PadLeft(7)}/s]|total:[{mValue.ToString().PadLeft(12)}]"; if (last) { if (mCount > 5) { Array.Sort(mDetail, 0, (int)mCount); long min; //if (Label == CTester.ERROR_TAG) min = mDetail[0]; //else // min = mDetail[1]; long max = mDetail[mCount - 1]; value += $"[min:{min}/s max:{max}/s]"; } } else { mDetail[mCount] = concurrent; mCount++; } return value; } } }
24.013889
131
0.441874
[ "Apache-2.0" ]
DomoYao/ConcurrentTest
BeetleX.ConcurrentTest/StatisticTag.cs
1,731
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("GitLineTrim")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GitLineTrim")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("02eb66e7-c715-4d88-9a39-e4f6c5a9b37e")] // 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")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject")]
38.763158
84
0.75017
[ "Apache-2.0" ]
Keepun/GitTools
GitLineTrim/Properties/AssemblyInfo.cs
1,476
C#