text stringlengths 13 6.01M |
|---|
using System.Threading.Tasks;
namespace CryptoInvestor.Infrastructure.Services.Interfaces
{
public interface IDataInitializer
{
Task SeedAsync();
}
} |
using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using WebDataDemo.Dtos;
namespace WebDataDemo.Option_03_Dapper_SQL;
[Route("api/v03/[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = "3. Authors - Dapper SQL")]
public class AuthorsController : ControllerBase
{
private readonly string _connString;
private readonly ILogger<AuthorsController> _logger;
public AuthorsController(IConfiguration config,
ILogger<AuthorsController> logger)
{
_connString = config.GetConnectionString("DefaultConnection");
_logger = logger;
}
// GET: api/<AuthorsController>
[HttpGet]
public ActionResult<IEnumerable<AuthorDTO>> Get()
{
using var conn = new SqlConnection(_connString);
var sql = "SELECT * FROM Authors";
_logger.LogInformation("Executing query: {sql}", sql);
var authors = conn.Query<AuthorDTO>(sql).ToList();
return Ok(authors);
}
// GET api/<AuthorsController>/5
[HttpGet("{id}")]
public ActionResult<AuthorWithCoursesDTO> Get(int id)
{
// https://medium.com/dapper-net/handling-multiple-resultsets-4b108a8c5172
using var conn = new SqlConnection(_connString);
var sql = @"SELECT a.Id, a.Name FROM Authors a WHERE Id = @AuthorId;
SELECT ca.RoyaltyPercentage, ca.CourseId, ca.AuthorId, c.Title
FROM CourseAuthor ca
INNER JOIN Courses c ON c.Id = ca.CourseId
WHERE ca.AuthorId = @AuthorId";
_logger.LogInformation("Executing query: {sql}", sql);
var result = conn.QueryMultiple(sql, new { AuthorId = id });
var author = result.ReadSingle<AuthorWithCoursesDTO>();
var courses = result.Read<CourseDTO>().ToList();
author.Courses.AddRange(courses);
return Ok(author);
}
// POST api/<AuthorsController>
[HttpPost]
public ActionResult<AuthorDTO> Post([FromBody] CreateAuthorRequest newAuthor)
{
// https://stackoverflow.com/a/8270264
var sql = "INSERT Authors (name) VALUES (@name);SELECT CAST(scope_identity() AS int)";
using var conn = new SqlConnection(_connString);
int newId = conn.QuerySingle<int>(sql, new { name = newAuthor.Name });
var authorDto = new AuthorDTO
{
Id = newId,
Name = newAuthor.Name
};
return Ok(authorDto);
}
// PUT api/<AuthorsController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
using var conn = new SqlConnection(_connString);
var sql = "UPDATE Authors SET name = @Name WHERE Id = @Id";
conn.Execute(sql, new { Name = value, Id = id });
}
// DELETE api/<AuthorsController>/5
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
using var conn = new SqlConnection(_connString);
var sql = "DELETE Authors WHERE Id = @AuthorId";
conn.Execute(sql, new { AuthorId = id });
return NoContent();
}
}
|
using SalaoG.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace SalaoG.ViewModels
{
public class ListaAtendimentoViewModel
{
public List<ListaAtendimento> ListaAtendimento { get; private set; }
public ListaAtendimentoViewModel()
{
this.ListaAtendimento = new List<ListaAtendimento>();
}
public event PropertyChangedEventHandler PropertyChanged;
public List<ListaAtendimento> GetAtendimento(int Idfunc)
{
var listaAtendimento = new ListaDeAtendimentoService();
var lista = listaAtendimento.listaAtendimento(Idfunc);
foreach (var item in lista)
{
this.ListaAtendimento.Add(
new ListaAtendimento
{
numeroCOMANDA = item.numeroCOMANDA,
Total = item.Total,
movimentacao = item.movimentacao.ToString()
}) ;
}
return ListaAtendimento;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SubSonic.DataProviders;
namespace SubSonic.Repository
{
public interface IGenericRepository<T> : IRepository
where T : class, new()
{
//#region IRepository Members
//bool Exists(System.Linq.Expressions.Expression<Func<T, bool>> expression);
//IQueryable<T> All();
//T Single(object key);
//T Single(System.Linq.Expressions.Expression<Func<T, bool>> expression);
//IList<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> expression);
//SubSonic.Schema.PagedList<T> GetPaged(int pageIndex, int pageSize);
//SubSonic.Schema.PagedList<T> GetPaged(string sortBy, int pageIndex, int pageSize);
//object Add(T item);
//void AddMany(IEnumerable<T> items);
//int Update(T item);
//int UpdateMany(IEnumerable<T> items);
//int Delete(T key);
//int DeleteMany(System.Linq.Expressions.Expression<Func<T, bool>> expression);
//int DeleteMany(IEnumerable<T> items);
//#endregion
}
public class GenericRepository<Type> : SimpleRepository, IGenericRepository<Type>
where Type : class, new()
{
public GenericRepository()
: base() { }
public GenericRepository(string connectionStringName)
: base(connectionStringName) { }
public GenericRepository(string connectionStringName, SimpleRepositoryOptions options)
: base(connectionStringName, options) { }
public GenericRepository(SimpleRepositoryOptions options)
: base(options) { }
public GenericRepository(IDataProvider provider)
: base(provider) { }
public GenericRepository(IDataProvider provider, SimpleRepositoryOptions options)
: base(provider, options)
{
}
//#region IGenericRepository<Type> Members
//public bool Exists(System.Linq.Expressions.Expression<Func<Type, bool>> expression)
//{
// throw new NotImplementedException();
//}
//public IQueryable<Type> All()
//{
// throw new NotImplementedException();
//}
//public Type Single(object key)
//{
// throw new NotImplementedException();
//}
//public Type Single(System.Linq.Expressions.Expression<Func<Type, bool>> expression)
//{
// throw new NotImplementedException();
//}
//public IList<Type> Find(System.Linq.Expressions.Expression<Func<Type, bool>> expression)
//{
// throw new NotImplementedException();
//}
//public SubSonic.Schema.PagedList<Type> GetPaged(int pageIndex, int pageSize)
//{
// throw new NotImplementedException();
//}
//public SubSonic.Schema.PagedList<Type> GetPaged(string sortBy, int pageIndex, int pageSize)
//{
// throw new NotImplementedException();
//}
//public object Add(Type item)
//{
// throw new NotImplementedException();
//}
//public void AddMany(IEnumerable<Type> items)
//{
// throw new NotImplementedException();
//}
//public int Update(Type item)
//{
// throw new NotImplementedException();
//}
//public int UpdateMany(IEnumerable<Type> items)
//{
// throw new NotImplementedException();
//}
//public int Delete(Type key)
//{
// throw new NotImplementedException();
//}
//public int DeleteMany(System.Linq.Expressions.Expression<Func<Type, bool>> expression)
//{
// throw new NotImplementedException();
//}
//public int DeleteMany(IEnumerable<Type> items)
//{
// throw new NotImplementedException();
//}
//#endregion
}
}
|
using System.IO;
using System.Xml.Linq;
namespace Converter.UI.Helpers
{
/// <summary>
/// Helper class for various XML related read operations
/// </summary>
public static class XmlHelper
{
/// <summary>
/// Reads the XML file.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <returns></returns>
public static XDocument ReadXmlFile(string filePath)
{
if (!File.Exists(filePath))
{
return null;
}
return XDocument.Load(filePath, LoadOptions.SetLineInfo);
}
}
}
|
using System.Collections.Generic;
namespace SplitPdf.Engine
{
public class ArgumentsInterpreter
{
public const string UsageMessage = "Usage:\r\n" +
"======\r\n" +
"\r\n" +
"Split a single PDF file into many:\r\n" +
"\tSplitPdf.exe <File>\r\n" +
"Split multiple PDF files into many (batching):\r\n" +
"\tSplitPdf.exe <File1> <File2> <...> <FileN>\r\n" +
"Merge multiple PDF files into one (creates <OutputFile> at the end):\r\n" +
"\tSplitPdf.exe -m <File1> <File2> <...> <FileN> <OutputFile>";
public List<string> InputFiles { get; private set; }
public bool IsMergeEnabled { get; private set; }
public string MergeOutputFile { get; private set; }
public bool IsUpgradeCheckRequested { get; private set; }
public void ProcessArguments(string[] arguments)
{
if (arguments == null || arguments.Length == 0)
ArgumentValidationException.ThrowWithUsageMessage();
var firstFileNameIndex = 0;
// ReSharper disable once PossibleNullReferenceException
if (arguments[0].ToUpper() == "-M")
{
if (arguments.Length < 2)
ArgumentValidationException.ThrowWithUsageMessage("Nothing to merge.");
IsMergeEnabled = true;
firstFileNameIndex = 1;
}
else if (arguments[0].ToUpper() == "-UC")
{
if (arguments.Length > 1)
ArgumentValidationException.ThrowWithUsageMessage(
"If passed, -uc must be the only argument.");
IsUpgradeCheckRequested = true;
return;
}
InputFiles = new List<string>();
// ReSharper disable once PossibleNullReferenceException
for (var i = firstFileNameIndex; i < arguments.Length; i++)
{
if (IsMergeEnabled && i == arguments.Length - 1)
// Last argument is the Output File
MergeOutputFile = arguments[i];
else
InputFiles.Add(arguments[i]);
}
if (IsMergeEnabled && InputFiles.Contains(MergeOutputFile))
ArgumentValidationException.ThrowWithUsageMessage("Merge output file cannot be the same as one " +
"of the input files.");
}
}
}
|
namespace Tookan.NET.Core
{
public interface IAgent
{
string Email { get; }
int FleetId { get; }
string FleetImage { get; }
string FleetStatusColor { get; }
string FleetThumbImage { get; }
int IsAvailable { get; }
string LastUpdatedLocationTime { get; }
string Latitude { get; }
string Longitude { get; }
int PendingTasks { get; }
string Phone { get; }
int RegistrationStatus { get; }
TaskStatus Status { get; }
string Username { get; }
}
} |
using System;
namespace WorldHardestGame.Core.Entities
{
public abstract class BaseEntity
{
protected BaseEntity(Position position, Rectangle boundingBox, Map map)
{
Map = map;
BoundingBox = boundingBox;
Position = position;
}
public virtual Position Position { get; set; }
public Rectangle BoundingBox { get; }
public Map Map { get; }
public bool IsKilled { get; set; }
public abstract bool IsEnnemy { get; }
public void Update(TimeSpan deltaTime)
=> UpdateImpl(deltaTime);
protected abstract void UpdateImpl(TimeSpan deltaTime);
protected abstract bool HasContactWith(Player player);
public static bool HasContactBetween(Player player, BaseEntity entity)
=> entity.HasContactWith(player);
}
}
|
using AuthAutho.Extensions;
using AuthAutho.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using KissLog;
using System;
namespace AuthAutho.Controllers
{
[Authorize]
public class HomeController : Controller
{
//private readonly ILogger<HomeController> _logger;
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
[AllowAnonymous]
public IActionResult Index()
{
try
{
//Testando o logger do kissLogger
throw new Exception("Algo Horrível ocorreu... ");
}
catch (Exception e)
{
_logger.Error(e);
throw;
}
}
[Authorize]
public IActionResult Privacy()
{
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult Secrety()
{
return View();
}
[Authorize(Policy = "PodeExcluir")]
public IActionResult SecretyClaim()
{
return View();
}
[Authorize(Policy = "PodeEscrever")]
public IActionResult SecretyClaimGravar()
{
return View();
}
//Customizando Claims
//Home = chave
//Segredo = valor da claims,poderia ser n valores
[ClaimsAuthorize("Home","Segredo")]
public IActionResult ClaimsCustom()
{
return View("SecretyClaim");
}
[ClaimsAuthorize("Produtos", "Leer")]
public IActionResult ClaimsCustomProdutos()
{
return View();
}
[Route("erro/{idErro:length(3,3)}")]
public IActionResult Error(int idErro)
{
var model = new ErrorViewModel();
switch (idErro)
{
case 500:
model.Mensagem = "Ocorreu um erro!!! Tente novamente mais tarde ou contate nosso suporte";
model.Titulo = "Ocorreu um erro!!!";
model.ErroCode = idErro;
break;
case 404:
model.Mensagem = "A página que está procurando nao foi encontrada. <br/>Em caso de dúvidas entre em contato com nosso suporte";
model.Titulo = "Opss!!! Página não encontrada!!!";
model.ErroCode = idErro;
break;
case 403:
model.Mensagem = "Você não tem permissão para acessar essa pagina. <br/>Em caso de dúvidas entre em contato com nosso suporte";
model.Titulo = "Opss!!! Você não tem permissão para fazer isto.";
model.ErroCode = idErro;
break;
default:
model.Mensagem = "Ocorreu um erro inesperado.";
model.Titulo = "=(";
model.ErroCode = idErro;
break;
}
return View("Error", model);
}
}
}
|
namespace RealEstate.Web.Api.Controllers
{
using Models.Users;
using Infrastructure;
using System.Web.Http;
using Services.Data.Contracts;
[Authorize]
public class UsersController : ApiController
{
private readonly IUsersService users;
private IUserIdProvider userIdProvider;
public UsersController(IUserIdProvider idProvider, IUsersService users)
{
this.userIdProvider = idProvider;
this.users = users;
}
[HttpPost]
[Route("api/User/Rate")]
public IHttpActionResult RateUser(RateUserRequestModel model)
{
this.users.RateUser
(
model.UserId,
model.Value
);
return this.Ok();
}
[HttpGet]
//[Route("api/Users/{username}")]
public IHttpActionResult GetUserByUsername(string username)
{
var user = users.GetUserByUsername(username);
var result = user
.ProjectTo<ListUserRequestModel>();
return this.Ok(result);
}
}
} |
using System;
using UnityEngine;
using DG.Tweening;
public class CardController : MonoBehaviour
{
CardView mCardView;
CardData mCardData;
public void SetupCard(CardData cardData)
{
mCardView = GetComponent<CardView>();
mCardData = cardData;
mCardView.SetData(mCardData);
}
public void RightAnswear()
{
}
public void LeftAnswear()
{
}
public void PlayAnimationBackToCenter()
{
}
public void PlayAnimationUsingOffSet(Vector2 movingVector)
{
transform.DORotate(new Vector3(0, 0, -movingVector.x), 0);
transform.DOLocalMoveX(movingVector.x, 0);
}
} |
using UnityEngine;
using System.Collections;
namespace Ph.Bouncer
{
public class TitleAnimation : MonoBehaviour
{
void Start()
{
// NGUI animation movement must be multipled by UI root scale
// http://www.tasharen.com/forum/index.php?topic=671.0
iTween.MoveBy(gameObject, iTween.Hash("y", -400f * 0.003125f,
"time", 2f,
"easetype", iTween.EaseType.easeOutBounce));
enabled = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02_Bieco
{
public class ClaimRepository
{
protected readonly Queue<InsuranceCl> _claims = new Queue<InsuranceCl>();
public bool AddClaimToQu(InsuranceCl claim)
{
int startingCount = _claims.Count;
_claims.Enqueue(claim);
bool wasAdded = (_claims.Count > startingCount) ? true : false;
return wasAdded;
}
public Queue<InsuranceCl> GetAllInsuranceClaims()
{
return _claims;
}
}
}
|
namespace HCL.Academy.Model
{
public class WikiPolicies
{
public string DocumentName { get; set; }
public string DocumentURL { get; set; }
public string PolicyOwner { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TacticalMaddiAdminTool.Models;
namespace TacticalMaddiAdminTool.Services
{
public abstract class ItemsProvider
{
protected IMaddiService maddiService;
protected Func<IItem[]> getItemsFunction;
public ItemsProvider(IMaddiService maddiService)
{
this.maddiService = maddiService;
}
public Task<IItem[]> GetItemsAsync()
{
return Task.Factory.StartNew(getItemsFunction);
}
}
public class SetsProvider : ItemsProvider
{
public SetsProvider(IMaddiService maddiService) : base(maddiService)
{
getItemsFunction = maddiService.GetSets;
}
}
public class FragmentsProvider : ItemsProvider
{
public FragmentsProvider(IMaddiService maddiService) : base(maddiService)
{
getItemsFunction = maddiService.GetFragments;
}
}
public class CollectionsProvider : ItemsProvider
{
public CollectionsProvider(IMaddiService maddiService) : base(maddiService)
{
getItemsFunction = maddiService.GetCollections;
}
}
}
|
using System;
namespace ComputerBuilderClasses.Contracts
{
public interface IPcSystem : ISystem
{
void Play(int guessNumber, Random randomGenerator);
}
} |
using System.Collections.Generic;
namespace Allvis.Kaylee.Validator.SqlServer.Models.DB
{
public class Table
{
public string Schema { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
public bool IsTable => Type == "BASE TABLE";
public bool IsView => Type == "VIEW";
public List<Column> Columns { get; } = new List<Column>();
public List<TableConstraint> Constraints { get; } = new List<TableConstraint>();
}
}
|
using System;
using Newtonsoft.Json;
namespace Server
{
public interface IAuth0UserProfile
{
string Name { get; set; }
string Nickname { get; set; }
Uri Picture { get; set; }
[JsonProperty("user_id")]
string UserId { get; set; }
string Email { get; set; }
[JsonProperty("email_verified")]
bool EmailVerified { get; set; }
[JsonProperty("given_name")]
string GivenName { get; set; }
[JsonProperty("family_name")]
string FamilyName { get; set; }
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
namespace Blog.Api.Models
{
public class ApplicationUser:IdentityUser<int>,IBaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public ICollection<BlogEntity> Blogs { get; set; }
}
} |
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_60
{
public class Program
{
public static void Main()
{}
}
}
|
namespace API.Omorfias.Data.Enumerator
{
public enum ServiceLocationEnum
{
Store = 1,
Home = 2
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace homeworkCSharp2020
{
class nal11
{
public static void func(int userInput)
{
Console.Write("Vneseno celo stevilo {0} - Mesec ", userInput);
switch (userInput)
{
case 1:
Console.WriteLine("Januar");
break;
case 2:
Console.WriteLine("Februar");
break;
case 3:
Console.WriteLine("Marec");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("Maj");
break;
case 6:
Console.WriteLine("Junij");
break;
case 7:
Console.WriteLine("Julij");
break;
case 8:
Console.WriteLine("Avgust");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("Oktober");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("Great Scott!");
break;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Curve
{
public bool addictive;
public AnimationCurve curve;
public int duration;
public float multiplier;
public float constant;
public float tax;
[HideInInspector] public int hours;
public float _Value => (addictive ? 1 : 0) + curve.Evaluate(hours++ / duration) * multiplier;
public float GetValue()
{
if (hours >= duration)
return -1;
else
return constant + curve.Evaluate((float)hours++ / duration) * multiplier;
}
public float GetValue(int hour)
{
return constant + curve.Evaluate((float)hour / duration) * multiplier;
}
}
[System.Serializable]
public class Curve_Tag
{
public Tag tag;
public Curve curve;
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
AudioSource audioSource;
public AudioClip sfxBg;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
public void PlayMusic ()
{
Debug.Log("Collidiu");
audioSource.clip = sfxBg;
audioSource.volume = 0.70f;
audioSource.Play();
}
}
|
// Requirements:
// - C# 4.0
// - Add System.Web.Extension.dll reference to your project so the code can compile.
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using System.Diagnostics;
namespace ConnectExample.Samples
{
public class RequestHeader
{
public string Token { get; set; }
public string CoordinationId { get; set; }
}
public class StatusEntry
{
public string Type { get; set; }
public string Code { get; set; }
public string Message { get; set; }
}
public class ResponseHeader
{
public string Status { get; set; }
public ICollection<StatusEntry> StatusList { get; set; }
public string CoordinationId { get; set; }
}
public class RenewSessionRequestBody
{
public string SystemId { get; set; }
public string SystemPassword { get; set; }
public string UserId { get; set; }
public string UserPassword { get; set; }
}
public class RenewSessionRequest
{
public RequestHeader RequestHeader { get; set; }
public RenewSessionRequestBody RenewSessionRequestBody { get; set; }
}
public class RenewSessionResult
{
public string AccountId { get; set; }
public string SecureToken { get; set; }
public string Token { get; set; }
public int TokenDurationMinutes { get; set; }
}
public class RenewSessionResponse
{
public ResponseHeader ResponseHeader { get; set; }
public RenewSessionResult RenewSessionResult { get; set; }
}
public class RenewSessionSample
{
public string GetToken(string secureToken)
{
return RenewSecureToken(secureToken).RenewSessionResult.Token;
}
public string GetSecureToken(string secureToken)
{
return RenewSecureToken(secureToken).RenewSessionResult.SecureToken;
}
// token received from CreateSession API call
public RenewSessionResponse RenewSecureToken(string secureToken)
{
const string renewSessionRequestUrl = "https://connect.gettyimages.com/v1/session/RenewSession";
var sessionToken = new RenewSessionRequestBody
{
SystemId = "systemId",
SystemPassword = "systemPassword",
};
var renewSessionRequest = new RenewSessionRequest
{
RequestHeader = new RequestHeader { Token = secureToken },
RenewSessionRequestBody = sessionToken
};
return MakeWebRequest(renewSessionRequestUrl, renewSessionRequest);
}
//You may wish to replace this code with your preferred library for posting and receiving JSON data.
private static RenewSessionResponse MakeWebRequest(string requestUrl, RenewSessionRequest request)
{
var webRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
var jsonSerializer = new JavaScriptSerializer();
var requestStr = jsonSerializer.Serialize(request);
Debug.WriteLine(requestStr);
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(requestStr);
writer.Close();
}
var response = webRequest.GetResponse() as HttpWebResponse;
string jsonResult;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonResult = reader.ReadToEnd();
reader.Close();
}
Debug.WriteLine(jsonResult);
return jsonSerializer.Deserialize<RenewSessionResponse>(jsonResult);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Ball : MonoBehaviour
{
Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
public float ballSpeed = 2f;
private void FixedUpdate()
{
Vector3 screenPos = Camera.main.WorldToViewportPoint(transform.position);
Vector3 velocity = rb.velocity;
if (screenPos.x > 1 || screenPos.x < 0)
{
Debug.Log("Left Side of screen");
velocity.x = -velocity.x;
}
if (screenPos.y > 1)
{
Debug.Log("Left Top of screen");
velocity.y = -velocity.y;
}
/*
if (velocity != rb.velocity)
{
*/
rb.velocity = velocity.normalized * ballSpeed;
//}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.GetComponent<IBrick>() != null)
{
collision.gameObject.GetComponent<IBrick>().Hit();
}
Vector3 vel = rb.velocity;
//If the ball is traveling horizontally & won't return to the player
if (Mathf.Abs(vel.y) < 0.01f)
{
vel.y += Random.Range(-1f,1f);
rb.velocity = vel.normalized * ballSpeed;
}
//If the ball is traveling Vertically & won't hit anymore blocks
if (Mathf.Abs(vel.x) < 0.01f)
{
vel.x += Random.Range(-1f, 1f);
rb.velocity = vel.normalized * ballSpeed;
}
}
public GameObject deathParticle;
private void OnDestroy()
{
if (deathParticle != null)
{
Instantiate(deathParticle, transform.position, Quaternion.identity, null);
}
}
}
|
using Paydock.SDK.Extensions;
using Paydock.SDK.Services.Base;
using System;
using System.Collections.Generic;
namespace Paydock.SDK.Services
{
public class ChargeService : IChargeService
{
private IWebService _webService;
public ChargeService(IWebService webService)
{
_webService = webService;
}
public Boolean OneOff(String customerID, Decimal amount, String currency, String reference = null, String description = null)
{
Dictionary<String, Object> data = new Dictionary<String, Object>()
{
{ PaydockConstants.Json.CUSTOMER_ID, customerID },
{ PaydockConstants.Json.CURRENCY, currency},
{ PaydockConstants.Json.AMOUNT, amount},
{ PaydockConstants.Json.REFERENCE, reference },
{ PaydockConstants.Json.DESCRIPTION, description }
}.RemoveItemsIfValueIsNull();
String json = _webService.JsonSerializer.Serialize(data);
String resultJson = _webService.SendJson(PaydockConstants.Urls.CHARGES, json);
dynamic obj = _webService.JsonSerializer.DeserializeObject(resultJson);
try
{
return obj["resource"]["data"]["status"] == "complete";
}
catch { }
return false;
}
}
}
|
using First_Api_Project.Models;
using First_Api_Project.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace First_Api_Project.Controllers.api
{
public class ProductsController : ApiController
{
ProductRepository prodrepo = new ProductRepository();
public IHttpActionResult Get()
{
return Ok(prodrepo.GetAll());
}
public IHttpActionResult Get(int id)
{
var product = prodrepo.Get(id);
if (product == null)
{
return StatusCode(HttpStatusCode.NoContent);
}
return Ok(product);
}
public IHttpActionResult Post(Product product)
{
prodrepo.Insert(product);
return Created("/api/Products"+product.ProductId,product);
}
public IHttpActionResult Put([FromUri]int id,[FromBody] Product product)
{
product.ProductId = id;
prodrepo.Update(product);
return Ok(product);
}
public IHttpActionResult Delete(int id)
{
prodrepo.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
}
}
|
using DAL.DataSource;
using DAL.Entity;
using Dapper;
using FirebirdSql.Data.FirebirdClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DAL.Persistence
{
public class PacienteDAL
{
public IList<Paciente> ListaPacientes()
{
FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();
try
{
_conexao.Open();
return _conexao.Query<Paciente>("SELECT id_paciente as IdPaciente, nome, idade, peso, altura FROM tb_paciente").ToList();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conexao.Close();
}
}
public Paciente getPaciente(int idPaciente)
{
FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();
try
{
_conexao.Open();
return _conexao.Query<Paciente>($@"SELECT ID_PACIENTE as IdPaciente, nome, idade, peso, altura FROM tb_paciente
WHERE id_paciente = {idPaciente}").SingleOrDefault();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conexao.Close();
}
}
public bool InserirPaciente(Paciente paciente)
{
FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();
try
{
_conexao.Open();
return _conexao.Execute($@"INSERT INTO TB_PACIENTE (NOME, IDADE, PESO, ALTURA)
VALUES ('{paciente.Nome}', {paciente.Idade}, {paciente.Peso}, {paciente.Altura}) ") > 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conexao.Close();
}
}
public bool EditarPaciente(Paciente paciente)
{
FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();
try
{
_conexao.Open();
return _conexao.Execute($@"UPDATE TB_PACIENTE
SET NOME = '{paciente.Nome}',
IDADE = {paciente.Idade},
PESO = {paciente.Peso},
ALTURA = {paciente.Altura}
WHERE (ID_PACIENTE = {paciente.IdPaciente})") > 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conexao.Close();
}
}
public bool DeletarPaciente(int idPaciente)
{
FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();
try
{
_conexao.Open();
return _conexao.Execute($@"DELETE FROM TB_PACIENTE
WHERE (ID_PACIENTE = {idPaciente})") > 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conexao.Close();
}
}
}
}
|
using System;
using UnityEngine;
public static class ComponentExtensions
{
public static T GetComponentInChildren<T>(this Component parent, bool includeInactive)
{
if (parent == null)
throw new NullReferenceException();
var component = default(T);
if (!includeInactive)
{
component = parent.GetComponentInChildren<T>();
}
else
{
foreach (Transform child in parent.transform)
{
component = child.GetComponent<T>();
if (component != null)
break;
}
}
return component;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CoachPosition.Web.Models
{
public class IndexModel
{
[Required(ErrorMessage = "Не заполнено поле 'Номер поезда'")]
[Display(Name = "Номер поезда")]
[RegularExpression(@"^[a-zA-ZА-Яа-я0-9]{1,5}$", ErrorMessage = "Недопустимый формат данных")]
public string NumTrain { get; set; }
[Required(ErrorMessage = "Не заполнено поле 'Номера вагонов'")]
[Display(Name = "Номер вагона")]
[RegularExpression(@"^[1-9][0-9]{0,3}$", ErrorMessage = "Номер вагона должен содержать цифры от 1 до 22.")]
public int NumCar { get; set; }
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Collections.Generic;
using Uxnet.Web.Properties;
using Utility;
using System.ComponentModel;
namespace Uxnet.Web.Module.Ajax
{
public partial class PagingControl : System.Web.UI.UserControl
{
protected const int __PAGING_SIZE = 10;
protected int _pageSize = Settings.Default.PageSize;
protected int _currentPageIndex = 0;
protected int _recordCount = 0;
protected void Page_Load(object sender, System.EventArgs e)
{
}
[Bindable(true)]
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (value > 0)
{
_pageSize = value;
}
}
}
public int PageCount
{
get
{
return (RecordCount + PageSize - 1) / PageSize;
}
}
[Bindable(true)]
public int RecordCount
{
get
{
return _recordCount;
}
set
{
if (value > 0)
{
_recordCount = value;
}
else
{
_recordCount = 0;
}
}
}
[Bindable(true)]
public int CurrentPageIndex
{
get
{
if (_currentPageIndex < 0 && _recordCount > 0)
{
_currentPageIndex = 0;
}
return _currentPageIndex;
}
set
{
_currentPageIndex = (value >= 0) ? value : 0;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LibreriaAgapea.App_Code.Herramientas;
using LibreriaAgapea.App_Code.Modelos;
using LibreriaAgapea.App_Code.Controladores;
namespace LibreriaAgapea.Vistas
{
public partial class Login : System.Web.UI.Page
{
private Ayudante ayudante = new Ayudante();
private CUsuario cU = new CUsuario();
protected void Page_Load(object sender, EventArgs e)
{
nombre.Focus();
ayudante.construirPath((Table)Master.FindControl("table_Path"), "Inicio:Login");
}
protected void usuario_CV_ServerValidate(object source, ServerValidateEventArgs args)
{
if (cU.listaUsuarios.Where(usuario => usuario.nombre == nombre.Text && usuario.contraseña == password.Text).Count() == 1 ) args.IsValid = true; else args.IsValid = false;
}
protected void entrar_Click(object sender, EventArgs e)
{
if ( IsValid )
{
if (Request.Cookies["usuario"] != null)
{
Request.Cookies["usuario"].Value = nombre.Text;
}
else
{
HttpCookie miCookie = new HttpCookie("usuario");
miCookie.Value = nombre.Text;
Response.Cookies.Add(miCookie);
}
Response.Redirect("Centro.aspx");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Masinsko_Ucenje
{
public class LinearRegression
{
public double k { get; set; }
public double n { get; set; }
public void fit(double[] x, double[] y) {
// TODO 2: implementirati fit funkciju koja odredjuje parametre k i n
// y = kx + n
}
public double predict(double x)
{
// TODO 3: Implementirati funkciju predict koja na osnovu x vrednosti vraca
// predvinjenu vrednost y
return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoursIngesup._3___Héritage
{
class Polygone1 : Polygone
{
public Polygone1() : base()
{
points.Add(new Point());
points.Add(new Point());
}
public override int nbPoints()
{
Console.WriteLine("Nombre de points : " + base.nbPoints());
return base.nbPoints();
}
}
}
|
namespace React_Redux.Repositories
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using React_Redux.Helper;
using React_Redux.Models;
public class ProductRepository<T> : IProductRepository<T>
{
MongoClient _client;
IMongoDatabase _db;
public ProductRepository()
{
_client = new MongoClient($"mongodb://{Constants.Server.Username}:{Constants.Server.Password}@{Constants.Server.Url}");
_db = _client.GetDatabase("pwasimpleapp");
}
public IQueryable<Product> Gets()
{
return _db.GetCollection<Product>(nameof(Product)).AsQueryable();
}
public Product GetProduct(ObjectId id)
{
return _db.GetCollection<Product>(nameof(Product)).AsQueryable().FirstOrDefault(p => p.Id == id);
}
public Product Create(Product p)
{
_db.GetCollection<Product>(nameof(Product)).InsertOne(p);
return p;
}
public void Update(ObjectId id, Product p)
{
p.Id = id;
var res = Query<Product>.EQ(pd => pd.Id, id).ToBsonDocument();
_db.GetCollection<Product>(nameof(Product)).ReplaceOne(res, p);
}
public void Remove(ObjectId id)
{
var res = Query<Product>.EQ(e => e.Id, id).ToBsonDocument();
var operation = _db.GetCollection<Product>(nameof(Product)).DeleteOne(res);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace PluginStudy.WebUi.Controllers
{
public class BaseController : Controller
{
/// <summary>
/// 视图调用之前
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
/// <summary>
/// 视图调用之后
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
/// <summary>
/// 结果返回之前
/// </summary>
/// <param name="filterContext"></param>
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
/// <summary>
/// 结果返回之后
/// </summary>
/// <param name="filterContext"></param>
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonSuccess(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
//
data = new {IsSuccess = true, Data = data};
return base.Json(data, contentType, contentEncoding, behavior);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonSuccess(object data, string contentType, Encoding contentEncoding)
{
//
data = new { IsSuccess = true, Data = data };
return base.Json(data, contentType, contentEncoding);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonSuccess(object data, string contentType)
{
//
data = new { IsSuccess = true, Data = data };
return base.Json(data, contentType);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonSuccess(object data, JsonRequestBehavior behavior)
{
//
data = new { IsSuccess = true, Data = data };
return base.Json(data, behavior);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonSuccess(object data)
{
//
data = new { IsSuccess = true, Data = data };
return base.Json(data);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonFailed(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
//
data = new { IsSuccess = false, Data = data };
return base.Json(data, contentType, contentEncoding, behavior);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonFailed(object data, string contentType, Encoding contentEncoding)
{
//
data = new { IsSuccess = false, Data = data };
return base.Json(data, contentType, contentEncoding);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonFailed(object data, string contentType)
{
//
data = new { IsSuccess = false, Data = data };
return base.Json(data, contentType);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonFailed(object data, JsonRequestBehavior behavior)
{
//
data = new { IsSuccess = false, Data = data };
return base.Json(data, behavior);
}
/// <summary>
/// 返回json信息
/// 返回数据包含{IsSuccess:bool, Data:string}
/// </summary>
/// <returns></returns>
protected JsonResult JsonFailed(object data)
{
//
data = new { IsSuccess = false, Data = data };
return base.Json(data);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using OmniSharp.Extensions.JsonRpc.Testing;
using OmniSharp.Extensions.LanguageProtocol.Testing;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Window;
using TestingUtils;
using Xunit;
using Xunit.Abstractions;
namespace Lsp.Integration.Tests
{
public class CustomRequestsTests : LanguageProtocolTestBase
{
public CustomRequestsTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper))
{
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Using_Base_Class()
{
var fake = Substitute.For<TelemetryEventHandlerBase<CustomTelemetryEventParams>>();
var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { });
var @event = new CustomTelemetryEventParams
{
CodeFolding = true,
ProfileLoading = false,
ScriptAnalysis = true,
Pester5CodeLens = true,
PromptToUpdatePackageManagement = false
};
server.SendTelemetryEvent(@event);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
args[0].Should().BeOfType<CustomTelemetryEventParams>()
.And.Subject
.Should().BeEquivalentTo(@event, z => z.UsingStructuralRecordEquality().Excluding(x => x.ExtensionData));
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Receiving_Regular_Telemetry_Using_Base_Class()
{
var fake = Substitute.For<TelemetryEventHandlerBase>();
var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { });
var @event = new CustomTelemetryEventParams
{
CodeFolding = true,
ProfileLoading = false,
ScriptAnalysis = true,
Pester5CodeLens = true,
PromptToUpdatePackageManagement = false
};
server.SendTelemetryEvent(@event);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<TelemetryEventParams>().Which;
request.ExtensionData.Should().ContainKey("codeFolding").And.Subject["codeFolding"].Should().Be(true);
request.ExtensionData.Should().ContainKey("profileLoading").And.Subject["profileLoading"].Should().Be(false);
request.ExtensionData.Should().ContainKey("scriptAnalysis").And.Subject["scriptAnalysis"].Should().Be(true);
request.ExtensionData.Should().ContainKey("pester5CodeLens").And.Subject["pester5CodeLens"].Should().Be(true);
request.ExtensionData.Should().ContainKey("promptToUpdatePackageManagement").And.Subject["promptToUpdatePackageManagement"].Should().Be(false);
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Using_Extension_Data_Using_Base_Class()
{
var fake = Substitute.For<TelemetryEventHandlerBase<CustomTelemetryEventParams>>();
var (_, server) = await Initialize(options => { options.AddHandler(fake); }, options => { });
server.SendTelemetryEvent(
new TelemetryEventParams
{
ExtensionData = new Dictionary<string, object>
{
["CodeFolding"] = true,
["ProfileLoading"] = false,
["ScriptAnalysis"] = true,
["Pester5CodeLens"] = true,
["PromptToUpdatePackageManagement"] = false
}
}
);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomTelemetryEventParams>().Which;
request.CodeFolding.Should().Be(true);
request.ProfileLoading.Should().Be(false);
request.ScriptAnalysis.Should().Be(true);
request.Pester5CodeLens.Should().Be(true);
request.PromptToUpdatePackageManagement.Should().Be(false);
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Using_Delegate()
{
var fake = Substitute.For<Func<CustomTelemetryEventParams, CancellationToken, Task>>();
var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { });
var @event = new CustomTelemetryEventParams
{
CodeFolding = true,
ProfileLoading = false,
ScriptAnalysis = true,
Pester5CodeLens = true,
PromptToUpdatePackageManagement = false
};
server.SendTelemetryEvent(@event);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
args[0]
.Should().BeOfType<CustomTelemetryEventParams>()
.And.Subject
.Should().BeEquivalentTo(@event, z => z.UsingStructuralRecordEquality().Excluding(x => x.ExtensionData));
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Receiving_Regular_Telemetry_Using_Delegate()
{
var fake = Substitute.For<Func<TelemetryEventParams, CancellationToken, Task>>();
var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { });
var @event = new CustomTelemetryEventParams
{
CodeFolding = true,
ProfileLoading = false,
ScriptAnalysis = true,
Pester5CodeLens = true,
PromptToUpdatePackageManagement = false
};
server.SendTelemetryEvent(@event);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<TelemetryEventParams>().Which;
request.ExtensionData.Should().ContainKey("codeFolding").And.Subject["codeFolding"].Should().Be(true);
request.ExtensionData.Should().ContainKey("profileLoading").And.Subject["profileLoading"].Should().Be(false);
request.ExtensionData.Should().ContainKey("scriptAnalysis").And.Subject["scriptAnalysis"].Should().Be(true);
request.ExtensionData.Should().ContainKey("pester5CodeLens").And.Subject["pester5CodeLens"].Should().Be(true);
request.ExtensionData.Should().ContainKey("promptToUpdatePackageManagement").And.Subject["promptToUpdatePackageManagement"].Should().Be(false);
}
[Fact]
public async Task Should_Support_Custom_Telemetry_Using_Extension_Data_Using_Delegate()
{
var fake = Substitute.For<Func<CustomTelemetryEventParams, CancellationToken, Task>>();
var (_, server) = await Initialize(options => { options.OnTelemetryEvent(fake); }, options => { });
server.SendTelemetryEvent(
new TelemetryEventParams
{
ExtensionData = new Dictionary<string, object>
{
["CodeFolding"] = true,
["ProfileLoading"] = false,
["ScriptAnalysis"] = true,
["Pester5CodeLens"] = true,
["PromptToUpdatePackageManagement"] = false
}
}
);
await TestHelper.DelayUntil(() => fake.ReceivedCalls().Any(), CancellationToken);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomTelemetryEventParams>().Which;
request.CodeFolding.Should().Be(true);
request.ProfileLoading.Should().Be(false);
request.ScriptAnalysis.Should().Be(true);
request.Pester5CodeLens.Should().Be(true);
request.PromptToUpdatePackageManagement.Should().Be(false);
}
public record CustomTelemetryEventParams : TelemetryEventParams
{
public bool ScriptAnalysis { get; init; }
public bool CodeFolding { get; init; }
public bool PromptToUpdatePackageManagement { get; init; }
public bool ProfileLoading { get; init; }
public bool Pester5CodeLens { get; init; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
//
using DriveMgr.BLL;
using DriveMgr.Common;
namespace DriveMgr.BLL
{
public class CoachBLL
{
private static readonly DriveMgr.IDAL.ICoachDAL dal = DriveMgr.DALFactory.Factory.GetCoachDAL();
/// <summary>
/// 获取分页数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="columns">要取的列名(逗号分开)</param>
/// <param name="order">排序</param>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页</param>
/// <param name="where">查询条件</param>
/// <param name="totalCount">总记录数</param>
public string GetPager(string tableName, string columns, string order, int pageSize, int pageIndex, string where, out int totalCount)
{
return dal.GetPager(tableName, columns, order, pageSize, pageIndex, where, out totalCount);
}
/// <summary>
/// 增加一条数据
/// </summary>
public bool Add(DriveMgr.Model.CoachModel model)
{
return dal.Add(model);
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(DriveMgr.Model.CoachModel model)
{
return dal.Update(model);
}
/// <summary>
/// 删除一条数据(伪删除)
/// </summary>
public bool Delete(int ID)
{
return dal.Delete(ID);
}
/// <summary>
/// 批量删除数据(伪删除)
/// </summary>
public bool DeleteList(string IDlist)
{
return dal.DeleteList(IDlist);
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
return dal.GetRecordCount(strWhere);
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataTable GetList(string strWhere)
{
return dal.GetList(strWhere);
}
/// <summary>
/// 记录分配学员情况
/// </summary>
/// <param name="coachID"></param>
/// <param name="dtStudents"></param>
/// <returns></returns>
public bool AddDistributeStu(int coachID, DataTable dtStudents, string operater)
{
return dal.AddDistributeStu(coachID, dtStudents, operater);
}
/// <summary>
/// 自动分配学员
/// </summary>
/// <returns></returns>
public string AutoDistributeStudents(string operater)
{
//根据教练数量,学员数量平均分配
//比如:111个学员,10个教练。则每个教练分配:111/10=12(个)学员
try
{
RegistrationBLL bllStu = new RegistrationBLL();
CoachBLL bllCoach = new CoachBLL();
//得到有效的教练个数
int coachCount = this.GetRecordCount(" CoachStatus=1");
//得到还未分配教练的学员个数
int studentsCount = bllStu.GetDistributeStuRecordCount(@" flag=1 and PeriodsID = (SELECT TOP 1 CurrentPeroidID FROM tb_CurrentPeroid)
and DistributeStuStatus=0 ");
int yushu = 0;
int shoudDistributeCount = Math.DivRem(studentsCount, coachCount, out yushu);
if (yushu != 0)
{
shoudDistributeCount += 1;
}
//int shoudDistributeCount = (studentsCount / coachCount) + 1;
DataTable dtCoach = this.GetList(" CoachStatus=1");
int startIndex = 0;
int endIndex = shoudDistributeCount;
for (int i = 0; i < dtCoach.Rows.Count; i++)
{
DataTable dtStudents = bllStu.GetDistributeStuListByPage(@" flag=1 and PeriodsID = (SELECT TOP 1 CurrentPeroidID FROM tb_CurrentPeroid)
and DistributeStuStatus=0 ", "ID", startIndex, endIndex);
int coachID = Int32.Parse(dtCoach.Rows[i]["ID"].ToString());
bool result = AddDistributeStu(coachID, dtStudents, operater);
}
return "共有学员" + studentsCount + "个;教练" + coachCount + "个;每个教练分得学员" + shoudDistributeCount + "个.";
}
catch
{
return "自动分配学员出错,请检查!";
}
}
/// <summary>
/// 更新分配学员信息
/// </summary>
public bool EditDistributeStudents(DriveMgr.Model.DistributeStudentsModel model)
{
return dal.EditDistributeStudents(model);
}
/// <summary>
/// 获得教练培训学员情况
/// </summary>
/// <param name="year"></param>
/// <returns></returns>
public DataSet GetCoachTeachInfo(int peridID)
{
return dal.GetCoachTeachInfo(peridID);
}
/// <summary>
/// 取数据,构造json数据,为画图做准备
/// </summary>
/// <param name="type"></param>
/// <param name="checkedYear"></param>
/// <returns></returns>
public HighChartOptions GetCoachTeachHighchart(HighchartTypeEnum type, int peridID, string peridName)
{
DataSet ds = GetCoachTeachInfo(peridID);
List<Series> ser = new List<Series>();
List<string> xaxis = new List<string>();
for (int j = 1; j < ds.Tables[0].Columns.Count; j++)
{
Series s = new Series();
List<object> obj = new List<object>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string coachName = ds.Tables[0].Rows[i]["CoachName"].ToString();
xaxis.Add(coachName);
int tname = Int32.Parse(ds.Tables[0].Rows[i][j].ToString());
obj.Add(tname);
}
s.data = obj;
s.type = ChartTypeEnum.column.ToString();
s.allowPointSelect = false;
if (j == 1)
{
s.name = "在学";
}
else if (j == 2)
{
s.name = "毕业";
}
else if (j == 3)
{
s.name = "退学";
}
ser.Add(s);
}
HighChartOptions currentChart = new HighChartOptions();
currentChart = new HighChartOptions()
{
//chart = new Chart()
//{
// renderTo = "highChartDiv",
// type = ChartTypeEnum.area.ToString(),
// reflow=true
//},
title = new Title() { text = peridName + "期教练培训学员情况图" },
xAxis = new List<XAxis>() {
new XAxis(){
categories = xaxis,
reversed = false,
opposite = false
}
},
yAxis = new YAxis() { title = new Title() { text = peridName + "期教练培训学员" } },
//tooltip = new ToolTip() { crosshairs = new List<bool>() { true, false } },
series = ser
};
return currentChart;
}
}
}
|
namespace Breezy.Sdk.Printing
{
public enum OutputColor
{
Unknown,
Color,
Grayscale,
Monochrome
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using PlayTennis.Bll;
using PlayTennis.Model;
namespace PlayTennis.WebApi.Controllers
{
public class TennisCourtController : ApiController
{
public TennisCourtController()
{
UserLoginService = new UserLoginService();
MyService = new TennisCourtService();
UserInformationService = new UserInformationService();
}
public UserLoginService UserLoginService { get; set; }
public TennisCourtService MyService { get; set; }
public UserInformationService UserInformationService { get; set; }
// GET: api/TennisCourt
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/TennisCourt/5
// GET: api/SportsEquipment/5
public TennisCourt Get(Guid id)
{
var userInfor = UserInformationService.GetUserInformationById(id);
if (userInfor != null)
{
return MyService.GetEntityFirstOrDefault(p => p.UserInformationId == userInfor.Id);
}
return null;
//return MyService.GetEntityByid(id);
}
// POST: api/SportsEquipment
/// <summary>
/// 新增
/// </summary>
/// <param name="id">wxid</param>
/// <param name="entity"></param>
public void Post(Guid id, TennisCourt entity)
{
var wxUser = UserLoginService.GetWxUserByuserid(id);
MyService.AddTennisCourt(entity, wxUser);
}
// PUT: api/SportsEquipment/5
public void Put(TennisCourt entity)
{
var oldEntity = MyService.GetEntityByid(entity.Id);
if (oldEntity != null)
{
oldEntity.CourtAddress = entity.CourtAddress;
oldEntity.CourtName = entity.CourtName;
oldEntity.OpenTime = entity.OpenTime;
oldEntity.UserLocation = entity.UserLocation;
MyService.EditEntity(oldEntity);
}
}
// DELETE: api/TennisCourt/5
public void Delete(int id)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Negozio.Core;
using Negozio.DataAccess.DbModel;
using Negozio.DataAccess.Services;
using Negozio.Dto;
namespace Movie.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FilmsController : ControllerBase
{
private readonly IFilmService _filmService;
private readonly IFilmCore _filmCore;
public FilmsController(IFilmService filmService, IFilmCore filmCore)
{
_filmService = filmService;
_filmCore = filmCore;
}
// GET: api/Film
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
var tomap = await _filmService.GetFilms();
var res = AnswerFilm.MappaPerLista(tomap);
return Ok(res);
}
catch (Exception)
{
return StatusCode(500, null);
}
}
// GET: api/Film/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
try
{
var toMap = await _filmService.GetFilm(id);
if (toMap == null)
{
return NotFound();
}
else
{
return Ok(AnswerFilm.MappaFilm(toMap));
}
}
catch (Exception)
{
return StatusCode(500, null);
}
}
// POST: api/Film
[HttpPost]
public async Task<IActionResult> Post([FromBody] RequestFilm value)
{
try
{
var res = await _filmCore.PostFilm(value);
if (res != 0)
{
return Ok(res);
}
else
{
return BadRequest();
}
}
catch (Exception)
{
return StatusCode(500, null);
}
}
// PUT: api/Film/5
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, [FromBody] Film film)
{
try
{
film.FilmId = id;
var res = await _filmService.UpdateFilm(film);
if (res)
{
return Ok();
}
else
{
return NotFound();
}
}
catch (Exception)
{
return StatusCode(500, null);
}
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
var res = await _filmService.DeleteFilm(id);
if (res)
{
return Ok();
}
else
{
return NotFound();
}
}
catch (Exception)
{
return StatusCode(500, null);
}
}
}
}
|
using System;
namespace OCP.Files
{
/**
* Class InvalidDirectoryException
*
* @package OCP\Files
* @since 9.2.0
*/
class InvalidDirectoryException : InvalidPathException
{
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using ProductTest.Models;
namespace ProductTest.Data
{
public interface IBulkUpload
{
Task<List<SkuTest>> UploadSku(List<SkuTest> skus);
Task<List<PatternTest>> UploadPattern(List<PatternTest> patterns);
Task<List<Test>> Testing(List<Test> test);
Task<List<BooleanTest>> Bool(List<BooleanTest> bools);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NestingParent : BaseEnemy
{
[SerializeField]
Vector2 _knockback = Vector2.zero;
[SerializeField]
Transform dest = null;
[SerializeField]
GameObject _child = null;
[SerializeField]
GameObject _child2 = null;
[SerializeField] AudioManager SFX = null;
Vector3 Target = Vector2.zero;
Vector3 Home = Vector2.zero;
Vector3 moveChild = Vector3.zero;
Vector3 moveChild2 = Vector3.zero;
// Start is called before the first frame update
protected override void Start()
{
base.Start();
_rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
Target = dest.position;
Home = transform.position;
moveChild = transform.position + new Vector3(0.5f, 0, 0);
moveChild2 = transform.position + new Vector3(0.75f, 0, 0);
}
// Update is called once per frame
void Update()
{
if(_canTakeDamage)
{
Move();
}
}
private void Move()
{
float step = speed * Time.deltaTime;
///////////////////////////////////////////////////////
// If the enemy reached it's target position,
// turn around, and reset target
///////////////////////////////////////////////////////
if (Mathf.Abs(transform.position.x - Target.x) <= 0.01f)
{
TurnOnY();
if (Target == Home)
{
Target = dest.position;
}
else
{
Target = Home;
}
}
transform.position = Vector2.MoveTowards(transform.position, Target, step);
}
public override void TakeDamage(int _damage, Vector3 _damageSource)
{
if (_canTakeDamage)
{
health -= _damage;
if (_damage > 0)
{
SFX.Play("ND_Damaged");
HitEffect.Play();
Knockback(_knockback, _damageSource);
}
if (health <= 0)
{
SFX.Play("ND_Break1");
_canTakeDamage = false;
anim.SetBool("Dying", true);
Invoke("split", 1f);
}
}
}
private void split()
{
Instantiate(_child, moveChild, transform.rotation);
Instantiate(_child2, moveChild2, transform.rotation);
Die();
}
private void Knockback(Vector2 knockbackPower, Vector2 contactPos)
{
_rb.velocity = Vector2.zero;
if (contactPos.x > transform.position.x)
{
_rb.AddForce(new Vector2(-knockbackPower.x, knockbackPower.y));
}
else if (contactPos.x < transform.position.x)
{
_rb.AddForce(new Vector2(knockbackPower.x, knockbackPower.y));
}
}
override protected void OnTriggerEnter2D(Collider2D _other)
{
if (_other.gameObject.tag == "Player")
{
SFX.Play("ND_Attack");
_other.gameObject.GetComponent<PlayerController2D>().TakeDamage(10);
}
}
}
|
namespace BookShopSytem.Models.BM
{
public class EditCatBM
{
public string Name { get; set; }
}
}
|
using System;
using System.Linq;
using Boo.Lang;
using Game.Online.Manager;
using UnityEngine;
using UnityEngine.UI;
namespace Game.Online.Web.Users
{
public class UserHandler : MonoBehaviour
{
[SerializeField] private GameObject _userPrefab;
public Transform Parent;
public List<User> Users = new List<User>();
public uint OnlineCount;
public Text Header;
private List<UserPlaceholders> _placeholders = new List<UserPlaceholders>();
public void UpdateHeader(uint usersCount)
{
Header.text = $"online - {OnlineCount}";
}
public void AddUser(User user)
{
if(Users.Any(x => x.Id == user.Id))
return;
Users.Add(user);
var userObject = Instantiate(_userPrefab, Parent, true);
userObject.transform.localScale = new Vector3(1,1,1);
var userPlaceholders = userObject.GetComponent<UserPlaceholders>();
_placeholders.Add(userPlaceholders);
userPlaceholders.Init(user, user.Username, user.Score.ToString(), user.Rank.ToString(), user.SpacePoints.ToString());
}
public void RemoveUser(User user)
{
Users.Remove(user);
var pHolder = _placeholders.FirstOrDefault(x => x.User == user);
Destroy(pHolder.gameObject);
_placeholders.Remove(pHolder);
OnlineCount--;
UpdateHeader(OnlineCount);
}
public void UpdateUserState(User user, UserStare userStare)
{
switch (userStare)
{
case UserStare.Offline:
Users.Remove(user);
break;
case UserStare.Online:
AddUser(user);
break;
default:
throw new ArgumentOutOfRangeException(nameof(userStare), userStare, null);
}
}
}
public enum UserStare
{
Offline,
Online
}
} |
// --------------------------------
// <copyright file="Location.cs" >
// © 2013 KarzPlus Inc.
// </copyright>
// <author>JOrtega</author>
// <summary>
// Location Entity Layer Object.
// </summary>
// ---------------------------------
using System;
using KarzPlus.Entities.Common;
namespace KarzPlus.Entities
{
/// <summary>
/// Location entity object.
/// </summary>
[Serializable]
public class Location
{
public bool IsItemModified { get; set; }
public string FullAddress { get { return string.Format("Location Name- {0} Address: {1} {2}, {3}, {4}", Name, Address, City, State, Zip); } }
private int? locationId;
/// <summary>
/// Gets or sets LocationId.
/// </summary>
[SqlName("LocationId")]
public int? LocationId
{
get
{
return locationId;
}
set
{
if (value != locationId)
{
locationId = value;
IsItemModified = true;
}
}
}
private string name;
/// <summary>
/// Gets or sets Name.
/// </summary>
[SqlName("Name")]
public string Name
{
get
{
return name;
}
set
{
if (value != name)
{
name = value;
IsItemModified = true;
}
}
}
private string address;
/// <summary>
/// Gets or sets Address.
/// </summary>
[SqlName("Address")]
public string Address
{
get
{
return address;
}
set
{
if (value != address)
{
address = value;
IsItemModified = true;
}
}
}
private string city;
/// <summary>
/// Gets or sets City.
/// </summary>
[SqlName("City")]
public string City
{
get
{
return city;
}
set
{
if (value != city)
{
city = value;
IsItemModified = true;
}
}
}
private string state;
/// <summary>
/// Gets or sets State.
/// </summary>
[SqlName("State")]
public string State
{
get
{
return state;
}
set
{
if (value != state)
{
state = value;
IsItemModified = true;
}
}
}
private string zip;
/// <summary>
/// Gets or sets Zip.
/// </summary>
[SqlName("Zip")]
public string Zip
{
get
{
return zip;
}
set
{
if (value != zip)
{
zip = value;
IsItemModified = true;
}
}
}
private bool deleted;
/// <summary>
/// Gets or sets Deleted.
/// </summary>
[SqlName("Deleted")]
public bool Deleted
{
get
{
return deleted;
}
set
{
if (value != deleted)
{
deleted = value;
IsItemModified = true;
}
}
}
private string phone;
/// <summary>
/// Gets or sets Phone
/// </summary>
[SqlName("Phone")]
public string Phone
{
get
{
return phone;
}
set
{
if (value != phone)
{
phone = value;
IsItemModified = true;
}
}
}
private string email;
/// <summary>
/// Gets or sets Email
/// </summary>
[SqlName("Email")]
public string Email
{
get
{
return email;
}
set
{
if (value != email)
{
email = value;
IsItemModified = true;
}
}
}
/// <summary>
/// Initializes a new instance of the Location class.
/// </summary>
public Location()
{
LocationId = default(int?);
Name = default(string);
Address = default(string);
City = default(string);
State = default(string);
Zip = default(string);
Phone = default(string);
Email = default(string);
Deleted = default(bool);
IsItemModified = false;
}
public override string ToString()
{
return string.Format("LocationId: {0}, Name: {1}, City: {2}, State: {3};", LocationId, Name, City, State);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EuclidianSpace3D
{
using System.IO;
public static class Path
{
private static Random pointsGenerator = new Random();
public static List<Point3D> GeneretePath(int numberOfPoints)
{
var path = new List<Point3D>(numberOfPoints);
for (int point = 0; point < numberOfPoints; point++)
{
path.Add(new Point3D(pointsGenerator.Next(1, 20), pointsGenerator.Next(1, 20), pointsGenerator.Next(1, 20)));
}
return path;
}
public static void SavePathToStorge( List<Point3D> path)
{
var writer = new StreamWriter(@"path.txt");
using (writer)
{
foreach (var point in path)
{
string line = point.X + " " + point.Y + " " + point.Z;
writer.WriteLine(line);
}
}
}
public static List<Point3D> LoadPathFromStorage()
{
var path = new List<Point3D>();
var reader =new StreamReader(@"path.txt");
var line = reader.ReadLine();
using (reader)
{
while (line != null)
{
int[] coords = line.Split(' ')
.Select(x => int.Parse(x))
.ToArray();
var point = new Point3D(coords[0], coords[1], coords[2]);
path.Add(point);
line = reader.ReadLine();
}
}
return path;
}
}
}
|
namespace Homework2.Models.Configuration
{
public class ProductsRepositoryConfig
{
public string Database { get; set; }
public string Collection { get; set; }
}
} |
using IoUring.Internal;
using Tmds.Linux;
using static Tmds.Linux.LibC;
using static IoUring.Internal.ThrowHelper;
namespace IoUring
{
public unsafe partial class Ring
{
/// <summary>
/// Adds a NOP to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareNop(ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareNopInternal(userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a NOP to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareNop(ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareNopInternal(userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareNopInternal(ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_NOP;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a readv, preadv or preadv2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="iov">I/O vectors to read to</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="flags">Flags for the I/O (as per preadv2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareReadV(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareReadVInternal(fd, iov, count, offset, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a readv, preadv or preadv2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="iov">I/O vectors to read to</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="flags">Flags for the I/O (as per preadv2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareReadV(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareReadVInternal(fd, iov, count, offset, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareReadVInternal(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_READV;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) iov;
sqe->len = (uint) count;
sqe->rw_flags = flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a readv, preadv or preadv2 with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="iov">I/O vectors to read to</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="flags">Flags for the I/O (as per preadv2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareReadV(int fd, iovec* iov, int count, int bgid, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareReadVInternal(fd, iov, count, bgid, offset, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a readv, preadv or preadv2 with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="iov">I/O vectors to read to</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="flags">Flags for the I/O (as per preadv2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareReadV(int fd, iovec* iov, int count, int bgid, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareReadVInternal(fd, iov, count, bgid, offset, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareReadVInternal(int fd, iovec* iov, int count, int bgid, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_READV;
sqe->flags = (byte) ((byte) options | IOSQE_BUFFER_SELECT);
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) iov;
sqe->len = (uint) count;
sqe->rw_flags = flags;
sqe->user_data = userData;
sqe->buf_group = (ushort) bgid;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a writev, pwritev or pwritev2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to write to</param>
/// <param name="iov">I/O vectors to write</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="offset">Offset at which the I/O is performed (as per pwritev)</param>
/// <param name="flags">Flags for the I/O (as per pwritev2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareWriteV(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareWriteVInternal(fd, iov, count, offset, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a writev, pwritev or pwritev2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to write to</param>
/// <param name="iov">I/O vectors to write</param>
/// <param name="count">Number of I/O vectors</param>
/// <param name="offset">Offset at which the I/O is performed (as per pwritev)</param>
/// <param name="flags">Flags for the I/O (as per pwritev2)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareWriteV(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareWriteVInternal(fd, iov, count, offset, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareWriteVInternal(int fd, iovec* iov, int count, off_t offset = default, int flags = 0, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_WRITEV;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) iov;
sqe->len = (uint) count;
sqe->rw_flags = flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a fsync to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to synchronize</param>
/// <param name="fsyncOptions">Integrity options</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareFsync(int fd, FsyncOption fsyncOptions = FsyncOption.FileIntegrity, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareFsyncInternal(fd, fsyncOptions, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a fsync to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to synchronize</param>
/// <param name="fsyncOptions">Integrity options</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareFsync(int fd, FsyncOption fsyncOptions = FsyncOption.FileIntegrity, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareFsyncInternal(fd, fsyncOptions, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareFsyncInternal(int fd, FsyncOption fsyncOptions = FsyncOption.FileIntegrity, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_FSYNC;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->fsync_flags = (uint) fsyncOptions;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a read using a registered buffer/file to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="buf">Buffer/file to read to</param>
/// <param name="count">Number of bytes to read</param>
/// <param name="index">Index of buffer/file</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareReadFixed(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareReadFixedInternal(fd, buf, count, index, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a read using a registered buffer/file to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to read from</param>
/// <param name="buf">Buffer/file to read to</param>
/// <param name="count">Number of bytes to read</param>
/// <param name="index">Index of buffer/file</param>
/// <param name="offset">Offset at which the I/O is performed (as per preadv)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareReadFixed(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareReadFixedInternal(fd, buf, count, index, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareReadFixedInternal(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_READ_FIXED;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) buf;
sqe->len = (uint) count;
sqe->buf_index = (ushort) index;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a write using a registered buffer/file to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to write to</param>
/// <param name="buf">Buffer/file to write</param>
/// <param name="count">Number of bytes to write</param>
/// <param name="index">Index of buffer/file</param>
/// <param name="offset">Offset at which the I/O is performed (as per pwritev)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareWriteFixed(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareWriteFixedInternal(fd, buf, count, index, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a write using a registered buffer/file to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to write to</param>
/// <param name="buf">Buffer/file to write</param>
/// <param name="count">Number of bytes to write</param>
/// <param name="index">Index of buffer/file</param>
/// <param name="offset">Offset at which the I/O is performed (as per pwritev)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareWriteFixed(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareWriteFixedInternal(fd, buf, count, index, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareWriteFixedInternal(int fd, void* buf, size_t count, int index, off_t offset = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_WRITE_FIXED;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) buf;
sqe->len = (uint) count;
sqe->buf_index = (ushort) index;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a one-shot poll of the file descriptor to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to poll</param>
/// <param name="pollEvents">Events to poll for</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PreparePollAdd(int fd, ushort pollEvents, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PreparePollAddInternal(fd, pollEvents, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a one-shot poll of the file descriptor to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to poll</param>
/// <param name="pollEvents">Events to poll for</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPreparePollAdd(int fd, ushort pollEvents, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PreparePollAddInternal(fd, pollEvents, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PreparePollAddInternal(int fd, ushort pollEvents, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_POLL_ADD;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->poll_events = pollEvents;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a request for removal of a previously added poll request to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="pollUserData">userData of the poll submission that should be removed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PreparePollRemove(ulong pollUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PreparePollRemoveInternal(pollUserData, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a request for removal of a previously added poll request to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="pollUserData">userData of the poll submission that should be removed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPreparePollRemove(ulong pollUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PreparePollRemoveInternal(pollUserData, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PreparePollRemoveInternal(ulong pollUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_POLL_REMOVE;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->addr = pollUserData;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a sync_file_range to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to sync</param>
/// <param name="offset">Offset in bytes into the file</param>
/// <param name="count">Number of bytes to sync</param>
/// <param name="flags">Flags for the operation (as per sync_file_range)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareSyncFileRange(int fd, off_t offset, off_t count, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareSyncFileRangeInternal(fd, offset, count, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a sync_file_range to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to sync</param>
/// <param name="offset">Offset in bytes into the file</param>
/// <param name="count">Number of bytes to sync</param>
/// <param name="flags">Flags for the operation (as per sync_file_range)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareSyncFileRange(int fd, off_t offset, off_t count, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareSyncFileRangeInternal(fd, offset, count, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareSyncFileRangeInternal(int fd, off_t offset, off_t count, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_SYNC_FILE_RANGE;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->len = (uint) count;
sqe->sync_range_flags = flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a sendmsg to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to send to</param>
/// <param name="msg">Message to send</param>
/// <param name="flags">Flags for the operation (as per sendmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareSendMsg(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareSendMsgInternal(fd, msg, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a sendmsg to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to send to</param>
/// <param name="msg">Message to send</param>
/// <param name="flags">Flags for the operation (as per sendmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareSendMsg(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareSendMsgInternal(fd, msg, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareSendMsgInternal(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_SENDMSG;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->addr = (ulong) msg;
sqe->len = 1;
sqe->msg_flags = flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a recvmsg to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to receive from</param>
/// <param name="msg">Message to read to</param>
/// <param name="flags">Flags for the operation (as per recvmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRecvMsg(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareRecvMsgInternal(fd, msg, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a recvmsg to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to receive from</param>
/// <param name="msg">Message to read to</param>
/// <param name="flags">Flags for the operation (as per recvmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRecvMsg(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareRecvMsgInternal(fd, msg, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareRecvMsgInternal(int fd, msghdr* msg, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_RECVMSG;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->addr = (ulong) msg;
sqe->len = 1;
sqe->msg_flags = flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a recvmsg with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to receive from</param>
/// <param name="msg">Message to read to</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="flags">Flags for the operation (as per recvmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRecvMsg(int fd, msghdr* msg, int bgid, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareRecvMsgInternal(fd, msg, bgid, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a recvmsg with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to receive from</param>
/// <param name="msg">Message to read to</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="flags">Flags for the operation (as per recvmsg)</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRecvMsg(int fd, msghdr* msg, int bgid, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareRecvMsgInternal(fd, msg, bgid, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareRecvMsgInternal(int fd, msghdr* msg, int bgid, uint flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_RECVMSG;
sqe->flags = (byte) ((byte) options | IOSQE_BUFFER_SELECT);
sqe->fd = fd;
sqe->addr = (ulong) msg;
sqe->len = 1;
sqe->msg_flags = flags;
sqe->user_data = userData;
sqe->buf_group = (ushort) bgid;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a timeout to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="ts">The amount of time after which the timeout should trigger if less than <paramref name="count"/> submissions completed.</param>
/// <param name="count">The amount of completed submissions after which the timeout should trigger</param>
/// <param name="timeoutOptions">Options on how <paramref name="ts"/> is interpreted</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareTimeout(timespec* ts, uint count = 1, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareTimeoutInternal(ts, count, timeoutOptions, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a timeout to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="ts">The amount of time after which the timeout should trigger if less than <paramref name="count"/> submissions completed.</param>
/// <param name="count">The amount of completed submissions after which the timeout should trigger</param>
/// <param name="timeoutOptions">Options on how <paramref name="ts"/> is interpreted</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareTimeout(timespec* ts, uint count = 1, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareTimeoutInternal(ts, count, timeoutOptions, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareTimeoutInternal(timespec* ts, uint count = 1, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_TIMEOUT;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->off = count;
sqe->addr = (ulong) ts;
sqe->len = 1;
sqe->timeout_flags = (uint) timeoutOptions;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds the removal of a timeout to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="timeoutUserData">userData of the timeout submission that should be removed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareTimeoutRemove(ulong timeoutUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareTimeoutRemoveInternal(timeoutUserData, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add the removal of a timeout to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="timeoutUserData">userData of the timeout submission that should be removed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareTimeoutRemove(ulong timeoutUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareTimeoutRemoveInternal(timeoutUserData, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareTimeoutRemoveInternal(ulong timeoutUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_TIMEOUT_REMOVE;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->addr = timeoutUserData;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds an accept to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to accept from</param>
/// <param name="addr">(out) the address of the connected client.</param>
/// <param name="addrLen">(out) the length of the address</param>
/// <param name="flags">Flags as per accept4</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareAccept(int fd, sockaddr* addr, socklen_t* addrLen, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareAcceptInternal(fd, addr, addrLen, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add an accept to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to accept from</param>
/// <param name="addr">(out) the address of the connected client.</param>
/// <param name="addrLen">(out) the length of the address</param>
/// <param name="flags">Flags as per accept4</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareAccept(int fd, sockaddr* addr, socklen_t* addrLen, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareAcceptInternal(fd, addr, addrLen, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareAcceptInternal(int fd, sockaddr* addr, socklen_t* addrLen, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_ACCEPT;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) addrLen;
sqe->addr = (ulong) addr;
sqe->accept_flags = (uint) flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds the cancellation of a previously submitted item to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="opUserData">userData of the operation to cancel</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareCancel(ulong opUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareCancelInternal(opUserData, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add the cancellation of a previously submitted item to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="opUserData">userData of the operation to cancel</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareCancel(ulong opUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareCancelInternal(opUserData, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareCancelInternal(ulong opUserData, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_ASYNC_CANCEL;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->addr = opUserData;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a timeout to a previously prepared linked item to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="ts">The amount of time after which the timeout should trigger</param>
/// <param name="timeoutOptions">Options on how <paramref name="ts"/> is interpreted</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareLinkTimeout(timespec* ts, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareLinkTimeoutInternal(ts, timeoutOptions, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a timeout to a previously prepared linked item to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="ts">The amount of time after which the timeout should trigger</param>
/// <param name="timeoutOptions">Options on how <paramref name="ts"/> is interpreted</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareLinkTimeout(timespec* ts, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareLinkTimeoutInternal(ts, timeoutOptions, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareLinkTimeoutInternal(timespec* ts, TimeoutOptions timeoutOptions = TimeoutOptions.Relative, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_LINK_TIMEOUT;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->addr = (ulong) ts;
sqe->len = 1;
sqe->timeout_flags = (uint) timeoutOptions;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a connect to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">The socket to connect on</param>
/// <param name="addr">The address to connect to</param>
/// <param name="addrLen">The length of the address</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareConnect(int fd, sockaddr* addr, socklen_t addrLen, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareConnectInternal(fd, addr, addrLen, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a connect to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">The socket to connect on</param>
/// <param name="addr">The address to connect to</param>
/// <param name="addrLen">The length of the address</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareConnect(int fd, sockaddr* addr, socklen_t addrLen, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareConnectInternal(fd, addr, addrLen, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareConnectInternal(int fd, sockaddr* addr, socklen_t addrLen, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_CONNECT;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = addrLen;
sqe->addr = (ulong) addr;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a fallocate to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">The file to manipulate the allocated disk space for</param>
/// <param name="mode">The operation to be performed</param>
/// <param name="offset">Offset in bytes into the file</param>
/// <param name="len">Number of bytes to operate on</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareFallocate(int fd, int mode, off_t offset, off_t len, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareFallocateInternal(fd, mode, offset, len, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a fallocate to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">The file to manipulate the allocated disk space for</param>
/// <param name="mode">The operation to be performed</param>
/// <param name="offset">Offset in bytes into the file</param>
/// <param name="len">Number of bytes to operate on</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareFallocate(int fd, int mode, off_t offset, off_t len, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareFallocateInternal(fd, mode, offset, len, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareFallocateInternal(int fd, int mode, off_t offset, off_t len, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_FALLOCATE;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) (long) len;
sqe->len = (uint) mode;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a closeat to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor</param>
/// <param name="path">Path to be opened</param>
/// <param name="flags">Flags for the open operation (e.g. access mode)</param>
/// <param name="mode">File mode bits</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareOpenAt(int dfd, byte* path, int flags, mode_t mode = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareOpenAtInternal(dfd, path, flags, mode, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a closeat to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor</param>
/// <param name="path">Path to be opened</param>
/// <param name="flags">Flags for the open operation (e.g. access mode)</param>
/// <param name="mode">File mode bits</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareOpenAt(int dfd, byte* path, int flags, mode_t mode = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareOpenAtInternal(dfd, path, flags, mode, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareOpenAtInternal(int dfd, byte* path, int flags, mode_t mode = default, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_OPENAT;
sqe->flags = (byte) options;
sqe->fd = dfd;
sqe->addr = (ulong) path;
sqe->len = (uint) mode;
sqe->open_flags = (uint) flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a close to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to close</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareClose(int fd, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareCloseInternal(fd, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a close to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor to close</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareClose(int fd, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareCloseInternal(fd, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareCloseInternal(int fd, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_CLOSE;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds an update to the registered files to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fds">File descriptors to add / -1 to remove</param>
/// <param name="nrFds">Number of changing file descriptors</param>
/// <param name="offset">Offset into the previously registered files</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareFilesUpdate(int* fds, int nrFds, int offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareFilesUpdateInternal(fds, nrFds, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add an update to the registered files to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fds">File descriptors to add / -1 to remove</param>
/// <param name="nrFds">Number of changing file descriptors</param>
/// <param name="offset">Offset into the previously registered files</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareFilesUpdate(int* fds, int nrFds, int offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareFilesUpdateInternal(fds, nrFds, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareFilesUpdateInternal(int* fds, int nrFds, int offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_CLOSE;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) fds;
sqe->len = (uint) nrFds;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a statx to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor for relative paths</param>
/// <param name="path">Absolute or relative path</param>
/// <param name="flags">Influence pathname-based lookup</param>
/// <param name="mask">Identifies the required fields</param>
/// <param name="statxbuf">Buffer for the required information</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareStatx(int dfd, byte* path, int flags, uint mask, statx* statxbuf, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareStatxInternal(dfd, path, flags, mask, statxbuf, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a statx to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor for relative paths</param>
/// <param name="path">Absolute or relative path</param>
/// <param name="flags">Influence pathname-based lookup</param>
/// <param name="mask">Identifies the required fields</param>
/// <param name="statxbuf">Buffer for the required information</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareStatx(int dfd, byte* path, int flags, uint mask, statx* statxbuf, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareStatxInternal(dfd, path, flags, mask, statxbuf, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareStatxInternal(int dfd, byte* path, int flags, uint mask, statx* statxbuf, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_STATX;
sqe->flags = (byte) options;
sqe->fd = dfd;
sqe->off = (ulong) statxbuf;
sqe->addr = (ulong) path;
sqe->len = mask;
sqe->statx_flags = (uint) flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a read to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="buf">Buffer to read to</param>
/// <param name="nbytes">Number of bytes to read</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRead(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareReadInternal(fd, buf, nbytes, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a read to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="buf">Buffer to read to</param>
/// <param name="nbytes">Number of bytes to read</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRead(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareReadInternal(fd, buf, nbytes, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareReadInternal(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_READ;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) buf;
sqe->len = nbytes;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a read with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="nbytes">Number of bytes to read</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRead(int fd, int bgid, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareReadInternal(fd, bgid, nbytes, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a read with buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="bgid">Group ID for buffer selection</param>
/// <param name="nbytes">Number of bytes to read</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRead(int fd, int bgid, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareReadInternal(fd, bgid, nbytes, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareReadInternal(int fd, int bgid, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_READ;
sqe->flags = (byte) ((byte) options | IOSQE_BUFFER_SELECT);
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->len = nbytes;
sqe->user_data = userData;
sqe->buf_group = (ushort) bgid;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a write to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="buf">Buffer to write</param>
/// <param name="nbytes">Number of bytes to write</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareWrite(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareWriteInternal(fd, buf, nbytes, offset, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a write to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="buf">Buffer to write</param>
/// <param name="nbytes">Number of bytes to write</param>
/// <param name="offset">Offset at which the I/O is performed</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareWrite(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareWriteInternal(fd, buf, nbytes, offset, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareWriteInternal(int fd, void* buf, uint nbytes, off_t offset, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_WRITE;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->addr = (ulong) buf;
sqe->len = nbytes;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a posix_fadvise to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="offset">Offset into the file</param>
/// <param name="len">Length of the file range</param>
/// <param name="advice">Advice for the file range</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareFadvise(int fd, off_t offset, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareFadviseInternal(fd, offset, len, advice, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a posix_fadvise to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fd">File descriptor</param>
/// <param name="offset">Offset into the file</param>
/// <param name="len">Length of the file range</param>
/// <param name="advice">Advice for the file range</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareFadvise(int fd, off_t offset, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareFadviseInternal(fd, offset, len, advice, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareFadviseInternal(int fd, off_t offset, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_FADVISE;
sqe->flags = (byte) options;
sqe->fd = fd;
sqe->off = (ulong) (long) offset;
sqe->len = (uint) len;
sqe->fadvise_advice = (uint) advice;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds an madvise to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="addr">Start of address range</param>
/// <param name="len">Length of address range</param>
/// <param name="advice">Advice for address range</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareMadvise(void* addr, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareMadviseInternal(addr, len, advice, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add an madvise to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="addr">Start of address range</param>
/// <param name="len">Length of address range</param>
/// <param name="advice">Advice for address range</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareMadvise(void* addr, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareMadviseInternal(addr, len, advice, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareMadviseInternal(void* addr, off_t len, int advice, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_MADVISE;
sqe->flags = (byte) options;
sqe->fd = -1;
sqe->len = (uint) len;
sqe->fadvise_advice = (uint) advice;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a send to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="sockfd">Socket file descriptor</param>
/// <param name="buf">Buffer to send</param>
/// <param name="len">Length of buffer to send</param>
/// <param name="flags">Flags for the send</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareSend(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareSendInternal(sockfd, buf, len, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a send to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="sockfd">Socket file descriptor</param>
/// <param name="buf">Buffer to send</param>
/// <param name="len">Length of buffer to send</param>
/// <param name="flags">Flags for the send</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareSend(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareSendInternal(sockfd, buf, len, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareSendInternal(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_SEND;
sqe->flags = (byte) options;
sqe->fd = sockfd;
sqe->addr = (ulong) buf;
sqe->len = (uint) len;
sqe->msg_flags = (uint) flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a recv to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="sockfd">Socket file descriptor</param>
/// <param name="buf">Buffer to read to</param>
/// <param name="len">Length of buffer to read to</param>
/// <param name="flags">Flags for the recv</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRecv(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareRecvInternal(sockfd, buf, len, flags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a recv to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="sockfd">Socket file descriptor</param>
/// <param name="buf">Buffer to read to</param>
/// <param name="len">Length of buffer to read to</param>
/// <param name="flags">Flags for the recv</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRecv(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareRecvInternal(sockfd, buf, len, flags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareRecvInternal(int sockfd, void* buf, size_t len, int flags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_RECV;
sqe->flags = (byte) options;
sqe->fd = sockfd;
sqe->addr = (ulong) buf;
sqe->len = (uint) len;
sqe->msg_flags = (uint) flags;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds an openat2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor</param>
/// <param name="path">Path to be opened</param>
/// <param name="how">How pat should be opened</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareOpenAt2(int dfd, byte* path, open_how* how, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareOpenAt2Internal(dfd, path, how, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add an openat2 to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="dfd">Directory file descriptor</param>
/// <param name="path">Path to be opened</param>
/// <param name="how">How pat should be opened</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareOpenAt2(int dfd, byte* path, open_how* how, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareOpenAt2Internal(dfd, path, how, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareOpenAt2Internal(int dfd, byte* path, open_how* how, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_OPENAT2;
sqe->flags = (byte) options;
sqe->fd = dfd;
sqe->off = (ulong) how;
sqe->addr = (ulong) path;
sqe->len = SizeOf.open_how;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds an epoll_ctl to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="epfd">epoll instance file descriptor</param>
/// <param name="fd">File descriptor</param>
/// <param name="op">Operation to be performed for the file descriptor</param>
/// <param name="ev">Settings</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareEpollCtl(int epfd, int fd, int op, epoll_event* ev, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareEpollCtlInternal(epfd, fd, op, ev, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add an epoll_ctl to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="epfd">epoll instance file descriptor</param>
/// <param name="fd">File descriptor</param>
/// <param name="op">Operation to be performed for the file descriptor</param>
/// <param name="ev">Settings</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareEpollCtl(int epfd, int fd, int op, epoll_event* ev, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareEpollCtlInternal(epfd, fd, op, ev, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareEpollCtlInternal(int epfd, int fd, int op, epoll_event* ev, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_EPOLL_CTL;
sqe->flags = (byte) options;
sqe->fd = epfd;
sqe->off = (ulong) fd;
sqe->addr = (ulong) ev;
sqe->len = (uint) op;
sqe->user_data = userData;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a splice to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fdIn">Source file descriptor</param>
/// <param name="offIn">Offset into the source</param>
/// <param name="fdOut">Target file descriptor</param>
/// <param name="offOut">Offset into the target</param>
/// <param name="nbytes">Number of bytes to move</param>
/// <param name="spliceFlags">Flags for the splice</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareSplice(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareSpliceInternal(fdIn, offIn, fdOut, offOut, nbytes, spliceFlags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a splice to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fdIn">Source file descriptor</param>
/// <param name="offIn">Offset into the source</param>
/// <param name="fdOut">Target file descriptor</param>
/// <param name="offOut">Offset into the target</param>
/// <param name="nbytes">Number of bytes to move</param>
/// <param name="spliceFlags">Flags for the splice</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareSplice(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareSpliceInternal(fdIn, offIn, fdOut, offOut, nbytes, spliceFlags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareSpliceInternal(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_SPLICE;
sqe->flags = (byte) options;
sqe->fd = fdOut;
sqe->off = offOut;
sqe->splice_off_in = offIn;
sqe->len = nbytes;
sqe->splice_flags = spliceFlags;
sqe->user_data = userData;
sqe->splice_fd_in = fdIn;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a splice using a fixed file/buffer as source to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fdIn">Fixed source file/buffer</param>
/// <param name="offIn">Offset into the source</param>
/// <param name="fdOut">Target file descriptor</param>
/// <param name="offOut">Offset into the target</param>
/// <param name="nbytes">Number of bytes to move</param>
/// <param name="spliceFlags">Flags for the splice</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareSpliceFixed(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareSpliceFixedInternal(fdIn, offIn, fdOut, offOut, nbytes, spliceFlags, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a splice using a fixed file/buffer as source to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="fdIn">Fixed source file/buffer</param>
/// <param name="offIn">Offset into the source</param>
/// <param name="fdOut">Target file descriptor</param>
/// <param name="offOut">Offset into the target</param>
/// <param name="nbytes">Number of bytes to move</param>
/// <param name="spliceFlags">Flags for the splice</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareSpliceFixed(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareSpliceFixedInternal(fdIn, offIn, fdOut, offOut, nbytes, spliceFlags, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareSpliceFixedInternal(int fdIn, ulong offIn, int fdOut, ulong offOut, uint nbytes, uint spliceFlags, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_SPLICE;
sqe->flags = (byte) options;
sqe->fd = fdOut;
sqe->off = offOut;
sqe->splice_off_in = offIn;
sqe->len = nbytes;
sqe->splice_flags = spliceFlags | SPLICE_F_FD_IN_FIXED;
sqe->user_data = userData;
sqe->splice_fd_in = fdIn;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a request to add provided buffers for buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="addr">Address of the first buffer to add</param>
/// <param name="len">Length of each buffers to be added</param>
/// <param name="nr">Number of buffers to add</param>
/// <param name="bgid">Group ID of the buffers</param>
/// <param name="bid">Buffer ID of the first buffer</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareProvideBuffers(void* addr, int len, int nr, int bgid, int bid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareProvideBuffersInternal(addr, len, nr, bgid, bid, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a request to add provided buffers for buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="addr">Address of the first buffer to add</param>
/// <param name="len">Length of each buffers to be added</param>
/// <param name="nr">Number of buffers to add</param>
/// <param name="bgid">Group ID of the buffers</param>
/// <param name="bid">Buffer ID of the first buffer</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareProvideBuffers(void* addr, int len, int nr, int bgid, int bid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareProvideBuffersInternal(addr, len, nr, bgid, bid, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareProvideBuffersInternal(void* addr, int len, int nr, int bgid, int bid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_PROVIDE_BUFFERS;
sqe->flags = (byte) options;
sqe->fd = nr;
sqe->off = (uint) bid;
sqe->addr = (ulong) addr;
sqe->len = (uint) len;
sqe->user_data = userData;
sqe->buf_group = (ushort) bgid;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
/// <summary>
/// Adds a request to rmeove provided buffers for buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="nr">Number of buffers to remove</param>
/// <param name="bgid">Group ID of the buffers to remove</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <exception cref="SubmissionQueueFullException">If no more free space in the Submission Queue is available</exception>
/// <exception cref="TooManyOperationsInFlightException">If <see cref="Ring.SupportsNoDrop"/> is false and too many operations are currently in flight</exception>
public void PrepareRemoveBuffers(int nr, int bgid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var result = PrepareRemoveBuffersInternal(nr, bgid, userData, options, personality);
if (result != SubmissionAcquireResult.SubmissionAcquired)
{
ThrowSubmissionAcquisitionException(result);
}
}
/// <summary>
/// Attempts to add a request to rmeove provided buffers for buffer selection to the Submission Queue without it being submitted.
/// The actual submission can be deferred to avoid unnecessary memory barriers.
/// </summary>
/// <param name="nr">Number of buffers to remove</param>
/// <param name="bgid">Group ID of the buffers to remove</param>
/// <param name="userData">User data that will be returned with the respective <see cref="Completion"/></param>
/// <param name="options">Options for the handling of the prepared Submission Queue Entry</param>
/// <param name="personality">The personality to impersonate for this submission</param>
/// <returns><code>false</code> if the submission queue is full. <code>true</code> otherwise.</returns>
public bool TryPrepareRemoveBuffers(int nr, int bgid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
return PrepareRemoveBuffersInternal(nr, bgid, userData, options, personality) == SubmissionAcquireResult.SubmissionAcquired;
}
private SubmissionAcquireResult PrepareRemoveBuffersInternal(int nr, int bgid, ulong userData = 0, SubmissionOption options = SubmissionOption.None, ushort personality = 0)
{
var acquireResult = NextSubmissionQueueEntry(out var sqe);
if (acquireResult != SubmissionAcquireResult.SubmissionAcquired) return acquireResult;
unchecked
{
sqe->opcode = IORING_OP_REMOVE_BUFFERS;
sqe->flags = (byte) options;
sqe->fd = nr;
sqe->user_data = userData;
sqe->buf_group = (ushort) bgid;
sqe->personality = personality;
}
return SubmissionAcquireResult.SubmissionAcquired;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Infnet.EngSoft.SistemaBancario.Modelo
{
public class ServicosDeTransacoesBancarias
{
// método para realizar Deposito Bancario
public decimal DepositoBancario(ContaCorrente conta, Decimal Valor)
{
return Valor;
}
// méodo para realizar Saque
public decimal SaqueBancario(ContaCorrente conta, Decimal Valor)
{
return Valor;
}
// método para realizar Transferência Bancária
public decimal TransferenciaBancaria(ContaCorrente conta, Decimal Valor)
{
return Valor;
}
// método para Emissão de Comprovante
public bool EmissaoDeComprovante(ContaCorrente conta, DateTime DataAtual)
{
return true;
}
// método para Encerrar Conta Corrente
public bool EncerrarContaCorrente(ContaCorrente conta)
{
return true;
}
}
}
|
using System;
using System.Collections.Generic;
namespace InfnetBanking
{
public abstract class Pessoa
{
private string cadastroPessoa;
public string CadastroPessoa
{
get => cadastroPessoa;
set
{
if (ValidarCadastroPessoa(value))
{
cadastroPessoa = value;
}
}
}
// Ref. programadores Python: listas de Python
// Ref. programadores Java: java.util.ArrayList<>
public List<Endereco> Enderecos { get; set; }
public DateTime DataNascimento { get; set; }
public abstract bool ValidarCadastroPessoa(string value);
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using Xunit;
using Xunit.Abstractions;
using static DocumentFormat.OpenXml.Framework.Tests.TestUtility;
namespace DocumentFormat.OpenXml.Framework.Tests
{
public class ElementLookupTests
{
private const byte Namespace1 = 1;
private const byte Namespace2 = 2;
private const byte Namespace3 = 3;
private const string Name1 = "Name1";
private const string Name2 = "Name1";
private const string Name3 = "Name1";
private readonly ITestOutputHelper _output;
public ElementLookupTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void NoProperties()
{
var lookup = CreateLookup<NoPropertiesTest>();
Assert.Equal(0, lookup.Count);
Assert.Null(lookup.Create(Namespace1, Name1));
Assert.Null(lookup.Create(Namespace2, Name2));
Assert.Null(lookup.Create(Namespace3, Name3));
}
[Fact]
public void SingleProperty()
{
var lookup = CreateLookup<OnePropertyTest>();
Assert.Equal(1, lookup.Count);
Assert.IsType<Element1>(lookup.Create(Namespace1, Name1));
Assert.Null(lookup.Create(Namespace2, Name2));
Assert.Null(lookup.Create(Namespace3, Name3));
}
[Fact]
public void MultipleProperties()
{
var lookup = CreateLookup<MultiplePropertyTest>();
Assert.Equal(3, lookup.Count);
Assert.IsType<Element1>(lookup.Create(Namespace1, Name1));
Assert.IsType<Element2>(lookup.Create(Namespace2, Name2));
Assert.IsType<Element3>(lookup.Create(Namespace3, Name3));
}
[Fact]
public void OpenXmlElementTypeGetsAll()
{
var lookup = CreateLookup(typeof(OpenXmlPartRootElement));
Assert.Equal(85, lookup.Count);
}
[Fact]
public void ElementDoesNotContainSchemaInfo()
{
Assert.Throws<InvalidOperationException>(() => CreateLookup<NoDataPropertyTest>());
}
[Fact]
public void ElementMustDeriveFromOpenXmlElement()
{
Assert.Throws<InvalidOperationException>(() => CreateLookup<NotElement>());
}
[Fact]
public void DerivedElements()
{
var lookup = CreateLookup<OnDerived>();
Assert.Equal(3, lookup.Count);
Assert.IsType<Element1>(lookup.Create(Namespace1, Name1));
Assert.IsType<Element2>(lookup.Create(Namespace2, Name2));
Assert.IsType<Element3>(lookup.Create(Namespace3, Name3));
}
[Fact]
public void BuiltInOpenXmlElements()
{
var elements = typeof(OpenXmlElement).GetTypeInfo().Assembly.GetTypes()
.Where(t => !t.GetTypeInfo().IsAbstract && typeof(OpenXmlElement).GetTypeInfo().IsAssignableFrom(t))
.Concat(new[] { typeof(OpenXmlPartRootElement) })
.OrderBy(type => type.FullName, StringComparer.Ordinal)
.Select(type => new LookupData(type));
#if DEBUG
var tmp = Path.GetTempFileName();
_output.WriteLine($"Wrote to temp path {tmp}");
File.WriteAllText(tmp, JsonConvert.SerializeObject(elements, Newtonsoft.Json.Formatting.Indented, new StringEnumConverter()));
#endif
var expected = Deserialize<LookupData[]>("ElementChildren.json");
var actual = GetBuiltIn().ToArray();
Assert.Equal(expected, actual);
}
[Fact]
public void DumpBuiltInOpenXmlElements()
{
// This should align with the text in ElementChildren.json
var expected = Serialize(GetBuiltIn());
Assert.NotNull(expected);
}
private static IEnumerable<LookupData> GetBuiltIn()
{
return typeof(OpenXmlElement).GetTypeInfo().Assembly.GetTypes()
.Where(t => !t.GetTypeInfo().IsAbstract && typeof(OpenXmlElement).GetTypeInfo().IsAssignableFrom(t))
.Concat(new[] { typeof(OpenXmlPartRootElement) })
.OrderBy(type => type.FullName, StringComparer.Ordinal)
.Select(type => new LookupData(type));
}
private static ElementLookup CreateLookup<T>() => CreateLookup(typeof(T));
private static ElementLookup CreateLookup(Type t)
{
return ElementLookup.CreateLookup(t, type => () => (OpenXmlElement)Activator.CreateInstance(type));
}
private class LookupData : IEquatable<LookupData>
{
public LookupData()
{
}
public LookupData(Type type)
{
Element = type.FullName;
Children = CreateLookup(type).Elements.Select(t => new ChildData
{
Name = t.Name,
Namespace = t.Namespace,
});
}
public string Element { get; set; }
public IEnumerable<ChildData> Children { get; set; }
public override bool Equals(object obj) => Equals(obj as LookupData);
public bool Equals(LookupData other)
{
if (other == null)
{
return false;
}
if (!string.Equals(Element, other.Element, StringComparison.Ordinal) || !Children.SequenceEqual(other.Children))
{
System.Diagnostics.Debugger.Break();
}
return string.Equals(Element, other.Element, StringComparison.Ordinal)
&& Children.SequenceEqual(other.Children);
}
public override int GetHashCode() => throw new NotImplementedException();
public class ChildData : IEquatable<ChildData>
{
public string Name { get; set; }
public string Namespace { get; set; }
public bool Equals(ChildData other)
{
return string.Equals(Name, other.Name, StringComparison.Ordinal)
&& string.Equals(Namespace, other.Namespace, StringComparison.Ordinal);
}
public override int GetHashCode() => throw new NotImplementedException();
public override bool Equals(object obj) => Equals(obj as ChildData);
}
}
#pragma warning disable CA1812
private class NoPropertiesTest
{
}
[ChildElementInfo(typeof(Element1))]
private class OnePropertyTest
{
public Element1 Element { get; set; }
}
[ChildElementInfo(typeof(ElementNoData))]
private class NoDataPropertyTest
{
public ElementNoData Element { get; set; }
}
[ChildElementInfo(typeof(Element1))]
[ChildElementInfo(typeof(Element2))]
[ChildElementInfo(typeof(Element3))]
private class MultiplePropertyTest
{
public Element1 Element1 { get; set; }
public Element2 Element2 { get; set; }
public Element3 Element3 { get; set; }
}
[ChildElementInfo(typeof(NotElement))]
[SchemaAttr(Namespace1, Name1)]
private class NotElement
{
public NotElement Element { get; set; }
}
private class OnDerived : MultiplePropertyTest
{
}
[SchemaAttr(Namespace1, Name1)]
private class Element1 : DerivedOpenXmlElement
{
}
[SchemaAttr(Namespace2, Name2)]
private class Element2 : DerivedOpenXmlElement
{
}
[SchemaAttr(Namespace3, Name3)]
private class Element3 : DerivedOpenXmlElement
{
}
private class ElementNoData : DerivedOpenXmlElement
{
}
private class DerivedOpenXmlElement : OpenXmlElement
{
public override bool HasChildren => throw new NotImplementedException();
public override void RemoveAllChildren() => throw new NotImplementedException();
internal override void WriteContentTo(XmlWriter w) => throw new NotImplementedException();
private protected override void Populate(XmlReader xmlReader, OpenXmlLoadMode loadMode) => throw new NotImplementedException();
}
#pragma warning restore CA1812
}
}
|
using BPiaoBao.Client.UIExt.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace BPiaoBao.Client.UIExt.Converter
{
/// <summary>
/// 描述转换器
/// </summary>
public class DescriptionConverter : IValueConverter
{
/// <summary>
/// 转换值。
/// </summary>
/// <param name="value">绑定源生成的值。</param>
/// <param name="targetType">绑定目标属性的类型。</param>
/// <param name="parameter">要使用的转换器参数。</param>
/// <param name="culture">要用在转换器中的区域性。</param>
/// <returns>
/// 转换后的值。如果该方法返回 null,则使用有效的 null 值。
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is Enum))
{
return value;
}
var result = EnumHelper.GetDescription((value as Enum));
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// 时间日期为空
/// </summary>
public class DateTimeValueConverter : IValueConverter
{
/// <summary>
/// 转换值。
/// </summary>
/// <param name="value">绑定源生成的值。</param>
/// <param name="targetType">绑定目标属性的类型。</param>
/// <param name="parameter">要使用的转换器参数。</param>
/// <param name="culture">要用在转换器中的区域性。</param>
/// <returns>
/// 转换后的值。如果该方法返回 null,则使用有效的 null 值。
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is DateTime)
{
if (((DateTime)value).Year == 1900)
return "";
}
return ((DateTime)value).ToString("yyyy-MM-dd hh:mm");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using SSW.DataOnion.Interfaces;
namespace SSW.DataOnion.Core
{
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContextScope dbContextScope;
private readonly IRepositoryLocator repositoryLocator;
public UnitOfWork(IDbContextScopeFactory dbContextScopeFactory, IRepositoryLocator repositoryLocator)
{
this.dbContextScope = dbContextScopeFactory.Create();
this.repositoryLocator = repositoryLocator;
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : class
{
return this.repositoryLocator.GetRepository<TEntity>();
}
public void SaveChanges()
{
this.RunBeforeSave(this.dbContextScope);
this.dbContextScope.SaveChanges();
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
this.RunBeforeSave(this.dbContextScope);
await this.dbContextScope.SaveChangesAsync(cancellationToken);
}
protected virtual void RunBeforeSave(IDbContextScope currentDbContextScope)
{
}
private bool disposed;
protected virtual void Dispose(bool disposing)
{
if (this.disposed)
{
return;
}
if (disposing)
{
this.dbContextScope.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
this.Dispose(true);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FormularioCadastroCliente.Models
{
public class Cliente
{
[Key]
[Display(Name = "Id")]
public int Id { get; set; }
[Display(Name = "Razão Social")]
[Column(TypeName = "varchar(100)")]
public string RazaoSocial { get; set; }
[Display(Name = "Nome Fantasia")]
[Column(TypeName = "varchar(100)")]
public string NomeFantasia { get; set; }
[Display(Name = "CNPJ")]
[Column(TypeName = "varchar(18)")]
public string Cnpj { get; set; }
[Display(Name = "Data de Abertura da Empresa")]
[Column(TypeName = "varchar(12)")]
public string DataAberturaEmpresa { get; set; }
[Column(TypeName = "varchar(100)")]
[Display(Name = "Endereço")]
public string Endereco { get; set; }
[Column(TypeName = "varchar(100)")]
[Display(Name = "Bairro")]
public string Bairro { get; set; }
[Column(TypeName = "varchar(100)")]
[Display(Name = "Cidade")]
public string Cidade { get; set; }
[Display(Name = "UF")]
[Column(TypeName = "varchar(2)")]
public string Uf { get; set; }
//adicionais
[Display(Name = "Visivel")]
[Column(TypeName = "tinyint")]
public bool Visivel { get; set; }
[Display(Name = "DataCriacao")]
[Column(TypeName = "varchar(12)")]
public string DataCriacao { get; set; }
[Display(Name = "DataAlteracao")]
[Column(TypeName = "varchar(12)")]
public string DataAlteracao { get; set; }
}
}
|
using System;
using System.Buffers;
using System.Diagnostics;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
static LargeArrayBuilder<TSource> ToArrayBuilder<TSource, TPredicate>(ReadOnlySpan<TSource> source, TPredicate predicate, ArrayPool<TSource> arrayPool)
where TPredicate: struct, IFunction<TSource, bool>
{
var builder = new LargeArrayBuilder<TSource>(arrayPool);
foreach (var item in source)
{
if (predicate.Invoke(item))
builder.Add(item);
}
return builder;
}
static LargeArrayBuilder<TSource> ToArrayBuilderRef<TSource, TPredicate>(ReadOnlySpan<TSource> source, TPredicate predicate, ArrayPool<TSource> arrayPool)
where TPredicate : struct, IFunctionIn<TSource, bool>
{
var builder = new LargeArrayBuilder<TSource>(arrayPool);
foreach (ref readonly var item in source)
{
if (predicate.Invoke(in item))
builder.AddRef(in item);
}
return builder;
}
static LargeArrayBuilder<TSource> ToArrayBuilderAt<TSource, TPredicate>(ReadOnlySpan<TSource> source, TPredicate predicate, ArrayPool<TSource> arrayPool)
where TPredicate: struct, IFunction<TSource, int, bool>
{
var builder = new LargeArrayBuilder<TSource>(arrayPool);
for (var index = 0; index < source.Length; index++)
{
var item = source[index];
if (predicate.Invoke(item, index))
builder.Add(item);
}
return builder;
}
static LargeArrayBuilder<TSource> ToArrayBuilderAtRef<TSource, TPredicate>(ReadOnlySpan<TSource> source, TPredicate predicate, ArrayPool<TSource> arrayPool)
where TPredicate : struct, IFunctionIn<TSource, int, bool>
{
var builder = new LargeArrayBuilder<TSource>(arrayPool);
for (var index = 0; index < source.Length; index++)
{
ref readonly var item = ref source[index];
if (predicate.Invoke(in item, index))
builder.AddRef(in item);
}
return builder;
}
static LargeArrayBuilder<TResult> ToArrayBuilder<TSource, TResult, TPredicate, TSelector>(ReadOnlySpan<TSource> source, TPredicate predicate, TSelector selector, ArrayPool<TResult> arrayPool)
where TPredicate: struct, IFunction<TSource, bool>
where TSelector: struct, IFunction<TSource, TResult>
{
var builder = new LargeArrayBuilder<TResult>(arrayPool);
foreach (var item in source)
{
if (predicate.Invoke(item))
builder.Add(selector.Invoke(item));
}
return builder;
}
static LargeArrayBuilder<TResult> ToArrayBuilderRef<TSource, TResult, TPredicate, TSelector>(ReadOnlySpan<TSource> source, TPredicate predicate, TSelector selector, ArrayPool<TResult> arrayPool)
where TPredicate : struct, IFunctionIn<TSource, bool>
where TSelector : struct, IFunctionIn<TSource, TResult>
{
var builder = new LargeArrayBuilder<TResult>(arrayPool);
foreach (ref readonly var item in source)
{
if (predicate.Invoke(in item))
builder.Add(selector.Invoke(in item));
}
return builder;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Resources;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;
public class CreateCapsuleSystem : JobComponentSystem
{
protected override void OnCreate()
{
base.OnCreate();
// var instance = EntityManager.CreateEntity(
// ComponentType.ReadOnly<LocalToWorld>(),
// // ComponentType.ReadWrite<Translation>(),
// // ComponentType.ReadWrite<Rotation>(),
// ComponentType.ReadOnly<RenderMesh>());
//
// EntityManager.SetComponentData(instance, new LocalToWorld
// {
// Value = new float4x4(rotation: quaternion.identity, translation: new float3(0,0,0))
// });
// // EntityManager.SetComponentData(instance, new Translation {Value = new float3(0, 0, 0)});
// // EntityManager.SetComponentData(instance, new Rotation{Value = new quaternion(0,0,0,0)});
//
// var rHolder = Resources.Load<GameObject>("ResourceHolder").GetComponent<ResourceHolder>();
//
// EntityManager.SetSharedComponentData(instance, new RenderMesh
// {
// mesh = rHolder.theMesh,
// material = rHolder.theMaterial
// });
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
return inputDeps;
}
}
|
using UnityEngine;
/// <summary>
/// A meter with a minimum and maximum value, a current value,
/// and a way to count up or down (by changing the current value) between the minimum and maximum.
/// </summary>
[System.Serializable]
public class Meter
{
/// <summary>
/// The current value. It can never be lower than the minimum value, nor higher than the maximum.
/// </summary>
public float currentValue
{
get
{
if (_currentValue < minValue)
{
_currentValue = minValue;
}
if (_currentValue > maxValue)
{
_currentValue = maxValue;
}
return _currentValue;
}
private set
{
_currentValue = value;
}
}
/// <summary>
/// The minimum value. 'currentValue' cannot be lower than this.
/// </summary>
public float minValue { get { return _minValue; } private set { _minValue = value; } }
/// <summary>
/// The maximum value. 'currentValue' cannot be lower than this.
/// </summary>
public float maxValue { get { return _maxValue; } private set { _maxValue = value; } }
[SerializeField]
private float _currentValue;
[SerializeField]
private float _minValue;
[SerializeField]
private float _maxValue;
/// <summary>
/// Creates a new meter, with a minimum and maximum value,
/// and an initial value that must fall in between these two values.
/// If it doesn't, an error will occur.
/// </summary>
/// <param name="initialValue">The starting value of the meter.</param>
/// <param name="_minValue">The minimum value of the meter.</param>
/// <param name="_maxValue">The maximum value of the meter.</param>
public Meter(float initialValue, float _minValue, float _maxValue)
{
if (initialValue < _minValue || initialValue > _maxValue)
{
Debug.LogError("Please enter an initial value within the ranges you have provided.");
return;
}
minValue = _minValue;
maxValue = _maxValue;
currentValue = initialValue;
}
/// <summary>
/// Counts in either direction along the meter, by 'interval', once per frame.
/// Use a negative number to count backwards, and vice versa.
/// </summary>
/// <param name="interval">
/// The number to count up or down by, per frame.
/// Multiply by 'Time.deltaTime' to count by the interval per second instead.
/// </param>
public void Count(float interval)
{
if (currentValue > maxValue)
{
ResetToMax();
}
if (currentValue < minValue)
{
ResetToMin();
}
currentValue += interval;
}
/// <summary>
/// Resets the timer to the minimum value.
/// </summary>
public void ResetToMin()
{
currentValue = minValue;
}
/// <summary>
/// Resets the timer to the maximum value.
/// </summary>
public void ResetToMax()
{
currentValue = maxValue;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BackToMenu : MonoBehaviour
{
public void Menu()
{
SceneManager.LoadScene("MenuScene");
}
public void Play()
{
SceneManager.LoadScene("GameScene");
}
}
|
using System;
namespace Juego
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
BaseJuego bj = new BaseJuego(new ParteVisual(),10);
bj.Start();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XorEncoder
{
public partial class MainForm : Form
{
/// <summary>
/// Отмена действия.
/// </summary>
private bool isCancel = false;
/// <summary>
/// Действие отменяется.
/// </summary>
private bool isDecoding = false;
public MainForm()
{
InitializeComponent();
this.Load += MainForm_Load;
}
private void MainForm_Load(object sender, EventArgs e)
{
this.buttonStop.Enabled = false;
this.textBoxKey.KeyPress += TextBoxKey_KeyPress;
}
/// <summary>
/// Обработчик нажатия на textBox ключа.
/// Доступен ввод цифр и Backspace.
/// </summary>
private void TextBoxKey_KeyPress(object sender, KeyPressEventArgs e)
{
char number = e.KeyChar;
Console.WriteLine(number);
Console.WriteLine((int)number);
if (!Char.IsDigit(number)
&& (int)number != 8)
{
e.Handled = true;
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
if (this.IsEncodingAvailable())
{
this.ToggleButtons(false);
ThreadPool.QueueUserWorkItem(this.Encrypt);
}
}
/// <summary>
/// Доступно кодирование.
/// </summary>
/// <returns>true если кодирование файла доступно.</returns>
private bool IsEncodingAvailable()
{
if (this.IsFileExists()
&& this.IsKeyEntered())
{
return true;
}
return false;
}
/// <summary>
/// Ключ введен.
/// </summary>
/// <returns>true если ключ введен, и содержит минимум 6 символов.</returns>
private bool IsKeyEntered()
{
if (this.textBoxKey.Text.Length > 5)
{
return true;
}
MessageBox.Show("Длина ключа должна быть минимум 6 символов",
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk);
return false;
}
/// <summary>
/// Файл существует.
/// </summary>
/// <returns>true если файл существует.</returns>
private bool IsFileExists()
{
if (File.Exists(this.textBoxFileAddress.Text))
{
return true;
}
MessageBox.Show("Файл не найден", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return false;
}
/// <summary>
/// Кодирование файла.
/// </summary>
private void Encrypt(object state)
{
string filePath = this.textBoxFileAddress.Text;
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
this.isDecoding = false;
fileStream.Position = 0;
this.progressBar.Maximum = (int)fileStream.Length;
this.progressBar.Value = 0;
// Кол-во байт для блока.
int nBytesInBlock = Convert.ToInt32(this.numericUpDownQuantityByte.Value);
byte[] dataRead = new byte[nBytesInBlock];
int key = Convert.ToInt32(this.textBoxKey.Text);
byte[] dataResult = new byte[nBytesInBlock];
long endPosition = fileStream.Length; // конечная позиция записи.
int nBytesRead = 0; // кол-во считанных байт.
// Кодируем файл.
while (fileStream.Position != endPosition)
{
// Считываем блок.
nBytesRead = fileStream.Read(dataRead, 0, dataRead.Length);
// Кодируем блок.
for (int i = 0; i < nBytesRead; i++)
{
dataResult[i] = (byte)(dataRead[i] ^ key);
this.ChangeValueProgressbar();
}
// Записываем блок.
fileStream.Position -= nBytesRead;
fileStream.Write(dataResult, 0, nBytesRead);
// Отмена кодирования (декодирование).
if (this.isCancel)
{
endPosition = fileStream.Position;
fileStream.Position = 0;
this.isCancel = false;
this.isDecoding = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
fileStream?.Close();
}
this.ToggleButtons(true);
}
/// <summary>
/// Изменение значение progressBar.
/// </summary>
private void ChangeValueProgressbar()
{
if (this.isDecoding)
{
this.progressBar.Value--;
}
else
{
this.progressBar.Value++;
}
}
/// <summary>
/// Переключение кнопок Старт и Отмена.
/// </summary>
/// <param name="isEnableStart">Включить кнопку Старт.</param>
private void ToggleButtons(bool isEnableStart)
{
if (isEnableStart)
{
this.buttonStart.Enabled = true;
this.buttonStop.Enabled = false;
}
else
{
this.buttonStop.Enabled = true;
this.buttonStart.Enabled = false;
this.buttonStop.Focus();
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
this.ToggleButtons(true);
this.isCancel = true;
}
private void buttonOverview_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Выбор файла";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
this.textBoxFileAddress.Text = openFileDialog.FileName;
}
}
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using Shunxi.Business.Enums;
using Shunxi.Business.Logic.Cultivations;
using Shunxi.Business.Models;
using Shunxi.Business.Models.cache;
using Shunxi.Business.Models.devices;
using Shunxi.Business.Protocols.Helper;
using Shunxi.Business.Tables;
using Shunxi.Infrastructure.Common.Extension;
using Shunxi.Business.Logic.Devices;
using Shunxi.Common.Log;
namespace Shunxi.Business.Logic.Controllers
{
public class PumpController : ControllerBase
{
public override bool IsEnable => true;
//输入/输出的体积
public double Volume;
//输入/输出的速度
public double Flowrate;
//每次收到暂停反馈后需要设置上一次未完成的量 方便下次开始的时候设置参数
public double PreUnfinishedVolume;
public BaseCultivation PumpCultivation { get; set; }
public PumpController(ControlCenter center, PumpDevice device, Pump pump) : base(center,device)
{
if (pump == null)
{
//CustomErrorEvent(new CustomException($"pump{PumpCultivation.PumpId} 的时间表排期为空", this.GetType().FullName, ExceptionPriority.Unrecoverable));
return;
}
PumpCultivation = CultivationFactory.GetCultivation(pump);
PumpCultivation.CalcSchedules();
LogFactory.Create().Info($"pump{PumpCultivation.Device.DeviceId} {PumpCultivation.Device.ProcessMode} startTime is {PumpCultivation.Device.StartTime:yyyy-MM-dd HH:mm:ss}");
}
private double CalcPreUnfinishedVolume()
{
LogFactory.Create().Info($"{Volume},{Flowrate}<=============>{StartTime:yyyy-MM-dd HH:mm:ss},{StopTime:yyyy-MM-dd HH:mm:ss}");
if (StartTime == DateTime.MinValue || StopTime == DateTime.MinValue || StartTime >= StopTime) return 0;
var finished = (StopTime - StartTime).TotalMinutes * Flowrate;
var ret = Volume - finished;
//目前版本 流量参数不能为小数
return ret >= 1 ? ret : 0;
}
private double CalcVolume(string desc)
{
var startTime = StartTime;
var endTime = StopTime;
if (desc == IdleDesc.Completed.ToString())
{
return Volume;
}
if (desc == IdleDesc.Paused.ToString() && startTime < endTime)
{
return Flowrate * (endTime - startTime).TotalMinutes;
}
return 0;
}
private Tuple<double, double, double> PreStart()
{
var interval = 0;
var flowrate = 0D;
var volume = 0D;
//TODO 如果上次未完成 则立即开始运行
if (PreUnfinishedVolume > 0)
{
flowrate = Flowrate;
volume = PreUnfinishedVolume;
LogFactory.Create().Info($"pump{PumpCultivation.Device.DeviceId} pre unfinished {PreUnfinishedVolume:##.###}, starttime{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
//清理数据 防止影响下一个流程
PreUnfinishedVolume = 0;
}
else
{
var currentDateTime = DateTime.Now;
var next = PumpCultivation.GetNextRunParams(AlreadyRunTimes == 0);
//暂停的时候泵还在运行, 但重新开始后由于需要加入的量很少(<1)所以认为上次已经加完,此时需要重新判断泵的流程是否全部完成
if (null == next)
{
LogFactory.Create().Info($"DEVICE{Device.DeviceId} cultivate process finished");
if (CurrentStatus != DeviceStatusEnum.AllFinished)
{
var comEventArgs = new CommunicationEventArgs
{
DeviceType = TargetDeviceTypeEnum.Pump,
DeviceId = PumpCultivation.Device.DeviceId,
DeviceStatus = DeviceStatusEnum.Idle,
Description = IdleDesc.Completed.ToString()
};
OnCommunicationChange(comEventArgs);
}
//整个流程已完成
return null;
}
var nextTime = next.Item1;
var timeSpan = nextTime > currentDateTime ? (DateTime)nextTime - currentDateTime : TimeSpan.FromSeconds(0);
interval = (int)timeSpan.TotalMilliseconds;
flowrate = next.Item2;
volume = next.Item3;
LogFactory.Create().Info($"pump{Device.DeviceId} prev is finished, next starttime{nextTime:yyyy-MM-dd HH:mm:ss}, interval{timeSpan.TotalMilliseconds}");
}
if (interval < 0) interval = 0;
return new Tuple<double, double, double>(interval, flowrate, volume);
}
public override async Task<DeviceIOResult> Start()
{
var pre = PreStart();
if (pre == null)
{
LogFactory.Create().Info($"DEVICE{Device.DeviceId} completed finished");
return new DeviceIOResult(false, "DISABLED");
}
var interval = pre.Item1;
var flowrate = pre.Item2;
var volume = pre.Item3;
try
{
await Task.Delay((int)interval, CancellationTokenSource.Token);
return await ExecStart(flowrate, volume);
}
catch (Exception)
{
LogFactory.Create().Info($"DEVICE{Device.DeviceId} start is cancel");
}
return new DeviceIOResult(false,"CANCEL");
}
private async Task<DeviceIOResult> ExecStart(double flowrate, double volume)
{
//出液泵开启前摇床要停止,出液泵停止后泵摇床开始
if (PumpCultivation.Device.InOrOut == PumpInOrOut.Out && CurrentContext.SysCache.System.Rocker.IsEnabled)
{
await Center.StopRockerAndThermometer();
}
Flowrate = flowrate;
Volume = volume;
((PumpDevice)Device).SetParams(Flowrate, Volume, PumpCultivation.Device.Direction);
StartTime = DateTime.Now;
SetStatus(DeviceStatusEnum.PreStart);
Device.TryStart();
StartEvent = new TaskCompletionSource<DeviceIOResult>();
return await StartEvent.Task;
// var p = await StartEvent.WaitAsync(CancellationTokenSource.Token);
// StartEvent.Reset();
// return p;
}
public override Task<DeviceIOResult> Close()
{
throw new NotImplementedException();
}
public override void Next(SerialPortEventArgs args)
{
var comEventArgs = new CommunicationEventArgs
{
Command = args.Command,
DirectiveId = args.Result.Data.DirectiveId,
DeviceType = args.Result.Data.DeviceType,
DeviceId = args.Result.Data.DeviceId,
Description = args.Message,
Data = args.Result.Data
};
this.Status.Handle(args.Result.SourceDirectiveType, args.Result.Data, comEventArgs);
OnCommunication(comEventArgs);
}
public void AdjustTimeForPause()
{
if(CurrentStatus == DeviceStatusEnum.AllFinished) return;
PumpCultivation.AdjustTimeForPause(StopTime == DateTime.MinValue ? Center.StopTime : StopTime);
}
public void AdjustStartTimeWhenFirstRun(TimeSpan span)
{
LogFactory.Create().Info($"{Device.DeviceId} need adjust time");
PumpCultivation.AdjustStartTimeWhenFirstRun(span);
}
public override void ProcessRunningDirectiveResult(DirectiveData data, CommunicationEventArgs comEventArgs)
{
var ret = data as PumpDirectiveData;
if (CurrentStatus == DeviceStatusEnum.Startting)
{
//从tryStart变为running(真的开始)
if (ret?.FlowRate > 0)
{
this.SetStatus(DeviceStatusEnum.Running);
comEventArgs.DeviceStatus = DeviceStatusEnum.Running;
StartEvent.TrySetResult(new DeviceIOResult(true));
OnCommunicationChange(comEventArgs);
}
else//泵收到开始命令 但还未运行
{
comEventArgs.DeviceStatus = CurrentStatus;
}
StartRunningLoop();
}
else if (CurrentStatus == DeviceStatusEnum.Running)
{
//泵输入/输出指定流量后停止
if (ret != null && ret.FlowRate <= 0)
{
this.SetStatus(DeviceStatusEnum.Idle);
comEventArgs.DeviceStatus = DeviceStatusEnum.Idle;
comEventArgs.Description = IdleDesc.Completed.ToString();
OnCommunicationChange(comEventArgs);
}
else//泵正在运行
{
comEventArgs.DeviceStatus = DeviceStatusEnum.Running;
StartRunningLoop();
}
}
}
public override void ProcessTryPauseResult(DirectiveData data, CommunicationEventArgs comEventArgs)
{
this.SetStatus(DeviceStatusEnum.Pausing);
comEventArgs.DeviceStatus = DeviceStatusEnum.Pausing;
OnCommunicationChange(comEventArgs);
StartPauseLoop();
}
public override void ProcessPausingResult(DirectiveData data, CommunicationEventArgs comEventArgs)
{
var ret = data as PumpDirectiveData;
if (ret != null && ret.FlowRate <= 0)
{
comEventArgs.DeviceStatus = DeviceStatusEnum.Idle;
comEventArgs.Description = IdleDesc.Paused.ToString(); ;
this.SetStatus(DeviceStatusEnum.Idle);
StopEvent.TrySetResult(new DeviceIOResult(true));
StopTime = DateTime.Now;
PreUnfinishedVolume = CalcPreUnfinishedVolume();
LogFactory.Create().Info($"device{Device.DeviceId} PreUnfinishedVolume is {PreUnfinishedVolume}");
OnCommunicationChange(comEventArgs);
}
else
{
comEventArgs.DeviceStatus = DeviceStatusEnum.Pausing;
StartPauseLoop();
}
}
public override void OnCommunicationChange(CommunicationEventArgs e)
{
base.OnCommunicationChange(e);
//HandleSystemStatusChange(e);
HandleDeviceStatusChange(e);
if (e.DeviceStatus != DeviceStatusEnum.Startting && e.DeviceStatus != DeviceStatusEnum.Pausing)
{
var data = e.Data as PumpDirectiveData;
if (data != null)
Center.SyncPumpWithServer(data.DeviceId);
}
}
protected void HandleDeviceStatusChange(CommunicationEventArgs e)
{
var deviceId = e.DeviceId;
var type = e.DeviceStatus;
var feedback = e.Data;
var delta = CalcVolume(e.Description);
var ftime = PumpCultivation.Schedules.FirstOrDefault();
var ltime = PumpCultivation.Schedules.LastOrDefault();
var stime = StartTime;
var etime = Flowrate <=0 ? DateTime.MinValue : StartTime.AddMinutes((PreUnfinishedVolume > 0 ? PreUnfinishedVolume : Volume) / Flowrate);
var ntime = PumpCultivation.Schedules.FirstOrDefault(each => each > DateTime.Now);
switch (type)
{
case DeviceStatusEnum.Startting:
CurrentContext.SysCache.SystemRealTimeStatus.Update(deviceId, true, Volume, 0,
this.AlreadyRunTimes, PumpCultivation.Schedules.Count, ftime, ltime, stime, etime, ntime);
break;
case DeviceStatusEnum.Running:
var data = feedback as PumpDirectiveData;
if (data != null)
{
CurrentContext.SysCache.SystemRealTimeStatus.Update(deviceId, true, Volume, data.FlowRate, AlreadyRunTimes);
}
break;
//case DeviceStatusEnum.Pausing:
case DeviceStatusEnum.Idle:
if (CurrentContext.SysCache.SystemRealTimeStatus.In.DeviceId == deviceId)
{
CurrentContext.SysCache.SystemRealTimeStatus.CurrVolume += Convert.ToInt32(delta);
}
else
{
CurrentContext.SysCache.SystemRealTimeStatus.CurrVolume -= Convert.ToInt32(delta);
}
HandleSystemStatusChange(e);
CurrentContext.SysCache.SystemRealTimeStatus.Update(deviceId, false, Volume, 0, AlreadyRunTimes);
break;
default:
break;
}
//涉及到动画, starting Running都会启动动画 只需要触发一次
if (type == DeviceStatusEnum.Running || type == DeviceStatusEnum.Idle)
Center.OnDeviceStatusChange(new IoStatusChangeEventArgs()
{
DeviceId = e.DeviceId,
DeviceType = e.DeviceType,
IoStatus = e.DeviceStatus,
Delta = delta,
Feedback = e.Data
});
}
private void SaveRecord(bool isManual)
{
DeviceService.SavePumpRecord(new PumpRecord()
{
CellCultivationId = CultivationService.GetLastCultivationId(),
DeviceId = Device.DeviceId,
StartTime = StartTime,
EndTime = DateTime.Now,
FlowRate = Flowrate,
Volume = Volume,
IsManual = isManual
});
}
private void HandleSystemStatusChange(CommunicationEventArgs e)
{
var p = new RunStatusChangeEventArgs();
//系统运行状态只与泵关联
if (e.DeviceType != TargetDeviceTypeEnum.Pump || e.DeviceStatus != DeviceStatusEnum.Idle) return;
if (e.Description == IdleDesc.Paused.ToString())//设备暂停运行
{
SaveRecord(true);
if (CurrentContext.Status == SysStatusEnum.Pausing)
{
p.SysStatus = SysStatusEnum.Paused;
Center.OnSystemStatusChange(p);
}
else if (CurrentContext.Status == SysStatusEnum.Discarding)
{
p.SysStatus = SysStatusEnum.Discarded;
Center.OnSystemStatusChange(p);
}
}
else if (e.Description == IdleDesc.Completed.ToString())//设备完成本次操作
{
SaveRecord(false);
AlreadyRunTimes++;
var next = PumpCultivation.GetNextRunParams(AlreadyRunTimes == 0);
//该泵整个培养流程完成
if (next == null || PumpCultivation.Device.ProcessMode == ProcessModeEnum.SingleMode)
{
LogFactory.Create().Info($"{e.DeviceId} cultivation finished");
SetStatus(DeviceStatusEnum.AllFinished);
//如果所有泵都已经完成 则通知前端培养流程完成
if (Center.IsAllFinished())
{
LogFactory.Create().Info("all cultivation finished");
p.SysStatus = SysStatusEnum.Completed;
Center.OnSystemStatusChange(p);
}
}
//该泵完成本次进液或出液流程
else
{
LogFactory.Create().Info($"<->pump{e.DeviceId} {AlreadyRunTimes}times completed");
StartNextLoop(next).IgnorCompletion();
StartIdleLoop();
}
//培养流程结束后 然后要保证摇床和温度打开
if (PumpCultivation.Device.InOrOut == PumpInOrOut.Out)
{
Center.StartRockerWhenPumpOutStop().IgnorCompletion();
// Center.StartRockerAndThermometer().IgnorCompletion();
}
Center.StartThermometerWhenPumpStop(CurrentContext.SysCache.SystemRealTimeStatus.CurrVolume, PumpCultivation.Device.InOrOut).IgnorCompletion();
}
}
private async Task StartNextLoop(Tuple<DateTime, double, double> next)
{
if (next != null)
{
var interval = (int)((DateTime)next.Item1 - DateTime.Now).TotalMilliseconds;
LogFactory.Create().Info($"StartNextLoop pump{PumpCultivation.Device.DeviceId} starttime{next.Item1:yyyy-MM-dd HH:mm:ss}, interval{interval}");
if (interval < 0)
interval = 0;
try
{
await Task.Delay(interval, CancellationTokenSource.Token);
await ExecStart(next.Item2, next.Item3);
}
catch (Exception)
{
LogFactory.Create().Info($"DEVICE{Device.DeviceId} StartNextLoop is cancel");
}
}
}
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
using TQVaultAE.Domain.Search;
using TQVaultAE.GUI.Components;
namespace TQVaultAE.GUI.Models.SearchDialogAdvanced
{
public class BoxItem
{
ScalingCheckedListBox _CheckedList;
[JsonIgnore]
public ScalingCheckedListBox CheckedList
{
get => _CheckedList;
set
{
CheckedListName = value.Name;
_CheckedList = value;
}
}
ScalingLabel _Category;
[JsonIgnore]
public ScalingLabel Category
{
get => _Category;
set
{
CategoryName = value.Name;
_Category = value;
}
}
[JsonIgnore]
public IEnumerable<Result> MatchingResults { get; set; }
public string CheckedListName { get; set; }
public string CategoryName { get; set; }
public string DisplayValue { get; set; }
public override string ToString()
=> this.DisplayValue;
}
}
|
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Zengo.WP8.FAS.Helpers;
using Zengo.WP8.FAS.ViewModels;
using Zengo.WP8.FAS.Models;
#endregion
namespace Zengo.WP8.FAS.Controls
{
public partial class PitchRotwControl : UserControl
{
#region Events
public event EventHandler<PlayerIconTapEventArgs> PlayerTapped;
//public event EventHandler<ManagerIconTapEventArgs> ManagerTapped;
#endregion
#region Constructors
public PitchRotwControl()
{
InitializeComponent();
//EuropeManagers.FlyoutOpened += EuropeManagers_FlyoutOpened;
//EuropeManagers.FlyoutClosed += EuropeManagers_FlyoutClosed;
FlyoutSubstitutes.FlyoutOpened += EuropeSubstitutes_FlyoutOpened;
FlyoutSubstitutes.FlyoutClosed += EuropeSubstitutes_FlyoutClosed;
foreach (UserControl c in CanvasRotw.Children)
{
if (c is PlayerIconControl)
{
PlayerIconControl icon = c as PlayerIconControl;
icon.PlayerTapped += Player_Tapped;
icon.ManipulationStarted += Animation.Standard_ManipulationStarted_1;
icon.ManipulationCompleted += Animation.Standard_ManipulationCompleted_1;
}
}
FlyoutSubstitutes.PlayerTapped += Player_Tapped;
//EuropeManagers.ManagerTapped += Manager_Tapped;
}
#endregion
#region Event Handlers
void Player_Tapped(object sender, PlayerIconTapEventArgs e)
{
if (PlayerTapped != null)
{
PlayerTapped(this, e);
}
}
//void Manager_Tapped(object sender, ManagerIconTapEventArgs e)
//{
// if (ManagerTapped != null)
// {
// ManagerTapped(this, e);
// }
//}
//void EuropeManagers_FlyoutOpened(object sender, System.EventArgs e)
//{
// EuropeSubstitutes.Close();
// GridGrayedOut.Visibility = System.Windows.Visibility.Visible;
// EuropeSubstitutes.GridSlidOutState.IsHitTestVisible = false;
//}
//void EuropeManagers_FlyoutClosed(object sender, System.EventArgs e)
//{
// GridGrayedOut.Visibility = System.Windows.Visibility.Collapsed;
// EuropeSubstitutes.GridSlidOutState.IsHitTestVisible = true;
//}
void EuropeSubstitutes_FlyoutOpened(object sender, System.EventArgs e)
{
//EuropeManagers.Close();
GridGrayedOut.Visibility = System.Windows.Visibility.Visible;
//EuropeManagers.GridSlidOutState.IsHitTestVisible = false;
}
void EuropeSubstitutes_FlyoutClosed(object sender, System.EventArgs e)
{
GridGrayedOut.Visibility = System.Windows.Visibility.Collapsed;
//EuropeManagers.GridSlidOutState.IsHitTestVisible = true;
}
private void GridGrayedOut_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
FlyoutSubstitutes.Close();
//EuropeManagers.Close();
}
#endregion
#region Helpers
internal void Reload(PitchRecord pitch)
{
foreach (UserControl c in CanvasRotw.Children)
{
if (c is PlayerIconControl)
{
PlayerIconControl icon = c as PlayerIconControl;
icon.Reload(pitch);
}
}
//EuropeManagers.Reload();
FlyoutSubstitutes.PlayerSubGoalkeper.IsEurope = false;
FlyoutSubstitutes.PlayerSubDefender.IsEurope = false;
FlyoutSubstitutes.PlayerSubMidfield.IsEurope = false;
FlyoutSubstitutes.PlayerSubForward.IsEurope = false;
FlyoutSubstitutes.Reload(pitch);
}
internal bool IsSubstitutesOpen()
{
return FlyoutSubstitutes.IsOpen();
}
internal void CloseSubstitutes()
{
FlyoutSubstitutes.Close();
}
//internal bool IsManagerOpen()
//{
// return EuropeManagers.IsOpen();
//}
//internal void CloseManager()
//{
// EuropeManagers.Close();
//}
#endregion
}
}
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraReports.UI;
namespace GUI.Report.Phieuketoan
{
public partial class r_pkt : DevExpress.XtraReports.UI.XtraReport
{
public r_pkt()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using Aqueduct.Domain;
using StructureMap;
namespace Aqueduct.SitecoreLib.DataAccess
{
[Serializable]
public class EntityCache
{
private const string Key = "EntityCacheKey";
private readonly Dictionary<EntityUniqueKey, ISitecoreDomainEntity> m_innerCache = new Dictionary<EntityUniqueKey, ISitecoreDomainEntity>();
private static readonly IContextLevelCache m_contextCache = ObjectFactory.GetInstance<IContextLevelCache>();
public bool Contains(Guid id, Type entityType)
{
return m_innerCache.ContainsKey(new EntityUniqueKey(id, entityType));
}
public ISitecoreDomainEntity Get(Guid id, Type entityType)
{
return m_innerCache[new EntityUniqueKey(id, entityType)];
}
public void Add(ISitecoreDomainEntity entity)
{
var key = new EntityUniqueKey(entity.Id, entity.GetType());
if (!m_innerCache.ContainsKey(key))
{
m_innerCache.Add(key, entity);
}
}
private EntityCache()
{
}
public static bool Exists
{
get { return GetCache () != null; }
}
public static EntityCache Current
{
get
{
var entityCache = GetCache ();
if (entityCache == null)
{
entityCache = new EntityCache ();
SetCache (entityCache);
}
return entityCache;
}
}
public void Clear()
{
m_innerCache.Clear ();
}
private static void SetCache (EntityCache scope)
{
m_contextCache.Store (Key, scope);
}
private static EntityCache GetCache ()
{
return m_contextCache.Get<EntityCache> (Key);
}
}
public interface IContextLevelCache
{
void Store<T>(string key, T t) where T : class;
T Get<T>(string key) where T : class;
void Remove (string key);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MobileService45.DAL;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
namespace MobileService45.Controllers
{
[RoutePrefix("DEL_PASSVersion1")]
public class DelPassVersion1Controller : ApiController
{
[Route("GET_DS_DEL_PASS")]
[HttpGet]
public async Task<IHttpActionResult> GetDSDelPass(string Mobile, string Password,string OTP , int P_Count)
{
var CheckMobile = await Datacs.IsValidMobile(Mobile, Password, OTP);
if (CheckMobile != "true") return BadRequest(CheckMobile);
List<OracleParameter> param = new List<OracleParameter>();
OracleParameter p1 = new OracleParameter("P_COUNT", OracleDbType.Int32);
p1.Value = P_Count;
param.Add(p1);
var Result = Datacs.GetData("DEL_PASS.", "GET_DS_DEL_PASS", param);
if (Result == null)
{
return BadRequest("Không thực hiện được yêu cầu, vui lòng xem lại thông tin");
}
return Ok(Result);
}
[Route("UPDATE_DEL_PASS")]
[HttpGet]
public async Task<IHttpActionResult> UpdateDelPass(string Mobile, string Password,string OTP, int P_ID, string P_Account, int P_Status, string P_Descript)
{
var CheckMobile = await Datacs.IsValidMobile(Mobile, Password, OTP);
if (CheckMobile != "true") return BadRequest(CheckMobile);
List<OracleParameter> param = new List<OracleParameter>();
OracleParameter p1 = new OracleParameter("P_ID", OracleDbType.Int32);
OracleParameter p2 = new OracleParameter("P_ACCOUNT", OracleDbType.Varchar2);
OracleParameter p3 = new OracleParameter("P_STATUS", OracleDbType.Int32);
OracleParameter p4 = new OracleParameter("P_DESCRIPT", OracleDbType.Varchar2);
p1.Value = P_ID;
p2.Value = P_Account;
p3.Value = P_Status;
p4.Value = P_Descript;
param.Add(p1);
param.Add(p2);
param.Add(p3);
param.Add(p4);
var Result = Datacs.GetData("DEL_PASS.", "UPDATE_DEL_PASS", param);
if (Result == null)
{
return BadRequest("Không thực hiện được yêu cầu, vui lòng xem lại thông tin");
}
return Ok(Result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App1
{
public partial class MainPage : ContentPage
{
List<TextSpinClass> textList;
int position = 0;
public MainPage()
{
InitializeComponent();
textList = new List<TextSpinClass>
{
new TextSpinClass { LineOfText = "MAN - BSN", ColorOfText = Color.Blue },
new TextSpinClass { LineOfText = "21:30", ColorOfText = Color.Blue },
new TextSpinClass { LineOfText = "NOW BOARDING", ColorOfText = Color.Green }
};
}
private void NewButton_Clicked(object sender, EventArgs e)
{
Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
rotateText.Text = textList[position].LineOfText;
rotateText.TextColor = textList[position].ColorOfText;
position++;
if (position == textList.Count)
position = 0;
return true;
});
}
}
}
|
/************************************
** Created by Wizcas (wizcas.me)
************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IThinkGoto
{
Transform MoveTo { get; }
}
public interface IThinkWatch
{
Transform StareAt { get; }
}
[System.Serializable]
public abstract class HumanThought
{
public HumanState state;
public bool isFinished;
public HumanAI owner;
public float speed = -1;
protected virtual string[] Speeches
{
get { return null; }
}
private SightTracer _tracer;
public HumanThought(HumanAI owner)
{
this.owner = owner;
}
public virtual void Init()
{
_tracer = new SightTracer(owner);
}
public virtual void Update()
{
isFinished = CheckFinished();
if (isFinished)
{
Debug.Log(string.Format("<color=red>Thought {0} is Finished</color>", GetType()), owner);
}
if (_tracer.IsInSight(owner.eyes, owner.cat.transform) && !owner.cat.isHiding)
{
Messenger.Broadcast("CatInSight");
}
}
protected abstract bool CheckFinished();
public virtual bool IsSame(HumanThought thought)
{
if (GetType() != thought.GetType()) return false;
return state == thought.state &&
isFinished == thought.isFinished &&
owner == thought.owner;
}
public override string ToString()
{
string color;
switch (state)
{
case HumanState.Peace: color = "green"; break;
case HumanState.Suspicious: color = "yellow"; break;
case HumanState.Hostile: color = "red"; break;
default: color = ""; break;
}
return string.Format("<color={0}>[{1}]{2}</color>", color, GetType(), "{0}");
}
public string RandomSpeech()
{
if (Speeches == null || Speeches.Length == 0) return null;
var rnd = UnityEngine.Random.Range(0, Speeches.Length);
return Speeches[rnd];
}
}
[System.Serializable]
public class HumanPatrolThought : HumanThought
{
public Route route;
public int index = -1;
public int direction = 1;
private Waypoint _currentWaypoint;
protected override string[] Speeches
{
get
{
return new[]
{
"Hmmmmmm...",
"I'm so tired of working",
"Hope some one would love this game",
"48 hours of sleepless :/"
};
}
}
public HumanPatrolThought(HumanAI owner) : base(owner)
{
}
public override void Init()
{
base.Init();
_currentWaypoint = NextWaypoint();
}
public Waypoint NextWaypoint()
{
_currentWaypoint = route.Next(ref index, ref direction);
//Debug.Log("Current route index: " + index, owner);
return _currentWaypoint;
}
protected override bool CheckFinished()
{
return _currentWaypoint == null;
}
public override string ToString()
{
return string.Format(base.ToString(), route);
}
public override bool IsSame(HumanThought thought)
{
if (!base.IsSame(thought)) return false;
var t = (HumanPatrolThought)thought;
return route == t.route;
}
}
[System.Serializable]
public class HumanNoticeThought : HumanThought, IThinkWatch
{
public Transform stareAt;
public Transform StareAt
{
get
{
return stareAt;
}
}
private SightTracer _tracer;
protected override string[] Speeches
{
get
{
return new[]
{
"Hi there, my little Doggie",
"What's up, girl?",
"Come to papa ❤",
"Nothing stupid",
"I know, I know. Clean the litter, right?"
};
}
}
public HumanNoticeThought(HumanAI owner) : base(owner)
{
_tracer = new SightTracer(owner);
}
protected override bool CheckFinished()
{
return !_tracer.IsInSight(owner.eyes, StareAt) || owner.cat.isHiding;
}
public override string ToString()
{
return string.Format(base.ToString(), string.Format("Stare @ {0}", stareAt));
}
public override bool IsSame(HumanThought thought)
{
if (!base.IsSame(thought)) return false;
var t = (HumanNoticeThought)thought;
return stareAt == t.stareAt;
}
}
[System.Serializable]
public class HumanChaseThought : HumanThought, IThinkWatch, IThinkGoto
{
public Transform moveTo;
public Transform stareAt;
private SightTracer _tracer;
protected override string[] Speeches
{
get
{
return new[]
{
"Hey! Give it back!",
"Please! I need that!",
"Don't you hide this one!",
"Good girl...And don't escape!"
};
}
}
public Transform MoveTo
{
get
{
return moveTo;
}
}
public Transform StareAt
{
get
{
return stareAt;
}
}
public HumanChaseThought(HumanAI owner) : base(owner)
{
_tracer = new SightTracer(owner);
}
protected override bool CheckFinished()
{
return !_tracer.IsInSight(owner.eyes, StareAt) || owner.cat.isHiding;
}
public override string ToString()
{
return string.Format(base.ToString(), string.Format("Stare @ {0}, Move {1}", stareAt, MoveTo.position));
}
public override bool IsSame(HumanThought thought)
{
if (!base.IsSame(thought)) return false;
var t = (HumanChaseThought)thought;
return stareAt == t.stareAt &&
moveTo == t.moveTo;
}
}
[System.Serializable]
public class HumanInvestigateThought : HumanThought, IThinkGoto
{
public Transform moveTo;
public bool isTempTarget;
public float investigateDuration = 3f;
private float investigateEndTime;
public Transform MoveTo
{
get
{
return moveTo;
}
}
protected override string[] Speeches
{
get
{
return new[]
{
"Something wrong with this...",
"Doggie! I know you did this!",
"MLGB..(╯‵□′)╯︵┻━┻",
"I'm enough of this"
};
}
}
public HumanInvestigateThought(HumanAI owner) : base(owner) {
investigateEndTime = float.NaN;
}
protected override bool CheckFinished()
{
var mover = owner.GetComponent<HumanMover>();
if (mover.IsStandingStill)
{
if (float.IsNaN(investigateEndTime))
{
investigateEndTime = Time.time + investigateDuration;
}
}
else
{
return false;
}
// Make sure the human stops for certain time
if (Time.time < investigateEndTime)
{
return false;
}
if (isTempTarget)
{
UnityEngine.Object.Destroy(moveTo.gameObject);
}
return true;
}
public override string ToString()
{
return string.Format(base.ToString(), string.Format("Move {0}", MoveTo.position));
}
public override bool IsSame(HumanThought thought)
{
if (!base.IsSame(thought)) return false;
var t = (HumanInvestigateThought)thought;
return moveTo == t.moveTo;
}
}
public class SightTracer
{
private const float scanDeltaAngle = 15f;
private HumanAI _owner;
public SightTracer(HumanAI owner)
{
_owner = owner;
}
private float minSightAngle
{
get { return -_owner.sightRangeAngle * .5f; }
}
private float maxSightAngle
{
get { return _owner.sightRangeAngle * .5f; }
}
public bool IsInSight(Transform eyes, Transform target)
{
var sightAngle = eyes.transform.localEulerAngles.y;
var catRelDir = target.position - eyes.position;
catRelDir.y = 0;
var catAngle = VectorUtils.NormalizeAngle(Vector3.Angle(catRelDir, eyes.forward));
//Debug.LogFormat("SightRange: {0}, Cat Angle: {1}", sightRange, catAngle);
bool isCatInSightAngle = catAngle >= minSightAngle && catAngle <= maxSightAngle;
bool isCatNearEnough = catRelDir.magnitude <= _owner.detectDistance;
//Debug.LogFormat("Cat In Range? {0}, Cat In Distance? {1}({2})", isCatInRange, isCatNearEnough, catRelDir.magnitude);
if (isCatInSightAngle && isCatNearEnough) // raycast only if the cat is in sight range, in the consideration of performance.
{
return ScanSight(eyes, target);
}
return false;
}
private bool ScanSight(Transform eyes, Transform target)
{
var scanCount = Mathf.RoundToInt(_owner.sightRangeAngle / scanDeltaAngle) + 1;
var forward = eyes.forward;
forward.y = 0;
for (int x = 0; x < scanCount; x++)
{
var horizontalAngle = minSightAngle + scanDeltaAngle * x;
//Debug.Log("x: " + xAngle);
for (int y = 0; y < scanCount; y++)
{
var verticalAngle = minSightAngle + scanDeltaAngle * y;
//Debug.Log("y: " + yAngle);
//var rayDir = Quaternion.Euler(xAngle, yAngle, 0f) * forward;
var rayDir = Quaternion.AngleAxis(verticalAngle, Vector3.right) * Quaternion.AngleAxis(horizontalAngle, Vector3.up) * forward;
var sightRay = new Ray(eyes.position, rayDir);
Debug.DrawRay(eyes.position, rayDir, Color.black);
RaycastHit hit;
if (Physics.Raycast(sightRay, out hit, _owner.detectDistance, Layers.GetLayerMasks(Layers.Cat, Layers.Environment, Layers.Wall)))
{
if (hit.collider.transform == target)
{
Debug.DrawLine(eyes.position, hit.point, Color.red);
return true;
}
}
}
}
return false;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Ex03.GarageLogic
{
internal abstract class MotorCycle : Vehicle
{
private eLiceseType m_LicenseType;
private float m_EngineVolume;
internal MotorCycle(string i_Model, string i_LicenseNumber, eLiceseType i_LicenseType, float i_EngineVolume)
: base(i_Model, i_LicenseNumber)
{
m_LicenseType = i_LicenseType;
EngineVolume = i_EngineVolume;
NumberOfWheels = 2;
MaxAirPressure = 28f;
}
internal MotorCycle()
: base()
{
m_LicenseType = eLiceseType.A1;
EngineVolume = 5.5f;
NumberOfWheels = 2;
MaxAirPressure = 28f;
}
internal eLiceseType LicenseType
{
get { return m_LicenseType; }
set
{
if ((int)value < 1 || (int)value > 4)
{
throw new ValueOutOfRangeException(1, 4, "Invalid license type!");
}
m_LicenseType = value;
}
}
internal float EngineVolume
{
get
{
return m_EngineVolume;
}
set
{
if (value <= 0)
{
throw new ArgumentException("Invalid engine volume!");
}
m_EngineVolume = value;
}
}
public override List<string> GetProperties()
{
List<string> allProperties = base.GetProperties();
allProperties.Add("License type - A1 = 1, B1 = 2, AA = 3, BB = 4");
allProperties.Add("Engine volume");
return allProperties;
}
public override void SetProperty(string i_PropertyName, object i_PropertyValue)
{
base.SetProperty(i_PropertyName, i_PropertyValue);
switch (i_PropertyName)
{
case "License type - A1 = 1, B1 = 2, AA = 3, BB = 4":
LicenseType = (eLiceseType)int.Parse(i_PropertyValue.ToString());
break;
case "Engine volume":
EngineVolume = float.Parse(i_PropertyValue.ToString());
break;
}
}
public override string ToString()
{
StringBuilder propertiesStr = new StringBuilder();
propertiesStr.Append(base.ToString());
string carPropertiesStr = string.Format(
@"
License type - {0}
Engine volume - {1}",
LicenseType,
EngineVolume);
propertiesStr.Append(carPropertiesStr);
return propertiesStr.ToString();
}
internal enum eLiceseType
{
A1 = 1,
B1 = 2,
AA = 3,
BB = 4
}
}
}
|
namespace Vega.Data.Models
{
using System.ComponentModel.DataAnnotations;
using Common.Models;
public class Feature : BaseModel
{
[Required]
[MaxLength(100)]
public string Name { get; set; }
}
}
|
using System;
using System.Reflection;
[assembly: AssemblyDescription("Realtime lightweight networking and entity streaming.")]
[assembly: AssemblyProduct("NetCode")]
[assembly: AssemblyTitle("NetCode")]
[assembly: AssemblyVersion("0.0.*")] |
using System;
using System.Threading.Tasks;
using Pubquiz.Domain;
using Pubquiz.Domain.Models;
using Pubquiz.Logic.Tools;
using Pubquiz.Persistence;
using Rebus.Bus;
using TeamMembersChanged = Pubquiz.Logic.Messages.TeamMembersChanged;
namespace Pubquiz.Logic.Requests
{
/// <summary>
/// Notification to change the <see cref="Team"/> members.
/// </summary>
[ValidateEntity(EntityType = typeof(Team), IdPropertyName = "TeamId")]
public class ChangeTeamMembersNotification : Notification
{
public Guid TeamId { get; set; }
public string TeamMembers { get; set; }
public ChangeTeamMembersNotification(IUnitOfWork unitOfWork, IBus bus) : base(unitOfWork, bus)
{
}
protected override async Task DoExecute()
{
var teamCollection = UnitOfWork.GetCollection<Team>();
var team = await teamCollection.GetAsync(TeamId);
team.MemberNames = TeamMembers;
await teamCollection.UpdateAsync(team);
await Bus.Publish(new TeamMembersChanged(team.GameId, TeamId, team.Name, TeamMembers));
}
}
} |
using System.IO;
namespace TQVaultAE.Domain.Entities;
public partial class RecordId
{
#region IsBroken
bool? _IsBroken;
/// <summary>
/// This <see cref="RecordId"/> leads to Broken content.
/// </summary>
public bool IsBroken
{
get
{
if (_IsBroken is null)
_IsBroken = this.Normalized.Contains(@"\BROKEN\");
return _IsBroken.Value;
}
}
#endregion
#region IsSuffix
bool? _IsSuffix;
/// <summary>
/// This <see cref="RecordId"/> leads to Suffix content.
/// </summary>
public bool IsSuffix
{
get
{
if (_IsSuffix is null)
_IsSuffix = this.Normalized.Contains(@"\SUFFIX\");
return _IsSuffix.Value;
}
}
#endregion
#region IsPrefix
bool? _IsPrefix;
/// <summary>
/// This <see cref="RecordId"/> leads to Prefix content.
/// </summary>
public bool IsPrefix
{
get
{
if (_IsPrefix is null)
_IsPrefix = this.Normalized.Contains(@"\PREFIX\");
return _IsPrefix.Value;
}
}
#endregion
#region IsLootMagicalAffixes
bool? _IsLootMagicalAffixes;
/// <summary>
/// This <see cref="RecordId"/> leads to LootMagicalAffixes content.
/// </summary>
public bool IsLootMagicalAffixes
{
get
{
if (_IsLootMagicalAffixes is null)
_IsLootMagicalAffixes = this.Normalized.Contains(@"\LOOTMAGICALAFFIXES\");
return _IsLootMagicalAffixes.Value;
}
}
#endregion
#region IsTablesWeapon
bool? _IsTablesWeapon;
/// <summary>
/// This <see cref="RecordId"/> leads to TablesUnique content.
/// </summary>
public bool IsTablesWeapon
{
get
{
if (_IsTablesWeapon is null)
_IsTablesWeapon = this.Normalized.Contains(@"\TABLESWEAPON") || Path.GetFileName(this.Normalized).StartsWith(@"TABLE_WEAPON");
return _IsTablesWeapon.Value;
}
}
#endregion
#region IsTablesUnique
bool? _IsTablesUnique;
/// <summary>
/// This <see cref="RecordId"/> leads to TablesUnique content.
/// </summary>
public bool IsTablesUnique
{
get
{
if (_IsTablesUnique is null)
_IsTablesUnique = this.Normalized.Contains(@"\TABLESUNIQUE");
return _IsTablesUnique.Value;
}
}
#endregion
#region IsTablesShields
bool? _IsTablesShields;
/// <summary>
/// This <see cref="RecordId"/> leads to TablesJewelry content.
/// </summary>
public bool IsTablesShields
{
get
{
if (_IsTablesShields is null)
_IsTablesShields = this.Normalized.Contains(@"\TABLESSHIELD") || Path.GetFileName(this.Normalized).StartsWith(@"TABLE_SHIELD");
return _IsTablesShields.Value;
}
}
#endregion
#region IsTablesJewelry
bool? _IsTablesJewelry;
/// <summary>
/// This <see cref="RecordId"/> leads to TablesJewelry content.
/// </summary>
public bool IsTablesJewelry
{
get
{
if (_IsTablesJewelry is null)
_IsTablesJewelry = this.Normalized.Contains(@"\TABLESJEWELRY");
return _IsTablesJewelry.Value;
}
}
#endregion
#region IsTablesArmor
bool? _IsTablesArmor;
/// <summary>
/// This <see cref="RecordId"/> leads to TablesArmor content.
/// </summary>
public bool IsTablesArmor
{
get
{
if (_IsTablesArmor is null)
_IsTablesArmor = this.Normalized.Contains(@"\TABLESARMOR") || Path.GetFileName(this.Normalized).StartsWith(@"TABLE_ARMOR");
return _IsTablesArmor.Value;
}
}
#endregion
#region LootTableGearType
GearType? _LootTableGearType;
/// <summary>
/// return GearType based on file naming rules for loot table <see cref="RecordId"/>.
/// </summary>
public GearType LootTableGearType
{
get
{
if (!IsLootMagicalAffixes) return GearType.Undefined;
if (_LootTableGearType is null)
_LootTableGearType = Path.GetFileName(this.Normalized) switch
{
var x when x.StartsWith(@"ARMSMAGE") || x.StartsWith(@"ARMMAGE") => GearType.Arm | GearType.ForMage,
var x when x.StartsWith(@"ARMSMELEE") || x.StartsWith(@"ARMMELEE") => GearType.Arm | GearType.ForMelee,
var x when x.StartsWith(@"HEADMAGE") => GearType.Head | GearType.ForMage,
var x when x.StartsWith(@"HEADMELEE") => GearType.Head | GearType.ForMelee,
var x when x.StartsWith(@"LEGSMAGE") || x.StartsWith(@"LEGMAGE") => GearType.Leg | GearType.ForMage,
var x when x.StartsWith(@"LEGSMELEE") || x.StartsWith(@"LEGMELEE") => GearType.Leg | GearType.ForMelee,
var x when x.StartsWith(@"TORSOMAGE") => GearType.Torso | GearType.ForMage,
var x when x.StartsWith(@"TORSOMELEE") => GearType.Torso | GearType.ForMelee,
var x when x.StartsWith(@"RING") => GearType.Ring,
var x when x.StartsWith(@"AMULET") => GearType.Amulet,
var x when x.StartsWith(@"SHIELD") => GearType.Shield,
var x when x.StartsWith(@"AXE") => GearType.Axe,
var x when x.StartsWith(@"BOW") => GearType.Bow,
var x when x.StartsWith(@"CLUB") => GearType.Mace,
var x when x.StartsWith(@"ROH") => GearType.Thrown,
var x when x.StartsWith(@"SPEAR") => GearType.Spear,
var x when x.StartsWith(@"STAFF") => GearType.Staff,
var x when x.StartsWith(@"SWORD") => GearType.Sword,
// For Broken Affixes
var x when x.StartsWith(@"TABLE_ARMOR") => GearType.AllArmor,
var x when x.StartsWith(@"TABLE_SHIELD") => GearType.Shield,
var x when x.StartsWith(@"TABLE_WEAPONSCLUB") => GearType.Mace,
var x when x.StartsWith(@"TABLE_WEAPONSMETAL") => GearType.Sword | GearType.Axe | GearType.Thrown,
var x when x.StartsWith(@"TABLE_WEAPONSWOOD") => GearType.Spear | GearType.Staff | GearType.Bow,
//RECORDS\XPACK4\ITEM\LOOTMAGICALAFFIXES\SUFFIX\TABLESARMOR\CHINAMONSTERSUFFIX_L05.DBR
//RECORDS\XPACK4\ITEM\LOOTMAGICALAFFIXES\SUFFIX\TABLESARMOR\EGYPTMONSTERSUFFIX_L05.DBR
var x when x.Contains(@"MONSTER") => GearType.MonsterInfrequent,
_ => GearType.Undefined,
};
return _LootTableGearType.Value;
}
}
#endregion
}
|
namespace PluginB
{
using System.Collections.Generic;
using System.Linq;
using Shared;
public class FooEFMepository : IFooRepository
{
private readonly PluginBDbContext _dbContext;
public FooEFMepository(PluginBDbContext dbContext)
{
this._dbContext = dbContext;
}
public IEnumerable<Foo> Get()
{
return this._dbContext.Foos
.Select(s => new Foo
{
Id = s.Id,
Name = s.Name
})
.ToList();
}
}
}
|
using Grupo5_Hotel.Entidades.Entidades;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grupo5_Hotel.Datos
{
public static class ReservaMapper
{
public static List<Reserva> TraerReservas()
{
string json = WebHelper.Get("./Hotel/Reservas/" + ConfigurationManager.AppSettings["Legajo"]);
return MapList(json);
}
public static List<Reserva> MapList(string json)
{
return JsonConvert.DeserializeObject<List<Reserva>>(json);
}
public static TransactionResult Resultado(string json)
{
return JsonConvert.DeserializeObject<TransactionResult>(json);
}
public static NameValueCollection ReverseMap(Reserva reserva)
{
NameValueCollection n = new NameValueCollection();
n.Add("idHabitacion", reserva.IdHabitacion.ToString());
n.Add("idCliente", reserva.IdCliente.ToString());
n.Add("CantidadHuespedes", reserva.CantidadHuespedes.ToString());
n.Add("FechaIngreso", reserva.FechaIngreso.ToString());
n.Add("FechaEgreso", reserva.FechaEgreso.ToString());
n.Add("Usuario", ConfigurationManager.AppSettings["Legajo"]);
n.Add("id", reserva.Id.ToString());
return n;
}
public static TransactionResult Insert(Reserva reserva)
{
NameValueCollection n = ReverseMap(reserva);
string result = WebHelper.Post("./Hotel/Reservas/", n);
return Resultado(result);
}
}
}
|
using System;
using System.Collections.Generic;
using SoSmartTv.VideoService.Dto;
namespace SoSmartTv.VideoService.Store
{
public interface IVideoItemsStoreReader
{
IObservable<VideoItem> GetVideoItem(string title);
IObservable<IList<VideoItem>> GetVideoItems(IEnumerable<string> titles);
IObservable<VideoDetailsItem> GetVideoDetailsItem(int id);
}
} |
namespace MVC_HomeWork.Models
{
using DataTypeAttributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(客戶銀行資訊MetaData))]
public partial class 客戶銀行資訊
{
}
public partial class 客戶銀行資訊MetaData
{
[Required]
public int Id { get; set; }
[Required]
public int 客戶Id { get; set; }
[Required(ErrorMessage = "請填寫銀行名稱")]
//[StringLength(10, ErrorMessage = "測試中,本系統名稱最長允許10個字元")]
[CustomStringLengthValidation(10)]
public string 銀行名稱 { get; set; }
[Required]
public int 銀行代碼 { get; set; }
public Nullable<int> 分行代碼 { get; set; }
[Required(ErrorMessage = "請填寫帳戶名稱")]
//[StringLength(10, ErrorMessage = "測試中,本系統名稱最長允許10個字元")]
[CustomStringLengthValidation(5)]
public string 帳戶名稱 { get; set; }
[Required(ErrorMessage = "請填寫帳戶號碼")]
[RegularExpression(@"^[0-9]{12}$", ErrorMessage = "測試中,帳戶號碼應為十二碼數字")]
public string 帳戶號碼 { get; set; }
public Nullable<bool> 是否已刪除 { get; set; }
public virtual 客戶資料 客戶資料 { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class ParcelModule : System.Web.UI.Page
{
string obj_Authenticated;
PlaceHolder maPlaceHolder;
UserControl obj_Tabs;
UserControl obj_LoginCtrl;
UserControl obj_WelcomCtrl;
UserControl obj_Navi;
UserControl obj_Navihome;
BizConnectClient bizcl = new BizConnectClient();
TripAgreementClass Trip_Agreement = new TripAgreementClass();
BizConnectLogisticsPlan obj_BizConnectLogisticsPlanClass = new BizConnectLogisticsPlan();
int AgreementID;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ChkAuthentication();
Client();
Transporter();
}
}
public void Client()
{
//Fill Client
DataSet dsl = new DataSet();
dsl = Trip_Agreement.Bizconnect_GetClient();
DDLClient.Items.Clear();
DDLClient.DataSource = dsl;
DDLClient.DataTextField = "CompanyName";
DDLClient.DataValueField = "ClientID";
DDLClient.DataBind();
DDLClient.Items.Insert(0, new ListItem("--- Select Client ---", "0"));
}
public void Clientcity()
{
//Fill Client Location
DataSet dsl = new DataSet();
dsl = bizcl.Fillclientcity(Convert.ToInt32(DDLClient.SelectedValue));
DDLClientAddrLoction.Items.Clear();
DDLClientAddrLoction.DataSource = dsl;
DDLClientAddrLoction.DataTextField = "City";
DDLClientAddrLoction.DataValueField = "ClientAddressLocationID";
DDLClientAddrLoction.DataBind();
DDLClientAddrLoction.Items.Insert(0, new ListItem("--- Select Client Location ---", "0"));
}
public void Transporter()
{
//Fill Transporter
DataSet dsl = new DataSet();
dsl = Trip_Agreement.Get_Transporter();
DDLTransporter.Items.Clear();
DDLTransporter.DataSource = dsl;
DDLTransporter.DataTextField = "Transporter";
DDLTransporter.DataValueField = "TransporterID";
DDLTransporter.DataBind();
DDLTransporter.Items.Insert(0, new ListItem("--- Select Transporter ---", "0"));
}
public void ChkAuthentication()
{
obj_LoginCtrl = null;
obj_WelcomCtrl = null;
obj_Navi = null;
obj_Navihome = null;
if (Session["Authenticated"] == null)
{
Session["Authenticated"] = "0";
}
else
{
obj_Authenticated = Session["Authenticated"].ToString();
}
maPlaceHolder = (PlaceHolder)Master.FindControl("P1");
if (maPlaceHolder != null)
{
obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1");
if (obj_Tabs != null)
{
obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1");
obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1");
// obj_Navi = (UserControl)obj_Tabs.FindControl("Navii");
//obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1");
if (obj_LoginCtrl != null & obj_WelcomCtrl != null)
{
if (obj_Authenticated == "1")
{
SetVisualON();
}
else
{
SetVisualOFF();
}
}
}
else
{
}
}
else
{
}
}
public void SetVisualON()
{
obj_LoginCtrl.Visible = false;
obj_WelcomCtrl.Visible = true;
//obj_Navi.Visible = true;
//obj_Navihome.Visible = true;
}
public void SetVisualOFF()
{
obj_LoginCtrl.Visible = true;
obj_WelcomCtrl.Visible = false;
// obj_Navi.Visible = true;
//obj_Navihome.Visible = false;
}
protected void DDLClient_SelectedIndexChanged(object sender, EventArgs e)
{
Clientcity();
}
protected void ButSubmit_Click(object sender, EventArgs e)
{
try
{
int res = Trip_Agreement.Bizconnect_InsertAgreement(Convert.ToInt32(DDLClient.SelectedValue), Convert.ToInt32(DDLClientAddrLoction.SelectedValue), Convert.ToInt32(DDLTransporter.SelectedValue),1);
if (res == 1)
{
GetAgreementID(Convert.ToInt32(DDLClient.SelectedValue), Convert.ToInt32(DDLClientAddrLoction.SelectedValue), Convert.ToInt32(DDLTransporter.SelectedValue));
lblmsg.Visible = true;
lblmsg1.Visible = true;
TblAgreement.Visible = true;
string Conn = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
SqlConnection conn = new SqlConnection();
SqlCommand cmd;
conn.ConnectionString = Conn;
conn.Open();
string qry = "insert into Bizconnect_ParcelParameters(ClientID,TransporterId,FSC,VSC,FOV,DHC,IntimationCharges,MinimumCharges,LRCharges)values(" + Convert.ToInt32(DDLClient.SelectedValue) + " ," + Convert.ToInt32(DDLTransporter.SelectedValue) + "," + Convert.ToSingle(txtFSCpercent.Text) + "," + Convert.ToSingle(txtVSCpercent.Text) + "," + Convert.ToSingle(txtFOVpercent.Text) + "," + Convert.ToSingle(txtDHC.Text) + "," + Convert.ToSingle(txtinitimation.Text) + "," + Convert.ToSingle(txtminimumbasic.Text) + "," + Convert.ToSingle(txtLRcharges.Text) + ")";
cmd = new SqlCommand(qry, conn);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
}
}
public void GetAgreementID(int ClientID, int ClientAdrID, int TransID)
{
AgreementID = 0;
AgreementID = Trip_Agreement.GetAgreementID(ClientID, ClientAdrID, TransID);
Session["AgreementID"] = AgreementID.ToString();
}
public void LoadAgreementRoutes()
{
try
{
DataTable dt = new DataTable();
dt = Trip_Agreement.DisplayAgreementRoutes(Convert.ToInt32(DDLClient.SelectedValue), Convert.ToInt32(DDLClientAddrLoction.SelectedValue), Convert.ToInt32(DDLTransporter.SelectedValue));
Gridwindow.DataSource = dt;
Gridwindow.DataBind();
if (dt.Rows.Count > 0)
{
TblAgreement.Visible = true;
}
else
{
TblAgreement.Visible = false;
}
}
catch (Exception ex)
{
}
}
//display details in gridview after selecting from transporter drop down list
public void LoadDetails()
{
try
{
DataTable dt = new DataTable();
dt = Trip_Agreement.Agreement_Details(Convert.ToInt32(Session["ClientID"].ToString()));
Gridwindow.DataSource = dt;
Gridwindow.DataBind();
if (dt.Rows.Count > 0)
{
TblAgreement.Visible = true;
}
else
{
TblAgreement.Visible = false;
}
}
catch (Exception ex)
{
}
}
protected void DDLTransporter_SelectedIndexChanged(object sender, EventArgs e)
{
//LoadAgreementRoutes();
LoadDetails();
GetAgreementID(Convert.ToInt32(DDLClient.SelectedValue), Convert.ToInt32(DDLClientAddrLoction.SelectedValue), Convert.ToInt32(DDLTransporter.SelectedValue));
if (AgreementID > 0)
{
lblmsg1.Visible = true;
TblAgreement.Visible = true;
}
else
{
lblmsg1.Visible = false;
TblAgreement.Visible = false;
}
}
protected void ButAssign_Click(object sender, EventArgs e)
{
try
{
Trip_Agreement.FromLocation =txtFrom .Text ;
Trip_Agreement .ToLocation =txtto .Text ;
Trip_Agreement .EnclosureType =1;
Trip_Agreement .TruckType =1;
Trip_Agreement .RatePerKG =Convert .ToSingle (txtDecideprice .Text);
Trip_Agreement .DeliveryPeriod =ddl_UOM .SelectedValue;
Trip_Agreement .OtherCharges =0;
Trip_Agreement .LRCharges =0;
Trip_Agreement .DoorDeliveryCharges =0;
Trip_Agreement .DoorCollectionCharges =0;
int resp = Trip_Agreement.Insert_ParcelAgreementDetails();
if (resp == 1)
{
LoadAgreementRoutes();
Clear();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Route Add Successfully');</script>");
}
//int resp = Trip_Agreement.Insert_AgreementRoute(Convert.ToInt32(DDLClient.SelectedValue), Convert.ToInt32(DDLClientAddrLoction.SelectedValue), Convert.ToInt32(DDLTransporter.SelectedValue), Convert.ToInt32(Session["AgreementID"].ToString()), txtFrom.Text, txtto.Text, 1, 1, ddl_UOM.SelectedItem.Text, Convert.ToSingle(txtDecideprice.Text), Convert.ToInt32(txttransitdays.Text));
if (resp == 1)
{
LoadAgreementRoutes();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Route Add Successfully');</script>");
}
}
catch (Exception ex)
{
}
}
public void Clear()
{
}
protected void ButAddslab_Click(object sender, EventArgs e)
{
string Conn = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
SqlConnection conn = new SqlConnection();
SqlCommand cmd;
conn.ConnectionString = Conn;
conn.Open();
string qry = "insert into DoorDeliverySlap(ClientID,TransporterID,NoofBoxs,charge)values(" + Convert.ToInt32(DDLClient.SelectedValue) + " ," + Convert.ToInt32(DDLTransporter.SelectedValue) + "," + Convert.ToInt32(ddl_CotonBox.SelectedValue) + ","+ Convert.ToInt32(txtDoordeliverycharges.Text)+")";
cmd = new SqlCommand(qry, conn);
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Slap Added Successfully');</script>");
}
} |
using System;
using MvvmCross.Binding.BindingContext;
using MvvmCross.iOS.Views;
using VictimApplication.Core.ViewModels;
using UIKit;
namespace VictimApplication.iOS.Views
{
public partial class MenuView : MvxViewController<MenuViewModel>
{
public MenuView() : base("MenuView", null)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
this.CreateBinding(VCLogout).To((MenuViewModel vm) => vm.ShowLoginCommand).Apply();
this.CreateBinding(VCInformation).To((MenuViewModel vm) => vm.ShowInformationCommand).Apply();
this.CreateBinding(VCCases).To((MenuViewModel vm) => vm.ShowCasesCommand).Apply();
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileImport.Common
{
public enum ImportEncodingType
{
Default = 1,
ASCII = 2,
UTF7 = 3,
UTF8 = 4,
UTF32 = 5,
BigEndianUnicode = 6,
Unicode = 7
}
}
|
using NSubstitute;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Assert = NUnit.Framework.Assert;
namespace SWT_20_ATM.Test.Unit
{
[TestFixture]
class UnitTestDecoder
{
private Decoder uut;
private IPlane CorrectPlane;
private DateTime CorrectDateTime;
[SetUp]
public void init()
{
uut = new Decoder();
CorrectDateTime = new DateTime( 2000, 01, 01, 12, 30, 30, 500 );
//Create fake Plane with Invalid Direction
CorrectPlane = Substitute.For<IPlane>();
CorrectPlane.Tag.Returns( "TEST123" );
CorrectPlane.XCoordinate.Returns( 10000 );
CorrectPlane.YCoordinate.Returns( 10000 );
CorrectPlane.Altitude.Returns( 10000 );
CorrectPlane.LastUpdate.Returns( CorrectDateTime );
}
[TestCase( "TEST123;10000;10000;10000;20000101123030500" )]
public void ReceiveValidInput_SetDecoderList( string input )
{
var inputList = new List<string> { input };
uut.Decode( inputList );
Assert.That( uut.OldPlaneList[0].XCoordinate, Is.EqualTo( CorrectPlane.XCoordinate ) );
Assert.That( uut.OldPlaneList[0].YCoordinate, Is.EqualTo( CorrectPlane.YCoordinate ) );
Assert.That( uut.OldPlaneList[0].LastUpdate, Is.EqualTo( CorrectPlane.LastUpdate ) );
Assert.That( uut.OldPlaneList[0].Tag, Is.EqualTo( CorrectPlane.Tag ) );
Assert.That( uut.OldPlaneList[0].Altitude, Is.EqualTo( CorrectPlane.Altitude ) );
Assert.That( uut.OldPlaneList[0].Direction, Is.EqualTo( CorrectPlane.Direction ) );
Assert.That( uut.OldPlaneList[0].Speed, Is.EqualTo( CorrectPlane.Speed ) );
}
[TestCase( "TEST123;10000;10000;10000;20000101123030500", "TEST123;10000;10500;10000;20000101123031500" )] //Plane travelled 500 units along y-axis.
public void Receive2Inputs_UpdateSpeedAndDirectionForPlanes( string input1, string input2 )
{
//First input
var InputList = new List<string> { input1 };
uut.Decode( InputList );
//Second input
InputList.Clear();
InputList.Add( input2 );
uut.Decode( InputList );
Assert.That( uut.OldPlaneList[0].Speed, Is.EqualTo( 500 ) );
}
[TestCase( "TEST123;10000;10000;10000;20000101123030500", "TEST321;10000;10500;10000;20000101123031500" )]
public void Receive2Inputs_HaveMultiplePlanesInOldPlaneList( string input1, string input2 )
{
//First input
var inputList = new List<string> { input1 };
uut.Decode( inputList );
//Second input
inputList.Add( input2 );
uut.Decode( inputList );
//Planes are in same position.
uut.Decode( inputList );
Assert.That( uut.OldPlaneList.Count, Is.EqualTo( 2 ) );
}
[TestCase]
public void Receive2Inputs_Update_SpeedAndDirectionIsNaN()
{
//Create fake Plane with Invalid
IPlane invalidSpeedPlane = Substitute.For<IPlane>();
invalidSpeedPlane.Tag.Returns( "TEST123" );
invalidSpeedPlane.XCoordinate.Returns( 10000 );
invalidSpeedPlane.YCoordinate.Returns( 10000 );
invalidSpeedPlane.LastUpdate.Returns( CorrectDateTime );
invalidSpeedPlane.Speed.Returns( Double.NaN );
//Create fake Plane with Invalid Direction
IPlane invalidDirectionPlane = Substitute.For<IPlane>();
invalidDirectionPlane.Tag.Returns( "TEST321" );
invalidDirectionPlane.XCoordinate.Returns( 10000 );
invalidDirectionPlane.YCoordinate.Returns( 10000 );
invalidDirectionPlane.LastUpdate.Returns( CorrectDateTime );
invalidDirectionPlane.Direction.Returns( Double.NaN );
List<IPlane> planeWithNaNSpeed = new List<IPlane> { invalidSpeedPlane, invalidDirectionPlane };
//No planes were added to EmptyPlaneList because all planes that was to be added were invalid.
List<IPlane> emptyPlaneList = uut.GetCompletePlanes( planeWithNaNSpeed );
Assert.IsEmpty( emptyPlaneList );
}
//[TestCase]
//public void Receive2Inputs_Update_DirectionIsNaN()
//{
// //Create fake Plane with Invalid Direction
// IPlane invalidDirectionPlane = Substitute.For<IPlane>();
// invalidDirectionPlane.Tag.Returns("TEST321");
// invalidDirectionPlane.XCoordinate.Returns(10000);
// invalidDirectionPlane.YCoordinate.Returns(10000);
// invalidDirectionPlane.LastUpdate.Returns(CorrectDateTime);
// invalidDirectionPlane.Speed.Returns(Double.NaN);
// List<IPlane> planeWithNaNSpeed = new List<IPlane> { invalidSpeedPlane, invalidDirectionPlane };
// //No planes were added to EmptyPlaneList because all planes that was to be added were invalid.
// List<IPlane> emptyPlaneList = uut.GetCompletePlanes(planeWithNaNSpeed);
// Assert.IsEmpty(emptyPlaneList);
//}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinCollection : MonoBehaviour {
public int value;
private AudioSource sound;
private Renderer rend;
void Start()
{
sound = GetComponent<AudioSource>();
rend = GetComponent<Renderer>();
rend.enabled = true;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
sound.Play();
other.GetComponent<PlayerManager>().addScore(value);
rend.enabled = false;
Destroy(gameObject, sound.clip.length);
//Destroy(gameObject);
}
}
}
|
using Iri.Plugin.Types;
namespace Iri.Plugin.Tests.Types
{
interface ITestPlugin : IPlugin
{
int DoFoo(int a, int b);
}
}
|
using MahApps.Metro.Controls;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Ribbon;
namespace Webcorp.erp.Utilities
{
internal static class FrameworkExtensions
{
static internal bool Is<T>(this FrameworkElement element)=>typeof(T).IsAssignableFrom(element.GetType());
}
public abstract class RegionAdapter<T> : RegionAdapterBase<T> where T : class{
public RegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
{
}
protected abstract void Add(T regionTarget, FrameworkElement element);
protected abstract void Remove(T regionTarget, UIElement element);
protected override void Adapt(IRegion region, T regionTarget)
{
region.Views.CollectionChanged += (sender, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (FrameworkElement element in e.NewItems)
{
Add(regionTarget, element);
/*if (element.Is<T>())
{
List<object> items = new List<object>();
foreach (var item in ((RibbonApplicationMenu)element).Items)
{
items.Add(item);
}
foreach (var item in items)
{
((RibbonApplicationMenu)element).Items.Remove(item);
//regionTarget.ApplicationMenu.Items.Add(item);
}
items.ForEach(item => regionTarget.ApplicationMenu.Items.Add(item));
}
else
regionTarget.Items.Add(element);*/
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (UIElement elementLoopVariable in e.OldItems)
{
var element = elementLoopVariable;
/*if (regionTarget.Items.Contains(element))
{
regionTarget.Items.Remove(element);
}*/
Remove(regionTarget, element);
}
break;
}
};
}
protected override IRegion CreateRegion()=> new SingleActiveRegion();
}
public class RibbonRegionAdapter : RegionAdapter<Ribbon>
{
public RibbonRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
{
}
protected override void Add(Ribbon regionTarget, FrameworkElement element)
{
if (element.Is<RibbonApplicationMenu>())
{
List<object> items = new List<object>();
foreach (var item in ((RibbonApplicationMenu)element).Items)
{
items.Add(item);
}
foreach (var item in items)
{
((RibbonApplicationMenu)element).Items.Remove(item);
//regionTarget.ApplicationMenu.Items.Add(item);
}
items.ForEach(item => regionTarget.ApplicationMenu.Items.Add(item));
}
else
regionTarget.Items.Add(element);
}
protected override void Remove(Ribbon regionTarget, UIElement element)
{
if (regionTarget.Items.Contains(element))
{
regionTarget.Items.Remove(element);
}
}
}
public class MetroAnimatedSingleRowTabControlAdapter : RegionAdapter<MetroAnimatedSingleRowTabControl>
{
public MetroAnimatedSingleRowTabControlAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
{
}
protected override void Add(MetroAnimatedSingleRowTabControl regionTarget, FrameworkElement element)
{
if (element.Is<MetroAnimatedSingleRowTabControl>())
{
List<object> items = new List<object>();
foreach (var item in ((MetroAnimatedSingleRowTabControl)element).Items)
{
items.Add(item);
}
foreach (var item in items)
{
((MetroAnimatedSingleRowTabControl)element).Items.Remove(item);
//regionTarget.ApplicationMenu.Items.Add(item);
}
items.ForEach(item => regionTarget.Items.Add(item));
}
else
regionTarget.Items.Add(element);
}
protected override void Remove(MetroAnimatedSingleRowTabControl regionTarget, UIElement element)
{
if (regionTarget.Items.Contains(element))
{
regionTarget.Items.Remove(element);
}
}
}
/* public class RibbonRegionAdapter : RegionAdapterBase<Ribbon>
{
public RibbonRegionAdapter(IRegionBehaviorFactory behaviorFactory):base(behaviorFactory)
{
}
protected override void Adapt(IRegion region, Ribbon regionTarget)
{
region.Views.CollectionChanged += (sender, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (FrameworkElement element in e.NewItems)
{
if(element is RibbonApplicationMenu)
{
List<object> items = new List<object>();
foreach (var item in ((RibbonApplicationMenu)element).Items)
{
items.Add(item);
}
foreach (var item in items)
{
((RibbonApplicationMenu)element).Items. Remove(item);
//regionTarget.ApplicationMenu.Items.Add(item);
}
items.ForEach(item => regionTarget.ApplicationMenu.Items.Add(item));
}
else
regionTarget.Items.Add(element);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (UIElement elementLoopVariable in e.OldItems)
{
var element = elementLoopVariable;
if (regionTarget.Items.Contains(element))
{
regionTarget.Items.Remove(element);
}
}
break;
}
};
}
protected override IRegion CreateRegion()
{
//return new SingleActiveRegion();
return new AllActiveRegion();
}
}*/
}
|
using System;
namespace Feilbrot.Graphics
{
public class ComplexCube3d
{
public ComplexPoint3d point;
public decimal width;
public decimal height;
public decimal depth;
public ComplexCube3d(ComplexPoint3d point, decimal width=0, decimal height=0, decimal depth=0)
{
this.point = point;
this.width = width;
this.height = height;
this.depth = depth;
}
public ComplexPoint3d PointAtPercent(decimal percentX, decimal percentY, decimal percentZ)
{
ComplexPoint3d result = new ComplexPoint3d();
result.r = percentX * width + point.r;
result.i = percentY * height + point.i;
result.u = percentZ * depth + point.u;
return result;
}
public override string ToString()
{
return $"ComplexCube3d#(point: {point}, width: {width}, height: {height}, depth: {depth})";
}
}
}
|
using System;
using System.Windows.Forms;
using Acme.IONTestApp.Client.Model;
namespace Acme.IONTestApp.Client.Controller
{
internal class ShellController
{
#region PRIVATE FIELDS
private Shell shell;
#endregion PRIVATE FIELDS
#region CTOR
internal ShellController(Shell shell)
{
this.shell = shell;
this.shell.ApplicationExit_AddEvenListner(this.ApplicationExit);
this.shell.Login_AddEvenListner(this.UserLogin);
this.shell.LoginCheck_AddEvenListner(this.UserLoginChangePassword);
}
#endregion CTOR
#region EVENTS
private void ApplicationExit(object sender, EventArgs e)
{
Application.Exit();
}
private void UserLoginChangePassword(object sender, EventArgs e)
{
ShowLoginForm(true);
}
private void UserLogin(object sender, EventArgs e)
{
ShowLoginForm(false);
}
#endregion EVENTS
#region METHODS
private void ShowLoginForm(bool bCheckPassword = false)
{
this.shell.Status = "Logging in...";
Login frmLogin = new Login();
Credentials credentials = new Credentials();
LoginController controller = new LoginController(frmLogin, credentials);
credentials.ChangePassword = bCheckPassword;
frmLogin.ShowDialog();
switch (credentials.LoginValidation)
{
case LoginResultType.Success:
this.shell.Status = "Logged in";
break;
case LoginResultType.NetworkError:
this.shell.Status = "Not logged: Network Error";
break;
case LoginResultType.AuthFailed:
this.shell.Status = "Not logged: Wrong Login or Password";
break;
default:
this.shell.Status = "Not logged";
break;
}
}
#endregion METHODS
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Web.Api
{
/// <summary>
/// Enumeration that contains HTTP Status Codes that are not included in the HttpStatusCode enumeration provided by the .NET framework
/// </summary>
public enum HttpStatusCodeAdditions
{
/// <summary>
/// Equivalent to HTTP Status 422. Unprocessable Entity status code means the server understands the content type of the request entity (hence a
/// 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request)
/// status code is inappropriate) but was unable to process the contained instructions.
/// <see>
/// <cref>http://tools.ietf.org/html/rfc4918</cref>
/// </see>
/// </summary>
UnprocessableEntity = 422
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recursion
{
class Program
{
static void Main(string[] args)
{
int result = Factorial.FactorialFunc(5);
Console.WriteLine($"Factorial of 5 is : {result}");
Console.ReadKey();
float result2 = Factorial.Power(5, 4);
Console.WriteLine($"Power of 5 to 4 is : {result2}");
Console.ReadKey();
Node nodeOne = new Node();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using Managers;
using System;
using DG.Tweening;
public class PostProcessingTweener : MonoBehaviour
{
[SerializeField] private PostProcessVolume _farPPV;
[SerializeField] private PostProcessVolume _nearPPV;
private GameManager.PlayingState _currentState;
private void Start()
{
_currentState = GameManager.Instance.CurrentState;
EventManager.Instance.OnPlayingStateChanged.AddListener(ChangePPVWeight);
}
private void ChangePPVWeight(GameManager.PlayingState state)
{
if (state == GameManager.PlayingState.Running)
{
DOTween.To(() => _farPPV.weight, value => _farPPV.weight = value, 1f, 0.5f);
DOTween.To(() => _nearPPV.weight, value => _nearPPV.weight = value, 0f, 0.5f);
}
else if (state == GameManager.PlayingState.Dialoguing || state == GameManager.PlayingState.Smarmotting)
{
DOTween.To(() => _farPPV.weight, value => _farPPV.weight = value, 0f, 0.5f);
DOTween.To(() => _nearPPV.weight, value => _nearPPV.weight = value, 1f, 0.5f);
}
}
}
|
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Security.Claims;
using System.Threading.Tasks;
namespace InforQui_17933.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
//***********************************************************************
// Os dados do utilizador que está a referenciar a classe 'registo'
//***********************************************************************
//O Nome do utilizador
public string Nome { get; set; }
public string Morada { get; set; }
public string CodPostal { get; set; }
public int NIF { get; set; }
public string Contacto { get; set; }
public string Imagem { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
//representar a Base de Dados descrevendo as tabelas que lá estão contidas
//representar o 'construtor' desta classe
//identifica onde se encontra a base de dados
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("InforQuiDBConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
//Classe Create vai criar as tabelas para o modelo (base de dados) ApplicationDBContext
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
} //fim da classe Create
//descrever as tabelas que estão na base de dados
//tabela de Produtos
public virtual DbSet<Produtos> Produtos { get; set; }
//tabela de Compras_Produtos
public virtual DbSet<Compras_Produtos> Compras_Produtos { get; set; }
//tabela de Compras
public virtual DbSet<Compras> Compras { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// não podemos usar a chave seguinte, nesta geração de tabelas
// por causa das tabelas do Identity (gestão de utilizadores)
// modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Experian_CreditProfile_XMLtoSQLServer
{
public static class TableEnumerator
{
public enum TableNamesEnum {
CreditProfile,
Error,
Header,
RiskModel,
SSN,
ConsumerIdentity,
Name,
EmploymentInformation,
PublicRecord,
Bankruptcy,
Inquiry,
ModelAttributes,
AddressInformation,
TradeLine,
EnhancedPaymentData,
Amount,
Ballon,
Credit,
InformationalMessage,
Statement,
DirectCheck,
STAGGSelect,
Attribute,
FraudServices,
ConsumerAssistanceReferralAddress,
ProfileSummary,
AutoProfileSummary,
AutoProfileSummaryDetails,
HealthcareProfileSummary};
}
}
|
//##################
//# Script_WebTQ #
//# By #
//# Slicksilver555 #
//##################
function WebTQ_Core::addClient(%this, %tcp)
{
for(%i=0;%i<100;%i++)
{
if(isObject(%this.client[%i]))
continue;
%this.client[%i] = %tcp;
%tcp.clientNum = %i;
%this.connectedClients++;
break;
}
}
function WebTQ_Core::removeClient(%this, %tcp)
{
%this.client[%tcp.clientNum] = 0;
%this.connectedClients--;
if(isObject(%this.client[%tcp.clientNum+1]))
{
%i = %tcp.clientNum;
while(isObject(%this.client[%i++]))
{
%this.client[%i-1] = %this.client[%i];
}
%this.client[%i-1] = 0;
}
}
function WebTQ_Core::onConnectionRequest(%this, %addr, %id)
{
%this.addClient(
new TCPObject( WebTQ_Client, %id) {
address = %addr;
id = %id;
host = %this;
}
);
}
function WebTQ_Core::onRequest(%this, %tcp, %req)
{
echo(%tcp NL %req);
}
function WebTQ_Client::onDisconnect(%this)
{
%this.host.removeClient(%this);
%this.schedule(0,delete);
}
function WebTQ_Client::onLine(%this, %line)
{
%this.host.onRequest(%this, %line);
} |
using UnityEngine;
namespace Light2D
{
public class Light2DOverlap
{
private ScalableArray<Collider2D> m_Results = null;
public ScalableArray<Collider2D> results {
get { return m_Results; }
}
public Light2DOverlap(int capacity)
{
m_Results = new ScalableArray<Collider2D>(capacity);
}
public void CircleOverlap(Transform lightTransform, float radius, int layerMask)
{
Vector3 center = lightTransform.position;
while(true)
{
int count = Physics2D.OverlapCircleNonAlloc(center, radius, results.array, layerMask);
if(count < m_Results.capacity)
{
m_Results.SetLength(count);
break;
}
m_Results.Rescale(m_Results.capacity * 2);
}
}
}
} |
//------------------------------------------------------------------------------
//
// CosmosEngine - The Lightweight Unity3D Game Develop Framework
//
// Version 0.8 (20140904)
// Copyright © 2011-2014
// MrKelly <23110388@qq.com>
// https://github.com/mr-kelly/CosmosEngine
//
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Load www, A wrapper of WWW.
/// Current version, loaded Resource will never release in memory
/// </summary>
[CDependencyClass(typeof(CResourceModule))]
public class CWWWLoader : IDisposable
{
class CLoadingCache
{
public string Url;
public WWW Www;
public CLoadingCache(string url)
{
Url = url;
}
}
public static event Action<string> WWWFinishCallback;
static Dictionary<string, CLoadingCache> Loaded = new Dictionary<string, CLoadingCache>();
CLoadingCache WwwCache = null;
public bool IsFinished { get { return WwwCache != null || IsError; } } // 可协程不停判断, 或通过回调
public bool IsError { get; private set; }
public WWW Www { get { return WwwCache.Www; } }
public float Progress = 0;
/// <summary>
/// Use this to directly load WWW by Callback or Coroutine, pass a full URL.
/// A wrapper of Unity's WWW class.
/// </summary>
public CWWWLoader(string url, Action<bool, WWW, object[]> callback = null, params object[] callbackArgs)
{
IsError = false;
CResourceModule.Instance.StartCoroutine(CoLoad(url, callback, callbackArgs));//开启协程加载Assetbundle,执行Callback
}
/// <summary>
/// 协和加载Assetbundle,加载完后执行callback
/// </summary>
/// <param name="url">资源的url</param>
/// <param name="callback"></param>
/// <param name="callbackArgs"></param>
/// <returns></returns>
IEnumerator CoLoad(string url, Action<bool, WWW, object[]> callback = null, params object[] callbackArgs)
{
if (CResourceModule.LoadByQueue)
{
while (Loaded.Count != 0)
yield return null;
}
CResourceModule.LogRequest("WWW", url);
CLoadingCache cache = null;
if (!Loaded.TryGetValue(url, out cache))
{
cache = new CLoadingCache(url);
Loaded.Add(url, cache);
System.DateTime beginTime = System.DateTime.Now;
WWW www = new WWW(url);
//设置AssetBundle解压缩线程的优先级
www.threadPriority = Application.backgroundLoadingPriority; // 取用全局的加载优先速度
while (!www.isDone)
{
Progress = www.progress;
yield return null;
}
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
IsError = true;
string fileProtocol = CResourceModule.GetFileProtocol();
if (url.StartsWith(fileProtocol))
{
string fileRealPath = url.Replace(fileProtocol, "");
CDebug.LogError("File {0} Exist State: {1}", fileRealPath, System.IO.File.Exists(fileRealPath));
}
CDebug.LogError(www.error + " " + url);
if (callback != null)
callback(false, null, null); // 失败callback
yield break;
}
else
{
CResourceModule.LogLoadTime("WWW", url, beginTime);
cache.Www = www;
if (WWWFinishCallback != null)
WWWFinishCallback(url);
}
}
else
{
//if (cache.Www != null)
// yield return null; // 确保每一次异步读取资源都延迟一帧
while (cache.Www == null) // 加载中,但未加载完
yield return null;
}
Progress = cache.Www.progress;
WwwCache = cache;
if (callback != null)
callback(true, WwwCache.Www, callbackArgs);
}
/// <summary>
/// 手动释放该部分内存
/// </summary>
public void Dispose()
{
if (WwwCache != null)
{
WwwCache.Www.Dispose();
Loaded.Remove(WwwCache.Url);
}
else
CDebug.LogError("[CWWWLoader:Release]无缓存的WWW");
}
}
|
using System;
using System.Collections;
namespace QuitSmokeWebAPI.Controllers.Entity
{
public class GetingPendingPlanReq
{
public string email { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Person{
private string name;
// 자바에서는 겟 셋 프로퍼티가 없어서 이렇게 사용
public string GetName(){
return name;
}
public void SetName(string name){
this.name = name;
}
// C#에서는 속성을 제공해줘서 이렇게 사용
public string Name { get; set; }
}
public class CoroutineWithUsing : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Person person = new Person {Name = null};
print(person?.Name); // 널이 아니면 Name을 출력
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Steamworks;
using Mirror;
using UnityEngine.SceneManagement;
using System;
using System.Linq;
public class MyNetworkManager : NetworkManager
{
[Scene] [SerializeField] private string menuScene = string.Empty;
[Header("Room")]
[SerializeField] private NetworkRoomPlayerLobby roomPlayerPrefab = null;
public static event Action OnClientConnected;
public static event Action OnClientDisconnected;
public override void OnServerAddPlayer(NetworkConnection conn)
{
base.OnServerAddPlayer(conn);
CSteamID steamId = SteamMatchmaking.GetLobbyMemberByIndex(SteamLobby.LobbyId, numPlayers - 1);
var playerInfoDisplay = conn.identity.GetComponent<PlayerInfoDisplay>();
playerInfoDisplay.SetSteamId(steamId.m_SteamID);
if (SceneManager.GetActiveScene().name == menuScene)
{
NetworkRoomPlayerLobby roomPlayerInstance = Instantiate(roomPlayerPrefab);
NetworkServer.AddPlayerForConnection(conn, roomPlayerInstance.gameObject);
}
}
public override void OnStartServer() => spawnPrefabs = Resources.LoadAll<GameObject>("SpawnablePrefabs").ToList();
public override void OnStartClient()
{
var spawnPrefabs = Resources.LoadAll<GameObject>("SpawnablePrefabs");
foreach (var prefab in spawnPrefabs)
{
NetworkClient.RegisterPrefab(prefab);
}
}
public override void OnClientConnect(NetworkConnection conn)
{
base.OnClientConnect(conn);
OnClientConnected?.Invoke();
}
public override void OnClientDisconnect(NetworkConnection conn)
{
base.OnClientDisconnect(conn);
OnClientDisconnected?.Invoke();
}
public override void OnServerConnect(NetworkConnection conn)
{
if (numPlayers >= maxConnections)
{
conn.Disconnect();
return;
}
if (SceneManager.GetActiveScene().name != menuScene)
{
conn.Disconnect();
return;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.