content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using TNO.API.Areas.Editor.Models.MediaType; using TNO.API.Models; using TNO.DAL.Services; namespace TNO.API.Areas.Editor.Controllers; /// <summary> /// MediaTypeController class, provides MediaType endpoints for the api. /// </summary> [Authorize] [ApiController] [Area("editor")] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[area]/media/types")] [Route("api/[area]/media/types")] [Route("v{version:apiVersion}/[area]/media/types")] [Route("[area]/media/types")] [ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.Unauthorized)] [ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.Forbidden)] public class MediaTypeController : ControllerBase { #region Variables private readonly IMediaTypeService _service; #endregion #region Constructors /// <summary> /// Creates a new instance of a MediaTypeController object, initializes with specified parameters. /// </summary> /// <param name="service"></param> public MediaTypeController(IMediaTypeService service) { _service = service; } #endregion #region Endpoints /// <summary> /// Return an array of MediaType. /// </summary> /// <returns></returns> [HttpGet] [Produces("application/json")] [ProducesResponseType(typeof(IEnumerable<MediaTypeModel>), (int)HttpStatusCode.OK)] [SwaggerOperation(Tags = new[] { "MediaType" })] public IActionResult FindAll() { return new JsonResult(_service.FindAll().Select(c => new MediaTypeModel(c))); } #endregion }
30.339286
102
0.712772
[ "Apache-2.0" ]
ckayfish/tno
api/net/Areas/Editor/Controllers/MediaTypeController.cs
1,699
C#
using Gildemeister.Cliente360.Contracts.Repository; using Gildemeister.Cliente360.Domain; using Gildemeister.Cliente360.Infrastructure; using Gildemeister.DWProd.Persistence.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gildemeister.DWProd.Persistence.Repository { public class CotizacionRepository : RepositoryBase<Cotizacion>, ICotizacionRepository { private IServiceClient serviceClient; public CotizacionRepository(DWProdDbContext context) : base(context) { } public CotizacionRepository(DWProdDbContext context, IServiceClient _serviceClient) : base(context) { this.serviceClient = _serviceClient; } public Task Actualizar(Dictionary<string, StoredProcedure> parameters) { throw new NotImplementedException(); } public IEnumerable<Cotizacion> Buscar(int tipofiltro, string textofiltro) { throw new NotImplementedException(); } public async Task<IEnumerable<Cotizacion>> BuscarPorClienteAsync(string clienteId) { IEnumerable<Cotizacion> _cotizaciones = null; await context.LoadStoredProc("sgsnet_sps_cotizacion_por_cliente") .WithSqlParam("numeroDocumento", clienteId) .ExecuteStoredProcAsync((handler) => { _cotizaciones = handler.ReadToList<Cotizacion>(); handler.NextResult(); }); return _cotizaciones; } public async Task<Cotizacion> BuscarPorCodigoAsync(string clienteId, string cotizacionId) { IEnumerable<Cotizacion> _cotizaciones = null; await context.LoadStoredProc("sgsnet_sps_cotizacion_por_numero") .WithSqlParam("numeroDocumento", clienteId) .WithSqlParam("numeroCotizacion", clienteId) .ExecuteStoredProcAsync(async (handler) => { _cotizaciones = handler.ReadToList<Cotizacion>(); await handler.NextResultAsync(); }); return _cotizaciones.FirstOrDefault(); } public Task Insertar(Dictionary<string, StoredProcedure> parameters) { throw new NotImplementedException(); } public IEnumerable<Cotizacion> Listar(int page, int pageSize, out int pageCount) { throw new NotImplementedException(); } } }
34.181818
97
0.629179
[ "MIT" ]
pSharpX/customer360-api
src/Gildemeister.DWProd.Persistence/Repository/CotizacionRepository.cs
2,634
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // This source code is made available under the terms of the Microsoft Public License (MS-PL) using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace HKH.Linq { /// <summary> /// A basic abstract LINQ query provider /// </summary> public abstract class QueryProvider : IQueryProvider, IQueryText { protected QueryProvider() { } IQueryable<S> IQueryProvider.CreateQuery<S>(Expression expression) { return new Query<S>(this, expression); } IQueryable IQueryProvider.CreateQuery(Expression expression) { Type elementType = TypeHelper.GetElementType(expression.Type); try { return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(elementType), new object[] { this, expression }); } catch (TargetInvocationException tie) { throw tie.InnerException; } } S IQueryProvider.Execute<S>(Expression expression) { // Jacky: dapper always return IEnumerable even if the sql like select count/sum(1)... var result = this.Execute(expression); return (typeof(IEnumerable).IsAssignableFrom(typeof(S))) ? (S)result : (S)(result as IEnumerable<S>).FirstOrDefault(); } object IQueryProvider.Execute(Expression expression) { return this.Execute(expression); } public abstract string GetQueryText(Expression expression); public abstract object Execute(Expression expression); } }
31.666667
141
0.636011
[ "Apache-2.0" ]
JackyLi918/HKH
HKHProjects/DataProvider/DapperLinq/HKH.Linq/Infrastructure/QueryProvider.cs
1,807
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BrightstarDB.Client { using System.Runtime.Serialization; [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="CommitPointInfo", Namespace="http://brightstardb.com/schemas/servicedata/")] internal partial class CommitPointInfo : object, System.Runtime.Serialization.IExtensibleDataObject { private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.DateTime CommitTimeField; private ulong IdField; private System.Guid JobIdField; private string StoreNameField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.DateTime CommitTime { get { return this.CommitTimeField; } set { this.CommitTimeField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal ulong Id { get { return this.IdField; } set { this.IdField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.Guid JobId { get { return this.JobIdField; } set { this.JobIdField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal string StoreName { get { return this.StoreNameField; } set { this.StoreNameField = value; } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="JobInfo", Namespace="http://brightstardb.com/schemas/servicedata/")] internal partial class JobInfo : object, System.Runtime.Serialization.IExtensibleDataObject { private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private System.ServiceModel.ExceptionDetail ExceptionInfoField; private bool JobCompletedOkField; private bool JobCompletedWithErrorsField; private System.DateTime JobEndedAtField; private string JobIdField; private bool JobPendingField; private bool JobStartedField; private System.DateTime JobStartedAtField; private string StatusMessageField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.ServiceModel.ExceptionDetail ExceptionInfo { get { return this.ExceptionInfoField; } set { this.ExceptionInfoField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal bool JobCompletedOk { get { return this.JobCompletedOkField; } set { this.JobCompletedOkField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal bool JobCompletedWithErrors { get { return this.JobCompletedWithErrorsField; } set { this.JobCompletedWithErrorsField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.DateTime JobEndedAt { get { return this.JobEndedAtField; } set { this.JobEndedAtField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal string JobId { get { return this.JobIdField; } set { this.JobIdField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal bool JobPending { get { return this.JobPendingField; } set { this.JobPendingField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal bool JobStarted { get { return this.JobStartedField; } set { this.JobStartedField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.DateTime JobStartedAt { get { return this.JobStartedAtField; } set { this.JobStartedAtField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal string StatusMessage { get { return this.StatusMessageField; } set { this.StatusMessageField = value; } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="TransactionInfo", Namespace="http://brightstardb.com/schemas/servicedata/")] internal partial class TransactionInfo : object, System.Runtime.Serialization.IExtensibleDataObject { private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private ulong IdField; private System.Guid JobIdField; private System.DateTime StartTimeField; private BrightstarDB.Storage.TransactionStatus StatusField; private string StoreNameField; private BrightstarDB.Storage.TransactionType TransactionTypeField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal ulong Id { get { return this.IdField; } set { this.IdField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.Guid JobId { get { return this.JobIdField; } set { this.JobIdField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal System.DateTime StartTime { get { return this.StartTimeField; } set { this.StartTimeField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal BrightstarDB.Storage.TransactionStatus Status { get { return this.StatusField; } set { this.StatusField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal string StoreName { get { return this.StoreNameField; } set { this.StoreNameField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] internal BrightstarDB.Storage.TransactionType TransactionType { get { return this.TransactionTypeField; } set { this.TransactionTypeField = value; } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://brightstardb.com/services/core/", ConfigurationName="BrightstarDB.Client.IBrightstarWcfService")] internal interface IBrightstarWcfService { [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ListStores", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ListStoresResponse")] string[] ListStores(); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ListStores", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ListStoresResponse")] System.Threading.Tasks.Task<string[]> ListStoresAsync(); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreResponse")] void CreateStore(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreResponse")] System.Threading.Tasks.Task CreateStoreAsync(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreWithPersis" + "tenceType", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreWithPersis" + "tenceTypeResponse")] void CreateStoreWithPersistenceType(string storeName, BrightstarDB.Storage.PersistenceType persistenceType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreWithPersis" + "tenceType", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/CreateStoreWithPersis" + "tenceTypeResponse")] System.Threading.Tasks.Task CreateStoreWithPersistenceTypeAsync(string storeName, BrightstarDB.Storage.PersistenceType persistenceType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/DeleteStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/DeleteStoreResponse")] void DeleteStore(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/DeleteStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/DeleteStoreResponse")] System.Threading.Tasks.Task DeleteStoreAsync(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/DoesStoreExist", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/DoesStoreExistRespons" + "e")] bool DoesStoreExist(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/DoesStoreExist", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/DoesStoreExistRespons" + "e")] System.Threading.Tasks.Task<bool> DoesStoreExistAsync(string storeName); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQuery", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryResponse")] System.IO.Stream ExecuteQuery(string storeName, string queryExpression, string[] defaultGraphUris, System.Nullable<System.DateTime> ifNotModifiedSince, string resultsMediaType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQuery", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryResponse")] System.Threading.Tasks.Task<System.IO.Stream> ExecuteQueryAsync(string storeName, string queryExpression, string[] defaultGraphUris, System.Nullable<System.DateTime> ifNotModifiedSince, string resultsMediaType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryOnCommitP" + "oint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryOnCommitP" + "ointResponse")] System.IO.Stream ExecuteQueryOnCommitPoint(BrightstarDB.Client.CommitPointInfo commitPoint, string queryExpression, string[] defaultGraphUris, string resultsMediaType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryOnCommitP" + "oint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteQueryOnCommitP" + "ointResponse")] System.Threading.Tasks.Task<System.IO.Stream> ExecuteQueryOnCommitPointAsync(BrightstarDB.Client.CommitPointInfo commitPoint, string queryExpression, string[] defaultGraphUris, string resultsMediaType); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteTransaction", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteTransactionRes" + "ponse")] BrightstarDB.Client.JobInfo ExecuteTransaction(string storeName, string preconditions, string deletePatterns, string insertData, string defaultGraphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteTransaction", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteTransactionRes" + "ponse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ExecuteTransactionAsync(string storeName, string preconditions, string deletePatterns, string insertData, string defaultGraphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetJobInfo", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetJobInfoResponse")] BrightstarDB.Client.JobInfo GetJobInfo(string storeName, string jobId); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetJobInfo", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetJobInfoResponse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> GetJobInfoAsync(string storeName, string jobId); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/StartImport", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/StartImportResponse")] BrightstarDB.Client.JobInfo StartImport(string store, string fileName, string graphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/StartImport", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/StartImportResponse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> StartImportAsync(string store, string fileName, string graphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/StartExport", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/StartExportResponse")] BrightstarDB.Client.JobInfo StartExport(string store, string fileName, string graphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/StartExport", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/StartExportResponse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> StartExportAsync(string store, string fileName, string graphUri); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteUpdate", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteUpdateResponse" + "")] BrightstarDB.Client.JobInfo ExecuteUpdate(string store, string updateExpression); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteUpdate", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ExecuteUpdateResponse" + "")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ExecuteUpdateAsync(string store, string updateExpression); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ConsolidateStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ConsolidateStoreRespo" + "nse")] BrightstarDB.Client.JobInfo ConsolidateStore(string store); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ConsolidateStore", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ConsolidateStoreRespo" + "nse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ConsolidateStoreAsync(string store); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPoints", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsRespon" + "se")] BrightstarDB.Client.CommitPointInfo[] GetCommitPoints(string storeName, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPoints", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsRespon" + "se")] System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo[]> GetCommitPointsAsync(string storeName, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsInDate" + "Range", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsInDate" + "RangeResponse")] BrightstarDB.Client.CommitPointInfo[] GetCommitPointsInDateRange(string storeName, System.DateTime latest, System.DateTime earliest, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsInDate" + "Range", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointsInDate" + "RangeResponse")] System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo[]> GetCommitPointsInDateRangeAsync(string storeName, System.DateTime latest, System.DateTime earliest, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPoint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointRespons" + "e")] BrightstarDB.Client.CommitPointInfo GetCommitPoint(string storeName, System.DateTime timestamp); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPoint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetCommitPointRespons" + "e")] System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo> GetCommitPointAsync(string storeName, System.DateTime timestamp); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/RevertToCommitPoint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/RevertToCommitPointRe" + "sponse")] void RevertToCommitPoint(string storeName, BrightstarDB.Client.CommitPointInfo commitPoint); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/RevertToCommitPoint", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/RevertToCommitPointRe" + "sponse")] System.Threading.Tasks.Task RevertToCommitPointAsync(string storeName, BrightstarDB.Client.CommitPointInfo commitPoint); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetTransactions", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetTransactionsRespon" + "se")] BrightstarDB.Client.TransactionInfo[] GetTransactions(string storeName, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/GetTransactions", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/GetTransactionsRespon" + "se")] System.Threading.Tasks.Task<BrightstarDB.Client.TransactionInfo[]> GetTransactionsAsync(string storeName, int skip, int take); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ReExecuteTransaction", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ReExecuteTransactionR" + "esponse")] BrightstarDB.Client.JobInfo ReExecuteTransaction(string storeName, BrightstarDB.Client.TransactionInfo transactionInfo); [System.ServiceModel.OperationContractAttribute(Action="http://brightstardb.com/services/core/IBrightstarWcfService/ReExecuteTransaction", ReplyAction="http://brightstardb.com/services/core/IBrightstarWcfService/ReExecuteTransactionR" + "esponse")] System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ReExecuteTransactionAsync(string storeName, BrightstarDB.Client.TransactionInfo transactionInfo); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] internal interface IBrightstarWcfServiceChannel : BrightstarDB.Client.IBrightstarWcfService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] internal partial class BrightstarWcfServiceClient : System.ServiceModel.ClientBase<BrightstarDB.Client.IBrightstarWcfService>, BrightstarDB.Client.IBrightstarWcfService { public BrightstarWcfServiceClient() { } public BrightstarWcfServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public BrightstarWcfServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public BrightstarWcfServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public BrightstarWcfServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public string[] ListStores() { return base.Channel.ListStores(); } public System.Threading.Tasks.Task<string[]> ListStoresAsync() { return base.Channel.ListStoresAsync(); } public void CreateStore(string storeName) { base.Channel.CreateStore(storeName); } public System.Threading.Tasks.Task CreateStoreAsync(string storeName) { return base.Channel.CreateStoreAsync(storeName); } public void CreateStoreWithPersistenceType(string storeName, BrightstarDB.Storage.PersistenceType persistenceType) { base.Channel.CreateStoreWithPersistenceType(storeName, persistenceType); } public System.Threading.Tasks.Task CreateStoreWithPersistenceTypeAsync(string storeName, BrightstarDB.Storage.PersistenceType persistenceType) { return base.Channel.CreateStoreWithPersistenceTypeAsync(storeName, persistenceType); } public void DeleteStore(string storeName) { base.Channel.DeleteStore(storeName); } public System.Threading.Tasks.Task DeleteStoreAsync(string storeName) { return base.Channel.DeleteStoreAsync(storeName); } public bool DoesStoreExist(string storeName) { return base.Channel.DoesStoreExist(storeName); } public System.Threading.Tasks.Task<bool> DoesStoreExistAsync(string storeName) { return base.Channel.DoesStoreExistAsync(storeName); } public System.IO.Stream ExecuteQuery(string storeName, string queryExpression, string[] defaultGraphUris, System.Nullable<System.DateTime> ifNotModifiedSince, string resultsMediaType) { return base.Channel.ExecuteQuery(storeName, queryExpression, defaultGraphUris, ifNotModifiedSince, resultsMediaType); } public System.Threading.Tasks.Task<System.IO.Stream> ExecuteQueryAsync(string storeName, string queryExpression, string[] defaultGraphUris, System.Nullable<System.DateTime> ifNotModifiedSince, string resultsMediaType) { return base.Channel.ExecuteQueryAsync(storeName, queryExpression, defaultGraphUris, ifNotModifiedSince, resultsMediaType); } public System.IO.Stream ExecuteQueryOnCommitPoint(BrightstarDB.Client.CommitPointInfo commitPoint, string queryExpression, string[] defaultGraphUris, string resultsMediaType) { return base.Channel.ExecuteQueryOnCommitPoint(commitPoint, queryExpression, defaultGraphUris, resultsMediaType); } public System.Threading.Tasks.Task<System.IO.Stream> ExecuteQueryOnCommitPointAsync(BrightstarDB.Client.CommitPointInfo commitPoint, string queryExpression, string[] defaultGraphUris, string resultsMediaType) { return base.Channel.ExecuteQueryOnCommitPointAsync(commitPoint, queryExpression, defaultGraphUris, resultsMediaType); } public BrightstarDB.Client.JobInfo ExecuteTransaction(string storeName, string preconditions, string deletePatterns, string insertData, string defaultGraphUri) { return base.Channel.ExecuteTransaction(storeName, preconditions, deletePatterns, insertData, defaultGraphUri); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ExecuteTransactionAsync(string storeName, string preconditions, string deletePatterns, string insertData, string defaultGraphUri) { return base.Channel.ExecuteTransactionAsync(storeName, preconditions, deletePatterns, insertData, defaultGraphUri); } public BrightstarDB.Client.JobInfo GetJobInfo(string storeName, string jobId) { return base.Channel.GetJobInfo(storeName, jobId); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> GetJobInfoAsync(string storeName, string jobId) { return base.Channel.GetJobInfoAsync(storeName, jobId); } public BrightstarDB.Client.JobInfo StartImport(string store, string fileName, string graphUri) { return base.Channel.StartImport(store, fileName, graphUri); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> StartImportAsync(string store, string fileName, string graphUri) { return base.Channel.StartImportAsync(store, fileName, graphUri); } public BrightstarDB.Client.JobInfo StartExport(string store, string fileName, string graphUri) { return base.Channel.StartExport(store, fileName, graphUri); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> StartExportAsync(string store, string fileName, string graphUri) { return base.Channel.StartExportAsync(store, fileName, graphUri); } public BrightstarDB.Client.JobInfo ExecuteUpdate(string store, string updateExpression) { return base.Channel.ExecuteUpdate(store, updateExpression); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ExecuteUpdateAsync(string store, string updateExpression) { return base.Channel.ExecuteUpdateAsync(store, updateExpression); } public BrightstarDB.Client.JobInfo ConsolidateStore(string store) { return base.Channel.ConsolidateStore(store); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ConsolidateStoreAsync(string store) { return base.Channel.ConsolidateStoreAsync(store); } public BrightstarDB.Client.CommitPointInfo[] GetCommitPoints(string storeName, int skip, int take) { return base.Channel.GetCommitPoints(storeName, skip, take); } public System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo[]> GetCommitPointsAsync(string storeName, int skip, int take) { return base.Channel.GetCommitPointsAsync(storeName, skip, take); } public BrightstarDB.Client.CommitPointInfo[] GetCommitPointsInDateRange(string storeName, System.DateTime latest, System.DateTime earliest, int skip, int take) { return base.Channel.GetCommitPointsInDateRange(storeName, latest, earliest, skip, take); } public System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo[]> GetCommitPointsInDateRangeAsync(string storeName, System.DateTime latest, System.DateTime earliest, int skip, int take) { return base.Channel.GetCommitPointsInDateRangeAsync(storeName, latest, earliest, skip, take); } public BrightstarDB.Client.CommitPointInfo GetCommitPoint(string storeName, System.DateTime timestamp) { return base.Channel.GetCommitPoint(storeName, timestamp); } public System.Threading.Tasks.Task<BrightstarDB.Client.CommitPointInfo> GetCommitPointAsync(string storeName, System.DateTime timestamp) { return base.Channel.GetCommitPointAsync(storeName, timestamp); } public void RevertToCommitPoint(string storeName, BrightstarDB.Client.CommitPointInfo commitPoint) { base.Channel.RevertToCommitPoint(storeName, commitPoint); } public System.Threading.Tasks.Task RevertToCommitPointAsync(string storeName, BrightstarDB.Client.CommitPointInfo commitPoint) { return base.Channel.RevertToCommitPointAsync(storeName, commitPoint); } public BrightstarDB.Client.TransactionInfo[] GetTransactions(string storeName, int skip, int take) { return base.Channel.GetTransactions(storeName, skip, take); } public System.Threading.Tasks.Task<BrightstarDB.Client.TransactionInfo[]> GetTransactionsAsync(string storeName, int skip, int take) { return base.Channel.GetTransactionsAsync(storeName, skip, take); } public BrightstarDB.Client.JobInfo ReExecuteTransaction(string storeName, BrightstarDB.Client.TransactionInfo transactionInfo) { return base.Channel.ReExecuteTransaction(storeName, transactionInfo); } public System.Threading.Tasks.Task<BrightstarDB.Client.JobInfo> ReExecuteTransactionAsync(string storeName, BrightstarDB.Client.TransactionInfo transactionInfo) { return base.Channel.ReExecuteTransactionAsync(storeName, transactionInfo); } } }
47.395129
244
0.670407
[ "MIT" ]
smkgeekfreak/BrightstarDB
src/core/BrightstarDB/Client/BrightstarWcfServiceClient.cs
35,027
C#
using System.Collections.Generic; using Microsoft.VisualStudio.TestPlatform.ObjectModel; namespace AzurePipelines.TestLogger { internal class VstpTestRunComplete { public VstpTestRunComplete(bool aborted, ICollection<AttachmentSet> attachmentSets) { Aborted = aborted; Attachments = attachmentSets; } public bool Aborted { get; } public ICollection<AttachmentSet> Attachments { get; set; } } }
27.764706
91
0.684322
[ "MIT" ]
daveaglick/PipelinesTestLogger
src/AzurePipelines.TestLogger/VstpTestRunComplete.cs
474
C#
namespace DotNet.TDD.DeskBooking.Domain.DTOs.Requests { public class BookingRequest { public long DeskId { get; set; } public long EmployeeId { get; set; } public DateTime Date { get; set; } } }
23.2
54
0.62069
[ "MIT" ]
MTrajK/dotnet-projects
DotNet.TDD/DeskBooking/Src/DotNet.TDD.DeskBooking.Domain/DTOs/Requests/BookingRequest.cs
234
C#
namespace Figlut.Server.Toolkit.Data.QueryRunners { #region Using Directives using System; using System.Collections.Generic; using System.Linq; using System.Text; using Figlut.Server.Toolkit.Utilities; #endregion //Using Directives [Serializable] public class SqlQueryRunnerConfig { #region Constructors public SqlQueryRunnerConfig( string sqlQueryRunnerAssemblyPath, string sqlQueryRunnerFullTypeName) { SqlQueryRunnerAssemblyPath = sqlQueryRunnerAssemblyPath; SqlQueryRunnerFullTypeName = sqlQueryRunnerFullTypeName; QueryRunnerAssemblyBytes = FileSystemHelper.GetFileBytes(sqlQueryRunnerAssemblyPath); } public SqlQueryRunnerConfig( string sqlQueryRunnerAssemblyPath, string sqlQueryRunnerFullTypeName, byte[] queryRunnerAssemblyBytes) { SqlQueryRunnerAssemblyPath = sqlQueryRunnerAssemblyPath; SqlQueryRunnerFullTypeName = sqlQueryRunnerFullTypeName; QueryRunnerAssemblyBytes = queryRunnerAssemblyBytes; } #endregion //Constructors #region Fields protected string _sqlQueryRunnerAssemblyPath; protected string _sqlQueryRunnerFullTypeName; protected byte[] _queryRunnerAssemblyBytes; #endregion //Fields #region Properties public string SqlQueryRunnerAssemblyPath { get { return _sqlQueryRunnerAssemblyPath; } set { if(string.IsNullOrEmpty(value)) { throw new NullReferenceException(string.Format( "{0} may not be null or empty on {1}.", EntityReader<SqlQueryRunnerConfig>.GetPropertyName(p => p.SqlQueryRunnerAssemblyPath, false), this.GetType().FullName)); } _sqlQueryRunnerAssemblyPath = value; } } public string SqlQueryRunnerFullTypeName { get { return _sqlQueryRunnerFullTypeName; } set { if (string.IsNullOrEmpty(value)) { throw new NullReferenceException(string.Format( "{0} may not be null or empty on {1}.", EntityReader<SqlQueryRunnerConfig>.GetPropertyName(p => p.SqlQueryRunnerFullTypeName, false), this.GetType().FullName)); } _sqlQueryRunnerFullTypeName = value; } } public byte[] QueryRunnerAssemblyBytes { get { return _queryRunnerAssemblyBytes; } set { if (value == null || value.Length < 1) { throw new NullReferenceException(string.Format( "{0} may not be null or have a 0 length on {1}.", EntityReader<SqlQueryRunnerConfig>.GetPropertyName(p => p.QueryRunnerAssemblyBytes, false), this.GetType().FullName)); } _queryRunnerAssemblyBytes = value; } } #endregion //Properties } }
33.30303
117
0.573552
[ "MIT" ]
PaulKolozsvari/Figlut-Suite
source/trunk/Windows/Figlut.Server.Toolkit.35/Data/QueryRunners/SqlQueryRunnerConfig.cs
3,299
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ASPNetCore3.Models.DTO { public class BookDto : BaseDto { public string Name { get; set; } public string CreatedAt { get; set; } } }
19.285714
45
0.677778
[ "MIT" ]
nvthinh09t4/B
sln/ASPNetCore3/Models/DTO/BookDto.cs
272
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Famoser.FexCompiler.Test.Service.Base { [TestClass] public abstract class BaseService { [TestMethod] public void TestSimpleFex() { TestFex("simple.fex"); } [TestMethod] public void TestAdvancedFex() { TestFex("advanced.fex"); } [TestMethod] public void TestLongFex() { TestFex("long.fex"); } protected abstract void TestFex(string fileName); } }
19.62069
57
0.55536
[ "MIT" ]
famoser/FexCompiler
Famoser.FexCompiler.Test/Service/Base/BaseService.cs
571
C#
using Microsoft.AspNetCore.Http; using System; using System.IO; using System.Threading.Tasks; namespace WalletWasabi.Backend.Middlewares { /// <summary> /// https://www.tpeczek.com/2017/10/exploring-head-method-behavior-in.html /// https://github.com/tpeczek/Demo.AspNetCore.Mvc.CosmosDB/blob/master/Demo.AspNetCore.Mvc.CosmosDB/Middlewares/HeadMethodMiddleware.cs /// </summary> public class HeadMethodMiddleware { #region Fields private readonly RequestDelegate Next; #endregion Fields #region Constructor public HeadMethodMiddleware(RequestDelegate next) { Next = next ?? throw new ArgumentNullException(nameof(next)); } #endregion Constructor #region Methods public async Task InvokeAsync(HttpContext context) { bool methodSwitched = false; if (HttpMethods.IsHead(context.Request.Method)) { methodSwitched = true; context.Request.Method = HttpMethods.Get; context.Response.Body = Stream.Null; } await Next(context); if (methodSwitched) { context.Request.Method = HttpMethods.Head; } } #endregion Methods } }
20.407407
137
0.73049
[ "MIT" ]
Kukks/WalletWasabi
WalletWasabi.Backend/Middlewares/HeadMethodMiddleware.cs
1,104
C#
using System; using Woz.Functional.Monads; using Xunit; namespace Woz.Functional.Tests.Monads { public class IOTests { private static readonly Func<int, IO<int>> Increment = value => () => value + 1; private static readonly Func<int> Get5 = () => 5; private static readonly IO<int> Get5IO = Get5.ToIO(); private static readonly Func<int> Bang = () => { throw new Exception("Bang"); }; private static readonly IO<int> BangIO = Bang.ToIO(); [Fact] public void Construction() => Assert.Equal(5, Get5IO()); [Fact] public void SelectMany() => Assert.Equal(6, Get5IO.SelectMany(Increment)()); [Fact] public void SelectManyFull() { var io = from a in Get5IO from b in Increment(a) select b; Assert.Equal(6, io()); } [Fact] public void Select() => Assert.Equal(6, Get5IO.Select(x => x + 1)()); [Fact] public void KleisliInto() => Assert.Equal(7, Increment.Into(Increment)(5)()); [Fact] public void KleisliSelectManyFull() => Assert.Equal(13, Increment.Into(Increment, (a, b) => a + b)(5)()); [Fact] public void Lift() { Func<int, string> func = value => value.ToString(); Assert.Equal("5", IO.Lift(func)(Get5IO).Run().Value); } [Fact] public void Flattern() => Assert.Equal(5, new IO<IO<int>>(() => Get5IO).Flattern().Run().Value); [Fact] public void Apply() { Func<int, string> func = value => value.ToString(); Assert.Equal("5", Get5IO.Apply(func.ToIO()).Run().Value); } [Fact] public void Run() { Assert.Equal(5, Get5IO.Run().Value); Assert.Equal("Bang", BangIO.Run().Error.Message); } } }
28.235294
113
0.527604
[ "Unlicense" ]
WozSoftware/Woz.Functional
Woz.Functional.Tests/Monads/IOTests.cs
1,922
C#
using System.Collections.Generic; using System.Linq; using Abp.Localization; using ScotchMe.EntityFramework; namespace ScotchMe.Migrations.SeedData { public class DefaultLanguagesCreator { public static List<ApplicationLanguage> InitialLanguages { get; private set; } private readonly ScotchMeDbContext _context; static DefaultLanguagesCreator() { InitialLanguages = new List<ApplicationLanguage> { new ApplicationLanguage(null, "en", "English", "famfamfam-flag-gb"), new ApplicationLanguage(null, "tr", "Türkçe", "famfamfam-flag-tr"), new ApplicationLanguage(null, "zh-CN", "简体中文", "famfamfam-flag-cn"), new ApplicationLanguage(null, "pt-BR", "Português-BR", "famfamfam-flag-br"), new ApplicationLanguage(null, "es", "Español", "famfamfam-flag-es"), new ApplicationLanguage(null, "fr", "Français", "famfamfam-flag-fr"), new ApplicationLanguage(null, "it", "Italiano", "famfamfam-flag-it"), new ApplicationLanguage(null, "ja", "日本語", "famfamfam-flag-jp"), new ApplicationLanguage(null, "nl-NL", "Nederlands", "famfamfam-flag-nl"), new ApplicationLanguage(null, "lt", "Lietuvos", "famfamfam-flag-lt") }; } public DefaultLanguagesCreator(ScotchMeDbContext context) { _context = context; } public void Create() { CreateLanguages(); } private void CreateLanguages() { foreach (var language in InitialLanguages) { AddLanguageIfNotExists(language); } } private void AddLanguageIfNotExists(ApplicationLanguage language) { if (_context.Languages.Any(l => l.TenantId == language.TenantId && l.Name == language.Name)) { return; } _context.Languages.Add(language); _context.SaveChanges(); } } }
33.709677
104
0.580383
[ "Apache-2.0" ]
YannTru/ScotchMe
ScotchMe.EntityFramework/Migrations/SeedData/DefaultLanguagesCreator.cs
2,111
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataTransferObjects.Requests { public class PredstavaUpsertRequest { [Required] public string Naziv { get; set; } public byte[] Slika { get; set; } [Required] public string Trajanje { get; set; } public string Opis { get; set; } public string ReziserImePrezime { get; set; } public string NazivIzvornogDjela { get; set; } public string PisacIzvornogDjela { get; set; } } }
25.045455
54
0.640653
[ "MIT" ]
AdnanIT/eTeatar
eTeatar/DataTransferObjects/Requests/PredstavaUpsertRequest.cs
553
C#
using Astrarium.Algorithms; using Astrarium.Plugins.Eclipses.ImportExport; using Astrarium.Plugins.Eclipses.Types; using Astrarium.Types; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Input; namespace Astrarium.Plugins.Eclipses.ViewModels { public class LunarEclipseVM : EclipseVM { /// <summary> /// Table of local contacts instants, displayed to the right of eclipse map /// </summary> public ObservableCollection<LunarEclipseLocalContactsTableItem> LocalContactsTable { get => GetValue(nameof(LocalContactsTable), new ObservableCollection<LunarEclipseLocalContactsTableItem>(Enumerable.Repeat(new LunarEclipseLocalContactsTableItem(null, null), 7))); private set => SetValue(nameof(LocalContactsTable), value); } /// <summary> /// Besselian elements table /// </summary> public ObservableCollection<LunarElementsTableItem> BesselianElementsTable { get => GetValue(nameof(BesselianElementsTable), new ObservableCollection<LunarElementsTableItem>()); private set => SetValue(nameof(BesselianElementsTable), value); } /// <summary> /// Table of local circumstances for selected cities /// </summary> public ObservableCollection<LunarEclipseCitiesListTableItem> CitiesListTable { get => GetValue(nameof(CitiesListTable), new ObservableCollection<LunarEclipseCitiesListTableItem>()); private set => SetValue(nameof(CitiesListTable), value); } /// <summary> /// Local circumstance of the eclipse /// </summary> public LunarEclipseLocalCircumstances LocalCircumstances { get => GetValue<LunarEclipseLocalCircumstances>(nameof(LocalCircumstances)); private set => SetValue(nameof(LocalCircumstances), value); } private readonly PolygonStyle polygonStyle = new PolygonStyle(new SolidBrush(Color.FromArgb(70, Color.Black))); public ICommand ClearLocationsTableCommand => new Command(ClearLocationsTable); public ICommand LoadLocationsFromFileCommand => new Command(LoadLocationsFromFile); public ICommand ExportLocationsTableCommand => new Command(ExportLocationsTable); private LunarEclipse eclipse; private LunarEclipseMap map; private PolynomialLunarEclipseElements elements; public LunarEclipseVM( ISky sky, IEclipsesCalculator eclipsesCalculator, IGeoLocationsManager locationsManager, ISettings settings) : base(sky, eclipsesCalculator, locationsManager, settings) { } protected override void CalculateLocalCircumstances(CrdsGeographical g) { var local = LunarEclipses.LocalCircumstances(eclipse, elements, g); System.Windows.Application.Current.Dispatcher.Invoke(() => { var items = new List<LunarEclipseLocalContactsTableItem>(); LocalContactsTable[0] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.P1"), local.PenumbralBegin); LocalContactsTable[1] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U1"), local.PartialBegin); LocalContactsTable[2] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U2"), local.TotalBegin); LocalContactsTable[3] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.Max"), local.Maximum); LocalContactsTable[4] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U3"), local.TotalEnd); LocalContactsTable[5] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U4"), local.PartialEnd); LocalContactsTable[6] = new LunarEclipseLocalContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.P4"), local.PenumbralEnd); }); ObserverLocationName = (IsMouseOverMap && !IsMapLocked) ? $"{Text.Get("EclipseView.MouseCoordinates")} ({Format.Geo.Format(FromGeoPoint(MapMouse))})" : $"{observerLocation.LocationName} ({Format.Geo.Format(observerLocation)})"; LocalVisibilityDescription = eclipsesCalculator.GetLocalVisibilityString(eclipse, local); IsVisibleFromCurrentPlace = !local.IsInvisible; LocalCircumstances = local; } protected override async void CalculateCitiesTable() { if (SelectedTabIndex != 3 || citiesListTableLunationNumber == meeusLunationNumber || !CitiesListTable.Any()) return; var cities = CitiesListTable.Select(l => l.Location).ToArray(); var locals = await Task.Run(() => eclipsesCalculator.FindLocalCircumstancesForCities(eclipse, elements, cities)); System.Windows.Application.Current.Dispatcher.Invoke(() => { CitiesListTable.Clear(); CitiesListTable = new ObservableCollection<LunarEclipseCitiesListTableItem>(locals.Select(c => new LunarEclipseCitiesListTableItem(c, eclipsesCalculator.GetLocalVisibilityString(eclipse, c)))); citiesListTableLunationNumber = meeusLunationNumber; }); } protected override async void CalculateEclipse(bool next, bool saros) { IsCalculating = true; eclipse = eclipsesCalculator.GetNearestLunarEclipse(meeusLunationNumber, next, saros); julianDay = eclipse.JulianDayMaximum; meeusLunationNumber = eclipse.MeeusLunationNumber; elements = eclipsesCalculator.GetLunarEclipseElements(eclipse.JulianDayMaximum); string type = Text.Get($"LunarEclipse.Type.{eclipse.EclipseType}"); EclipseDescription = Text.Get("LunarEclipseView.EclipseDescription", ("type", type)); EclipseDate = Formatters.Date.Format(new Date(eclipse.JulianDayMaximum, 0)); PrevSarosEnabled = eclipsesCalculator.GetNearestLunarEclipse(meeusLunationNumber, next: false, saros: true).Saros == eclipse.Saros; NextSarosEnabled = eclipsesCalculator.GetNearestLunarEclipse(meeusLunationNumber, next: true, saros: true).Saros == eclipse.Saros; await Task.Run(() => { map = LunarEclipses.EclipseMap(eclipse, elements); Polygons.Clear(); Tracks.Clear(); Markers.Clear(); if (map.PenumbralBegin != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.PenumbralBegin.Select(p => ToGeo(p))); Polygons.Add(polygon); } if (map.PartialBegin != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.PartialBegin.Select(p => ToGeo(p))); Polygons.Add(polygon); } if (map.TotalBegin != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.TotalBegin.Select(p => ToGeo(p))); Polygons.Add(polygon); } if (map.TotalEnd != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.TotalEnd.Select(p => ToGeo(p))); Polygons.Add(polygon); } if (map.PartialEnd != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.PartialEnd.Select(p => ToGeo(p))); Polygons.Add(polygon); } if (map.PenumbralEnd != null) { var polygon = new Polygon(polygonStyle); polygon.AddRange(map.PenumbralEnd.Select(p => ToGeo(p))); Polygons.Add(polygon); } // Brown lunation number var lunation = LunarEphem.Lunation(eclipse.JulianDayMaximum); var eclipseGeneralDetails = new ObservableCollection<NameValueTableItem>() { new NameValueTableItem(Text.Get("LunarEclipseView.EclipseType"), $"{type}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipseSaros"), $"{eclipse.Saros}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipseDate"), $"{EclipseDate}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipseMagnitude"), $"{eclipse.Magnitude.ToString("N5", nf)}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipseGamma"), $"{eclipse.Gamma.ToString("N5", nf)}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipsePenumbralDuration"), $"{Format.Time.Format(eclipse.PenumbralDuration)}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipsePartialDuration"), $"{Format.Time.Format(eclipse.PartialDuration)}"), new NameValueTableItem(Text.Get("LunarEclipseView.EclipseTotalDuration"), $"{Format.Time.Format(eclipse.TotalityDuration)}"), new NameValueTableItem(Text.Get("LunarEclipseView.BrownLunationNumber"), $"{lunation}"), new NameValueTableItem("ΔT", $"{elements.DeltaT.ToString("N1", nf) } s") }; System.Windows.Application.Current.Dispatcher.Invoke(() => { EclipseGeneralDetails = eclipseGeneralDetails; }); var eclipseContacts = new ObservableCollection<ContactsTableItem> { new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.P1"), eclipse.JulianDayFirstContactPenumbra), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U1"), eclipse.JulianDayFirstContactUmbra), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U2"), eclipse.JulianDayTotalBegin), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.Max"), eclipse.JulianDayMaximum), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U3"), eclipse.JulianDayTotalEnd), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.U4"), eclipse.JulianDayLastContactUmbra), new ContactsTableItem(Text.Get("LunarEclipseView.LocalCircumstances.P4"), eclipse.JulianDayLastContactPenumbra) }; System.Windows.Application.Current.Dispatcher.Invoke(() => { EclipseContacts = eclipseContacts; }); var besselianElementsTable = new ObservableCollection<LunarElementsTableItem>(); for (int i = 0; i < 4; i++) { besselianElementsTable.Add(new LunarElementsTableItem(i, elements)); } System.Windows.Application.Current.Dispatcher.Invoke(() => { BesselianElementsTable = besselianElementsTable; }); // Besselian elements table header var beTableHeader = new StringBuilder(); beTableHeader.AppendLine($"{Text.Get("EclipseView.BesselianElements.HeaderTime")} t\u2080 = {Formatters.DateTime.Format(new Date(elements.JulianDay0))} TDT (JDE = { elements.JulianDay0.ToString("N6", nf)})"); beTableHeader.AppendLine(Text.Get("LunarEclipseView.BesselianElements.HeaderValid")); BesselianElementsTableHeader = beTableHeader.ToString(); AddLocationMarker(); CalculateSarosSeries(); CalculateLocalCircumstances(observerLocation); CalculateCitiesTable(); CitiesListTable.Select(l => l.Location).ToList().ForEach(c => AddCitiesListMarker(c)); IsCalculating = false; }); } protected override async void CalculateSarosSeries() { await Task.Run(() => { if (SelectedTabIndex != 2 || currentSarosSeries == eclipse.Saros) return; IsCalculating = true; int ln = meeusLunationNumber; var eclipses = new List<LunarEclipse>(); // add current eclipse eclipses.Add(eclipse); currentSarosSeries = eclipse.Saros; SarosSeriesTableTitle = Text.Get("EclipseView.SarosTable.Header", ("currentSarosSeries", currentSarosSeries.ToString())); // add previous eclipses do { var e = eclipsesCalculator.GetNearestLunarEclipse(ln, next: false, saros: true); ln = e.MeeusLunationNumber; if (e.Saros == eclipse.Saros) { eclipses.Insert(0, e); } else { break; } } while (true); ln = meeusLunationNumber; // add next eclipses do { var e = eclipsesCalculator.GetNearestLunarEclipse(ln, next: true, saros: true); ln = e.MeeusLunationNumber; if (e.Saros == eclipse.Saros) { eclipses.Add(e); } else { break; } } while (true); var settingsLocation = settings.Get<CrdsGeographical>("ObserverLocation"); ObservableCollection<SarosSeriesTableItem> sarosSeriesTable = new ObservableCollection<SarosSeriesTableItem>(); int sarosMember = 0; foreach (var e in eclipses) { string type = Text.Get($"LunarEclipse.Type.{e.EclipseType}"); var pbe = eclipsesCalculator.GetLunarEclipseElements(e.JulianDayMaximum); var local = LunarEclipses.LocalCircumstances(e, pbe, settingsLocation); sarosSeriesTable.Add(new SarosSeriesTableItem() { Member = $"{++sarosMember}", MeeusLunationNumber = e.MeeusLunationNumber, JulianDay = e.JulianDayMaximum, Date = Formatters.Date.Format(new Date(e.JulianDayMaximum, 0)), Type = $"{type}", Gamma = e.Gamma.ToString("N5", nf), Magnitude = e.Magnitude.ToString("N5", nf), LocalVisibility = eclipsesCalculator.GetLocalVisibilityString(eclipse, local) }); } System.Windows.Application.Current.Dispatcher.Invoke(() => { SarosSeriesTable = sarosSeriesTable; }); IsCalculating = false; }); } protected override void AddToCitiesList(CrdsGeographical location) { var local = eclipsesCalculator.FindLocalCircumstancesForCities(eclipse, elements, new[] { location }).First(); CitiesListTable.Add(new LunarEclipseCitiesListTableItem(local, eclipsesCalculator.GetLocalVisibilityString(eclipse, local))); AddCitiesListMarker(location); IsCitiesListTableNotEmpty = true; } private async void LoadLocationsFromFile() { var tokenSource = new CancellationTokenSource(); var progress = new Progress<double>(); ICollection<LunarEclipseLocalCircumstances> locals = null; try { string file = ViewManager.ShowOpenFileDialog("$EclipseView.ImportCitiesList.DialogTitle", $"{Text.Get("EclipseView.ImportCitiesList.FileFormat")}|*.csv", out int filterIndex); if (file != null) { ViewManager.ShowProgress("$EclipseView.WaitMessageBox.Title", "$EclipseView.LocalCircumstances.CalculatingCircumstancesProgress", tokenSource); var cities = new CsvLocationsReader().ReadFromFile(file); locals = await Task.Run(() => eclipsesCalculator.FindLocalCircumstancesForCities(eclipse, elements, cities, tokenSource.Token, null)); } } catch (Exception ex) { tokenSource.Cancel(); ViewManager.ShowMessageBox("$Error", ex.Message); } if (!tokenSource.IsCancellationRequested && locals != null) { tokenSource.Cancel(); System.Windows.Application.Current.Dispatcher.Invoke(() => { CitiesListTable.Clear(); CitiesListTable = new ObservableCollection<LunarEclipseCitiesListTableItem>(locals.Select(c => new LunarEclipseCitiesListTableItem(c, eclipsesCalculator.GetLocalVisibilityString(eclipse, c)))); var cities = CitiesListTable.Select(l => l.Location).ToList(); cities.ForEach(c => AddCitiesListMarker(c)); IsCitiesListTableNotEmpty = CitiesListTable.Any(); }); } } private void ExportLocationsTable() { var formats = new Dictionary<string, string> { [Text.Get("EclipseView.LocalCircumstances.OutputFormat.CsvWithFormatting")] = "*.csv", [Text.Get("EclipseView.LocalCircumstances.OutputFormat.CsvRawData")] = "*.csv", }; string filter = string.Join("|", formats.Select(kv => $"{kv.Key}|{kv.Value}")); var file = ViewManager.ShowSaveFileDialog("$EclipseView.Export", "CitiesList", ".csv", filter, out int selectedFilterIndex); if (file != null) { bool rawData = selectedFilterIndex == 2; var writer = new LunarEclipseCitiesTableCsvWriter(rawData); writer.Write(file, CitiesListTable); var answer = ViewManager.ShowMessageBox("$EclipseView.InfoMessageBox.Title", "$EclipseView.ExportDoneMessage", System.Windows.MessageBoxButton.YesNo); if (answer == System.Windows.MessageBoxResult.Yes) { System.Diagnostics.Process.Start(file); } } } private void ClearLocationsTable() { if (ViewManager.ShowMessageBox("$EclipseView.WarnMessageBox.Title", "$EclipseView.LocalCircumstances.ClearTable.Warning", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes) { System.Windows.Application.Current.Dispatcher.Invoke(() => { CitiesListTable.Clear(); Markers.Clear(); AddLocationMarker(); IsCitiesListTableNotEmpty = false; }); } } } }
48.901478
239
0.596504
[ "MIT" ]
AlexanderKrutov/ADK
Astrarium.Plugins.Eclipses/ViewModels/LunarEclipseVM.cs
19,857
C#
using System; namespace traVRsal.SDK { [Serializable] public class TMLayer { public TMChunk[] chunks; public string compression; public uint[] data; public string draworder; public string encoding; public int height; public int id; public string image; public TMLayer[] layers; public string name; public TMObject[] objects; public float offsetx; public float offsety; public float opacity; public TMProperty[] properties; public string transparentcolor; public string type; public bool visible; public int width; public int x; public int y; public override string ToString() { return $"Layer {name} ({type})"; } } }
23.971429
44
0.570918
[ "MIT" ]
WetzoldStudios/traVRsal-sdk
Runtime/Construction/Tiled/TMLayer.cs
841
C#
using Unity.Animation; using Unity.Collections; using Unity.Entities; using Unity.Jobs; using Unity.Mathematics; using Unity.Physics.Systems; using Unity.Sample.Core; using Unity.Transforms; using UnityEngine.Profiling; public class RigAttacher { public struct AttachEntity : IComponentData { public Entity Value; } public struct AttachBone : IComponentData { public RuntimeBoneReference Value; } public struct State : IComponentData { public static State Default => new State { LastMappedBoneRef = RuntimeBoneReference.Default, boneIndex = -1,}; public Entity rigEntity; public RuntimeBoneReference LastMappedBoneRef; public int boneIndex; } public static void AddRigAttacher(Entity entity, EntityManager dstManager, RuntimeBoneReference boneRef) { var attachBone = new AttachBone { Value = boneRef, }; dstManager.AddComponentData(entity, attachBone); dstManager.AddComponentData(entity, State.Default); if(dstManager.HasComponent<Static>(entity)) dstManager.AddComponentData(entity,new Static()); if(dstManager.HasComponent<Static>(entity)) dstManager.AddComponentData(entity,new Static()); if(dstManager.HasComponent<Parent>(entity)) dstManager.RemoveComponent<Parent>(entity); } [UpdateInGroup(typeof(SimulationSystemGroup))] [UpdateAfter(typeof(AnimationSystemGroup))] [UpdateBefore(typeof(TransformSystemGroup))] [UpdateBefore(typeof(BuildPhysicsWorld))] [AlwaysSynchronizeSystem] public class Update : JobComponentSystem { protected override JobHandle OnUpdate(JobHandle inputDeps) { // TODO (mogensh) When all rig remapping happens we animstream, we no longer need to handle rig change Profiler.BeginSample("RigAttach.HandleChange"); Entities .WithoutBurst() // EntityManager.Exists() and EntityManager.GetSharedComponentData() are not Burst-compatible .ForEach((Entity entity, ref AttachEntity attachEntity, ref AttachBone attachBone, ref State state) => { if (!EntityManager.Exists(attachEntity.Value)) { GameDebug.LogWarning(World,"Attach entity:{0}" + attachEntity.Value + " does no longer exist"); return; } // TODO (mogensh) dont check this every frame. Instead // Find bone index if (!attachBone.Value.Equals(state.LastMappedBoneRef) || attachEntity.Value != state.rigEntity) { if (attachEntity.Value != Entity.Null) { Profiler.BeginSample("GetSharedRigDef"); var sharedRigDef = EntityManager.GetSharedComponentData<SharedRigDefinition>(attachEntity.Value); Profiler.EndSample(); if (attachBone.Value.ReferenceRig.Value.GetHashCode() == sharedRigDef.Value.Value.GetHashCode()) { state.boneIndex = attachBone.Value.BoneIndex; } else { Profiler.BeginSample("GetOrCreateRigMapping"); BlobAssetReference<AnimationAssetDatabase.RigMap> rigMap; AnimationAssetDatabase.GetOrCreateRigMapping(World, attachBone.Value.ReferenceRig, sharedRigDef.Value, out rigMap); Profiler.EndSample(); state.boneIndex = rigMap.Value.BoneMap[attachBone.Value.BoneIndex]; } } else { state.boneIndex = -1; } state.LastMappedBoneRef = attachBone.Value; // new RuntimeBoneReference(attachBone.Value); state.rigEntity = attachEntity.Value; } }).Run(); Profiler.EndSample(); var AnimatedLocalToWorldFromEntity = GetBufferFromEntity<AnimatedLocalToWorld>(true); var LocalToParentFromEntity = GetComponentDataFromEntity<LocalToParent>(true); Profiler.BeginSample("RigAttach.Move"); Entities .WithReadOnly(AnimatedLocalToWorldFromEntity) .WithReadOnly(LocalToParentFromEntity) .ForEach((Entity entity, ref LocalToWorld localToWorld, ref Translation translation, ref Rotation rotation, in AttachEntity attachEntity, in AttachBone attachBone, in State state) => { if (!AnimatedLocalToWorldFromEntity.Exists(attachEntity.Value)) { //GameDebug.LogWarning(World, string.Format("RigAttacher:{0} attacheEntity:{1} has not AnimatedLocalToWorld", entity,attachEntity.Value)); return; } // Move if (state.boneIndex != -1) { var localToWorldBuffer = AnimatedLocalToWorldFromEntity[attachEntity.Value]; var boneLocalToWorld = localToWorldBuffer[state.boneIndex].Value; if (LocalToParentFromEntity.HasComponent(entity)) { var attacherLocalToParent = LocalToParentFromEntity[entity]; boneLocalToWorld = math.mul(boneLocalToWorld, attacherLocalToParent.Value); } localToWorld = new LocalToWorld { Value = boneLocalToWorld }; // TODO (mogensh) Unity.Physics uses translation+rotation as input so they also need to be set. translation = new Translation { Value = boneLocalToWorld.c3.xyz, }; rotation = new Rotation { Value = new quaternion(boneLocalToWorld), }; } }).Run(); Profiler.EndSample(); return default; } } }
40.424051
158
0.56662
[ "MIT" ]
The-ULTIMATE-MULTIPLAYER-EXPERIENCE/Ultimate-Archery-Multiplayer-Unity-Game
DOTSSample-master/Assets/Unity.Sample.Game/Animation/RigAttacher.cs
6,389
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Configuration; using Autodesk.DesignScript.Runtime; using DynaShape; using DynaShape.Goals; using DynaShape.GeometryBinders; namespace DynaShape.ZeroTouch { public static class Solver { public static DynaShape.Solver Create() => new DynaShape.Solver(); [CanUpdatePeriodically(true)] [MultiReturn( "nodePositions", "goalOutputs", "geometries", "time", "display")] public static Dictionary<string, object> Execute( DynaShape.Solver solver, List<Goal> goals, [DefaultArgument("null")] List<GeometryBinder> geometryBinders, [DefaultArgument("10")] int iterations, [DefaultArgument("true")] bool reset, [DefaultArgument("true")] bool momentum, [DefaultArgument("true")] bool fastDisplay, [DefaultArgument("false")] bool mouseInteract) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (reset) { solver.Clear(); solver.AddGoals(goals); if (geometryBinders != null) solver.AddGeometryBinders(geometryBinders); } else { solver.AllowMouseInteraction = mouseInteract; solver.Step(iterations, momentum); } double time = stopwatch.Elapsed.TotalMilliseconds; return fastDisplay ? new Dictionary<string, object> { {"time", time}, {"display", new DynaShapeDisplay(solver)} } : new Dictionary<string, object> { {"nodePositions", solver.GetNodePositionsAsPoints()}, {"geometries", solver.GetGeometries()}, {"time", time}, }; } } }
29.347826
74
0.540741
[ "MIT" ]
MostafaElAyoubi/DynaShape
DynaShape/ZeroTouch/Solver.cs
2,027
C#
using System.Collections.Generic; using System.Linq; using System.Data.Entity; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using MultiSAAS.Extensions; namespace MultiSAAS.Data { public class UserData { private readonly DbContext _context; public UserData() : this(new DbContext()) { } public UserData(DbContext context) { _context = context; } public async Task<List<ProjectTo>> ProjectToListAsync<ProjectTo>(string username, string firstName = null, string lastName = null, string emailAddress = null, bool? enabled = null) { return await Queryable(username, firstName, lastName, emailAddress, enabled).ProjectTo<ProjectTo>().ToListAsync(); } public List<ProjectTo> ProjectToList<ProjectTo>(string username, string firstName = null, string lastName = null, string emailAddress = null, bool? enabled = null) { using (var context = new DbContext()) { return Queryable(username, firstName, lastName, emailAddress, enabled).ProjectTo<ProjectTo>().ToList(); } } private IQueryable Queryable(string username, string firstName = null, string lastName = null, string emailAddress = null, bool? enabled = null) { var list = _context.Users .Include(u => u.ExternalTenant) .Where(u => (string.IsNullOrEmpty(username) || u.Username.Equals(username)) && (string.IsNullOrEmpty(firstName) || u.FirstName.StartsWith(firstName)) && (string.IsNullOrEmpty(lastName) || u.LastName.StartsWith(lastName)) && (string.IsNullOrEmpty(emailAddress) || u.EmailAddress.StartsWith(emailAddress)) && (enabled == null || u.Enabled == enabled) ) .AsNoTracking(); return list; } public Entities.User Single(string id) { if (string.IsNullOrEmpty(id)) { return null; } else { return _context.Users.AsNoTracking().SingleOrDefault(u => u.Username == id); } } public Entities.User Authenticate(string id, string password) { var encryptedPassword = password.Encrypt(); return _context.Users.FirstOrDefault(u => u.Username == id && u.Password == encryptedPassword); } public void Add(Entities.User entity, bool onlyIfNotExists = false) { if (entity != null) { if (onlyIfNotExists) { _context.Users.AddIfNotExists(entity); } else { _context.Users.Add(entity); } _context.SaveChanges(); } } public void Update(Entities.User entity) { if (entity != null) { if (string.IsNullOrEmpty(entity.Password)) { _context.Users.Attach(entity); _context.Entry(entity).Property("Password").IsModified = false; } _context.Entry(entity).State = EntityState.Modified; _context.SaveChanges(); } } public void Remove(string id) { if (!string.IsNullOrEmpty(id)) { _context.Users.Remove(_context.Users.Find(id)); _context.SaveChanges(); } } } }
28.645455
184
0.627737
[ "MIT" ]
hallbox/MultiSAAS
MultiSAAS.Data/UserData.cs
3,153
C#
using System; using ClickHouse.Client.Types.Grammar; using ClickHouse.Client.Utility; namespace ClickHouse.Client.Types { internal class DecimalType : ParameterizedType { public virtual int Precision { get; set; } public int Scale { get; set; } public override string Name => "Decimal"; public override ClickHouseTypeCode TypeCode => ClickHouseTypeCode.Decimal; /// <summary> /// Gets size of type in bytes /// </summary> public virtual int Size => GetSizeFromPrecision(Precision); private int GetSizeFromPrecision(int precision) => precision switch { int p when p >= 1 && p < 10 => 4, int p when p >= 10 && p < 19 => 8, int p when p >= 19 && p < 39 => 16, _ => throw new ArgumentOutOfRangeException(nameof(Precision)), }; public override Type FrameworkType => typeof(decimal); public override ParameterizedType Parse(SyntaxTreeNode node, Func<SyntaxTreeNode, ClickHouseType> typeResolverFunc) { var precision = int.Parse(node.ChildNodes[0].Value); var scale = int.Parse(node.ChildNodes[1].Value); var size = GetSizeFromPrecision(precision); switch (size) { case 4: return new Decimal32Type { Precision = precision, Scale = scale }; case 8: return new Decimal64Type { Precision = precision, Scale = scale }; case 16: return new Decimal128Type { Precision = precision, Scale = scale }; default: return new DecimalType { Precision = precision, Scale = scale }; } } public override string ToString() => $"{Name}({Precision}, {Scale})"; } }
33.690909
123
0.573664
[ "MIT" ]
2nnar/ClickHouse.Client
ClickHouse.Client/Types/DecimalType.cs
1,855
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediastore-data-2017-09-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MediaStoreData.Model { /// <summary> /// A metadata entry for a folder or object. /// </summary> public partial class Item { private long? _contentLength; private string _contentType; private string _eTag; private DateTime? _lastModified; private string _name; private ItemType _type; /// <summary> /// Gets and sets the property ContentLength. /// <para> /// The length of the item in bytes. /// </para> /// </summary> public long ContentLength { get { return this._contentLength.GetValueOrDefault(); } set { this._contentLength = value; } } // Check to see if ContentLength property is set internal bool IsSetContentLength() { return this._contentLength.HasValue; } /// <summary> /// Gets and sets the property ContentType. /// <para> /// The content type of the item. /// </para> /// </summary> public string ContentType { get { return this._contentType; } set { this._contentType = value; } } // Check to see if ContentType property is set internal bool IsSetContentType() { return this._contentType != null; } /// <summary> /// Gets and sets the property ETag. /// <para> /// The ETag that represents a unique instance of the item. /// </para> /// </summary> public string ETag { get { return this._eTag; } set { this._eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this._eTag != null; } /// <summary> /// Gets and sets the property LastModified. /// <para> /// The date and time that the item was last modified. /// </para> /// </summary> public DateTime LastModified { get { return this._lastModified.GetValueOrDefault(); } set { this._lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this._lastModified.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the item. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The item type (folder or object). /// </para> /// </summary> public ItemType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
27.582781
113
0.5491
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/MediaStoreData/Generated/Model/Item.cs
4,165
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210210 { /// <summary> /// Base class for container with backup items. Containers with specific workloads are derived from this class. /// </summary> [AzureNativeResourceType("azure-native:recoveryservices/v20210210:ProtectionContainer")] public partial class ProtectionContainer : Pulumi.CustomResource { /// <summary> /// Optional ETag. /// </summary> [Output("eTag")] public Output<string?> ETag { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name associated with the resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// ProtectionContainerResource properties /// </summary> [Output("properties")] public Output<object> Properties { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a ProtectionContainer resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ProtectionContainer(string name, ProtectionContainerArgs args, CustomResourceOptions? options = null) : base("azure-native:recoveryservices/v20210210:ProtectionContainer", name, args ?? new ProtectionContainerArgs(), MakeResourceOptions(options, "")) { } private ProtectionContainer(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:recoveryservices/v20210210:ProtectionContainer", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20210210:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20161201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20161201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20201001:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20201001:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20201201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20201201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20210101:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20210101:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20210201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20210201:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20210201preview:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20210201preview:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-native:recoveryservices/v20210301:ProtectionContainer"}, new Pulumi.Alias { Type = "azure-nextgen:recoveryservices/v20210301:ProtectionContainer"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ProtectionContainer resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ProtectionContainer Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ProtectionContainer(name, id, options); } } public sealed class ProtectionContainerArgs : Pulumi.ResourceArgs { /// <summary> /// Name of the container to be registered. /// </summary> [Input("containerName")] public Input<string>? ContainerName { get; set; } /// <summary> /// Optional ETag. /// </summary> [Input("eTag")] public Input<string>? ETag { get; set; } /// <summary> /// Fabric name associated with the container. /// </summary> [Input("fabricName", required: true)] public Input<string> FabricName { get; set; } = null!; /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// ProtectionContainerResource properties /// </summary> [Input("properties")] public Input<object>? Properties { get; set; } /// <summary> /// The name of the resource group where the recovery services vault is present. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// The name of the recovery services vault. /// </summary> [Input("vaultName", required: true)] public Input<string> VaultName { get; set; } = null!; public ProtectionContainerArgs() { } } }
43.544944
160
0.607276
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210210/ProtectionContainer.cs
7,751
C#
// Copyright (c) 2012, Michael Kunz. All rights reserved. // http://kunzmi.github.io/managedCuda // // This file is part of ManagedCuda. // // ManagedCuda 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. // // ManagedCuda 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 Street, Fifth Floor, Boston, // MA 02110-1301 USA, http://www.gnu.org/licenses/. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using ManagedCuda.BasicTypes; namespace ManagedCuda.CudaFFT { /// <summary> /// Creates a 3D FFT plan configuration according to specified signal sizes /// and data type. This class is the same as <see cref="CudaFFTPlan2D"/> except that /// it takes a third size parameter <c>nz</c>. /// </summary> public class CudaFFTPlan3D : IDisposable { private cufftHandle _handle; private cufftResult res; private bool disposed; private int _nx; private int _ny; private int _nz; private cufftType _type; #region Contructors /// <summary> /// Creates a new 3D FFT plan (old API) /// </summary> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., R2C for real to complex)</param> public CudaFFTPlan3D(int nx, int ny, int nz, cufftType type) { _handle = new cufftHandle(); _nx = nx; _ny = ny; _nz = nz; _type = type; res = CudaFFTNativeMethods.cufftPlan3d(ref _handle, nx, ny, nz, type); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftPlan3d", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Creates a new 3D FFT plan (old API) /// </summary> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., R2C for real to complex)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> public CudaFFTPlan3D(int nx, int ny, int nz, cufftType type, CUstream stream) : this(nx, ny, nz, type) { SetStream(stream); } /// <summary> /// Creates a new 3D FFT plan (old API) /// </summary> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., R2C for real to complex)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> public CudaFFTPlan3D(int nx, int ny, int nz, cufftType type, Compatibility mode) : this(nx, ny, nz, type) { SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (old API) /// </summary> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., R2C for real to complex)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> public CudaFFTPlan3D(int nx, int ny, int nz, cufftType type, CUstream stream, Compatibility mode) : this(nx, ny, nz, type) { SetStream(stream); SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="size"></param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, ref SizeT size) { _handle = handle; _nx = nx; _type = type; res = CudaFFTNativeMethods.cufftMakePlan2d(_handle, nx, ny, type, ref size); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftMakePlan2d", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type) { SizeT size = new SizeT(); _handle = handle; _nx = nx; _type = type; res = CudaFFTNativeMethods.cufftMakePlan2d(_handle, nx, ny, type, ref size); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftMakePlan2d", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream) : this(handle, nx, ny, nz, type) { SetStream(stream); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, Compatibility mode) : this(handle, nx, ny, nz, type) { SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, Compatibility mode) : this(handle, nx, ny, nz, type) { SetStream(stream); SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="size"></param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, ref SizeT size) : this(handle, nx, ny, nz, type, ref size) { SetStream(stream); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="size"></param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, Compatibility mode, ref SizeT size) : this(handle, nx, ny, nz, type, ref size) { SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="size"></param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, Compatibility mode, ref SizeT size) : this(handle, nx, ny, nz, type, ref size) { SetStream(stream); SetCompatibilityMode(mode); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, bool autoAllocate) : this(handle, nx, ny, nz, type) { SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="size"></param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, ref SizeT size, bool autoAllocate) : this(handle, nx, ny, nz, type, ref size) { SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, bool autoAllocate) : this(handle, nx, ny, nz, type) { SetStream(stream); SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, Compatibility mode, bool autoAllocate) : this(handle, nx, ny, nz, type) { SetCompatibilityMode(mode); SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, Compatibility mode, bool autoAllocate) : this(handle, nx, ny, nz, type) { SetStream(stream); SetCompatibilityMode(mode); SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="size"></param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, ref SizeT size, bool autoAllocate) : this(handle, nx, ny, nz, type, ref size) { SetStream(stream); SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="size"></param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, Compatibility mode, ref SizeT size, bool autoAllocate) : this(handle, nx, ny, nz, type, ref size) { SetCompatibilityMode(mode); SetAutoAllocation(autoAllocate); } /// <summary> /// Creates a new 3D FFT plan (new API) /// </summary> /// <param name="handle">cufftHandle object</param> /// <param name="nx">The transform size in the X dimension</param> /// <param name="ny">The transform size in the Y dimension</param> /// <param name="nz">The transform size in the Z dimension</param> /// <param name="type">The transform data type (e.g., C2R for complex to real)</param> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> /// <param name="size"></param> /// <param name="autoAllocate">indicates that the caller intends to allocate and manage /// work areas for plans that have been generated.</param> public CudaFFTPlan3D(cufftHandle handle, int nx, int ny, int nz, cufftType type, CUstream stream, Compatibility mode, ref SizeT size, bool autoAllocate) : this(handle, nx, ny, nz, type, ref size) { SetStream(stream); SetCompatibilityMode(mode); SetAutoAllocation(autoAllocate); } /// <summary> /// For dispose /// </summary> ~CudaFFTPlan3D() { Dispose(false); } #endregion #region Dispose /// <summary> /// Dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// For IDisposable /// </summary> /// <param name="fDisposing"></param> protected virtual void Dispose(bool fDisposing) { if (fDisposing && !disposed) { //Ignore if failing res = CudaFFTNativeMethods.cufftDestroy(_handle); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftDestroy", res)); disposed = true; } if (!fDisposing && !disposed) Debug.WriteLine(String.Format("ManagedCUDA not-disposed warning: {0}", this.GetType())); } #endregion #region Methods /// <summary> /// This call gives a more accurate estimate of the work area size required for a plan than /// cufftEstimate1d(), given the specified parameters, and taking into account any plan /// settings that may have been made. /// </summary> /// <returns></returns> public SizeT GetSize() { SizeT size = new SizeT(); res = CudaFFTNativeMethods.cufftGetSize3d(_handle, _nx, _ny, _nz, _type, ref size); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftGetSize3d", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); return size; } /// <summary> /// During plan execution, CUFFT requires a work area for temporary storage of /// intermediate results. This call returns an estimate for the size of the work area required, /// given the specified parameters, and assuming default plan settings. Note that changing /// some plan settings, such as compatibility mode, may alter the size required for the work /// area. /// </summary> /// <param name="nx">The transform size in the x dimension</param> /// <param name="ny">The transform size in the y dimension</param> /// <param name="nz">The transform size in the z dimension</param> /// <param name="type">The transform data type (e.g., CUFFT_C2C for single /// precision complex to complex)</param> /// <returns></returns> public static SizeT EstimateSize(int nx, int ny, int nz, cufftType type) { SizeT size = new SizeT(); cufftResult res = CudaFFTNativeMethods.cufftEstimate3d(nx, ny, nz, type, ref size); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftEstimate3d", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); return size; } /// <summary> /// Once plan generation has been done, either with the original API or the extensible API, /// this call returns the actual size of the work area required to support the plan. Callers /// who choose to manage work area allocation within their application must use this call /// after plan generation, and after any cufftSet*() calls subsequent to plan generation, if /// those calls might alter the required work space size. /// </summary> /// <returns></returns> public SizeT GetActualSize() { SizeT size = new SizeT(); res = CudaFFTNativeMethods.cufftGetSize(_handle, ref size); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftGetSize", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); return size; } /// <summary> /// SetWorkArea() overrides the work area pointer associated with a plan. /// If the work area was auto-allocated, CUFFT frees the auto-allocated space. The /// cufftExecute*() calls assume that the work area pointer is valid and that it points to /// a contiguous region in device memory that does not overlap with any other work area. If /// this is not the case, results are indeterminate. /// </summary> /// <param name="workArea"></param> public void SetWorkArea(CUdeviceptr workArea) { res = CudaFFTNativeMethods.cufftSetWorkArea(_handle, workArea); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftSetWorkArea", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// SetAutoAllocation() indicates that the caller intends to allocate and manage /// work areas for plans that have been generated. CUFFT default behavior is to allocate /// the work area at plan generation time. If cufftSetAutoAllocation() has been called /// with autoAllocate set to "false" prior to one of the cufftMakePlan*() calls, CUFFT /// does not allocate the work area. This is the preferred sequence for callers wishing to /// manage work area allocation. /// </summary> /// <param name="autoAllocate"></param> public void SetAutoAllocation(bool autoAllocate) { int auto = 0; if (autoAllocate) auto = 1; res = CudaFFTNativeMethods.cufftSetAutoAllocation(_handle, auto); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftSetAutoAllocation", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Executes a CUFTT transorm as defined by the cufftType. /// If idata and odata are the /// same, this method does an in‐place transform. /// </summary> /// <param name="idata"></param> /// <param name="odata"></param> /// <param name="direction">Only unsed for transformations where direction is not implicitly given by type</param> public void Exec(CUdeviceptr idata, CUdeviceptr odata, TransformDirection direction) { switch (_type) { case cufftType.R2C: res = CudaFFTNativeMethods.cufftExecR2C(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecR2C", res)); break; case cufftType.C2R: res = CudaFFTNativeMethods.cufftExecC2R(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2R", res)); break; case cufftType.C2C: res = CudaFFTNativeMethods.cufftExecC2C(_handle, idata, odata, direction); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2C", res)); break; case cufftType.D2Z: res = CudaFFTNativeMethods.cufftExecD2Z(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecD2Z", res)); break; case cufftType.Z2D: res = CudaFFTNativeMethods.cufftExecZ2D(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2D", res)); break; case cufftType.Z2Z: res = CudaFFTNativeMethods.cufftExecZ2Z(_handle, idata, odata, direction); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2Z", res)); break; default: break; } if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Executes a CUFTT transorm as defined by the cufftType. /// This method does an in‐place transform. /// </summary> /// <param name="iodata"></param> /// <param name="direction">Only unsed for transformations where direction is not implicitly given by type</param> public void Exec(CUdeviceptr iodata, TransformDirection direction) { switch (_type) { case cufftType.R2C: res = CudaFFTNativeMethods.cufftExecR2C(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecR2C", res)); break; case cufftType.C2R: res = CudaFFTNativeMethods.cufftExecC2R(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2R", res)); break; case cufftType.C2C: res = CudaFFTNativeMethods.cufftExecC2C(_handle, iodata, iodata, direction); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2C", res)); break; case cufftType.D2Z: res = CudaFFTNativeMethods.cufftExecD2Z(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecD2Z", res)); break; case cufftType.Z2D: res = CudaFFTNativeMethods.cufftExecZ2D(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2D", res)); break; case cufftType.Z2Z: res = CudaFFTNativeMethods.cufftExecZ2Z(_handle, iodata, iodata, direction); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2Z", res)); break; default: break; } if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Executes a CUFTT transorm as defined by the cufftType. /// If idata and odata are the /// same, this method does an in‐place transform.<para/> /// This method is only valid for transform types where transorm direction is implicitly /// given by the type (i.e. not C2C and not Z2Z) /// </summary> /// <param name="idata"></param> /// <param name="odata"></param> public void Exec(CUdeviceptr idata, CUdeviceptr odata) { switch (_type) { case cufftType.R2C: res = CudaFFTNativeMethods.cufftExecR2C(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecR2C", res)); break; case cufftType.C2R: res = CudaFFTNativeMethods.cufftExecC2R(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2R", res)); break; case cufftType.D2Z: res = CudaFFTNativeMethods.cufftExecD2Z(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecD2Z", res)); break; case cufftType.Z2D: res = CudaFFTNativeMethods.cufftExecZ2D(_handle, idata, odata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2D", res)); break; default: throw new ArgumentException("For transformation not of type R2C, C2R, D2Z or Z2D, you must specify a transform direction."); } if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Executes a CUFTT transorm as defined by the cufftType. /// This method does an in‐place transform.<para/> /// This method is only valid for transform types where transorm direction is implicitly /// given by the type (i.e. not C2C and not Z2Z) /// </summary> /// <param name="iodata"></param> public void Exec(CUdeviceptr iodata) { switch (_type) { case cufftType.R2C: res = CudaFFTNativeMethods.cufftExecR2C(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecR2C", res)); break; case cufftType.C2R: res = CudaFFTNativeMethods.cufftExecC2R(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecC2R", res)); break; case cufftType.D2Z: res = CudaFFTNativeMethods.cufftExecD2Z(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecD2Z", res)); break; case cufftType.Z2D: res = CudaFFTNativeMethods.cufftExecZ2D(_handle, iodata, iodata); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftExecZ2D", res)); break; default: throw new ArgumentException("For transformation not of type R2C, C2R, D2Z or Z2D, you must specify a transform direction."); } if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// Associates a CUDA stream with a CUFFT plan. All kernel launches /// made during plan execution are now done through the associated /// stream, enabling overlap with activity in other streams (for example, /// data copying). The association remains until the plan is destroyed or /// the stream is changed with another call to SetStream(). /// </summary> /// <param name="stream">A valid CUDA stream created with cudaStreamCreate() (or 0 for the default stream)</param> public void SetStream(CUstream stream) { res = CudaFFTNativeMethods.cufftSetStream(_handle, stream); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftSetStream", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } /// <summary> /// configures the layout of CUFFT output in FFTW‐compatible modes. /// When FFTW compatibility is desired, it can be configured for padding /// only, for asymmetric complex inputs only, or to be fully compatible. /// </summary> /// <param name="mode">The <see cref="Compatibility"/> option to be used</param> public void SetCompatibilityMode(Compatibility mode) { res = CudaFFTNativeMethods.cufftSetCompatibilityMode(_handle, mode); Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cufftSetCompatibilityMode", res)); if (res != cufftResult.Success) throw new CudaFFTException(res); } #endregion #region Properties /// <summary> /// The transform size in the X dimension /// </summary> public int NX { get { return _nx; } } /// <summary> /// The transform size in the Y dimension /// </summary> public int NY { get { return _ny; } } /// <summary> /// The transform size in the Z dimension /// </summary> public int NZ { get { return _nz; } } /// <summary> /// The transform data type (e.g., R2C for real to complex) /// </summary> public cufftType Type { get { return _type; } } /// <summary> /// Handle /// </summary> public cufftHandle Handle { get { return _handle; } } #endregion } }
45.60582
154
0.621469
[ "Apache-2.0" ]
TillAlex/managedCuda
CudaFFT/CudaFFTPlan3D.cs
34,490
C#
using BannerlordCheats.Settings; using HarmonyLib; using TaleWorlds.CampaignSystem; using TaleWorlds.CampaignSystem.SandBox.GameComponents.Map; namespace BannerlordCheats.Patches { [HarmonyPatch(typeof(DefaultCombatSimulationModel), nameof(DefaultCombatSimulationModel.SimulateHit))] public static class AlwaysWinBattleSimulationPatch { [HarmonyPostfix] public static void SimulateHit(ref CharacterObject strikerTroop, ref CharacterObject struckTroop, ref PartyBase strikerParty, ref PartyBase struckParty, ref float strikerAdvantage, ref MapEvent battle, ref int __result) { if ((struckParty?.Leader?.IsPlayerCharacter ?? false) && BannerlordCheatsSettings.Instance.AlwaysWinBattleSimulation) { __result = 0; } } } }
38
227
0.723684
[ "MIT" ]
adam-march/BannerlordCheats
Patches/Combat/AlwaysWinBattleSimulationPatch.cs
838
C#
using System; using System.Linq; using System.Threading.Tasks; using Illusive.Data; using Illusive.Database; using Illusive.Illusive.Core.Database.Interfaces; using Illusive.Models; using Illusive.Models.Extensions; using Illusive.Utility; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using MongoDB.Bson; namespace Illusive.Pages { public class ForumPost : PageModel { private readonly ILogger<ForumPost> _logger; private readonly IForumService _forumService; private readonly INotificationService _notificationService; public ForumData ForumData { get; set; } [BindProperty] public ForumReply ForumReply { get; set; } public ForumPost(ILogger<ForumPost> logger, IForumService forumService, INotificationService notificationService) { this._logger = logger; this._forumService = forumService; this._notificationService = notificationService; } public async Task<IActionResult> OnGetAsync(string id) { this.ForumData = this._forumService.GetForumById(id); if ( this.ForumData == null ) return this.LocalRedirect("/Index"); this._forumService.AddViewToForum(this.ForumData); await this._notificationService.ReadNotificationsForUserAsync(this.User, this.ForumData.Id); return this.Page(); } public async Task<IActionResult> OnPost(string id) { this.ForumData = this._forumService.GetForumById(id); if ( !this.ModelState.IsValid ) return this.Page(); var forum = this._forumService.GetForumById(id); var reply = this.ForumReply; reply.AuthorId = this.User.GetUniqueId(); if ( forum.IsLocked ) { this._logger.LogError($"{this.User.GetDisplayName()} tried to reply to a locked forum! This shouldn't be possible."); return this.Forbid(); } this._forumService.AddReplyToForum(forum, reply); // Don't notify the owner of their own comments! if ( reply.AuthorId != forum.OwnerId ) { await this._notificationService.AddNotificationAsync(new UserNotification( target: forum.OwnerId, content: $"{this.User.GetDisplayName()} has commented to your post: {reply.Content.SafeSubstring(0, 25)}...", imageUrl: "", link: this.Request.Path + this.Request.QueryString, triggerId: forum.Id )); } this._logger.LogInformation($"{this.User.GetUniqueId()} has replied to forum post {forum.Id}"); return this.Redirect($"/ForumPost?id={id}"); } public class ForumLike { public string forumId { get; set; } } public class ForumLock { public string forumId { get; set; } } public class ForumDelete { public string forumId { get; set; } } public class ForumReplyDelete { public string forumId { get; set; } public string replyId { get; set; } } // POST: DeletePost?handler={json} public ActionResult OnPostDeletePost([FromBody] ForumDelete body) { if ( !this.User.IsLoggedIn() ) this._logger.LogWarning("User attempting to delete a forum without being authenticated!"); var forum = this._forumService.GetForumById(body.forumId); var user = this.User; if ( forum == null ) { this._logger.LogWarning( $"{this.User.GetUniqueId()} is trying to delete an invalid forum ({body.forumId})"); return this.BadRequest(); } if ( user.CanDeletePost(forum) || user.IsAdminAccount() ) { this._forumService.DeleteForum(x => x.Id == forum.Id); this._logger.LogInformation( $"{this.User.GetDisplayName()} has successfully deleted forum with id {forum.Id}!"); } else { this._logger.LogWarning( $"{this.User.GetDisplayName()} is attempting to delete a forum without being authenticated!"); } return new JsonResult(new { Redirect = "/" }); } // POST: LikePost?handler={json} public ActionResult OnPostLikePost([FromBody] ForumLike body) { if ( !this.User.IsLoggedIn() ) throw new Exception("User attempting to like a forum without being authenticated!"); var forum = this._forumService.GetForumById(body.forumId); var user = this.User; var isLiked = forum.Likes.Contains(user.GetUniqueId()); if ( isLiked ) { this._logger.LogInformation($"{user.GetUniqueId()} is unliking post {body.ToJson()})"); this._forumService.RemoveLikeFromForum(forum, user); } else { this._logger.LogInformation($"{user.GetUniqueId()} is liking post {body.ToJson()})"); this._forumService.AddLikeToForum(forum, user); } return new JsonResult(new { Result = isLiked ? "unliked" : "liked", LikeCount = forum.Likes.Count }); } // POST: DeleteReply?handler={json} public ActionResult OnPostDeleteReply([FromBody] ForumReplyDelete body) { if ( !this.User.IsLoggedIn() ) this._logger.LogWarning("User attempting to delete a forum without being authenticated!"); var forum = this._forumService.GetForumById(body.forumId); var reply = forum.Replies.FirstOrDefault(x => x.Id == body.replyId); var user = this.User; if ( reply == null ) { return new JsonResult(new {Error = "TRUE"}); } if ( user.CanDeleteReply(reply) || user.IsAdminAccount() ) { this._forumService.RemoveReplyFromForum(forum, reply.Id); this._logger.LogInformation( $"{this.User.GetDisplayName()} has successfully deleted forum reply with id {reply.Id}!"); } else { this._logger.LogWarning( $"{this.User.GetDisplayName()} is attempting to delete a forum reply without being authenticated!"); } return new JsonResult(new { Redirect = $"/ForumPost?id={forum.Id}" }); } // POST: LockPost?handler={json} public ActionResult OnPostLockPost([FromBody] ForumLock body) { if ( !this.User.IsLoggedIn() ) this._logger.LogWarning("User attempting to delete a forum without being authenticated!"); var forum = this._forumService.GetForumById(body.forumId); var user = this.User; this._logger.LogWarning("OnLockPost"); if ( user.CanLockPost(forum) || user.IsAdminAccount() ) { this._forumService.ToggleLockState(forum); this._logger.LogInformation( forum.IsLocked ? $"{this.User.GetDisplayName()} has successfully unlocked forum reply with id {forum.Id}!" : $"{this.User.GetDisplayName()} has successfully locked forum reply with id {forum.Id}!"); } else { this._logger.LogWarning( $"{this.User.GetDisplayName()} is attempting to lock a forum without being authenticated!"); } return new JsonResult(new { Redirect = $"/ForumPost?id={forum.Id}" }); } } }
39.515
133
0.577629
[ "MIT" ]
pippinmole/Illusive
Pages/ForumPost.cshtml.cs
7,905
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// actioncard /// </summary> public partial class MicrosoftDynamicsCRMactioncard { /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMactioncard /// class. /// </summary> public MicrosoftDynamicsCRMactioncard() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMactioncard /// class. /// </summary> public MicrosoftDynamicsCRMactioncard(string _createdbyValue = default(string), System.DateTimeOffset? expirydate = default(System.DateTimeOffset?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string _createdonbehalfbyValue = default(string), int? recordidobjecttypecode2 = default(int?), string _regardingobjectidValue = default(string), int? priority = default(int?), string data = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), string _parentregardingobjectidValue = default(string), string _owneridValue = default(string), string referencetokens = default(string), string _modifiedbyValue = default(string), int? cardtype = default(int?), string _owningbusinessunitValue = default(string), string description = default(string), int? state = default(int?), long? versionnumber = default(long?), string _modifiedonbehalfbyValue = default(string), object exchangerate = default(object), System.DateTimeOffset? startdate = default(System.DateTimeOffset?), string _owninguserValue = default(string), string actioncardid = default(string), string _transactioncurrencyidValue = default(string), bool? visibility = default(bool?), string _cardtypeidValue = default(string), int? importsequencenumber = default(int?), string _recordidValue = default(string), string _owningteamValue = default(string), string title = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), int? source = default(int?), MicrosoftDynamicsCRMlead regardingobjectidLeadActioncard = default(MicrosoftDynamicsCRMlead), MicrosoftDynamicsCRMincident regardingobjectidIncidentActioncard = default(MicrosoftDynamicsCRMincident), MicrosoftDynamicsCRMserviceappointment regardingobjectidServiceappointmentActioncard = default(MicrosoftDynamicsCRMserviceappointment), MicrosoftDynamicsCRMopportunity regardingobjectidOpportunityActioncard = default(MicrosoftDynamicsCRMopportunity), MicrosoftDynamicsCRMspiceRequiredchecks regardingobjectidSpiceRequiredchecks = default(MicrosoftDynamicsCRMspiceRequiredchecks), MicrosoftDynamicsCRMletter regardingobjectidLetterActioncard = default(MicrosoftDynamicsCRMletter), MicrosoftDynamicsCRMphonecall regardingobjectidPhonecallActioncard = default(MicrosoftDynamicsCRMphonecall), MicrosoftDynamicsCRMfax regardingobjectidFaxActioncard = default(MicrosoftDynamicsCRMfax), MicrosoftDynamicsCRMbusinessunit owningbusinessunit = default(MicrosoftDynamicsCRMbusinessunit), MicrosoftDynamicsCRMtransactioncurrency transactioncurrencyid = default(MicrosoftDynamicsCRMtransactioncurrency), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMprincipal ownerid = default(MicrosoftDynamicsCRMprincipal), MicrosoftDynamicsCRMcontact regardingobjectidContactActioncard = default(MicrosoftDynamicsCRMcontact), IList<MicrosoftDynamicsCRMactioncarduserstate> actionCardUserStateActionCard = default(IList<MicrosoftDynamicsCRMactioncarduserstate>), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMemail regardingobjectidEmailActioncard = default(MicrosoftDynamicsCRMemail), MicrosoftDynamicsCRMappointment regardingobjectidAppointmentActioncard = default(MicrosoftDynamicsCRMappointment), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMrecurringappointmentmaster regardingobjectidRecurringappointmentmasterActioncard = default(MicrosoftDynamicsCRMrecurringappointmentmaster), MicrosoftDynamicsCRMaccount regardingobjectidAccountActioncard = default(MicrosoftDynamicsCRMaccount), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMtask regardingobjectidTaskActioncard = default(MicrosoftDynamicsCRMtask)) { this._createdbyValue = _createdbyValue; Expirydate = expirydate; Overriddencreatedon = overriddencreatedon; this._createdonbehalfbyValue = _createdonbehalfbyValue; Recordidobjecttypecode2 = recordidobjecttypecode2; this._regardingobjectidValue = _regardingobjectidValue; Priority = priority; Data = data; Createdon = createdon; this._parentregardingobjectidValue = _parentregardingobjectidValue; this._owneridValue = _owneridValue; Referencetokens = referencetokens; this._modifiedbyValue = _modifiedbyValue; Cardtype = cardtype; this._owningbusinessunitValue = _owningbusinessunitValue; Description = description; State = state; Versionnumber = versionnumber; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; Exchangerate = exchangerate; Startdate = startdate; this._owninguserValue = _owninguserValue; Actioncardid = actioncardid; this._transactioncurrencyidValue = _transactioncurrencyidValue; Visibility = visibility; this._cardtypeidValue = _cardtypeidValue; Importsequencenumber = importsequencenumber; this._recordidValue = _recordidValue; this._owningteamValue = _owningteamValue; Title = title; Modifiedon = modifiedon; Source = source; RegardingobjectidLeadActioncard = regardingobjectidLeadActioncard; RegardingobjectidIncidentActioncard = regardingobjectidIncidentActioncard; RegardingobjectidServiceappointmentActioncard = regardingobjectidServiceappointmentActioncard; RegardingobjectidOpportunityActioncard = regardingobjectidOpportunityActioncard; RegardingobjectidSpiceRequiredchecks = regardingobjectidSpiceRequiredchecks; RegardingobjectidLetterActioncard = regardingobjectidLetterActioncard; RegardingobjectidPhonecallActioncard = regardingobjectidPhonecallActioncard; RegardingobjectidFaxActioncard = regardingobjectidFaxActioncard; Owningbusinessunit = owningbusinessunit; Transactioncurrencyid = transactioncurrencyid; Modifiedonbehalfby = modifiedonbehalfby; Ownerid = ownerid; RegardingobjectidContactActioncard = regardingobjectidContactActioncard; ActionCardUserStateActionCard = actionCardUserStateActionCard; Createdonbehalfby = createdonbehalfby; RegardingobjectidEmailActioncard = regardingobjectidEmailActioncard; RegardingobjectidAppointmentActioncard = regardingobjectidAppointmentActioncard; Createdby = createdby; RegardingobjectidRecurringappointmentmasterActioncard = regardingobjectidRecurringappointmentmasterActioncard; RegardingobjectidAccountActioncard = regardingobjectidAccountActioncard; Modifiedby = modifiedby; RegardingobjectidTaskActioncard = regardingobjectidTaskActioncard; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "expirydate")] public System.DateTimeOffset? Expirydate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "overriddencreatedon")] public System.DateTimeOffset? Overriddencreatedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "recordidobjecttypecode2")] public int? Recordidobjecttypecode2 { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_regardingobjectid_value")] public string _regardingobjectidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "priority")] public int? Priority { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "data")] public string Data { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_parentregardingobjectid_value")] public string _parentregardingobjectidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "referencetokens")] public string Referencetokens { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "cardtype")] public int? Cardtype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningbusinessunit_value")] public string _owningbusinessunitValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "state")] public int? State { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "versionnumber")] public long? Versionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "exchangerate")] public object Exchangerate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "startdate")] public System.DateTimeOffset? Startdate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owninguser_value")] public string _owninguserValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "actioncardid")] public string Actioncardid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_transactioncurrencyid_value")] public string _transactioncurrencyidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "visibility")] public bool? Visibility { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_cardtypeid_value")] public string _cardtypeidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_recordid_value")] public string _recordidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningteam_value")] public string _owningteamValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "source")] public int? Source { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_lead_actioncard")] public MicrosoftDynamicsCRMlead RegardingobjectidLeadActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_incident_actioncard")] public MicrosoftDynamicsCRMincident RegardingobjectidIncidentActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_serviceappointment_actioncard")] public MicrosoftDynamicsCRMserviceappointment RegardingobjectidServiceappointmentActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_opportunity_actioncard")] public MicrosoftDynamicsCRMopportunity RegardingobjectidOpportunityActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_spice_requiredchecks")] public MicrosoftDynamicsCRMspiceRequiredchecks RegardingobjectidSpiceRequiredchecks { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_letter_actioncard")] public MicrosoftDynamicsCRMletter RegardingobjectidLetterActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_phonecall_actioncard")] public MicrosoftDynamicsCRMphonecall RegardingobjectidPhonecallActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_fax_actioncard")] public MicrosoftDynamicsCRMfax RegardingobjectidFaxActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public MicrosoftDynamicsCRMbusinessunit Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "transactioncurrencyid")] public MicrosoftDynamicsCRMtransactioncurrency Transactioncurrencyid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ownerid")] public MicrosoftDynamicsCRMprincipal Ownerid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_contact_actioncard")] public MicrosoftDynamicsCRMcontact RegardingobjectidContactActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ActionCardUserState_ActionCard")] public IList<MicrosoftDynamicsCRMactioncarduserstate> ActionCardUserStateActionCard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_email_actioncard")] public MicrosoftDynamicsCRMemail RegardingobjectidEmailActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_appointment_actioncard")] public MicrosoftDynamicsCRMappointment RegardingobjectidAppointmentActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_recurringappointmentmaster_actioncard")] public MicrosoftDynamicsCRMrecurringappointmentmaster RegardingobjectidRecurringappointmentmasterActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_account_actioncard")] public MicrosoftDynamicsCRMaccount RegardingobjectidAccountActioncard { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_task_actioncard")] public MicrosoftDynamicsCRMtask RegardingobjectidTaskActioncard { get; set; } } }
48.119565
3,839
0.684436
[ "Apache-2.0" ]
GeorgeWalker/SPD-SPICE
interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMactioncard.cs
17,708
C#
namespace Antijank.Interop { public enum FileDialogAddedPlace { Bottom, Top, } }
8.909091
36
0.642857
[ "MIT" ]
JoeFwd/MnB2-Bannerlord-CommunityPatch
tools/Antijank/Interop/FileDialogAddedPlace.cs
100
C#
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using RoslynCodeTaskFactory.Internal; using RoslynCodeTaskFactory.Properties; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Xml; using System.Xml.Linq; namespace RoslynCodeTaskFactory { /// <inheritdoc /> /// <summary> /// A task factory for compiling in-line code into a <see cref="T:Microsoft.Build.Utilities.Task" />. /// </summary> /// <example> /// </example> public sealed partial class CodeTaskFactory : ITaskFactory { /// <summary> /// A set of default namespaces to add so that user does not have to include them. Make sure that these are covered /// by the list of <see cref="DefaultReferences"/>. /// </summary> internal static readonly IList<string> DefaultNamespaces = new List<string> { "Microsoft.Build.Framework", "Microsoft.Build.Utilities", "System", "System.Collections", "System.Collections.Generic", "System.IO", "System.Linq", "System.Text", }; /// <summary> /// A set of default references to add so that the user does not have to include them. /// </summary> internal static readonly IDictionary<string, IEnumerable<string>> DefaultReferences = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase) { // Common assembly references for all code languages // { String.Empty, new List<string> { "Microsoft.Build.Framework", "Microsoft.Build.Utilities.Core", "netstandard", } }, // CSharp specific assembly references // { "CS", new List<string> { "System.Runtime", } }, // Visual Basic specific assembly references // { "VB", new List<string> { "System.Diagnostics.Debug" } } }; internal static readonly IDictionary<string, ISet<string>> ValidCodeLanguages = new Dictionary<string, ISet<string>>(StringComparer.OrdinalIgnoreCase) { // This dictionary contains a mapping between code languages and known aliases (like "C#"). Everything is case-insensitive. // { "CS", new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "CSharp", "C#" } }, { "VB", new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "VisualBasic", "Visual Basic" } }, }; /// <summary> /// The name of a subdirectory that contains reference assemblies. /// </summary> private const string ReferenceAssemblyDirectoryName = "ref"; /// <summary> /// A cache of <see cref="TaskInfo"/> objects and their corresponding compiled assembly. This cache ensures that two of the exact same code task /// declarations are not compiled multiple times. /// </summary> private static readonly ConcurrentDictionary<TaskInfo, Assembly> CompiledAssemblyCache = new ConcurrentDictionary<TaskInfo, Assembly>(); /// <summary> /// Stores a cache of loaded assemblies by the <see cref="AppDomain.AssemblyResolve"/> handler. /// </summary> private static readonly ConcurrentDictionary<string, Assembly> LoadedAssemblyCache = new ConcurrentDictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Stores the path to the directory that this assembly is located in. /// </summary> private static readonly Lazy<string> ThisAssemblyDirectoryLazy = new Lazy<string>(() => Path.GetDirectoryName(typeof(CodeTaskFactory).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName)); /// <summary> /// Stores the parent directory of this assembly's directory. /// </summary> private static readonly Lazy<string> ThisAssemblyParentDirectoryLazy = new Lazy<string>(() => Path.GetDirectoryName(ThisAssemblyDirectoryLazy.Value)); /// <summary> /// Stores an instance of a <see cref="TaskLoggingHelper"/> for logging messages. /// </summary> private TaskLoggingHelper _log; /// <summary> /// Stores the parameters parsed in the &lt;UsingTask /&gt;. /// </summary> private TaskPropertyInfo[] _parameters; /// <summary> /// Stores the task name parsed in the &lt;UsingTask /&gt;. /// </summary> private string _taskName; /// <inheritdoc cref="ITaskFactory.FactoryName"/> public string FactoryName => "Roslyn Code Task Factory"; /// <inheritdoc /> /// <summary> /// Gets the <see cref="T:System.Type" /> of the compiled task. /// </summary> public Type TaskType { get; private set; } /// <inheritdoc cref="ITaskFactory.CleanupTask(ITask)"/> public void CleanupTask(ITask task) { AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_AssemblyResolve; } /// <inheritdoc cref="ITaskFactory.CreateTask(IBuildEngine)"/> public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) { // The type of the task has already been determined and the assembly is already loaded after compilation so // just create an instance of the type and return it. // return Activator.CreateInstance(TaskType) as ITask; } /// <inheritdoc cref="ITaskFactory.GetTaskParameters"/> public TaskPropertyInfo[] GetTaskParameters() { return _parameters; } /// <inheritdoc cref="ITaskFactory.Initialize"/> public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { WaitForDebuggerIfConfigured(); _log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName) { TaskResources = Strings.ResourceManager, }; _taskName = taskName; _parameters = parameterGroup.Values.ToArray(); // Attempt to parse and extract everything from the <UsingTask /> // if (!TryLoadTaskBody(_log, _taskName, taskBody, _parameters, out TaskInfo taskInfo)) { return false; } // Attempt to compile an assembly (or get one from the cache) // if (!TryCompileInMemoryAssembly(taskFactoryLoggingHost, taskInfo, out Assembly assembly)) { return false; } if (assembly != null) { TaskType = assembly.GetExportedTypes().FirstOrDefault(type => type.Name.Equals(taskName)); } AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve; // Initialization succeeded if we found a type matching the task name from the compiled assembly // return TaskType != null; } /// <summary> /// Gets the full source code by applying an appropriate template based on the current <see cref="CodeTaskFactoryCodeType"/>. /// </summary> internal static void ApplySourceCodeTemplate(TaskInfo taskInfo, ICollection<TaskPropertyInfo> parameters) { if (taskInfo?.SourceCode != null && CodeTemplates.ContainsKey(taskInfo.CodeLanguage) && CodeTemplates[taskInfo.CodeLanguage].ContainsKey(taskInfo.CodeType)) { string usingStatement = String.Join(Environment.NewLine, GetNamespaceStatements(taskInfo.CodeLanguage, DefaultNamespaces.Union(taskInfo.Namespaces, StringComparer.OrdinalIgnoreCase))); string properties = parameters == null ? String.Empty : String.Join(Environment.NewLine, GetPropertyStatements(taskInfo.CodeLanguage, parameters).Select(i => $" {i}")); // Apply the corresponding template based on the code type // taskInfo.SourceCode = String.Format(CodeTemplates[taskInfo.CodeLanguage][taskInfo.CodeType], usingStatement, taskInfo.Name, properties, taskInfo.SourceCode); } } /// <summary> /// Parses and validates the body of the &lt;UsingTask /&gt;. /// </summary> /// <param name="log">A <see cref="TaskLoggingHelper"/> used to log events during parsing.</param> /// <param name="taskName">The name of the task.</param> /// <param name="taskBody">The raw inner XML string of the &lt;UsingTask />&gt; to parse and validate.</param> /// <param name="parameters">An <see cref="ICollection{TaskPropertyInfo}"/> containing parameters for the task.</param> /// <param name="taskInfo">A <see cref="TaskInfo"/> object that receives the details of the parsed task.</param> /// <returns><code>true</code> if the task body was successfully parsed, otherwise <code>false</code>.</returns> /// <remarks> /// The <paramref name="taskBody"/> will look like this: /// <![CDATA[ /// /// <Using Namespace="Namespace" /> /// <Reference Include="AssemblyName|AssemblyPath" /> /// <Code Type="Fragment|Method|Class" Language="cs|vb" Source="Path"> /// // Source code /// </Code> /// /// ]]> /// </remarks> internal static bool TryLoadTaskBody(TaskLoggingHelper log, string taskName, string taskBody, ICollection<TaskPropertyInfo> parameters, out TaskInfo taskInfo) { taskInfo = new TaskInfo() { CodeLanguage = "CS", CodeType = CodeTaskFactoryCodeType.Fragment, Name = taskName, }; XDocument document; try { // For legacy reasons, the inner XML of the <UsingTask /> has no document element. So we have to add a top-level // element around it so it can be parsed. // document = XDocument.Parse($"<Task>{taskBody}</Task>"); } catch (Exception e) { log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidTaskXml", e.Message); return false; } if (document.Root == null) { log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidTaskXml"); return false; } XElement codeElement = null; // Loop through the children, ignoring ones we don't care about, parsing valid ones, and logging an error if we // encounter any element that is not recognized. // foreach (XNode node in document.Root.Nodes() .Where(i => i.NodeType != XmlNodeType.Comment && i.NodeType != XmlNodeType.Whitespace)) { switch (node.NodeType) { case XmlNodeType.Element: XElement child = (XElement) node; // Parse known elements and go to the default case if its an unknown element // if (child.Name.LocalName.Equals("Code", StringComparison.OrdinalIgnoreCase)) { if (codeElement != null) { // Only one <Code /> element is allowed. // log.LogErrorWithCodeFromResources("CodeTaskFactory_MultipleCodeNodes"); return false; } codeElement = child; } else if (child.Name.LocalName.Equals("Reference", StringComparison.OrdinalIgnoreCase)) { XAttribute includeAttribute = child.Attributes().FirstOrDefault(i => i.Name.LocalName.Equals("Include", StringComparison.OrdinalIgnoreCase)); if (String.IsNullOrWhiteSpace(includeAttribute?.Value)) { // A <Reference Include="" /> is not allowed. // log.LogErrorWithCodeFromResources("CodeTaskFactory_AttributeEmpty", "Include", "Reference"); return false; } // Store the reference in the list // taskInfo.References.Add(includeAttribute.Value.Trim()); } else if (child.Name.LocalName.Equals("Using", StringComparison.OrdinalIgnoreCase)) { XAttribute namespaceAttribute = child.Attributes().FirstOrDefault(i => i.Name.LocalName.Equals("Namespace", StringComparison.OrdinalIgnoreCase)); if (String.IsNullOrWhiteSpace(namespaceAttribute?.Value)) { // A <Using Namespace="" /> is not allowed // log.LogErrorWithCodeFromResources("CodeTaskFactory_AttributeEmpty", "Namespace", "Using"); return false; } // Store the using in the list // taskInfo.Namespaces.Add(namespaceAttribute.Value.Trim()); } else { log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidElementLocation", child.Name.LocalName, document.Root.Name.LocalName, " Valid child elements are <Code>, <Reference>, and <Using>."); return false; } break; default: log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidElementLocation", node.NodeType, document.Root.Name.LocalName, " Valid child elements are <Code>, <Reference>, and <Using>."); return false; } } if (codeElement == null) { // <Code /> element is required so if we didn't find it then we need to error // log.LogErrorWithCodeFromResources("CodeTaskFactory_CodeElementIsMissing", taskName); return false; } // Copies the source code from the inner text of the <Code /> element. This might be override later if the user specified // a file instead. // taskInfo.SourceCode = codeElement.Value; // Parse the attributes of the <Code /> element // XAttribute languageAttribute = codeElement.Attributes().FirstOrDefault(i => i.Name.LocalName.Equals("Language", StringComparison.OrdinalIgnoreCase)); XAttribute sourceAttribute = codeElement.Attributes().FirstOrDefault(i => i.Name.LocalName.Equals("Source", StringComparison.OrdinalIgnoreCase)); XAttribute typeAttribute = codeElement.Attributes().FirstOrDefault(i => i.Name.LocalName.Equals("Type", StringComparison.OrdinalIgnoreCase)); if (sourceAttribute != null) { if (String.IsNullOrWhiteSpace(sourceAttribute.Value)) { // A <Code Source="" /> is not allowed // log.LogErrorWithCodeFromResources("CodeTaskFactory_AttributeEmpty", "Source", "Code"); return false; } // Instead of using the inner text of the <Code /> element, read the specified file as source code // taskInfo.CodeType = CodeTaskFactoryCodeType.Class; taskInfo.SourceCode = File.ReadAllText(sourceAttribute.Value.Trim()); } else if (typeAttribute != null) { if (String.IsNullOrWhiteSpace(typeAttribute.Value)) { // A <Code Type="" /> is not allowed // log.LogErrorWithCodeFromResources("CodeTaskFactory_AttributeEmpty", "Type", "Code"); return false; } // Attempt to parse the code type as a CodeTaskFactoryCodeType // if (!Enum.TryParse(typeAttribute.Value.Trim(), ignoreCase: true, result: out CodeTaskFactoryCodeType codeType)) { log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidCodeType", typeAttribute.Value, String.Join(", ", Enum.GetNames(typeof(CodeTaskFactoryCodeType)))); return false; } taskInfo.CodeType = codeType; } if (languageAttribute != null) { if (String.IsNullOrWhiteSpace(languageAttribute.Value)) { // A <Code Language="" /> is not allowed // log.LogErrorWithCodeFromResources("CodeTaskFactory_AttributeEmpty", "Language", "Code"); return false; } if (ValidCodeLanguages.ContainsKey(languageAttribute.Value)) { // The user specified one of the primary code languages using our vernacular // taskInfo.CodeLanguage = languageAttribute.Value.ToUpperInvariant(); } else { bool foundValidCodeLanguage = false; // Attempt to map the user specified value as an alias to our vernacular for code languages // foreach (string validLanguage in ValidCodeLanguages.Keys) { if (ValidCodeLanguages[validLanguage].Contains(languageAttribute.Value)) { taskInfo.CodeLanguage = validLanguage; foundValidCodeLanguage = true; break; } } if (!foundValidCodeLanguage) { // The user specified a code language we don't support // log.LogErrorWithCodeFromResources("CodeTaskFactory_InvalidCodeLanguage", languageAttribute.Value, String.Join(", ", ValidCodeLanguages.Keys)); return false; } } } if (String.IsNullOrWhiteSpace(taskInfo.SourceCode)) { // The user did not specify a path to source code or source code within the <Code /> element. // log.LogErrorWithCodeFromResources("CodeTaskFactory_NoSourceCode"); return false; } ApplySourceCodeTemplate(taskInfo, parameters); return true; } /// <summary> /// Attempts to resolve assembly references that were specified by the user. /// </summary> /// <param name="log">A <see cref="TaskLoggingHelper"/> used for logging.</param> /// <param name="taskInfo">A <see cref="TaskInfo"/> object containing details about the task.</param> /// <param name="items">Receives the list of full paths to resolved assemblies.</param> /// <returns><code>true</code> if all assemblies could be resolved, otherwise <code>false</code>.</returns> /// <remarks>The user can specify a short name like My.Assembly or My.Assembly.dll. In this case we'll /// attempt to look it up in the directory containing our reference assemblies. They can also specify a /// full path and we'll do no resolution. At this time, these are the only two resolution mechanisms. /// Perhaps in the future this could be more powerful by using NuGet to resolve assemblies but we think /// that is too complicated for a simple in-line task. If users have more complex requirements, they /// can compile their own task library.</remarks> internal static bool TryResolveAssemblyReferences(TaskLoggingHelper log, TaskInfo taskInfo, out ITaskItem[] items) { // Store the list of resolved assemblies because a user can specify a short name or a full path // ISet<string> resolvedAssemblyReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase); // Keeps track if there were one or more unresolved assemblies // bool hasInvalidReference = false; // Start with the user specified references and include all of the default references that are language agnostic // IEnumerable<string> references = taskInfo.References.Union(DefaultReferences[String.Empty]); if (DefaultReferences.ContainsKey(taskInfo.CodeLanguage)) { // Append default references for the specific language // references = references.Union(DefaultReferences[taskInfo.CodeLanguage]); } // Loop through the user specified references as well as the default references // foreach (string reference in references) { // The user specified a full path to an assembly, so there is no need to resolve // if (File.Exists(reference)) { // The path could be relative like ..\Assembly.dll so we need to get the full path // resolvedAssemblyReferences.Add(Path.GetFullPath(reference)); continue; } // Attempt to "resolve" the assembly by getting a full path to our distributed reference assemblies // string assemblyFileName = reference.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || reference.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? reference : $"{reference}.dll"; string possiblePath = Path.Combine(ThisAssemblyParentDirectoryLazy.Value, ReferenceAssemblyDirectoryName, assemblyFileName); if (File.Exists(possiblePath)) { resolvedAssemblyReferences.Add(possiblePath); continue; } // Could not resolve the assembly. We currently don't support looking things up the GAC so that in-line task // assemblies are portable across platforms // log.LogErrorWithCodeFromResources("CodeTaskFactory_CouldNotFindReferenceAssembly", reference); hasInvalidReference = true; } // Transform the list of resolved assemblies to TaskItems if they were all resolved // items = hasInvalidReference ? null : resolvedAssemblyReferences.Select(i => (ITaskItem) new TaskItem(i)).ToArray(); return !hasInvalidReference; } /// <summary> /// Gets the namespace statements for the specified code language. /// </summary> /// <param name="codeLanguage">The code language to use.</param> /// <param name="namespaces">An <see cref="IEnumerable{String}"/> containing namespaces to generate statements for.</param> /// <returns>An <see cref="IEnumerable{String}"/> containing namespace statements for the specified code language.</returns> private static IEnumerable<string> GetNamespaceStatements(string codeLanguage, IEnumerable<string> namespaces) { foreach (string @namespace in namespaces.Union(DefaultNamespaces, StringComparer.OrdinalIgnoreCase)) { switch (codeLanguage) { case "CS": yield return $"using {@namespace};"; break; case "VB": yield return $"Imports {@namespace}"; break; } } } /// <summary> /// Gets the property statements for the specified language. /// </summary> /// <param name="codeLanguage">The code language to use.</param> /// <param name="parameters">An <see cref="IEnumerable{TaskPropertyInfo}"/> containing information about the property statements to generate.</param> /// <returns>An <see cref="IEnumerable{String}"/> containing property statements for the specified code language.</returns> private static IEnumerable<string> GetPropertyStatements(string codeLanguage, IEnumerable<TaskPropertyInfo> parameters) { foreach (TaskPropertyInfo taskPropertyInfo in parameters) { switch (codeLanguage) { case "CS": if (taskPropertyInfo.Output) { yield return "[Microsoft.Build.Framework.OutputAttribute]"; } if (taskPropertyInfo.Required) { yield return "[Microsoft.Build.Framework.RequiredAttribute]"; } yield return $"public {taskPropertyInfo.PropertyType.FullName} {taskPropertyInfo.Name} {{ get; set; }}"; break; case "VB": if (taskPropertyInfo.Output) { yield return "<Microsoft.Build.Framework.OutputAttribute>"; } if (taskPropertyInfo.Required) { yield return "<Microsoft.Build.Framework.RequiredAttribute>"; } yield return $"Public Property {taskPropertyInfo.Name} As {taskPropertyInfo.PropertyType.FullName}"; break; } } } /// <summary> /// A custom <see cref="AppDomain.AssemblyResolve"/> handler which loads assemblies needed for the CodeTaskFactory to work. /// </summary> /// <returns></returns> private Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); // Guess the path based on the name // string candidateAssemblyPath = Path.Combine(ThisAssemblyDirectoryLazy.Value, $"{assemblyName.Name}.dll"); // See if the assembly has already been loaded from this path // if (LoadedAssemblyCache.TryGetValue(candidateAssemblyPath, out Assembly loadedAssembly)) { return loadedAssembly; } if (File.Exists(candidateAssemblyPath)) { loadedAssembly = Assembly.LoadFrom(candidateAssemblyPath); // Cache the loaded assembly for later if necessary // LoadedAssemblyCache.TryAdd(candidateAssemblyPath, loadedAssembly); return loadedAssembly; } return null; } /// <summary> /// Loads an assembly from the specified path. /// </summary> /// <param name="path">The full path to the assembly.</param> /// <returns>An <see cref="Assembly"/> object for the loaded assembly.</returns> private Assembly LoadAssembly(string path) { // This method must use reflection so that this task will work on .NET Framework 4.6 (System.Reflection.Assembly) // and .NET Core 1.0 (System.Runtime.Loader.AssemblyLoadContext) // MethodInfo loadMethodInfo = Type.GetType("System.Reflection.Assembly")?.GetMethod("Load", new[] { typeof(byte[]) }); if (loadMethodInfo != null) { return loadMethodInfo.Invoke(null, new object[] { File.ReadAllBytes(path) }) as Assembly; } Type assemblyLoadContextType = Type.GetType("System.Runtime.Loader.AssemblyLoadContext"); PropertyInfo defaultPropertyInfo = assemblyLoadContextType?.GetProperty("Default", BindingFlags.Public | BindingFlags.Static); if (defaultPropertyInfo != null) { object defaultAssemblyLoadContext = defaultPropertyInfo.GetValue(null); MethodInfo loadFromStreamMethodInfo = assemblyLoadContextType.GetMethod("LoadFromStream", new[] { typeof(Stream) }); if (loadFromStreamMethodInfo != null) { using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { return loadFromStreamMethodInfo.Invoke(defaultAssemblyLoadContext, new object[] { stream }) as Assembly; } } } return null; } /// <summary> /// Attempts to compile the current source code and load the assembly into memory. /// </summary> /// <param name="buildEngine">An <see cref="IBuildEngine"/> to use give to the compiler task so that messages can be logged.</param> /// <param name="taskInfo">A <see cref="TaskInfo"/> object containing details about the task.</param> /// <param name="assembly">The <see cref="Assembly"/> if the source code be compiled and loaded, otherwise <code>null</code>.</param> /// <returns><code>true</code> if the source code could be compiled and loaded, otherwise <code>null</code>.</returns> private bool TryCompileInMemoryAssembly(IBuildEngine buildEngine, TaskInfo taskInfo, out Assembly assembly) { // First attempt to get a compiled assembly from the cache // if (CompiledAssemblyCache.TryGetValue(taskInfo, out assembly)) { return true; } // The source code cannot actually be compiled "in memory" so instead the source code is written to disk in // the temp folder as well as the assembly. After compilation, the source code and assembly are deleted. // string sourceCodePath = Path.GetTempFileName(); string assemblyPath = Path.GetTempFileName(); // Delete the code file unless compilation failed or the environment variable MSBUILDLOGCODETASKFACTORYOUTPUT // is set (which allows for debugging problems) // bool deleteSourceCodeFile = Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") == null; try { // Create the code // File.WriteAllText(sourceCodePath, taskInfo.SourceCode); // Execute the compiler. We re-use the existing build task by hosting it and giving it our IBuildEngine instance for logging // ManagedCompiler managedCompiler = null; // User specified values are translated using a dictionary of known aliases and checking if the user specified // a valid code language is already done // if (taskInfo.CodeLanguage.Equals("CS")) { managedCompiler = new Csc { NoStandardLib = true, }; string toolExe = Environment.GetEnvironmentVariable("CscToolExe"); if (!String.IsNullOrEmpty(toolExe)) { managedCompiler.ToolExe = toolExe; } } else if (taskInfo.CodeLanguage.Equals("VB")) { managedCompiler = new Vbc { //NoStandardLib = true, //RootNamespace = "InlineCode", //OptionCompare = "Binary", //OptionExplicit = true, //OptionInfer = true, //OptionStrict = false, //Verbosity = "Verbose", }; string toolExe = Environment.GetEnvironmentVariable("VbcToolExe"); if (!String.IsNullOrEmpty(toolExe)) { managedCompiler.ToolExe = toolExe; } } if (!TryResolveAssemblyReferences(_log, taskInfo, out ITaskItem[] references)) { return false; } if (managedCompiler != null) { // Pass a wrapped BuildEngine which will lower the message importance so it doesn't clutter up the build output // managedCompiler.BuildEngine = new BuildEngineWithLowImportance(buildEngine); managedCompiler.Deterministic = true; managedCompiler.NoConfig = true; managedCompiler.NoLogo = true; managedCompiler.Optimize = false; managedCompiler.OutputAssembly = new TaskItem(assemblyPath); managedCompiler.References = references.ToArray(); managedCompiler.Sources = new ITaskItem[] { new TaskItem(sourceCodePath) }; managedCompiler.TargetType = "Library"; managedCompiler.UseSharedCompilation = false; _log.LogMessageFromResources(MessageImportance.Low, "CodeTaskFactory_CompilingAssembly"); if (!managedCompiler.Execute()) { deleteSourceCodeFile = false; _log.LogErrorWithCodeFromResources("CodeTaskFactory_FindSourceFileAt", sourceCodePath); return false; } } // Return the assembly which is loaded into memory // assembly = LoadAssembly(assemblyPath); // Attempt to cache the compiled assembly // CompiledAssemblyCache.TryAdd(taskInfo, assembly); return true; } catch (Exception e) { _log.LogErrorFromException(e); return false; } finally { if (File.Exists(assemblyPath)) { File.Delete(assemblyPath); } if (deleteSourceCodeFile && File.Exists(sourceCodePath)) { File.Delete(sourceCodePath); } } } /// <summary> /// Waits for a user to attach a debugger. /// </summary> private void WaitForDebuggerIfConfigured() { if (!String.Equals(Environment.GetEnvironmentVariable("ROSLYNCODETASKFACTORY_DEBUG"), "1")) { return; } Process currentProcess = Process.GetCurrentProcess(); Console.WriteLine(Strings.CodeTaskFactory_WaitingForDebugger, currentProcess.MainModule.FileName, currentProcess.Id); while (!Debugger.IsAttached) { Thread.Sleep(200); } Debugger.Break(); } } }
44.486061
201
0.55102
[ "MIT" ]
binki/RoslynCodeTaskFactory
src/RoslynCodeTaskFactory/CodeTaskFactory.cs
36,703
C#
// See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using Microsoft.ML; using Microsoft.ML.Data; using Microsoft.ML.Runtime; using Microsoft.ML.Model; using Scikit.ML.PipelineHelper; namespace Scikit.ML.ProductionPrediction { /// <summary> /// Creates a prediction engine which does not create getters each time. /// It is much faster as it does not recreate getter for every observation. /// </summary> public class ValueMapperPredictionEngine<TRowValue> : IDisposable where TRowValue : class, IClassWithGetter<TRowValue>, new() { #region result type public class PredictionTypeForBinaryClassification : IClassWithSetter<PredictionTypeForBinaryClassification> { public bool PredictedLabel; public float Score; public float Probability; public Delegate[] GetCursorGetter(DataViewRowCursor cursor) { var indexL = SchemaHelper.GetColumnIndexDC(cursor.Schema, "PredictedLabel"); var indexS = SchemaHelper.GetColumnIndexDC(cursor.Schema, "Score"); var indexP = SchemaHelper.GetColumnIndexDC(cursor.Schema, "Probability"); return new Delegate[] { cursor.GetGetter<bool>(indexL), cursor.GetGetter<float>(indexS), cursor.GetGetter<float>(indexP), }; } public void Set(Delegate[] delegates) { var del1 = delegates[0] as ValueGetter<bool>; del1(ref PredictedLabel); var del2 = delegates[1] as ValueGetter<float>; del2(ref Score); var del3 = delegates[2] as ValueGetter<float>; del3(ref Probability); } } #endregion readonly IHostEnvironment _env; readonly IDataView _transforms; readonly IPredictor _predictor; ValueMapper<TRowValue, PredictionTypeForBinaryClassification> _mapperBinaryClassification; IDisposable _valueMapper; public ValueMapperPredictionEngine() { throw Contracts.Except("Use arguments."); } /// <summary> /// Constructor /// </summary> /// <param name="env">environment</param> /// <param name="modelName">filename</param> /// <param name="conc">number of concurrency threads</param> /// <param name="features">features name</param> public ValueMapperPredictionEngine(IHostEnvironment env, string modelName, bool outputIsFloat = true, string features = "Features") : this(env, File.OpenRead(modelName), features) { } /// <summary> /// Constructor /// </summary> /// <param name="env">environment</param> /// <param name="modelStream">stream</param> /// <param name="conc">number of concurrency threads</param> /// <param name="features">features column</param> public ValueMapperPredictionEngine(IHostEnvironment env, Stream modelStream, string features = "Features") { _env = env; if (_env == null) throw Contracts.Except("env must not be null"); var inputs = new TRowValue[0]; var view = DataViewConstructionUtils.CreateFromEnumerable<TRowValue>(_env, inputs); long modelPosition = modelStream.Position; _predictor = ModelFileUtils.LoadPredictorOrNull(_env, modelStream); if (_predictor == null) throw _env.Except("Unable to load a model."); modelStream.Seek(modelPosition, SeekOrigin.Begin); _transforms = ModelFileUtils.LoadTransforms(_env, view, modelStream); if (_transforms == null) throw _env.Except("Unable to load a model."); var data = _env.CreateExamples(_transforms, features); if (data == null) throw _env.Except("Cannot create rows."); var scorer = _env.CreateDefaultScorer(data, _predictor); if (scorer == null) throw _env.Except("Cannot create a scorer."); _CreateMapper(scorer); } /// <summary> /// Constructor /// </summary> /// <param name="env">environment</param> /// <param name="modelStream">stream</param> /// <param name="output">name of the output column</param> /// <param name="outputIsFloat">output is a gloat (true) or a vector of floats (false)</param> public ValueMapperPredictionEngine(IHostEnvironment env, IDataScorerTransform scorer) { _env = env; if (_env == null) throw Contracts.Except("env must not be null"); _CreateMapper(scorer); } void _CreateMapper(IDataScorerTransform scorer) { _mapperBinaryClassification = null; var schema = scorer.Schema; int i1, i2, i3; i1 = SchemaHelper.GetColumnIndex(schema, "PredictedLabel"); i2 = SchemaHelper.GetColumnIndex(schema, "Score"); i3 = SchemaHelper.GetColumnIndex(schema, "Probability"); var map = new ValueMapperFromTransform<TRowValue, PredictionTypeForBinaryClassification>(_env, scorer); _mapperBinaryClassification = map.GetMapper<TRowValue, PredictionTypeForBinaryClassification>(); _valueMapper = map; } public void Dispose() { _valueMapper.Dispose(); _valueMapper = null; } /// <summary> /// Produces prediction for a binary classification. /// </summary> /// <param name="features">features</param> /// <param name="res">prediction</param> public void Predict(TRowValue features, ref PredictionTypeForBinaryClassification res) { if (_mapperBinaryClassification != null) _mapperBinaryClassification(in features, ref res); else throw _env.Except("Unrecognized machine learn problem."); } } }
38.709877
116
0.598629
[ "MIT" ]
sdpython/machinelearningext
machinelearningext/ProductionPrediction/ValueMapperPredictionEngine.cs
6,273
C#
using Godo.Helper; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Godo { public class Kernel { // Section 0: Command Data public static byte[] RandomiseSection0(byte[] data, bool[] options, Random rnd, int seed) { /* Flags for commands like attack/magic. Not much to be changed here besides targeting parameters * and which menus open which sub-menus (for instance, Magic opens the magic sub-menu). * Would recommend leaving this data alone. * * 32 commands in all, IDs start from 0: * 0) 'Left' - Dummy/unknown * 1) Attack * 2) Magic * 3) Summon * 4) Item * 5) Steal * 6) Sense * 7) Coin * 8) Throw * 9) Morph * 10) Deathblow * 11) Manip. * 12) Mime * 13) E. Skill * 14) All: (the all modifier that attach to spells) * 15) 4x: (The quadra modifier) * 16) Unknown * 17) Mug * 18) Change Row * 19) Defend * 20) Limit * 21) W-Magic * 22) W-Summon * 23) W-Item * 24) Slash-All * 25) 2x-Cut * 26) Flash * 27) 4x-Cut * 28-31) Dummy * * The data available to modify (8 bytes each): * InitialCursor (1) * Targeting Flag (1) * Unknown (2) * CameraID Single (2) * CameraID Multi (2) */ int r = 0; int o = 0; try { while (r < 32) { // No Spells if (options[53] != false && r == 2) { data[o] = 255; o++; o += 7; } // No Summons else if (options[54] != false && r == 3) { data[o] = 255; o++; o += 7; } // No Items else if (options[55] != false && r == 4) { data[o] = 255; o++; o += 7; } else { o += 8; } r++; } } catch { MessageBox.Show("Kernel Section #0 (Command Data) has failed to randomise"); } return data; } // Section 1: Attack Data public static byte[] RandomiseSection1(byte[] data, bool[] options, Random rnd, int seed) { /* Player-available attacks. It should be noted that text strings are not stored with the * related data in 99% of cases, but instead at the back of the kernel in sections. * * There are 128 actions that can be edited; the tool appears to list 256 but the remaining 128 * do not exist and are actually stored in the .EXE (Limit Breaks). They have text pointers in * the kernel but nothing else. * * The data available to modify (28 bytes each): * Hit % (1) * Impact Effect (1) * Target Hurt Anim (1) * Unknown (1) * MP Cost (2) * Impact Sound (2) * Camera Single (2) * Camera Multi (2) * Target Flag (1) * Attack Anim ID (1) * Damage Calc (1) * Base Power (1) * Restore Type (1) * Status Toggle Type (1) * Additional Effects (1) * ^ Modifier (1) * Status Effects Mask (4) * Elements Mask (2) * Special Attack Flags (2) */ int r = 0; int o = 0; try { while (r < 96) { // Not proper attacks, used for effects & padding so skip if (r == 54 || r == 55) { o += 28; } else { if (options[8] != false) { // Attack % data[o] = (byte)rnd.Next(75, 125); o++; // Impact Effect data[o] = data[o]; o++; // Target Hurt Anim data[o] = data[o]; o++; // Unknown data[o] = data[o]; o++; // MP Cost if (options[50] != false) { data[o] = 0; o++; data[o] = 0; o++; } else { data[o] = (byte)rnd.Next(3, 100); o++; data[o] = 0; o++; } // Impact Sound data[o] = data[o]; o++; data[o] = data[o]; o++; // Camera Single data[o] = data[o]; o++; data[o] = data[o]; o++; // Camera Multiple data[o] = data[o]; o++; data[o] = data[o]; o++; // Target Flag data[o] = data[o]; o++; // Anim ID if (r < 54 && r != 25 && r != 26) { // Spells //data[o] = (byte)rnd.Next(54); o++; data[o] = (byte)SpellIndex.CheckValidSpellIndex(rnd); o++; } else if (r > 55 && r < 72 && r != 66) { // Summons //data[o] = (byte)rnd.Next(15); o++; data[o] = (byte)SpellIndex.CheckValidSummonIndex(rnd); o++; } else if (r < 96 && r > 71) { // E. Skills data[o] = (byte)rnd.Next(23); o++; } else { // Leave it be o++; } // Damage Calc data[o] = FormulaChange.PickDamageFormula(rnd); o++; // Base Power // First, check if the previous Damage Calc assigned with %-based damage if (data[o - 1] == 0x13 || data[o - 1] == 0x14 || data[o - 1] == 0x23 || data[o - 1] == 0x24 || data[o - 1] == 0x33 || data[o - 1] == 0x34 || data[o - 1] == 0x44 || data[o - 1] == 0x44 || data[o - 1] == 0x53 || data[o - 1] == 0x54 || data[o - 1] == 0xB3 || data[o - 1] == 0xB4) { // Max is 16/32 data[o] = (byte)rnd.Next(2, 8); o++; } else { // Assign a base power increase or reduction if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] * 0.75); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 15); o++; } else { o++; } } // Restore Type data[o] = data[o]; o++; // Status Toggle Type data[o] = data[o]; o++; // Additional Effects data[o] = data[o]; o++; // Modifier for Additional Effects data[o] = data[o]; o++; // Status Effect Mask data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Elements Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Special Attack Flags data[o] = data[o]; o++; data[o] = data[o]; o++; } else { o += 28; } } r++; } } catch { MessageBox.Show("Kernel Section #1 (Attack Data) has failed to randomise"); } return data; } // Section 2: Battle & Growth Data + Kernel Lookup Table public static byte[] RandomiseSection2(byte[] data, bool[] options, Random rnd, int seed, byte[] kernelLookup) { /* Contains the following: * 1) Stat Curve IDs, Join Level Modifier, Limit IDs, Limit Requirements, and Gauge-fill resistance (9 for each character) (59 * 9) * STR > Vit > MAG > SPR > DEX > LCK > HP > MP > EXP Level Up Curve (9) * Padding (1) * Level Modifier (1) * Padding (1) * Limit ID 1-1 > 4-3 (1 each, 12 total) (not a typo; there are 3 limit slots for each Limit Level) * Required Uses 1-2 > 3-3 (2 each, 12 total) * Gauge Resistance 1 > 4 (4 each, 16 total) * * 2) Curve Data * Random Bonus to Primary Stats (1 each, 12 total) * Random Bonus to HP (1 each, 12 total) * Random Bonus to MP (1 each, 12 total) * Curve Values (16 each, 64 total) * * 3) Character AI (2048) * * 4) Random Number Lookup Table (256) * * 5) Scene Lookup Table (64) * * 6) Spell Order (56) */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; int c = 0; try { while (r < 9) { // Stat Curve IDs if (options[0] != false) { data[o] = (byte)rnd.Next(0, 36); o++; // STR data[o] = (byte)rnd.Next(0, 36); o++; // VIT data[o] = (byte)rnd.Next(0, 36); o++; // MAG data[o] = (byte)rnd.Next(0, 36); o++; // SPR data[o] = (byte)rnd.Next(0, 36); o++; // DEX data[o] = (byte)rnd.Next(0, 36); o++; // LCK data[o] = (byte)rnd.Next(37, 45); o++; // HP data[o] = (byte)rnd.Next(46, 54); o++; // MP data[o] = (byte)rnd.Next(55, 63); o++; // EXP } else { o += 9; } data[o] = data[o]; o++; // Padding data[o] = data[o]; o++; // Joining Level Modifier data[o] = data[o]; o++; // Padding // These values should be 80h/128 and above - Characters can mostly use any Limit (albeit with skeleton flailing around) // Avoid using 95h/149 > 9Bh/155 as these are Tifa's limits and will crash if not used by her if (options[1] != false && r != 2 && r != 6 && r != 7) { int picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 1-1 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 1-2 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 1-3 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 2-1 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 2-2 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 2-3 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 3-1 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 3-2 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 3-3 picker = LimitIndex.CheckValidLimitIndex(rnd); data[o] = (byte)picker; o++; // Limit ID 4 o++; // 4-2, but cannot be unlocked o++; // 4-3, but cannot be unlocked } else { o += 12; } if (options[2] != false && r != 6 && r != 7) { data[o] = (byte)rnd.Next(50, 100); o++; // Kills for Limit Level 2 data[o] = data[o]; o++; data[o] = (byte)rnd.Next(120, 150); o++; // Kills for Limit Level 3 data[o] = data[o]; o++; data[o] = (byte)rnd.Next(2, 8); o++; // Required uses for 1-2 data[o] = data[o]; o++; if (options[1] != false) { data[o] = (byte)rnd.Next(9, 16); o++; // Required uses for 1-3 data[o] = data[o]; o++; } else { o += 2; } data[o] = (byte)rnd.Next(2, 8); o++; // Required uses for 2-2 data[o] = data[o]; o++; if (options[1] != false) { data[o] = (byte)rnd.Next(9, 16); o++; // Required uses for 2-3 data[o] = data[o]; o++; } else { o += 2; } data[o] = (byte)rnd.Next(2, 8); o++; // Required uses for 3-2 data[o] = data[o]; o++; if (options[1] != false) { data[o] = (byte)rnd.Next(9, 16); o++; // Required uses for 3-3 data[o] = data[o]; o++; } else { o += 2; } } else { o += 16; } if (options[52] != false) { // Limits will never fill data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; } else if (options[3] != false) { data[o] = (byte)rnd.Next(100, 255); o++; // Gauge Resistance for Limit Level 1 data[o] = (byte)rnd.Next(1); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = (byte)rnd.Next(100, 255); o++; // Gauge Resistance for Limit Level 2 data[o] = (byte)rnd.Next(1); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = (byte)rnd.Next(100, 255); o++; // Gauge Resistance for Limit Level 3 data[o] = (byte)rnd.Next(1); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = (byte)rnd.Next(100, 255); o++; // Gauge Resistance for Limit Level 4 data[o] = (byte)rnd.Next(1); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; } else { o += 16; } r++; } r = 0; if (options[4] != false) { // Random bonuses to primary stats (1 value per entry; default is 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3) data[o] = (byte)rnd.Next(0, 1); o++; data[o] = (byte)rnd.Next(0, 1); o++; data[o] = (byte)rnd.Next(0, 1); o++; data[o] = (byte)rnd.Next(0, 2); o++; data[o] = (byte)rnd.Next(0, 2); o++; data[o] = (byte)rnd.Next(0, 2); o++; data[o] = (byte)rnd.Next(0, 3); o++; data[o] = (byte)rnd.Next(0, 3); o++; data[o] = (byte)rnd.Next(0, 4); o++; data[o] = (byte)rnd.Next(0, 4); o++; data[o] = (byte)rnd.Next(0, 5); o++; data[o] = (byte)rnd.Next(0, 5); o++; // Random bonuses to HP - Range from 0 - 160 data[o] = (byte)rnd.Next(40, 50); o++; data[o] = (byte)rnd.Next(50, 60); o++; data[o] = (byte)rnd.Next(60, 70); o++; data[o] = (byte)rnd.Next(70, 80); o++; data[o] = (byte)rnd.Next(80, 90); o++; data[o] = (byte)rnd.Next(90, 100); o++; data[o] = (byte)rnd.Next(100, 110); o++; data[o] = (byte)rnd.Next(110, 120); o++; data[o] = (byte)rnd.Next(120, 130); o++; data[o] = (byte)rnd.Next(130, 140); o++; data[o] = (byte)rnd.Next(140, 150); o++; data[o] = (byte)rnd.Next(150, 160); o++; // Random bonuses to MP - Range from 0 to 60 data[o] = (byte)rnd.Next(10, 20); o++; data[o] = (byte)rnd.Next(10, 20); o++; data[o] = (byte)rnd.Next(10, 20); o++; data[o] = (byte)rnd.Next(20, 30); o++; data[o] = (byte)rnd.Next(20, 30); o++; data[o] = (byte)rnd.Next(20, 30); o++; data[o] = (byte)rnd.Next(30, 40); o++; data[o] = (byte)rnd.Next(30, 40); o++; data[o] = (byte)rnd.Next(40, 50); o++; data[o] = (byte)rnd.Next(40, 50); o++; data[o] = (byte)rnd.Next(50, 60); o++; data[o] = (byte)rnd.Next(50, 60); o++; } else { o += 36; } // Stat Curve values; 64 of them, 16 bytes each if (options[5] != false) { while (r < 64) { while (c < 16) { data[o] = (byte)rnd.Next(255); o++; c++; } r++; } } else { o += 1024; } r = 0; c = 0; // Character AI // My recommendation is to make multiple AI scripts (innate abilities or whatever) and have the tool read these scripts (byte files). // Then have the program read these byte files, put them in an array, and write to the data here. Make sure to read up on the // AI structure on Qhimm Wiki (link available on Qhimm Forum's front page) to get the header logic together. if (options[6] != false) { while (r < 2048) { data[o] = data[o]; o++; r++; } } else { o += 2048; } r = 0; // Random Lookup Table // For encounters to pop in a different order, randomise this. // But to be honest, the impact of randomising the random table will, ironically, be minimal. if (options[7] != false) { while (r < 256) { data[o] = (byte)rnd.Next(255); o++; r++; } } else { while (r < 256) { data[o] = data[o]; o++; r++; } } r = 0; c = 0; // Scene Lookup Table // This must be updated with the lookup table data built in the Scene randomisation section. // If it isn't, the game will look for scenes in the wrong places and you'll get wrong encounters/softlocks from empty formations while (r < 64) { data[o] = kernelLookup[c]; o++; c++; r++; } r = 0; c = 0; // Spell Order List while (r < 56) { data[o] = data[o]; o++; r++; } } catch { MessageBox.Show("Kernel Section #2 (Growth & Lookup Data) has failed to randomise"); } return data; } // Section 3: Character Record & Savemap Initialisation public static byte[] RandomiseSection3(byte[] data, bool[] options, Random rnd, int seed) { /* Kernel File Breakdown * The kernel.bin comprises multiple sections in a gzip-bin format. * This method focuses on the Initialisation section, which is copied to the game's savemap when starting a New Game */ try { #region Initialisation Data (kernel.3) struct int[] charRecord = new int[132]; // Character Data is 132bytes in length int[] miscRecord = new int[4]; // Handles 4 misc bytes between character record and item record int[] itemRecord = new int[640]; // Item Data int[] materiaRecord = new int[800]; // Materia Data int[] stolenRecord = new int[192]; // Stolen Materia Data int r = 0; // For counting characters int o = 0; // For counting bytes in the character record int c = 0; // For Weapon minimum value ID int k = 0; // For Weapon maximum value ID byte[] nameBytes; // For assigning FF7 Ascii bytes after method processing //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument #region Character Records (132bytes, 9 times) while (r < 9) // Iterates 9 times for each character; 0 = Cloud, 8 = Cid { // Character ID // Doesn't seem to affect anything, so disabled //if (options[14] != false) //{ // data[o] = (byte)rnd.Next(11); o++; //} //else //{ o++; //} // Character Stats if (options[15] != false) { // Level data[o] = (byte)rnd.Next(1, 15); o++; // Strength data[o] = (byte)rnd.Next(15, 50); o++; // Vitality data[o] = (byte)rnd.Next(15, 50); o++; // Magic data[o] = (byte)rnd.Next(15, 50); o++; // Spirit data[o] = (byte)rnd.Next(15, 50); o++; // Dexterity data[o] = (byte)rnd.Next(10, 40); o++; // Luck data[o] = (byte)rnd.Next(15, 50); o++; // Sources used - There are 6 values (1byte) for each Source type, redundant to change so skipped. // A case could be made that Source-boosted Dex behaves differently to natural Dex, so added that. o += 4; // Power to Spirit Sources, skipped and at 0 data[o] = (byte)rnd.Next(5, 10); o++; // Dex sources o++; // Luck Sources } else { o += 13; } /* Current Limit Lv - Skipped as this wouldn't serve much purpose. You can freely change Limit Level if the Limits are learned but having a Limit Level equipped with no Limits in it would likely cause a crash. */ //data[o] = (byte)rnd.Next(1, 5); data[o] = data[o]; o++; // Current Limit Gauge data[o] = data[o]; o++; // Character Name: Gets two random 4-letter words from the method NameGenerate for the character name // This is pointless as name is internal, and overridden when Character Naming screen is called if (options[16] != false) { nameBytes = Misc.NameGenerate(rnd); data[o] = nameBytes[0]; o++; data[o] = nameBytes[1]; o++; data[o] = nameBytes[2]; o++; data[o] = nameBytes[3]; o++; data[o] = nameBytes[4]; o++; data[o] = nameBytes[5]; o++; data[o] = nameBytes[6]; o++; data[o] = nameBytes[7]; o++; data[o] = 0; o++; // Empty - Note that names longer than 9 characters are stored but aren't retrieved properly by field script data[o] = 0; o++; // Empty - For instance, Ex-Soldier prints as 'Ex-Soldie' if his name is called by field script data[o] = 0; o++; // Empty data[o] = 255; o++; // Empty - Use FF to terminate the string } else { o += 12; } // Equipped Weapon ID /* Characters have a varying range for weapons, so this switch-case assigns the the range for the randomisation. Characters are capable of using each other's weapons without issue, but this helps eliminate late-game weapons from the mix. */ #region Switch-Case for Weapon Ranges if (options[17] != false) { switch (r) { //TODO: Sort out the valid ranges case 0: c = 0; // Cloud k = 14; break; case 1: c = 32; // Barret k = 46; break; case 2: c = 16; // Tifa k = 30; break; case 3: c = 62; // Aeristh k = 71; break; case 4: c = 48; // Red XIII k = 60; break; case 5: c = 87; // Yuffers k = 99; break; case 6: c = 0; // This is Young Cloud k = 14; break; case 7: c = 0; // This is Sephiroth k = 127; break; case 8: c = 73; // Cid k = 85; break; } data[o] = (byte)rnd.Next(c, k); o++; } else { o++; } #endregion // Equipped Armour ID if (options[18] != false) { data[o] = (byte)rnd.Next(31); o++; } else { o++; } // Equipped Accessory ID if (options[19] != false) { data[o] = (byte)rnd.Next(31); o++; } else { o++; } // Status Flag - 0 by default, valid ranges? Any point in checking? This'll be for Fury/Sadness. //data[o] = (byte)rnd.Next(1); o++; // Row Flag - No point changing this, default seems to be FF? Would have thought unchecked would = 0, and checked = 1 but guess not o++; // LvlProgressBar - No point changing this, it's purely visual. o++; // Learned Limit Skills - Bear in mind there are actually 3 Limits per level; 1-3, 2-3, 3-3, and 4-2/4-3 are unused // Oddly, a character can only learn 5-6 Limits and will stop learning any more after that even if conditions are met. // This was perhaps to prevent players learning the empty #-3 Limit by using the #-2 Limit 65535 times or something. data[o] = data[o]; o++; data[o] = data[o]; o++; // 2nd byte // Number of Kills data[o] = data[o]; o++; data[o] = data[o]; o++; // 2nd byte // Times Limit 1-1 used - If you hit the max value I think it unlocks 1-3 data[o] = data[o]; o++; data[o] = data[o]; o++; // 2nd byte // Times Limit 2-1 used - If you hit the max value I think it unlocks 2-3 data[o] = data[o]; o++; data[o] = data[o]; o++; // 2nd byte // Times Limit 3-1 used - If you hit the max value I think it unlocks 3-3 data[o] = data[o]; o++; data[o] = data[o]; o++; // 2nd byte // Current HP - 100 is game's functional minimum if (options[20] != false) { data[o] = (byte)rnd.Next(100, 209); o++; data[o] = (byte)rnd.Next(4); o++; } else { o += 2; } // Base HP - Character's 'real' HP - Setting this to same as Current HP data[o] = data[o - 2]; o++; // Sets it to the Current HP value data[o] = data[o - 2]; o++; // Current MP - Setting limit of 200 for balance - 10 is game's functional minimum. if (options[21] != false) { data[o] = (byte)rnd.Next(11, 201); o++; o++; // Returns 10MP minimum, 200 max. 2nd byte is left as zero as we don't exceed 999MP } else { o++; o++; } // Base MP - Starting MP on New Game - Setting this to same as Current MP data[o] = data[o - 2]; o++; o++; // Sets it to the Current MP value // Unknown, 4 bytes in length - Defaults are 0s o += 4; // Max HP - Set to //data[o] = data[o - 10]; o++; // Set to Current HP value //data[o] = data[o - 10]; o++; o += 2; // Max MP - Setting limit of 200 for balance //data[o] = data[o - 8]; o++; // Set to Current MP value //data[o] = data[o - 8]; o++; // Set to Current MP value o += 2; // Current EXP - Likely needs paired with Level to avoid oddities with the gauge data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; #region Equipment Materia Slots if (options[22] != false) { // Randomising all 8 slots completely could be absolute chaos, some rules may need to be applied here // Weapon Materia Slot #1 - Contains the ID + AP of the Materia, can be placed in an empty slot int picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; // ID of the Materia data[o] = (byte)rnd.Next(256); o++; // AP of the Materia, 3-byte data[o] = (byte)rnd.Next(11); o++; data[o] = (byte)rnd.Next(0); o++; // Weapon Materia Slot #2 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(11); o++; data[o] = (byte)rnd.Next(0); o++; // Weapon Materia Slot #3 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(11); o++; data[o] = (byte)rnd.Next(0); o++; // Weapon Materia Slot #4 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(11); o++; data[o] = (byte)rnd.Next(0); o++; // Weapon Materia Slot #5 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Weapon Materia Slot #6 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Weapon Materia Slot #7 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Weapon Materia Slot #8 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Armour Materia Slot #1 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; // ID of the Materia data[o] = (byte)rnd.Next(256); o++; // AP of the Materia, 3-byte data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(0); o++; // Armour Materia Slot #2 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(0); o++; // Armour Materia Slot #3 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(0); o++; // Armour Materia Slot #4 - Contains the ID + AP of the Materia, can be placed in an empty slot picker = MateriaIndex.CheckValidMateriaIndex(rnd); data[o] = (byte)picker; o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(256); o++; data[o] = (byte)rnd.Next(0); o++; // Armour Materia Slot #5 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Armour Materia Slot #6 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Armour Materia Slot #7 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; // Armour Materia Slot #8 - Contains the ID + AP of the Materia, can be placed in an empty slot data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; data[o] = 255; o++; } else { o += 64; } #endregion // EXP to Next Level - If not correct then only causes temporary visual glitch with the gauge. Will be very difficult to synch // as each character requires different amount of EXP, and the current EXP/Level will vary. May stick with default level. data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; //#region Write Offset for Character Record //// Randomised Character Record is now written into the kernel.3 bytestream //// Casts the int array into a byte array //array = data.Select(b => (byte)b).ToArray(); //switch (r) //{ // case 0: // bw.BaseStream.Position = 0x00000; // Sets the offset, using placeholders for now // bw.Write(array, 0, array.Length); // Overwrites the target with byte array // break; // case 1: // bw.BaseStream.Position = 0x00084; // Barret // bw.Write(array, 0, array.Length); // break; // case 2: // bw.BaseStream.Position = 0x00108; // Tifa // bw.Write(array, 0, array.Length); // break; // case 3: // bw.BaseStream.Position = 0x0018C; // Aeristh // bw.Write(array, 0, array.Length); // break; // case 4: // bw.BaseStream.Position = 0x00210; // Red XIII // bw.Write(array, 0, array.Length); // break; // case 5: // bw.BaseStream.Position = 0x00294; // Yuffie // bw.Write(array, 0, array.Length); // break; // case 6: // bw.BaseStream.Position = 0x00318; // Young Cloud // bw.Write(array, 0, array.Length); // break; // case 7: // bw.BaseStream.Position = 0x0039C; // Sephiroth // bw.Write(array, 0, array.Length); // break; // case 8: // bw.BaseStream.Position = 0x00420; // Cid // bw.Write(array, 0, array.Length); // break; //} //#endregion // Character Record has been written, byte-counter (o) is reset and character counter (r) is incremented //Array.Clear(data, 0, data.Length); //o = 0; r++; } #endregion #region Misc Bytes (4bytes) // Miscellaneous 4-bytes between character records and the item/materia arrays is handled here // Char ID Party Member Slot 1 - Party Leader should be Cloud, Tifa, or Cid // Pointless, as the game overrides it on start with an opcode but kept for future flevel modification //if (options[22] != false) //{ // int slotA = rnd.Next(3); // int slotB = rnd.Next(9); // int slotC = rnd.Next(9); // if (slotA == 1) // { // data[o] = 0; o++; // Cloud // } // else if (slotA == 2) // { // data[o] = 2; o++; // Tifa // } // else if (slotA == 3) // { // data[o] = 8; o++; // Cid // } // else // { // o++; // } // // Char ID Party Member Slot 2 // while (slotB == slotA) // Re-rolls until SlotB has a different ID to SlotA // { // slotB = rnd.Next(9); // } // data[o] = (byte)slotB; o++; // // Char ID Party Member Slot 3 - Unchanged as having unexpected party members can lock field scripts // while (slotC == slotA || slotC == slotB) // Re-rolls until SlotC has a different ID to SlotA and SlotB // { // slotC = rnd.Next(9); // } // data[o] = (byte)slotC; o++; //} //else //{ o += 3; //} // Padding of 1 byte, default value is FF data[o] = data[o]; o++; ////array = miscRecord.Select(b => (byte)b).ToArray(); ////bw.BaseStream.Position = 0x004A4; ////bw.Write(array, 0, array.Length); #endregion //#region Item, Materia, and Stolen Materia (1632 bytes) //// Starting Item stock - This array is massive, 2*320 bytes to handle Item ID + Quantity with no absolute position within inventory //// Best approach is likely to restrict it to 5-10 items or so, from within item range only (not equipment) //c = 640; // Adjust to fill empty space in item inventory to FF, 640 is entire item inventory is empty //while (c != 0) //{ // data[o] = 255; o++; // Unused values must be FF, unfortunately // c--; //} //// TODO: Add the BaseStream writer when adding items, for now it can be left as-is. //// Starting Materia stock - Even larger at 4*200 bytes, same deal as items //c = 800; // Adjust to fill empty space in Materia inventory to FF, 800 is entire Materia inventory is empty //while (c != 0) //{ // materiaRecord[o] = 255; o++; // Unused values must be FF, unfortunately // c--; //} //// TODO: Will probably not update this part of kernel.3, but may go for this instead of equipping Materia by default //// If that happens, remember to add a BaseStream to write the array to the file //// Stolen Materia stock - 4*48 for 192 bytes. Unlikely to be changed but added for completeness //c = 192; // Adjust to fill empty space in Materia inventory to FF, 192 sets entire Stolen Materia to blank //while (c != 0) //{ // // There is a mysterious set of values in this array by default; Materia at offset 0xB28(F0 00 00 00) // // F0 isn't a valid Materia ID, as valid index IDs go up to around 95 decimal or so. Avoid editing these 4 values. // stolenRecord[o] = 255; o++; // Unused values must be FF, unfortunately // c--; //} //// TODO: Unlikely that this array will be edited, but add a BaseStream to update this part of kernel if you do. //#endregion //MessageBox.Show("Finished Randomising"); #endregion } catch { MessageBox.Show("Kernel Section #3 (Initial Data) has failed to randomise"); } return data; } public static byte[] RandomiseSection4(byte[] data, bool[] options, Random rnd, int seed) { /* Item Data * * The data available to modify (28 bytes each): * 8x FF Mask (8) * Camera Move ID (2) * Restriction Mask (2) - 01 can be sold, 02 can be used in battle, 04 can be used in menu * Target Flags (1) * Attack Effect ID (1) * Damage Calc. (1) * Base Power (1) * Conditions (1) - 00 party HP, 01 party MP, 02 party status, other: none * Status Chance (1) - 3F chance to inflict (/63), 40 Cure, 80 Toggle * Attack Additional Effects (1) * Additional Effects Modifier (1) * Status Effects (4) * Attack Element (2) * Special Attack Flags (2) */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; try { if (options[9] != false) { while (r < 105) { // FF Mask data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Camera Move ID data[o] = data[o]; o++; data[o] = data[o]; o++; // Use Restriction Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Target Flags data[o] = data[o]; o++; // Attack Effect ID data[o] = (byte)rnd.Next(69); o++; // Damage Calc data[o] = FormulaChange.PickDamageFormula(rnd); o++; // Base Power if (data[o - 1] == 0x13 || data[o - 1] == 0x14 || data[o - 1] == 0x23 || data[o - 1] == 0x24 || data[o - 1] == 0x33 || data[o - 1] == 0x34 || data[o - 1] == 0x44 || data[o - 1] == 0x44 || data[o - 1] == 0x53 || data[o - 1] == 0x54 || data[o - 1] == 0xB3 || data[o - 1] == 0xB4) { // Max is 16/32 data[o] = (byte)rnd.Next(4, 8); o++; } else { // Assign a base power increase or reduction if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] / 2); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.5); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 25); o++; } else { o++; } } // Conditions data[o] = data[o]; o++; // Status Chance data[o] = data[o]; o++; // Additional Effects data[o] = data[o]; o++; // Additional Effects Modifier data[o] = data[o]; o++; // Status Effects data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Attack Element data[o] = data[o]; o++; data[o] = data[o]; o++; // Special Attack Flags data[o] = data[o]; o++; data[o] = data[o]; o++; r++; } } if (options[55] != false) { r = 0; o = 0; while (r < 105) { o += 10; data[o] = 254; o++; data[o] = 255; o++; o += 16; r++; } } else { o += 3584; } } catch { MessageBox.Show("Kernel Section #4 (Item Data) has failed to randomise"); } return data; } public static byte[] RandomiseSection5(byte[] data, bool[] options, Random rnd, int seed) { /* Weapon Data * * The data available to modify (44 bytes each): * Target Flags (1) * Always FF (1) * Damage Calc. (1) * Always FF (1) * Base Power (1) * Status Attack (1) * Growth Rate (1) * Crit% (1) * Acc% (1) * Model ID (1) - Upper nybble = attack animation modifier (barret/vince only), lower nybble: model ID * Always FF (1) * Sound ID Mask (1) * Camera ID (2) - Always FFFF * Equip Mask (2) 1, 2, 4, 8, 10, 20, 40, 80, 100, 200, 400 = Cloud > Sephiroth * Attack Element (2) * Always FFFF (2) * Stat Type (4) FF None, 00 STR > 05 LCK * Stat Boost (4) * Slots (8) 00 > 07 none > right-linked growth * Sound ID Hit (1) * Sound ID Crit (1) * Sound ID Miss (1) * Impact ID (1) * Special Flags (2) * Restrict Mask (2) 01 can sell, 02 can throw, 04 can Menu */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; try { if (options[10] != false) { while (r < 128) { // Target Flags data[o] = data[o]; o++; // Always FF data[o] = data[o]; o++; // Damage Calc data[o] = FormulaChange.PickWeaponFormula(rnd); o++; // Always FF data[o] = data[o]; o++; // Base Power // Assign a base power increase or reduction int seeder = rnd.Next(4); if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] * 0.75); o++; } else if (seeder == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (seeder == 2) { data[o] = (byte)(data[o] + 25); o++; } else if (seeder == 3 && data[o] > 25) { data[o] = (byte)(data[o] - 25); o++; } else { o++; } // Status Attack data[o] = Misc.PickEquipmentStatus(rnd); o++; // Growth Rate data[o] = (byte)rnd.Next(4); o++; // Crit% data[o] = (byte)rnd.Next(5, 25); o++; // Acc% data[o] = (byte)rnd.Next(50, 125); o++; // Model ID - Barret, Vincent data[o] = data[o]; o++; // Always FF data[o] = data[o]; o++; // Sound ID data[o] = data[o]; o++; // Camera ID - Always FF data[o] = data[o]; o++; data[o] = data[o]; o++; // Equip Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Attack Element data[o] = data[o]; o++; data[o] = data[o]; o++; // Always FF data[o] = data[o]; o++; data[o] = data[o]; o++; // Stat Boost Type data[o] = (byte)rnd.Next(1, 5); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Stat Boost Value data[o] = (byte)rnd.Next(10, 40); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Slots if (data[o - 22] != 0) { int empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } } else { int empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 1); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } } // Sound ID Hit data[o] = data[o]; o++; // Sound ID Crit data[o] = data[o]; o++; // Sound ID Miss data[o] = data[o]; o++; // Impact ID data[o] = data[o]; o++; // Special Flags data[o] = data[o]; o++; data[o] = data[o]; o++; // Restrict Mask data[o] = data[o]; o++; data[o] = data[o]; o++; r++; } } if (options[51] != false) { r = 0; o = 0; while (r < 128) { o += 2; data[o] = 0; o++; o += 41; r++; } } if (options[60] != false) { r = 0; o = 0; while (r < 128) { o += 14; data[o] = 0; o++; data[o] = 0; o++; o += 28; r++; } } } catch { MessageBox.Show("Kernel Section #5 (Weapon Data) has failed to randomise"); } return data; } public static byte[] RandomiseSection6(byte[] data, bool[] options, Random rnd, int seed) { /* Armour Data * * The data available to modify (44 bytes each): * Unknown (1) * Damage Type (1) - FF norm, 00 absorb, 01 null, 02 halve * Defence (1) * MDef (1) * Defence% (1) * MDef% (1) * Status Def (1) * Unknown (2) * Slots (8) - 00 > 07 none > right-linked growth * Growth (1) * Equip Mask (2) - 1, 2, 4, 8, 10, 20, 40, 80, 100, 200, 400 = Cloud > Sephiroth * Elem Def (2) * Always FF (2) * Stat Type (4) * Stat Boost (4) * Restrict Mask (2) * Always FF (2) */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; try { if (options[11] != false) { while (r < 32) { // Unknown data[o] = data[o]; o++; // Damage Type - FF Normal, 00 Absorb, 01 Null, 02 Halve data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 3) { data[o - 1] = 255; } // Defence if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] / 2); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 25); o++; } else { o++; } // MDefence if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] / 2); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 25); o++; } else { o++; } // Defence% if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] / 2); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 10); o++; } else { o++; } // MDef% if (rnd.Next(3) == 0) { data[o] = (byte)(data[o] / 2); o++; } else if (rnd.Next(3) == 1) { data[o] = (byte)(data[o] * 1.25); o++; } else if (rnd.Next(3) == 2) { data[o] = (byte)(data[o] + 10); o++; } else { o++; } // Status Defence data[o] = Misc.PickEquipmentStatus(rnd); o++; // Unknown data[o] = data[o]; o++; data[o] = data[o]; o++; // Slots int growth = rnd.Next(4); if (growth != 0) { int empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(5, 7); o++; if (data[o - 1] == 6) { data[o] = 7; o++; } else { data[o] = 5; o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } } else { int empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } empty = rnd.Next(2); if (empty == 1) { data[o] = (byte)rnd.Next(0, 1); o++; if (data[o - 1] == 2) { data[o] = 3; o++; } else { data[o] = (byte)rnd.Next(0, 2); o++; } } else { data[o] = 0; o++; data[o] = 0; o++; } } // Growth data[o] = (byte)growth; o++; // Equip Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Elem Defence int picker = rnd.Next(2); int[] element = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 }; if (picker == 0) { picker = rnd.Next(0, 7); data[o] = (byte)element[picker]; o++; data[o] = 0; o++; } else if (picker == 1) { picker = rnd.Next(0, 7); data[o] = 0; o++; data[o] = (byte)element[picker]; o++; } else { o += 2; } // Always FF data[o] = data[o]; o++; data[o] = data[o]; o++; // Stat Boost Type data[o] = (byte)rnd.Next(5); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Stat Boost Value data[o] = (byte)rnd.Next(10, 40); o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; // Restrict Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Always FF data[o] = data[o]; o++; data[o] = data[o]; o++; r++; } } } catch { MessageBox.Show("Kernel Section #6 (Armour Data) has failed to randomise"); } return data; } public static byte[] RandomiseSection7(byte[] data, bool[] options, Random rnd, int seed) { /* Accessory Data * * The data available to modify (44 bytes each): * Stat Type (2) * Stat Boost (2) * Elem Strength (1) - 00 absorb, 01 null, 02 halve * Special Effect (1) - 00 > 06 auto-haste > auto-wall * Elemental Mask (2) * Status Mask (4) * Equip Mask (2) * Restrict Mask (2) */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; try { if (options[12] != false) { while (r < 32) { // Stat Boost Type data[o] = (byte)rnd.Next(5); o++; data[o] = data[o]; o++; // Stat Boost Value data[o] = (byte)rnd.Next(10, 40); o++; data[o] = data[o]; o++; // Elem Strength data[o] = (byte)rnd.Next(0, 3); o++; if (data[o - 1] == 3) { data[o - 1] = 255; } // Special Effect data[o] = data[o]; o++; // Elem Mask int picker = rnd.Next(2); int[] element = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 }; if (picker == 0) { picker = rnd.Next(0, 7); data[o] = (byte)element[picker]; o++; data[o] = 0; o++; } else if (picker == 1) { picker = rnd.Next(0, 7); data[o] = 0; o++; data[o] = (byte)element[picker]; o++; } else { o += 2; } // Status Mask picker = rnd.Next(4); int[] status = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 }; if (picker == 0) { picker = rnd.Next(0, 7); data[o] = (byte)status[picker]; o++; data[o] = 0; o++; data[o] = 0; o++; data[o] = 0; o++; } else if (picker == 1) { picker = rnd.Next(0, 7); // Prevents Regen being set data[o] = 0; o++; data[o] = (byte)status[picker]; o++; data[o] = 0; o++; data[o] = 0; o++; } else if (picker == 2) { picker = rnd.Next(0, 7); // Prevents Barrier being set data[o] = 0; o++; data[o] = 0; o++; data[o] = (byte)status[picker]; o++; data[o] = 0; o++; } else { picker = rnd.Next(0, 7); // Prevents Peerless being set if (picker == 8 && data[o - 1] != 8) // Checks for Dual-Drain, sets Dual on previous byte { data[o - 1] = 8; } data[o] = 0; o++; data[o] = 0; o++; data[o] = 0; o++; data[o] = (byte)status[picker]; o++; } // Equip Mask data[o] = data[o]; o++; data[o] = data[o]; o++; // Restrict Mask data[o] = data[o]; o++; data[o] = data[o]; o++; r++; } } } catch { MessageBox.Show("Kernel Section #7 (Accessory Data) has failed to randomise"); } return data; } public static byte[] RandomiseSection8(byte[] data, bool[] options, Random rnd, int seed) { /* Materia Data * * The data available to modify (44 bytes each): * Level Up (8) - Multiples of 100 (4x WORD) * Equip Effect ID (1) * Status Effects (3) - Only 24 statuses * Element Index (1) * Materia Type (1) * Attributes (6) */ //Random rnd = new Random(Guid.NewGuid().GetHashCode()); // TODO: Have it take a seed as argument int r = 0; int o = 0; int c = 0; try { // Nulls all Materia for No Materia option if (options[56] != false) { while (r < 91) { while (c < 21) { data[o] = 255; o++; c++; } r++; c = 0; } r = 0; o = 0; } else if (options[13] != false) { while (r < 91) { // AP if (data[o] != 255) { data[o] = (byte)rnd.Next(1, 100); o++; o++; } else { o += 2; } if (data[o] != 255) { data[o] = (byte)rnd.Next(101, 250); o++; o++; } else { o += 2; } if (data[o] != 255) { data[o] = (byte)rnd.Next(250); o++; data[o] = (byte)rnd.Next(1, 3); o++; } else { o += 2; } if (data[o] != 255) { data[o] = (byte)rnd.Next(250); o++; data[o] = (byte)rnd.Next(4, 6); o++; } else { o += 2; } // Equip Effect ID data[o] = (byte)rnd.Next(16); o++; // Status Effects int picker = rnd.Next(3); int[] status = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 }; if (picker == 0) { picker = rnd.Next(0, 7); data[o] = (byte)status[picker]; o++; data[o] = 0; o++; data[o] = 0; o++; } else if (picker == 1) { picker = rnd.Next(0, 7); // Prevents Regen being set data[o] = 0; o++; data[o] = (byte)status[picker]; o++; data[o] = 0; o++; } else { picker = rnd.Next(0, 7); // Prevents Peerless being set data[o] = 0; o++; data[o] = 0; o++; data[o] = (byte)status[picker]; o++; } // Element Index data[o] = (byte)rnd.Next(16); o++; // Materia Type data[o] = data[o]; o++; // Attributes data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; data[o] = data[o]; o++; r++; } } o = 0; } catch { MessageBox.Show("Kernel Section #8 (Materia Data) has failed to randomise"); } return data; } } }
40.849132
152
0.293067
[ "Apache-2.0" ]
Segachief/Godo
Godo/Kernel.cs
91,790
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Extended Controls")] [assembly: AssemblyDescription("An extention to the Krypton toolkit suite for .NET framework 4.7 (https://github.com/Wagnerp/Krypton-NET-5.480).")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Extended Controls")] [assembly: AssemblyCopyright("Copyright © Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2018 - 2020 et al. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1c9153e4-cdc4-44c9-9794-1d144fe87a1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.480.1393.0")] [assembly: AssemblyFileVersion("5.480.1393.0")] [assembly: NeutralResourcesLanguage("en-GB")] [assembly: Dependency("System", LoadHint.Always)] [assembly: Dependency("System.Xml", LoadHint.Always)] [assembly: Dependency("System.Drawing", LoadHint.Always)] [assembly: Dependency("System.Windows.Forms", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)]
44.2
147
0.757164
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.480
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/Properties/AssemblyInfo.cs
1,992
C#
using Microsoft.AspNetCore.WebHooks.Metadata; namespace TwitchLib.Webhook.Metadata { public class TwitchMetadata : WebHookMetadata, IWebHookBodyTypeMetadataService, IWebHookGetHeadRequestMetadata { public TwitchMetadata() : base(TwitchConstants.ReceiverName) { } public WebHookBodyType BodyType => WebHookBodyType.Json; public bool AllowHeadRequests => false; public string ChallengeQueryParameterName => TwitchConstants.ChallengeQueryParameterName; public int SecretKeyMinLength => 8; public int SecretKeyMaxLength => 128; } }
27.565217
97
0.700315
[ "MIT" ]
LXGaming/TwitchLib.Webhook
src/TwitchLib.Webhook/Metadata/TwitchMetadata.cs
636
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reflection; using Avalonia.Collections; using Avalonia.Media; namespace Avalonia.Controls.Shapes { public abstract class Shape : Control { public static readonly StyledProperty<IBrush> FillProperty = AvaloniaProperty.Register<Shape, IBrush>(nameof(Fill)); public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register<Shape, Stretch>(nameof(Stretch)); public static readonly StyledProperty<IBrush> StrokeProperty = AvaloniaProperty.Register<Shape, IBrush>(nameof(Stroke)); public static readonly StyledProperty<AvaloniaList<double>> StrokeDashArrayProperty = AvaloniaProperty.Register<Shape, AvaloniaList<double>>(nameof(StrokeDashArray)); public static readonly StyledProperty<double> StrokeDashOffsetProperty = AvaloniaProperty.Register<Shape, double>(nameof(StrokeDashOffset)); public static readonly StyledProperty<double> StrokeThicknessProperty = AvaloniaProperty.Register<Shape, double>(nameof(StrokeThickness)); public static readonly StyledProperty<PenLineCap> StrokeLineCapProperty = AvaloniaProperty.Register<Shape, PenLineCap>(nameof(StrokeLineCap), PenLineCap.Flat); public static readonly StyledProperty<PenLineJoin> StrokeJoinProperty = AvaloniaProperty.Register<Shape, PenLineJoin>(nameof(StrokeJoin), PenLineJoin.Miter); private Matrix _transform = Matrix.Identity; private Geometry _definingGeometry; private Geometry _renderedGeometry; bool _calculateTransformOnArrange = false; static Shape() { AffectsMeasure<Shape>(StretchProperty, StrokeThicknessProperty); AffectsRender<Shape>(FillProperty, StrokeProperty, StrokeDashArrayProperty, StrokeDashOffsetProperty, StrokeThicknessProperty, StrokeLineCapProperty, StrokeJoinProperty); } public Geometry DefiningGeometry { get { if (_definingGeometry == null) { _definingGeometry = CreateDefiningGeometry(); } return _definingGeometry; } } public IBrush Fill { get { return GetValue(FillProperty); } set { SetValue(FillProperty, value); } } public Geometry RenderedGeometry { get { if (_renderedGeometry == null && DefiningGeometry != null) { if (_transform == Matrix.Identity) { _renderedGeometry = DefiningGeometry; } else { _renderedGeometry = DefiningGeometry.Clone(); if (_renderedGeometry.Transform == null || _renderedGeometry.Transform.Value == Matrix.Identity) { _renderedGeometry.Transform = new MatrixTransform(_transform); } else { _renderedGeometry.Transform = new MatrixTransform( _renderedGeometry.Transform.Value * _transform); } } } return _renderedGeometry; } } public Stretch Stretch { get { return GetValue(StretchProperty); } set { SetValue(StretchProperty, value); } } public IBrush Stroke { get { return GetValue(StrokeProperty); } set { SetValue(StrokeProperty, value); } } public AvaloniaList<double> StrokeDashArray { get { return GetValue(StrokeDashArrayProperty); } set { SetValue(StrokeDashArrayProperty, value); } } public double StrokeDashOffset { get { return GetValue(StrokeDashOffsetProperty); } set { SetValue(StrokeDashOffsetProperty, value); } } public double StrokeThickness { get { return GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } public PenLineCap StrokeLineCap { get { return GetValue(StrokeLineCapProperty); } set { SetValue(StrokeLineCapProperty, value); } } public PenLineJoin StrokeJoin { get { return GetValue(StrokeJoinProperty); } set { SetValue(StrokeJoinProperty, value); } } public override void Render(DrawingContext context) { var geometry = RenderedGeometry; if (geometry != null) { var pen = new Pen(Stroke, StrokeThickness, new DashStyle(StrokeDashArray, StrokeDashOffset), StrokeLineCap, StrokeJoin); context.DrawGeometry(Fill, pen, geometry); } } /// <summary> /// Marks a property as affecting the shape's geometry. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateGeometry"/> to be called on the element. /// </remarks> protected static void AffectsGeometry<TShape>(params AvaloniaProperty[] properties) where TShape : Shape { foreach (var property in properties) { property.Changed.Subscribe(e => { var senderType = e.Sender.GetType().GetTypeInfo(); var affectedType = typeof(TShape).GetTypeInfo(); if (affectedType.IsAssignableFrom(senderType)) { AffectsGeometryInvalidate(e); } }); } } protected abstract Geometry CreateDefiningGeometry(); protected void InvalidateGeometry() { _renderedGeometry = null; _definingGeometry = null; InvalidateMeasure(); } protected override Size MeasureOverride(Size availableSize) { bool deferCalculateTransform; switch (Stretch) { case Stretch.Fill: case Stretch.UniformToFill: deferCalculateTransform = double.IsInfinity(availableSize.Width) || double.IsInfinity(availableSize.Height); break; case Stretch.Uniform: deferCalculateTransform = double.IsInfinity(availableSize.Width) && double.IsInfinity(availableSize.Height); break; case Stretch.None: default: deferCalculateTransform = false; break; } if (deferCalculateTransform) { _calculateTransformOnArrange = true; return DefiningGeometry?.Bounds.Size ?? Size.Empty; } else { _calculateTransformOnArrange = false; return CalculateShapeSizeAndSetTransform(availableSize); } } protected override Size ArrangeOverride(Size finalSize) { if (_calculateTransformOnArrange) { _calculateTransformOnArrange = false; CalculateShapeSizeAndSetTransform(finalSize); } return finalSize; } private Size CalculateShapeSizeAndSetTransform(Size availableSize) { if (DefiningGeometry != null) { // This should probably use GetRenderBounds(strokeThickness) but then the calculations // will multiply the stroke thickness as well, which isn't correct. var (size, transform) = CalculateSizeAndTransform(availableSize, DefiningGeometry.Bounds, Stretch); if (_transform != transform) { _transform = transform; _renderedGeometry = null; } return size; } return Size.Empty; } internal static (Size, Matrix) CalculateSizeAndTransform(Size availableSize, Rect shapeBounds, Stretch Stretch) { Size shapeSize = new Size(shapeBounds.Right, shapeBounds.Bottom); Matrix translate = Matrix.Identity; double desiredX = availableSize.Width; double desiredY = availableSize.Height; double sx = 0.0; double sy = 0.0; if (Stretch != Stretch.None) { shapeSize = shapeBounds.Size; translate = Matrix.CreateTranslation(-(Vector)shapeBounds.Position); } if (double.IsInfinity(availableSize.Width)) { desiredX = shapeSize.Width; } if (double.IsInfinity(availableSize.Height)) { desiredY = shapeSize.Height; } if (shapeBounds.Width > 0) { sx = desiredX / shapeSize.Width; } if (shapeBounds.Height > 0) { sy = desiredY / shapeSize.Height; } if (double.IsInfinity(availableSize.Width)) { sx = sy; } if (double.IsInfinity(availableSize.Height)) { sy = sx; } switch (Stretch) { case Stretch.Uniform: sx = sy = Math.Min(sx, sy); break; case Stretch.UniformToFill: sx = sy = Math.Max(sx, sy); break; case Stretch.Fill: if (double.IsInfinity(availableSize.Width)) { sx = 1.0; } if (double.IsInfinity(availableSize.Height)) { sy = 1.0; } break; default: sx = sy = 1; break; } var transform = translate * Matrix.CreateScale(sx, sy); var size = new Size(shapeSize.Width * sx, shapeSize.Height * sy); return (size, transform); } private static void AffectsGeometryInvalidate(AvaloniaPropertyChangedEventArgs e) { if (!(e.Sender is Shape control)) { return; } // If the geometry is invalidated when Bounds changes, only invalidate when the Size // portion changes. if (e.Property == BoundsProperty) { var oldBounds = (Rect)e.OldValue; var newBounds = (Rect)e.NewValue; if (oldBounds.Size == newBounds.Size) { return; } } control.InvalidateGeometry(); } } }
33.395415
128
0.530759
[ "MIT" ]
HendrikMennen/Avalonia
src/Avalonia.Controls/Shapes/Shape.cs
11,655
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { using System.Text.RegularExpressions; public class MarkdownEscapedTextInlineRule : IMarkdownRule { public string Name => "Inline.EscapedText"; public virtual Regex EscapedText => Regexes.Inline.EscapedText; public virtual IMarkdownToken TryMatch(IMarkdownParser parser, ref string source) { var match = EscapedText.Match(source); if (match.Length == 0) { return null; } source = source.Substring(match.Length); return new MarkdownTextToken(this, parser.Context, StringHelper.Escape(match.Groups[1].Value), match.Value); } } }
32.296296
120
0.65711
[ "MIT" ]
ghuntley/docfx
src/Microsoft.DocAsCode.MarkdownLite/Basic/InlineRules/MarkdownEscapedTextInlineRule.cs
874
C#
using BlueCloud.Extensions.Data; namespace BlueCloud.Extensions.Tests.Model { public class Artist { [DbField("ArtistId")] public long ArtistId { get; set; } [DbField("Name")] public string Name { get; set; } } }
18.5
42
0.598456
[ "MIT" ]
zenkimoto/bluecloud.extensions
BlueCloud.Extensions.Tests/Model/Artist.cs
261
C#
using System; public class CostumeHair { public string hair = string.Empty; public string hair_1 = string.Empty; public static CostumeHair[] hairsF; public static CostumeHair[] hairsM; public bool hasCloth; public int id; public string texture = string.Empty; public static void init() { hairsM = new CostumeHair[11]; hairsM[0] = new CostumeHair(); hairsM[0].hair = hairsM[0].texture = "hair_boy1"; hairsM[1] = new CostumeHair(); hairsM[1].hair = hairsM[1].texture = "hair_boy2"; hairsM[2] = new CostumeHair(); hairsM[2].hair = hairsM[2].texture = "hair_boy3"; hairsM[3] = new CostumeHair(); hairsM[3].hair = hairsM[3].texture = "hair_boy4"; hairsM[4] = new CostumeHair(); hairsM[4].hair = hairsM[4].texture = "hair_eren"; hairsM[5] = new CostumeHair(); hairsM[5].hair = hairsM[5].texture = "hair_armin"; hairsM[6] = new CostumeHair(); hairsM[6].hair = hairsM[6].texture = "hair_jean"; hairsM[7] = new CostumeHair(); hairsM[7].hair = hairsM[7].texture = "hair_levi"; hairsM[8] = new CostumeHair(); hairsM[8].hair = hairsM[8].texture = "hair_marco"; hairsM[9] = new CostumeHair(); hairsM[9].hair = hairsM[9].texture = "hair_mike"; hairsM[10] = new CostumeHair(); hairsM[10].hair = hairsM[10].texture = string.Empty; for (int i = 0; i <= 10; i++) { hairsM[i].id = i; } hairsF = new CostumeHair[11]; hairsF[0] = new CostumeHair(); hairsF[0].hair = hairsF[0].texture = "hair_girl1"; hairsF[1] = new CostumeHair(); hairsF[1].hair = hairsF[1].texture = "hair_girl2"; hairsF[2] = new CostumeHair(); hairsF[2].hair = hairsF[2].texture = "hair_girl3"; hairsF[3] = new CostumeHair(); hairsF[3].hair = hairsF[3].texture = "hair_girl4"; hairsF[4] = new CostumeHair(); hairsF[4].hair = hairsF[4].texture = "hair_girl5"; hairsF[4].hasCloth = true; hairsF[4].hair_1 = "hair_girl5_cloth"; hairsF[5] = new CostumeHair(); hairsF[5].hair = hairsF[5].texture = "hair_annie"; hairsF[6] = new CostumeHair(); hairsF[6].hair = hairsF[6].texture = "hair_hanji"; hairsF[6].hasCloth = true; hairsF[6].hair_1 = "hair_hanji_cloth"; hairsF[7] = new CostumeHair(); hairsF[7].hair = hairsF[7].texture = "hair_mikasa"; hairsF[8] = new CostumeHair(); hairsF[8].hair = hairsF[8].texture = "hair_petra"; hairsF[9] = new CostumeHair(); hairsF[9].hair = hairsF[9].texture = "hair_rico"; hairsF[10] = new CostumeHair(); hairsF[10].hair = hairsF[10].texture = "hair_sasha"; hairsF[10].hasCloth = true; hairsF[10].hair_1 = "hair_sasha_cloth"; for (int j = 0; j <= 10; j++) { hairsF[j].id = j; } } }
38.320513
60
0.565741
[ "Apache-2.0" ]
ITALIA195/AoTTG-Mod
CostumeHair.cs
2,989
C#
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Management.MediaServices.Models; using Microsoft.WindowsAzure.Management.Storage.Models; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Commands.Utilities.MediaServices { /// <summary> /// Defines interface to communicate with Azure Media Services REST API /// </summary> public interface IMediaServicesClient { /// <summary> /// Gets the media service accounts async. /// </summary> /// <returns></returns> Task<MediaServicesAccountListResponse> GetMediaServiceAccountsAsync(); /// <summary> /// Gets the media service account details async. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> Task<MediaServicesAccountGetResponse> GetMediaServiceAsync(string name); /// <summary> /// Create new azure media service async. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> Task<MediaServicesAccountCreateResponse> CreateNewAzureMediaServiceAsync(MediaServicesAccountCreateParameters request); /// <summary> /// Deletes azure media service account async. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> Task<OperationResponse> DeleteAzureMediaServiceAccountAsync(string name); /// <summary> /// Regenerates azure media service account key async. /// </summary> /// <param name="name">The name.</param> /// <param name="keyType">Key Type</param> /// <returns></returns> Task<OperationResponse> RegenerateMediaServicesAccountAsync(string name, MediaServicesKeyType keyType); /// <summary> /// Gets the storage service keys. /// </summary> /// <param name="storageAccountName">Name of the storage account.</param> /// <returns></returns> Task<StorageAccountGetKeysResponse> GetStorageServiceKeysAsync(string storageAccountName); /// <summary> /// Gets the storage service properties. /// </summary> /// <param name="storageAccountName">Name of the storage account.</param> /// <returns></returns> Task<StorageAccountGetResponse> GetStorageServicePropertiesAsync(string storageAccountName); } }
43.905405
128
0.610957
[ "MIT" ]
stankovski/azure-sdk-tools
src/ServiceManagement/Services/Commands.Utilities/MediaServices/IMediaServicesClient.cs
3,178
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core) // Version 5.500.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.ComponentModel; using System.ComponentModel.Design; namespace Krypton.Toolkit { internal class KryptonCheckButtonActionList : KryptonButtonActionList { #region Instance Fields private readonly KryptonCheckButton _checkButton; private readonly IComponentChangeService _service; private string _action; #endregion #region Identity /// <summary> /// Initialize a new instance of the KryptonCheckButtonActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonCheckButtonActionList(KryptonCheckButtonDesigner owner) : base(owner) { // Remember the button instance _checkButton = owner.Component as KryptonCheckButton; // Assuming we were correctly passed an actual component... if (_checkButton != null) { // Get access to the actual Orientation property PropertyDescriptor checkedProp = TypeDescriptor.GetProperties(_checkButton)["Checked"]; // If we succeeded in getting the property if (checkedProp != null) { // Decide on the next action to take given the current setting _action = (bool) checkedProp.GetValue(_checkButton) ? "Uncheck the button" : "Check the button"; } } // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); } #endregion #region Public /// <summary> /// Gets and sets the checked state. /// </summary> public bool Checked { get => _checkButton.Checked; set { if (_checkButton.Checked != value) { _service.OnComponentChanged(_checkButton, null, _checkButton.Checked, value); _checkButton.Checked = value; } } } #endregion #region Public Override /// <summary> /// Returns the collection of DesignerActionItem objects contained in the list. /// </summary> /// <returns>A DesignerActionItem array that contains the items in this list.</returns> public override DesignerActionItemCollection GetSortedActionItems() { // Create a new collection for holding the single item we want to create DesignerActionItemCollection actions = new DesignerActionItemCollection(); // This can be null when deleting a control instance at design time if (_checkButton != null) { // Add the list of button specific actions actions.Add(new DesignerActionHeaderItem("Appearance")); actions.Add(new KryptonDesignerActionItem(new DesignerVerb(_action, OnCheckedClick), "Appearance")); actions.Add(new DesignerActionPropertyItem("ButtonStyle", "Style", "Appearance", "Button style")); actions.Add(new DesignerActionPropertyItem("Orientation", "Orientation", "Appearance", "Button orientation")); actions.Add(new DesignerActionHeaderItem("Values")); actions.Add(new DesignerActionPropertyItem("Text", "Text", "Values", "Button text")); actions.Add(new DesignerActionPropertyItem("ExtraText", "ExtraText", "Values", "Button extra text")); actions.Add(new DesignerActionPropertyItem("Image", "Image", "Values", "Button image")); actions.Add(new DesignerActionHeaderItem("Visuals")); actions.Add(new DesignerActionPropertyItem("PaletteMode", "Palette", "Visuals", "Palette applied to drawing")); } return actions; } #endregion #region Implementation private void OnCheckedClick(object sender, EventArgs e) { // Cast to the correct type // Double check the source is the expected type if (sender is DesignerVerb verb) { // Decide on the new orientation required bool isChecked = verb.Text.Equals("Uncheck the button"); // Decide on the next action to take given the new setting _action = isChecked ? "Uncheck the button" : "Check the button"; // Get access to the actual Orientation property PropertyDescriptor checkedProp = TypeDescriptor.GetProperties(_checkButton)["Checked"]; // If we succeeded in getting the property // Update the actual property with the new value checkedProp?.SetValue(_checkButton, !isChecked); // Get the user interface service associated with actions // If we managed to get it then request it update to reflect new action setting if (GetService(typeof(DesignerActionUIService)) is DesignerActionUIService service) { service.Refresh(_checkButton); } } } #endregion } }
44.34058
170
0.597483
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-NET-Core
Source/Truncated Namespaces/Source/Krypton Components/Krypton.Toolkit/Designers/KryptonCheckButtonActionList.cs
6,122
C#
namespace ZimLabs.TableCreator { /// <summary> /// The different supported table types /// </summary> public enum OutputType { /// <summary> /// The default table type /// </summary> Default, /// <summary> /// The table as markdown /// </summary> Markdown, /// <summary> /// The table as a comma separated value list /// </summary> Csv } }
19.625
53
0.475584
[ "MIT" ]
InvaderZim85/ZimLabs.TableCreator
ZimLabs.TableCreator/OutputType.cs
473
C#
using System.Threading.Tasks; using ChameleonForms.Tests.FieldGenerator; using NUnit.Framework; namespace ChameleonForms.Tests.ModelBinders.FlagsEnumModelBinderTests { [TestFixture(TypeArgs = new[]{typeof(TestFlagsEnum)})] [TestFixture(TypeArgs = new[]{typeof(TestFlagsEnum?)})] class FlagsEnumModelBinderShould<T> : ModelBinderTestBase<TestViewModel<T>> { [Test] public async Task Use_default_value_when_there_is_empty_value([Values("", null)] string value) { var (state, model) = await BindAndValidateAsync(m => m.FlagEnum, value); Assert.That(model, Is.EqualTo(default(T))); Assert.That(state.IsValid, Is.EqualTo(typeof(T) == typeof(TestFlagsEnum?))); if (typeof(T) == typeof(TestFlagsEnum)) AssertPropertyError(state, m => m.FlagEnum, "The FlagEnum field is required."); } [Test] public async Task Register_error_when_there_is_empty_value_on_field_with_required_attribute([Values("", null)] string value) { var (state, model) = await BindAndValidateAsync(m => m.RequiredFlagEnum, value); Assert.That(model, Is.EqualTo(default(T))); Assert.That(state.IsValid, Is.False); AssertPropertyError(state, m => m.RequiredFlagEnum, "The RequiredFlagEnum field is required."); } [Test] public async Task Register_error_when_there_is_empty_value_on_implicitly_required_field([Values("", null)] string value) { var (state, model) = await BindAndValidateAsync(m => m.ImplicitlyRequiredFlagEnum, value); Assert.That(model, Is.EqualTo(default(TestFlagsEnum))); Assert.That(state.IsValid, Is.False); AssertPropertyError(state, m => m.ImplicitlyRequiredFlagEnum, "The ImplicitlyRequiredFlagEnum field is required."); } [Test] public async Task Use_default_value_when_there_is_no_value() { var (state, model) = await BindAndValidateAsync(m => m.FlagEnum); Assert.That(model, Is.EqualTo(default(T))); Assert.That(state.IsValid, Is.EqualTo(typeof(T) == typeof(TestFlagsEnum?))); if (typeof(T) == typeof(TestFlagsEnum)) AssertPropertyError(state, m => m.FlagEnum, "The FlagEnum field is required."); } [Test] public async Task Use_default_value_and_add_error_when_there_is_an_invalid_value() { var (state, model) = await BindAndValidateAsync(m => m.FlagEnum, "invalid"); Assert.That(model, Is.EqualTo(default(T))); Assert.That(state.IsValid, Is.False); AssertPropertyError(state, m => m.FlagEnum, "The value 'invalid' is not valid for FlagEnum."); } [Test] public async Task Return_and_bind_valid_value_if_there_us_an_ok_single_value() { var (state, model) = await BindAndValidateAsync(m => m.FlagEnum, TestFlagsEnum.Simplevalue.ToString()); Assert.That(model, Is.EqualTo(TestFlagsEnum.Simplevalue)); Assert.That(state.IsValid, Is.True); } [Test] public async Task Return_and_bind_valid_value_if_there_is_an_ok_multiple_value() { var (state, model) = await BindAndValidateAsync(m => m.FlagEnum, TestFlagsEnum.Simplevalue.ToString(), TestFlagsEnum.ValueWithDescriptionAttribute.ToString()); Assert.That(model, Is.EqualTo(TestFlagsEnum.Simplevalue | TestFlagsEnum.ValueWithDescriptionAttribute)); Assert.That(state.IsValid, Is.True); } } }
45.317073
172
0.639935
[ "MIT" ]
MRCollective/ChameleonForms
ChameleonForms.Tests/ModelBinders/FlagsEnumModelBinderTests/FlagsEnumModelBinderShould.cs
3,718
C#
using System.Collections.Generic; namespace Client.Event { public struct MaxCombo : IEventHandle { public int Level { get; } public MaxCombo(int level) { Level = level; } } }
16.642857
41
0.55794
[ "MIT" ]
Noname-Studio/ET
Unity/Assets/Scripts/Client/Event/MaxCombo.cs
235
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CCHCMS.Repositories { public class DrugRepository { } }
14.909091
33
0.737805
[ "MIT" ]
imdrashedul/CCHCMS
CCHCMS/Repositories/DrugRepository.cs
166
C#
using FluentAssertions; using FunctionalTests.Base; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using System; using System.Net; using System.Threading.Tasks; using Xunit; namespace FunctionalTests.HealthChecks.MySql { [Collection("execution")] public class mysql_healthcheck_should { private readonly ExecutionFixture _fixture; public mysql_healthcheck_should(ExecutionFixture fixture) { _fixture = fixture ?? throw new ArgumentException(nameof(fixture)); } [Fact] public async Task be_healthy_when_mysql_server_is_available() { var connectionString = "server=localhost;port=3306;database=information_schema;uid=root;password=Password12!"; var webHostBuilder = new WebHostBuilder() .UseStartup<DefaultStartup>() .ConfigureServices(services => { services.AddHealthChecks() .AddMySql(connectionString, tags: new string[] { "mysql" }); }) .Configure(app => { app.UseHealthChecks("/health", new HealthCheckOptions() { Predicate = r => r.Tags.Contains("mysql") }); }); var server = new TestServer(webHostBuilder); var response = await server.CreateRequest("/health") .GetAsync(); response.StatusCode.Should() .Be(HttpStatusCode.OK); } [Fact] public async Task be_unhealthy_when_mysql_server_is_unavailable() { var connectionString = "server=255.255.255.255;port=3306;database=information_schema;uid=root;password=Password12!"; var webHostBuilder = new WebHostBuilder() .UseStartup<DefaultStartup>() .ConfigureServices(services => { services.AddHealthChecks() .AddMySql(connectionString, tags: new string[] { "mysql" }); }) .Configure(app => { app.UseHealthChecks("/health", new HealthCheckOptions() { Predicate = r => r.Tags.Contains("mysql") }); }); var server = new TestServer(webHostBuilder); var response = await server.CreateRequest("/health") .GetAsync(); response.StatusCode.Should() .Be(HttpStatusCode.ServiceUnavailable); } } }
34.059524
129
0.551555
[ "Apache-2.0" ]
697765/AspNetCore.Diagnostics.HealthChecks
test/FunctionalTests/HealthChecks.MySql/MySqlHealthCheckTests.cs
2,863
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devops-guru-2020-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DevOpsGuru.Model { /// <summary> /// Container for the parameters to the AddNotificationChannel operation. /// Adds a notification channel to DevOps Guru. A notification channel is used to notify /// you about important DevOps Guru events, such as when an insight is generated. /// /// /// <para> /// If you use an Amazon SNS topic in another account, you must attach a policy to it /// that grants DevOps Guru permission to it notifications. DevOps Guru adds the required /// policy on your behalf to send notifications using Amazon SNS in your account. For /// more information, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-required-permissions.html">Permissions /// for cross account Amazon SNS topics</a>. /// </para> /// /// <para> /// If you use an Amazon SNS topic that is encrypted by an AWS Key Management Service /// customer-managed key (CMK), then you must add permissions to the CMK. For more information, /// see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-kms-permissions.html">Permissions /// for AWS KMS–encrypted Amazon SNS topics</a>. /// </para> /// </summary> public partial class AddNotificationChannelRequest : AmazonDevOpsGuruRequest { private NotificationChannelConfig _config; /// <summary> /// Gets and sets the property Config. /// <para> /// A <code>NotificationChannelConfig</code> object that specifies what type of notification /// channel to add. The one supported notification channel is Amazon Simple Notification /// Service (Amazon SNS). /// </para> /// </summary> [AWSProperty(Required=true)] public NotificationChannelConfig Config { get { return this._config; } set { this._config = value; } } // Check to see if Config property is set internal bool IsSetConfig() { return this._config != null; } } }
39.153846
139
0.657171
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DevOpsGuru/Generated/Model/AddNotificationChannelRequest.cs
3,056
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MediationFocus : MonoBehaviour { GameObject GameController; public float SuffleFrequency = 30.0f; public float BallDistance = 0.4f; public GameObject BallGlowing; public GameObject BallNormal; GameObject LocationObject; float mediatationStartTime; float sessionTimer; float suffleTimer = 0.0f; float randomRotation; int chosenLocation; GameObject glowBall; GameObject ballToMove; public List <GameObject> focusBallsList; void Awake (){ GameController = GameObject.Find ("GameController"); LocationObject = GameObject.Find ("SphereSpawnPoint"); } // Use this for initialization void Start () { GameController.GetComponent <GameController> ().MeditationTestType = "Focused Attention"; float x = LocationObject.transform.position.x; float y = LocationObject.transform.position.y; float z = LocationObject.transform.position.z; //create normal balls for (int i=0; i<5; i++) { x += BallDistance; GameObject ballToInstantiate = (GameObject)Instantiate (BallNormal); ballToInstantiate.name = "SphereNormal " + i; ballToInstantiate.transform.parent = LocationObject.transform; ballToInstantiate.transform.position = new Vector3 (x, y, z); randomRotation = UnityEngine.Random.Range (0, 180); ballToInstantiate.transform.Rotate(0,randomRotation,0,Space.World); focusBallsList.Insert(0, ballToInstantiate); } // and glowing ball at the top of one of these. chosenLocation = UnityEngine.Random.Range (0, 4); ballToMove = focusBallsList [chosenLocation]; glowBall= (GameObject)Instantiate (BallGlowing); glowBall.transform.parent = LocationObject.transform; glowBall.transform.position = new Vector3 (ballToMove.transform.position.x, ballToMove.transform.position.y, ballToMove.transform.position.z); ballToMove.transform.position += new Vector3(0,-5000,0); } void FixedUpdate () { // Ball suffling suffleTimer += Time.deltaTime; if ((suffleTimer > SuffleFrequency) && (GameController.GetComponent <GameController> ().GameStarted == true)) { ballToMove.transform.position += new Vector3(0,5000,0); suffleTimer = 0.0f; int chosenLocation = UnityEngine.Random.Range (0, 4); ballToMove = focusBallsList [chosenLocation]; glowBall.transform.position = new Vector3 (ballToMove.transform.position.x, ballToMove.transform.position.y, ballToMove.transform.position.z); ballToMove.transform.position += new Vector3(0,-5000,0); } } }
31.073171
146
0.748823
[ "Apache-2.0" ]
petrutsi/mindtiervr
Assets/Scripts/RelaWorld/MediationFocus.cs
2,550
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// AlipayMarketingCampaignDiscountBudgetQueryModel Data Structure. /// </summary> [Serializable] public class AlipayMarketingCampaignDiscountBudgetQueryModel : AopObject { /// <summary> /// 预算名称 /// </summary> [XmlElement("budget_id")] public string BudgetId { get; set; } } }
23.421053
76
0.640449
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/AlipayMarketingCampaignDiscountBudgetQueryModel.cs
453
C#
// <copyright file="AggregatedEventGeneratorCommonUt.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> using System.Collections.Generic; using System.Linq; using Microsoft.Azure.IoT.Agent.Core.EventGeneration; using Microsoft.Azure.IoT.Agent.Core.Tests.UnitTests; using Microsoft.Azure.IoT.Contracts.Events; using Microsoft.Azure.IoT.Contracts.Events.Payloads; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Security.Tests.Common.UnitTests { /// <summary> /// Base class for testing the functionallity of Aggregated event generaotr /// </summary> [TestClass] public abstract class AggregatedEventGeneratorCommonUt<TPayload> : UnitTestBase where TPayload : Payload { /// <summary> /// Create a new instance of the generator to test /// </summary> /// <param name="mockedEventGenerator">mocked event generator to be used as event supplier</param> /// <returns></returns> protected abstract AggregatedEventsGenerator<TPayload> CreateInstance(EventGenerator mockedEventGenerator); /// <summary> /// Mocked event1 /// </summary> protected abstract EventBase<TPayload> E1 { get; } /// <summary> /// Mocked event2 /// </summary> protected abstract EventBase<TPayload> E2 { get; } /// <summary> /// Change event generator priority /// </summary> /// <param name="priority">priority to set</param> protected abstract void SetEventPriority(EventPriority priority); /// <summary> /// Enable aggregation /// </summary> /// <param name="toggle"></param> protected abstract void ToggleAggregation(bool toggle); /// <summary> /// Set aggregation interval /// </summary> /// <param name="ISO8601Interval">interval to set in ISO8601 format</param> protected abstract void SetAggregationIntervalTime(string ISO8601Interval); /// <summary> /// Compare between two aggregated payloads /// </summary> /// <param name="p1">payload1</param> /// <param name="p2">payload2</param> /// <returns>true if p1 equals to p2</returns> protected abstract bool ComparePayloads(TPayload p1, TPayload p2); private Mock<EventGenerator> _mockedEventGenerator; private AggregatedEventsGenerator<TPayload> _generatorUnderTest; /// <summary> /// Test init /// </summary> [TestInitialize] public override void Init() { base.Init(); SetEventPriority(EventPriority.Low); _mockedEventGenerator = new Mock<EventGenerator>(); _generatorUnderTest = CreateInstance(_mockedEventGenerator.Object); } /// <summary> /// Test event generator with aggregation disabled, validated no aggregation /// </summary> [TestMethod] public void TestNoAggregatoin() { ToggleAggregation(false); _mockedEventGenerator .Setup(x => x.GetEvents()) .Returns(new List<IEvent> { E1, E2, E1 }); var events = _generatorUnderTest.GetEvents(); Assert.AreEqual(3, events.Count()); Assert.AreEqual(2, events.Count(x => x == (IEvent) E1)); Assert.AreEqual(1, events.Count(x => x == (IEvent) E2)); } /// <summary> /// Test event generator with aggregation enabled, validated events are aggregated /// </summary> [TestMethod] public void TestAggregatoin() { ToggleAggregation(true); SetAggregationIntervalTime("PT12H"); _mockedEventGenerator .Setup(x => x.GetEvents()) .Returns(new List<IEvent> { E1, E2, E1 }); var events = _generatorUnderTest.GetEvents(); Assert.AreEqual(0, events.Count()); SetAggregationIntervalTime("PT0S"); events = _generatorUnderTest.GetEvents(); Assert.AreEqual(2, events.Count()); Assert.IsTrue(events.All(x => x is AggregatedEvent<TPayload>)); var aggregatedEvents = events.Cast<AggregatedEvent<TPayload>>(); Assert.IsTrue(aggregatedEvents.Any(e => ComparePayloads(e.Payload.First(), E1.Payload.First()))); Assert.IsTrue(aggregatedEvents.Any(e => ComparePayloads(e.Payload.First(), E2.Payload.First()))); var e1Payload = aggregatedEvents.First(e => ComparePayloads(e.Payload.First(), E1.Payload.First())).Payload; Assert.AreEqual("4", e1Payload.First().ExtraDetails["HitCount"]); var e2Payload = aggregatedEvents.First(e => ComparePayloads(e.Payload.First(), E2.Payload.First())).Payload; Assert.AreEqual("2", e2Payload.First().ExtraDetails["HitCount"]); } /// <summary> /// Validates the event generator produces events when enable aggregation is off /// and then produces aggregated events when aggregation is on /// </summary> [TestMethod] public void TestAggregatoinTogglingOffToOn() { ToggleAggregation(false); _mockedEventGenerator .Setup(x => x.GetEvents()) .Returns(new List<IEvent> { E1, E2, E1 }); var events = _generatorUnderTest.GetEvents(); Assert.AreEqual(3, events.Count()); ToggleAggregation(true); SetAggregationIntervalTime("PT0S"); events = _generatorUnderTest.GetEvents(); Assert.AreEqual(2, events.Count()); Assert.IsTrue(events.All(x => x is AggregatedEvent<TPayload>r)); } /// <summary> /// Validates events are aggregated when agrregation is set to on /// and then events are not aggregated when aggregation is off /// Validate the event generator emits the aggregated event when toggling agrregation to off /// </summary> [TestMethod] public void TestAggregatoinTogglingOnToOff() { ToggleAggregation(true); SetAggregationIntervalTime("PT1H"); _mockedEventGenerator .Setup(x => x.GetEvents()) .Returns(new List<IEvent> { E1, E2, E1 }); var events = _generatorUnderTest.GetEvents(); Assert.AreEqual(0, events.Count()); ToggleAggregation(false); events = _generatorUnderTest.GetEvents(); Assert.AreEqual(5, events.Count()); Assert.AreEqual(2, events.Count(x => x is AggregatedEvent<TPayload>)); } } }
37.988827
120
0.6075
[ "MIT" ]
Azure/Azure-IoT-Security-Agent-CS
src/Modules/Security/Tests/Common/UnitTests/AggregatedEventGeneratorCommonUT.cs
6,802
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Gicco.Module.Core.Extensions; using Gicco.Module.Reviews.Data; using Gicco.Module.Reviews.Models; using Gicco.Module.Reviews.ViewModels; using System.Linq; using System.Threading.Tasks; namespace Gicco.Module.Reviews.Controllers { [Area("Reviews")] public class ReviewController : Controller { private const int DefaultPageSize = 25; private readonly IReviewRepository _reviewRepository; private readonly IWorkContext _workContext; public ReviewController(IReviewRepository reviewRepository, IWorkContext workContext) { _reviewRepository = reviewRepository; _workContext = workContext; } [HttpPost] public async Task<IActionResult> AddReview(ReviewForm model) { if (ModelState.IsValid) { var user = await _workContext.GetCurrentUser(); var review = new Review { Rating = model.Rating, Title = model.Title, Comment = model.Comment, ReviewerName = model.ReviewerName, EntityId = model.EntityId, EntityTypeId = model.EntityTypeId, UserId = user.Id, }; _reviewRepository.Add(review); _reviewRepository.SaveChanges(); return PartialView("_ReviewFormSuccess", model); } return PartialView("_ReviewForm", model); } public async Task<IActionResult> List(long entityId, string entityTypeId, int? pageNumber, int? pageSize) { var entity = _reviewRepository .List() .FirstOrDefault(); if (entity == null) { return Redirect("~/Error/FindNotFound"); } var itemsPerPage = pageSize.HasValue ? pageSize.Value : DefaultPageSize; var currentPageNum = pageNumber.HasValue ? pageNumber.Value : 1; var offset = (itemsPerPage * currentPageNum) - itemsPerPage; var model = new ReviewVm(); model.EntityName = entity.EntityName; model.EntitySlug = entity.EntitySlug; var query = _reviewRepository .Query() .Where(x => (x.EntityId == entityId) && (x.EntityTypeId == entityTypeId) && (x.Status == ReviewStatus.Approved)) .OrderByDescending(x => x.CreatedOn) .Select(x => new ReviewItem { Id = x.Id, Title = x.Title, Rating = x.Rating, Comment = x.Comment, ReviewerName = x.ReviewerName, CreatedOn = x.CreatedOn, Replies = x.Replies .Where(r => r.Status == ReplyStatus.Approved) .OrderByDescending(r => r.CreatedOn) .Select(r => new ViewModels.Reply { Comment = r.Comment, ReplierName = r.ReplierName, CreatedOn = r.CreatedOn }) .ToList() }); model.Items.Data = await query .Skip(offset) .Take(itemsPerPage) .ToListAsync(); model.Items.PageNumber = currentPageNum; model.Items.PageSize = itemsPerPage; model.Items.TotalItems = await query.CountAsync(); var allItems = await query.ToListAsync(); model.ReviewsCount = allItems.Count; model.Rating1Count = allItems.Count(x => x.Rating == 1); model.Rating2Count = allItems.Count(x => x.Rating == 2); model.Rating3Count = allItems.Count(x => x.Rating == 3); model.Rating4Count = allItems.Count(x => x.Rating == 4); model.Rating5Count = allItems.Count(x => x.Rating == 5); model.EntityId = entityId; model.EntityTypeId = entityTypeId; return View(model); } } }
35.625
128
0.529825
[ "Apache-2.0" ]
dvbtham/gicco
src/Modules/Gicco.Module.Reviews/Areas/Reviews/Controllers/ReviewController.cs
4,277
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-jobs-data-2017-09-29.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.IoTJobsDataPlane.Model; using Amazon.IoTJobsDataPlane.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.IoTJobsDataPlane { /// <summary> /// Implementation for accessing IoTJobsDataPlane /// /// AWS IoT Jobs is a service that allows you to define a set of jobs — remote operations /// that are sent to and executed on one or more devices connected to AWS IoT. For example, /// you can define a job that instructs a set of devices to download and install application /// or firmware updates, reboot, rotate certificates, or perform remote troubleshooting /// operations. /// /// /// <para> /// To create a job, you make a job document which is a description of the remote operations /// to be performed, and you specify a list of targets that should perform the operations. /// The targets can be individual things, thing groups or both. /// </para> /// /// <para> /// AWS IoT Jobs sends a message to inform the targets that a job is available. The target /// starts the execution of the job by downloading the job document, performing the operations /// it specifies, and reporting its progress to AWS IoT. The Jobs service provides commands /// to track the progress of a job on a specific target and for all the targets of the /// job /// </para> /// </summary> public partial class AmazonIoTJobsDataPlaneClient : AmazonServiceClient, IAmazonIoTJobsDataPlane { #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region DescribeJobExecution internal virtual DescribeJobExecutionResponse DescribeJobExecution(DescribeJobExecutionRequest request) { var marshaller = new DescribeJobExecutionRequestMarshaller(); var unmarshaller = DescribeJobExecutionResponseUnmarshaller.Instance; return Invoke<DescribeJobExecutionRequest,DescribeJobExecutionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeJobExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeJobExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iot-jobs-data-2017-09-29/DescribeJobExecution">REST API Reference for DescribeJobExecution Operation</seealso> public virtual Task<DescribeJobExecutionResponse> DescribeJobExecutionAsync(DescribeJobExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeJobExecutionRequestMarshaller(); var unmarshaller = DescribeJobExecutionResponseUnmarshaller.Instance; return InvokeAsync<DescribeJobExecutionRequest,DescribeJobExecutionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetPendingJobExecutions internal virtual GetPendingJobExecutionsResponse GetPendingJobExecutions(GetPendingJobExecutionsRequest request) { var marshaller = new GetPendingJobExecutionsRequestMarshaller(); var unmarshaller = GetPendingJobExecutionsResponseUnmarshaller.Instance; return Invoke<GetPendingJobExecutionsRequest,GetPendingJobExecutionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetPendingJobExecutions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPendingJobExecutions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iot-jobs-data-2017-09-29/GetPendingJobExecutions">REST API Reference for GetPendingJobExecutions Operation</seealso> public virtual Task<GetPendingJobExecutionsResponse> GetPendingJobExecutionsAsync(GetPendingJobExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetPendingJobExecutionsRequestMarshaller(); var unmarshaller = GetPendingJobExecutionsResponseUnmarshaller.Instance; return InvokeAsync<GetPendingJobExecutionsRequest,GetPendingJobExecutionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartNextPendingJobExecution internal virtual StartNextPendingJobExecutionResponse StartNextPendingJobExecution(StartNextPendingJobExecutionRequest request) { var marshaller = new StartNextPendingJobExecutionRequestMarshaller(); var unmarshaller = StartNextPendingJobExecutionResponseUnmarshaller.Instance; return Invoke<StartNextPendingJobExecutionRequest,StartNextPendingJobExecutionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartNextPendingJobExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartNextPendingJobExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iot-jobs-data-2017-09-29/StartNextPendingJobExecution">REST API Reference for StartNextPendingJobExecution Operation</seealso> public virtual Task<StartNextPendingJobExecutionResponse> StartNextPendingJobExecutionAsync(StartNextPendingJobExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StartNextPendingJobExecutionRequestMarshaller(); var unmarshaller = StartNextPendingJobExecutionResponseUnmarshaller.Instance; return InvokeAsync<StartNextPendingJobExecutionRequest,StartNextPendingJobExecutionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateJobExecution internal virtual UpdateJobExecutionResponse UpdateJobExecution(UpdateJobExecutionRequest request) { var marshaller = new UpdateJobExecutionRequestMarshaller(); var unmarshaller = UpdateJobExecutionResponseUnmarshaller.Instance; return Invoke<UpdateJobExecutionRequest,UpdateJobExecutionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateJobExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateJobExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iot-jobs-data-2017-09-29/UpdateJobExecution">REST API Reference for UpdateJobExecution Operation</seealso> public virtual Task<UpdateJobExecutionResponse> UpdateJobExecutionAsync(UpdateJobExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateJobExecutionRequestMarshaller(); var unmarshaller = UpdateJobExecutionResponseUnmarshaller.Instance; return InvokeAsync<UpdateJobExecutionRequest,UpdateJobExecutionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
46.356164
227
0.708629
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/IoTJobsDataPlane/Generated/_mobile/AmazonIoTJobsDataPlaneClient.cs
10,154
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using StarkPlatform.Compiler.Host; using StarkPlatform.Compiler.Serialization; using StarkPlatform.Compiler.Shared.Utilities; using Roslyn.Utilities; namespace StarkPlatform.Compiler.FindSymbols { internal sealed partial class SyntaxTreeIndex : IObjectWritable { private const string PersistenceName = "<SyntaxTreeIndex>"; private const string SerializationFormat = "15"; public readonly Checksum Checksum; private void WriteFormatAndChecksum(ObjectWriter writer, string formatVersion) { writer.WriteString(formatVersion); Checksum.WriteTo(writer); } private static bool TryReadFormatAndChecksum( ObjectReader reader, string formatVersion, out Checksum checksum) { checksum = null; if (reader.ReadString() != formatVersion) { return false; } checksum = Checksum.ReadFrom(reader); return true; } private static async Task<SyntaxTreeIndex> LoadAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>(); try { // attempt to load from persisted state using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false)) using (var stream = await storage.ReadStreamAsync(document, PersistenceName, cancellationToken).ConfigureAwait(false)) using (var reader = ObjectReader.TryGetReader(stream)) { if (reader != null) { if (FormatAndChecksumMatches(reader, SerializationFormat, checksum)) { return ReadFrom(GetStringTable(document.Project), reader, checksum); } } } } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return null; } private static bool FormatAndChecksumMatches( ObjectReader reader, string formatVersion, Checksum checksum) { return TryReadFormatAndChecksum(reader, formatVersion, out var persistChecksum) && persistChecksum == checksum; } public static async Task<Checksum> GetChecksumAsync( Document document, CancellationToken cancellationToken) { // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change // any time the SyntaxTree could have changed. Right now, that can only happen if the // text of the document changes, or the ParseOptions change. So we get the checksums // for both of those, and merge them together to make the final checksum. var projectChecksumState = await document.Project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var parseOptionsChecksum = projectChecksumState.ParseOptions; var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = documentChecksumState.Text; return Checksum.Create(WellKnownSynchronizationKind.SyntaxTreeIndex, new[] { textChecksum, parseOptionsChecksum }); } private async Task<bool> SaveAsync( Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>(); try { using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false)) using (var stream = SerializableBytes.CreateWritableStream()) using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken)) { this.WriteFormatAndChecksum(writer, SerializationFormat); this.WriteTo(writer); stream.Position = 0; return await storage.WriteStreamAsync(document, PersistenceName, stream, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } private static async Task<bool> PrecalculatedAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>(); // check whether we already have info for this document try { using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false)) using (var stream = await storage.ReadStreamAsync(document, PersistenceName, cancellationToken).ConfigureAwait(false)) using (var reader = ObjectReader.TryGetReader(stream)) { if (reader != null) { return FormatAndChecksumMatches(reader, SerializationFormat, checksum); } } } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { _literalInfo.WriteTo(writer); _identifierInfo.WriteTo(writer); _contextInfo.WriteTo(writer); _declarationInfo.WriteTo(writer); } private static SyntaxTreeIndex ReadFrom( StringTable stringTable, ObjectReader reader, Checksum checksum) { var literalInfo = LiteralInfo.TryReadFrom(reader); var identifierInfo = IdentifierInfo.TryReadFrom(reader); var contextInfo = ContextInfo.TryReadFrom(reader); var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader); if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null) { return null; } return new SyntaxTreeIndex( checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value); } } }
42.287356
161
0.6215
[ "BSD-2-Clause", "MIT" ]
encrypt0r/stark
src/compiler/StarkPlatform.Compiler.Workspaces/FindSymbols/SyntaxTree/SyntaxTreeIndex_Persistence.cs
7,360
C#
using Newtonsoft.Json; using System; using System.Globalization; namespace RedFolder.ActivityTracker.Models { public class WeekActivity { private Week _week; public WeekActivity() { _week = new Week(); } public WeekActivity(int year, int weekNumber) { _week = Week.FromYearAndWeekNumber(year, weekNumber); } [JsonProperty("year")] public int Year { get => _week.Year; set => _week.Year = value; } [JsonProperty("weekNumber")] public int WeekNumber { get => _week.WeekNumber; set => _week.WeekNumber = value; } [JsonProperty("start")] public DateTime Start { get => _week.Start; set => _week.Start = value; } [JsonProperty("end")] public DateTime End { get => _week.End; set => _week.End = value; } [JsonProperty("podCasts")] public PodCastActivity PodCasts { get; set; } [JsonProperty("skills")] public SkillsActivity Skills { get; set; } [JsonProperty("focus")] public FocusActivity Focus { get; set; } [JsonProperty("pluralsight")] public PluralsightActivity Pluralsight { get; set; } [JsonProperty("clients")] public ClientActivity Clients { get; set; } [JsonProperty("blogs")] public BlogActivity Blogs { get; set; } [JsonProperty("events")] public EventActivity Events { get; set; } [JsonProperty("books")] public BookActivity Books { get; set; } public void AddPodCast(PodCast podCast) { if (PodCasts == null) PodCasts = new PodCastActivity(); PodCasts.Add(podCast); } public void AddBook(Book book) { if (Books == null) Books = new BookActivity(); Books.Add(book); } public void AddEvent(Event newEvent) { if (Events == null) Events = new EventActivity(); Events.Add(newEvent); } } }
23.168421
67
0.527942
[ "MIT" ]
Red-Folder/activity-tracker-azure-function
RedFolder.ActivityTracker/Models/WeekActivity.cs
2,203
C#
using log4net; using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using Vulnerator.Helper; using Vulnerator.Model.Object; namespace Vulnerator.Model.DataAccess { public class DatabaseInterface { DdlReader _ddlReader = new DdlReader(); Assembly assembly = Assembly.GetExecutingAssembly(); private string _storedProcedureBase = "Vulnerator.Resources.DdlFiles.StoredProcedures."; public void CreateVulnerabilityRelatedIndices() { try { if (!DatabaseBuilder.sqliteConnection.State.ToString().Equals("Open")) { DatabaseBuilder.sqliteConnection.Open(); } using (SQLiteCommand sqliteCommand = DatabaseBuilder.sqliteConnection.CreateCommand()) { sqliteCommand.CommandText = "PRAGMA user_version"; int latestVersion = int.Parse(sqliteCommand.ExecuteScalar().ToString()); for (int i = 0; i <= latestVersion; i++) { switch (i) { case 0: { sqliteCommand.CommandText = _ddlReader.ReadDdl("Vulnerator.Resources.DdlFiles.v6-2-0_CreateVulnerabilityRelatedIndices.ddl", assembly); break; } default: { break; } } if (sqliteCommand.CommandText.Equals(string.Empty)) { return; } sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = string.Empty; } } } catch (Exception exception) { LogWriter.LogError("Unable to create vulnerability related indices."); throw exception; } finally { DatabaseBuilder.sqliteConnection.Close(); } } public void DeleteVulnerabilityToCciMapping(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.VulnerabilityCCI_Mapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete the Vulnerability / CCI mapping for UniqueFinding ID '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}' and CCI '{sqliteCommand.Parameters["CCI"].Value}'."); throw exception; } } public void DeleteRemovedVulnerabilities(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilitiesForDeletion.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (!sqliteDataReader.HasRows) { return; } using (SQLiteCommand deleteVulnsCommand = DatabaseBuilder.sqliteConnection.CreateCommand()) { deleteVulnsCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.Vulnerability.dml", assembly); while (sqliteDataReader.Read()) { deleteVulnsCommand.Parameters.Add(new SQLiteParameter("Vulnerability_ID", sqliteDataReader["Vulnerability_ID"].ToString())); deleteVulnsCommand.ExecuteNonQuery(); } } } } catch (Exception exception) { LogWriter.LogError($"Unable to delete the Vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void DeleteMitigationGroupMappingByMitigation(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupMitigationOrConditionVulnerabilityMappingByMitigationOrCondition.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete the Mitigation / Group mappings for Mitigation ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}'."); throw exception; } } public void DeleteMitigationOrCondition(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.MitigationOrCondition.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete the MitigationOrCondition with Mitigation ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}'."); throw exception; } } public void DeleteUniqueFinding(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.UniqueFinding.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete the selected UniqueFinding with Unique Finding ID '{sqliteCommand.Parameters["UniqueFinding_ID"].Value}'."); throw exception; } } public void DropIndices() { try { List<string> indices = new List<string>(); if (!DatabaseBuilder.sqliteConnection.State.ToString().Equals("Open")) { DatabaseBuilder.sqliteConnection.Open(); } using (SQLiteCommand sqliteCommand = DatabaseBuilder.sqliteConnection.CreateCommand()) { sqliteCommand.CommandText = _ddlReader.ReadDdl("Vulnerator.Resources.DdlFiles.StoredProcedures.Select.Indices.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (sqliteDataReader.HasRows) { return; } while (sqliteDataReader.Read()) { if (sqliteDataReader["name"].ToString().Contains("autoindex")) { continue; } indices.Add(sqliteDataReader["name"].ToString()); } } foreach (string index in indices) { sqliteCommand.CommandText = $"DROP INDEX IF EXISTS {index};"; sqliteCommand.ExecuteNonQuery(); } } } catch (Exception exception) { LogWriter.LogError("$Unable to drop database indices."); throw exception; } finally { DatabaseBuilder.sqliteConnection.Close(); } } public void Reindex() { try { if (!DatabaseBuilder.sqliteConnection.State.ToString().Equals("Open")) { DatabaseBuilder.sqliteConnection.Open(); } using (SQLiteCommand sqliteCommand = DatabaseBuilder.sqliteConnection.CreateCommand()) { sqliteCommand.CommandText = "REINDEX sqlite_master;"; sqliteCommand.ExecuteNonQuery(); } } catch (Exception exception) { LogWriter.LogError("$Unable to reindex the database."); throw exception; } finally { DatabaseBuilder.sqliteConnection.Close(); } } public void InsertAndMapIpAddress(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.IP_Address.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.IP_AddressHardwareMapping.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert and map IP Address '{sqliteCommand.Parameters["IP_Address"].Value}'."); throw exception; } } public void InsertAndMapMacAddress(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.MAC_Address.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.MAC_AddressHardwareMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert and map MAC Address '{sqliteCommand.Parameters["MAC_Address"].Value}'."); throw exception; } } public void InsertAndMapPort(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.PortProtocolService.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.HardwarePortProtocolServiceMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert or map '{sqliteCommand.Parameters["Protocol"].Value} {sqliteCommand.Parameters["Port"].Value}'."); throw exception; } } public void InsertAndMapVulnerabilityReferences(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.VulnerabilityReference.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.VulnerabilityReferenceVulnerabilityMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert and map vulnerability reference '{sqliteCommand.Parameters["Reference"].Value}'."); throw exception; } } public void InsertGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.Group.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert group '{sqliteCommand.Parameters["Name"].Value}' into database."); throw exception; } } public void InsertHardware(SQLiteCommand sqliteCommand) { try { sqliteCommand.Parameters.Add(new SQLiteParameter("IsVirtualServer", "False")); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.Hardware.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert host '{sqliteCommand.Parameters["IP_Address"].Value}'."); throw exception; } } public void InsertEmptyMitigationOrCondition(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.EmptyMitigationOrCondition.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError("Unable to insert a new empty mitigation."); throw exception; } } public void InsertMitigationOrCondition(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.MitigationOrCondition.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError("Unable to insert the new mitigation."); throw exception; } } public void InsertMitigationOrConditionMitigatedStatus(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.MitigationOrConditionMitigatedStatus.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError("Unable to insert the new mitigation mitigated status."); throw exception; } } public void InsertParameterPlaceholders(SQLiteCommand sqliteCommand) { try { string[] parameters = { // CCI Table "CCI_Number", // FindingTypes Table "FindingType", // Groups Table "Group_ID", "GroupName", "GroupAcronym", "GroupTier", "IsAccreditation", "Accreditation_eMASS_ID", "IsPlatform", "Organization_ID", "ConfidentialityLevel_ID", "IntegrityLevel_ID", "AvailabilityLevel_ID", "SystemCategorization_ID", "AccreditationVersion", "CybersafeGrade", "FISCAM_Applies", "ControlSelection_ID", "HasForeignNationals", "SystemType", "RDTE_Zone", "StepOneQuestionnaire_ID", "SecurityAssessmentProcedure_ID", "PIT_Determination_ID", // Hardware Table "Hardware_ID", "DisplayedHostName", "DiscoveredHostName", "FQDN", "NetBIOS", "ScanIP", "Found21745", "Found26917", "IsVirtualServer", "NIAP_Level", "Manufacturer", "ModelNumber", "IsIA_Enabled", "SerialNumber", "Role", "LifecycleStatus_ID", "OperatingSystem", // IP_Addresses Table "IP_Address_ID", "IP_Address", // MAC_Addresses Table "MAC_Address_ID", "MAC_Address", // MitigationsOrConditions Table "MitigationOrCondition_ID", "ImpactDescription", "PredisposingConditions", "TechnicalMitigation", "ProposedMitigation", "ThreatRelevance", "SeverityPervasiveness", "Likelihood", "Impact", "Risk", "ResidualRisk", "ResidualRiskAfterProposed", "MitigatedStatus", "EstimatedCompletionDate", "ApprovalDate", "ExpirationDate", "IsApproved", "Approver", "ThreatDescription", // HardwarePortsProtocolsServices Table "PortProtocolService_ID", "Port", "Protocol", // PortsServices Table "PortService_ID", "DiscoveredServiceName", "DisplayedServiceName", "ServiceAcronym", // Software Table "Software_ID", "DiscoveredSoftwareName", "DisplayedSoftwareName", "SoftwareAcronym", "SoftwareVersion", "SoftwareFunction", "SoftwareDescription", "DADMS_ID", "DADMS_Disposition", "DADMS_LastDateAuthorized", "HasCustomCode", "IA_OrIA_Enabled", "IsOS_OrFirmware", "FAM_Accepted", "ExternallyAuthorized", "ReportInAccreditationGlobal", "ApprovedForBaselineGlobal", "BaselineApproverGlobal", "Instance", "InstallDate", // UniqueFindings Table "UniqueFinding_ID", "InstanceIdentifier", "ToolGeneratedOutput", "Comments", "FindingDetails", "FirstDiscovered", "LastObserved", "DeltaAnalysisIsRequired", "FindingType_ID", "FindingSourceFile_ID", "Status", "Vulnerability_ID", "Hardware_ID", "Software_ID", "SeverityOverride", "SeverityOverrideJustification", "TechnologyArea", "WebDB_Site", "WebDB_Instance", "Classification", "CVSS_EnvironmentalScore", "CVSS_EnvironmentalVector", // UniqueFindingSourceFiles Table "FindingSourceFile_ID", "FindingSourceFileName", // Vulnerabilities Table "Vulnerability_ID", "UniqueVulnerabilityIdentifier", "VulnerabilityGroupIdentifier", "VulnerabilityGroupTitle", "SecondaryVulnerabilityIdentifier", "VulnerabilityFamilyOrClass", "VulnerabilityVersion", "VulnerabilityRelease", "VulnerabilityTitle", "VulnerabilityDescription", "RiskStatement", "FixText", "PublishedDate", "ModifiedDate", "FixPublishedDate", "PrimaryRawRiskIndicator", "SecondaryRawRiskIndicator", "CVSS_BaseScore", "CVSS_BaseVector", "CVSS_TemporalScore", "CVSS_TemporalVector", "CheckContent", "FalsePositives", "FalseNegatives", "IsDocumentable", "Mitigations", "MitigationControl", "IsActive", "PotentialImpacts", "ThirdPartyTools", "SecurityOverrideGuidance", "SeverityOverrideGuidance", "Overflow", // VulnerabilityReferences Table "Reference_ID", "Reference", "ReferenceType", // VulnerabilitySources Table "VulnerabilitySource_ID", "SourceName", "SourceSecondaryIdentifier", "VulnerabilitySourceFileName", "SourceDescription", "SourceVersion", "SourceRelease", // SCAP_Scores Table "SCAP_Score_ID", "Score", "ScanDate", "ScanProfile", "ScanUser", "UserIsPrivileged", "UserIsAuthenticated", // Report Filtering "UserName" }; foreach (string parameter in parameters) { sqliteCommand.Parameters.Add(new SQLiteParameter(parameter, DBNull.Value)); } } catch (Exception exception) { LogWriter.LogError("Unable to insert SQLiteParameter placeholders into SQLiteCommand"); throw exception; } } public void InsertParsedFileSource(SQLiteCommand sqliteCommand, Object.File file) { try { sqliteCommand.Parameters.Add(new SQLiteParameter("FindingSourceFileName", file.FileName)); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.UniqueFindingSourceFile.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert unique finding source file '{file.FileName}'."); throw exception; } } public void InsertParsedFileSource(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.UniqueFindingSourceFile.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert unique finding source file '{sqliteCommand.Parameters["FindingSourceFileName"].Value}'."); throw exception; } } public void InsertScapScore(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.ScapScore.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert SCAP score for '{sqliteCommand.Parameters["DiscoveredHostName"].Value}', '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public void InsertSoftware(SQLiteCommand sqliteCommand) { try { if (sqliteCommand.Parameters["FindingType"].Value.ToString().Equals("Fortify")) { sqliteCommand.Parameters["HasCustomCode"].Value = "True"; } else { sqliteCommand.Parameters["HasCustomCode"].Value = "False"; } sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.Software.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert software '{sqliteCommand.Parameters["DiscoveredSoftwareName"].Value}'."); throw exception; } } public void InsertUniqueFinding(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.UniqueFinding.dml", assembly);; sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to generate a new unique finding for '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}', '{sqliteCommand.Parameters["DiscoveredHostName"].Value}', '{sqliteCommand.Parameters["ScanIP"].Value}'."); throw exception; } } public void InsertVulnerability(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.Vulnerability.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void InsertVulnerabilitySource(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.VulnerabilitySource.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert vulnerability source '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public void MapMitigationToGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.MitigationOrConditionGroupMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map mitigation with Mitigation ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}' to group with Group ID '{sqliteCommand.Parameters["Group_ID"]}' and vulnerability with Vulnerability ID '{sqliteCommand.Parameters["Vulnerability_ID"]}'."); throw exception; } } public void MapHardwareToGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.HardwareGroupMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map host '{sqliteCommand.Parameters["DiscoveredHostName"].Value}' to group '{sqliteCommand.Parameters["GroupName"].Value}'."); throw exception; } } public void MapHardwareToSoftware(SQLiteCommand sqliteCommand) { try { sqliteCommand.Parameters.Add(new SQLiteParameter("ReportInAccreditation", "False")); sqliteCommand.Parameters.Add(new SQLiteParameter("ApprovedForBaseline", "False")); sqliteCommand.Parameters.Add(new SQLiteParameter("BaselineApprover", DBNull.Value)); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.HardwareSoftwareMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map software '{sqliteCommand.Parameters["DiscoveredSoftwareName"].Value}' to hardware '{sqliteCommand.Parameters["DiscoveredHostName"].Value}'."); throw exception; } } public void MapHardwareToVulnerabilitySource(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.HardwareVulnerabilitySourceMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map hardware '{sqliteCommand.Parameters["DiscoveredHostName"].Value}' to source '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public void MapVulnerabilityToCci(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.VulnerabilityCCI_Mapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map CCI '{sqliteCommand.Parameters["CCI_Number"].Value}' to vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void MapVulnerabilityToSource(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Insert.VulnerabilitySourceVulnerabilityMapping.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to map vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}' to source '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public int SelectLastInsertRowId(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = "SELECT last_insert_rowid();"; return int.Parse(sqliteCommand.ExecuteScalar().ToString()); } catch (Exception exception) { LogWriter.LogError("Unable to select the last inserted row ID."); throw exception; } } public int? SelectUniqueFindingMitigationOrConditionId(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.UniqueFindingMitigationOrConditionId.dml", assembly); object scalarResult = sqliteCommand.ExecuteScalar(); if (string.IsNullOrWhiteSpace(scalarResult.ToString())) { return null; } return int.Parse(scalarResult.ToString()); } catch (Exception exception) { LogWriter.LogError("Unable to select the last inserted row ID."); throw exception; } } public List<string> SelectOutdatedUniqueFindings(SQLiteCommand sqliteCommand, DateTime lastObserved) { try { List<string> ids = new List<string>(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.UniqueFindingLastObservedDateAndId.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (!sqliteDataReader.HasRows) { return ids; } while (sqliteDataReader.Read()) { if (DateTime.Parse(sqliteDataReader["LastObserved"].ToString()) < lastObserved) { ids.Add(sqliteDataReader["UniqueFinding_ID"].ToString()); } } } return ids; } catch (Exception exception) { LogWriter.LogError($"Unable to generate a list of outdated unique findings for hardware '{sqliteCommand.Parameters["DiscoveredHostName"].Value}'."); throw exception; } } public List<string> SelectOutdatedVulnerabilities(SQLiteCommand sqliteCommand, bool filterOnInstanceIdentifier) { try { List<string> ids = new List<string>(); if (filterOnInstanceIdentifier) { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilityVersionAndReleaseAndUniqueFindingIdByInstanceIdentifier.dml", assembly); } else { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilityVersionAndReleaseAndUniqueFindingId.dml", assembly); } using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (!sqliteDataReader.HasRows) { return ids; } while (sqliteDataReader.Read()) { bool versionOutdated = false; bool releaseOutdated = false; if ((int.TryParse(sqliteDataReader["VulnerabilityVersion"].ToString(), out int i) && int.TryParse(sqliteCommand.Parameters["VulnerabilityVersion"].Value.ToString(), out i)) && (int.Parse(sqliteDataReader["VulnerabilityVersion"].ToString()) < int.Parse(sqliteCommand.Parameters["VulnerabilityVersion"].Value.ToString()))) { versionOutdated = true; } if ((int.TryParse(sqliteDataReader["VulnerabilityVersion"].ToString(), out i) && int.TryParse(sqliteCommand.Parameters["VulnerabilityVersion"].Value.ToString(), out i)) && (int.TryParse(sqliteDataReader["VulnerabilityRelease"].ToString(), out i) && int.TryParse(sqliteCommand.Parameters["VulnerabilityRelease"].Value.ToString(), out i)) && (int.Parse(sqliteDataReader["VulnerabilityVersion"].ToString()) == int.Parse(sqliteCommand.Parameters["VulnerabilityVersion"].Value.ToString())) && (int.Parse(sqliteDataReader["VulnerabilityRelease"].ToString()) < int.Parse(sqliteCommand.Parameters["VulnerabilityRelease"].Value.ToString()))) { releaseOutdated = true; } if (versionOutdated || releaseOutdated) { ids.Add(sqliteDataReader["UniqueFinding_ID"].ToString()); } } } return ids; } catch (Exception exception) { LogWriter.LogError($"Unable to generate a list of outdated unique findings for vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public List<string> SelectUniqueVulnerabilityIdentifiersBySource(SQLiteCommand sqliteCommand) { try { List<string> vulnerabilityIds = new List<string>(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.UniqueVulnerabilityIdentifiersBySource.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (sqliteDataReader.HasRows) { while (sqliteDataReader.Read()) { vulnerabilityIds.Add(sqliteDataReader["UniqueVulnerabilityIdentifier"].ToString()); } } } return vulnerabilityIds; } catch (Exception exception) { LogWriter.LogError($"Unable to generate a list of vulnerabilities associated with the vulnerability source associated with ID '{sqliteCommand.Parameters["VulnerabilitySource_ID"].Value}'."); throw exception; } } public void SelectVulnerabilitySourceName(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilitySourceName.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (sqliteDataReader.HasRows) { while (sqliteDataReader.Read()) { sqliteCommand.Parameters["SourceName"].Value = sqliteDataReader["SourceName"].ToString(); } } } } catch (Exception exception) { LogWriter.LogError($"Unable to retrieve the vulnerability source name for the vulnerability source associated with ID '{sqliteCommand.Parameters["VulnerabilitySource_ID"].Value}'."); throw exception; } } public void SelectHardware(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.Hardware.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (sqliteDataReader.HasRows) { while (sqliteDataReader.Read()) { sqliteCommand.Parameters["DiscoveredHostName"].Value = sqliteDataReader["DiscoveredHostName"].ToString(); sqliteCommand.Parameters["FQDN"].Value = sqliteDataReader["FQDN"].ToString(); sqliteCommand.Parameters["NetBIOS"].Value = sqliteDataReader["NetBIOS"].ToString(); sqliteCommand.Parameters["ScanIP"].Value = sqliteDataReader["ScanIP"].ToString(); } } } } catch (Exception exception) { LogWriter.LogError($"Unable to select the details for the hardware record associated with ID '{sqliteCommand.Parameters["Hardware_ID"].Value}'."); throw exception; } } public void SetCredentialedScanStatus(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.CredentialedScanStatus.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to set the credentialed scan status for '{sqliteCommand.Parameters["ScanIP"].Value}'."); throw exception; } } public void UpdateMitigationOrCondition(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.MitigationOrCondition.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update MitigationOrCondition associated with ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}'."); throw exception; } } public void UpdateMitigationOrConditionMitigatedStatus(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.MitigationOrConditionMitigatedStatus.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update MitigationOrCondition associated with ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}'."); throw exception; } } public void UpdateUniqueFinding(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.UniqueFinding.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update the unique finding for '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}', '{sqliteCommand.Parameters["DiscoveredHostName"].Value}', '{sqliteCommand.Parameters["ScanIP"].Value}'."); throw exception; } } public void UpdateUniqueFindingMitigationOrCondition(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.UniqueFindingMitigationOrCondition.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update MitigationOrCondition associated with ID '{sqliteCommand.Parameters["MitigationOrCondition_ID"].Value}' for the UniqueFinding with ID '{sqliteCommand.Parameters["UniqueFinding_ID"].Value}'."); throw exception; } } public void UpdateVulnerability(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.Vulnerability.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to insert vulnerability '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void UpdateDeltaAnalysisFlags(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.DeltaAnalysisFlag.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update the delta analysis flag(s) for unique findings related to '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void UpdateVulnerabilitySource(SQLiteCommand sqliteCommand) { try { switch (sqliteCommand.Parameters["FindingType"].Value.ToString()) { case "ACAS": { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.AcasVulnerabilitySource.dml", assembly); sqliteCommand.ExecuteNonQuery(); sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.AcasVulnerabilitiesMappedToUnknownVersion.dml", assembly); sqliteCommand.ExecuteNonQuery(); return; } case "CKL": { if (VulnerabilitySourceUpdateRequired(sqliteCommand)) { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.VulnerabilitySource.dml", assembly); sqliteCommand.ExecuteNonQuery(); } return; } default: { break; } } } catch (Exception exception) { LogWriter.LogError($"Unable to update vulnerability source '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public void UpdateRequiredReportSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.RequiredReportIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update the 'Is_Report_Selected' field for Report ID '{sqliteCommand.Parameters["Required_Report_ID"].Value}'"); throw exception; } } private void MapVulnerabilityToIAControl(SQLiteCommand sqliteCommand) { try { } catch (Exception exception) { LogWriter.LogError("Unable to vulnerability to IA Control."); throw exception; } } private bool VulnerabilitySourceUpdateRequired(SQLiteCommand sqliteCommand) { try { bool versionUpdated = false; bool versionSame = false; bool releaseUpdated = false; sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilitySourceVersionAndRelease.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (sqliteDataReader.HasRows) { while (sqliteDataReader.Read()) { if (string.IsNullOrWhiteSpace(sqliteDataReader["SourceVersion"].ToString())) { return true; } Regex regex = new Regex(@"\D"); int newVersion; int newRelease; bool newVersionParsed = int.TryParse(regex.Replace(sqliteCommand.Parameters["SourceVersion"].Value.ToString(), string.Empty), out newVersion); bool newReleaseParsed = int.TryParse(regex.Replace(sqliteCommand.Parameters["SourceRelease"].Value.ToString(), string.Empty), out newRelease); int oldVersion; int oldRelease; bool oldVersionParsed = int.TryParse(regex.Replace(sqliteDataReader["SourceVersion"].ToString(), string.Empty), out oldVersion); bool oldReleaseParsed = int.TryParse(regex.Replace(sqliteDataReader["SourceRelease"].ToString(), string.Empty), out oldRelease); if (newVersionParsed && oldVersionParsed) { versionUpdated = (newVersion > oldVersion); versionSame = (newVersion == oldVersion); } if (newReleaseParsed && oldReleaseParsed && (newRelease > oldRelease)) { releaseUpdated = true; } if (versionUpdated || (versionSame && releaseUpdated)) { return true; } sqliteCommand.Parameters["SourceVersion"].Value = sqliteDataReader["SourceVersion"].ToString(); sqliteCommand.Parameters["SourceRelease"].Value = sqliteDataReader["SourceRelease"].ToString(); } } return false; } } catch (Exception exception) { LogWriter.LogError($"Unable to determine if an update is required for vulnerability '{sqliteCommand.Parameters["SourceName"].Value}'."); throw exception; } } public string CompareVulnerabilityVersions(SQLiteCommand sqliteCommand) { try { bool versionsMatch = false; bool releasesMatch = false; bool ingestedVersionIsNewer = false; bool ingestedReleaseIsNewer = false; bool existingVersionIsNewer = false; bool existingReleaseIsNewer = false; sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Select.VulnerabilityVersionAndRelease.dml", assembly); using (SQLiteDataReader sqliteDataReader = sqliteCommand.ExecuteReader()) { if (!sqliteDataReader.HasRows) return "Record Not Found"; while (sqliteDataReader.Read()) { if (string.IsNullOrWhiteSpace(sqliteDataReader["VulnerabilityVersion"].ToString())) { return "Record Not Found"; } Regex regex = new Regex(@"\D"); bool newVersionParsed = int.TryParse(regex.Replace(sqliteCommand.Parameters["VulnerabilityVersion"].Value.ToString(), string.Empty), out int newVersion); bool newReleaseParsed = int.TryParse(regex.Replace(sqliteCommand.Parameters["VulnerabilityRelease"].Value.ToString(), string.Empty), out int newRelease); bool oldVersionParsed = int.TryParse(regex.Replace(sqliteDataReader["VulnerabilityVersion"].ToString(), string.Empty), out int oldVersion); bool oldReleaseParsed = int.TryParse(regex.Replace(sqliteDataReader["VulnerabilityRelease"].ToString(), string.Empty), out int oldRelease); if (newVersionParsed && oldVersionParsed) { ingestedVersionIsNewer = (newVersion > oldVersion); existingVersionIsNewer = (newVersion < oldVersion); versionsMatch = (newVersion == oldVersion); } if (newReleaseParsed && oldReleaseParsed) { ingestedReleaseIsNewer = (newRelease > oldRelease); existingReleaseIsNewer = (newRelease < oldRelease); releasesMatch = (newRelease == oldRelease); } if (ingestedVersionIsNewer) { return "Ingested Version Is Newer"; } if (existingVersionIsNewer) { sqliteCommand.Parameters["VulnerabilityVersion"].Value = sqliteDataReader["VulnerabilityVersion"].ToString(); sqliteCommand.Parameters["VulnerabilityRelease"].Value = sqliteDataReader["VulnerabilityRelease"].ToString(); return "Existing Version Is Newer"; } if (versionsMatch) { if (releasesMatch || (!oldReleaseParsed && !newReleaseParsed)) { return "Identical Versions"; } if (ingestedReleaseIsNewer) { return "Ingested Version Is Newer"; } if (existingReleaseIsNewer) { sqliteCommand.Parameters["VulnerabilityVersion"].Value = sqliteDataReader["VulnerabilityVersion"].ToString(); sqliteCommand.Parameters["VulnerabilityRelease"].Value = sqliteDataReader["VulnerabilityRelease"].ToString(); return "Existing Version Is Newer"; } } } } return "Record Not Found"; } catch (Exception exception) { LogWriter.LogError($"Unable to compare vulnerability version information for '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}' against current database information."); throw exception; } } public void UpdateVulnerabilityDates(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.VulnerabilityDates.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update the Modified Date for '{sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value}'."); throw exception; } } public void UpdateGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.Group.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update Group '{sqliteCommand.Parameters["GroupName"].Value}'."); throw exception; } } public void UpdateReportIsSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.RequiredReportIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'IsReportSelected' value for RequiredReport with ID '{sqliteCommand.Parameters["RequiredReportUserSelection_ID"].Value}'."); throw exception; } } public void UpdateReportFindingTypeIsSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportFindingTypeIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'IsSelected' value for ReportFindingTypeUserSetting with ID '{sqliteCommand.Parameters["ReportFindingTypeUserSettings_ID"].Value}'."); throw exception; } } public void UpdateReportGroupIsSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportGroupIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'IsSelected' value for ReportGroupUserSetting with ID '{sqliteCommand.Parameters["ReportGroupUserSettings_ID"].Value}'."); throw exception; } } public void UpdateReportSeverityIsSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportSeverityIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'IsSelected' value for ReportSeverityUserSetting with ID '{sqliteCommand.Parameters["ReportSeverityUserSettings_ID"].Value}'."); throw exception; } } public void UpdateReportStatusIsSelected(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportStatusIsSelected.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'IsSelected' value for ReportStatusUserSetting with ID '{sqliteCommand.Parameters["ReportStatusUserSettings_ID"].Value}'."); throw exception; } } public void UpdateReportUseGlobalValueUserSettings(SQLiteCommand sqliteCommand, string columnName) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportUseGlobalValueUserSettings.dml", assembly); sqliteCommand.CommandText = sqliteCommand.CommandText.Replace("[COLUMN_NAME]", columnName); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update '{columnName}' value for ReportUseGlobalValueUserSetting with RequiredReport_ID '{sqliteCommand.Parameters["RequiredReport_ID"].Value}'."); throw exception; } } public void UpdateReportRmfOverrideGlobal(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportRmfOverrideGlobal.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError("Unable to update 'Group_ID' value for the 'Global' ReportRmfOverrideUserSettings."); throw exception; } } public void UpdateReportRmfOverrideSelectedReport(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ReportRmfOverrideSelectedReport.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'Group_ID' value for ReportRmfOverrideUserSettings with RequiredReport_ID '{sqliteCommand.Parameters["RequiredReport_ID"].Value}'."); throw exception; } } public void UpdateUniqueFindingStatusById(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.UniqueFindingStatusById.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to update 'Status' value for UniqueFinding with UniqueFinding_ID '{sqliteCommand.Parameters["UniqueFinding_ID"].Value}'."); throw exception; } } public void ClearReportRmfOverrideGlobal(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ClearReportRmfOverrideGlobal.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError("Unable to clear 'Group_ID' value for the 'Global' ReportRmfOverrideUserSettings."); throw exception; } } public void ClearReportRmfOverrideSelectedReport(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Update.ClearReportRmfOverrideSelectedReport.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to clear 'Group_ID' value for ReportRmfOverrideUserSettings with RequiredReport_ID '{sqliteCommand.Parameters["RequiredReport_ID"].Value}'."); throw exception; } } public void DeleteGroupsCCIsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupCCI_MappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsCCIs mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsWaiversMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupWaiverMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsWaivers mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsOverlaysMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupOverlayMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsOverlays mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsConnectedSystemsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupConnectedSystemByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsConnectedSystems mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsMitigationsOrConditionsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupMitigationOrConditionVulnerabilityMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsMitigationsOrConditions mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsConnectionsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupConnectionMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsConnections mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteHardwareGroupsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.HardwareGroupMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete HardwareGroups mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroups_IATA_StandardsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupIATA_StandardMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete Group / IATA_Standard mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroupsContactsMappingByGroup(SQLiteCommand sqliteCommand) { try { sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.GroupContactMappingByGroup.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete GroupsContacts mapping for Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } public void DeleteGroup(SQLiteCommand sqliteCommand) { try { // Ensure that no mappings will be orphaned DeleteGroupsCCIsMappingByGroup(sqliteCommand); DeleteGroupsWaiversMappingByGroup(sqliteCommand); DeleteGroupsOverlaysMappingByGroup(sqliteCommand); DeleteGroupsConnectedSystemsMappingByGroup(sqliteCommand); DeleteGroupsMitigationsOrConditionsMappingByGroup(sqliteCommand); DeleteGroupsConnectionsMappingByGroup(sqliteCommand); DeleteHardwareGroupsMappingByGroup(sqliteCommand); DeleteGroups_IATA_StandardsMappingByGroup(sqliteCommand); DeleteGroupsContactsMappingByGroup(sqliteCommand); // Execute DeleteGroup Command sqliteCommand.CommandText = _ddlReader.ReadDdl(_storedProcedureBase + "Delete.Group.dml", assembly); sqliteCommand.ExecuteNonQuery(); } catch (Exception exception) { LogWriter.LogError($"Unable to delete Group with Group_ID '{sqliteCommand.Parameters["Group_ID"].Value}'."); throw exception; } } } }
47.093343
300
0.571424
[ "MIT" ]
Vulnerator/Vulnerator
Model/DataAccess/DatabaseInterface.cs
65,085
C#
using BookStore.Core.Messaging; using System; namespace BookStore.Domain.Commands { public class SetBookPrice : Command { public Guid BookId { get; set; } public decimal Price { get; set; } } }
18.666667
42
0.651786
[ "MIT" ]
fvilers/AspNetCqrsSample
BookStore/BookStore.Domain/Commands/SetBookPrice.cs
226
C#
using System; using System.Collections; using YamlDotNet.RepresentationModel; using NerdyMishka.Reflection; using NerdyMishka.Reflection.Extensions; using System.Collections.Generic; using System.Linq; using NerdyMishka.Text; using NerdyMishka.ComponentModel.DataAnnotations; using NerdyMishka.ComponentModel.ValueConversion; namespace NerdyMishka.Extensions.Flex { public class YamlObjectReader { private ITextTransform propertyTransform = new PascalCaseTransform(); private IFlexSerializationSettings settings; public YamlObjectReader(IFlexSerializationSettings settings = null) { this.settings = settings ?? new FlexSerializationSettings(); } private IType GetIType(Type clrType) { return this.settings.ReflectionCache.GetOrAdd(clrType); } public object Visit(YamlNode node, IProperty propertyInfo, IType typeInfo) { switch(node) { case YamlMappingNode element: return this.VisitElement(element, propertyInfo, typeInfo); case YamlSequenceNode array: return this.VisitArray(array, propertyInfo, typeInfo); case YamlScalarNode value: return this.VisitValue(value, propertyInfo, typeInfo); } return null; } public T VisitDocument<T>(YamlDocument document) { return (T)this.VisitDocument(document, this.GetIType(typeof(T))); } public object VisitDocument(YamlDocument document, Type clrType) { return this.VisitDocument(document, this.GetIType(clrType)); } internal object VisitDocument(YamlDocument document, IType typeInfo) { var rootNode = document.RootNode; return this.Visit(rootNode, null, typeInfo); } public string VisitComment(YamlNode node) { return null; } public object VisitAttribute(YamlNode node, IType typeInfo) { return null; } public object VisitValue(YamlScalarNode node, IProperty property, IType type = null) { if(node.Value == "null") return null; IReadOnlyCollection<ValueConverter> converters = new List<ValueConverter>(); string propertyName = "unknown property"; Type clrType = type?.ClrType; if(property != null) { propertyName = property.Name; type = this.GetIType(property.ClrType); converters = property.GetValueConverters(typeof(string)); foreach(var converter in converters) { if(converter is ValueEncryptionConverter) { if(this.settings.OmitEncryption) continue; if(this.settings.EncryptionProvider != null) { ((ValueEncryptionConverter)converter).SetEncryptionProvider( this.settings.EncryptionProvider); } } if(converter.CanConvertFrom(clrType) && converter.CanConvertTo(typeof(string))) return converter.ConvertFrom(node.Value); } } if(this.settings.ValueConverters != null && this.settings.ValueConverters.Count > 0) { foreach(var converter in this.settings.ValueConverters) { if(converter is ValueEncryptionConverter) { if(this.settings.OmitEncryption) continue; if(this.settings.EncryptionProvider != null) { ((ValueEncryptionConverter)converter).SetEncryptionProvider( this.settings.EncryptionProvider); } } // Property => Store if(converter.CanConvertFrom(clrType) && converter.CanConvertTo(typeof(string))) return converter.ConvertFrom(node.Value); } } if(!(type.IsDataType || type.IsNullableOfT() && type.UnderlyingType.IsDataType)) throw new MappingException("Scalar Nodes must be a data type"); switch(type.FullName) { case "System.Byte[]": return Convert.FromBase64String(node.Value); case "System.Char[]": return node.Value.ToCharArray(); case "System.String": return node.Value; case "System.DateTime": var dt = DateTime.Parse(node.Value, null, System.Globalization.DateTimeStyles.AssumeUniversal); if(dt.Kind != DateTimeKind.Utc) return dt.ToUniversalTime(); return dt; case "System.Boolean": case "System.Nullable[System.Boolean]": switch (node.Value) { case "": case null: case "null": if (type.FullName != "System.Nullable[System.Boolean]") throw new InvalidCastException("Cannot convert null to boolean"); return null; case "y": case "Y": case "yes": case "Yes": case "YES": case "true": case "True": case "TRUE": case "on": case "On": case "ON": return true; default: return false; } default: bool isNull = string.IsNullOrWhiteSpace(node.Value) || node.Value.Match("null"); clrType = type.ClrType; if(type.IsNullableOfT()) { if(isNull) return null; clrType = type.UnderlyingType.ClrType; } if(isNull) throw new MappingException($"{propertyName} is type {type.FullName} which must not be null."); return Convert.ChangeType(node.Value, clrType); } } public class YamlPropertyEnumerator : IEnumerator<KeyValuePair<string, YamlNode>> { private YamlMappingNode node; private List<YamlScalarNode> keys; private int index = -1; public YamlPropertyEnumerator(YamlMappingNode node) { this.node = node; this.keys = this.node.Children.Keys .Cast<YamlScalarNode>() .ToList(); } public KeyValuePair<string, YamlNode> Current { get{ var key = this.keys[this.index]; return new KeyValuePair<string, YamlNode>(key.Value, node.Children[key]); } } object IEnumerator.Current => this.Current; public void Dispose() { this.node = null; this.keys = null; } public bool MoveNext() { if(this.index >= (this.keys.Count - 1)) return false; this.index = this.index + 1; return true; } public void Reset() { this.index = -1; } } private string ConvertToPropertyName(string key) { // TODO: cache property convertions in a dictionary with a max cap var propertyName = key; if(this.propertyTransform != null) propertyName = this.propertyTransform.Transform(propertyName).ToString(); if(String.IsInterned(propertyName) == null) string.Intern(propertyName); return propertyName; } public object VisitElement(YamlMappingNode node, IProperty propertyInfo = null, IType typeInfo = null) { if(propertyInfo != null) { if(typeInfo == null) typeInfo = this.GetIType(propertyInfo.ClrType); } var isDictionaryLike = typeInfo.IsIDictionaryOfKv() || typeInfo.IsIDictionary(); var childType = typeInfo.AsItemType()?.ItemType; var clrType = childType?.ClrType; if(childType == null || clrType == typeof(Object)) { clrType = typeof(string); childType = this.GetIType(clrType); } if(isDictionaryLike) { var dictionary = (IDictionary)Activator.CreateInstance(typeInfo.ClrType); var enumerator = new YamlPropertyEnumerator(node); while(enumerator.MoveNext()) { var child = enumerator.Current; dictionary.Add( child.Key, this.Visit(child.Value, null, childType)); } return dictionary; } { var properties = typeInfo.Properties.ToList(); var enumerator = new YamlPropertyEnumerator(node); var obj = Activator.CreateInstance(typeInfo.ClrType); var defaultProperty = properties .FirstOrDefault(o => o.Attributes .Any(a => a is DynamicDefaultAttribute)); if(defaultProperty != null) { while(enumerator.MoveNext()) { if(enumerator.Current.Key.Match(defaultProperty.Name)) { var value = enumerator.Current.Value; if(value != null) { return this.Visit(value, defaultProperty, this.GetIType(defaultProperty.ClrType)); } properties.Remove(defaultProperty); break; } } enumerator.Reset(); } if(typeInfo.IsDataType) throw new MappingException("YamlMappingNode cannot be converted into a data type"); while(enumerator.MoveNext()) { var child = enumerator.Current; var propertyName = this.ConvertToPropertyName(child.Key); var property = properties.FirstOrDefault(o => o.Name.Match(propertyName)); if(property == null) continue; if(!property.CanWrite) continue; if(property.Attributes.Any(o => o is IgnoreAttribute)) continue; property.SetValue(obj, this.Visit(child.Value, property, this.GetIType(property.ClrType))); } return obj; } } public IList VisitArray(YamlSequenceNode node, IProperty propertyInfo, IType typeInfo) { if(propertyInfo != null) { if(typeInfo == null) typeInfo = this.GetIType(propertyInfo.ClrType); } if(!typeInfo.IsListLike()) throw new MappingException($"{typeInfo.FullName} is not an array or list like."); var childType = typeInfo.AsItemType()?.ItemType; var clrType = childType?.ClrType; if(childType == null) { clrType = typeof(Object); childType = this.GetIType(clrType); } if(typeInfo.IsArray()) { var array = (Array)Array.CreateInstance(clrType, node.Children.Count); for(var i = 0; i < node.Children.Count; i++) { var child = node.Children[i]; var value = this.Visit(child, null, childType); array.SetValue(value, i); } return array; } var list = (IList)Activator.CreateInstance(typeInfo.ClrType); for(var i = 0; i < node.Children.Count; i++) { var child = node.Children[i]; var value = this.Visit(child, null, childType); list.Add(value); } return list; } } }
34.070352
118
0.473009
[ "Apache-2.0" ]
nerdymishka/gainz
dotnet/src/Extensions/Proto.Flex/YamlObjectReader.cs
13,560
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _6.Math_Power { class Program { static void Main(string[] args) { var number = long.Parse(Console.ReadLine()); var power = long.Parse(Console.ReadLine()); Console.WriteLine(MathPower(number, power)); } static long MathPower(long number, long power) { var result = 1L; for (long i = 0; i < power; i++) { result *= number; } return result; } } }
19.787879
57
0.523737
[ "MIT" ]
bingoo0/SoftUni-TechModule
Methods Defining and Calling Methods/6. Math Power/Program.cs
655
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace BAG.Common.Sitemap { public class SiteUrl { [XmlElement("loc")] public string Location { get; set; } [XmlElement("priority")] public string Priority { get; set; } [XmlElement("news", Namespace = "http://www.google.com/schemas/sitemap-news/0.9")] public string News { get; set; } [XmlElement("lastmod")] public DateTime? LastModified { get; set; } [XmlElement("changefreq")] public string ChangeFrequency { get; set; } public bool ShouldSerializeLastModified() { return LastModified.HasValue; } } }
29.192308
90
0.650856
[ "MIT" ]
BROCKHAUS-AG/ContentMonkee
MAIN/BAG.Common/Sitemap/SiteUrl.cs
761
C#
namespace Octokit.GraphQL.Model { using System; using System.Collections.Generic; using System.Linq.Expressions; using Octokit.GraphQL.Core; using Octokit.GraphQL.Core.Builders; /// <summary> /// The connection type for Commit. /// </summary> public class CommitConnection : QueryableValue<CommitConnection>, IPagingConnection<Commit> { public CommitConnection(Expression expression) : base(expression) { } /// <summary> /// A list of edges. /// </summary> public IQueryableList<CommitEdge> Edges => this.CreateProperty(x => x.Edges); /// <summary> /// A list of nodes. /// </summary> public IQueryableList<Commit> Nodes => this.CreateProperty(x => x.Nodes); /// <summary> /// Information to aid in pagination. /// </summary> public PageInfo PageInfo => this.CreateProperty(x => x.PageInfo, Octokit.GraphQL.Model.PageInfo.Create); /// <summary> /// Identifies the total count of items in the connection. /// </summary> public int TotalCount { get; } IPageInfo IPagingConnection.PageInfo => PageInfo; internal static CommitConnection Create(Expression expression) { return new CommitConnection(expression); } } }
30.177778
112
0.611929
[ "MIT" ]
PEPE-net/octokit.graphql.net
Octokit.GraphQL/Model/CommitConnection.cs
1,358
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion namespace Json.Lite.Tests.TestObjects { public class GenericImpl : AbstractGenericBase<int> { public override int Id { get; set; } } }
40.8125
68
0.749617
[ "MIT" ]
TFrascaroli/Json.Net.Unity3D
src/Newtonsoft.Json.Tests/TestObjects/GenericImpl.cs
1,306
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.IO; using System.Xml; namespace Sce.Atf { /// <summary> /// Localizes strings by looking for *.Localization.xml files in a .NET satellite assembly /// directory pattern. See the tool LocalizableStringExtractor for building these XML files.</summary> /// <remarks>Consider embedding the XML files into your assemblies as resources and using /// EmbeddedResourceStringLocalizer instead.</remarks> public class SatelliteAssemblyStringLocalizer : XmlStringLocalizer { /// <summary> /// Constructor that searches for *.Localization.xml files in the language-specific /// sub-directory of the Resources sub-directory</summary> public SatelliteAssemblyStringLocalizer() { string localizedDir = AppDomain.CurrentDomain.BaseDirectory; localizedDir = Path.Combine(localizedDir, "Resources\\"); localizedDir = PathUtil.GetCulturePath(localizedDir); try { foreach (string path in Directory.GetFiles(localizedDir, "*.Localization.xml", SearchOption.TopDirectoryOnly)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); AddLocalizedStrings(xmlDoc); } } catch(System.IO.IOException e) { Outputs.WriteLine(OutputMessageType.Warning, e.Message); } } } }
40.1
127
0.617207
[ "Apache-2.0" ]
T-rvw/LevelEditor
ATF/Framework/Atf.Core/SatelliteAssemblyStringLocalizer.cs
1,566
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The interface IAndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionPage. /// </summary> [JsonConverter(typeof(InterfaceConverter<AndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionPage>))] public interface IAndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionPage : ICollectionPage<ManagedDeviceCertificateState> { /// <summary> /// Gets the next page <see cref="IAndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionRequest"/> instance. /// </summary> IAndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionRequest NextPageRequest { get; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString); } }
43.666667
153
0.670368
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IAndroidScepCertificateProfileManagedDeviceCertificateStatesCollectionPage.cs
1,441
C#
using UnityEngine; using System; public class PauseGame : MonoBehaviour { public Transform canvas; public static GM instance = null; // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { Pause(); } } public void Pause() { if (canvas.gameObject.activeInHierarchy == false) { canvas.gameObject.SetActive(true); Time.timeScale = 0; } else { canvas.gameObject.SetActive(false); Time.timeScale = 1; } } }
14.627907
57
0.515103
[ "MIT" ]
JasonMcTigue/GestureBasedUI
Assets/Scripts/PauseGame.cs
631
C#
// This file is Apache 2 licensed. Copy from: // https://github.com/ninject/ninject.extensions.azure/blob/master/src/Ninject.Extensions.Azure/NinjectRoleEntryPoint.cs // File has not been changed. // -------------------------------------------------------------------------------------------------------------------- // <copyright file="NinjectRoleEntryPoint.cs" company="bbv Software Services AG"> // 2009-2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Microsoft.WindowsAzure.ServiceRuntime; // ReSharper disable once CheckNamespace namespace Ninject.Extensions.Azure { /// <summary> /// Abstract implementation of a ninject-capable RoleEntryPoint for azure roles. /// </summary> public abstract class NinjectRoleEntryPoint : RoleEntryPoint { private IKernel Kernel { get; set; } /// <summary> /// Called by Windows Azure to initialize the role instance. /// </summary> /// <returns> /// True if initialization succeeds, False if it fails. The default implementation returns True. /// </returns> public override sealed bool OnStart() { Kernel = CreateKernel(); Kernel.Inject(this); return OnRoleStarted(); } /// <summary> /// Called by Windows Azure after the role instance has been initialized. This method serves as the /// main thread of execution for your role. /// </summary> public abstract override void Run(); /// <summary> /// Called by Windows Azure when the role instance is to be stopped. /// </summary> public override sealed void OnStop() { OnRoleStopping(); if (Kernel != null) { Kernel.Dispose(); Kernel = null; } OnRoleStopped(); } /// <summary> /// The extension point to create the kernel and load all modules for your azure role. /// </summary> /// <returns>The kernel</returns> protected abstract IKernel CreateKernel(); /// <summary> /// The extension point to perform custom startup actions for your azure role. This method is called after the kernel is created. /// </summary> /// <returns>True if startup succeeds, False if it fails. The default implementation returns True.</returns> protected virtual bool OnRoleStarted() { return true; } /// <summary> /// The extension point to perform custom shutdown actions that needs Ninject kernel. This method is called before ninject kernel is disposed. /// </summary> protected virtual void OnRoleStopping() { } /// <summary> /// The extension point to perform custom shutdown actions for your azure role. This method is called after the ninject kernel is disposed. /// </summary> protected virtual void OnRoleStopped() { } } }
37.034483
151
0.545003
[ "MIT" ]
noocyte/UXBackgroundWorker
src/AzureWorkers/NinjectRoleEntryPoint.cs
3,222
C#
namespace _02.KingsGambit.Models { using System; public abstract class Soldier { protected Soldier(string name) { this.Name = name; } public string Name { get; } public abstract void KingUnderAttack(object sender, EventArgs e); } }
17.882353
73
0.585526
[ "MIT" ]
melikpehlivanov/CSharp-OOP-Advanced
Object Communication and Events - Exercise/02.KingsGambit/Models/Soldier.cs
306
C#
using System.Threading.Tasks; namespace Demo.WebApi.Services { public class Bcrypt : IHash { public Task<string> Make(string text) { var hash = BCrypt.Net.BCrypt.HashPassword(text); return Task.FromResult(hash); } public Task<bool> Verify(string text, string hash) { var result = BCrypt.Net.BCrypt.Verify(text, hash); return Task.FromResult(true); } } }
21.227273
62
0.573876
[ "MIT" ]
flaviogf/Exemplos
example_working_with_roles_at_asp_net_core/Demo/Demo.WebApi/Services/Bcrypt.cs
469
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; namespace Pathoschild.Stardew.DataMaps.Framework { /// <summary>Simplifies access to the game's sprite sheets.</summary> /// <remarks>Each sprite is represented by a rectangle, which specifies the coordinates and dimensions of the image in the sprite sheet.</remarks> internal static class Sprites { /// <summary>Sprites used to draw a legend box.</summary> public static class Legend { /// <summary>The sprite sheet containing the icon sprites.</summary> public static Texture2D Sheet => Game1.mouseCursors; /// <summary>The legend background.</summary> public static readonly Rectangle Background = new Rectangle(334, 321, 1, 1); /// <summary>The top border.</summary> public static readonly Rectangle Top = new Rectangle(331, 318, 1, 2); /// <summary>The bottom border.</summary> public static readonly Rectangle Bottom = new Rectangle(327, 334, 1, 2); /// <summary>The left border.</summary> public static readonly Rectangle Left = new Rectangle(325, 320, 6, 1); /// <summary>The right border.</summary> public static readonly Rectangle Right = new Rectangle(344, 320, 6, 1); /// <summary>The top-left corner.</summary> public static readonly Rectangle TopLeft = new Rectangle(325, 318, 6, 2); /// <summary>The top-right corner.</summary> public static readonly Rectangle TopRight = new Rectangle(344, 318, 6, 2); /// <summary>The bottom-left corner.</summary> public static readonly Rectangle BottomLeft = new Rectangle(325, 334, 6, 2); /// <summary>The bottom-right corner.</summary> public static readonly Rectangle BottomRight = new Rectangle(344, 334, 6, 2); } } }
42.804348
150
0.635348
[ "MIT" ]
CrimsonTautology/StardewMods
DataMaps/Framework/Sprites.cs
1,971
C#
using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TindevApp.Backend.Models; namespace TindevApp.Backend.Repositories.Mongo { internal static class IMongoDatabaseExtensions { internal static IMongoCollection<Developer> GetDeveloperCollection(this IMongoDatabase mongoDatabase) { return mongoDatabase.GetCollection<Developer>("developer"); } internal static IMongoCollection<BsonDocument> GetDeveloperBsonCollection(this IMongoDatabase mongoDatabase) { return mongoDatabase.GetCollection<BsonDocument>("developer"); } } }
28.84
116
0.742025
[ "MIT" ]
bootcamp-bbq/r-tindev-poc1
Tindev/src/TindevApp.Backend/Repositories/Mongo/IMongoDatabaseExtensions.cs
723
C#
/* © Siemens AG, 2017-2018 Author: Dr. Martin Bischoff (martin.bischoff@siemens.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using UnityEngine; using Object = UnityEngine.Object; namespace RosSharp { public static class TransformExtensions { private const int RoundDigits = 6; public static void DestroyImmediateIfExists<T>(this Transform transform) where T : Component { T component = transform.GetComponent<T>(); if (component != null) Object.DestroyImmediate(component); } public static T AddComponentIfNotExists<T>(this Transform transform) where T : Component { T component = transform.GetComponent<T>(); if (component == null) component = transform.gameObject.AddComponent<T>(); return component; } public static void SetParentAndAlign(this Transform transform, Transform parent, bool keepLocalTransform = true) { Vector3 localPosition = transform.localPosition; Quaternion localRotation = transform.localRotation; transform.parent = parent; if (keepLocalTransform) { transform.position = transform.parent.position + localPosition; transform.rotation = transform.parent.rotation * localRotation; } else { transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; } } public static bool HasExactlyOneChild(this Transform transform) { return transform.childCount == 1; } public static void MoveChildTransformToParent(this Transform parent, bool transferRotation = true) { //Detach child in order to get a transform indenpendent from parent Transform childTransform = parent.GetChild(0); parent.DetachChildren(); //Copy transform from child to parent parent.position = childTransform.position; parent.localScale = childTransform.localScale; if (transferRotation) { parent.rotation = childTransform.rotation; childTransform.localRotation = Quaternion.identity; } childTransform.parent = parent; childTransform.localPosition = Vector3.zero; childTransform.localScale = Vector3.one; } public static Vector3 Ros2Unity(this Vector3 vector3) { return new Vector3(-vector3.y, vector3.z, vector3.x); } public static Vector3 Unity2Ros(this Vector3 vector3) { return new Vector3(vector3.z, -vector3.x, vector3.y); } public static Vector3 Ros2UnityScale(this Vector3 vector3) { return new Vector3(vector3.y, vector3.z, vector3.x); } public static Vector3 Unity2RosScale(this Vector3 vector3) { return new Vector3(vector3.z, vector3.x, vector3.y); } public static Quaternion Ros2Unity(this Quaternion quaternion) { //return new Quaternion(-quaternion.x, -quaternion.z, -quaternion.y, quaternion.w); return new Quaternion(quaternion.y, -quaternion.z, -quaternion.x, quaternion.w); } public static Quaternion Unity2Ros(this Quaternion quaternion) { //return new Quaternion(-quaternion.x, -quaternion.z, -quaternion.y, quaternion.w); return new Quaternion(-quaternion.z, quaternion.x, -quaternion.y, quaternion.w); } public static double[] ToRoundedDoubleArray(this Vector3 vector3) { double[] arr = new double[3]; for (int i = 0; i < 3; i++) arr[i] = Math.Round(vector3[i], RoundDigits); return arr; } public static Vector3 ToVector3(this double[] array) { return new Vector3((float)array[0], (float)array[1], (float)array[2]); } public static string SetSeparatorChar(this string path) { return path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } } }
34.869565
120
0.62448
[ "Apache-2.0" ]
UM-ARM-Lab/unity_victor_teleop
Assets/RosSharp/Scripts/Extensions/TransformExtensions.cs
4,815
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4c0b103d-d164-45b2-98c8-dc599b50520e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.942857
84
0.740211
[ "Unlicense" ]
adammartinez271828/MechEngineer
source/AssemblyInfo.cs
1,331
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace Mozart.Payment.Demo { public partial class AliWapPayCallBackDemo { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; } }
24.48
81
0.385621
[ "Apache-2.0" ]
zhenghua75/WeiXinEasy
Mozart/Payment/Demo/AliWapPayCallBackDemo.aspx.designer.cs
804
C#
using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace UtilityBot.Services.Data { public class TagContext : DbContext { public TagContext(DbContextOptions<TagContext> options) : base(options) { } public DbSet<TagInfo> Tags { get; set; } } // Named 'TagInfo' to prevent conflicts with Discord.Tag public class TagInfo { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public long OwnerId { get; set; } public string Name { get; set; } public List<AliasInfo> Aliases { get; set; } public string Content { get; set; } public int Uses { get; set; } } public class AliasInfo { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Trigger { get; set; } public int TagId { get; set; } public TagInfo Tag { get; set; } } }
27.55
83
0.637931
[ "ISC" ]
SindreMA/AutoChat
AutoChat/Services/Data/TagContext.cs
1,104
C#
namespace BusTickets.Models { public class Ticket { private Ticket() { } public Ticket(decimal price, string seat, Customer customer, Trip trip) { this.Price = price; this.Seat = seat; this.Customer = customer; this.Trip = trip; } public int Id { get; set; } public decimal Price { get; set; } public string Seat { get; set; } public int CustomerId { get; set; } public Customer Customer { get; set; } public int TripId { get; set; } public Trip Trip { get; set; } } }
21.333333
79
0.5125
[ "MIT" ]
RAstardzhiev/SoftUni-C-
Databases Advanced - Entity Framework Core/Best Practices and Architecture/BusTickets/BusTickets.Models/Ticket.cs
642
C#
using System; using System.ComponentModel; using _RowPropertiesChanged_ = m3u8.download.manager.models.LogListModel.RowPropertiesChangedEventHandler; using M = System.Runtime.CompilerServices.MethodImplAttribute; using O = System.Runtime.CompilerServices.MethodImplOptions; namespace m3u8.download.manager.models { /// <summary> /// /// </summary> public enum RequestRowTypeEnum { None, Success, Error, Finish }; /// <summary> /// /// </summary> public sealed class LogRow : RowBase< LogRow >, INotifyPropertyChanged { private _RowPropertiesChanged_ _RowPropertiesChanged; public event PropertyChangedEventHandler PropertyChanged; [M(O.AggressiveInlining)] private void Fire_PropertyChanged_Events( string propertyName ) { _RowPropertiesChanged?.Invoke( this, propertyName ); PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) ); } internal LogRow( LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) : base( model ) { _RowPropertiesChanged = rowPropertiesChanged ?? throw (new ArgumentNullException( nameof(rowPropertiesChanged) )); RequestText = ResponseText = string.Empty; } internal static LogRow CreateRequest( string requestText, LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) => new LogRow( model, rowPropertiesChanged ) { RequestText = requestText }; internal static LogRow CreateRequestSuccess( string requestText, LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) => new LogRow( model, rowPropertiesChanged ) { RequestRowType = RequestRowTypeEnum.Success, RequestText = requestText }; internal static LogRow CreateRequestFinish( string requestText, LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) => new LogRow( model, rowPropertiesChanged ) { RequestRowType = RequestRowTypeEnum.Finish, RequestText = requestText }; internal static LogRow CreateRequestError( string requestErrorText, LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) => new LogRow( model, rowPropertiesChanged ) { RequestRowType = RequestRowTypeEnum.Error, RequestText = requestErrorText }; internal static LogRow CreateResponseError( string requestText, string responseErrorText, LogListModel model, _RowPropertiesChanged_ rowPropertiesChanged ) => new LogRow( model, rowPropertiesChanged ) { RequestRowType = RequestRowTypeEnum.Error, RequestText = requestText, ResponseText = responseErrorText }; public string RequestText { [M(O.AggressiveInlining)] get; private set; } public string ResponseText { [M(O.AggressiveInlining)] get; private set; } public RequestRowTypeEnum RequestRowType { [M(O.AggressiveInlining)] get; private set; } [M(O.AggressiveInlining)] public void SetResponseSuccess( string responseText ) { ResponseText = responseText; RequestRowType = RequestRowTypeEnum.Success; Fire_PropertyChanged_Events( nameof(ResponseText) ); Fire_PropertyChanged_Events( nameof(RequestRowType) ); } [M(O.AggressiveInlining)] public void SetResponseError( string responseErrorText ) { ResponseText = responseErrorText; RequestRowType = RequestRowTypeEnum.Error; Fire_PropertyChanged_Events( nameof(ResponseText) ); Fire_PropertyChanged_Events( nameof(RequestRowType) ); } } }
51.6
165
0.719823
[ "MIT" ]
zamgi/m3u8
m3u8.download.manager/Avalonia/Model/LogRow.cs
3,614
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the macie2-2020-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; namespace Amazon.Macie2.Model { /// <summary> /// Paginators for the Macie2 service ///</summary> public class Macie2PaginatorFactory : IMacie2PaginatorFactory { private readonly IAmazonMacie2 client; internal Macie2PaginatorFactory(IAmazonMacie2 client) { this.client = client; } /// <summary> /// Paginator for DescribeBuckets operation ///</summary> public IDescribeBucketsPaginator DescribeBuckets(DescribeBucketsRequest request) { return new DescribeBucketsPaginator(this.client, request); } /// <summary> /// Paginator for GetUsageStatistics operation ///</summary> public IGetUsageStatisticsPaginator GetUsageStatistics(GetUsageStatisticsRequest request) { return new GetUsageStatisticsPaginator(this.client, request); } /// <summary> /// Paginator for ListClassificationJobs operation ///</summary> public IListClassificationJobsPaginator ListClassificationJobs(ListClassificationJobsRequest request) { return new ListClassificationJobsPaginator(this.client, request); } /// <summary> /// Paginator for ListCustomDataIdentifiers operation ///</summary> public IListCustomDataIdentifiersPaginator ListCustomDataIdentifiers(ListCustomDataIdentifiersRequest request) { return new ListCustomDataIdentifiersPaginator(this.client, request); } /// <summary> /// Paginator for ListFindings operation ///</summary> public IListFindingsPaginator ListFindings(ListFindingsRequest request) { return new ListFindingsPaginator(this.client, request); } /// <summary> /// Paginator for ListFindingsFilters operation ///</summary> public IListFindingsFiltersPaginator ListFindingsFilters(ListFindingsFiltersRequest request) { return new ListFindingsFiltersPaginator(this.client, request); } /// <summary> /// Paginator for ListInvitations operation ///</summary> public IListInvitationsPaginator ListInvitations(ListInvitationsRequest request) { return new ListInvitationsPaginator(this.client, request); } /// <summary> /// Paginator for ListMembers operation ///</summary> public IListMembersPaginator ListMembers(ListMembersRequest request) { return new ListMembersPaginator(this.client, request); } /// <summary> /// Paginator for ListOrganizationAdminAccounts operation ///</summary> public IListOrganizationAdminAccountsPaginator ListOrganizationAdminAccounts(ListOrganizationAdminAccountsRequest request) { return new ListOrganizationAdminAccountsPaginator(this.client, request); } } } #endif
34.892857
132
0.647646
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Macie2/Generated/Model/_bcl45+netstandard/Macie2PaginatorFactory.cs
3,908
C#
using System; #if FEATURE_BINARY_SERIALIZATION using System.Runtime.Serialization; #endif // FEATURE_BINARY_SERIALIZATION namespace Renci.SshNet.Common { /// <summary> /// The exception that is thrown when a proxy connection cannot be established. /// </summary> #if FEATURE_BINARY_SERIALIZATION [Serializable] #endif // FEATURE_BINARY_SERIALIZATION public class ProxyException : SshException { /// <summary> /// Initializes a new instance of the <see cref="ScpException"/> class. /// </summary> public ProxyException() { } /// <summary> /// Initializes a new instance of the <see cref="ScpException"/> class. /// </summary> /// <param name="message">The message.</param> public ProxyException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ScpException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> public ProxyException(string message, Exception innerException) : base(message, innerException) { } #if FEATURE_BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="ProxyException"/> class. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is <c>null</c>.</exception> /// <exception cref="SerializationException">The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).</exception> protected ProxyException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif // FEATURE_BINARY_SERIALIZATION } }
37.258621
146
0.633966
[ "MIT" ]
iodes/SSH.NET
src/Renci.SshNet/Common/ProxyException.cs
2,163
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ImagesDownloader.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
42.325942
167
0.579129
[ "MIT" ]
programulya/ImagesDownloader
ImagesDownloader/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs
19,089
C#
using ApiCatalogoJogos.inputModel; using ApiCatalogoJogos.Services; using ApiCatalogoJogos.ViewModel; using ApiCatalogoJogos.Entities; using ApiCatalogoJogos.Exceptions; using ApiCatalogoJogos.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ApiCatalogoJogos.Services { public class JogoService : IJogoService { private readonly IJogoRepository _jogoRepository; public JogoService(IJogoRepository jogoRepository) { _jogoRepository = jogoRepository; } public async Task<List<JogoViewModel>> Obter(int pagina, int quantidade) { var jogos = await _jogoRepository.Obter(pagina, quantidade); return jogos.Select(jogo => new JogoViewModel { Id = jogo.Id, Nome = jogo.Nome, Produtora = jogo.Produtora, Preco = jogo.Preco }) .ToList(); } public async Task<JogoViewModel> Obter(Guid id) { var jogo = await _jogoRepository.Obter(id); if (jogo == null) return null; return new JogoViewModel { Id = jogo.Id, Nome = jogo.Nome, Produtora = jogo.Produtora, Preco = jogo.Preco }; } public async Task<JogoViewModel> Inserir(JogoInputModel jogo) { var entidadeJogo = await _jogoRepository.Obter(jogo.Nome, jogo.Produtora); if (entidadeJogo.Count > 0) throw new JogoJaCadastradoException(); var jogoInsert = new Jogo { Id = Guid.NewGuid(), Nome = jogo.Nome, Produtora = jogo.Produtora, Preco = jogo.Preco }; await _jogoRepository.Inserir(jogoInsert); return new JogoViewModel { Id = jogoInsert.Id, Nome = jogo.Nome, Produtora = jogo.Produtora, Preco = jogo.Preco }; } public async Task Atualizar(Guid id, JogoInputModel jogo) { var entidadeJogo = await _jogoRepository.Obter(id); if (entidadeJogo == null) throw new JogoNaoCadastradoException(); entidadeJogo.Nome = jogo.Nome; entidadeJogo.Produtora = jogo.Produtora; entidadeJogo.Preco = jogo.Preco; await _jogoRepository.Atualizar(entidadeJogo); } public async Task Atualizar(Guid id, double preco) { var entidadeJogo = await _jogoRepository.Obter(id); if (entidadeJogo == null) throw new JogoNaoCadastradoException(); entidadeJogo.Preco = preco; await _jogoRepository.Atualizar(entidadeJogo); } public async Task Remover(Guid id) { var jogo = await _jogoRepository.Obter(id); if (jogo == null) throw new JogoNaoCadastradoException(); await _jogoRepository.Remover(id); } public void Dispose() { _jogoRepository?.Dispose(); } } }
27.561983
86
0.550525
[ "Apache-2.0" ]
braziltaiany/Bootcamp-Decola-Tech
ApiCatalogoJogos/ApiCatalogoJogos/Services/JogoService.cs
3,337
C#
using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace LinqToDB.Linq.Builder { using System; using Extensions; using LinqToDB.Expressions; using Mapping; using Common; class LoadWithBuilder : MethodCallBuilder { public static readonly string[] MethodNames = { "LoadWith", "ThenLoad", "LoadWithAsTable" }; protected override bool CanBuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { return methodCall.IsQueryable(MethodNames); } static void CheckFilterFunc(Type expectedType, Type filterType, MappingSchema mappingSchema) { var propType = expectedType; if (EagerLoading.IsEnumerableType(expectedType, mappingSchema)) propType = EagerLoading.GetEnumerableElementType(expectedType, mappingSchema); var itemType = typeof(Expression<>).IsSameOrParentOf(filterType) ? filterType.GetGenericArguments()[0].GetGenericArguments()[0].GetGenericArguments()[0] : filterType.GetGenericArguments()[0].GetGenericArguments()[0]; if (propType != itemType) throw new LinqException("Invalid filter function usage."); } protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0])); var selector = (LambdaExpression)methodCall.Arguments[1].Unwrap(); // reset LoadWith sequence if (methodCall.IsQueryable("LoadWith")) { for(;;) { if (sequence is LoadWithContext lw) sequence = lw.Context; else break; } } var path = selector.Body.Unwrap(); var table = GetTableContext(sequence, path, out var level); var associations = ExtractAssociations(builder, path, level) .Reverse() .ToArray(); if (associations.Length == 0) throw new LinqToDBException($"Unable to retrieve properties path for LoadWith/ThenLoad. Path: '{path}'"); if (methodCall.Method.Name == "ThenLoad") { if (!(table.LoadWith?.Count > 0)) throw new LinqToDBException($"ThenLoad function should be followed after LoadWith. Can not find previous property for '{path}'."); var lastPath = table.LoadWith[table.LoadWith.Count - 1]; associations = Array<LoadWithInfo>.Append(lastPath, associations); if (methodCall.Arguments.Count == 3) { var lastElement = associations[associations.Length - 1]; lastElement.FilterFunc = (Expression?)methodCall.Arguments[2]; CheckFilterFunc(lastElement.MemberInfo.GetMemberType(), lastElement.FilterFunc!.Type, builder.MappingSchema); } // append to the last member chain table.LoadWith[table.LoadWith.Count - 1] = associations; } else { if (table.LoadWith == null) table.LoadWith = new List<LoadWithInfo[]>(); if (methodCall.Arguments.Count == 3) { var lastElement = associations[associations.Length - 1]; lastElement.FilterFunc = (Expression?)methodCall.Arguments[2]; CheckFilterFunc(lastElement.MemberInfo.GetMemberType(), lastElement.FilterFunc!.Type, builder.MappingSchema); } table.LoadWith.Add(associations); } var loadWithSequence = sequence as LoadWithContext ?? new LoadWithContext(sequence, table); return loadWithSequence; } TableBuilder.TableContext GetTableContext(IBuildContext ctx, Expression path, out Expression? stopExpression) { stopExpression = null; var table = ctx as TableBuilder.TableContext; if (table != null) return table; if (ctx is LoadWithContext lwCtx) return lwCtx.TableContext; if (table == null) { var isTableResult = ctx.IsExpression(null, 0, RequestFor.Table); if (isTableResult.Result) { table = isTableResult.Context as TableBuilder.TableContext; if (table != null) return table; } } var maxLevel = path.GetLevel(ctx.Builder.MappingSchema); var level = 1; while (level <= maxLevel) { var levelExpression = path.GetLevelExpression(ctx.Builder.MappingSchema, level); var isTableResult = ctx.IsExpression(levelExpression, 1, RequestFor.Table); if (isTableResult.Result) { table = isTableResult.Context switch { TableBuilder.TableContext t => t, AssociationContext a => a.TableContext as TableBuilder.TableContext, _ => null }; if (table != null) { stopExpression = levelExpression; return table; } } ++level; } var expr = path.GetLevelExpression(ctx.Builder.MappingSchema, 0); throw new LinqToDBException( $"Unable to find table information for LoadWith. Consider moving LoadWith closer to GetTable<{expr.Type.Name}>() method."); } static IEnumerable<LoadWithInfo> ExtractAssociations(ExpressionBuilder builder, Expression expression, Expression? stopExpression) { var currentExpression = expression; while (currentExpression.NodeType == ExpressionType.Call) { var mc = (MethodCallExpression)currentExpression; if (mc.IsQueryable()) currentExpression = mc.Arguments[0]; else break; } LambdaExpression? filterExpression = null; if (currentExpression != expression) { var parameter = Expression.Parameter(currentExpression.Type, "e"); var body = expression.Replace(currentExpression, parameter); var lambda = Expression.Lambda(body, parameter); filterExpression = lambda; } foreach (var member in GetAssociations(builder, currentExpression, stopExpression)) { yield return new LoadWithInfo(member) { MemberFilter = filterExpression }; filterExpression = null; } } static IEnumerable<MemberInfo> GetAssociations(ExpressionBuilder builder, Expression expression, Expression? stopExpression) { MemberInfo? lastMember = null; for (;;) { if (stopExpression == expression) { yield break; } switch (expression.NodeType) { case ExpressionType.Parameter : if (lastMember == null) goto default; yield break; case ExpressionType.Call : { var cexpr = (MethodCallExpression)expression; if (cexpr.Method.IsSqlPropertyMethodEx()) { foreach (var assoc in GetAssociations(builder, builder.ConvertExpression(expression), stopExpression)) yield return assoc; yield break; } if (lastMember == null) goto default; var expr = cexpr.Object; if (expr == null) { if (cexpr.Arguments.Count == 0) goto default; expr = cexpr.Arguments[0]; } if (expr.NodeType != ExpressionType.MemberAccess) goto default; var member = ((MemberExpression)expr).Member; var mtype = member.GetMemberType(); if (lastMember.ReflectedType != mtype.GetItemType()) goto default; expression = expr; break; } case ExpressionType.MemberAccess : { var mexpr = (MemberExpression)expression; var member = lastMember = mexpr.Member; var attr = builder.MappingSchema.GetAttribute<AssociationAttribute>(member.ReflectedType!, member); if (attr == null) { member = mexpr.Expression.Type.GetMemberEx(member)!; attr = builder.MappingSchema.GetAttribute<AssociationAttribute>(mexpr.Expression.Type, member); } if (attr == null) throw new LinqToDBException($"Member '{expression}' is not an association."); yield return member; expression = mexpr.Expression; break; } case ExpressionType.ArrayIndex : { expression = ((BinaryExpression)expression).Left; break; } case ExpressionType.Extension : { if (expression is GetItemExpression getItemExpression) { expression = getItemExpression.Expression; break; } goto default; } case ExpressionType.Convert : { expression = ((UnaryExpression)expression).Operand; break; } default : { throw new LinqToDBException($"Expression '{expression}' is not an association."); } } } } protected override SequenceConvertInfo? Convert( ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression? param) { return null; } internal class LoadWithContext : PassThroughContext { private readonly TableBuilder.TableContext _tableContext; public TableBuilder.TableContext TableContext => _tableContext; public LoadWithContext(IBuildContext context, TableBuilder.TableContext tableContext) : base(context) { _tableContext = tableContext; } } } }
28.895238
136
0.659416
[ "MIT" ]
AndreyAndryushinPSB/linq2db
Source/LinqToDB/Linq/Builder/LoadWithBuilder.cs
8,790
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using VDS.RDF.Nodes; using VDS.RDF.Parsing; using VDS.RDF.Parsing.Contexts; using VDS.RDF.Parsing.Tokens; using VDS.RDF.Query.Aggregates.Leviathan; using VDS.RDF.Query.Aggregates.Sparql; using VDS.RDF.Query.Expressions; using VDS.RDF.Query.Expressions.Arithmetic; using VDS.RDF.Query.Expressions.Comparison; using VDS.RDF.Query.Expressions.Conditional; using VDS.RDF.Query.Expressions.Functions.Sparql; using VDS.RDF.Query.Expressions.Functions.Sparql.Boolean; using VDS.RDF.Query.Expressions.Functions.Sparql.Constructor; using VDS.RDF.Query.Expressions.Functions.Sparql.DateTime; using VDS.RDF.Query.Expressions.Functions.Sparql.Hash; using VDS.RDF.Query.Expressions.Functions.Sparql.Numeric; using VDS.RDF.Query.Expressions.Functions.Sparql.Set; using VDS.RDF.Query.Expressions.Functions.Sparql.String; using VDS.RDF.Query.Expressions.Primary; namespace VDS.RDF.Query { /// <summary> /// Internal Class which parses SPARQL Expressions into Expression Trees. /// </summary> class SparqlExpressionParser { private NamespaceMapper _nsmapper; private Uri _baseUri; private bool _allowAggregates = false; private SparqlQuerySyntax _syntax = Options.QueryDefaultSyntax; private SparqlQueryParser _parser; private IEnumerable<ISparqlCustomExpressionFactory> _factories = Enumerable.Empty<ISparqlCustomExpressionFactory>(); /// <summary> /// Creates a new SPARQL Expression Parser. /// </summary> public SparqlExpressionParser() { } /// <summary> /// Creates a new SPARQL Expression Parser which has a reference back to a Query Parser. /// </summary> /// <param name="parser">Query Parser.</param> public SparqlExpressionParser(SparqlQueryParser parser) : this(parser, false) { } /// <summary> /// Creates a new SPARQL Expression Parser. /// </summary> /// <param name="allowAggregates">Whether Aggregates are allowed in Expressions.</param> public SparqlExpressionParser(bool allowAggregates) : this(null, allowAggregates) { } /// <summary> /// Creates a new SPARQL Expression Parser which has a reference back to a Query Parser. /// </summary> /// <param name="parser">Query Parser.</param> /// <param name="allowAggregates">Whether Aggregates are allowed in Expressions.</param> public SparqlExpressionParser(SparqlQueryParser parser, bool allowAggregates) { _parser = parser; _allowAggregates = allowAggregates; } /// <summary> /// Sets the Base Uri used to resolve URIs and QNames. /// </summary> public Uri BaseUri { set { _baseUri = value; } } /// <summary> /// Sets the Namespace Map used to resolve QNames. /// </summary> public NamespaceMapper NamespaceMap { set { _nsmapper = value; } } /// <summary> /// Gets/Sets whether Aggregates are permitted in Expressions. /// </summary> public bool AllowAggregates { get { return _allowAggregates; } set { _allowAggregates = value; } } /// <summary> /// Gets/Sets the Syntax that should be supported. /// </summary> public SparqlQuerySyntax SyntaxMode { get { return _syntax; } set { _syntax = value; } } /// <summary> /// Sets the Query Parser that the Expression Parser can call back into when needed. /// </summary> public SparqlQueryParser QueryParser { set { _parser = value; } } /// <summary> /// Gets/Sets the locally scoped custom expression factories. /// </summary> public IEnumerable<ISparqlCustomExpressionFactory> ExpressionFactories { get { return _factories; } set { if (value != null) { _factories = value; } } } /// <summary> /// Parses a SPARQL Expression. /// </summary> /// <param name="tokens">Tokens that the Expression should be parsed from.</param> /// <returns></returns> public ISparqlExpression Parse(Queue<IToken> tokens) { try { return TryParseConditionalOrExpression(tokens); } catch (InvalidOperationException ex) { // The Queue was empty throw new RdfParseException("Unexpected end of Token Queue while trying to parse an Expression", ex); } } private ISparqlExpression TryParseConditionalOrExpression(Queue<IToken> tokens) { // Get the first Term in the Expression ISparqlExpression firstTerm = TryParseConditionalAndExpression(tokens); if (tokens.Count > 0) { // Expect an || Token IToken next = tokens.Dequeue(); if (next.TokenType == Token.OR) { return new OrExpression(firstTerm, TryParseConditionalOrExpression(tokens)); } else { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered while trying to parse a Conditional Or expression", next); } } else { return firstTerm; } } private ISparqlExpression TryParseConditionalAndExpression(Queue<IToken> tokens) { // Get the first Term in the Expression ISparqlExpression firstTerm = TryParseValueLogical(tokens); if (tokens.Count > 0) { // Expect an && Token IToken next = tokens.Peek(); if (next.TokenType == Token.AND) { tokens.Dequeue(); return new AndExpression(firstTerm, TryParseConditionalAndExpression(tokens)); } else { return firstTerm; // throw new RdfParseException("Unexpected Token '" + next.GetType().ToString() + "' encountered while trying to parse a Conditional And expression"); } } else { return firstTerm; } } private ISparqlExpression TryParseValueLogical(Queue<IToken> tokens) { return TryParseRelationalExpression(tokens); } private ISparqlExpression TryParseRelationalExpression(Queue<IToken> tokens) { // Get the First Term of this Expression ISparqlExpression firstTerm = TryParseNumericExpression(tokens); if (tokens.Count > 0) { IToken next = tokens.Peek(); switch (next.TokenType) { case Token.EQUALS: tokens.Dequeue(); return new EqualsExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.NOTEQUALS: tokens.Dequeue(); return new NotEqualsExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.LESSTHAN: tokens.Dequeue(); return new LessThanExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.GREATERTHAN: tokens.Dequeue(); return new GreaterThanExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.LESSTHANOREQUALTO: tokens.Dequeue(); return new LessThanOrEqualToExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.GREATERTHANOREQUALTO: tokens.Dequeue(); return new GreaterThanOrEqualToExpression(firstTerm, TryParseNumericExpression(tokens)); case Token.IN: case Token.NOTIN: return TryParseSetExpression(firstTerm, tokens); default: return firstTerm; } } else { return firstTerm; } } private ISparqlExpression TryParseNumericExpression(Queue<IToken> tokens) { return TryParseAdditiveExpression(tokens); } private ISparqlExpression TryParseAdditiveExpression(Queue<IToken> tokens) { // Get the First Term of this Expression ISparqlExpression firstTerm = TryParseMultiplicativeExpression(tokens); if (tokens.Count > 0) { IToken next = tokens.Peek(); switch (next.TokenType) { case Token.PLUS: tokens.Dequeue(); return new AdditionExpression(firstTerm, TryParseMultiplicativeExpression(tokens)); case Token.MINUS: tokens.Dequeue(); return new SubtractionExpression(firstTerm, TryParseMultiplicativeExpression(tokens)); case Token.PLAINLITERAL: return new AdditionExpression(firstTerm, TryParseMultiplicativeExpression(tokens)); default: return firstTerm; } } else { return firstTerm; } } private ISparqlExpression TryParseMultiplicativeExpression(Queue<IToken> tokens) { // Get the First Term of this Expression ISparqlExpression firstTerm = TryParseUnaryExpression(tokens); if (tokens.Count > 0) { IToken next = tokens.Peek(); switch (next.TokenType) { case Token.MULTIPLY: { tokens.Dequeue(); var rhs = TryParseMultiplicativeExpression(tokens); if (rhs is DivisionExpression) { var args = rhs.Arguments.ToList(); return new DivisionExpression(new MultiplicationExpression(firstTerm, args[0]), args[1]); } if (rhs is MultiplicationExpression) { var args = rhs.Arguments.ToList(); return new MultiplicationExpression(new MultiplicationExpression(firstTerm, args[0]), args[1]); } return new MultiplicationExpression(firstTerm, rhs); } case Token.DIVIDE: { tokens.Dequeue(); var rhs = TryParseMultiplicativeExpression(tokens); if (rhs is DivisionExpression) { var args = rhs.Arguments.ToList(); return new DivisionExpression(new DivisionExpression(firstTerm, args[0]), args[1]); } if (rhs is MultiplicationExpression) { var args = rhs.Arguments.ToList(); return new MultiplicationExpression(new DivisionExpression(firstTerm, args[0]), args[1]); } return new DivisionExpression(firstTerm, rhs); } default: return firstTerm; } } else { return firstTerm; } } private ISparqlExpression TryParseUnaryExpression(Queue<IToken> tokens) { IToken next = tokens.Peek(); switch (next.TokenType) { case Token.NEGATION: tokens.Dequeue(); return new NotExpression(TryParsePrimaryExpression(tokens)); case Token.PLUS: // Semantically Unary Plus does nothing so no special expression class for it tokens.Dequeue(); return TryParsePrimaryExpression(tokens); case Token.MINUS: tokens.Dequeue(); return new MinusExpression(TryParsePrimaryExpression(tokens)); default: return TryParsePrimaryExpression(tokens); } } private ISparqlExpression TryParsePrimaryExpression(Queue<IToken> tokens) { IToken next = tokens.Peek(); switch (next.TokenType) { case Token.LEFTBRACKET: return TryParseBrackettedExpression(tokens); case Token.ABS: case Token.BNODE: case Token.BOUND: case Token.CALL: case Token.CEIL: case Token.COALESCE: case Token.CONCAT: case Token.DATATYPEFUNC: case Token.DAY: case Token.ENCODEFORURI: case Token.EXISTS: case Token.FLOOR: case Token.HOURS: case Token.IF: case Token.IRI: case Token.ISBLANK: case Token.ISIRI: case Token.ISLITERAL: case Token.ISNUMERIC: case Token.ISURI: case Token.LANG: case Token.LANGMATCHES: case Token.LCASE: case Token.MD5: case Token.MINUTES: case Token.MONTH: case Token.NOTEXISTS: case Token.NOW: case Token.RAND: case Token.REGEX: case Token.REPLACE: case Token.ROUND: case Token.SAMETERM: case Token.SECONDS: case Token.SHA1: case Token.SHA224: case Token.SHA256: case Token.SHA384: case Token.SHA512: case Token.STR: case Token.STRAFTER: case Token.STRBEFORE: case Token.CONTAINS: case Token.STRDT: case Token.STRENDS: case Token.STRLANG: case Token.STRLEN: case Token.STRSTARTS: case Token.STRUUID: case Token.SUBSTR: case Token.TIMEZONE: case Token.TZ: case Token.UCASE: case Token.URIFUNC: case Token.UUID: case Token.YEAR: if (_syntax == SparqlQuerySyntax.Sparql_1_0 && SparqlSpecsHelper.IsFunctionKeyword11(next.Value)) throw Error("The function " + next.Value + " is not supported in SPARQL 1.0", next); return TryParseBuiltInCall(tokens); case Token.AVG: case Token.COUNT: case Token.GROUPCONCAT: case Token.MAX: case Token.MEDIAN: case Token.MIN: case Token.MODE: case Token.NMAX: case Token.NMIN: case Token.SAMPLE: case Token.SUM: if (_allowAggregates) { return TryParseAggregateExpression(tokens); } else { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, Aggregates are not permitted in this Expression or you have attempted to nest aggregates", next); } case Token.URI: case Token.QNAME: return TryParseIriRefOrFunction(tokens); case Token.LITERAL: case Token.LONGLITERAL: return TryParseRdfLiteral(tokens); case Token.PLAINLITERAL: return TryParseBooleanOrNumericLiteral(tokens); case Token.VARIABLE: tokens.Dequeue(); return new VariableTerm(next.Value); default: throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered while trying to parse a Primary Expression",next); } } private ISparqlExpression TryParseBrackettedExpression(Queue<IToken> tokens) { return TryParseBrackettedExpression(tokens, true); } private ISparqlExpression TryParseBrackettedExpression(Queue<IToken> tokens, bool requireOpeningLeftBracket) { bool temp = false; return TryParseBrackettedExpression(tokens, requireOpeningLeftBracket, out temp); } private ISparqlExpression TryParseBrackettedExpression(Queue<IToken> tokens, bool requireOpeningLeftBracket, out bool commaTerminated) { bool temp = false; return TryParseBrackettedExpression(tokens, requireOpeningLeftBracket, out commaTerminated, out temp); } private ISparqlExpression TryParseBrackettedExpression(Queue<IToken> tokens, bool requireOpeningLeftBracket, out bool commaTerminated, out bool semicolonTerminated) { IToken next; commaTerminated = false; semicolonTerminated = false; // Discard the Opening Bracket if (requireOpeningLeftBracket) { next = tokens.Dequeue(); if (next.TokenType != Token.LEFTBRACKET) { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Left Bracket to start a Bracketted Expression",next); } } int openBrackets = 1; Queue<IToken> exprTerms = new Queue<IToken>(); while (openBrackets > 0) { // Get next Token next = tokens.Peek(); // Take account of nesting if (next.TokenType == Token.LEFTBRACKET) { openBrackets++; } else if (next.TokenType == Token.RIGHTBRACKET) { openBrackets--; } else if (next.TokenType == Token.COMMA && openBrackets == 1) { openBrackets--; commaTerminated = true; } else if (next.TokenType == Token.SEMICOLON && openBrackets == 1) { openBrackets--; semicolonTerminated = true; } else if (next.TokenType == Token.DISTINCT && openBrackets == 1) { // DISTINCT can terminate the Tokens that make an expression if it occurs as the first thing and only 1 bracket is open if (tokens.Count == 0) { tokens.Dequeue(); commaTerminated = true; return new DistinctModifier(); } else { throw Error("Unexpected DISTINCT Keyword Token encountered, DISTINCT modifier keyword may only occur as the first argument to an aggregate function", next); } } if (openBrackets > 0) { exprTerms.Enqueue(next); } tokens.Dequeue(); } if (exprTerms.Count > 0) { // Recurse to invoke self return Parse(exprTerms); } else { return null; } } private ISparqlExpression TryParseBuiltInCall(Queue<IToken> tokens) { IToken next = tokens.Dequeue(); bool comma = false, first = true; List<ISparqlExpression> args; ISparqlExpression strExpr; switch (next.TokenType) { case Token.ABS: return new AbsFunction(TryParseBrackettedExpression(tokens)); case Token.BNODE: return new BNodeFunction(TryParseBrackettedExpression(tokens)); case Token.BOUND: // Expect a Left Bracket, Variable and then a Right Bracket next = tokens.Dequeue(); if (next.TokenType == Token.LEFTBRACKET) { next = tokens.Dequeue(); if (next.TokenType == Token.VARIABLE) { VariableTerm varExpr = new VariableTerm(next.Value); next = tokens.Dequeue(); if (next.TokenType == Token.RIGHTBRACKET) { return new BoundFunction(varExpr); } else { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, a Right Bracket to end a BOUND function call was expected",next); } } else { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, a Variable Token for a BOUND function call was expected", next); } } else { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, a Left Bracket to start a BOUND function call was expected", next); } case Token.CALL: if (_syntax != SparqlQuerySyntax.Extended) throw Error("The CALL keyword is only valid when using SPARQL 1.1 Extended syntax", next); args = new List<ISparqlExpression>(); do { args.Add(TryParseBrackettedExpression(tokens, first, out comma)); first = false; } while (comma); return new CallFunction(args); case Token.CEIL: return new CeilFunction(TryParseBrackettedExpression(tokens)); case Token.COALESCE: // Get as many argument expressions as we can args = new List<ISparqlExpression>(); do { args.Add(TryParseBrackettedExpression(tokens, first, out comma)); first = false; } while (comma); return new CoalesceFunction(args); case Token.CONCAT: // Get as many argument expressions as we can args = new List<ISparqlExpression>(); do { args.Add(TryParseBrackettedExpression(tokens, first, out comma)); first = false; } while (comma); return new ConcatFunction(args); case Token.CONTAINS: return new ContainsFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.DATATYPEFUNC: if (_syntax == SparqlQuerySyntax.Sparql_1_0) { return new DataTypeFunction(TryParseBrackettedExpression(tokens)); } else { return new DataType11Function(TryParseBrackettedExpression(tokens)); } case Token.DAY: return new DayFunction(TryParseBrackettedExpression(tokens)); case Token.ENCODEFORURI: return new EncodeForUriFunction(TryParseBrackettedExpression(tokens)); case Token.FLOOR: return new FloorFunction(TryParseBrackettedExpression(tokens)); case Token.HOURS: return new HoursFunction(TryParseBrackettedExpression(tokens)); case Token.IF: return new IfElseFunction(TryParseBrackettedExpression(tokens, true, out comma), TryParseBrackettedExpression(tokens, false, out comma), TryParseBrackettedExpression(tokens, false, out comma)); case Token.IRI: case Token.URIFUNC: return new IriFunction(TryParseBrackettedExpression(tokens)); case Token.ISBLANK: return new IsBlankFunction(TryParseBrackettedExpression(tokens)); case Token.ISIRI: return new IsIriFunction(TryParseBrackettedExpression(tokens)); case Token.ISLITERAL: return new IsLiteralFunction(TryParseBrackettedExpression(tokens)); case Token.ISNUMERIC: return new IsNumericFunction(TryParseBrackettedExpression(tokens)); case Token.ISURI: return new IsUriFunction(TryParseBrackettedExpression(tokens)); case Token.LANG: return new LangFunction(TryParseBrackettedExpression(tokens)); case Token.LANGMATCHES: return new LangMatchesFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.LCASE: return new LCaseFunction(TryParseBrackettedExpression(tokens)); case Token.MD5: return new MD5HashFunction(TryParseBrackettedExpression(tokens)); case Token.MINUTES: return new MinutesFunction(TryParseBrackettedExpression(tokens)); case Token.MONTH: return new MonthFunction(TryParseBrackettedExpression(tokens)); case Token.NOW: // Expect a () after the Keyword Token TryParseNoArgs(tokens, "NOW"); return new NowFunction(); case Token.RAND: // Expect a () after the Keyword Token TryParseNoArgs(tokens, "RAND"); return new RandFunction(); case Token.REGEX: return TryParseRegexExpression(tokens); case Token.REPLACE: // REPLACE may have 3/4 arguments strExpr = TryParseBrackettedExpression(tokens); ISparqlExpression patternExpr = TryParseBrackettedExpression(tokens, false); ISparqlExpression replaceExpr = TryParseBrackettedExpression(tokens, false, out comma); if (comma) { ISparqlExpression opsExpr = TryParseBrackettedExpression(tokens, false); return new ReplaceFunction(strExpr, patternExpr, replaceExpr, opsExpr); } else { return new ReplaceFunction(strExpr, patternExpr, replaceExpr); } case Token.ROUND: return new RoundFunction(TryParseBrackettedExpression(tokens)); case Token.SAMETERM: return new SameTermFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.SECONDS: return new SecondsFunction(TryParseBrackettedExpression(tokens)); case Token.SHA1: return new Sha1HashFunction(TryParseBrackettedExpression(tokens)); case Token.SHA256: return new Sha256HashFunction(TryParseBrackettedExpression(tokens)); case Token.SHA384: return new Sha384HashFunction(TryParseBrackettedExpression(tokens)); case Token.SHA512: return new Sha512HashFunction(TryParseBrackettedExpression(tokens)); case Token.STR: return new StrFunction(TryParseBrackettedExpression(tokens)); case Token.STRAFTER: return new StrAfterFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRBEFORE: return new StrBeforeFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRDT: return new StrDtFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRENDS: return new StrEndsFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRLANG: return new StrLangFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRLEN: return new StrLenFunction(TryParseBrackettedExpression(tokens)); case Token.STRSTARTS: return new StrStartsFunction(TryParseBrackettedExpression(tokens), TryParseBrackettedExpression(tokens, false)); case Token.STRUUID: TryParseNoArgs(tokens, "STRUUID"); return new StrUUIDFunction(); case Token.SUBSTR: // SUBSTR may have 2/3 arguments strExpr = TryParseBrackettedExpression(tokens); ISparqlExpression startExpr = TryParseBrackettedExpression(tokens, false, out comma); if (comma) { ISparqlExpression lengthExpr = TryParseBrackettedExpression(tokens, false); return new SubStrFunction(strExpr, startExpr, lengthExpr); } else { return new SubStrFunction(strExpr, startExpr); } case Token.TIMEZONE: return new TimezoneFunction(TryParseBrackettedExpression(tokens)); case Token.TZ: return new TZFunction(TryParseBrackettedExpression(tokens)); case Token.UCASE: return new UCaseFunction(TryParseBrackettedExpression(tokens)); case Token.UUID: TryParseNoArgs(tokens, "UUID"); return new UUIDFunction(); case Token.YEAR: return new YearFunction(TryParseBrackettedExpression(tokens)); case Token.EXISTS: case Token.NOTEXISTS: if (_syntax == SparqlQuerySyntax.Sparql_1_0) throw new RdfParseException("EXISTS/NOT EXISTS clauses are not supported in SPARQL 1.0"); if (_parser == null) throw new RdfParseException("Unable to parse an EXISTS/NOT EXISTS as there is no Query Parser to call into"); // Gather Tokens for the Pattern NonTokenisedTokenQueue temptokens = new NonTokenisedTokenQueue(); int openbrackets = 0; bool mustExist = (next.TokenType == Token.EXISTS); do { if (tokens.Count == 0) throw new RdfParseException("Unexpected end of Tokens while trying to parse an EXISTS/NOT EXISTS function"); next = tokens.Dequeue(); if (next.TokenType == Token.LEFTCURLYBRACKET) { openbrackets++; } else if (next.TokenType == Token.RIGHTCURLYBRACKET) { openbrackets--; } temptokens.Enqueue(next); } while (openbrackets > 0); // Call back into the Query Parser to try and Parse the Graph Pattern for the Function SparqlQueryParserContext tempcontext = new SparqlQueryParserContext(temptokens); tempcontext.Query.NamespaceMap.Import(_nsmapper); tempcontext.Query.BaseUri = _baseUri; return new ExistsFunction(_parser.TryParseGraphPattern(tempcontext, true), mustExist); default: throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered while trying to parse a Built-in Function call", next); } } private void TryParseNoArgs(Queue<IToken> tokens, String function) { IToken next = tokens.Dequeue(); if (next.TokenType != Token.LEFTBRACKET) throw Error("Expected a Left Bracket after a " + function + " keyword to call the " + function + "() function", next); next = tokens.Dequeue(); if (next.TokenType != Token.RIGHTBRACKET) throw Error("Expected a Right Bracket after " + function + "( since the " + function + "() function does not take any arguments", next); } private ISparqlExpression TryParseRegexExpression(Queue<IToken> tokens) { bool hasOptions = false; // Get Text and Pattern Expressions ISparqlExpression textExpr = TryParseBrackettedExpression(tokens); ISparqlExpression patternExpr = TryParseBrackettedExpression(tokens, false, out hasOptions); // Check whether we need to get an Options Expression if (hasOptions) { ISparqlExpression optionExpr = TryParseBrackettedExpression(tokens, false); return new RegexFunction(textExpr, patternExpr, optionExpr); } else { return new RegexFunction(textExpr, patternExpr); } } private ISparqlExpression TryParseIriRefOrFunction(Queue<IToken> tokens) { // Get the Uri/QName Token IToken first = tokens.Dequeue(); // Resolve the Uri Uri u; if (first.TokenType == Token.QNAME) { // Resolve QName u = UriFactory.Create(Tools.ResolveQName(first.Value, _nsmapper, _baseUri)); } else { u = UriFactory.Create(Tools.ResolveUri(first.Value, _baseUri.ToSafeString())); } // Get the Argument List (if any) if (tokens.Count > 0) { IToken next = tokens.Peek(); if (next.TokenType == Token.LEFTBRACKET) { bool comma = false, semicolon = false; List<ISparqlExpression> args = new List<ISparqlExpression>(); args.Add(TryParseBrackettedExpression(tokens, true, out comma, out semicolon)); while (comma && !semicolon) { args.Add(TryParseBrackettedExpression(tokens, false, out comma, out semicolon)); } // If there are no arguments (one null argument) then discard if (args.Count == 1 && args.First() == null) args.Clear(); // Check whether we need to parse Scalar Arguments Dictionary<String, ISparqlExpression> scalarArgs = null; if (semicolon) { if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("Arguments List terminated by a Semicolon - Arbitrary Scalar Arguments for Extension Functions/Aggregates are not permitted in SPARQL 1.1"); scalarArgs = TryParseScalarArguments(first, tokens); } // Return an Extension Function expression ISparqlExpression expr = SparqlExpressionFactory.CreateExpression(u, args, _factories); if (expr is AggregateTerm) { if (!_allowAggregates) throw new RdfParseException("Aggregate Expression '" + expr.ToString() + "' encountered but aggregates are not permitted in this Expression"); } return expr; } else { // Just an IRIRef return new ConstantTerm(new UriNode(null, u)); } } else { // Just an IRIRef return new ConstantTerm(new UriNode(null, u)); } } private ISparqlExpression TryParseRdfLiteral(Queue<IToken> tokens) { // First Token will be the String value of this RDF Literal IToken str = tokens.Dequeue(); // Might have a Language Specifier/DataType afterwards if (tokens.Count > 0) { IToken next = tokens.Peek(); if (next.TokenType == Token.LANGSPEC) { tokens.Dequeue(); return new ConstantTerm(new LiteralNode(null, str.Value, next.Value)); } else if (next.TokenType == Token.HATHAT) { tokens.Dequeue(); // Should be a DataTypeToken afterwards next = tokens.Dequeue(); LiteralWithDataTypeToken dtlit = new LiteralWithDataTypeToken(str, (DataTypeToken)next); ; Uri u; if (next.Value.StartsWith("<")) { u = UriFactory.Create(next.Value.Substring(1, next.Value.Length - 2)); } else { // Resolve the QName u = UriFactory.Create(Tools.ResolveQName(next.Value, _nsmapper, _baseUri)); } if (SparqlSpecsHelper.GetNumericTypeFromDataTypeUri(u) != SparqlNumericType.NaN) { // Should be a Number return TryParseNumericLiteral(dtlit, tokens, false); } else if (XmlSpecsHelper.XmlSchemaDataTypeBoolean.Equals(u.AbsoluteUri)) { // Appears to be a Boolean bool b; if (Boolean.TryParse(dtlit.Value, out b)) { return new ConstantTerm(new BooleanNode(null, b)); } else { return new ConstantTerm(new StringNode(null, dtlit.Value, dtlit.DataType)); } } else { // Just a datatyped Literal Node return new ConstantTerm(new LiteralNode(null, str.Value, u)); } } else { return new ConstantTerm(new LiteralNode(null, str.Value)); } } else { return new ConstantTerm(new LiteralNode(null, str.Value)); } } private ISparqlExpression TryParseBooleanOrNumericLiteral(Queue<IToken> tokens) { // First Token must be a Plain Literal IToken lit = tokens.Dequeue(); if (lit.Value.Equals("true")) { return new ConstantTerm(new BooleanNode(null, true)); } else if (lit.Value.Equals("false")) { return new ConstantTerm(new BooleanNode(null, false)); } else { return TryParseNumericLiteral(lit, tokens, true); } } private ISparqlExpression TryParseNumericLiteral(IToken literal, Queue<IToken> tokens, bool requireValidLexicalForm) { switch (literal.TokenType) { case Token.PLAINLITERAL: // Use Regular Expressions to see what type it is if (SparqlSpecsHelper.IsInteger(literal.Value)) { return new ConstantTerm(new LongNode(null, Int64.Parse(literal.Value))); } else if (SparqlSpecsHelper.IsDecimal(literal.Value)) { return new ConstantTerm(new DecimalNode(null, Decimal.Parse(literal.Value, NumberStyles.Any, CultureInfo.InvariantCulture))); } else if (SparqlSpecsHelper.IsDouble(literal.Value)) { return new ConstantTerm(new DoubleNode(null, Double.Parse(literal.Value, NumberStyles.Any, CultureInfo.InvariantCulture))); } else { throw Error("The Plain Literal '" + literal.Value + "' is not a valid Integer, Decimal or Double", literal); } case Token.LITERALWITHDT: // Get the Data Type Uri String dt = ((LiteralWithDataTypeToken)literal).DataType; String dtUri; if (dt.StartsWith("<")) { String baseUri = (_baseUri == null) ? String.Empty : _baseUri.AbsoluteUri; dtUri = Tools.ResolveUri(dt.Substring(1, dt.Length - 2), baseUri); } else { dtUri = Tools.ResolveQName(dt, _nsmapper, _baseUri); } // Try to return a numeric expression, enforce the need for a valid numeric value where relevant LiteralNode lit = new LiteralNode(null, literal.Value, UriFactory.Create(dtUri)); IValuedNode value = lit.AsValuedNode(); if (requireValidLexicalForm && value.NumericType == SparqlNumericType.NaN) { throw Error("The Literal '" + literal.Value + "' with Datatype URI '" + dtUri + "' is not a valid Integer, Decimal or Double", literal); } else { return new ConstantTerm(value); } case Token.LITERAL: // Check if there's a Datatype following the Literal if (tokens.Count > 0) { IToken next = tokens.Peek(); if (next.TokenType == Token.HATHAT) { tokens.Dequeue(); // Should now see a DataTypeToken DataTypeToken datatype = (DataTypeToken)tokens.Dequeue(); LiteralWithDataTypeToken dtlit = new LiteralWithDataTypeToken(literal, datatype); // Self-recurse to save replicating code return TryParseNumericLiteral(dtlit, tokens, true); } } // Use Regex to see if it's a Integer/Decimal/Double if (SparqlSpecsHelper.IsInteger(literal.Value)) { return new ConstantTerm(new LongNode(null, Int64.Parse(literal.Value))); } else if (SparqlSpecsHelper.IsDecimal(literal.Value)) { return new ConstantTerm(new DecimalNode(null, Decimal.Parse(literal.Value))); } else if (SparqlSpecsHelper.IsDouble(literal.Value)) { return new ConstantTerm(new DoubleNode(null, Double.Parse(literal.Value))); } else { // Otherwise treat as a Node Expression throw Error("The Literal '" + literal.Value + "' is not a valid Integer, Decimal or Double", literal); } default: throw Error("Unexpected Token '" + literal.GetType().ToString() + "' encountered while trying to parse a Numeric Literal", literal); } } private ISparqlExpression TryParseAggregateExpression(Queue<IToken> tokens) { if (_syntax == SparqlQuerySyntax.Sparql_1_0) throw new RdfParseException("Aggregates are not permitted in SPARQL 1.0"); IToken agg = tokens.Dequeue(); ISparqlExpression aggExpr = null; bool distinct = false, all = false; bool scalarArgs = false; // Turn off aggregate allowance since aggregates may not be nested bool aggsAllowed = _allowAggregates; _allowAggregates = false; // Expect a Left Bracket next IToken next = tokens.Dequeue(); if (next.TokenType != Token.LEFTBRACKET) { throw Error("Unexpected Token '" + next.GetType().ToString() + "', expected a Left Bracket after an Aggregate Keyword", next); } // Then a possible DISTINCT/ALL next = tokens.Peek(); if (next.TokenType == Token.DISTINCT) { distinct = true; tokens.Dequeue(); } next = tokens.Peek(); if (next.TokenType == Token.ALL || next.TokenType == Token.MULTIPLY) { all = true; tokens.Dequeue(); } next = tokens.Peek(); // If we've seen an ALL then we need the closing bracket if (all && next.TokenType != Token.RIGHTBRACKET) { throw Error("Unexpected Token '" + next.GetType().ToString() + "', expected a Right Bracket after the * specifier in an aggregate to terminate the aggregate", next); } else if (all && agg.TokenType != Token.COUNT) { throw new RdfQueryException("Cannot use the * specifier in aggregates other than COUNT"); } else if (!all) { // If it's not an all then we expect some expression(s) // Gather the Tokens and parse the Expression Queue<IToken> subtokens = new Queue<IToken>(); int openBrackets = 1; List<ISparqlExpression> expressions = new List<ISparqlExpression>(); while (openBrackets > 0) { subtokens = new Queue<IToken>(); next = tokens.Dequeue(); do { if (next.TokenType == Token.LEFTBRACKET) { openBrackets++; } else if (next.TokenType == Token.RIGHTBRACKET) { openBrackets--; } else if (next.TokenType == Token.COMMA) { // If we see a comma when we only have 1 bracket open then it is separating argument expressions if (openBrackets == 1) { break; } } else if (next.TokenType == Token.SEMICOLON) { // If we see a semicolon when we only have 1 bracket open then this indicates we have scalar arguments in-use if (openBrackets == 1) { scalarArgs = true; break; } } if (openBrackets > 0) { subtokens.Enqueue(next); next = tokens.Dequeue(); } } while (openBrackets > 0); // Parse this expression and add to the list of expressions we're concatenating expressions.Add(Parse(subtokens)); // Once we've hit the ; for the scalar arguments then we can stop looking for expressions if (scalarArgs) break; // If we've hit a , then openBrackets will still be one and we'll go around again looking for another expression // Otherwise we've reached the end of the aggregate and there was no ; for scalar arguments } if (expressions.Count == 0) throw new RdfParseException("Aggregate must have at least one argument expression unless they are a COUNT(*)"); if (expressions.Count > 1) throw new RdfParseException("The " + agg.Value + " aggregate does not support more than one argument expression"); aggExpr = expressions.First(); } else { tokens.Dequeue(); } // If the aggregate uses scalar arguments then we'll parse them here Dictionary<String, ISparqlExpression> scalarArguments = new Dictionary<string, ISparqlExpression>(); if (scalarArgs) { scalarArguments = TryParseScalarArguments(agg, tokens); } // Reset Aggregate Allowance _allowAggregates = aggsAllowed; // Now we need to generate the actual expression switch (agg.TokenType) { case Token.AVG: // AVG Aggregate if (aggExpr is VariableTerm) { return new AggregateTerm(new AverageAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new AverageAggregate(aggExpr, distinct)); } case Token.COUNT: // COUNT Aggregate if (all) { if (distinct) { return new AggregateTerm(new CountAllDistinctAggregate()); } else { return new AggregateTerm(new CountAllAggregate()); } } else if (aggExpr is VariableTerm) { if (distinct) { return new AggregateTerm(new CountDistinctAggregate((VariableTerm)aggExpr)); } else { return new AggregateTerm(new CountAggregate((VariableTerm)aggExpr)); } } else { if (distinct) { return new AggregateTerm(new CountDistinctAggregate(aggExpr)); } else { return new AggregateTerm(new CountAggregate(aggExpr)); } } case Token.GROUPCONCAT: if (scalarArgs) { if (!scalarArguments.ContainsKey(SparqlSpecsHelper.SparqlKeywordSeparator)) throw new RdfParseException("The GROUP_CONCAT aggregate has Scalar Arguments but does not have the expected SEPARATOR argument"); return new AggregateTerm(new GroupConcatAggregate(aggExpr, scalarArguments[SparqlSpecsHelper.SparqlKeywordSeparator], distinct)); } else { return new AggregateTerm(new GroupConcatAggregate(aggExpr, distinct)); } case Token.MAX: // MAX Aggregate if (aggExpr is VariableTerm) { return new AggregateTerm(new MaxAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new MaxAggregate(aggExpr, distinct)); } case Token.MEDIAN: // MEDIAN Aggregate if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("The MEDIAN aggregate is only supported when the Syntax is set to Extended."); if (aggExpr is VariableTerm) { return new AggregateTerm(new MedianAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new MedianAggregate(aggExpr, distinct)); } case Token.MIN: // MIN Aggregate if (aggExpr is VariableTerm) { return new AggregateTerm(new MinAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new MinAggregate(aggExpr, distinct)); } case Token.MODE: // MODE Aggregate if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("The MODE aggregate is only supported when the Syntax is set to Extended."); if (aggExpr is VariableTerm) { return new AggregateTerm(new ModeAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new ModeAggregate(aggExpr, distinct)); } case Token.NMAX: // NMAX Aggregate if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("The NMAX (Numeric Maximum) aggregate is only supported when the Syntax is set to Extended. To achieve an equivalent result in SPARQL 1.0/1.1 apply a FILTER to your query so the aggregated variable is only literals of the desired numeric type"); if (aggExpr is VariableTerm) { return new AggregateTerm(new NumericMaxAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new NumericMaxAggregate(aggExpr, distinct)); } case Token.NMIN: // NMIN Aggregate if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("The NMIN (Numeric Minimum) aggregate is only supported when the Syntax is set to Extended. To achieve an equivalent result in SPARQL 1.0/1.1 apply a FILTER to your query so the aggregated variable is only literals of the desired numeric type"); if (aggExpr is VariableTerm) { return new AggregateTerm(new NumericMinAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new NumericMinAggregate(aggExpr, distinct)); } case Token.SAMPLE: // SAMPLE Aggregate if (distinct) throw new RdfParseException("DISTINCT modifier is not valid for the SAMPLE aggregate"); return new AggregateTerm(new SampleAggregate(aggExpr)); case Token.SUM: // SUM Aggregate if (aggExpr is VariableTerm) { return new AggregateTerm(new SumAggregate((VariableTerm)aggExpr, distinct)); } else { return new AggregateTerm(new SumAggregate(aggExpr, distinct)); } default: // Should have already handled this but have to have it to keep the compiler happy throw Error("Cannot parse an Aggregate since '" + agg.GetType().ToString() + "' is not an Aggregate Keyword Token", agg); } } private Dictionary<String, ISparqlExpression> TryParseScalarArguments(IToken funcToken, Queue<IToken> tokens) { // Parse the Scalar Arguments Dictionary<String, ISparqlExpression> scalarArguments = new Dictionary<string, ISparqlExpression>(); IToken next; Queue<IToken> subtokens = new Queue<IToken>(); int openBrackets = 1; while (openBrackets > 0) { // First expect a Keyword/QName/URI for the Scalar Argument Name String argName; next = tokens.Peek(); switch (next.TokenType) { case Token.SEPARATOR: if (funcToken.TokenType == Token.GROUPCONCAT) { // OK argName = SparqlSpecsHelper.SparqlKeywordSeparator; } else { throw Error("The SEPARATOR scalar argument is only valid with the GROUP_CONCAT aggregate", next); } break; case Token.QNAME: case Token.URI: if (_syntax != SparqlQuerySyntax.Extended) throw new RdfParseException("Arbitrary Scalar Arguments for Aggregates are not permitted in SPARQL 1.1"); // Resolve QName/URI if (next.TokenType == Token.QNAME) { argName = Tools.ResolveQName(next.Value, _nsmapper, _baseUri); } else { argName = Tools.ResolveUri(next.Value, _baseUri.ToSafeString()); } break; default: throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Keyword/QName/URI for the Scalar Argument Name", next); } tokens.Dequeue(); // After the Argument Name need an = next = tokens.Peek(); if (next.TokenType != Token.EQUALS) { throw Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a = after a Scalar Argument name in an aggregate", next); } tokens.Dequeue(); // Get the subtokens for the Argument Expression next = tokens.Dequeue(); do { if (next.TokenType == Token.LEFTBRACKET) { openBrackets++; } else if (next.TokenType == Token.RIGHTBRACKET) { openBrackets--; } else if (next.TokenType == Token.COMMA) { // If we see a COMMA and there is only 1 bracket open then expect another argument if (openBrackets == 1) { break; } } // If not the end bracket then add it to the subtokens if (openBrackets > 0) { subtokens.Enqueue(next); next = tokens.Dequeue(); } } while (openBrackets > 0); // Parse the Subtokens into the Argument Expression if (scalarArguments.ContainsKey(argName)) { scalarArguments[argName] = Parse(subtokens); } else { scalarArguments.Add(argName, Parse(subtokens)); } } return scalarArguments; } private ISparqlExpression TryParseSetExpression(ISparqlExpression expr, Queue<IToken> tokens) { IToken next = tokens.Dequeue(); bool inSet = (next.TokenType == Token.IN); List<ISparqlExpression> expressions = new List<ISparqlExpression>(); // Expecting a ( afterwards next = tokens.Dequeue(); if (next.TokenType == Token.LEFTBRACKET) { next = tokens.Peek(); if (next.TokenType == Token.RIGHTBRACKET) { tokens.Dequeue(); } else { bool comma = false; expressions.Add(TryParseBrackettedExpression(tokens, false, out comma)); while (comma) { expressions.Add(TryParseBrackettedExpression(tokens, false, out comma)); } } } else { throw Error("Expected a left bracket to start the set of values for an IN/NOT IN expression", next); } if (inSet) { return new InFunction(expr, expressions); } else { return new NotInFunction(expr, expressions); } } /// <summary> /// Helper method for raising informative standardised Parser Errors. /// </summary> /// <param name="msg">The Error Message.</param> /// <param name="t">The Token that is the cause of the Error.</param> /// <returns></returns> private RdfParseException Error(String msg, IToken t) { StringBuilder output = new StringBuilder(); output.Append("["); output.Append(t.GetType().ToString()); output.Append(" at Line "); output.Append(t.StartLine); output.Append(" Column "); output.Append(t.StartPosition); output.Append(" to Line "); output.Append(t.EndLine); output.Append(" Column "); output.Append(t.EndPosition); output.Append("]\n"); output.Append(msg); return new RdfParseException(output.ToString(), t); } } }
42.680386
337
0.500196
[ "MIT" ]
blackwork/dotnetrdf
Libraries/dotNetRDF/Query/SPARQLExpressionParser.cs
66,368
C#
// Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com) // // This file is part of the Health extension for Unity. Licensed under the MIT // license. See LICENSE file in the project root folder. using UnityEditor; using UnityEngine; namespace HealthEx.DamageComponent { [CustomEditor(typeof (Damage))] [CanEditMultipleObjects] public sealed class DamageEditor : Editor { #region FIELDS private Damage Script { get; set; } #endregion FIELDS #region SERIALIZED PROPERTIES private SerializedProperty damageValue; private SerializedProperty description; #endregion SERIALIZED PROPERTIES #region UNITY MESSAGES public override void OnInspectorGUI() { serializedObject.Update(); DrawVersionLabel(); DrawDescriptionTextArea(); EditorGUILayout.Space(); DrawDamageValueField(); serializedObject.ApplyModifiedProperties(); } private void OnEnable() { Script = (Damage) target; description = serializedObject.FindProperty("description"); damageValue = serializedObject.FindProperty("damageValue"); } #endregion UNITY MESSAGES #region INSPECTOR CONTROLS private void DrawDamageValueField() { EditorGUILayout.PropertyField( damageValue, new GUIContent( "Damage", "Damage value.")); } private void DrawDescriptionTextArea() { description.stringValue = EditorGUILayout.TextArea( description.stringValue); } private void DrawVersionLabel() { EditorGUILayout.LabelField( string.Format( "{0} ({1})", Damage.Version, Damage.Extension)); } #endregion INSPECTOR CONTROLS #region METHODS [MenuItem("Component/Health/Damage")] private static void AddEntryToComponentMenu() { if (Selection.activeGameObject != null) { Selection.activeGameObject.AddComponent(typeof (Damage)); } } #endregion METHODS } }
25.988636
78
0.590293
[ "MIT" ]
bartlomiejwolk/Health
DamageComponent/Editor/DamageEditor.cs
2,289
C#
/* Problem: https://www.hackerrank.com/challenges/camelcase/problem C# Language Version: 6.0 .Net Framework Version: 4.7 Tool Version : Visual Studio Community 2017 Thoughts : 1. Keep a counter initialized at 1. 2. We need to iterate the entire string chracter by character. Increment the counter by 1 everytime you encounter an upper case character in the string. We're using .NET's built-in method char.IsUpper to check whether the current character is an upper case character or not. This is an O(1) operation. We can also keep a dictionary (HashSet in C# is best fit as we need to store only keys) to check it in O(1) time. Time Complexity: O(n) Space Complexity: O(1) //dynamically allocated variables are fixed for any length of input. */ using System; class Solution { private static int CamelCase() { var wordCount = 1; var nextChar = Console.Read(); //This is a special condition for hacker rank execution environment //while running it in Visual Studio I was comparing it with 13 which is the ASCII code of enter key. while (nextChar != -1) { if (char.IsUpper((char)nextChar)) wordCount++; nextChar = Console.Read(); } return wordCount; } static void Main(string[] args) { var result = CamelCase(); Console.WriteLine(result); } }
34.090909
123
0.626667
[ "MIT" ]
4ngelica/HackerRank
Algorithms/Strings/camelCase/Solution.cs
1,500
C#
using System; using System.Linq; using System.Threading.Tasks; using Abp.Dependency; namespace TestProject.Authentication.External { public class ExternalAuthManager : IExternalAuthManager, ITransientDependency { private readonly IExternalAuthConfiguration _externalAuthConfiguration; private readonly IIocResolver _iocResolver; public ExternalAuthManager(IIocResolver iocResolver, IExternalAuthConfiguration externalAuthConfiguration) { _iocResolver = iocResolver; _externalAuthConfiguration = externalAuthConfiguration; } public Task<bool> IsValidUser(string provider, string providerKey, string providerAccessCode) { using (var providerApi = CreateProviderApi(provider)) { return providerApi.Object.IsValidUser(providerKey, providerAccessCode); } } public Task<ExternalAuthUserInfo> GetUserInfo(string provider, string accessCode) { using (var providerApi = CreateProviderApi(provider)) { return providerApi.Object.GetUserInfo(accessCode); } } public IDisposableDependencyObjectWrapper<IExternalAuthProviderApi> CreateProviderApi(string provider) { var providerInfo = _externalAuthConfiguration.Providers.FirstOrDefault(p => p.Name == provider); if (providerInfo == null) throw new Exception("Unknown external auth provider: " + provider); var providerApi = _iocResolver.ResolveAsDisposable<IExternalAuthProviderApi>(providerInfo.ProviderApiType); providerApi.Object.Initialize(providerInfo); return providerApi; } } }
38.666667
119
0.69023
[ "MIT" ]
antboj/TestProject
aspnet-core/src/TestProject.Web.Core/Authentication/External/ExternalAuthManager.cs
1,742
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using Microsoft.Dynamics365.UIAutomation.Api; using Microsoft.Dynamics365.UIAutomation.Browser; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Security; namespace Microsoft.Dynamics365.UIAutomation.Sample.Web { [TestClass] public class DuplicateDetection { private readonly SecureString _username = System.Configuration.ConfigurationManager.AppSettings["OnlineUsername"].ToSecureString(); private readonly SecureString _password = System.Configuration.ConfigurationManager.AppSettings["OnlinePassword"].ToSecureString(); private readonly Uri _xrmUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["OnlineCrmUrl"].ToString()); [TestMethod] public void WEBTestDuplicateDetection() { using (var xrmBrowser = new Api.Browser(TestSettings.Options)) { xrmBrowser.LoginPage.Login(_xrmUri, _username, _password); xrmBrowser.GuidedHelp.CloseGuidedHelp(); xrmBrowser.Navigation.OpenSubArea("Sales", "Leads"); xrmBrowser.Grid.SwitchView("All Leads"); xrmBrowser.CommandBar.ClickCommand("New"); List<Field> fields = new List<Field> { new Field() {Id = "firstname", Value = "Test"}, new Field() {Id = "lastname", Value = "Lead"} }; xrmBrowser.ThinkTime(2000); xrmBrowser.Entity.SetValue("subject", "Test API Lead"); xrmBrowser.Entity.SetValue(new CompositeControl() { Id = "fullname", Fields = fields }); xrmBrowser.Entity.SetValue("mobilephone", "555-555-5555"); xrmBrowser.Entity.SetValue("description", "Test lead creation with API commands"); xrmBrowser.Entity.SetValue("emailaddress1", "test@contoso.com"); xrmBrowser.CommandBar.ClickCommand("Save"); xrmBrowser.ThinkTime(2000); xrmBrowser.Dialogs.DuplicateDetection(true); xrmBrowser.ThinkTime(2000); } } } }
39.644068
140
0.624626
[ "MIT" ]
operep/Easy-Repro-Example
Microsoft.Dynamics365.UIAutomation.Sample/Web/Dialogs/DuplicateDetection.cs
2,341
C#
/* Copyright 2017 Cimpress Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Linq; namespace VP.FF.PT.Common.Infrastructure { /// <summary> /// Removes all non digit characters from input string. /// </summary> public static class StringExtensions { public static string ToDigitsOnly(this string input) { return new String(input.Where(char.IsDigit).ToArray()); } /// <summary> /// Increases any number within the string even if it's mixed with non digit characters. /// </summary> /// <remarks> /// E.g. the input string "A105-X" will return "A106-X". /// </remarks> /// <returns></returns> public static string IncreaseAnyNumber(this string input) { bool alreadyIncreased = false; int i = input.Length - 1; string result = string.Empty; while (i >= 0) { char character = input[i]; if (!alreadyIncreased && char.IsDigit(character)) { int digit = (int)Char.GetNumericValue(character); if (digit == 9) { digit = 0; } else { alreadyIncreased = true; ++digit; } result = digit + result; } else { result = character + result; } --i; } return result; } } }
28.866667
96
0.525635
[ "Apache-2.0" ]
sizilium/Mosaic.Infrastructure
src/Infrastructure/StringExtensions.cs
2,165
C#
using System; using System.Data; using System.Web.Security; using umbraco.BusinessLogic; using umbraco.DataLayer; using umbraco.BasePages; using Umbraco.Core.IO; using umbraco.cms.businesslogic.member; namespace umbraco { public class MemberTypeTasks : interfaces.ITaskReturnUrl { private string _alias; private int _parentID; private int _typeID; private int _userID; public int UserId { set { _userID = value; } } public int TypeID { set { _typeID = value; } get { return _typeID; } } public string Alias { set { _alias = value; } get { return _alias; } } public int ParentID { set { _parentID = value; } get { return _parentID; } } public bool Save() { int id = cms.businesslogic.member.MemberType.MakeNew(BusinessLogic.User.GetUser(_userID), Alias).Id; m_returnUrl = string.Format("members/EditMemberType.aspx?id={0}", id); return true; } public bool Delete() { new cms.businesslogic.member.MemberType(_parentID).delete(); return true; } public MemberTypeTasks() { // // TODO: Add constructor logic here // } #region ITaskReturnUrl Members private string m_returnUrl = ""; public string ReturnUrl { get { return m_returnUrl; } } #endregion } }
22.77027
113
0.512166
[ "MIT" ]
gildebrand/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/create/MemberTypeTasks.cs
1,685
C#
using GraphQL.Types; namespace GraphQL.Relay.Types { public class QueryGraphType : ObjectGraphType { public QueryGraphType() { Name = "Query"; Field<NodeInterface>() .Name("node") .Description("Fetches an object given its global Id") .Argument<NonNullGraphType<IdGraphType>>("id", "The global Id of the object") .Resolve(ResolveObjectFromGlobalId); } private object ResolveObjectFromGlobalId(ResolveFieldContext<object> context) { var globalId = context.GetArgument<string>("id"); var parts = Node.FromGlobalId(globalId); var node = (IRelayNode<object>) context.Schema.FindType(parts.Type); return node.GetById(parts.Id); } } }
29.607143
93
0.587455
[ "MIT" ]
BillBaird/relay
src/GraphQL.Relay/Types/QueryGraphType.cs
831
C#
using TheBitCave.MMToolsExtensions.AI.Graph; using UnityEditor; using XNodeEditor; namespace TheBitCave.TopDownEngineExensions.AI.Graph { [CustomNodeEditor(typeof(AIDecisionDetectTargetRadius3DNode))] public class AIDecisionDetectTargetRadius3DNodeEditor : AIDecisionNodeEditor { private SerializedProperty _radius; private SerializedProperty _detectionOriginOffset; private SerializedProperty _targetLayerMask; private SerializedProperty _obstacleMask; private SerializedProperty _targetCheckFrequency; private SerializedProperty _canTargetSelf; protected override void SerializeAdditionalProperties() { _radius = serializedObject.FindProperty("radius"); _detectionOriginOffset = serializedObject.FindProperty("detectionOriginOffset"); _targetLayerMask = serializedObject.FindProperty("targetLayerMask"); _obstacleMask = serializedObject.FindProperty("obstacleMask"); _targetCheckFrequency = serializedObject.FindProperty("targetCheckFrequency"); _canTargetSelf = serializedObject.FindProperty("canTargetSelf"); serializedObject.Update(); EditorGUIUtility.labelWidth = 150; NodeEditorGUILayout.PropertyField(_radius); NodeEditorGUILayout.PropertyField(_detectionOriginOffset); NodeEditorGUILayout.PropertyField(_targetLayerMask); NodeEditorGUILayout.PropertyField(_obstacleMask); NodeEditorGUILayout.PropertyField(_targetCheckFrequency); NodeEditorGUILayout.PropertyField(_canTargetSelf); serializedObject.ApplyModifiedProperties(); } } }
46.459459
92
0.734148
[ "MIT" ]
ko1nkgw/ai-brain-extensions-for-topdown-engine
Common/Scripts/AI/Graph/Decisions/Editor/AIDecisionDetectTargetRadius3DNodeEditor.cs
1,721
C#
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator}) // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Commvault.Powershell.Models { using Commvault.Powershell.Runtime.PowerShell; /// <summary>Create a hypervisor group with Google Cloud as the destination vendor</summary> [System.ComponentModel.TypeConverter(typeof(CreateHypervisorGroupXenTypeConverter))] public partial class CreateHypervisorGroupXen { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Commvault.Powershell.Models.CreateHypervisorGroupXen" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal CreateHypervisorGroupXen(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).HypervisorType = (string) content.GetValueForProperty("HypervisorType",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).HypervisorType, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).ServerName = (string) content.GetValueForProperty("ServerName",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).ServerName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).UserName = (string) content.GetValueForProperty("UserName",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).UserName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).Password = (string) content.GetValueForProperty("Password",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).Password, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsId = (int?) content.GetValueForProperty("CredentialsId",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsName = (string) content.GetValueForProperty("CredentialsName",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Credentials = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("Credentials",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Credentials, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Name = (string) content.GetValueForProperty("Name",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Name, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).SkipCredentialValidation = (bool?) content.GetValueForProperty("SkipCredentialValidation",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).SkipCredentialValidation, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).AccessNodes = (Commvault.Powershell.Models.IIdName[]) content.GetValueForProperty("AccessNodes",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).AccessNodes, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.IIdName>(__y, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom)); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Commvault.Powershell.Models.CreateHypervisorGroupXen" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal CreateHypervisorGroupXen(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).HypervisorType = (string) content.GetValueForProperty("HypervisorType",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).HypervisorType, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).ServerName = (string) content.GetValueForProperty("ServerName",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).ServerName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).UserName = (string) content.GetValueForProperty("UserName",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).UserName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).Password = (string) content.GetValueForProperty("Password",((Commvault.Powershell.Models.ICreateHypervisorGroupXenInternal)this).Password, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsId = (int?) content.GetValueForProperty("CredentialsId",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsName = (string) content.GetValueForProperty("CredentialsName",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).CredentialsName, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Credentials = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("Credentials",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Credentials, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Name = (string) content.GetValueForProperty("Name",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).Name, global::System.Convert.ToString); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).SkipCredentialValidation = (bool?) content.GetValueForProperty("SkipCredentialValidation",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).SkipCredentialValidation, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).AccessNodes = (Commvault.Powershell.Models.IIdName[]) content.GetValueForProperty("AccessNodes",((Commvault.Powershell.Models.ICreateHypervisorGroupReqInternal)this).AccessNodes, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.IIdName>(__y, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom)); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Commvault.Powershell.Models.CreateHypervisorGroupXen" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Commvault.Powershell.Models.ICreateHypervisorGroupXen" />. /// </returns> public static Commvault.Powershell.Models.ICreateHypervisorGroupXen DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new CreateHypervisorGroupXen(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Commvault.Powershell.Models.CreateHypervisorGroupXen" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Commvault.Powershell.Models.ICreateHypervisorGroupXen" />. /// </returns> public static Commvault.Powershell.Models.ICreateHypervisorGroupXen DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new CreateHypervisorGroupXen(content); } /// <summary> /// Creates a new instance of <see cref="CreateHypervisorGroupXen" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Commvault.Powershell.Models.ICreateHypervisorGroupXen FromJsonString(string jsonText) => FromJson(Commvault.Powershell.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Commvault.Powershell.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Create a hypervisor group with Google Cloud as the destination vendor [System.ComponentModel.TypeConverter(typeof(CreateHypervisorGroupXenTypeConverter))] public partial interface ICreateHypervisorGroupXen { } }
86.157895
410
0.742593
[ "MIT" ]
Commvault/CVPowershellSDKV2
generated/api/Models/CreateHypervisorGroupXen.PowerShell.cs
13,096
C#
using GigHub.Models; using System.Collections.Generic; namespace GigHub.ViewModels { public class FolloweesViewModel { public List<ApplicationUser> Artists { get; set; } } }
19.5
58
0.707692
[ "MIT" ]
gspolima/GigHub
GigHub/ViewModels/FolloweesViewModel.cs
197
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Collections.Specialized; using System.Security.Claims; using System.Threading.Tasks; using FluentAssertions; using IdentityServer.UnitTests.Common; using IdentityServer4; using IdentityServer4.Configuration; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Stores; using IdentityServer4.Validation; using Xunit; namespace IdentityServer.UnitTests.Validation.EndSessionRequestValidation { public class EndSessionRequestValidatorTests { private EndSessionRequestValidator _subject; private IdentityServerOptions _options; private StubTokenValidator _stubTokenValidator = new StubTokenValidator(); private StubRedirectUriValidator _stubRedirectUriValidator = new StubRedirectUriValidator(); private MockHttpContextAccessor _context = new MockHttpContextAccessor(); private MockUserSession _userSession = new MockUserSession(); private MockMessageStore<EndSession> _mockEndSessionMessageStore = new MockMessageStore<EndSession>(); private InMemoryClientStore _clientStore; private ClaimsPrincipal _user; public EndSessionRequestValidatorTests() { _user = new IdentityServerUser("alice").CreatePrincipal(); _clientStore = new InMemoryClientStore(new Client[0]); _options = TestIdentityServerOptions.Create(); _subject = new EndSessionRequestValidator( _context, _options, _stubTokenValidator, _stubRedirectUriValidator, _userSession, _clientStore, _mockEndSessionMessageStore, TestLogger.Create<EndSessionRequestValidator>()); } [Fact] public async Task anonymous_user_when_options_require_authenticated_user_should_return_error() { _options.Authentication.RequireAuthenticatedUserForSignOutMessage = true; var parameters = new NameValueCollection(); var result = await _subject.ValidateAsync(parameters, null); result.IsError.Should().BeTrue(); result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal()); result.IsError.Should().BeTrue(); result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(new ClaimsIdentity())); result.IsError.Should().BeTrue(); } [Fact] public async Task valid_params_should_return_success() { _stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult() { IsError = false, Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) }, Client = new Client() { ClientId = "client"} }; _stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true; var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); parameters.Add("post_logout_redirect_uri", "http://client/signout-cb"); parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeFalse(); result.ValidatedRequest.Client.ClientId.Should().Be("client"); result.ValidatedRequest.PostLogOutUri.Should().Be("http://client/signout-cb"); result.ValidatedRequest.State.Should().Be("foo"); result.ValidatedRequest.Subject.GetSubjectId().Should().Be(_user.GetSubjectId()); } [Fact] public async Task no_post_logout_redirect_uri_should_use_single_registered_uri() { _stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult() { IsError = false, Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) }, Client = new Client() { ClientId = "client1", PostLogoutRedirectUris = new List<string> { "foo" } } }; _stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true; var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeFalse(); result.ValidatedRequest.PostLogOutUri.Should().Be("foo"); } [Fact] public async Task no_post_logout_redirect_uri_should_not_use_multiple_registered_uri() { _stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult() { IsError = false, Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) }, Client = new Client() { ClientId = "client1", PostLogoutRedirectUris = new List<string> { "foo", "bar" } } }; _stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true; var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeFalse(); result.ValidatedRequest.PostLogOutUri.Should().BeNull(); } [Fact] public async Task post_logout_uri_fails_validation_should_not_honor_logout_uri() { _stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult() { IsError = false, Claims = new Claim[] { new Claim("sub", _user.GetSubjectId()) }, Client = new Client() { ClientId = "client" } }; _stubRedirectUriValidator.IsPostLogoutRedirectUriValid = false; var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); parameters.Add("post_logout_redirect_uri", "http://client/signout-cb"); parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeFalse(); result.ValidatedRequest.Client.ClientId.Should().Be("client"); result.ValidatedRequest.Subject.GetSubjectId().Should().Be(_user.GetSubjectId()); result.ValidatedRequest.State.Should().BeNull(); result.ValidatedRequest.PostLogOutUri.Should().BeNull(); } [Fact] public async Task subject_mismatch_should_return_error() { _stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult() { IsError = false, Claims = new Claim[] { new Claim("sub", "xoxo") }, Client = new Client() { ClientId = "client" } }; _stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true; var parameters = new NameValueCollection(); parameters.Add("id_token_hint", "id_token"); parameters.Add("post_logout_redirect_uri", "http://client/signout-cb"); parameters.Add("client_id", "client1"); parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeTrue(); } [Fact] public async Task successful_request_should_return_inputs() { var parameters = new NameValueCollection(); var result = await _subject.ValidateAsync(parameters, _user); result.IsError.Should().BeFalse(); result.ValidatedRequest.Raw.Should().BeSameAs(parameters); } } }
42.394737
122
0.638858
[ "Apache-2.0" ]
AaqibAhamed/IdentityServer4
src/IdentityServer4/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs
8,057
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net.Http; namespace DataFlowAPI.Tests { [TestClass] public class APITest { [TestMethod] public void APIGetJobStatusLocal() { var client = new HttpClient(); } } }
17.823529
51
0.623762
[ "MIT" ]
liarjo/Data-Flow-Manager
DataFlowAPI.Tests/APITest.cs
305
C#
using System.ComponentModel.DataAnnotations; namespace ApartmanWeb.Models.AccountViewModels { public class LoginWith2faViewModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Authenticator code")] public string TwoFactorCode { get; set; } [Display(Name = "Remember this machine")] public bool RememberMachine { get; set; } public bool RememberMe { get; set; } } }
30
123
0.647368
[ "MIT" ]
kfugosic/Apartment-Web-App
ApartmanWeb/Models/AccountViewModels/LoginWith2faViewModel.cs
572
C#
using System; using System.Collections.Generic; using TramsDataApi.DatabaseModels; using TramsDataApi.RequestModels; namespace TramsDataApi.ResponseModels { public class AcademyTransferProjectResponse { public string ProjectUrn { get; set; } public string ProjectNumber { get; set; } public string OutgoingTrustUkprn { get; set; } public List<TransferringAcademiesResponse> TransferringAcademies { get; set; } public AcademyTransferProjectFeaturesResponse Features { get; set; } public AcademyTransferProjectDatesResponse Dates { get; set; } public AcademyTransferProjectBenefitsResponse Benefits { get; set; } public AcademyTransferProjectRationaleResponse Rationale { get; set; } public AcademyTransferProjectGeneralInformationResponse GeneralInformation { get; set; } public string State { get; set; } public string Status { get; set; } public string AcademyPerformanceAdditionalInformation { get; set; } public string PupilNumbersAdditionalInformation { get; set; } public string LatestOfstedJudgementAdditionalInformation { get; set; } public string KeyStage2PerformanceAdditionalInformation { get; set; } public string KeyStage4PerformanceAdditionalInformation { get; set; } public string KeyStage5PerformanceAdditionalInformation { get; set; } } }
48.689655
96
0.733711
[ "MIT" ]
DFE-Digital/trams-data-api
TramsDataApi/ResponseModels/AcademyTransferProjectResponse.cs
1,412
C#
using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; namespace az203labs.vm_provision { class Program { static void Main(string[] args) { //First of all, we need to create a resource group where we will add all the resources //needed for the virtual machine. var groupName = "az203-ResoureGroup"; var vmName = "az203VMTesting"; var location = Region.USWest2; var vNetName = "az203VNET"; var vNetAddress = "172.16.0.0/16"; var subnetName = "az203Subnet"; var subnetAddress = "172.16.0.0/24"; var nicName = "az203NIC"; var adminUser = "azureadminuser"; var adminPassword = "Pa$$w0rd!2019"; //Create the management client. This will be used for all the operations that we will perform in Azure. var credentials = SdkContext.AzureCredentialsFactory.FromFile("./azureauth.properties"); var azure = Azure.Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); //We need to create the resource group where we will add the virtual machine. var resourceGroup = azure.ResourceGroups.Define(groupName) .WithRegion(location) .Create(); //Every virtual machine needs to be connected to a virtual network. var network = azure.Networks.Define(vNetName) .WithRegion(location) .WithExistingResourceGroup(groupName) .WithAddressSpace(vNetAddress) .WithSubnet(subnetName, subnetAddress) .Create(); //Any virtual machine needs a network interface for connecting to the virtual network. var nic = azure.NetworkInterfaces.Define(nicName) .WithRegion(location) .WithExistingResourceGroup(groupName) .WithExistingPrimaryNetwork(network) .WithSubnet(subnetName) .WithPrimaryPrivateIPAddressDynamic() .Create(); //Create the virtual machine. azure.VirtualMachines.Define(vmName) .WithRegion(location) .WithExistingResourceGroup(groupName) .WithExistingPrimaryNetworkInterface(nic) .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter") .WithAdminUsername(adminUser) .WithAdminPassword(adminPassword) .WithComputerName(vmName) .WithSize(VirtualMachineSizeTypes.StandardDS2V2) .Create(); } } }
42.342857
115
0.608974
[ "MIT" ]
ahmad-luqman/az-203-practice-labs
src/1-develop-iaas-solution/vm/csharp/vm-provision/Program.cs
2,966
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SharpClock.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SharpClock.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.5
176
0.613147
[ "MIT" ]
FrejBjornsson/C-sharp-LOCK
Properties/Resources.Designer.cs
2,786
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Contoso.GameNetCore.Proto.Features { /// <summary> /// Feature to start response writing. /// </summary> public interface IProtoResponseStartFeature { /// <summary> /// Starts the response by calling OnStarting() and making headers unmodifiable. /// </summary> Task StartAsync(CancellationToken token = default); } }
31.25
112
0.6688
[ "Apache-2.0" ]
bclnet/GameNetCore
src/Proto/Proto.Features/src/IHttpResponseStartFeature.cs
625
C#
// Author: // Brian Faust <brian@ark.io> // // Copyright (c) 2018 Ark Ecosystem <info@ark.io> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace ArkEcosystem.Crypto.Networks { public class Testnet : INetwork { public byte GetPublicKeyHash() { return 0x17; } public DateTime GetEpoch() { return new DateTime(2017, 3, 21, 13, 00, 0, DateTimeKind.Utc); } public string GetNethash() { return "d9acd04bde4234a81addb8482333b4ac906bed7be5a9970ce8ada428bd083192"; } public byte GetWIF() { return 186; } } }
34.26
86
0.687682
[ "MIT" ]
supaiku0/dotnet-crypto
ArkEcosystem.Crypto/ArkEcosystem.Crypto/ArkEcosystem.Crypto/Networks/Testnet.cs
1,713
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.BssOpenApi.Model.V20171214 { public class QueryAvailableInstancesResponse : AcsResponse { private string requestId; private bool? success; private string code; private string message; private QueryAvailableInstances_Data data; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public QueryAvailableInstances_Data Data { get { return data; } set { data = value; } } public class QueryAvailableInstances_Data { private int? pageNum; private int? pageSize; private int? totalCount; private List<QueryAvailableInstances_Instance> instanceList; public int? PageNum { get { return pageNum; } set { pageNum = value; } } public int? PageSize { get { return pageSize; } set { pageSize = value; } } public int? TotalCount { get { return totalCount; } set { totalCount = value; } } public List<QueryAvailableInstances_Instance> InstanceList { get { return instanceList; } set { instanceList = value; } } public class QueryAvailableInstances_Instance { private long? ownerId; private long? sellerId; private string productCode; private string productType; private string subscriptionType; private string instanceID; private string region; private string createTime; private string endTime; private string stopTime; private string releaseTime; private string expectedReleaseTime; private string status; private string subStatus; private string renewStatus; private int? renewalDuration; private string renewalDurationUnit; private string seller; public long? OwnerId { get { return ownerId; } set { ownerId = value; } } public long? SellerId { get { return sellerId; } set { sellerId = value; } } public string ProductCode { get { return productCode; } set { productCode = value; } } public string ProductType { get { return productType; } set { productType = value; } } public string SubscriptionType { get { return subscriptionType; } set { subscriptionType = value; } } public string InstanceID { get { return instanceID; } set { instanceID = value; } } public string Region { get { return region; } set { region = value; } } public string CreateTime { get { return createTime; } set { createTime = value; } } public string EndTime { get { return endTime; } set { endTime = value; } } public string StopTime { get { return stopTime; } set { stopTime = value; } } public string ReleaseTime { get { return releaseTime; } set { releaseTime = value; } } public string ExpectedReleaseTime { get { return expectedReleaseTime; } set { expectedReleaseTime = value; } } public string Status { get { return status; } set { status = value; } } public string SubStatus { get { return subStatus; } set { subStatus = value; } } public string RenewStatus { get { return renewStatus; } set { renewStatus = value; } } public int? RenewalDuration { get { return renewalDuration; } set { renewalDuration = value; } } public string RenewalDurationUnit { get { return renewalDurationUnit; } set { renewalDurationUnit = value; } } public string Seller { get { return seller; } set { seller = value; } } } } } }
14.527845
64
0.510833
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-bssopenapi/BssOpenApi/Model/V20171214/QueryAvailableInstancesResponse.cs
6,000
C#
// Copyright (c) Richasy. All rights reserved. using System.ComponentModel; using Richasy.Bili.ViewModels.Uwp; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Richasy.Bili.App.Controls { /// <summary> /// 应用标题栏. /// </summary> public sealed partial class AppTitleBar : UserControl { /// <summary> /// <see cref="ViewModel"/>的依赖属性. /// </summary> public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(AppViewModel), typeof(AppTitleBar), new PropertyMetadata(AppViewModel.Instance)); /// <summary> /// Initializes a new instance of the <see cref="AppTitleBar"/> class. /// </summary> public AppTitleBar() { this.InitializeComponent(); this.Loaded += OnLoaded; } /// <summary> /// 视图模型. /// </summary> public AppViewModel ViewModel { get { return (AppViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } } private void OnLoaded(object sender, RoutedEventArgs e) { Window.Current.SetTitleBar(TitleBarHost); CheckBackButtonVisibility(); ViewModel.PropertyChanged += OnViewModelPropertyChanged; } private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ViewModel.IsOpenPlayer) || e.PropertyName == nameof(ViewModel.IsShowOverlay)) { CheckBackButtonVisibility(); } } private void OnMenuButtonClick(object sender, RoutedEventArgs e) { ViewModel.IsNavigatePaneOpen = !ViewModel.IsNavigatePaneOpen; } private void OnBackButtonClick(object sender, RoutedEventArgs e) { if (ViewModel.IsOpenPlayer) { ViewModel.IsOpenPlayer = false; } else if (ViewModel.IsShowOverlay) { ViewModel.SetMainContentId(ViewModel.CurrentMainContentId); } } private void CheckBackButtonVisibility() { BackButton.Visibility = (ViewModel.IsShowOverlay || ViewModel.IsOpenPlayer) ? Visibility.Visible : Visibility.Collapsed; } } }
31.217949
147
0.596304
[ "MIT" ]
Caseming/Bili.Uwp
src/App/Controls/App/AppTitleBar.xaml.cs
2,465
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Domain { /// <summary> /// KoubeiMerchantOperatorModifyModel Data Structure. /// </summary> [Serializable] public class KoubeiMerchantOperatorModifyModel : AopObject { /// <summary> /// 授权码 /// </summary> [XmlElement("auth_code")] public string AuthCode { get; set; } /// <summary> /// 组织部门ID /// </summary> [XmlElement("department_id")] public string DepartmentId { get; set; } /// <summary> /// 折让限额单位 /// </summary> [XmlElement("discount_limit_unit")] public string DiscountLimitUnit { get; set; } /// <summary> /// 折让限额值 /// </summary> [XmlElement("discount_limit_value")] public string DiscountLimitValue { get; set; } /// <summary> /// 每天 /// </summary> [XmlElement("free_limit_unit")] public string FreeLimitUnit { get; set; } /// <summary> /// 免单限额值 /// </summary> [XmlElement("free_limit_value")] public string FreeLimitValue { get; set; } /// <summary> /// 性别 /// </summary> [XmlElement("gender")] public string Gender { get; set; } /// <summary> /// 5-非叶子节点,6叶子节点 /// </summary> [XmlElement("job_type")] public string JobType { get; set; } /// <summary> /// 手机号 /// </summary> [XmlElement("mobile")] public string Mobile { get; set; } /// <summary> /// 操作员Id /// </summary> [XmlElement("operator_id")] public string OperatorId { get; set; } /// <summary> /// 操作员姓名 /// </summary> [XmlElement("operator_name")] public string OperatorName { get; set; } /// <summary> /// 操作员角色ID /// </summary> [XmlElement("role_id")] public string RoleId { get; set; } } }
24.188235
62
0.499027
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk/Domain/KoubeiMerchantOperatorModifyModel.cs
2,162
C#
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Windows; using System.Windows.Controls; namespace Microsoft.VisualStudioTools.Wpf { sealed class LabelledControl : ContentControl { public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(LabelledControl), new PropertyMetadata()); public string HelpText { get { return (string)GetValue(HelpTextProperty); } set { SetValue(HelpTextProperty, value); } } public static readonly DependencyProperty HelpTextProperty = DependencyProperty.Register("HelpText", typeof(string), typeof(LabelledControl), new PropertyMetadata(HelpText_PropertyChanged)); private static void HelpText_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(HasHelpTextPropertyKey, !string.IsNullOrWhiteSpace(e.NewValue as string)); } public bool HasHelpText { get { return (bool)GetValue(HasHelpTextProperty); } private set { SetValue(HasHelpTextPropertyKey, value); } } private static readonly DependencyPropertyKey HasHelpTextPropertyKey = DependencyProperty.RegisterReadOnly("HasHelpText", typeof(bool), typeof(LabelledControl), new PropertyMetadata(false)); public static readonly DependencyProperty HasHelpTextProperty = HasHelpTextPropertyKey.DependencyProperty; } }
43.54902
198
0.671769
[ "MIT" ]
Muraad/VisualRust
Microsoft.VisualStudio.Project/Wpf/LabelledControl.cs
2,223
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetCore.Security; using LinCms.Aop.Attributes; using LinCms.Entities; using LinCms.Exceptions; using LinCms.IRepositories; namespace LinCms.Cms.Users { public class UserIdentityService : ApplicationService, IUserIdentityService { private readonly IAuditBaseRepository<LinUserIdentity> _userIdentityRepository; private readonly ICryptographyService _cryptographyService; public UserIdentityService(IAuditBaseRepository<LinUserIdentity> userIdentityRepository, ICryptographyService cryptographyService) { _userIdentityRepository = userIdentityRepository; _cryptographyService = cryptographyService; } public async Task<bool> VerifyUserPasswordAsync(long userId, string password, string salt) { LinUserIdentity userIdentity = await this.GetFirstByUserIdAsync(userId); string encryptPassword = _cryptographyService.Encrypt(password, salt); return userIdentity != null && userIdentity.Credential == encryptPassword; } public async Task ChangePasswordAsync(long userId, string newpassword, string salt) { var linUserIdentity = await this.GetFirstByUserIdAsync(userId); ; await this.ChangePasswordAsync(linUserIdentity, newpassword, salt); } public Task ChangePasswordAsync(LinUserIdentity linUserIdentity, string newpassword, string salt) { string encryptPassword = _cryptographyService.Encrypt(newpassword, salt); if (linUserIdentity == null) { linUserIdentity = new LinUserIdentity(LinUserIdentity.Password, "", encryptPassword, DateTime.Now); return _userIdentityRepository.InsertAsync(linUserIdentity); } else { linUserIdentity.Credential = encryptPassword; return _userIdentityRepository.UpdateAsync(linUserIdentity); } } [Transactional] public Task DeleteAsync(long userId) { return _userIdentityRepository.Where(r => r.CreateUserId == userId).ToDelete().ExecuteAffrowsAsync(); } public Task<LinUserIdentity> GetFirstByUserIdAsync(long userId) { return _userIdentityRepository .Where(r => r.CreateUserId == userId && r.IdentityType == LinUserIdentity.Password) .FirstAsync(); } public async Task<List<UserIdentityDto>> GetListAsync(long userId) { List<LinUserIdentity> userIdentities = await _userIdentityRepository .Where(r => r.CreateUserId == userId) .ToListAsync(); return Mapper.Map<List<UserIdentityDto>>(userIdentities); } public async Task UnBind(Guid id) { LinUserIdentity userIdentity = await _userIdentityRepository.GetAsync(id); if (userIdentity == null || userIdentity.CreateUserId != CurrentUser.Id) { throw new LinCmsException("你无权解绑此账号"); } List<LinUserIdentity> userIdentities = await _userIdentityRepository.Select.Where(r => r.CreateUserId == CurrentUser.Id).ToListAsync(); bool hasPwd = userIdentities.Where(r => r.IdentityType == LinUserIdentity.Password).Any(); if (!hasPwd && userIdentities.Count == 1) { throw new LinCmsException("你未设置密码,无法解绑最后一个第三方登录账号"); } await _userIdentityRepository.DeleteAsync(userIdentity); } } }
38.458333
147
0.656555
[ "MIT" ]
KribKing/lin-cms-dotnetcore
src/LinCms.Application/Cms/Users/UserIdentityService.cs
3,754
C#