text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GroundEleBtn : MonoBehaviour { [HideInInspector] public GameObject Go; public UnityEngine.UI.Text NameText, RequiredMatsText; public void OnClick() { MarketManger.SelectBuilding(Go); } }
 using System.Collections.Generic; using System; using System.Text; using BrainDuelsLib.view.forms; using BrainDuelsLib.model.entities; using BrainDuelsLib.utils; using BrainDuelsLib.web; using BrainDuelsLib.web.exceptions; using BrainDuelsLib.view; using BrainDuelsLib.utils.pic; using BrainDuelsLib.threads; namespace BrainDuelsLib.widgets { public abstract class Widget { public abstract class CallbackStore { public Action<Exception> errorCallback = delegate { }; } public abstract class ControlsStore { } public Widget() { } public virtual void Go() { } public IImage LightAvaToImage(LightImage li, int width, int height) { li = li.CropToSize(width, height); IImage avaImage = SocketManager.resourcesProvider.MakeIImage(li); return avaImage; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; namespace Degree.Models.Dto { public class WordSentiment { public string Word { get; set; } public double AvgPositiveScore { get; set; } public double AvgNeutralScore { get; set; } public double AvgNegativeScore { get; set; } public int PositiveLabel { get; set; } public int NeutralLabel { get; set; } public int NegativeLabel { get; set; } public int MixedLabel { get; set; } public int Tweets { get; set; } } }
using AutoMapper; using Contoso.Bsl.Business.Requests; using Contoso.Bsl.Business.Responses; using Contoso.Bsl.Utils; using Contoso.Repositories; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Contoso.Bsl.Controllers { [Produces("application/json")] [Route("api/Entity")] public class EntityController : Controller { private readonly IMapper mapper; private readonly ISchoolRepository repository; public EntityController(IMapper mapper, ISchoolRepository repository) { this.mapper = mapper; this.repository = repository; } [HttpPost("GetEntity")] public async Task<BaseResponse> GetEntity([FromBody] GetEntityRequest request) => await RequestHelpers.GetEntity ( request, repository, mapper ); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class bullet : MonoBehaviour { public float speed = 20f; public Rigidbody2D rb; public float TimeToLive = 5f; private Animator animator; private AudioSource audio; // Start is called before the first frame update void Start() { animator = gameObject.GetComponent<Animator>(); audio = gameObject.GetComponent<AudioSource>(); rb.velocity = transform.right; Destroy(gameObject, TimeToLive); } public void explosion() { Destroy(gameObject); } private void OnTriggerEnter2D(Collider2D collision) { if (!collision.CompareTag("Player")) { Destroy(collision.gameObject); animator.SetBool("Hit",true); audio.Play(); rb.velocity = new Vector2(0,0); } } }
// C# Excel Writer library v2.0 // by Serhiy Perevoznyk, 2008-2018 namespace Export.XLS { internal class FormatInfo { private CellInfo cell; private int formatIndex; private int fontIndex; public FormatInfo(CellInfo cell) { this.cell = cell; if (string.IsNullOrEmpty(cell.Format)) formatIndex = 0; else formatIndex = cell.Document.Formats.IndexOf(cell.Format); FontInfo fontInfo = new FontInfo(cell.Font, cell.ForeColor); fontIndex = cell.Document.Fonts.IndexOf(fontInfo); if (fontIndex == -1) { cell.Document.Fonts.Add(fontInfo); fontIndex = cell.Document.Fonts.IndexOf(fontInfo); } if (fontIndex > 3) fontIndex++; } public override bool Equals(object obj) { if (obj is FormatInfo) { FormatInfo info = (FormatInfo)obj; return ((this.fontIndex == info.fontIndex) && (this.formatIndex == info.formatIndex) && (this.ForeColor.Index == info.ForeColor.Index) && (this.BackColor.Index == info.BackColor.Index) && (this.HorizontalAlignment == info.HorizontalAlignment) ); } else return false; } public override int GetHashCode() { return base.GetHashCode(); } public ExcelColor BackColor { get { return cell.BackColor; } } public ExcelColor ForeColor { get { return cell.ForeColor; } } public Font Font { get { return cell.Font; } } public string Format { get { return cell.Format; } } public Alignment HorizontalAlignment { get { return cell.Alignment; } } public int FormatIndex { get { return formatIndex; } } public int FontIndex { get { return fontIndex; } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Shared; using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { namespace Models { [Serial] [Method(WorkspaceNames.ExecuteCommand, Direction.ClientToServer)] [ GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace" /*, AllowDerivedRequests = true*/), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) ] [RegistrationOptions(typeof(ExecuteCommandRegistrationOptions)), Capability(typeof(ExecuteCommandCapability))] public partial record ExecuteCommandParams : IJsonRpcRequest, IWorkDoneProgressParams, IExecuteCommandParams { /// <summary> /// The identifier of the actual command handler. /// </summary> public string Command { get; init; } /// <summary> /// Arguments that the command should be invoked with. /// </summary> [Optional] public JArray? Arguments { get; init; } } [Serial] [Method(WorkspaceNames.ExecuteCommand, Direction.ClientToServer)] [ GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Workspace" /*, AllowDerivedRequests = true*/), GenerateHandlerMethods, GenerateRequestMethods(typeof(IWorkspaceLanguageClient), typeof(ILanguageClient)) ] [RegistrationOptions(typeof(ExecuteCommandRegistrationOptions)), Capability(typeof(ExecuteCommandCapability))] public partial record ExecuteCommandParams<T> : IRequest<T>, IWorkDoneProgressParams, IExecuteCommandParams { /// <summary> /// The identifier of the actual command handler. /// </summary> public string Command { get; init; } /// <summary> /// Arguments that the command should be invoked with. /// </summary> [Optional] public JArray? Arguments { get; init; } } /// <summary> /// Execute command registration options. /// </summary> [GenerateRegistrationOptions(nameof(ServerCapabilities.ExecuteCommandProvider))] [RegistrationOptionsConverter(typeof(ExecuteCommandRegistrationOptionsConverter))] [RegistrationName(WorkspaceNames.ExecuteCommand)] public partial class ExecuteCommandRegistrationOptions : IWorkDoneProgressOptions { /// <summary> /// The commands to be executed on the server /// </summary> public Container<string> Commands { get; set; } = null!; class ExecuteCommandRegistrationOptionsConverter : RegistrationOptionsConverterBase<ExecuteCommandRegistrationOptions, StaticOptions> { private readonly IHandlersManager _handlersManager; public ExecuteCommandRegistrationOptionsConverter(IHandlersManager handlersManager) { _handlersManager = handlersManager; } public override StaticOptions Convert(ExecuteCommandRegistrationOptions source) { var allRegistrationOptions = _handlersManager.Descriptors .OfType<ILspHandlerDescriptor>() .Where(z => z.HasRegistration) .Select(z => z.RegistrationOptions) .OfType<ExecuteCommandRegistrationOptions>() .ToArray(); return new() { Commands = allRegistrationOptions.SelectMany(z => z.Commands).ToArray(), // WorkDoneProgress = allRegistrationOptions.Any(x => x.WorkDoneProgress) }; } } } } namespace Client.Capabilities { [CapabilityKey(nameof(ClientCapabilities.TextDocument), nameof(WorkspaceClientCapabilities.ExecuteCommand))] public class ExecuteCommandCapability : DynamicCapability { } } namespace Workspace { public abstract class ExecuteTypedCommandHandlerBase<T> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); return Handle(arg1!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); return Handle(arg1!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedCommandHandlerBase<T, T2> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, T2 arg2, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, T2, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, T2 arg2, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedCommandHandlerBase<T, T2, T3> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, T2, T3, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedCommandHandlerBase<T, T2, T3, T4> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedCommandHandlerBase<T, T2, T3, T4, T5> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); T5 arg5 = default; if (args.Count > 4) arg5 = args[4].ToObject<T5>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, arg5!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, T5, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); T5 arg5 = default; if (args.Count > 4) arg5 = args[4].ToObject<T5>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, arg5!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedCommandHandlerBase<T, T2, T3, T4, T5, T6> : ExecuteCommandHandlerBase { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<Unit> Handle(ExecuteCommandParams request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); T5 arg5 = default; if (args.Count > 4) arg5 = args[4].ToObject<T5>(_serializer.JsonSerializer); T6 arg6 = default; if (args.Count > 5) arg6 = args[5].ToObject<T6>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, arg5!, arg6!, cancellationToken); } public abstract Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public abstract class ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, T5, T6, TResponse> : ExecuteCommandHandlerBase<TResponse> { private readonly string _command; private readonly ISerializer _serializer; public ExecuteTypedResponseCommandHandlerBase(string command, ISerializer serializer) { _command = command; _serializer = serializer; } public sealed override Task<TResponse> Handle(ExecuteCommandParams<TResponse> request, CancellationToken cancellationToken) { var args = request.Arguments ?? new JArray(); T arg1 = default; if (args.Count > 0) arg1 = args[0].ToObject<T>(_serializer.JsonSerializer); T2 arg2 = default; if (args.Count > 1) arg2 = args[1].ToObject<T2>(_serializer.JsonSerializer); T3 arg3 = default; if (args.Count > 2) arg3 = args[2].ToObject<T3>(_serializer.JsonSerializer); T4 arg4 = default; if (args.Count > 3) arg4 = args[3].ToObject<T4>(_serializer.JsonSerializer); T5 arg5 = default; if (args.Count > 4) arg5 = args[4].ToObject<T5>(_serializer.JsonSerializer); T6 arg6 = default; if (args.Count > 5) arg6 = args[5].ToObject<T6>(_serializer.JsonSerializer); return Handle(arg1!, arg2!, arg3!, arg4!, arg5!, arg6!, cancellationToken); } public abstract Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, CancellationToken cancellationToken); protected internal override ExecuteCommandRegistrationOptions CreateRegistrationOptions(ExecuteCommandCapability capability, ClientCapabilities clientCapabilities) => new ExecuteCommandRegistrationOptions { Commands = new Container<string>(_command) }; } public static partial class ExecuteTypedCommandExtensions { public static Task ExecuteCommand( this IWorkspaceLanguageClient mediator, Command @params, CancellationToken cancellationToken = default ) => mediator.SendRequest(new ExecuteCommandParams { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); public static Task ExecuteCommand( this ILanguageClient mediator, Command @params, CancellationToken cancellationToken = default ) => mediator.SendRequest(new ExecuteCommandParams { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); public static Task<TResponse> ExecuteCommandWithResponse<TResponse>( this IWorkspaceLanguageClient mediator, Command @params, CancellationToken cancellationToken = default ) => mediator.SendRequest(new ExecuteCommandParams<TResponse> { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); public static Task<TResponse> ExecuteCommandWithResponse<TResponse>( this ILanguageClient mediator, Command @params, CancellationToken cancellationToken = default ) => mediator.SendRequest(new ExecuteCommandParams<TResponse> { Arguments = @params.Arguments, Command = @params.Name }, cancellationToken); public static ILanguageServerRegistry OnExecuteCommand<T>( this ILanguageServerRegistry registry, string command, Func<T, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T>( this ILanguageServerRegistry registry, string command, Func<T, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T>(command, (arg1, _, token) => handler(arg1, token), _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T>( this ILanguageServerRegistry registry, string command, Func<T, Task> handler ) => registry.AddHandler(_ => new Handler<T>(command, (arg1, _, _) => handler(arg1), _.GetRequiredService<ISerializer>())); private class Handler<T> : ExecuteTypedCommandHandlerBase<T> { private readonly Func<T, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler(string command, Func<T, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override async Task<Unit> Handle(T arg1, CancellationToken cancellationToken) { await _handler(arg1, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } public static ILanguageServerRegistry OnExecuteCommand<T, T2>( this ILanguageServerRegistry registry, string command, Func<T, T2, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2>( this ILanguageServerRegistry registry, string command, Func<T, T2, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2>(command, (arg1, arg2, _, token) => handler(arg1, arg2, token), _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2>( this ILanguageServerRegistry registry, string command, Func<T, T2, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2>(command, (arg1, arg2, _, _) => handler(arg1, arg2), _.GetRequiredService<ISerializer>())); private class Handler<T, T2> : ExecuteTypedCommandHandlerBase<T, T2> { private readonly Func<T, T2, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler(string command, Func<T, T2, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override async Task<Unit> Handle(T arg1, T2 arg2, CancellationToken cancellationToken) { await _handler(arg1, arg2, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3>(command, (arg1, arg2, arg3, _, token) => handler(arg1, arg2, arg3, token), _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3>(this ILanguageServerRegistry registry, string command, Func<T, T2, T3, Task> handler) => registry.AddHandler(_ => new Handler<T, T2, T3>(command, (arg1, arg2, arg3, _, _) => handler(arg1, arg2, arg3), _.GetRequiredService<ISerializer>())); private class Handler<T, T2, T3> : ExecuteTypedCommandHandlerBase<T, T2, T3> { private readonly Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler(string command, Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override async Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken) { await _handler(arg1, arg2, arg3, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, CancellationToken, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4>(command, (arg1, arg2, arg3, arg4, _, token) => handler(arg1, arg2, arg3, arg4, token), _.GetRequiredService<ISerializer>()) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4>(command, (arg1, arg2, arg3, arg4, _, _) => handler(arg1, arg2, arg3, arg4), _.GetRequiredService<ISerializer>()) ); private class Handler<T, T2, T3, T4> : ExecuteTypedCommandHandlerBase<T, T2, T3, T4> { private readonly Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler( string command, Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer ) : base(command, serializer) => _handler = handler; public override async Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, CancellationToken cancellationToken) { await _handler(arg1, arg2, arg3, arg4, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4, T5>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, CancellationToken, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5>( command, (arg1, arg2, arg3, arg4, arg5, _, token) => handler(arg1, arg2, arg3, arg4, arg5, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5>(command, (arg1, arg2, arg3, arg4, arg5, _, _) => handler(arg1, arg2, arg3, arg4, arg5), _.GetRequiredService<ISerializer>()) ); private class Handler<T, T2, T3, T4, T5> : ExecuteTypedCommandHandlerBase<T, T2, T3, T4, T5> { private readonly Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler(string command, Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override async Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, CancellationToken cancellationToken) { await _handler(arg1, arg2, arg3, arg4, arg5, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4, T5, T6>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, CancellationToken, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, T6>( command, (arg1, arg2, arg3, arg4, arg5, arg6, _, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, Task> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, T6>( command, (arg1, arg2, arg3, arg4, arg5, arg6, _, _) => handler(arg1, arg2, arg3, arg4, arg5, arg6), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, T3, T4, T5, T6> : ExecuteTypedCommandHandlerBase<T, T2, T3, T4, T5, T6> { private readonly Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task> _handler; public Handler(string command, Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task> handler, ISerializer serializer) : base( command, serializer ) => _handler = handler; public override async Task<Unit> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, CancellationToken cancellationToken) { await _handler(arg1, arg2, arg3, arg4, arg5, arg6, Capability, cancellationToken).ConfigureAwait(false); return Unit.Value; } } } public static partial class ExecuteTypedResponseCommandExtensions { public static ILanguageServerRegistry OnExecuteCommand<T, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, TResponse>(command, (arg1, _, token) => handler(arg1, token), _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, TResponse>( command, (arg1, _, _) => handler(arg1), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, TResponse> { private readonly Func<T, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler(string command, Func<T, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override Task<TResponse> Handle(T arg1, CancellationToken cancellationToken) => _handler(arg1, Capability, cancellationToken); } public static ILanguageServerRegistry OnExecuteCommand<T, T2, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, T2, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, TResponse>( command, (arg1, arg2, _, token) => handler(arg1, arg2, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, TResponse>( command, (arg1, arg2, _, _) => handler(arg1, arg2), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, T2, TResponse> { private readonly Func<T, T2, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler(string command, Func<T, T2, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer) : base( command, serializer ) => _handler = handler; public override Task<TResponse> Handle(T arg1, T2 arg2, CancellationToken cancellationToken) => _handler(arg1, arg2, Capability, cancellationToken); } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, TResponse>( command, (arg1, arg2, arg3, _, token) => handler(arg1, arg2, arg3, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, TResponse>( command, (arg1, arg2, arg3, _, _) => handler(arg1, arg2, arg3), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, T3, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, T2, T3, TResponse> { private readonly Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler(string command, Func<T, T2, T3, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer) : base( command, serializer ) => _handler = handler; public override Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken) { return _handler(arg1, arg2, arg3, Capability, cancellationToken); } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, TResponse>( command, (arg1, arg2, arg3, arg4, _, token) => handler(arg1, arg2, arg3, arg4, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, TResponse>( command, (arg1, arg2, arg3, arg4, _, _) => handler(arg1, arg2, arg3, arg4), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, T3, T4, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, TResponse> { private readonly Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler( string command, Func<T, T2, T3, T4, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer ) : base(command, serializer) => _handler = handler; public override Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, CancellationToken cancellationToken) { return _handler(arg1, arg2, arg3, arg4, Capability, cancellationToken); } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4, T5, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, TResponse>( command, (arg1, arg2, arg3, arg4, arg5, _, token) => handler(arg1, arg2, arg3, arg4, arg5, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, TResponse>( command, (arg1, arg2, arg3, arg4, arg5, _, _) => handler(arg1, arg2, arg3, arg4, arg5), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, T3, T4, T5, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, T5, TResponse> { private readonly Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler(string command, Func<T, T2, T3, T4, T5, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer) : base(command, serializer) => _handler = handler; public override Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, CancellationToken cancellationToken) { return _handler(arg1, arg2, arg3, arg4, arg5, Capability, cancellationToken); } } public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler(_ => new Handler<T, T2, T3, T4, T5, T6, TResponse>(command, handler, _.GetRequiredService<ISerializer>())); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, CancellationToken, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, T6, TResponse>( command, (arg1, arg2, arg3, arg4, arg5, arg6, _, token) => handler(arg1, arg2, arg3, arg4, arg5, arg6, token), _.GetRequiredService<ISerializer>() ) ); public static ILanguageServerRegistry OnExecuteCommand<T, T2, T3, T4, T5, T6, TResponse>( this ILanguageServerRegistry registry, string command, Func<T, T2, T3, T4, T5, T6, Task<TResponse>> handler ) => registry.AddHandler( _ => new Handler<T, T2, T3, T4, T5, T6, TResponse>( command, (arg1, arg2, arg3, arg4, arg5, arg6, _, _) => handler(arg1, arg2, arg3, arg4, arg5, arg6), _.GetRequiredService<ISerializer>() ) ); private class Handler<T, T2, T3, T4, T5, T6, TResponse> : ExecuteTypedResponseCommandHandlerBase<T, T2, T3, T4, T5, T6, TResponse> { private readonly Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task<TResponse>> _handler; public Handler(string command, Func<T, T2, T3, T4, T5, T6, ExecuteCommandCapability, CancellationToken, Task<TResponse>> handler, ISerializer serializer) : base( command, serializer ) => _handler = handler; public override Task<TResponse> Handle(T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, CancellationToken cancellationToken) { return _handler(arg1, arg2, arg3, arg4, arg5, arg6, Capability, cancellationToken); } } } } }
using System; using System.Collections.Generic; using System.Text; namespace BASETOOL { public class EncoderConverter { public EncoderConverter() { } public static string Convert(string content,Encoding formEncoding,Encoding toEncoding) { byte[] buff = formEncoding.GetBytes(content); return toEncoding.GetString(buff); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SiscomSoft.Models { [Table("Facturas")] public class Factura { [Key] public int idFactura { get; set; } public int usuario_id { get; set; } public int sucursal_id { get; set; } public int cliente_id { get; set; } public DateTime dtFecha { get; set; } public string sFolio { get; set; } public string sTipoCambio { get; set; } public string sMoneda { get; set; } public string sUsoCfdi { get; set; } public string sFormaPago { get; set; } public string sMetodoPago { get; set; } public string sTipoCompro { get; set; } public Boolean bStatus { get; set; } public Factura() { this.bStatus = true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class CommonVars { public static bool selected1, selected2; public enum Family {NoParent, Grandparent, Parent, Child, Leaf}; public enum axis {x,y,z}; public static Vector3 offset = new Vector3(0.1f,0.1f,0.1f); public static string[] names = { "null", "MyCube", "MySphere", "MyCylinder" }; }
using MongoDB.Driver; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WishListLabs.Models; namespace WishListLabs.Repository { public class WishesRepository : BaseRepository<Wishes>, IWishesRepository { private readonly IMongoCollection<Wishes> _wishesCollection; private readonly IMongoCollection<Product> _productRepository; public WishesRepository( IMongoCollection<Wishes> wishesCollection, IMongoCollection<Product> productRepository ) : base(wishesCollection) { this._wishesCollection = wishesCollection; this._productRepository = productRepository; } public async Task InsertItem(IList<Wishes> wishList, int userId) { try { Wishes wish = new Wishes(); wish.Id = 0; wish.userId = userId; wish.Products = new List<Product>(); var retCode = _wishesCollection.Find(m => true) .SortByDescending(x => x.Id) .Project(u => u.Id) .FirstOrDefault(); retCode = retCode == 0 ? 1 : retCode + 1; wish.Id = retCode; foreach (var item in wishList) { var prod = await _productRepository.FindAsync(x => x.Id == item.IdProduct); var prodItem = await prod.FirstOrDefaultAsync(); if (prodItem.Id > 0) wish.Products.Add(prodItem); else throw new Exception($"Id {item.IdProduct} não exite."); } await _wishesCollection.InsertOneAsync(wish); } catch { throw; } } public async Task Delete( int userId, int productId) { try { await _wishesCollection.FindOneAndDeleteAsync(x => x.userId == userId ); } catch { throw; } } public async Task<Wishes> GetItem( int userId) { try { var foundWish = await _wishesCollection.FindAsync(x => x.userId == userId ); var firstWish = await foundWish.FirstOrDefaultAsync(); return firstWish; } catch { throw; } } public async Task UpdateItem(int userId, int productId) { try { var item = await _wishesCollection.FindAsync(x => x.userId == userId && x.IdProduct == productId); var firstItem = await item.FirstOrDefaultAsync(); var update = await _wishesCollection.ReplaceOneAsync(x => x.IdProduct == productId ,firstItem); } catch { throw; } } } }
using Newtonsoft.Json; using NUnit.Framework; using RestSharp; using System.Net; namespace BakeryTests { public sealed class Owner { private RestClient _client; public Owner InitializeConnection(RestClient client) { _client = client ?? throw new System.ArgumentNullException(nameof(client)); return this; } public Product BakeNewProduct(string name, string price) { if (name == null) throw new System.ArgumentNullException(nameof(name)); if (price == null) throw new System.ArgumentNullException(nameof(price)); return new Product(name, price); } public void AddNewProduct(Product product) { if (product == null) throw new System.ArgumentNullException(nameof(product)); RestRequest request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; request.AddJsonBody(product); IRestResponse response = _client.Execute(request); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), "Request was rejected"); Assert.That(response.ContentType, Is.EqualTo("application/json")); } private IRestResponse GetGoods() { RestRequest request = new RestRequest(Method.GET); var response = _client.Execute(request); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), "Request was rejected"); Assert.That(response.ContentType, Is.EqualTo("application/json")); return response; } public int GetNewestProductId(string url) { _client = new RestClient($"{url}/newest_id"); IRestResponse response = GetGoods(); return int.Parse(JsonConvert.DeserializeObject<Product>(response.Content).id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace anagram { public class Anagram { public string W1 { get; set; } public string W2{ get; set; } } }
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZUS.Zeus.Models.Validators { public class BikeValidator : AbstractValidator<Bike> { public BikeValidator() { RuleFor(p => p.Color) .NotEmpty(); RuleFor(p => p.Number) .Length(1, 5) .WithMessage("Długość pola przekoczona!"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DinosaurTailRotation : MonoBehaviour { public GameObject Tail; public GameObject aim; public float aimSpeed; public int rotationSpeed; void OnTriggerStay (Collider other) { string playerName = other.gameObject.name; float rotateHorizontal = InputManager.GetAimX (playerName); Vector3 rotation = new Vector3 (rotateHorizontal, 0.0f, 0.0f); if (InputManager.GetShootButton(playerName)) { aim.GetComponent<Rigidbody>().velocity = rotation * aimSpeed; } Vector3 Left = new Vector3(-10,0,0); Vector3 Right = new Vector3(10,0,0); if(aim.transform.localPosition.x >= 23){ aim.GetComponent<Rigidbody>().AddForce(30*Right); } if(aim.transform.localPosition.x <= -23){ aim.GetComponent<Rigidbody>().AddForce(30*Left); } } void Update(){ Vector3 pointToLook = new Vector3(aim.transform.position.x,0.0f,aim.transform.position.z/10); Tail.transform.LookAt(pointToLook); } }
using FluentAssertions; using HangmanGame.App.Services; using HangmanGame.App.Services.Interfaces; using Xunit; namespace HangmanGame.UnitTests.Services { public class VectorProviderTests { private readonly IVectorProvider _vectorProvider; private const string Vector1 = @" ------| | | () | /||\ | / \ | | | ======================== "; private const string Vector2 = @" ------| | | () | / | | | | ======================== "; private const string Vector3 = @" ------| | | () | /||\ | | | | ======================== "; public VectorProviderTests() { _vectorProvider = new VectorProvider(); } [Fact] public void CanGetFullHangmanVector() { // Arrange // Act var vector = _vectorProvider.GetFullHangmanVector(); // Assert vector.Should() .Be(Vector1); } [Theory] [InlineData(4, Vector2)] [InlineData(2, Vector3)] public void GetHangmanVectorByAttempt(int attemptNumber, string expectedText) { // Arrange // Act var vector = _vectorProvider.GetHangmanVectorByAttempt(attemptNumber); // Assert vector.Should() .Be(expectedText); } } }
using LuaInterface; using SLua; using System; using System.Collections.Generic; using UnityEngine; public class Lua_UnityEngine_Component : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { Component o = new Component(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponent(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 2, typeof(string))) { Component component = (Component)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); Component component2 = component.GetComponent(text); LuaObject.pushValue(l, true); LuaObject.pushValue(l, component2); result = 2; } else if (LuaObject.matchType(l, total, 2, typeof(Type))) { Component component3 = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component component4 = component3.GetComponent(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, component4); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponentInChildren(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component componentInChildren = component.GetComponentInChildren(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentInChildren); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponentsInChildren(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component[] componentsInChildren = component.GetComponentsInChildren(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentsInChildren); result = 2; } else if (num == 3) { Component component2 = (Component)LuaObject.checkSelf(l); Type type2; LuaObject.checkType(l, 2, out type2); bool flag; LuaObject.checkType(l, 3, out flag); Component[] componentsInChildren2 = component2.GetComponentsInChildren(type2, flag); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentsInChildren2); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponentInParent(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component componentInParent = component.GetComponentInParent(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentInParent); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponentsInParent(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component[] componentsInParent = component.GetComponentsInParent(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentsInParent); result = 2; } else if (num == 3) { Component component2 = (Component)LuaObject.checkSelf(l); Type type2; LuaObject.checkType(l, 2, out type2); bool flag; LuaObject.checkType(l, 3, out flag); Component[] componentsInParent2 = component2.GetComponentsInParent(type2, flag); LuaObject.pushValue(l, true); LuaObject.pushValue(l, componentsInParent2); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetComponents(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); Type type; LuaObject.checkType(l, 2, out type); Component[] components = component.GetComponents(type); LuaObject.pushValue(l, true); LuaObject.pushValue(l, components); result = 2; } else if (num == 3) { Component component2 = (Component)LuaObject.checkSelf(l); Type type2; LuaObject.checkType(l, 2, out type2); List<Component> list; LuaObject.checkType<List<Component>>(l, 3, out list); component2.GetComponents(type2, list); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int CompareTag(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); bool b = component.CompareTag(text); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SendMessageUpwards(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); component.SendMessageUpwards(text); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(SendMessageOptions))) { Component component2 = (Component)LuaObject.checkSelf(l); string text2; LuaObject.checkType(l, 2, out text2); SendMessageOptions sendMessageOptions; LuaObject.checkEnum<SendMessageOptions>(l, 3, out sendMessageOptions); component2.SendMessageUpwards(text2, sendMessageOptions); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(object))) { Component component3 = (Component)LuaObject.checkSelf(l); string text3; LuaObject.checkType(l, 2, out text3); object obj; LuaObject.checkType<object>(l, 3, out obj); component3.SendMessageUpwards(text3, obj); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Component component4 = (Component)LuaObject.checkSelf(l); string text4; LuaObject.checkType(l, 2, out text4); object obj2; LuaObject.checkType<object>(l, 3, out obj2); SendMessageOptions sendMessageOptions2; LuaObject.checkEnum<SendMessageOptions>(l, 4, out sendMessageOptions2); component4.SendMessageUpwards(text4, obj2, sendMessageOptions2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SendMessage(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); component.SendMessage(text); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(SendMessageOptions))) { Component component2 = (Component)LuaObject.checkSelf(l); string text2; LuaObject.checkType(l, 2, out text2); SendMessageOptions sendMessageOptions; LuaObject.checkEnum<SendMessageOptions>(l, 3, out sendMessageOptions); component2.SendMessage(text2, sendMessageOptions); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(object))) { Component component3 = (Component)LuaObject.checkSelf(l); string text3; LuaObject.checkType(l, 2, out text3); object obj; LuaObject.checkType<object>(l, 3, out obj); component3.SendMessage(text3, obj); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Component component4 = (Component)LuaObject.checkSelf(l); string text4; LuaObject.checkType(l, 2, out text4); object obj2; LuaObject.checkType<object>(l, 3, out obj2); SendMessageOptions sendMessageOptions2; LuaObject.checkEnum<SendMessageOptions>(l, 4, out sendMessageOptions2); component4.SendMessage(text4, obj2, sendMessageOptions2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int BroadcastMessage(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Component component = (Component)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); component.BroadcastMessage(text); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(SendMessageOptions))) { Component component2 = (Component)LuaObject.checkSelf(l); string text2; LuaObject.checkType(l, 2, out text2); SendMessageOptions sendMessageOptions; LuaObject.checkEnum<SendMessageOptions>(l, 3, out sendMessageOptions); component2.BroadcastMessage(text2, sendMessageOptions); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, num, 2, typeof(string), typeof(object))) { Component component3 = (Component)LuaObject.checkSelf(l); string text3; LuaObject.checkType(l, 2, out text3); object obj; LuaObject.checkType<object>(l, 3, out obj); component3.BroadcastMessage(text3, obj); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Component component4 = (Component)LuaObject.checkSelf(l); string text4; LuaObject.checkType(l, 2, out text4); object obj2; LuaObject.checkType<object>(l, 3, out obj2); SendMessageOptions sendMessageOptions2; LuaObject.checkEnum<SendMessageOptions>(l, 4, out sendMessageOptions2); component4.BroadcastMessage(text4, obj2, sendMessageOptions2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_transform(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, component.get_transform()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_gameObject(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, component.get_gameObject()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_tag(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, component.get_tag()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_tag(IntPtr l) { int result; try { Component component = (Component)LuaObject.checkSelf(l); string tag; LuaObject.checkType(l, 2, out tag); component.set_tag(tag); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.Component"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponent)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponentInChildren)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponentsInChildren)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponentInParent)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponentsInParent)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.GetComponents)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.CompareTag)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.SendMessageUpwards)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.SendMessage)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Component.BroadcastMessage)); LuaObject.addMember(l, "transform", new LuaCSFunction(Lua_UnityEngine_Component.get_transform), null, true); LuaObject.addMember(l, "gameObject", new LuaCSFunction(Lua_UnityEngine_Component.get_gameObject), null, true); LuaObject.addMember(l, "tag", new LuaCSFunction(Lua_UnityEngine_Component.get_tag), new LuaCSFunction(Lua_UnityEngine_Component.set_tag), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Component.constructor), typeof(Component), typeof(Object)); } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class BidLogReport : System.Web.UI.Page { string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; DataTable dt; BizConnectClient obj_Class = new BizConnectClient(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ChkAuthentication(); Bind(); } } public void Bind() { try { dt = new DataTable(); dt = obj_Class.Get_BiddingStatus(2, Session["UserID"].ToString()); GridQuotingLevel.DataSource = dt; GridQuotingLevel.DataBind(); } catch (Exception ex) { } } protected void GridQuotingLevel_RowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label LblPostID = (Label)e.Row.FindControl("lblPostID"); dt = new DataTable(); dt = obj_Class.Get_Level(Convert.ToInt32(LblPostID.Text)); for (int i = 0; i <= dt.Rows.Count - 1; i++) { e.Row.Cells[5 + i].Text = dt.Rows[i][0].ToString() + "-" + dt.Rows[i][1].ToString(); e.Row.Cells[5].ForeColor = System.Drawing.Color.Green; e.Row.Cells[6].ForeColor = System.Drawing.Color.YellowGreen; e.Row.Cells[7].ForeColor = System.Drawing.Color.Goldenrod; e.Row.Cells[8].ForeColor = System.Drawing.Color.Red; e.Row.Cells[9].Text =dt.Rows[i][4].ToString(); } } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; //obj_Navi.Visible = true; //obj_Navihome.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; // obj_Navi.Visible = true; //obj_Navihome.Visible = false; } protected void ButDownload_Click(object sender, EventArgs e) { ExportGrid(GridQuotingLevel, "ReBidLogReport.xls"); } public static void ExportGrid(GridView oGrid, string exportFile) { //Clear the response, and set the content type and mark as attachment HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + exportFile + "\""); //Clear the character set HttpContext.Current.Response.Charset = ""; //Create a string and Html writer needed for output System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //Clear the controls from the pased grid ClearControls(oGrid); //Show grid lines oGrid.GridLines = GridLines.Both; //Color header oGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray; //Render the grid to the writer oGrid.RenderControl(oHtmlTextWriter); //Write out the response (file), then end the response HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } private static void ClearControls(Control control) { //Recursively loop through the controls, calling this method for (int i = control.Controls.Count - 1; i >= 0; i--) { ClearControls(control.Controls[i]); } //If we have a control that is anything other than a table cell if (!(control is TableCell)) { if (control.GetType().GetProperty("SelectedItem") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); try { literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null); } catch { } control.Parent.Controls.Remove(control); } else if (control.GetType().GetProperty("Text") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null); control.Parent.Controls.Remove(control); } } return; } public override void VerifyRenderingInServerForm(Control control) { } }
using System.Collections.Generic; using System.Text; using System; namespace LinnworksAPI { public class WarehouseBinRack { public Int32 BinRackId; public Int32 BinRackTypeId; public String BinRack; public GeoPosition GeoPosition; public Dimension Dimension; public Int32 RoutingSequence; public Decimal MaxCapacityVolumetric; public Decimal CurrentFullPercentage; public Int32 MaxQuantityCapacity; public Int32 CurrentQuantity; public Decimal CurrentVolumetric; public Decimal OptimalReplenishFullPercentage; public Decimal CriticalReplenishFullPercentage; public Boolean ItemRestriction; public Boolean GroupRestriction; public Guid LocationId; public String TypeName; public Int32 StandardType; public String AccessOrientation; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MGK.Basecore.Xml.Data { // where to put this ? public class Tarih_Date { /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Currency")] public Tarih_DateCurrency[] Currency { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Tarih { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Date { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Bulten_No { get; set; } } /// <remarks/> [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class Tarih_DateCurrency { /// <remarks/> public byte Unit { get; set; } /// <remarks/> public string Isim { get; set; } /// <remarks/> public string CurrencyName { get; set; } /// <remarks/> public decimal ForexBuying { get; set; } /// <remarks/> public string ForexSelling { get; set; } /// <remarks/> public string BanknoteBuying { get; set; } /// <remarks/> public string BanknoteSelling { get; set; } /// <remarks/> public string CrossRateUSD { get; set; } /// <remarks/> public string CrossRateOther { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte CrossOrder { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Kod { get; set; } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string CurrencyCode { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data.Entity; using System.Data.Entity.Validation; using NBTM.Repository.Interfaces; using NBTM.Repository.Models; using System.Linq.Expressions; using System.Reflection; using log4net; //using LinqKit; namespace NBTM.Repository { /// <summary> /// /// </summary> /// <typeparam name="TEntity"></typeparam> /// <remarks>Good article as basis to possibly extend this generic repository:http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet</remarks> public class GenericRepository<TEntity> where TEntity : class { private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected readonly SalesApp1Entities _context; private readonly DbSet<TEntity> _dbSet; protected GenericRepository(SalesApp1Entities context, LoggedInUserContext userContext=null) //TODO: Remove optionality { _userContext = userContext; _context = context; _dbSet = context.Set<TEntity>(); } #region Get public IEnumerable<TEntity> Get() { return GetQuery(null, String.Empty); } public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter) { return GetQuery(filter, String.Empty); } public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter, string includeProperties) { return GetQuery(filter, includeProperties); } protected IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> filter = null, string includeProperties = "") { IQueryable<TEntity> query = _dbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } return query; } #endregion public virtual TEntity GetById(object id) { if (!(id is Guid)) return _dbSet.Find(id); var guid = (Guid) id; return _dbSet.Find(guid); } public virtual TEntity GetById(int id) { return _dbSet.Find(id); } public virtual TEntity GetById(Guid id) { return _dbSet.Find(id); } public virtual void Insert(TEntity entity) { _context.Entry(entity).State = EntityState.Added; if (entity is IAuditable) { var auditEntity = (IAuditable) entity; auditEntity.CreatedDate = DateTime.Now; if (_userContext != null) { auditEntity.CreatedBy = _userContext.UserName; } else { auditEntity.CreatedBy = "No Domain"; } _dbSet.Add(entity); } else if (entity is ICreateAuditable) { var auditEntity = (ICreateAuditable) entity; auditEntity.DateCreated = DateTime.Now; if (_userContext != null) { auditEntity.CreatedBy = _userContext.UserId; } _dbSet.Add(entity); } else { _dbSet.Add(entity); } } public virtual void Delete(Guid id) { TEntity entityToDelete = _dbSet.Find(id); if (entityToDelete is IsDeleted) { var softDelete = (IsDeleted) entityToDelete; softDelete.IsDeleted = true; _context.Entry(softDelete).State = EntityState.Modified; } else { Delete(entityToDelete); } } public virtual void Delete(object id) { TEntity entityToDelete = _dbSet.Find(id); if (entityToDelete is IsDeleted) { var softDelete = (IsDeleted)entityToDelete; softDelete.IsDeleted = true; _context.Entry(softDelete).State = EntityState.Modified; } else { Delete(entityToDelete); } } protected virtual void Delete(TEntity entityToDelete) { if (_context.Entry(entityToDelete).State == System.Data.Entity.EntityState.Detached) { _dbSet.Attach(entityToDelete); } if (entityToDelete is IsDeleted) { var softDelete = (IsDeleted)entityToDelete; softDelete.IsDeleted = true; _context.Entry(softDelete).State = EntityState.Modified; } else { _dbSet.Remove(entityToDelete); } } public virtual void Update(TEntity entityToUpdate) { _dbSet.Attach(entityToUpdate); if (_userContext != null && entityToUpdate is IAuditable) { var auditEntity = (IAuditable) entityToUpdate; auditEntity.UpdatedDate = DateTime.Now; if (_userContext != null) { //auditEntity.UpdatedBy = _userContext.UserId; auditEntity.UpdatedBy = _userContext.UserName; } _context.Entry(auditEntity).State = EntityState.Modified; } else { _context.Entry(entityToUpdate).State = EntityState.Modified; } } public void Save() { try { // Your code... // Could also be before try if you know the exception occurs in SaveChanges _context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Logger.ErrorFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Logger.ErrorFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _context.Dispose(); } } _disposed = true; } #region Members private bool _disposed; protected readonly LoggedInUserContext _userContext; #endregion } }
using UnityEngine; public class WeaponController : MonoBehaviour{ [Header("Objects to Load")] [SerializeField] private ObjectPooler _bulletPool; [SerializeField] private Transform _muzzle; [SerializeField] private AudioClip _shootSfx; [Header("Ammo")] [SerializeField] public int _maxAmmo; [SerializeField] public int _currentAmmo; [SerializeField] private bool _isInfiniteAmmo; [Header("Bullets")] [SerializeField] private float _bulletSpeed; [SerializeField] private float _shootRate; private float _lastShootTime; private bool _isPlayer; private AudioSource _audioSource; private void Awake(){ CheckForPlayer(); GetAudioSource(); } private void CheckForPlayer(){ if (GetComponent<PlayerController>()) _isPlayer = true; } private void GetAudioSource(){ _audioSource = GetComponent<AudioSource>(); } public bool CheckToShoot(){ if (Time.time - _lastShootTime >= _shootRate && (_currentAmmo > 0 || _isInfiniteAmmo)) return true; return false; } public void Shoot(){ _lastShootTime = Time.time; _currentAmmo--; if (_isPlayer) GameUIController._instance.UpdateAmmoText(_currentAmmo, _maxAmmo); _audioSource.PlayOneShot(_shootSfx); GameObject bullet = _bulletPool.GetObject(); bullet.transform.position = _muzzle.position; bullet.transform.rotation = _muzzle.rotation; bullet.GetComponent<Rigidbody>().velocity = _muzzle.forward * _bulletSpeed; } }
using System; namespace RealEstate.BusinessObjects { public class Categorys { #region ***** Fields & Properties ***** private int _CategoryID; public int CategoryID { get { return _CategoryID; } set { _CategoryID = value; } } private string _Tag; public string Tag { get { return _Tag; } set { _Tag = value; } } private string _Name; public string Name { get { return _Name; } set { _Name = value; } } private string _Content; public string Content { get { return _Content; } set { _Content = value; } } private string _Level; public string Level { get { return _Level; } set { _Level = value; } } private int _Priority; public int Priority { get { return _Priority; } set { _Priority = value; } } private int _Index; public int Index { get { return _Index; } set { _Index = value; } } private string _Title; public string Title { get { return _Title; } set { _Title = value; } } private string _Description; public string Description { get { return _Description; } set { _Description = value; } } private string _Keyword; public string Keyword { get { return _Keyword; } set { _Keyword = value; } } private int _Active; public int Active { get { return _Active; } set { _Active = value; } } private int _Ord; public int Ord { get { return _Ord; } set { _Ord = value; } } private string _Lang; public string Lang { get { return _Lang; } set { _Lang = value; } } private string _Image; public string Image { get { return _Image; } set { _Image = value; } } private string _Image2; public string Image2 { get { return _Image2; } set { _Image2 = value; } } #endregion #region ***** Init Methods ***** public Categorys() { } public Categorys(int categoryid) { this.CategoryID = categoryid; } public Categorys(int categoryid, string tag, string name, string content, string level, int priority, int index, string title, string description, string keyword, int active, int ord, string lang, string image, string image2) { this.CategoryID = categoryid; this.Tag = tag; this.Name = name; this.Content = content; this.Level = level; this.Priority = priority; this.Index = index; this.Title = title; this.Description = description; this.Keyword = keyword; this.Active = active; this.Ord = ord; this.Lang = lang; this.Image = image; this.Image2 = image2; } #endregion } }
namespace Faust.PetShopApp.MySecurity.Data { public interface ISecurityContextInitializer { void Initialize(SecurityContext context); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pulse : MonoBehaviour { [SerializeField] float _current; private void Start() { _current = 0.5f; } // Update is called once per frame void Update() { _current = Mathf.PingPong(Time.time, 0.6f); RenderSettings.haloStrength = _current; } }
using Prj.BusinessLogic.Interfaces; using Prj.BusinessLogic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Prj.Utilities; namespace Prj.Web.Areas.Admin.Controllers { [Authorize] public class AccountController : BaseController { IBranchService _branchService; public AccountController(IBranchService branchService, IAccountService accountService, IPermissionService permissionService) : base(accountService, permissionService) { _branchService = branchService; } // GET: Admin/Account public ActionResult Index() { return View(); } public ActionResult ChangePassword() { return View(); } [HttpPost] [ValidateInput(false)] [AllowAnonymous] public ActionResult ChangePassword(AccountChangePassModel model) { //#region Permission //bool bPermission = _permissionService.PERMISSION(AccountIsAuthenticated(), ConfigPermission.ManagerAccount); //if (bPermission.Equals(false)) //{ // return RedirectToAction("Index", "Mainternance", new { area = "Admin" }); //} //#endregion model.ModifiedBy = AccountIsAuthenticated(); model.UserName = AccountIsAuthenticated(); MessageModel msg = _accountService.ChangePassword(model); ViewBag.message = Globals.ErrorMessage(msg.message, msg.result); return View(); } public ActionResult CreateAccount() { ViewBag.listBranch = _branchService.GetBranch(true); return View(); } [HttpPost] [ValidateInput(false)] [AllowAnonymous] public ActionResult CreateAccount(AccountModel model) { model.ModifiedBy = AccountIsAuthenticated(); model.CreatedBy = AccountIsAuthenticated(); model.bLock = true; MessageModel msg = _accountService.CreateAccount(model); if (msg.result == true) { return RedirectToAction("Index", "Account", new { area = "Admin" }); } if (msg.code == -2) { msg.message = "UserName exist in system, please check again."; } ViewBag.message = Globals.ErrorMessage(msg.message, msg.result); return View(); } } }
using System.Collections; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; public class SocketIoClientHandshake { private string key1 = null; private string key2 = null; private byte[] key3 = null; public byte[] expectedServerResponse = null; private Uri url = null; private string origin = null; private string protocol = null; private Random r = new Random(); public SocketIoClientHandshake(Uri url, string protocol) { this.url = url; this.protocol = null; generateKeys(); } public byte[] getHandshake() { string path = url.LocalPath; string host = url.Host; origin = "http://" + host; string handshake = "GET " + path + " HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: " + host + "\r\n" + "Origin: " + origin + "\r\n" /*+ "Sec-WebSocket-Key2: " + key2 + "\r\n" + "Sec-WebSocket-Key1: " + key1 + "\r\n"*/; /* Not using handshake currently */ if (protocol != null) { handshake += "Sec-WebSocket-Protocol: " + protocol + "\r\n"; } handshake += "\r\n"; return Encoding.UTF8.GetBytes(handshake); } public void verifyServerResponse(byte[] response) { if (!response.Equals(expectedServerResponse)) { throw new SocketIoClientException("Handshake failed"); } } public void verifyServerStatusLine(string statusLine) { int statusCode = int.Parse(statusLine.Substring(9, 3)); if (statusCode == 407) { throw new SocketIoClientException("connection failed: proxy authentication not supported"); } else if (statusCode == 404) { throw new SocketIoClientException("connection failed: 404 not found"); } else if (statusCode != 101) { throw new SocketIoClientException("connection failed: unknown status code " + statusCode); } } public void verifyServerHandshakeHeaders(Dictionary<string, string> headers) { if (!headers["Upgrade"].Equals("WebSocket")) { throw new SocketIoClientException("connection failed: missing header field in server handshake: Upgrade"); } else if (!headers["Connection"].Equals("Upgrade")) { throw new SocketIoClientException("connection failed: missing header field in server handshake: Connection"); } else if (!headers["WebSocket-Origin"].Equals(origin)) { /* should be "Sec-"WebSocket-Origin if handshakes worked */ throw new SocketIoClientException("connection failed: missing header field in server handshake: Sec-WebSocket-Origin"); } } private void generateKeys() { int spaces1 = r.Next(1,12); int spaces2 = r.Next(1,12); int max1 = int.MaxValue / spaces1; int max2 = int.MaxValue / spaces2; int number1 = r.Next(0, max1); int number2 = r.Next(0, max2); int product1 = number1 * spaces1; int product2 = number2 * spaces2; key1 = product1.ToString(); key2 = product2.ToString(); key1 = insertRandomCharacters(key1); key2 = insertRandomCharacters(key2); key1 = insertSpaces(key1, spaces1); key2 = insertSpaces(key2, spaces2); key3 = createRandomBytes(); //ByteBuffer buffer = ByteBuffer.allocate(4); MemoryStream buffer = new MemoryStream(4); //buffer.putInt(number1); using (BinaryWriter writer = new BinaryWriter(buffer)) { writer.Write(number1); } //byte[] number1Array = buffer.array(); byte[] number1Array = buffer.ToArray(); //buffer = ByteBuffer.allocate(4); buffer = new MemoryStream(4); //buffer.putInt(number2); using (BinaryWriter writer = new BinaryWriter(buffer)) { writer.Write(number2); } //byte[] number2Array = buffer.array(); byte[] number2Array = buffer.ToArray(); byte[] challenge = new byte[16]; Array.Copy(number1Array, 0, challenge, 0, 4); Array.Copy(number2Array, 0, challenge, 4, 4); Array.Copy(key3, 0, challenge, 8, 8); expectedServerResponse = md5(challenge); } private string insertRandomCharacters(string key) { int count = r.Next(1, 12); char[] randomChars = new char[count]; int randCount = 0; while (randCount < count) { int rand = (int) (((float)r.NextDouble()) * 0x7e + 0x21); if (((0x21 < rand) && (rand < 0x2f)) || ((0x3a < rand) && (rand < 0x7e))) { randomChars[randCount] = (char) rand; randCount += 1; } } for (int i = 0; i < count; i++) { int split = r.Next(0, key.Length); String part1 = key.Substring(0, split); String part2 = key.Substring(split); key = part1 + randomChars[i] + part2; } return key; } private string insertSpaces(String key, int spaces) { for (int i = 0; i < spaces; i++) { int split = r.Next(0, key.Length); String part1 = key.Substring(0, split); String part2 = key.Substring(split); key = part1 + " " + part2; } return key; } private byte[] createRandomBytes() { byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { bytes[i] = (byte) r.Next(0, 255); } return bytes; } private byte[] md5(byte[] bytes) { System.Security.Cryptography.MD5 md = System.Security.Cryptography.MD5.Create(); return md.ComputeHash(bytes); } }
// ---------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="IConnectionMessageHandler.cs" company="David Eiwen"> // Copyright © 2016 by David Eiwen // </copyright> // <author>David Eiwen</author> // <summary> // This file contains the IConnectionMessageHandler interface. // </summary> // ---------------------------------------------------------------------------------------------------------------------------------------- namespace IndiePortable.Communication.Devices { using System; using ConnectionMessages; /// <summary> /// Represents a message handler for a connection message. /// </summary> public interface IConnectionMessageHandler { /// <summary> /// Gets the type of the handled messages. /// </summary> /// <value> /// Contains the type of the handled messages. /// </value> Type MessageType { get; } /// <summary> /// Handles the specified message. /// </summary> /// <param name="message"> /// The <see cref="ConnectionMessageBase" /> that shall be handled. /// Must not be <c>null</c>. /// Must be of type <see cref="MessageType" />. /// </param> /// <exception cref="ArgumentNullException"> /// <para>Thrown if <paramref name="message" /> is <c>null</c>.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para>Thrown if <paramref name="message" /> is not of type <see cref="MessageType" />.</para> /// </exception> void HandleMessage(ConnectionMessageBase message); } }
namespace Bjerner.LoremIpsum.Providers { public class UmbracoProvider : Provider { public override string PreText { get { return "Umbraco ipsum dolor sit amet"; } } public override string[] Words { get { return new[] { "Web Platform Installer", "Our.Umbraco.org", "XSLT", "Umbraco.tv", "Examine", "XSLT Extensions", "Base", "Windows Azure", "certified partners", "certified developer", "Concorde", "Razor", "MVC", "model", "data types", "documents", "Contour", "content", "media", "XML", "dashboards", "CropUp", "stream", "#H5YR", "SQL CE", "DAMP", "uComponents", "Concierge", "CMSImport", "NodeFactory", "Confidence", "macro engine", "MVPs", "property editor", "document types", ".NET usercontrol", "packages", "view", "service", "API", "picker", "release", "publish", "CodeGarden", "uHangout", "pull request", "CMS", "meetup", "partial view", "macro", "SirTrevor", "api controller", "surface controller", "TinyMCE" }; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Master.Contract; namespace Master.Contract { public class Merchant : IContract { public Merchant() { } public Int16 BranchID { get; set; } public string MerchantCode { get; set; } public string MerchantName { get; set; } public Int16 BillingBranchID { get; set; } public string BillingCustomer { get; set; } public string PortCode { get; set; } public string RegNo { get; set; } public string TaxID { get; set; } public string OwnerCode { get; set; } public string AgentCode { get; set; } public string YardCode { get; set; } public Int16 BillingMethod { get; set; } public Int32 CreditTerm { get; set; } public decimal CreditLimit { get; set; } public string DefaultCurrency { get; set; } public string CreditorCode { get; set; } public string DebtorCode { get; set; } public string EDIMappingCode { get; set; } public string WebSite { get; set; } public string Remarks { get; set; } public bool IsBillingCustomer { get; set; } public bool IsShipper { get; set; } public bool IsConsignee { get; set; } public bool IsLiner { get; set; } public bool IsForwarder { get; set; } public bool IsYard { get; set; } public bool IsCFS { get; set; } public bool IsRailOperator { get; set; } public bool IsTerminal { get; set; } public bool IsPrincipal { get; set; } public bool IsVMIVendor { get; set; } public bool IsHaulier { get; set; } public bool IsTransporter { get; set; } public bool IsVendor { get; set; } public bool IsRailYard { get; set; } public bool IsTaxable { get; set; } public bool IsSelectContainer { get; set; } public decimal CurrentBalance { get; set; } public bool IsActive { get; set; } public string CreatedBy { get; set; } public DateTime CreatedOn { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedOn { get; set; } public List<Address> AddressList { get; set; } public List<MerchantRelation> MerchantRelationList { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HCL.Academy.Model; using HCLAcademy.Controllers; using System.Threading.Tasks; using System.Net.Http; using HCLAcademy.Util; using Microsoft.ApplicationInsights; using System.Diagnostics; namespace HCL.Academy.Web.Controllers { public class SecondLevelProjectController : BaseController { // GET: SecondLevelProject public ActionResult Index() { return View(); } [ActionName("ProjectAdmin")] [Authorize] [SessionExpire] public async Task<ActionResult> ProjectAdmin(int parentProjectId) { Project project = new Project(); InitializeServiceClient(); HttpResponseMessage adminResponse = await client.PostAsJsonAsync("Project/GetProjectAdmin?projectid="+ parentProjectId.ToString(), req); List<ProjectAdmin> admins = await adminResponse.Content.ReadAsAsync<List<ProjectAdmin>>(); HttpResponseMessage userResponse = await client.PostAsJsonAsync("User/GetUsers", req); ViewBag.Users = await userResponse.Content.ReadAsAsync<List<Users>>(); HttpResponseMessage response = await client.PostAsJsonAsync("Project/EditProjectByID?projectID=" + parentProjectId, req); project = await response.Content.ReadAsAsync<Project>(); ViewBag.ProjectName = project.projectName; ViewBag.ProjectId = parentProjectId; project.projectAdmins = admins; return View(project); } [HttpPost] [Authorize] [SessionExpire] public async Task<bool> AddProject(string projectname,int parentProjectId) { InitializeServiceClient(); HttpResponseMessage response = await client.PostAsJsonAsync("Project/AddProjectDetails?name=" + projectname + "&parentprojectid="+ parentProjectId + "&projectlevel=2", req); return true; } [ActionName("ManageChildProject")] [Authorize] [SessionExpire] public async Task<ActionResult> ManageChildProject(int parentProjectId) { InitializeServiceClient(); UserManager user = (UserManager)Session["CurrentUser"]; Project project = new Project(); HttpResponseMessage response = await client.PostAsJsonAsync("Project/EditProjectByID?projectID=" + parentProjectId, req); project = await response.Content.ReadAsAsync<Project>(); ViewBag.ProjectName = project.projectName; ViewBag.ProjectId = parentProjectId; HttpResponseMessage projectResponse = await client.PostAsJsonAsync("Project/GetProjectByParent?projectid="+ parentProjectId.ToString(), req); List<Project> projects = await projectResponse.Content.ReadAsAsync<List<Project>>(); List<Project> childProjects = new List<Project>(); if (user.GroupPermission > 2 || user.Admininfo.IsFirstLevelAdmin || user.Admininfo.IsSecondLevelAdmin) childProjects = projects; else if (user.Admininfo.IsThirdLevelAdmin) { foreach (Project p in projects) { ProjectInfo selectedProject = user.Admininfo.ThirdLevelProjects.Find(x => x.ProjectId == p.id); if (selectedProject != null) { childProjects.Add(p); } } } return View(childProjects); } [Authorize] [HttpPost] [SessionExpire] public async Task<bool> AddAdmin(int userid,int projectid) { InitializeServiceClient(); HttpResponseMessage response = await client.PostAsJsonAsync("Project/AddProjectAdmin?userid=" + userid+"&projectid="+projectid, req); return true; } [HttpPost] // GET: SecondLevelProject/Details/5 public ActionResult Details(int id) { return View(); } // GET: SecondLevelProject/Create public ActionResult Create() { return View(); } // POST: SecondLevelProject/Create [HttpPost] public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } /// <summary> /// Edit the information of the selcted project /// </summary> /// <param name="projectID"></param> /// <returns></returns> [HttpGet] [Authorize] [SessionExpire] public async Task<ActionResult> EditProjects(int projectID) { Project project = new Project(); InitializeServiceClient(); try { HttpResponseMessage response = await client.PostAsJsonAsync("Project/EditProjectByID?projectID=" + projectID, req); project = await response.Content.ReadAsAsync<Project>(); Session["EditProject"] = project; } catch (Exception ex) { //UserManager user = (UserManager)Session["CurrentUser"]; //LogHelper.AddLog("ProjectController", ex.Message, ex.StackTrace, "HCL.Academy.Web", user.EmailID); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } return View(project); } /// <summary> /// Edits/Updates the information of the selected project. /// </summary> /// <param name="projectName"></param> /// <returns></returns> [Authorize] [HttpPost] [SessionExpire] public async Task<ActionResult> EditProjects(string projectName) { if (projectName.Equals(String.Empty)) { ModelState.AddModelError("ProjectName", "Project Name is required"); } try { if (ModelState.IsValid) { Project project = (Project)Session["EditProject"]; InitializeServiceClient(); UserProjectRequest userProjectInfo = new UserProjectRequest(); userProjectInfo.ProjectName = projectName; userProjectInfo.ProjectId = project.id; userProjectInfo.ClientInfo = req.ClientInfo; HttpResponseMessage ProjResponse = await client.PostAsJsonAsync("Project/UpdateProject", userProjectInfo); return RedirectToAction("Index","FirstLevelProject"); } else { return View(); } } catch (Exception ex) { // UserManager user = (UserManager)Session["CurrentUser"]; //LogHelper.AddLog("SecondLevelProjectController", ex.Message, ex.StackTrace, "HCL.Academy.Web", user.EmailID); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); return View(); } } // GET: SecondLevelProject/Delete/5 public async Task<ActionResult> Delete(int id,int projectid) { InitializeServiceClient(); HttpResponseMessage response = await client.PostAsJsonAsync("Project/DeleteProjectAdmin?projectid="+projectid+"&userid=" + id, req); return RedirectToAction("ProjectAdmin", "SecondLevelProject",new { parentProjectId = projectid }); } /// <summary> /// Delete selected project /// </summary> /// <param name="projectID"></param> /// <returns></returns> [Authorize] [SessionExpire] public async Task<ActionResult> DeleteProject(int projectID) { try { InitializeServiceClient(); UserProjectRequest userProjectInfo = new UserProjectRequest(); userProjectInfo.ProjectId = projectID; userProjectInfo.ClientInfo = req.ClientInfo; HttpResponseMessage ProjResponse = await client.PostAsJsonAsync("Project/RemoveProject", userProjectInfo); return RedirectToAction("Index", "FirstLevelProject"); } catch (Exception ex) { //UserManager user = (UserManager)Session["CurrentUser"]; //LogHelper.AddLog("SecondLevelProjectController", ex.Message, ex.StackTrace, "HCL.Academy.Web", user.EmailID); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); return PartialView(new Project()); } } // POST: SecondLevelProject/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
// ----------------------------------------------------------------------- // <copyright file="CodegenTypeAttribute.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- using System; namespace Mlos.SettingsSystem.Attributes { /// <summary> /// An attribute class to mark a C# data structure as a eligible for code generation. /// </summary> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class, AllowMultiple = false)] public class CodegenTypeAttribute : BaseCodegenAttribute { } /// <summary> /// An attribute to mark a C# data structure as a message type. /// </summary> public class CodegenMessageAttribute : CodegenTypeAttribute { } /// <summary> /// An attribute to mark a C# data structure as a component configuration. /// </summary> /// <remarks> /// Component configuration structures do not allow variable length fields. /// </remarks> public class CodegenConfigAttribute : CodegenTypeAttribute { } }
namespace WebApplication1.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Firebird.L_ADD_T")] public partial class AddressLocatorType { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public AddressLocatorType() { AddressLocators = new HashSet<AddressLocator>(); } [Key, Column("ID")] public Guid Id { get; set; } [Required] [StringLength(128)] [Column("NAME")] public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AddressLocator> AddressLocators { get; set; } } }
using AppDuoXF.Interfaces; using Xamarin.Forms; namespace AppDuoXF.Views { public partial class RankingView : ContentPage, ITabPageIcons { public RankingView() { InitializeComponent(); } public string GetIcon() { return "tab_ranking"; } public string GetSelectedIcon() { return "tab_ranking_selected"; } } }
#load "..\Shared\AirtableHandler.csx" #load "MerchandiseItem.csx" #load "..\Shared\NotificationManager.csx" using AirtableApiClient; using HtmlAgilityPack; private static TraceWriter _logger; private static AirtableHandler _airtableHandler; private static NotificationManager _notificationManager; public static async Task Run(TimerInfo myTimer, TraceWriter log) { var baseKey = Utility.GetEnvironmentVariable("Airtable_MerchandiseBaseKey"); var tableName = Utility.GetEnvironmentVariable("Airtable_MerchandiseTableName"); _airtableHandler = new AirtableHandler(log, baseKey, tableName); _notificationManager = new NotificationManager(log); _logger = log; _logger.Info($"Start time: {DateTime.Now}"); var merchandiseItems = await GetMerchandiseItems(); _logger.Info($"Items Found: {merchandiseItems.Count}"); foreach (var item in merchandiseItems) { _logger.Info($"Item: {item.Name}"); if (!(await _airtableHandler.RecordExists("Id", item.Id.ToString()))) { _logger.Info($"New result found: {item.Id}"); var fields = new Fields(); fields.AddField("Id", item.Id); fields.AddField("Name", item.Name); fields.AddField("Description", item.Description); fields.AddField("DetailsUrl", item.DetailsUrl); fields.AddField("Price", item.Price); await _airtableHandler.AddRecordToTable(fields); var message = $"*shopDisney Limited Edition Item*\n*Name:* {item.Name}\n*Price:* {item.Price}\n<https://www.shopdisney.com{item.DetailsUrl}|Details>"; await _notificationManager.SendSlackNotification(message, "shirt"); } } } private static async Task<List<MerchandiseItem>> GetMerchandiseItems() { const string url = "https://www.shopdisney.com/disney-parks-limited-release-items"; var htmlWeb = new HtmlWeb(); var htmlDocument = htmlWeb.Load(url); var items = htmlDocument.DocumentNode.SelectNodes("//ul[@class='items-container']//li"); var merchandiseItems = new List<MerchandiseItem>(); foreach (var item in items) { var titleDiv = item.SelectSingleNode(".//div[@class='title']"); var merchandiseItem = new MerchandiseItem { Id = Int32.Parse(titleDiv.Attributes["id"].Value.Replace("-title", String.Empty)), Name = titleDiv.InnerText, DetailsUrl = item.SelectSingleNode(".//a[@class='ada-el-focus']").Attributes["href"].Value, Price = item.SelectSingleNode(".//span[@class='price listprice']").InnerText }; merchandiseItems.Add(merchandiseItem); } return merchandiseItems; }
using System.Collections.Generic; namespace Bindable.Linq.Interfaces.Internal { internal interface IEditableBindableGrouping<TKey, TElement> : IBindableGrouping<TKey, TElement> { /// <summary> /// Adds a range of elements to the collection. /// </summary> /// <param name="elements">The elements.</param> void AddRange(IEnumerable<TElement> elements); /// <summary> /// Removes a range of elements from the collection. /// </summary> /// <param name="elements">The elements.</param> void RemoveRange(IEnumerable<TElement> elements); /// <summary> /// Replaces a range of elements in the collection with another range. /// </summary> /// <param name="oldItems">The old items.</param> /// <param name="newItems">The new items.</param> void ReplaceRange(IEnumerable<TElement> oldItems, IEnumerable<TElement> newItems); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class scrPlayerGlobalCooldown : MonoBehaviour { [Header("Cooldown")] public float currentGlobalCooldown; private void Update() { if(!GetComponent<scrPlayerPaused>().playerPaused) GlobalCooldownUpdate(); } void GlobalCooldownUpdate() { if (currentGlobalCooldown > 0) currentGlobalCooldown -= Time.deltaTime; if (currentGlobalCooldown < 0) currentGlobalCooldown = 0; } }
using UnityEngine; using System.Collections; using uFrame.Attributes; using Leap; using System; [ActionLibrary, uFrameCategory ("Hand")] public static class HandUtils { public static void getLeftHandIfNotNull (out Hand left, Action success) { Frame frame = FrameUtils.getFrame (); for (int i = 0; i < frame.Hands.Count; i++) { if (frame.Hands [i].IsLeft) { left = frame.Hands [i]; success.Invoke (); return; } } left = null; } public static void getRightHandIfNotNull (out Hand right, Action success) { Frame frame = FrameUtils.getFrame (); for (int i = 0; i < frame.Hands.Count; i++) { if (frame.Hands [i].IsRight) { right = frame.Hands [i]; success.Invoke (); return; } } right = null; } public static Vector getPalNormal (Hand hand) { return hand.PalmNormal; } /* public static Finger getFinger(int index, Hand hand) { return hand.Finger(index); }*/ public static Finger getFinger (int index, Hand hand) { return hand.Fingers [index]; } public static Boolean isThumpUp (Vector direction, Hand right) { return direction.z <= -0.8f && right.PalmNormal.y <= -0.8f; } public static Boolean isThumpDown (Vector direction, Hand right) { return direction.z >= 0.8f && right.PalmNormal.y >= 0.8f; } public static Boolean isMenuOpenGestureSatisfied (Hand hand) { //Debug.Log ("Hand Normal: " + hand.PalmNormal); //Debug.Log ("Hand Direction: " + hand.Direction); return hand.PalmNormal.y <= -0.76f && hand.Direction.x <= 0.2f && hand.Direction.x >= -0.92f; } public static Vector getDirection (Hand hand) { return hand.Direction; } public static float getPinchDistance (Hand hand) { return hand.PinchDistance; } public static float getPinchStrength (Hand hand) { return hand.PinchStrength; } public static float getTimeVisible (Hand hand) { return hand.TimeVisible; } public static Vector getWristPosition (Hand hand) { return hand.WristPosition; } public static bool isLeft (Hand hand) { return hand.IsLeft; } public static bool isRight (Hand hand) { return hand.IsRight; } public static float getGrabAngle (Hand hand) { return hand.GrabAngle; } public static float getGrabStrength (Hand hand) { return hand.GrabStrength; } public static Arm getArm (Hand hand) { return hand.Arm; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HaloHistory.Business.Entities; using HaloHistory.Business.Entities.Metadata; using HaloSharp; using HaloSharp.Extension; using HaloSharp.Model.Metadata; using HaloSharp.Query.Metadata; using Newtonsoft.Json; namespace HaloHistory.Business.Repositories.Metadata { public class MetadataRepository : IMetadataRepository { private readonly ICartographerContext _db; private readonly IHaloSession _session; private bool _updatedWeapons; public MetadataRepository(ICartographerContext context, IHaloSession session) { _session = session; _db = context; } public async Task<Commendation> GetCommendation(Guid id) { var item = await _db.FindAsync<CommendationData, string, Commendation>(id.ToString()); return item; } public async Task<CompetitiveSkillRankDesignation> GetCompetitiveSkillRankDesignation(int id) { var item = await _db.FindAsync<CompetitiveSkillRankDesignationData, int, CompetitiveSkillRankDesignation>(id); return item; } public async Task<Enemy> GetEnemy(long id) { var item = await _db.FindAsync<EnemyData, long, Enemy>(id); return item; } public async Task<FlexibleStat> GetFlexibleStat(Guid id) { var item = await _db.FindAsync<FlexibleStatData, string, FlexibleStat>(id.ToString()); return item; } public async Task<GameBaseVariant> GetGameBaseVariant(Guid id) { if (id == Guid.Empty) return null; var item = await _db.FindAsync<GameBaseVariantData, string, GameBaseVariant>(id.ToString()); return item; } public async Task<GameVariant> GetGameVariant(Guid id) { if (id == Guid.Empty) return null; var data = await _db.FindAsync<GameVariantData>(id.ToString()); if (data == null) { var query = new GetGameVariant().ForGameVariantId(id); var item = await _session.Query(query); if (item == null) return null; data = new GameVariantData(id, item); _db.InsertAsync(data); return item; } return data.Deserialize(); } public async Task<Impulse> GetImpulse(long id) { var item = await _db.FindAsync<ImpulseData, long, Impulse>(id); return item; } public async Task<Map> GetMap(Guid id) { if (id == Guid.Empty) return null; var item = await _db.FindAsync<MapData, string, Map>(id.ToString()); return item; } public async Task<MapVariant> GetMapVariant(Guid id) { if (id == Guid.Empty) return null; var data = await _db.FindAsync<MapVariantData, string, MapVariant>(id.ToString()); if (data == null) { var query = new GetMapVariant().ForMapVariantId(id); var item = await _session.Query(query); if (item == null) return null; var d = new MapVariantData(id, item); _db.InsertAsync<MapVariantData, string, MapVariant>(d, true); return item; } return data; } public async Task<Medal> GetMedal(long id) { var item = await _db.FindAsync<MedalData, long, Medal>(id); return item; } public async Task<Playlist> GetPlaylist(Guid id) { if (id == Guid.Empty) return null; var item = await _db.FindAsync<PlaylistData>(id.ToString()); if (item == null) { await Populate(new GetPlaylists(), d => new PlaylistData(d.Id, d), true); item = await _db.FindAsync<PlaylistData>(id.ToString()); } return item?.Deserialize(); } public async Task<Season> GetSeason(Guid? id) { if (!id.HasValue || id== Guid.Empty) return null; var item = await _db.FindAsync<SeasonData>(id.ToString()); if (item == null) { await Populate(new GetSeasons(), d => new SeasonData(d.Id, d), true); item = await _db.FindAsync<SeasonData>(id.ToString()); } return item.Deserialize(); } public async Task<Skull> GetSkull(int id) { var item = await _db.FindAsync<SkullData, int, Skull>(id); return item; } public async Task<SpartanRank> GetSpartanRank(int id) { var item = await _db.FindAsync<SpartanRankData, int, SpartanRank>(id); return item; } public async Task<TeamColor> GetTeamColor(int id) { var item = await _db.FindAsync<TeamColorData, int, TeamColor>(id); return item; } public async Task<Vehicle> GetVehicle(long id) { var item = await _db.FindAsync<VehicleData, long, Vehicle>(id); return item; } public async Task<Weapon> GetWeapon(long id) { var item = await _db.FindAsync<WeaponData,long,Weapon>(id); if (item == null && !_updatedWeapons) { await Populate(new GetWeapons(), d => new WeaponData(d.Id, d), true); _updatedWeapons = true; item = await _db.FindAsync<WeaponData, long, Weapon>(id); } return item; } public async Task<Enemy> GetEnemyOrVehicle(long id) { var item = await _db.FindAsync<EnemyData>(id); if (item != null) { var enemy = item.Deserialize(); return enemy; } var vehicleData = await _db.FindAsync<VehicleData>(id); if (vehicleData != null) { return JsonConvert.DeserializeObject<Enemy>(vehicleData.Data); } return null; } public async Task<Weapon> GetWeaponOrEnemyOrVehicle(long id) { var weapon = await GetWeapon(id); if (weapon != null) return weapon; var item = await _db.FindAsync<EnemyData>(id); if (item != null) { return JsonConvert.DeserializeObject<Weapon>(item.Data); } var vehicleData = await _db.FindAsync<VehicleData>(id); if (vehicleData != null) { return JsonConvert.DeserializeObject<Weapon>(vehicleData.Data); } return null; } public async Task Initialize() { await Populate(new GetCampaignMissions(), d => new CampaignMissionData(d.Id, d)); await Populate(new GetCommendations(), d => new CommendationData(d.Id, d)); await Populate(new GetCompetitiveSkillRankDesignations(), d => new CompetitiveSkillRankDesignationData(d.Id, d)); await Populate(new GetEnemies(), d => new EnemyData(d.Id, d)); await Populate(new GetFlexibleStats(), d => new FlexibleStatData(d.Id, d)); await Populate(new GetGameBaseVariants(), d => new GameBaseVariantData(d.Id, d)); await Populate(new GetImpulses(), d => new ImpulseData(d.Id, d)); await Populate(new GetMaps(), d => new MapData(d.Id, d)); await Populate(new GetMedals(), d => new MedalData(d.Id, d)); await Populate(new GetPlaylists(), d => new PlaylistData(d.Id, d)); await Populate(new GetSeasons(), d => new SeasonData(d.Id, d)); await Populate(new GetSkulls(), d => new SkullData(d.Id, d)); await Populate(new GetSpartanRanks(), d => new SpartanRankData(d.Id, d)); await Populate(new GetTeamColors(), d => new TeamColorData(d.Id, d)); await Populate(new GetVehicles(), d => new VehicleData(d.Id, d)); await Populate(new GetWeapons(), d => new WeaponData(d.Id, d)); } private async Task Populate<T, T2>(IQuery<List<T2>> query, Func<T2, T> func, bool force = false) where T : class { bool exists = _db.Get<T>().Any(); if (!exists || force) { await _db.DeleteAsync<T>(); IEnumerable<T2> items = await _session.Query(query); var data = items.Select(func).ToArray(); _db.InsertAsync(data); await _db.CommitChanges(); } } } }
namespace Bjerner.LoremIpsum { public enum LoremIpsumType { Words, WordsAndFillers } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using liteCMS.Web.Controller; using liteCMS.Entity.CMS; using liteCMS.Logic; using liteCMS.Entity.Ventas; namespace liteCMS.Web.uc { public partial class pagina_contactos : WebContentUC { string codigo = ""; string nombre = ""; string codigoContacto = ""; protected void Page_Load(object sender, EventArgs e) { if (oPagina != null) { FillContent(); } } private void FillContent() { if (Request["codCli"] != null) codigo = Request["codCli"]; if (Request["ct"] != null) nombre = Request["ct"]; int codigoContacto = Request["codigoContacto"] != null ? Convert.ToInt32("0" + Request["codigoContacto"].ToString()) : 0; if (codigoContacto > 0) FillDetalle(codigoContacto); else BindContactos(); } protected void FillDetalle(int codigoContacto) { eContacto oContacto = lVentas.Contacto_item(codigoContacto); if (oContacto != null) { divFiltros.Visible = false; divDetalle.Visible = true; litNombre.Text = oContacto.nombre; litCargo.Text = oContacto.cargo; litEmail.Text = oContacto.correo; litMovil.Text = oContacto.celular; litTelefono.Text = oContacto.telefono; litFechaCumpleaņos.Text = oContacto.fechaCumple; } else { BindContactos(); } } protected void BindContactos() { divFiltros.Visible = true; divDetalle.Visible = false; List<eContacto> lContacto = lVentas.Contacto_listar_uc(codigo, txtNombre.Text, "", 0); if (lContacto.Count > 0) { repContactos.DataSource = lContacto; repContactos.DataBind(); } else { lblMensaje.Visible = true; } } protected void lbtBuscarContacto_Click(object sender, EventArgs e) { if (Request["codCli"] != null) codigo = Request["codCli"]; List<eContacto> lContacto = lVentas.Contacto_listar_uc(codigo, txtNombre.Text, txtCargo.Text, int.Parse(ddlFiltro.SelectedValue)); repContactos.DataSource = lContacto; repContactos.DataBind(); } protected void repContactos_ItemDataBound(object sender, RepeaterItemEventArgs e) { Literal litContacto = (Literal)e.Item.FindControl("litContacto"); Literal litCargo = (Literal)e.Item.FindControl("litCargo"); Literal liCorreo = (Literal)e.Item.FindControl("liCorreo"); Literal litCelular = (Literal)e.Item.FindControl("litCelular"); Literal litTelefono = (Literal)e.Item.FindControl("litTelefono"); Literal litFechaCumple = (Literal)e.Item.FindControl("litFechaCumple"); if (litContacto != null) { eContacto oContacto = (eContacto)e.Item.DataItem; //litContacto.Text = "<a class=\"persona-info\" href=\"" + ClientScriptHelper.getURLRoot() + "lightContacto.aspx?nombre=" + oContacto.nombre + "&cargo=" + oContacto.cargo + "&email=" + oContacto.correo + "&movil=" + oContacto.celular + "&telefono=" + oContacto.telefono + "&fechaCumpleaņos=" + oContacto.fechaCumple + "\" >" + oContacto.nombre + "</a>"; litContacto.Text = "<a class=\"persona-info\" href=\"" + ClientScriptHelper.getURLRoot() + "Index.aspx?aID=" + oPagina.IdArticulo + "&codCli=" + oContacto.codigoCliente + "&codigoContacto=" + oContacto.codigoContacto + "\" >" + oContacto.nombre + "</a>"; litCargo.Text = oContacto.cargo; //liCorreo.Text = oContacto.correo; //litCelular.Text = oContacto.celular; //litTelefono.Text = oContacto.telefono; //litFechaCumple.Text = oContacto.fechaCumple; } } } }
using System; namespace JiraExport { public sealed class JiraAttachment : IEquatable<JiraAttachment> { public string Id { get; internal set; } public string Filename { get; internal set; } public string Url { get; internal set; } public string ThumbUrl { get; internal set; } public string LocalPath { get; internal set; } public string LocalThumbPath { get; internal set; } public bool Equals(JiraAttachment other) { return Id == other.Id; } public override string ToString() { return $"{Id}/{Filename}"; } } }
namespace Requestrr.WebApi.RequestrrBot.Movies { public class MovieUserRequester { public string UserId { get; } public string Username { get; } public MovieUserRequester(string userId, string username) { UserId = userId; Username = username; } } }
using BPiaoBao.SystemSetting.Domain.Models.SMS; using JoveZhao.Framework.SMS; using System; using System.Collections.Generic; using System.Linq; using System.Text; using JoveZhao.Framework.Expand; using BPiaoBao.Common.Enums; using JoveZhao.Framework; using BPiaoBao.Common; namespace BPiaoBao.SystemSetting.Domain.Models.Businessmen { /// <summary> /// 商户员工行为 /// </summary> public partial class Businessman { /// <summary> /// 查找员工 /// </summary> /// <param name="account"></param> /// <returns></returns> public Operator FindByAccount(string account) { var vm = this.Operators.SingleOrDefault(p => p.Account == account); if (vm == null) throw new CustomException(404, "账户不存在"); return vm; } /// <summary> /// 创建新操作员 /// </summary> /// <param name="oper"></param> public void NewOperator(Operator oper) { if (!this.CheckAccountExists(oper.Account)) { oper.Password = oper.Password.Md5(); oper.CreateDate = DateTime.Now; this.Operators.Add(oper); } else { throw new CustomException(500, "账户已存在!"); } } /// <summary> /// 登录 /// </summary> /// <param name="account">账户</param> /// <param name="password">密码</param> /// <returns></returns> public Operator GetOperatorByPasswordAndAccount(string account, string password) { string md5Password = password.Md5(); var ope = this.Operators.Where(p => string.Equals(p.Account, account, StringComparison.InvariantCultureIgnoreCase) && p.Password == md5Password).FirstOrDefault(); return ope; } /// <summary> /// 修改密码 /// </summary> /// <param name="account"></param> /// <param name="newPassword"></param> public void ChangePassword(string account, string oldPassword, string newPassword) { var vm = this.FindByAccount(account); if (vm != null) { if (vm.Password != oldPassword.Md5()) throw new CustomException(404, "原始密码输入错误!"); vm.Password = newPassword.Md5(); } } /// <summary> /// 搜索员工 /// </summary> /// <param name="realName"></param> /// <param name="account"></param> /// <param name="operatorState"></param> /// <returns></returns> public IQueryable<Operator> GetOperatorsBySearch(string realName, string account, EnumOperatorState? operatorState) { var query = this.Operators.AsQueryable(); if (!string.IsNullOrEmpty(realName) && !string.IsNullOrEmpty(realName.Trim())) query = query.Where(p => p.Realname.Contains(realName.Trim())); if (!string.IsNullOrEmpty(account) && !string.IsNullOrEmpty(account.Trim())) query = query.Where(p => p.Account.ToLower().Contains(account.Trim().ToLower())); if (operatorState != null) query = query.Where(p => p.OperatorState == operatorState.Value); return query; } /// <summary> /// 当前账户是否重复 /// </summary> /// <param name="account"></param> /// <returns>存在True</returns> public bool IsExistAccount(string account) { return this.Operators.Where(p => p.Account == account).Count() == 0; } /// <summary> /// 移除员工 /// </summary> /// <param name="account"></param> public void RemoveOperator(string account) { var currentAccount = FindByAccount(account); if (currentAccount != null) this.Operators.Remove(currentAccount); } /// <summary> /// 验证账户是否存在 /// </summary> /// <param name="account"></param> /// <returns></returns> public bool CheckAccountExists(string account) { return this.Operators.SingleOrDefault(p => p.Account == account) != null ? true : false; } /// <summary> /// 修改员工信息 /// </summary> /// <param name="op"></param> public void UpdateOperator(Operator op) { Operator vm = this.FindByAccount(op.Account); vm.Realname = op.Realname; vm.Phone = op.Phone; // vm.Password = op.Password.Md5(); } /// <summary> /// 启用,禁用 /// </summary> /// <param name="account"></param> public void CanExecute(string account) { var vm = this.FindByAccount(account); vm.OperatorState = vm.OperatorState == EnumOperatorState.Normal ? EnumOperatorState.Frozen : EnumOperatorState.Normal; } } /// <summary> /// 商户短信 /// </summary> public partial class Businessman { /// <summary> /// 发送消息 /// </summary> /// <param name="sendDetail"></param> public void SendMessage(string oName, string receiveName, string receiveNum, string content) { Tuple<int, bool> result = SMSServiceFactory.GetEmailService().SMS(receiveNum, content); SendDetail detail = new SendDetail { Content = content, Name = oName, ReceiveName = receiveName, ReceiveNum = receiveNum, SendTime = DateTime.Now, SendState = result.Item2, SendCount = result.Item1 }; if (result.Item2) { this.SMS.Send(result.Item1); } this.SendDetails.Add(detail); } /// <summary> /// 消息发送记录列表 /// </summary> /// <param name="currentPageIndex">当前页</param> /// <param name="pageSize">分页大小【默认10】</param> /// <param name="startTime">查询开始时间</param> /// <param name="endTime">截至时间</param> /// <returns></returns> public Tuple<int, IList<SendDetail>> GetSendRecordByPage(int currentPageIndex, int? pageSize, DateTime? startTime, DateTime? endTime) { int pSize = pageSize ?? 10; int count = ((currentPageIndex == default(int) ? 1 : currentPageIndex) - 1) * pSize; var query = this.SendDetails.AsQueryable(); if (startTime.HasValue) query = query.Where(p => p.SendTime >= startTime.Value); if (endTime.HasValue) query = query.Where(p => p.SendTime <= endTime.Value); var totalCount = query.Count(); var list = query.OrderByDescending(x => x.SendTime).Skip(count).Take(pSize).ToList(); return Tuple.Create<int, IList<SendDetail>>(totalCount, list); } public void BuySms(BuyDetail buyDetail) { this.BuyDetails.Add(buyDetail); } public string GetPayNo() { return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), new Random().Next(1000, 9999).ToString()); } /// <summary> /// 购买短信 /// </summary> /// <param name="oName">操作员姓名</param> /// <param name="count">购买条数</param> /// <param name="payWay">支付方式</param> /// <param name="payAmount">支付金额</param> /// <returns>支付URL地址信息</returns> public string BuySms(string oName, int count, EnumPayMethod payWay, decimal payAmount) { string payNo = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), new Random().Next(1000, 9999).ToString()); BuyDetail buyDetail = new BuyDetail { BuyState = EnumPayStatus.NoPay, PayNo = payNo, BuyTime = DateTime.Now, Count = count, Name = oName, PayAmount = payAmount, PayWay = payWay, PayFee = Math.Round(payAmount * SystemConsoSwitch.Rate, 2) }; this.BuyDetails.Add(buyDetail); return payNo; } /// <summary> /// 异步通知更新 /// </summary> public void SMSNotify(string payno, string outPayno,EnumPayMethod payMethod) { var model = this.BuyDetails.Where(x => x.PayNo == payno).SingleOrDefault(); model.OutPayNo = outPayno; model.PayTime = DateTime.Now; model.BuyState = EnumPayStatus.OK; model.PayWay = payMethod; this.SMS.Buy(model.Count); } /// <summary> /// 消息发送记录列表 /// </summary> /// <param name="currentPageIndex">当前页</param> /// <param name="pageSize">分页大小【默认10】</param> /// <param name="startTime">查询开始时间</param> /// <param name="endTime">截至时间</param> /// <param name="outTradeNo"></param> /// <returns></returns> public Tuple<int, IList<BuyDetail>> GetBuyRecordByPage(int currentPageIndex, int? pageSize, DateTime? startTime, DateTime? endTime, string outTradeNo = null) { int pSize = pageSize ?? 10; int count = ((currentPageIndex == default(int) ? 1 : currentPageIndex) - 1) * pSize; var query = this.BuyDetails.AsQueryable(); if (startTime.HasValue) query = query.Where(p => p.BuyTime >= startTime.Value); if (endTime.HasValue) query = query.Where(p => p.BuyTime <= endTime.Value); if (!string.IsNullOrWhiteSpace(outTradeNo)) { query = query.Where(p => p.OutPayNo == outTradeNo.Trim()); } var totalCount = query.Count(); var list = query.OrderByDescending(x => x.BuyTime).Skip(count).Take(pSize).ToList(); return Tuple.Create<int, IList<BuyDetail>>(totalCount, list); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConsumableItemController : MonoBehaviour { [SerializeField] GameObject itemPrefab; private List<GameObject> items; int itemIndex; [SerializeField] GameObject itemSelectorPrefab; private GameObject itemSelector; [SerializeField] List<Sprite> imageList; [SerializeField] SpeedTextController speedText; [SerializeField] HealthBarController healthBar; [SerializeField] StatusEffectController statusEffectBar; [SerializeField] GameObject confirmationWindow; bool axisPressed; bool trigPressed; int currentFilter; [SerializeField] String[] filterNames; [SerializeField] Text filterName; //list<gameitem> hfhfhd; // Use this for initialization void Start () { currentFilter = 0; axisPressed = false; trigPressed = false; } // Update is called once per frame void Update () { if (((Input.GetButtonDown("Vertical")) || ((int)Input.GetAxisRaw("Vertical") != 0 && !axisPressed)) && items.Count > 0 && confirmationWindow.activeInHierarchy != true) { axisPressed = true; itemIndex = Mathf.Clamp(itemIndex + (int)Input.GetAxisRaw("Vertical"), 0, items.Count - 1); UpdateActiveItem(); } if ((Input.GetButtonDown("Submit") || Input.GetButtonDown("Fire1")) && confirmationWindow.activeInHierarchy != true) { confirmationWindow.SetActive(true); } if((Input.GetAxisRaw("RT") != 0 || Input.GetAxisRaw("LT") != 0) && !trigPressed) { trigPressed = true; int direction = 0; if (Input.GetAxisRaw("RT") != 0) { direction = 1; } else if (Input.GetAxisRaw("LT") != 0) { direction = -1; } currentFilter += direction; if (currentFilter >= filterNames.Length) currentFilter = 0; if (currentFilter < 0) currentFilter = filterNames.Length - 1; //currentFilter = Mathf.Clamp(currentFilter + direction, 0, filterNames.Length - 1); filterName.text = filterNames[currentFilter]; RandomizeItems(); } if((int)Input.GetAxisRaw("Vertical") == 0) { axisPressed = false; } if(Input.GetAxisRaw("RT") == 0 && Input.GetAxisRaw("LT") == 0) { trigPressed = false; } } private void UpdateActiveItem() { if (items.Count == 0) { healthBar.Deactivate(); speedText.Deactivate(); } else { if (itemSelector == null) { itemSelector = Instantiate(itemSelectorPrefab); } itemSelector.transform.SetParent(items[itemIndex].transform, false); Item finalItem = items[itemIndex].GetComponent<Item>(); if (finalItem != null) { switch (finalItem.GetItemType()) { case ItemType.SPEED: speedText.Activate(finalItem.GetItemValue()); healthBar.Deactivate(); statusEffectBar.Deactivate(); break; case ItemType.HEALTH: speedText.Deactivate(); healthBar.Activate(finalItem.GetItemValue()); statusEffectBar.Deactivate(); break; case ItemType.BLEEDING: healthBar.Deactivate(); speedText.Deactivate(); statusEffectBar.Activate(finalItem.GetItemType()); break; } } } } private void OnEnable() { items = new List<GameObject>(); confirmationWindow.SetActive(false); itemIndex = 0; foreach(Transform child in transform) { Destroy(child.gameObject); } for(int i = 0; i < 4; i++) { GameObject g = Instantiate(itemPrefab); g.transform.SetParent(transform, false); items.Add(g); } if(items.Count > 0) { itemSelector = Instantiate(itemSelectorPrefab); } TestFill(); UpdateActiveItem(); } private void TestFill() { items[0].GetComponent<Item>().Initialize("Haste", imageList[0], ItemType.SPEED, 25); items[1].GetComponent<Item>().Initialize("Potion S", imageList[1], ItemType.HEALTH, 25); items[2].GetComponent<Item>().Initialize("Potion X", imageList[2], ItemType.HEALTH, 75); items[3].GetComponent<Item>().Initialize("Bandage", imageList[3], ItemType.BLEEDING, 1); } public void ConsumeItem(bool success) { confirmationWindow.SetActive(false); if (success) { //include case where we delete last item in the list int adjustedFinalIndex = (itemIndex == items.Count - 1) ? itemIndex - 1 : itemIndex; GameObject i = items[itemIndex]; Item it = i.GetComponent<Item>(); switch (it.GetItemType()) { case ItemType.SPEED: Player.Instance.AddSpeed(it.GetItemValue()); break; case ItemType.HEALTH: Player.Instance.RestoreHealth(it.GetItemValue() / 100.0f); break; case ItemType.BLEEDING: Player.Instance.RemoveStatusEffect(StatusEffectType.BLEED); break; } items.RemoveAt(itemIndex); itemSelector.transform.SetParent(null, false); Destroy(i); itemIndex = adjustedFinalIndex; UpdateActiveItem(); } } private void RandomizeItems() { System.Random r = new System.Random(); for(int it = 0; it < 4; it++) { int dx = r.Next(0, items.Count - 1); GameObject first = items[dx]; items.Remove(first); items.Add(first); first.GetComponent<RectTransform>().SetAsLastSibling(); } UpdateActiveItem(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test5._5andtest5._6 { class Program { static void Main(string[] args) { ///////////////////// 试题5.5 ///////////////////// /// Console.WriteLine("请输入一个英文字符串,单词与单词之间用空格隔开。"); char[] str = Console.ReadLine().ToCharArray(); int wordNum = 1;//单词数 if (str.Length == 0) { wordNum = 0; } for (int i = 0; i < str.Length; i++) { if (i == 0 && str[i] == ' ') { wordNum = 0; } if (str[i] == ' ' && i != str.Length-1) { wordNum++; } } Console.WriteLine("当前输入的字符串中包含{0}个单词",wordNum); ///////////////////// 试题5.6 ///////////////////// Console.WriteLine("购物车明细如下:\n\n"); Console.WriteLine("商品名称\t\t数量\t价格"); string[,] info = { { "C#项目开发实战入门", "1", "68.8" }, { "零基础学C#\t", "2", "59.8" }, { "小米6高配版\t", "1", "2899" } }; double sum = 0; for (int i = 0; i < info.GetLength(0); i++) { for (int j = 0; j < info.GetLength(1); j++) { Console.Write(info[i,j] + "\t"); if (j == 1) { int a = Convert.ToInt32(info[i, j]); double b = Convert.ToDouble(info[i, j+1]); sum += (double)a * b; } } Console.WriteLine(); } Console.WriteLine("您的应付款总额为:" + sum + "元"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace IoTWebApi.Models { public class itemsIssuedModel { public int itemIssuedID { get; set; } public personModel person { get; set; } public itemModel item { get; set; } public bool? itemReturned { get; set; } public itemsIssuedModel(int itemIssuedID , personModel person, itemModel item, bool? itemReturned) { this.itemIssuedID = itemIssuedID; this.person = person; this.item = item; this.itemReturned = itemReturned; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasketLogic : MonoBehaviour { private PossessivesManager possessivesManager; private Animator anime; private List<string> fruitList; private BoxCollider objectCollider; void Start() { anime = GameObject.Find("VA").GetComponent<VirtualAssistantManager>().animator; SetupBoxCollider(); SetupGameManager(); } private void SetupBoxCollider() { objectCollider = gameObject.GetComponent<BoxCollider>(); } private void SetupGameManager() { possessivesManager = GameObject.Find("SceneManager").GetComponent<PossessivesManager>(); if (possessivesManager == null) throw new Exception("GameManager Object could not be found"); } public void SetFruitList(List<string> fruitListString) { fruitList = fruitListString; } public List<string> GetFruitList() { return fruitList; } private bool CheckIfInList(string objectStringIdentifier) { return fruitList.Contains(objectStringIdentifier); } private void OnTriggerEnter(Collider otherCollider) { //If the collider belongs to a target fruit if (CheckIfInList(otherCollider.gameObject.name)) { //Make the object disappear possessivesManager.DeactivateObject(otherCollider.gameObject.name); //Remove it from the list of target fruits fruitList.Remove(otherCollider.gameObject.name); //Trigger the positive reaction of the Virtual assistant EventManager.TriggerEvent(EventManager.Triggers.VAOk); Wait(3); } else { //Trigger the negative reaction of the Virtual assistant EventManager.TriggerEvent(EventManager.Triggers.VAKo); } } void Wait(float seconds) { StartCoroutine(_wait(seconds)); } IEnumerator _wait(float time) { yield return new WaitForSeconds(time); EventManager.TriggerEvent(EventManager.Triggers.PickedFruit); } }
namespace HH.RulesEngine.Data.Enums { public enum ShippingMethod { FirstClass = 1, SecondClass = 2, Express = 3 } }
using System; using HaloSharp.Model.Metadata; namespace HaloHistory.Business.Entities.Metadata { public class SeasonData : BaseDataEntity<string, Season> { public SeasonData() { } public SeasonData(Guid id, Season data) : base(id.ToString(), data) { } } }
using System.ComponentModel.DataAnnotations; namespace Dentist.ViewModels { public class PersonListViewModel { public int Id { get; set; } [Display(Name = "Frist Name")] [Required] public string FirstName { get; set; } [Display(Name = "Last Name")] [Required] public string LastName { get; set; } [DataType(DataType.EmailAddress)] public string Email { get; set; } [DataType(DataType.PhoneNumber)] public string Phone { get; set; } public int? AvatarId { get; set; } } }
namespace XMLApiProject.Services.Models.PaymentService.XML.RequestService.Responses { public class BINLookup { public string CardIdentifier { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Darek_kancelaria.Models { public class PersonModel { public string Id { get; set; } [Required] [Display(Name = "Imie")] public string Name { get; set; } [Required] [Display(Name = "Nazwisko")] public string FName{ get; set; } [Required] [Display(Name = "Adres")] public string Address { get; set; } [Required] [Display(Name = "Kod pocztowy")] public string Zip { get; set; } [Display(Name = "Nr. telefonu")] [Phone] public string Phone { get; set; } [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } public DateTime AddDate { get; set; } public string Role { get; set; } } }
namespace WebDataDemo.Dtos; public class CreateAuthorRequest { public string Name { get; set; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBase : MonoBehaviour, ICollider { public SpriteRenderer SpriteRenderer; public Color OneDamageColor; public Color TwoDamageColor; public Color ThreeDamageColor; public List<EnemyShooter> Shooters = new List<EnemyShooter>(); private float maxHealth = 4000; private EnemySpawner associatedSpawner; private float shotDelayMin = 2f; private float shotDelayMax = 3.5f; private float currentHealth; private void OnDestroy() { EnemyController enemyController = EnemyController.Instance; if(enemyController != null) { EnemyController.Instance.UnregisterEnemy(this); } } private void Start() { currentHealth = maxHealth; StartCoroutine(EnemyShotRoutine()); } //private void OnCollisionEnter2D(Collision2D collision) //{ // if (collision.collider.CompareTag(GameTags.Ball)) // { // BallBase ball = collision.collider.GetComponent<BallBase>(); // if(ball != null) // { // ContactPoint2D contactPoint = collision.GetContact(0); // CollisionSide colSide = CollisionSideDetect.GetCollisionSide(ball.LastFrameCenterPoint, contactPoint.point); // ball.SetOppositeVelocity(colSide, PhysicsConstants.BallSpeedAfterEnemyHit); // if (ball.LastFrameVelocity.magnitude < PhysicsConstants.BallSpeedPowerShotThreshold) // { // currentHealth--; // } // else // { // currentHealth -= 3; // } // SetColor(); // } // if(currentHealth <= 0) // { // associatedSpawner.TryToDestroy(this); // } // } //} public void OnCollisionWithBall(BallBase ball) { if (ball.LastFrameVelocity.magnitude < PhysicsConstants.BallSpeedPowerShotThreshold) { currentHealth--; } else { currentHealth -= 3; } if (currentHealth <= 0) { associatedSpawner.TryToDestroy(this); } } private void SetColor() { switch (currentHealth) { case 3: SpriteRenderer.color = OneDamageColor; break; case 2: SpriteRenderer.color = TwoDamageColor; break; case 1: SpriteRenderer.color = ThreeDamageColor; break; } } public void Init(EnemySpawner enemySpawner) { associatedSpawner = enemySpawner; } private IEnumerator EnemyShotRoutine() { while (true) { yield return new WaitForSeconds(UnityEngine.Random.Range(shotDelayMin, shotDelayMax)); Shoot(); } } public void Shoot() { if(Shooters.Count > 0) { Shooters[UnityEngine.Random.Range(0, Shooters.Count)].InitShot(); } } }
using System; namespace Shunxi.Business.Tables { public class TemperatureRecord { public int Id { get; set; } public int CellCultivationId { get; set; } public int DeviceId { get; set; } public double HeaterTemperature { get; set; } public double EnvTemperature { get; set; } public DateTime CreatedAt { get; set; } public double Temperature { get; set; } } }
using Asp.netCoreMVCCRUD.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace AspnetCoreMVCCRUD.Models { public class LoginModel { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Win32.TaskScheduler; namespace ListenRadioResvTool { class Reservation { private const string TaskFolderName = "ListenRadioReservationTool"; private static TaskFolder taskFolder { get { using (TaskService ts = new TaskService()) { try { TaskFolder folder = ts.GetFolder(TaskFolderName); if (folder == null) { throw new Exception(); } return folder; } catch { return ts.RootFolder.CreateFolder(TaskFolderName); } } } } private static string FileNameEscape(string input) { string regexSearch = new string(System.IO.Path.GetInvalidFileNameChars()) + new string(System.IO.Path.GetInvalidPathChars()); var r = new System.Text.RegularExpressions.Regex(string.Format("[{0}]", System.Text.RegularExpressions.Regex.Escape(regexSearch))); return r.Replace(input, "_").Replace(' ', '_'); } public static string ProgramToTaskName(ListenRadioAPI.DataStructure.ScheduleItem program) { return FileNameEscape(program.ProgramName + ":" + program.StartDate + "-" + program.EndDate); } public static Task AddReservation(ListenRadioAPI.DataStructure.ScheduleItem program) { try { using (TaskService ts = new TaskService()) { // create task TaskDefinition td = ts.NewTask(); td.Settings.WakeToRun = true; td.Settings.Hidden = true; td.Triggers.Add(new TimeTrigger() { StartBoundary = program.StartDateTime.AddSeconds(-Properties.Settings.Default.RecordingMargin) }); // generate command line var path = Properties.Settings.Default.ScriptPath; var duration = (program.EndDateTime - program.StartDateTime).TotalSeconds + Properties.Settings.Default.RecordingMargin * 2; var arguments = new object[] { (int)duration, program.StationName, program.StationId, program.BroadcastChannelName, program.ProgramName, program.ProgramId, program.ProgramScheduleId, program.ProgramSummary, program.StartDate, program.EndDate, program.MainteFlg, }; var argumentString = new StringBuilder(); argumentString.Append(program.ApplicationUrl + " "); argumentString.Append(program.ApplicationUrlHds + " "); argumentString.Append(program.ApplicationUrlM3u8 + " "); foreach (var o in arguments) { argumentString.Append(FileNameEscape(o.ToString()) + " "); } td.Actions.Add(new ExecAction() { Path = path, Arguments = argumentString.ToString() }); return taskFolder.RegisterTaskDefinition(ProgramToTaskName(program), td); } } catch { return null; } } public static List<Task> GetRerservationList() { List<Task> result = new List<Task>(); try { foreach (Task el in taskFolder.AllTasks) { if (el.NextRunTime < DateTime.Now) { try { taskFolder.DeleteTask(el.Name); } catch { } } else { result.Add(el); } } } catch { } return result; } public static ListenRadioAPI.DataStructure.Schedule GetReservationListAsProgram() { var resvPrograms = new ListenRadioAPI.DataStructure.Schedule(); resvPrograms.ProgramSchedule = new List<ListenRadioAPI.DataStructure.ScheduleItem>(); foreach (var item in GetRerservationList()) { var args = ((ExecAction)item.Definition.Actions[0]).Arguments.Split(' '); var program = new ListenRadioAPI.DataStructure.ScheduleItem() { ApplicationUrl = args[0], ApplicationUrlHds = args[1], ApplicationUrlM3u8 = args[2], BroadcastChannelName = args[6], EndDate = args[12], MainteFlg = args[13] == "True", ProgramId = Int32.Parse(args[8]), ProgramName = args[7], ProgramScheduleId = Int32.Parse(args[9]), ProgramSummary = args[10], StartDate = args[11], StationId = Int32.Parse(args[5]), StationName = args[4], Reserved = true, IsEnabled = true, }; resvPrograms.ProgramSchedule.Add(program); } return resvPrograms; } public static bool Cancel(ListenRadioAPI.DataStructure.ScheduleItem program) { try { taskFolder.DeleteTask(ProgramToTaskName(program)); return true; } catch { return false; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Account { class Fixed : Account { private int tenureYear = 5; private int year; public int Year { get { return year; } set { year = value; } } public Fixed() { } public Fixed(int accountID, string accountName, int balance, int year) : base(accountID, accountName, balance) { this.year = year; } public void Transfer(int amount, Account acc) { if (tenureYear == this.year) { base.Transfer(amount, acc); } else { Console.WriteLine("Sorry, you are not eligible to transfer money. Please try again.... "); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Newtonsoft.Json.Linq; namespace Microsoft.CodeAnalysis.Sarif.Multitool { public class SarifValidationContext : IAnalysisContext { public enum ReportingDescriptorKind { None, Rule, Notification, Taxon } public SarifValidationContext() { CurrentRunIndex = -1; CurrentResultIndex = -1; CurrentReportingDescriptorKind = ReportingDescriptorKind.None; } public bool IsValidAnalysisTarget { get { return Path.GetExtension(TargetUri.LocalPath).Equals(SarifConstants.SarifFileExtension, StringComparison.OrdinalIgnoreCase) || Path.GetExtension(TargetUri.LocalPath).Equals(".json", StringComparison.OrdinalIgnoreCase); } } public IAnalysisLogger Logger { get; set; } public string MimeType { get { return "application/sarif-json"; } set { throw new InvalidOperationException(); } } public bool AnalysisComplete { get; set; } public HashData Hashes { get; set; } public PropertiesDictionary Policy { get; set; } public ReportingDescriptor Rule { get; set; } public RuntimeConditions RuntimeErrors { get; set; } public Exception TargetLoadException { get; set; } public bool UpdateInputsToCurrentSarif { get; set; } private Uri _uri; public Uri TargetUri { get { return _uri; } set { if (_uri != null) { throw new InvalidOperationException(MultitoolResources.ErrorIllegalContextReuse); } _uri = value; } } public string SchemaFilePath { get; internal set; } public string InputLogContents { get; internal set; } public SarifLog InputLog { get; internal set; } public Run CurrentRun { get; internal set; } public int CurrentRunIndex { get; internal set; } public Result CurrentResult { get; internal set; } public int CurrentResultIndex { get; internal set; } public ReportingDescriptorKind CurrentReportingDescriptorKind { get; internal set; } public JToken InputLogToken { get; internal set; } public DefaultTraces Traces { get; set; } public void Dispose() { // Nothing to dispose. } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Framework.Remote.Mobile { [DataContract(Name = "CxExportToCsvInfo", Namespace = "http://schemas.datacontract.org/2004/07/FulcrumWeb")] public class CxExportToCsvInfo { [DataMember] public Guid StreamId; //---------------------------------------------------------------------------- [DataMember] public CxExceptionDetails Error { get; set; } } }
using BenchmarkDotNet.Engines; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Jobs; using Win32FileIOBenchmarkDotNet.Benchmarks.Read; using Win32FileIOBenchmarkDotNet.Configs.Common; namespace Win32FileIOBenchmarkDotNet.Configs.Read { /// <summary> /// Implement class with benchmark settings to test <see cref="SingleReadFileClearIoCacheBenchmark"/> /// </summary> public class SingleFileReadClearIoCacheConfig : CommonConfig { #region Constructor public SingleFileReadClearIoCacheConfig() => Add( Job.Default .With(RunStrategy.ColdStart) .With(Jit.RyuJit) .With(Platform.X64) .With(ClrRuntime.Net461) .WithLaunchCount(10) .WithIterationCount(1) .WithWarmupCount(0) ); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class PlayerMoveTest : MonoBehaviour { public float speed = 0.4f; Vector2 dest = Vector2.zero; public static Vector2 currentDirection = Vector2.right; Vector2 nextDirectionWhenAvailable = Vector2.zero; public Sprite playerUp, playerDown, playerLeft, playerRight; public GameObject bulletObject; private SpriteRenderer playerSprite; private Sprite nextSprite; private Vector2 touchStartPosition; private bool uiTouchDetected = false; private void OnCollisionEnter2D(Collision2D collision) { Debug.Log(collision.collider.tag); Debug.Log(dest); Debug.Log(currentDirection); } void Start() { dest = transform.position; playerSprite = GetComponent<SpriteRenderer>(); playerSprite.sprite = playerRight; nextSprite = playerRight; } bool valid(Vector2 dir) { Vector2 pos = transform.position; Debug.Log(pos); Vector2 leftCheck = new Vector2(-1.5f, pos.y); Vector2 rightCheck = new Vector2(1.5f, pos.y); Vector2 downCheck = new Vector2(pos.x, -1.5f); Vector2 upCheck = new Vector2(pos.x, 1.5f); Vector2 finalVector1 = new Vector2(0, 0); Vector2 finalVector2 = new Vector2(0, 0); Vector2 finalVector3 = new Vector2(0, 0); if (dir == Vector2.left) { finalVector1 = new Vector2(-1.5f, 0.0f); finalVector2 = new Vector2(-1.5f, 0.9f); finalVector3 = new Vector2(-1.5f, -0.9f); } else if(dir == Vector2.right) { finalVector1 = new Vector2(1.5f, 0.0f); finalVector2 = new Vector2(1.5f, 0.9f); finalVector3 = new Vector2(1.5f, -0.9f); } else if(dir == Vector2.up) { finalVector1 = new Vector2(0.0f, 1.5f); finalVector2 = new Vector2(0.9f, 1.5f); finalVector3 = new Vector2(-0.9f, 1.5f); } else if(dir == Vector2.down) { finalVector1 = new Vector2(0.0f, -1.5f); finalVector2 = new Vector2(0.9f, -1.5f); finalVector3 = new Vector2(-0.9f, -1.5f); } RaycastHit2D hitLeft = Physics2D.Linecast((finalVector1 + pos), pos); RaycastHit2D hitRight = Physics2D.Linecast((finalVector2 + pos), pos); RaycastHit2D hitDown = Physics2D.Linecast((finalVector3 + pos), pos); Debug.DrawLine((finalVector1 + pos), pos, Color.red); Debug.DrawLine((finalVector2 + pos), pos, Color.red); Debug.DrawLine((finalVector3 + pos), pos, Color.red); if (hitDown.collider.tag == "Environment" || hitRight.collider.tag == "Environment" || hitLeft.collider.tag == "Environment") { return false; } else { return true; } } void Update() { checkForUserInput(); checkForShooting(); } void FixedUpdate() { if ((Vector2)transform.position == dest) { if (valid(nextDirectionWhenAvailable)) { dest = (Vector2)transform.position + nextDirectionWhenAvailable; currentDirection = nextDirectionWhenAvailable; playerSprite.sprite = nextSprite; } else if (valid(currentDirection)) { dest = (Vector2)transform.position + currentDirection; } } MovePlayer(dest); } void MovePlayer(Vector2 destination) { Vector2 p = Vector2.MoveTowards(transform.position, dest, speed); GetComponent<Rigidbody2D>().MovePosition(p); } void checkForUserInput() { #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_EDITOR if (Input.GetKeyDown(KeyCode.W)) { nextDirectionWhenAvailable = Vector2.up; nextSprite = playerUp; } if (Input.GetKeyDown(KeyCode.D)) { nextDirectionWhenAvailable = Vector2.right; nextSprite = playerRight; } if (Input.GetKeyDown(KeyCode.S)) { nextDirectionWhenAvailable = -Vector2.up; nextSprite = playerDown; } if (Input.GetKeyDown(KeyCode.A)) { nextDirectionWhenAvailable = -Vector2.right; nextSprite = playerLeft; } #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE if (Input.touchCount > 0) { Touch myTouch = Input.touches[0]; if (myTouch.phase == TouchPhase.Began) { touchStartPosition = myTouch.position; if (EventSystem.current.IsPointerOverGameObject(myTouch.fingerId)) { uiTouchDetected = true; } else { uiTouchDetected = false; } } else if (myTouch.phase == TouchPhase.Ended && touchStartPosition.x >= 0) { if (uiTouchDetected) { GameController.playerScore += 333; } else if (!uiTouchDetected) { Vector2 touchEnd = myTouch.position; float x = touchEnd.x - touchStartPosition.x; float y = touchEnd.y - touchStartPosition.y; touchStartPosition.x = -1; if (Mathf.Abs(x) > Mathf.Abs(y)) { if (x > 0) { nextDirectionWhenAvailable = Vector2.right; nextSprite = playerRight; } else { nextDirectionWhenAvailable = -Vector2.right; nextSprite = playerLeft; } } else { if (y > 0) { nextDirectionWhenAvailable = Vector2.up; nextSprite = playerUp; } else { nextDirectionWhenAvailable = -Vector2.up; nextSprite = playerDown; } } GameController.playerScore += 1000; } } } #endif } void checkForShooting() { if (Input.GetKeyDown(KeyCode.Space)) { Vector3 fireLocation = (Vector3)transform.position + (Vector3)currentDirection * 2; GameObject firedBullet = Instantiate(bulletObject, fireLocation, Quaternion.identity); } } public void shootButtonPressed() { Debug.Log("BUTTON PRESSED"); Vector3 fireLocation = (Vector3)transform.position + (Vector3)currentDirection * 2; GameObject firedBullet = Instantiate(bulletObject, fireLocation, Quaternion.identity); } }
 namespace otus_architecture_lab_8 { public abstract class FileParcerBase : HandlerBase { #region Methods protected abstract bool CanParce(string path); protected abstract void Parce(string path); public override void Handle(object request) { if (request is string path && CanParce(path)) { Parce(path); } else if (parent != null) { parent.Handle(request); } else { SimpleServiceLocator.Instance.GetService<ILogger>().Log($"Can't parce file: {request.ToString()}"); } } #endregion } }
using UnityEngine; using System.Collections; public class PlayShip : PlayObject { //ship's parts public GameObject body, wing, booster; //max rotations on x, y, and z axes, respectively public int maxPitch = 15; public int maxRoll = 15; public int maxYaw = 30; void Start(){ generateShip(); } // Update is called once per frame new void Update () { base.Update (); //change the ship's velocity based on input if( rigidbody2D.velocity != Vector2.zero || Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0){ rigidbody2D.velocity = new Vector2 (Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed); } //rotate the ship based on its velocity gameObject.transform.rotation = Quaternion.Euler(maxPitch * rigidbody2D.velocity.y / speed, -maxRoll * rigidbody2D.velocity.x / speed, -maxYaw * rigidbody2D.velocity.x / speed); } //Craft the ship out of the stored parts void generateShip(){ //delete all current ship parts foreach(Transform child in gameObject.transform){ GameObject.Destroy(child.gameObject); } //add parts addPart(body); addPart(wing); addPart(booster); } //Add a ship part to the sceneand set it as a child, then craft the collider private void addPart(GameObject part){ GameObject temp; //add part to scene temp = (GameObject)Instantiate(part, this.transform.position, this.transform.rotation); temp.transform.localScale.Set(this.transform.localScale.x, this.transform.localScale.y, this.transform.localScale.z); //set this object as parent temp.transform.SetParent(this.gameObject.transform); //move the part's collider PolygonCollider2D coll = gameObject.GetComponent<PolygonCollider2D>(); PolygonCollider2D old = temp.GetComponent<PolygonCollider2D>(); //TODO: re-create the collider to fit the new shape /* //edit the correct path if(part == body){ coll.SetPath(0, old.GetPath(0)); //copy body collider } else if(part == wing){ coll.SetPath(1, old.GetPath(0)); //copy wing collider } else if(part == booster){ coll.SetPath(2, old.GetPath(0)); //copy booster collider } Destroy(old); //old one not needed; waste of CPU */ } //swap a part private void changePart(int type, GameObject part){ switch(type){ case 0: //change body body = part; break; case 1: //change wings wing = part; break; case 2: //change boosters booster = part; break; default: Debug.LogError("Invalid type when changing ship parts!"); return; } generateShip(); } }
using System; using System.Windows; using System.Windows.Controls; using System.ComponentModel.Composition; // Export[]; reqs ref to System.ComponentModel.Composition using IWx_Client; using Humidity_ViewModel; namespace Wind_Client { /// <summary> /// Interaction logic for HumidityClient.xaml /// </summary> public partial class HumidityClient : UserControl, IWxClient { string[] m_cmdArgs = null; HumidityViewModel vm = null; /// <summary> /// Will generally be called by .net MEF runtime. /// Called when the MEF GetExportedValues() method is run. /// </summary> public HumidityClient() { InitializeComponent(); vm = new HumidityViewModel(); this.DataContext = vm; } private void HumidityClient_Unloaded(object sender, RoutedEventArgs e) { } private void Stopping() { } /***************** MEF **************************/ /// <summary> /// allows MEF to make this WPF control/MVVM view available to other apps by discovery at runtime /// </summary> [Export(typeof(IWxClient))] public IWxClient Window { get { return this; } } public void Close() { // could call Dispose() if IDispose implemented cmdStop.Command.Execute(null); } public string ServiceName { get { return " Humidity Control"; } } /***************** MEF **************************/ } }
using UnityEngine; namespace syscrawl.Game.Models { public class LevelGeneratorConfiguration { public int MinimumNodes = 20; public int MaximumNodes = 50; public Vector3 NodeMinimumScale = new Vector3(1, 1, 1); public Vector3 NodeMaximumScale = new Vector3(10, 30, 30); public float MinimumNodeDistance = 8; public float MaximumNodeDistance = 20; public int NodeExtraEdges = 10; public int NodeExtraEdgesAttempts = 100; public float NodeAngle = 90f; public float NodeDistance = 25f; public int GetRandomNumberOfNodes() { return Random.Range( MinimumNodes, MaximumNodes + 1); } } }
//Class Name: FormInput.cs //Author:Kristina VanderBoog //Purpose: This is the state Context part of the State pattern, it interacts with the client and the state //Date : August 14, 2020 namespace Project_3_Starter { //this is the state context! public class FormInput { //a form object will be created and passed to the state context private Form form; private State state; public FormInput(Form f) { this.form = f; } //a form object is created and populated then sent to FormInput //state context class must maintain a reference to state /*This method will change the state depending on the current state that is passed to it */ public void ChangeState(State state) { this.state = state; state.Run(); } //this run method will begin the program public void Run() { this.state = new InputState(this); state.Run(); } /*Get form is used to get the currently populated form into the input state */ public Form getForm() { return form; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Programming { public class VowelCount_Monktalkwalks { public static void Main() { //This Program will counts the Number of Vowels in a given string Console.WriteLine("Enter string to This Program will counts the Number of Vowels in a given string"); string Input =Convert.ToString(Console.ReadLine()).ToLower(); int Count=0; for (int i = 0; i < Input.Count(); i++) { if(Input[i]=='a' || Input[i] == 'e' || Input[i] == 'o' || Input[i] =='u' || Input[i] == 'i') { Count++; } } Console.WriteLine("Number of vowels are "+Count); // Toggle String Case Console.WriteLine("Enter string to Toggle string Case"); string result = string.Empty; string input = Convert.ToString(Console.ReadLine()); char[] inputArray = input.ToCharArray(); foreach (char c in inputArray) { if (char.IsLower(c)) result += Char.ToUpper(c); else result += Char.ToLower(c); } Console.WriteLine("After converting upper to lower and lower to upper "+ result); //Check given Number is Prime or not bool isprime = false; Console.WriteLine("Enter integer to Check given Number is Prime or not "); int number = Convert.ToInt32(Console.ReadLine()); if (number == 1) Console.WriteLine("Given Number is not a prime "); if (number == 2) Console.WriteLine("Given Number is a prime "); for (int i = 2; i <= number - 1; i++) { if (number % i == 0) { isprime = false; } } if (!isprime) Console.WriteLine("Given Number is not a prime "); else Console.WriteLine("Given Number is a prime "); //Find Product of given number Console.WriteLine("Enter integer to Find Product of given number"); number = Convert.ToInt32(Console.ReadLine()); int results =1; for (int i = 1; i <= number; i++) { results = results * i; } Console.WriteLine("Results is "+results); Console.ReadKey(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using YoctoScheduler.Core.Database; using System.Data.SqlClient; namespace YoctoScheduler.UnitTest.Daatabase { [TestClass] public class ExecutionQueueItem_Test { [TestMethod] public void ExecutionQueueItem_InsertNotNull() { ExecutionQueueItem eqi = new ExecutionQueueItem() { Inserted = DateTime.Now, Priority = Core.Priority.Lowest, ScheduleID = Guid.NewGuid(), TaskID = 1 }; using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING)) { conn.Open(); using (var trans = conn.BeginTransaction()) { ExecutionQueueItem.Insert(conn, trans, eqi); trans.Commit(); } } } [TestMethod] public void ExecutionQueueItem_InsertNull() { ExecutionQueueItem eqi = new ExecutionQueueItem() { Inserted = DateTime.Now, Priority = Core.Priority.Lowest, TaskID = 1 }; using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING)) { conn.Open(); using (var trans = conn.BeginTransaction()) { ExecutionQueueItem.Insert(conn, trans, eqi); trans.Commit(); } } } } }
using System; using System.Collections.Generic; using UnityEngine; namespace RO { public class AreaTriggerManager<T, AT> : SingleTonGO<T> where T : SingleTonGO<T>, new() where AT : AreaTrigger { protected AT currentTrigger; protected List<AT> triggers = new List<AT>(); public bool Add(AT at) { if (!this.DoAdd(at)) { return false; } this.triggers.Add(at); return true; } public void Remove(AT at) { this.DoRemove(at); if (this.triggers.Remove(at)) { } } protected virtual bool DoAdd(AT at) { return !this.triggers.Contains(at); } protected virtual void DoRemove(AT at) { } protected virtual void OnTriggerChanged(AT oldTrigger, AT newTrigger) { } protected virtual AT DoCheck(Transform t) { for (int i = 0; i < this.triggers.get_Count(); i++) { AT result = this.triggers.get_Item(i); if (result.Check(t)) { return result; } } return (AT)((object)null); } protected void SetTrigger(AT newTrigger, Transform t) { AT aT = this.currentTrigger; if (aT == newTrigger) { return; } this.currentTrigger = newTrigger; if (null != aT) { aT.ddPlayerIn = false; aT.OnRoleExit(t); } if (null != newTrigger) { newTrigger.ddPlayerIn = true; newTrigger.OnRoleEnter(t); } this.OnTriggerChanged(aT, newTrigger); } private void Check() { LuaLuancher me = SingleTonGO<LuaLuancher>.Me; if (null == me) { this.SetTrigger((AT)((object)null), null); return; } if (me.ignoreAreaTrigger) { this.SetTrigger((AT)((object)null), null); return; } RoleComplete myself = me.myself; if (null == myself) { this.SetTrigger((AT)((object)null), null); return; } this.SetTrigger(this.DoCheck(myself.get_transform()), myself.get_transform()); } protected virtual void LateUpdate() { this.Check(); } } }
using System; using System.Collections.Generic; namespace SceneGraphSync { public class Node : Syncables.Syncable, IEquatable<Node> { public string Name = string.Empty; public List<Node> Children { get; set; } public Node Parent { get; set; } public List<Component> Components { get; set; } public Node() { } public Node( string name ) { Name = name; } public bool Equals( Node other ) { return Object.ReferenceEquals(this, other); } public override string ToString() { return $"{Name}"; } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace Grisaia.Categories { /// <summary> /// Sprite part groups and other information for a specific Grisaia character. /// </summary> public sealed class CharacterInfo { #region Fields /// <summary> /// Gets the character database containing this character info. /// </summary> [JsonIgnore] public CharacterDatabase Database { get; internal set; } /// <summary> /// The parent to this character info. Used to avoid duplicate information. /// </summary> [JsonIgnore] private CharacterInfo parent; /// <summary> /// The character info related to this character in same way. Used for $RELATION$ name token. /// </summary> [JsonIgnore] public CharacterInfo Relation { get; internal set; } /// <summary> /// Gets the Id associated with this character. /// </summary> [JsonProperty("id")] public string Id { get; private set; } /// <summary> /// Gets the Id of the parent to this character info. Used to avoid duplicate information.<para/> /// Only the following fields are duplicated: <see cref="FirstName"/>, <see cref="LastName"/>, /// <see cref="Nickname"/>, <see cref="Title"/>.<para/> /// These fields are also only copied if the underlying field is null. /// </summary> [JsonProperty("parent_id")] public string ParentId { get; private set; } /// <summary> /// Gets the Id of the character info related to this character in same way. Used for $RELATION$ name token. /// </summary> [JsonProperty("relation_id")] public string RelationId { get; private set; } /// <summary> /// Gets the character's first name. This can be null. /// </summary> [JsonProperty("first_name")] public string FirstName { get; private set; } /// <summary> /// Gets the character's last name. This can be null. /// </summary> [JsonProperty("last_name")] public string LastName { get; private set; } /// <summary> /// Gets the character's nickname. This can be null. /// </summary> [JsonProperty("nickname")] public string Nickname { get; private set; } /// <summary> /// Gets the character's name as a title. This can be null. /// </summary> [JsonProperty("title")] public string Title { get; private set; } /// <summary> /// Gets the character's label appended to their name. This can be null. /// </summary> [JsonProperty("label")] public string Label { get; private set; } // Extractor: /// <summary> /// Gets the sorting subgroup. Also functions as the label when none is present. /// </summary> [JsonProperty("subgroup")] public string SubGroup { get; private set; } // Sprite Viewer: /// <summary> /// Gets the default part groups associated with this character. /// </summary> [JsonProperty("parts")] public IReadOnlyList<CharacterSpritePartGroupInfo> Parts { get; private set; } /// <summary> /// Gets the list of game-specific part groups associated with this character. /// </summary> [JsonProperty("game_parts")] public IReadOnlyList<CharacterGameSpecificPartsInfo> GameParts { get; private set; } #endregion #region Properties /*/// <summary> /// Gets the single-Id representation of the character. /// </summary> [JsonProperty("id")] private string Id { get => Ids?.FirstOrDefault(); set => Ids = new string[] { value }; }*/ /// <summary> /// Formats the name of the this character info using the naming scheme settings. /// </summary> /// <returns>The character's name with the naming scheme applied.</returns> /// /// <exception cref="InvalidOperationException"> /// A name token is invalid or a token character does not have a name for the specified token. /// </exception> [JsonIgnore] public string FormattedName => Database.NamingScheme.GetName(this); /// <summary> /// Gets the parent to this character info. Used to avoid duplicate information. /// </summary> [JsonIgnore] public CharacterInfo Parent { get => parent; internal set { parent = value ?? throw new ArgumentNullException(nameof(Parent)); if (FirstName == null) FirstName = value.FirstName; if (LastName == null) LastName = value.LastName; if (Nickname == null) Nickname = value.Nickname; if (Title == null) Title = value.Title; } } #endregion /*#region Accessors /// <summary> /// Returns true if this character info contains has the specified Id. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the character has the specified Id.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> is null. /// </exception> public bool ContainsId(string id) { return Id == id; //if (id == null) // throw new ArgumentNullException(nameof(id)); //return Array.IndexOf(Ids, id) != -1; } #endregion*/ #region ToString Override /// <summary> /// Gets the string representation of the character info. /// </summary> /// <returns>The string representation of the character info.</returns> public override string ToString() => Id; #endregion #region MakeDefault /// <summary> /// Makes the default character info for an undefined character. /// </summary> /// <param name="id">The Id of the character.</param> /// <param name="defaultParts">The default parts to use for the character info.</param> /// <returns>The newly constructed character info.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> or <paramref name="defaultParts"/> is null. /// </exception> public static CharacterInfo MakeDefault(string id, CharacterSpritePartGroupInfo[] defaultParts) { if (id == null) throw new ArgumentNullException(nameof(id)); if (defaultParts == null) throw new ArgumentNullException(nameof(defaultParts)); return new CharacterInfo { Id = id, Parts = defaultParts, }; } #endregion } /// <summary> /// A <see cref="CharacterSpritePartGroupInfo[]"/> for a specific game and character. /// </summary> public sealed class CharacterGameSpecificPartsInfo { #region Fields /// <summary> /// Gets the game Ids associated this part categorization. /// </summary> [JsonProperty("game_ids")] public IReadOnlyList<string> GameIds { get; private set; } /// <summary> /// Gets the list of part groups associated with this game and character. /// </summary> [JsonProperty("parts")] public IReadOnlyList<CharacterSpritePartGroupInfo> Parts { get; private set; } #endregion #region Properties /// <summary> /// Gets the single game Id. /// </summary> [JsonProperty("game_id")] private string GameId { get => GameIds?.FirstOrDefault(); set => GameIds = Array.AsReadOnly(new string[] { value }); } #endregion } /// <summary> /// A single group of sprites that form a single part of the entire character sprite. /// </summary> public sealed class CharacterSpritePartGroupInfo { #region Fields /// <summary> /// Gets the user-friendly name of the sprite part group. /// </summary> [JsonProperty("Name")] public string Name { get; private set; } /// <summary> /// Gets the part type Ids associated with this part group. /// </summary> [JsonProperty("ids")] public IReadOnlyList<int> TypeIds { get; private set; } /// <summary> /// Gets if this group is enabled by default when activated. /// </summary> [JsonProperty("enabled")] public bool Enabled { get; private set; } = true; #endregion #region Properties /// <summary> /// Gets the single part type Id. /// </summary> [JsonProperty("id")] private int TypeId { get => TypeIds.First(); set => TypeIds = Array.AsReadOnly(new int[] { value }); } #endregion } }
namespace LogoHandler { public interface ILogoDesigner { bool[,] CreateLogo(); } }
using Payroll.Common; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Payroll.Models { public class Employee : Addressable { [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType =typeof(Resource), Name ="Company")] public Guid CompanyId { get; set; } [ForeignKey("CompanyId")] public virtual Company Company { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Department")] public Guid DepartmentId { get; set; } [ForeignKey("DepartmentId")] public virtual Department Department { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "JobRole")] public Guid JobRoleId { get; set; } [ForeignKey("JobRoleId")] public virtual JobRole JobRole { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Workplace")] public Guid WorkplaceId { get; set; } [ForeignKey("WorkplaceId")] public virtual Workplace Workplace { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Function")] public Guid FunctionId { get; set; } [ForeignKey("FunctionId")] public virtual Function Function { get; set; } [Display(ResourceType = typeof(Resource), Name = "Manager")] public Guid? ManagerId { get; set; } [ForeignKey("ManagerId")] public virtual Employee Manager { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Occupation")] public Guid OccupationId { get; set; } [ForeignKey("OccupationId")] public virtual Occupation Occupation { get; set; } public virtual IEnumerable<EmployeeHistory> Occurrences { get; set; } public virtual IEnumerable<Employee> Subordinates { get; set; } public virtual IEnumerable<ProjectEmployee> Projects { get; set; } public virtual IEnumerable<VacationEmployee> Vacations { get; set; } public virtual IEnumerable<WorkHoursEmployee> WorkHours { get; set; } public virtual IEnumerable<Certification> Certifications {get; set;} [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "IDName")] public string IDName { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Nationality")] public string Nationality { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "EmployeeNumber")] public string EmployeeNumber { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "DateBirth")] public DateTime? DateBirth { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "AdmissionalDate")] public DateTime? AdmissionalDate { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "PersonalDocument")] public string PersonalDocument { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "PhoneNumber")] public string PhoneNumber { get; set; } [Display(ResourceType = typeof(Resource), Name = "Salary")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public double Salary { get; set; } [Display(ResourceType = typeof(Resource), Name = "Gender")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public Gender Gender { get; set; } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Text; using System.Collections.Generic; using AgentStoryComponents; namespace AgentStoryHTTP.screens { public partial class ListMembers : SessionAwareWebForm { protected void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e, this.divToolBarAttachPoint, this.divFooter); if (base.currentUser.isObserver() && base.currentUser.ID == config.publicUserID) { Response.Redirect("./Platform2.aspx?msg=" + Server.UrlEncode("Please login to perform this operation.")); Response.End(); } Users us = new Users(config.conn); //filter only my sponsored contacts. //User u = new User(); //u.SponsorID List<User> users = us.UserList; StringBuilder html = new StringBuilder(); html.Append("<script language='JavaScript'>"); html.Append(@" function changeUserState(widget) { var userID = widget.id.split('_')[1]; var stateID = widget.options[ widget.selectedIndex ].id; if(stateID == -1) return; var m = new macro(); m.name = 'ChangeUserState'; addParam(m,'UserID',userID); addParam(m,'State',stateID); processRequest( m ); } "); html.Append("</script>"); html.Append("<table border='1'>"); html.Append("<tr class='clsGridHeadRow'>"); html.Append("<td>"); html.Append("Username"); html.Append("</td>"); html.Append("<td>"); html.Append("Email"); html.Append("</td>"); html.Append("<td>"); html.Append("Roles"); html.Append("</td>"); html.Append("<td>"); html.Append("State"); html.Append("</td>"); html.Append("<td>"); html.Append("Action"); html.Append("</td>"); html.Append("<td>"); html.Append("send message"); html.Append("</td>"); html.Append("<td>"); html.Append("Sponsor"); html.Append("</td>"); html.Append("</tr>"); foreach (User u in users) { if (u.ID == base.currentUser.ID) { //that's me, show! } else if (base.currentUser.isAdmin() || base.currentUser.isRoot()) { //no filtering } else { if (u.SponsorID != base.currentUser.ID) { if (u.ID == base.currentUser.SponsorID) { //show my sponsor! } else { continue; //skip this user. } } else { //let in } } if (u.ID == base.currentUser.SponsorID) html.Append("<tr class='clsSponsorRow'>"); else html.Append("<tr class='clsGridRow'>"); html.Append("<td>"); html.Append("<div title='Tags: "); html.Append(u.Tags); html.Append("'>"); if (base.currentUser.isRoot()) { html.Append(" [ " + u.ID + " ] "); } if (u.ID != base.currentUser.SponsorID) { html.Append("<a href='./EditUserInfo.aspx?UserGUID="); html.Append(u.UserGUID); html.Append("' >"); } html.Append(u.UserName); html.Append(" ( "); html.Append(u.LastName); html.Append(", "); html.Append(u.FirstName); html.Append(" ) "); if (u.ID != base.currentUser.SponsorID) { html.Append("</a>"); } html.Append("</div></td>"); html.Append("<td>"); html.Append(u.Email); html.Append("</td>"); html.Append("<td>"); html.Append(u.Roles); html.Append("</td>"); html.Append("<td>"); html.Append(u.StateHR); html.Append("</td>"); if (u.ID == base.currentUser.SponsorID || u.ID == base.currentUser.ID) { //hide state change action on sponsor and themself html.Append("<td>"); html.Append(" "); html.Append("</td>"); } else { #region states html.Append("<td>"); html.Append("<select id='sel_" + u.ID + "' onchange='changeUserState(this);'>"); html.Append("<option id='-1'"); html.Append(">"); html.Append(" -- change state -- "); html.Append("</option>"); html.Append("<option id='" + ((int)UserStates.signed_in) + "'"); if (u.State == ((int)UserStates.signed_in)) { html.Append(" SELECTED "); } html.Append(">"); html.Append("signed-in"); html.Append("</option>"); html.Append("<option id='" + ((int)UserStates.added) + "'"); if (u.State == ((int)UserStates.added)) { html.Append(" SELECTED "); } html.Append(">"); html.Append("added"); html.Append("</option>"); html.Append("<option id='" + ((int)UserStates.accepted) + "'"); if (u.State == ((int)UserStates.accepted)) { html.Append(" SELECTED "); } html.Append(">"); html.Append("accepted"); html.Append("</option>"); html.Append("<option id='" + ((int)UserStates.suspended) + "'"); if (u.State == ((int)UserStates.suspended)) { html.Append(" SELECTED "); } html.Append(">"); html.Append("suspended"); html.Append("</option>"); // only users can self terminate //html.Append("<option id='" + ((int)UserStates.terminated) + "'"); //if (u.State == ((int)UserStates.terminated)) //{ // html.Append(" SELECTED "); //} //html.Append(">"); //html.Append("terminated"); //html.Append("</option>"); html.Append("<option id='" + ((int)UserStates.pre_approved) + "'"); if (u.State == ((int)UserStates.pre_approved)) { html.Append(" SELECTED "); } html.Append(">"); html.Append("preapproved"); html.Append("</option>"); html.Append("</select>"); html.Append("</td>"); #endregion } html.Append("<td>"); html.Append("<a href='SendEmail.aspx?idTo=" + u.ID + "'>email</a>"); html.Append("</td>"); html.Append("<td>"); html.Append("<div title='Sponsored by: "); html.Append(u.Sponsor.FirstName); html.Append(" "); html.Append(u.Sponsor.LastName); html.Append("'>"); html.Append(u.SponsorFullName); html.Append("</div></td>"); html.Append("</tr>"); } html.Append("</table>"); html.Append("<table><tr><td class='clsSponsorRow'>&nbsp;&nbsp;</td><td>Your Sponsor</td></tr></table>"); this.divBodyAttachPoint.InnerHtml = html.ToString(); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; namespace Dawnfall.Helper { public static class Helper { public static void Swap<T>(IList<T> array, int i1, int i2) { T temp1 = array[i1]; array[i1] = array[i2]; array[i2] = temp1; } public static T[] ReverseArray<T>(T[] arr) { T[] reversedArr = new T[arr.Length]; for (int i = 0; i < arr.Length; i++) reversedArr[i] = arr[arr.Length - i - 1]; return reversedArr; } public static T[] SubArray<T>(T[] arr, int startIndex, int length) { T[] subArr = new T[length]; for (int i = 0; i < length; i++) subArr[i] = arr[i + startIndex]; return subArr; } public static bool IsInArray<T>(IEnumerable<T> arrStr, T item) { if (arrStr == null) return false; foreach (T str in arrStr) if (str.Equals(item)) return true; return false; } public static bool AddIfType<T>(object obj, List<T> list) where T : class { T castObj = obj as T; if (castObj != null) { list.Add(castObj); return true; } return false; } //not necceserily correct public static byte[] ObjectToByteArray(object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } public static object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); return binForm.Deserialize(memStream); } } } //public static bool AddIfType<T>(AActorData actorData, List<T> list) where T : AActorData //{ // T castActor = actorData as T; // if (castActor != null) // { // list.Add(castActor); // return true; // } // return false; //}
using bot_backEnd.BL.Interfaces; using bot_backEnd.DAL.Interfaces; using bot_backEnd.Data; using bot_backEnd.Models.DbModels; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.DAL { public class PostLikeDAL : IPostLikeDAL { private readonly AppDbContext _context; private readonly INotificationBL _iNotificationBL; public PostLikeDAL(AppDbContext context, INotificationBL iNotificationBL) { _context = context; _iNotificationBL = iNotificationBL; } public async Task<ActionResult<int>> AddPostLike(PostLike like) { var post = await _context.Post.FindAsync(like.PostID); if (post == null) return -1; _context.PostLike.Add(like); await _context.SaveChangesAsync(); return _context.PostLike.Where(e => e.PostID == like.PostID).Count(); } public async Task<ActionResult<int>> DeletePostLike(int postID, int userID) { var entityLike = await _context.PostLike.FindAsync(postID, userID); if (entityLike == null) return -1; var post = await _context.Post.FindAsync(postID); if (post == null) return -1; _context.PostLike.Remove(entityLike); await _context.SaveChangesAsync(); _iNotificationBL.DeletePostNotification(postID, userID, (int)Enums.NotificationType.POST_LIKE); return _context.PostLike.Where(e => e.PostID == postID).Count(); } public async Task<ActionResult<List<PostLike>>> GetLikesByPostID(int postID) { return await _context.PostLike.Include(e => e.User).Where(e => e.PostID == postID).ToListAsync(); } } }
#region 版本说明 /***************************************************************************** * * 项 目 : * 作 者 : 冯兴彬 * 创建时间 : 2010-5-27 10:23:16 * * Copyright (C) 2008 - 鹏业软件公司 * *****************************************************************************/ #endregion using System; using System.Collections; using System.Text; using PengeSoft.Data; using PengeSoft.WorkZoneData; namespace PengeSoft.CMS.BaseDatum { /// <summary> /// PersonalTemplet 的摘要说明。 /// </summary> public class PersonalTemplet : DataPacket { #region 私有字段 private string _PersonalId; // 人员模板ID private string _PersonalName; // 人员名称 private int _PersonType; // 人员类型 private string _ID; // 主键 private string _RefID; // 引用标识 #endregion #region 属性定义 /// <summary> /// 人员模板ID /// </summary> public string PersonalId { get { return _PersonalId; } set { _PersonalId = value; } } /// <summary> /// 人员名称 /// </summary> public string PersonalName { get { return _PersonalName; } set { _PersonalName = value; } } /// <summary> /// 人员类型 /// </summary> public int PersonType { get { return _PersonType; } set { _PersonType = value; } } /// <summary> /// 主键 /// </summary> public string ID { get { return _ID; } set { _ID = value; } } /// <summary> /// 引用标识 /// </summary> public string RefID { get { return _RefID; } set { _RefID = value; } } #endregion #region 重载公共函数 /// <summary> /// 清除所有数据。 /// </summary> public override void Clear() { base.Clear(); _PersonalId = null; _PersonalName = null; _PersonType = 0; _ID = null; _RefID = null; } /// <summary> /// 用指定节点序列化整个数据对象。 /// </summary> /// <param name="node">用于序列化的 XmlNode 节点。</param> public override void XMLEncode(System.Xml.XmlNode node) { base.XMLEncode(node); WriteXMLValue(node, "PersonalId", _PersonalId); WriteXMLValue(node, "PersonalName", _PersonalName); WriteXMLValue(node, "PersonType", _PersonType); WriteXMLValue(node, "ID", _ID); WriteXMLValue(node, "RefID", _RefID); } /// <summary> /// 用指定节点反序列化整个数据对象。 /// </summary> /// <param name="node">用于反序列化的 XmlNode 节点。</param> public override void XMLDecode(System.Xml.XmlNode node) { base.XMLDecode(node); ReadXMLValue(node, "PersonalId", ref _PersonalId); ReadXMLValue(node, "PersonalName", ref _PersonalName); ReadXMLValue(node, "PersonType", ref _PersonType); ReadXMLValue(node, "ID", ref _ID); ReadXMLValue(node, "RefID", ref _RefID); } /// <summary> /// 复制数据对象 /// </summary> /// <param name="sou">源对象,需从DataPacket继承</param> public override void AssignFrom(DataPacket sou) { base.AssignFrom(sou); PersonalTemplet s = sou as PersonalTemplet; if (s != null) { _PersonalId = s._PersonalId; _PersonalName = s._PersonalName; _PersonType = s._PersonType; _ID = s._ID; _RefID = s._RefID; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.IO; using System.Xml; namespace JoveZhao.Framework.SMS { public class SMSDefaultService : ISMSService { public Tuple<int, bool> SMS(string to, string message) { if (string.IsNullOrEmpty(message)) return Tuple.Create<int, bool>(0, false); //得到发送条数 int sendCount = 0; bool sendState = false; #region old //string url = "http://122.4.79.43:2852/sms.aspx"; //string data = "action=send&userid=1190&account=mypb&password=mypb2014&mobile=" + to + "&content=" + message + "&sendTime=&checkcontent=1"; //string rs = GetBackData(url, data, "POST"); //XmlDocument xd = new XmlDocument(); //xd.LoadXml(rs); //string state = xd.SelectSingleNode("returnsms/returnstatus/text()").Value; //string count = xd.SelectSingleNode("returnsms/successCounts/text()").Value; //string info = xd.SelectSingleNode("returnsms/message/text()").Value; #endregion int state = SendSms(to, message); if (state > 0) { sendState = true; sendCount = Convert.ToInt32(Math.Ceiling((double)message.Length / 64)); } else { //未完成 Logger.WriteLog(LogType.INFO, "[" + DateTime.Now.ToString() + "]发送失败[" + to + "]"); } return Tuple.Create<int, bool>(sendCount, sendState); } public string GetBackData(string m_baseurl, string Data, string m_doMetthod) { string rs = string.Empty; try { byte[] dt = Encoding.UTF8.GetBytes(Data); if (m_doMetthod == "GET") { if (!string.IsNullOrEmpty(Data)) m_baseurl = m_baseurl + "?" + Data; } Uri uRI = new Uri(m_baseurl); HttpWebRequest req = WebRequest.Create(uRI) as HttpWebRequest; req.Method = m_doMetthod; if (m_doMetthod != "GET") { req.KeepAlive = true; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = dt.Length; req.AllowAutoRedirect = true; Stream outStream = req.GetRequestStream(); outStream.Write(dt, 0, dt.Length); outStream.Close(); } HttpWebResponse res = req.GetResponse() as HttpWebResponse; Stream inStream = res.GetResponseStream(); StreamReader sr = new StreamReader(inStream, Encoding.UTF8); rs = sr.ReadToEnd(); } catch (Exception ex) { Logger.WriteLog(LogType.ERROR, ex.Message, ex); } return rs; } public int SendSms(string to, string message) { try { SMSService.Service1SoapClient sms = new SMSService.Service1SoapClient(); return sms.FastSendSMS(to, message); } catch (Exception e) { Logger.WriteLog(LogType.ERROR, "短信发送失败", e); throw new CustomException(500, "发送消息失败"); } } } }
using System.Collections.Generic; namespace Shared.Models { public class Cup { public ICollection<CupRound> Type { get; set; } } }
using ClosedXML.Excel; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Spreadsheet; namespace Kit.Services.Excel { public class ExcelService : IDisposable { public string FilePath { get; private set; } public ClosedXML.Excel.XLWorkbook Document { get; private set; } public ExcelService(string FilePath, ClosedXML.Excel.XLWorkbook Document) { this.FilePath = FilePath; this.Document = Document; } public static ExcelService GenerateExcel(String fileName) { // Creating the SpreadsheetDocument in the indicated FilePath string FilePath = Path.Combine(Kit.Tools.Instance.LibraryPath, fileName); ExcelService xls = new(FilePath, new XLWorkbook()); return xls; } public Cell ConstructCell(object value) { if (value is Formula formula) { Cell cell = new Cell(); CellFormula cellformula = new CellFormula(); cellformula.Text = formula.Text; CellValue cellValue = new CellValue(); cellValue.Text = "0"; cell.Append(cellformula); cell.Append(cellValue); return cell; } return ConstructCell(value.ToString(), GetType(value)); } public CellValues GetType(object value) { switch (value) { case int: case float: case decimal: case double: return CellValues.Number; case string: return CellValues.String; case TimeSpan: case DateTime: return CellValues.Date; case bool: return CellValues.Boolean; default: return CellValues.String; } } public Cell ConstructCell(string value, CellValues dataTypes) => new Cell() { CellValue = new CellValue(value), DataType = new EnumValue<CellValues>(dataTypes) }; public CalculationCell ConstructCell(string formula) => new CalculationCell() { InnerXml = formula }; public ExcelService AddWorkSheet(string Name = null, int SheetId = 0) { if (string.IsNullOrEmpty(Name)) { Name = $"Sheet{(Document.Worksheets?.Count ?? 0) + 1}"; } var worksheet = Document.Worksheets.Add(Name, SheetId); return this; } public ExcelService InsertDataIntoSheet(string sheetName, ExcelStructureDataTable data) { Document.Worksheets.Add(data.Table, sheetName); var table = data.Table; return this; } public void Dispose() { Document.SaveAs(FilePath); this.Document.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; namespace JoveZhao.Framework.EFRepository.ContextStorage { public class ThreadDbContextStorageContainer<T>:IDbContextStorageContainer<T> where T:DbContext,new() { private string _key = typeof(T).Name + "ef_dbcontext"; public T GetDbContext() { return CallContext.GetData(_key) as T; } public void Store(T dbContext) { CallContext.SetData(_key, dbContext); } //private static readonly Hashtable _dbContexts = new Hashtable(); //public T GetDbContext() // { // T dbContext = default(T); // if (_dbContexts.Contains(getThreadName())) // dbContext = _dbContexts[getThreadName()] as T; // return dbContext; // } // private string getThreadName() // { // if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) // Thread.CurrentThread.Name = Thread.CurrentThread.GetHashCode().ToString(); // return Thread.CurrentThread.Name; // } // public void Store(T dbContext) // { // if (_dbContexts.Contains(getThreadName())) // _dbContexts[getThreadName()] = dbContext; // else // _dbContexts.Add(getThreadName(), dbContext); // } public void Clear() { CallContext.FreeNamedDataSlot(_key); } } }
// Accord Machine Learning Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.MachineLearning { using System.Collections; using System.Collections.Generic; /// <summary> /// Common interface for clustering algorithms. /// </summary> /// /// <typeparam name="TData">The type of the data being clustered, such as <see cref="T:double[]"/>.</typeparam> /// /// <seealso cref="KMeans"/> /// <seealso cref="KModes{T}"/> /// <seealso cref="BinarySplit"/> /// <seealso cref="GaussianMixtureModel"/> /// public interface IClusteringAlgorithm<TData> { /// <summary> /// Divides the input data into a number of clusters. /// </summary> /// /// <param name="points">The data where to compute the algorithm.</param> /// /// <returns> /// The labellings for the input data. /// </returns> /// int[] Compute(TData[] points); /// <summary> /// Gets the collection of clusters currently modeled by the clustering algorithm. /// </summary> /// IClusterCollection<TData> Clusters { get; } } /// <summary> /// Common interface for clustering algorithms. /// </summary> /// /// <typeparam name="TData">The type of the data being clustered, such as <see cref="T:double[]"/>.</typeparam> /// <typeparam name="TWeights">The type of the weights associated with each point, such as <see cref="T:double[]"/> or <see cref="T:double[]"/>.</typeparam> /// /// <seealso cref="KMeans"/> /// <seealso cref="KModes{T}"/> /// <seealso cref="BinarySplit"/> /// <seealso cref="GaussianMixtureModel"/> /// public interface IClusteringAlgorithm<TData, TWeights> : IClusteringAlgorithm<TData> { /// <summary> /// Divides the input data into a number of clusters. /// </summary> /// /// <param name="points">The data where to compute the algorithm.</param> /// <param name="weights">The weight associated with each data point.</param> /// /// <returns> /// The labellings for the input data. /// </returns> /// int[] Compute(TData[] points, TWeights[] weights); } /// <summary> /// Common interface for cluster collections. /// </summary> /// /// <typeparam name="TData">The type of the data being clustered, such as <see cref="T:double[]"/>.</typeparam> /// public interface IClusterCollection<in TData> : IEnumerable { /// <summary> /// Gets the number of clusters in the collection. /// </summary> /// int Count { get; } /// <summary> /// Returns the closest cluster to an input point. /// </summary> /// /// <param name="point">The input vector.</param> /// <returns> /// The index of the nearest cluster /// to the given data point. </returns> /// int Nearest(TData point); } /// <summary> /// Common interface for cluster collections. /// </summary> /// /// <typeparam name="TData">The type of the data being clustered, such as <see cref="T:double[]"/>.</typeparam> /// <typeparam name="TCluster">The type of the clusters considered by a clustering algorithm.</typeparam> /// public interface IClusterCollection<TData, #if !NET35 out #endif TCluster> : IEnumerable<TCluster>, IClusterCollection<TData> { /// <summary> /// Gets the cluster at the given index. /// </summary> /// /// <param name="index">The index of the cluster. This should also be the class label of the cluster.</param> /// /// <returns>An object holding information about the selected cluster.</returns> /// TCluster this[int index] { get; } } }
namespace RealEstate.Web.Api.Models.RealEstates { using System; using System.Collections.Generic; using AutoMapper; using Comments; using Data.Models; using Infrastructure.Mappings; public class ListedRealEstateResponseModelForPublic : IMapFrom<RealEstate>, IHaveCustomMappings, IRealEstateResponseModel { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public DateTime DateCreated { get; set; } public RealEstateType RealEstateType { get; set; } public int? ConstructionYear { get; set; } public string Address { get; set; } public bool CanBeSold { get; set; } public bool CanBeRented { get; set; } public string Contact { get; set; } public string UserName { get; set; } public IEnumerable<ListCommentRequestModel> Comments { get; set; } public void CreateMappings(IConfiguration configuration) { configuration.CreateMap<RealEstate, ListedRealEstateResponseModelForPublic>() .ForMember(r => r.UserName, opts => opts.MapFrom(r => r.User.UserName)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BarberShop.Domains { public abstract class Person { public Guid Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public int Age { get; set; } public Enum Gender { get; set; } } }
namespace System.Collections.Immutable { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Validation; public static class ImmutableSortedDictionary { public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>() { return ImmutableSortedDictionary<TKey, TValue>.Empty; } public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer); } public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>() { return Create<TKey, TValue>().ToBuilder(); } public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer) { return Create<TKey, TValue>(keyComparer).ToBuilder(); } public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder(); } public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.AddRange(items); } public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items); } public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { return source.ToImmutableSortedDictionary<TKey, TValue>(null, null); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer) { return source.ToImmutableSortedDictionary<TKey, TValue>(keyComparer, null); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull<IEnumerable<KeyValuePair<TKey, TValue>>>(source, "source"); ImmutableSortedDictionary<TKey, TValue> dictionaryV40 = source as ImmutableSortedDictionary<TKey, TValue>; if (dictionaryV40 != null) { return dictionaryV40.WithComparers(keyComparer, valueComparer); } return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector) { return source.ToImmutableSortedDictionary<TSource, TKey, TValue>(keySelector, elementSelector, null, null); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer) { return source.ToImmutableSortedDictionary<TSource, TKey, TValue>(keySelector, elementSelector, keyComparer, null); } public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull<IEnumerable<TSource>>(source, "source"); Requires.NotNull<Func<TSource, TKey>>(keySelector, "keySelector"); Requires.NotNull<Func<TSource, TValue>>(elementSelector, "elementSelector"); return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(Enumerable.Select<TSource, KeyValuePair<TKey, TValue>>(source, delegate (TSource element) { return new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element)); })); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test5._7andtest5._8 { class Program { static void Main(string[] args) { ///////////////////// 试题5.7 ///////////////////// /// List<string> list = new List<string>(); list.Add("零基础学C#"); list.Add("2本"); list.Add("69.8"); foreach (var item in list)Console.Write(item+"\t"); Console.WriteLine(); ///////////////////// 试题5.8 ///////////////////// Console.WriteLine("有意思的名字:"); string[] nameList = {"王者荣耀","黄埔军校","高富帅","白富美","徐栩如生"}; foreach (var item in nameList) Console.WriteLine(item); Console.WriteLine(); Console.ReadKey(); } } }
using Assets.Scripts.Overlay.MainMenu; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UpdateAmountOfCharacters : MonoBehaviour { public Text amountText; private int lastAmount = 0; // Update is called once per frame void Update() { if(lastAmount != TempoarySettings.NumberOfSelectedCharacters) { lastAmount = TempoarySettings.NumberOfSelectedCharacters; amountText.text = TempoarySettings.NumberOfSelectedCharacters.ToString() + " / " + TempoarySettings.NumberOfPlayers.ToString(); //Allow scene change if(TempoarySettings.NumberOfSelectedCharacters == TempoarySettings.NumberOfPlayers) { var start = FindObjectOfType<StartGameSession>(); start.canStart = true; } else { var start = FindObjectOfType<StartGameSession>(); start.canStart = false; } } } }
using System; using System.Collections.Generic; namespace NGrams.Extensions { public static class ICollectionExtensions { public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> toAdd){ foreach (var addition in toAdd){ collection.Add(addition); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace GistManager.GistService { public abstract class AuthenticationHandlerBase : IAuthenticationHandler { private const string accessTokenKey = "access_token"; private readonly HttpClient httpClient; protected AuthenticationHandlerBase(HttpClient httpClient) { this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } protected abstract AuthenticationResult GetAuthenticationCode(); public async Task<TokenResult> GetTokenAsync() { var authenticationResult = GetAuthenticationCode(); if (!authenticationResult.IsAuthenticationSuccessful) return new TokenResult(false); var requestUri = new Uri($"https://github.com/login/oauth/access_token?client_id={ClientInfo.ClientId}&client_secret={ClientInfo.ClientSecret}&code={authenticationResult.AuthenticationCode}"); using (var response = await httpClient.PostAsync(requestUri, null)) { string responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString); var accessToken = jsonObject[accessTokenKey]; return new TokenResult(true, accessToken); } } } }
namespace EventsKob.Dtos { public class FollowsDto { public string EventMakerId { get; set; } } }
using Lib.Refactor; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Refactor.Repository.Interface { /// <summary> /// Interface ISupplierRepository /// </summary> public interface ISupplierRepository { /// <summary> /// 取得POI資料 /// </summary> /// <returns>List&lt;POI&gt;.</returns> List<POI> Get(); } }
using UnityEngine; using System.Collections; public class LevelChoose : MonoBehaviour { public int level; public Game gameClass; private bool isActive; // Use this for initialization void Start () { if (!gameClass) gameClass = GameObject.FindGameObjectWithTag ("GameScript").GetComponent<Game>(); } void Update () { } void OnMouseDown(){ if (level > gameClass.currentLevel) return; switch (level) { case 1: case 2: case 4: case 5: case 6: case 7: case 8: case 9: case 10: break; } } void OnMouseEnter() { } void OnMouseOver() { } void OnMouseExit() { } }
using Maverick.Xrm.DI.DataObjects; using Maverick.Xrm.DI.Extensions; using Maverick.XTB.DI.DataObjects; using Maverick.XTB.DI.Extensions; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using Microsoft.Xrm.Tooling.Connector; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Maverick.Xrm.DI.Helper { public class DataverseHelper { static IOrganizationService Service = null; /// <summary> /// Rerieve all entities with the given filter conditions /// </summary> /// <param name="service"></param> /// <param name="entityFilters"></param> /// <param name="retrieveAsIfPublished"></param> /// <returns></returns> public static List<EntityMetadata> RetrieveAllEntities(IOrganizationService service, List<EntityFilters> entityFilters = null, bool retrieveAsIfPublished = true) { Service = service; if (entityFilters == null) { entityFilters = new List<EntityFilters>() { EntityFilters.Default }; } // build the bitwise or list of the entity filters var filters = entityFilters.Aggregate<EntityFilters, EntityFilters>(0, (current, item) => current | item); var req = new RetrieveAllEntitiesRequest() { EntityFilters = filters, RetrieveAsIfPublished = retrieveAsIfPublished }; var resp = (RetrieveAllEntitiesResponse)service.Execute(req); // set the itemsource of the itembox equal to entity metadata that is customizable (takes out systemjobs and stuff like that) var entities = resp.EntityMetadata.Where(x => x.IsCustomizable.Value == true).ToList<EntityMetadata>(); return entities; } public static List<DependencyReport> GetDependencyList(IOrganizationService service, Guid objectId, int componentType) { List<DependencyReport> lstReport = new List<DependencyReport>(); Service = service; var dependencyRequest = new RetrieveDependentComponentsRequest { ObjectId = objectId, ComponentType = componentType }; var dependencyResponse = (RetrieveDependentComponentsResponse)service.Execute(dependencyRequest); // If there are no dependent components, we can ignore this component. if (dependencyResponse.EntityCollection.Entities.Any() == false) return lstReport; lstReport = ProcessDependencyList(service, dependencyResponse.EntityCollection); return lstReport; } public static List<DependencyReport> ProcessDependencyList(IOrganizationService service, EntityCollection dependencyEC) { List<DependencyReport> lstReport = new List<DependencyReport>(); Service = service; // If there are no dependent components, we can ignore this component. if (dependencyEC.Entities.Any() == false) return lstReport; Parallel.ForEach(dependencyEC.Entities, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (dependentEntity) => { DependencyReport dr = GenerateDependencyReport(dependentEntity); if (!dr.SkipAdding) { lstReport.Add(dr); } }); return lstReport; } #region Private Methods private static DependencyReport GenerateDependencyReport(Entity dependency) { DependencyReport dependencyReport = new DependencyReport(); var lstComponentTypes = System.Enum.GetValues(typeof(Enum.ComponentType)).Cast<Enum.ComponentType>() .ToList() .Select(ct => new { DisplayValue = ct.GetAttribute<DI.CustomAttributes.DisplayAttribute>().Name, Component = (int)ct }); /*foreach (var ct in lstComponentTypes) { var text = ct.GetAttribute<DI.CustomAttributes.DisplayAttribute>(); if (((OptionSetValue)dependency["dependentcomponenttype"]).Value == (int)ct) { dependencyReport.DependentComponentType = text.Name; } if (((OptionSetValue)dependency["requiredcomponenttype"]).Value == (int)ct) { dependencyReport.RequiredComponentType = text.Name; } }*/ var dependentOptionSet = ((OptionSetValue)dependency["dependentcomponenttype"]).Value; var requiredOptionSet = ((OptionSetValue)dependency["requiredcomponenttype"]).Value; var dependentType = lstComponentTypes.FirstOrDefault(dct => dependentOptionSet == dct.Component); var requiredType = lstComponentTypes.FirstOrDefault(dct => requiredOptionSet == dct.Component); dependencyReport.DependentComponentType = dependentType?.DisplayValue; dependencyReport.RequiredComponentType = requiredType?.DisplayValue; ComponentInfo dependentCI = GetComponentInfo(((OptionSetValue)dependency["dependentcomponenttype"]).Value, (Guid)dependency["dependentcomponentobjectid"]); if (dependentCI != null && !string.IsNullOrEmpty(dependencyReport.DependentComponentType) && !string.IsNullOrEmpty(dependencyReport.RequiredComponentType)) { dependencyReport.DependentComponentName = dependentCI.Name; dependencyReport.DependentDescription = dependentCI.Description; if (dependentCI.IsDashboard) { dependencyReport.DependentComponentType = "Dashboard"; } } else { dependencyReport.SkipAdding = true; } ComponentInfo requiredCI = GetComponentInfo(((OptionSetValue)dependency["requiredcomponenttype"]).Value, (Guid)dependency["requiredcomponentobjectid"]); if (requiredCI != null) { dependencyReport.RequiredComponentName = requiredCI.Name; } // Disabled for testing if (!dependencyReport.SkipAdding && (string.IsNullOrEmpty(dependencyReport.DependentComponentName) || string.IsNullOrEmpty(dependencyReport.RequiredComponentName))) { dependencyReport.SkipAdding = true; } return dependencyReport; } // The name or display name of the component depends on the type of component. private static ComponentInfo GetComponentInfo(int componentType, Guid componentId) { ComponentInfo info = null; switch (componentType) { case (int)Enum.ComponentType.Entity: info = new ComponentInfo(); info.Name = componentId.ToString(); break; case (int)Enum.ComponentType.Attribute: //name = GetAttributeInformation(componentId); info = GetAttributeInformation(componentId); break; case (int)Enum.ComponentType.OptionSet: info = GetGlobalOptionSet(componentId); break; case (int)Enum.ComponentType.SystemForm: info = GetFormDisplay(componentId); break; case (int)Enum.ComponentType.EntityRelationship: info = GetEntityRelationship(componentId); break; case (int)Enum.ComponentType.SDKMessageProcessingStep: info = GetSdkMessageProcessingStep(componentId); break; case (int)Enum.ComponentType.EntityMap: info = GetEntityMap(componentId); break; case (int)Enum.ComponentType.SavedQuery: info = GetSavedQuery(componentId); break; case (int)Enum.ComponentType.ModelDrivenApp: info = GetModelDrivenApp(componentId); break; case (int)Enum.ComponentType.SiteMap: info = GetSitemap(componentId); break; case (int)Enum.ComponentType.MobileOfflineProfile: info = GetMobileProfile(componentId); break; case (int)Enum.ComponentType.EmailTemplate: info = GetEmailTemplate(componentId); break; case (int)Enum.ComponentType.MailMergeTemplate: info = GetMailMergeTemplate(componentId); break; case (int)Enum.ComponentType.Report: info = GetReport(componentId); break; case (int)Enum.ComponentType.CanvasApp: info = GetCanvasApp(componentId); break; case (int)Enum.ComponentType.Workflow: info = GetWorkflow(componentId); break; case (int)Enum.ComponentType.FieldSecurityProfile: info = GetFieldSecurityProfile(componentId); break; default: //name = $"{componentType} - Not Implemented"; break; } return info; } private static ComponentInfo GetAttributeInformation(Guid id) { try { ComponentInfo info = new ComponentInfo(); RetrieveAttributeRequest req = new RetrieveAttributeRequest { MetadataId = id }; RetrieveAttributeResponse resp = null; if (Service is CrmServiceClient svc) { resp = (RetrieveAttributeResponse)svc.Execute(req); } else { resp = (RetrieveAttributeResponse)Service.Execute(req); } AttributeMetadata attmet = resp.AttributeMetadata; info.Name = attmet.SchemaName; info.Description = $"Entity: {attmet.EntityLogicalName}, Label: {attmet.DisplayName.UserLocalizedLabel.Label}"; return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetGlobalOptionSet(Guid id) { try { ComponentInfo info = new ComponentInfo(); RetrieveOptionSetRequest req = new RetrieveOptionSetRequest { MetadataId = id }; RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)Service.Execute(req); OptionSetMetadataBase os = resp.OptionSetMetadata; info.Name = os.DisplayName.UserLocalizedLabel.Label; info.Description = $"Schema: {os.Name}, Is Global: {os.IsGlobal}"; return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetFormDisplay(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eForm = Service.Retrieve("systemform", id, new ColumnSet("name", "objecttypecode", "type", "formactivationstate")); if (eForm != null && eForm.Contains("type") && eForm.Contains("name")) { info.Name = $"{eForm["name"]}"; info.Description = $"Entity: {eForm["objecttypecode"]}, Type: {eForm.GetFormattedValue("type")}, Status: {eForm.GetFormattedValue("formactivationstate")}"; } if (eForm.FormattedValues["type"] == "Dashboard") { info.IsDashboard = true; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetSavedQuery(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eSavedQuery = Service.Retrieve("savedquery", id, new ColumnSet("name", "returnedtypecode", "statuscode", "isdefault")); if (eSavedQuery != null && eSavedQuery.Contains("name") && eSavedQuery.Contains("returnedtypecode")) { info.Name = $"{eSavedQuery["name"]}"; info.Description = $"Entity: {eSavedQuery["returnedtypecode"]}, Status: {eSavedQuery.GetFormattedValue("statuscode")}, Is Default: {eSavedQuery["isdefault"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetEntityMap(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eEntityMap = Service.Retrieve("entitymap", id, new ColumnSet("sourceentityname", "targetentityname")); if (eEntityMap != null && eEntityMap.Contains("sourceentityname") && eEntityMap.Contains("targetentityname")) { info.Name = $"Source: {eEntityMap["sourceentityname"]} | Target: {eEntityMap["targetentityname"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetModelDrivenApp(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eAppModule = Service.Retrieve("appmodule", id, new ColumnSet("name", "uniquename", "statuscode")); if (eAppModule != null && eAppModule.Contains("name")) { info.Name = $"{eAppModule["name"]}"; info.Description = $"Unique Name: {eAppModule["uniquename"]}, Status: {eAppModule.GetFormattedValue("statuscode")}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetCanvasApp(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eCanvasApp = Service.Retrieve("canvasapp", id, new ColumnSet("name", "displayname")); if (eCanvasApp != null && eCanvasApp.Contains("name")) { info.Name = $"{eCanvasApp["displayname"]}"; info.Description = $"Unique Name: {eCanvasApp["name"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetSitemap(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eSitemap = Service.Retrieve("sitemap", id, new ColumnSet(true)); if (eSitemap != null && eSitemap.Contains("sitemapname")) { info.Name = $"{eSitemap["sitemapname"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetMobileProfile(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eMobileProfile = Service.Retrieve("mobileofflineprofile", id, new ColumnSet("name")); if (eMobileProfile != null && eMobileProfile.Contains("name")) { info.Name = $"{eMobileProfile["name"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetEmailTemplate(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eEmailTemplate = Service.Retrieve("template", id, new ColumnSet("title", "templatetypecode", "languagecode")); if (eEmailTemplate != null && eEmailTemplate.Contains("title")) { info.Name = $"{eEmailTemplate["title"]}"; info.Description = $"Type: {eEmailTemplate["templatetypecode"]}, Language: {eEmailTemplate["languagecode"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetMailMergeTemplate(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eMailMerge = Service.Retrieve("mailmergetemplate", id, new ColumnSet("name", "languagecode", "templatetypecode")); if (eMailMerge != null && eMailMerge.Contains("name")) { info.Name = $"{eMailMerge["name"]}"; info.Description = $"Type: {eMailMerge["templatetypecode"]}, Language: {eMailMerge["languagecode"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetReport(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eReport = Service.Retrieve("report", id, new ColumnSet("name", "languagecode", "reporttypecode")); if (eReport != null && eReport.Contains("name")) { info.Name = $"{eReport["name"]}"; info.Description = $"Type: {eReport.GetFormattedValue("reporttypecode")}, Language: {eReport["languagecode"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetSdkMessageProcessingStep(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eSdkMessage = Service.Retrieve("sdkmessageprocessingstep", id, new ColumnSet("name", "stage", "sdkmessageid", "statuscode")); if (eSdkMessage != null && eSdkMessage.Contains("name")) { info.Name = $"{eSdkMessage["name"]}"; info.Description = $"Stage: {eSdkMessage.GetFormattedValue("stage")}, SDK Message: {eSdkMessage.GetFormattedValue("sdkmessageid")}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetWorkflow(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eWorkflow = Service.Retrieve("workflow", id, new ColumnSet("name", "category", "primaryentity", "statuscode", "scope")); if (eWorkflow != null && eWorkflow.Contains("name")) { info.Name = $"{eWorkflow["name"]}"; info.Description = $"Type: {eWorkflow.GetFormattedValue("category")}, Entity: {eWorkflow.GetFormattedValue("primaryentity")}, Status: {eWorkflow.GetFormattedValue("statuscode")}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetFieldSecurityProfile(Guid id) { try { ComponentInfo info = new ComponentInfo(); Entity eFLS = Service.Retrieve("fieldsecurityprofile", id, new ColumnSet("name")); if (eFLS != null && eFLS.Contains("name")) { info.Name = $"{eFLS["name"]}"; } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } private static ComponentInfo GetEntityRelationship(Guid id) { try { ComponentInfo info = new ComponentInfo(); RetrieveRelationshipRequest req = new RetrieveRelationshipRequest { MetadataId = id }; RetrieveRelationshipResponse resp = (RetrieveRelationshipResponse)Service.Execute(req); if (resp != null) { if (resp.RelationshipMetadata.GetType().Name == "OneToManyRelationshipMetadata") { info.Name = $"{resp.RelationshipMetadata.SchemaName} (1:M)"; OneToManyRelationshipMetadata oneToMany = (OneToManyRelationshipMetadata)resp.RelationshipMetadata; info.Description = $"Referenced: {oneToMany.ReferencedEntity} ({oneToMany.ReferencedAttribute}), Referencing: {oneToMany.ReferencingEntity} ({oneToMany.ReferencingAttribute})"; } else if (resp.RelationshipMetadata.GetType().Name == "ManyToManyRelationshipMetadata") { info.Name = $"{resp.RelationshipMetadata.SchemaName} (M:M)"; ManyToManyRelationshipMetadata manyToMany = (ManyToManyRelationshipMetadata)resp.RelationshipMetadata; info.Description = $"First: {manyToMany.Entity1LogicalName} ({manyToMany.Entity1IntersectAttribute}), Second: {manyToMany.Entity2LogicalName} ({manyToMany.Entity2IntersectAttribute})"; } } return info; } catch (Exception ex) { Telemetry.TrackException(ex); return null; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Hotelo.Pages.Hotels { public class UploadModel : PageModel { private IHostingEnvironment _environment; public UploadModel(IHostingEnvironment environment) { _environment = environment; } [BindProperty] public IFormFile Upload { get; set; } public async Task OnPostAsync() { var file = Path.Combine(_environment.ContentRootPath, "uploads", Upload.FileName); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; using (var fileStream = System.IO.File.OpenText("Hotel.xml")) using (XmlReader reader = XmlReader.Create(fileStream, settings)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.WriteLine($"Start Element: {reader.Name}. Has Attributes? : {reader.HasAttributes}"); break; case XmlNodeType.Text: Console.WriteLine($"Inner Text: {reader.Value}"); break; case XmlNodeType.EndElement: Console.WriteLine($"End Element: {reader.Name}"); break; default: Console.WriteLine($"Unknown: {reader.NodeType}"); break; } } } } public void OnGet() { } } }
using System; using System.Threading.Tasks; using GreenPipes; using MassTransit; namespace Sandbox.Blocks { public class TrackingSink : IBlock { public string Name => "TrackingSink"; public void Setup(IReceiveEndpointConfigurator x) { x.UseRateLimit(10); x.UseExecuteAsync(async xx => { await Task.Delay(20); Console.WriteLine("Hello!"); }); } } }
using CityReport.Services; using CityReport.Services.Models; using Moq; using NUnit.Framework; using Shouldly; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace CityReport.Tests.Unit { [TestFixture] public class TestCityReportService { private CityReportService service; [SetUp] public void Setup() { var mockCLient = new Mock<IWeatherAPIHttpClient>(); mockCLient.Setup(x => x.Get(It.IsAny<string>())).ReturnsAsync(new HttpResponseMessage()); service = new CityReportService(mockCLient.Object); } [Test] public async Task TestGetLocation() { //act var LocationResult = await service.GetLocation("test info"); // assert LocationResult.ShouldBeOfType<LocationDTO>(); } [Test] public async Task TestGetCurrent() { //act var CurrentResult = await service.GetCurrent("test info"); // assert CurrentResult.ShouldBeOfType<CurrentDTO>(); } [Test] public async Task TestGetAstronomy() { //act var AstronomyResult = await service.GetAstronomy("test info"); // assert AstronomyResult.ShouldBeOfType<AstronomyDTO>(); } } }
using Caliburn.Micro; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TacticalMaddiAdminTool.ViewModels { public class MainViewModel : Conductor<IScreen>.Collection.OneActive { public MainViewModel(SetsViewModel setsViewModel, CollectionsViewModel collectionsViewModel, FragmentsViewModel fragmentsViewModel) { Items.Add(fragmentsViewModel); Items.Add(collectionsViewModel); Items.Add(setsViewModel); ActivateItem(fragmentsViewModel); } } }
using UnityEngine; public class ResetScript : MonoBehaviour { void OnTriggerEnter(Collider coll) { if(coll.gameObject.tag == "car") { coll.gameObject.transform.position = new Vector3(0, 5, 0); } } }