content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Furiza.AspNetCore.WebApp.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SESMTTech.Gestor.RazorPages.RestClients.PlanosDeAcao.PlanosDeAcao;
using System;
using System.Threading.Tasks;
namespace SESMTTech.Gestor.RazorPages.Pages.Reunioes.PlanosDeAcao.Itens
{
[Authorize(Policy = FurizaPolicies.RequireEditorRights)]
public class ConcluirModel : PageModel
{
private readonly IPlanosDeAcaoClient planosDeAcaoClient;
[BindProperty]
public Guid ReuniaoId { get; set; }
[BindProperty]
public Guid PlanoDeAcaoId { get; set; }
[BindProperty]
public Guid ItemId { get; set; }
[BindProperty]
public PlanosDeAcaoItensConcluirPost PlanosDeAcaoItensConcluirPost { get; set; }
public ConcluirModel(IPlanosDeAcaoClient planosDeAcaoClient)
{
this.planosDeAcaoClient = planosDeAcaoClient ?? throw new ArgumentNullException(nameof(planosDeAcaoClient));
}
public void OnGet(Guid reuniaoId, Guid planoDeAcaoId, Guid itemId)
{
ReuniaoId = reuniaoId;
PlanoDeAcaoId = planoDeAcaoId;
ItemId = itemId;
}
public async Task<IActionResult> OnPostAsync()
{
await planosDeAcaoClient.ItensConcluirPostAsync(PlanoDeAcaoId, ItemId, PlanosDeAcaoItensConcluirPost);
return new JsonResult(
new
{
returnUrl = Url.Page("/Reunioes/Detalhar", new { id = ReuniaoId })
});
}
}
} | 32.196078 | 120 | 0.665652 | [
"MIT"
] | sesmt-tecnologico/gestor | src/SESMTTech.Gestor.RazorPages/Pages/Reunioes/PlanosDeAcao/Itens/Concluir.cshtml.cs | 1,644 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.RecoveryServices.V20161201.Outputs
{
/// <summary>
/// Container extended information
/// </summary>
[OutputType]
public sealed class GenericContainerExtendedInfoResponse
{
/// <summary>
/// Container identity information
/// </summary>
public readonly Outputs.ContainerIdentityInfoResponse? ContainerIdentityInfo;
/// <summary>
/// Public key of container cert
/// </summary>
public readonly string? RawCertData;
/// <summary>
/// Azure Backup Service Endpoints for the container
/// </summary>
public readonly ImmutableDictionary<string, string>? ServiceEndpoints;
[OutputConstructor]
private GenericContainerExtendedInfoResponse(
Outputs.ContainerIdentityInfoResponse? containerIdentityInfo,
string? rawCertData,
ImmutableDictionary<string, string>? serviceEndpoints)
{
ContainerIdentityInfo = containerIdentityInfo;
RawCertData = rawCertData;
ServiceEndpoints = serviceEndpoints;
}
}
}
| 31.521739 | 85 | 0.664828 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/RecoveryServices/V20161201/Outputs/GenericContainerExtendedInfoResponse.cs | 1,450 | C# |
using UnityEngine;
namespace Unit
{
[RequireComponent(typeof(SphereCollider))]
public class Sensor : MonoBehaviour
{
public float range;
private void Awake()
{
GetComponent<SphereCollider>().isTrigger = true;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player") && other.GetComponent<Unit>().isActiveAndEnabled)
{
GetComponentInParent<Unit>().target = other.transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
GetComponentInParent<Unit>().target = null;
}
}
public void OnPlayerDeath()
{
GetComponentInParent<Unit>().target = null;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, range);
}
private void OnValidate()
{
GetComponent<SphereCollider>().radius = range;
}
}
}
| 23.833333 | 92 | 0.527972 | [
"MIT"
] | qreenify/NeonARPG | Assets/Scripts/Unit/Sensor.cs | 1,146 | C# |
// WARNING
//
// This file has been generated automatically by Visual Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace MenuBarCodeReader
{
[Register ("ScanWindowController")]
partial class ScanWindowController
{
[Outlet]
MenuBarCodeReader.ScanView scanView { get; set; }
void ReleaseDesignerOutlets ()
{
if (scanView != null) {
scanView.Dispose ();
scanView = null;
}
}
}
}
| 21.518519 | 83 | 0.712565 | [
"MIT"
] | msioen/MenuBarCodeReader | MenuBarCodeReader/ScanWindowController.designer.cs | 581 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Iot.Device.Ssd13xx.Commands;
using Iot.Device.Ssd13xx.Commands.Ssd1306Commands;
using Xunit;
namespace Iot.Device.Ssd13xx.Tests
{
public class NoOperationTests
{
[Fact]
public void Get_Bytes()
{
NoOperation noOperation = new NoOperation();
byte[] actualBytes = noOperation.GetBytes();
Assert.Equal(new byte[] { 0xE3 }, actualBytes);
}
}
}
| 27.809524 | 72 | 0.635274 | [
"MIT"
] | gukoff/nanoFramework.IoT.Device | src/devices_generated/Ssd13xx/tests/Commands/NoOperationTests.cs | 584 | C# |
using System;
using System.Runtime.Serialization;
using WebArticleLibrary.Model;
namespace WebArticleLibrary.Models
{
[DataContract]
public class CommentStatusUpdate
{
[DataMember(Name = "id")]
public Int32 CommentId { get; set; }
[DataMember(Name = "status")]
public CommentStatus Status { get; set; }
}
}
| 19.470588 | 43 | 0.712991 | [
"MIT"
] | Jahn08/WEB-ARTICLE-CORE | WebArticleLibrary/Models/CommentStatusUpdate.cs | 331 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Response
{
/// <summary>
/// ZhimaCreditScoreBriefGetResponse.
/// </summary>
public class ZhimaCreditScoreBriefGetResponse : AopResponse
{
/// <summary>
/// 芝麻信用对于每一次请求返回的业务号。后续可以通过此业务号进行对账
/// </summary>
[XmlElement("biz_no")]
public string BizNo { get; set; }
/// <summary>
/// 准入判断结果 Y(用户的芝麻分大于等于准入分数),N(用户的芝麻分小于准入分数),N/A(无法评估,例如用户未开通芝麻信用,或芝麻采集的信息不足以评估该用户的信用)
/// </summary>
[XmlElement("is_admittance")]
public string IsAdmittance { get; set; }
}
}
| 26.291667 | 95 | 0.614897 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Response/ZhimaCreditScoreBriefGetResponse.cs | 841 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace XfHappySad
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new XfHappySad.MainPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| 19.171429 | 50 | 0.52161 | [
"MIT"
] | bennoffsinger/xfhappysad | XfHappySad/XfHappySad/XfHappySad/App.xaml.cs | 673 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Cats.Areas.Procurement.Models;
using Cats.Helpers;
using Cats.Models.Constant;
using Cats.Models.Hubs;
using Cats.Models.ViewModels.Bid;
using Cats.Services.EarlyWarning;
using Cats.Services.Procurement;
using Cats.Services.Common;
using System;
using Cats.Models;
using Cats.Services.Security;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Cats.Helpers;
namespace Cats.Areas.Procurement.Controllers
{
public class BidController : Controller
{
// GET: /Procurement/Bid/
private readonly IBidService _bidService;
private readonly IBidDetailService _bidDetailService;
private readonly IAdminUnitService _adminUnitService;
private readonly IStatusService _statusService;
private readonly ITransportBidPlanService _transportBidPlanService;
private readonly ITransportBidPlanDetailService _transportBidPlanDetailService;
private readonly IApplicationSettingService _applicationSettingService;
private readonly IUserAccountService _userAccountService;
private readonly ITransportBidQuotationService _transportBidQuotationService;
private readonly IBidWinnerService _bidWinnerService;
private readonly ITransporterService _transporterService;
private readonly IHubService _hubService;
private readonly IWorkflowStatusService _workflowStatusService;
public BidController(IBidService bidService, IBidDetailService bidDetailService,
IAdminUnitService adminUnitService,
IStatusService statusService,
ITransportBidPlanService transportBidPlanService,
ITransportBidPlanDetailService transportBidPlanDetailService,
IApplicationSettingService applicationSettingService,IUserAccountService userAccountService,
ITransportBidQuotationService transportBidQuotationService, IBidWinnerService bidWinnerService,
ITransporterService transporterService, IHubService hubService,IWorkflowStatusService workflowStatusService)
{
_bidService = bidService;
_bidDetailService = bidDetailService;
_adminUnitService = adminUnitService;
_statusService = statusService;
_transportBidPlanService = transportBidPlanService;
_transportBidPlanDetailService = transportBidPlanDetailService;
_applicationSettingService = applicationSettingService;
_userAccountService = userAccountService;
_transportBidQuotationService = transportBidQuotationService;
_bidWinnerService = bidWinnerService;
_transporterService = transporterService;
_hubService = hubService;
_workflowStatusService = workflowStatusService;
}
public ActionResult Index(int id=0)
{
ViewBag.BidStatus = id;
ViewBag.BidTitle = id == 0
? "Open"
: _workflowStatusService.GetStatusName(WORKFLOW.BID, id);
return View();
}
[HttpGet]
public ActionResult WoredasBidStatus()
{
var filter = new PriceQuotationFilterViewModel();
ViewBag.filter = filter;
ViewBag.BidID = new SelectList(_bidService.GetAllBid(), "BidID", "BidNumber");
ViewBag.RegionID = new SelectList(_adminUnitService.FindBy(t => t.AdminUnitTypeID == 2), "AdminUnitID", "Name");
ViewBag.HubID = new SelectList(_hubService.GetAllHub(), "HubID", "Name", "Select Hub");
return View("WoredaWithOutBidOfferFilterParial", filter);
}
[HttpPost]
public ActionResult WoredasBidStatus(PriceQuotationFilterOfferlessViewModel filter)
{
ViewBag.WoredaFirstBidWinners = ReadWoredasWithBidWinners(filter.BidID, filter.RegionID, 1, filter.HubID);
ViewBag.WoredaSecondBidWinners = ReadWoredasWithBidWinners(filter.BidID, filter.RegionID, 2, filter.HubID);
ViewBag.filter = filter;
ViewBag.BidID = new SelectList(_bidService.GetAllBid(), "BidID", "BidNumber");
ViewBag.RegionID = new SelectList(_adminUnitService.FindBy(t => t.AdminUnitTypeID == 2), "AdminUnitID", "Name");
ViewBag.HubID = new SelectList(_hubService.GetAllHub(), "HubID", "Name", "Select Hub");
return View("WoredasWithOutBidOffer",filter);
}
public ActionResult MergeBidWinners(WoredaBidWinnerViewModel woredaBidWinnerViewModel)
{
var bidWinnerObj =_bidWinnerService.Get(t => t.SourceID == woredaBidWinnerViewModel.SourceId && t.DestinationID == woredaBidWinnerViewModel.DestinationId &&
t.BidID == woredaBidWinnerViewModel.BidID && t.TransporterID == woredaBidWinnerViewModel.LeavingTransporterID &&
t.Position == 1 && t.Status == 1).FirstOrDefault();
if (bidWinnerObj !=null)
{
bidWinnerObj.Status = (int)BIDWINNER.Left;
_bidWinnerService.EditBidWinner(bidWinnerObj);
}
var regionObj = _adminUnitService.FindById(woredaBidWinnerViewModel.DestinationId).AdminUnit2.AdminUnit2;
//var filter = new PriceQuotationFilterOfferlessViewModel()
// {
// BidID = woredaBidWinnerViewModel.BidID,
// HubID = woredaBidWinnerViewModel.SourceId,
// RegionID = regionObj.AdminUnitID
// };
return RedirectToAction("WoredasBidStatus");
}
public ActionResult LoadBidWinnerLeave(WoredaBidWinnerViewModel woredaBidWinnerViewModel)
{
if (woredaBidWinnerViewModel == null || woredaBidWinnerViewModel.SourceId <= 0 ||
woredaBidWinnerViewModel.DestinationId <= 0 || woredaBidWinnerViewModel.BidID <= 0)
{
return Json(new SelectList(Enumerable.Empty<SelectListItem>()), JsonRequestBehavior.AllowGet);
}
woredaBidWinnerViewModel.Woreda =
_adminUnitService.FindById(woredaBidWinnerViewModel.DestinationId).Name;
woredaBidWinnerViewModel.SourceWarehouse = _hubService.FindById(woredaBidWinnerViewModel.SourceId).Name;
woredaBidWinnerViewModel.BidNumber = _bidService.FindById(woredaBidWinnerViewModel.BidID).BidNumber;
var bidWinners =
_bidWinnerService.Get(
t =>
t.SourceID == woredaBidWinnerViewModel.SourceId &&
t.DestinationID == woredaBidWinnerViewModel.DestinationId &&
t.BidID == woredaBidWinnerViewModel.BidID && t.Position == 1 && t.Status == 1).Select(
t => t.Transporter).ToList();
var transporters =
bidWinners.Select(i => new SelectListItemModel {Name = i.Name, Id = i.TransporterID.ToString()}).
ToList();
//transporters.Add(new SelectListItemModel { Name = "N/A", Id = "0" }); //TODO just a hack for now for unknown stacks
woredaBidWinnerViewModel.Transporters = new SelectList(transporters, "Id", "Name");
return Json(woredaBidWinnerViewModel, JsonRequestBehavior.AllowGet);
}
public ActionResult CancelBidWinners(WoredaCancelBidWinnerViewModel woredaCancelBidWinnerViewModel)
{
var canceledBidWinnerObj = _bidWinnerService.Get(t => t.SourceID == woredaCancelBidWinnerViewModel.SourceId && t.DestinationID == woredaCancelBidWinnerViewModel.DestinationId &&
t.BidID == woredaCancelBidWinnerViewModel.BidID && t.Position == 1 && t.Status == 1);
if (canceledBidWinnerObj != null)
{
foreach (var bidWinner in canceledBidWinnerObj)
{
bidWinner.Status = (int)BIDWINNER.Failed;
_bidWinnerService.EditBidWinner(bidWinner);
}
}
var promotedBidWinnerObj = _bidWinnerService.Get(t => t.SourceID == woredaCancelBidWinnerViewModel.SourceId && t.DestinationID == woredaCancelBidWinnerViewModel.DestinationId &&
t.BidID == woredaCancelBidWinnerViewModel.BidID && t.Position == 2 && t.Status == 1);
if (promotedBidWinnerObj != null)
{
foreach (var bidWinner in promotedBidWinnerObj)
{
bidWinner.Position = 1;
bidWinner.Status = (int)BIDWINNER.Awarded;
_bidWinnerService.EditBidWinner(bidWinner);
}
}
return RedirectToAction("WoredasBidStatus");
}
public ActionResult LoadBidWinnerCancel(WoredaCancelBidWinnerViewModel woredaCancelBidWinnerViewModel)
{
if (woredaCancelBidWinnerViewModel == null || woredaCancelBidWinnerViewModel.SourceId <= 0 ||
woredaCancelBidWinnerViewModel.DestinationId <= 0 || woredaCancelBidWinnerViewModel.BidID <= 0)
{
return Json(new EmptyResult(), JsonRequestBehavior.AllowGet);
}
woredaCancelBidWinnerViewModel.Woreda = _adminUnitService.FindById(woredaCancelBidWinnerViewModel.DestinationId).Name;
woredaCancelBidWinnerViewModel.SourceWarehouse = _hubService.FindById(woredaCancelBidWinnerViewModel.SourceId).Name;
woredaCancelBidWinnerViewModel.BidNumber = _bidService.FindById(woredaCancelBidWinnerViewModel.BidID).BidNumber;
var bidFirstWinners =
_bidWinnerService.Get(
t =>
t.SourceID == woredaCancelBidWinnerViewModel.SourceId &&
t.DestinationID == woredaCancelBidWinnerViewModel.DestinationId &&
t.BidID == woredaCancelBidWinnerViewModel.BidID && t.Position == 1 && t.Status == 1).Select(
t => t.Transporter).ToList();
var bidSecondWinners =
_bidWinnerService.Get(
t =>
t.SourceID == woredaCancelBidWinnerViewModel.SourceId &&
t.DestinationID == woredaCancelBidWinnerViewModel.DestinationId &&
t.BidID == woredaCancelBidWinnerViewModel.BidID && t.Position == 2 && t.Status == 1).Select(
t => t.Transporter).ToList();
woredaCancelBidWinnerViewModel.CanceledTransporters = bidFirstWinners.Select(t => t.Name).ToList();
woredaCancelBidWinnerViewModel.PromotedTransporters = bidSecondWinners.Select(t => t.Name).ToList();
return Json(woredaCancelBidWinnerViewModel, JsonRequestBehavior.AllowGet);
}
public ActionResult ReadWoredasWithOutBidOffer([DataSourceRequest] DataSourceRequest request, int bidID, int regionID)
{
var planID = _bidService.FindById(bidID).TransportBidPlanID;
var bidPlanDetail =
_transportBidPlanDetailService.FindBy(t => t.Destination.AdminUnit2.AdminUnit2.AdminUnitID == regionID
&& t.BidPlanID == planID);
var df = (from planDetail in bidPlanDetail
group planDetail by new
{
planDetail.DestinationID,
planDetail.SourceID
}
into gr
select gr
);
var detailPlans = df.Select(d => d.ToList()).Select(er => er.FirstOrDefault()).ToList();
var result = new List<PriceQuotationDetail>();
foreach (var transportBidPlanDetail in detailPlans)
{
var pdetail = transportBidPlanDetail;
var detail = _transportBidQuotationService.FindBy(t => t.BidID == bidID
&& t.SourceID == pdetail.SourceID
&& t.DestinationID == pdetail.DestinationID).FirstOrDefault();
if(detail==null)
{
var n = new PriceQuotationDetail()
{
SourceWarehouse = pdetail.Source.Name,
Zone = pdetail.Destination.AdminUnit2.Name,
Woreda = pdetail.Destination.Name,
Tariff = 0,
Remark = String.Empty,
BidID = bidID,
DestinationID = pdetail.DestinationID,
SourceID = pdetail.SourceID
};
result.Add(n);
}
}
return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult NoOfferWoredas(int bidID)
{
var planID = _bidService.FindById(bidID).TransportBidPlanID;
var bidPlanDetail =
_transportBidPlanDetailService.FindBy(t => t.BidPlanID == planID);
var df = (from planDetail in bidPlanDetail
group planDetail by new
{
planDetail.DestinationID,
planDetail.SourceID
}
into gr
select gr
);
var detailPlans = df.Select(d => d.ToList()).Select(er => er.FirstOrDefault()).ToList();
var result = new List<NoOfferWoreda>();
foreach (var transportBidPlanDetail in detailPlans)
{
var pdetail = transportBidPlanDetail;
var detail = _transportBidQuotationService.FindBy(t => t.BidID == bidID
&& t.SourceID == pdetail.SourceID
&& t.DestinationID == pdetail.DestinationID).FirstOrDefault();
if (detail == null)
{
var n = new NoOfferWoreda()
{
SourceWarehouse = pdetail.Source.Name,
Zone = pdetail.Destination.AdminUnit2.Name,
Woreda = pdetail.Destination.Name,
Region = pdetail.Destination.AdminUnit2.AdminUnit2.Name
};
result.Add(n);
}
}
var re = (from planDetail in result
group planDetail by planDetail.Region
into gr select new
{
gr.Key,
Count = gr.Count()
}
);
return Json(re, JsonRequestBehavior.AllowGet);
}
public List<BidWinnerViewingModel> ReadWoredasWithBidWinners(int bidID, int regionID, int rank, int hubID = 0)
{
List<BidWinner> bidWinners;
if(hubID == 0)
{
bidWinners = _bidWinnerService.Get(t => t.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == regionID && t.BidID == bidID
&& t.Position == rank && t.Status == 1, null, "Transporter,AdminUnit, AdminUnit.AdminUnit2").ToList();
}
else
{
bidWinners = _bidWinnerService.Get(t => t.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == regionID && t.BidID == bidID
&& t.Position == rank && t.Status == 1 && t.SourceID == hubID, null, "Transporter,AdminUnit, AdminUnit.AdminUnit2").ToList();
}
//var enumerable = bidWinners as List<BidWinner> ?? bidWinners.ToList();
var bw = (from bidWinner in bidWinners
group bidWinner by new
{
Woreda = bidWinner.AdminUnit.Name,
Zone = bidWinner.AdminUnit.AdminUnit2.Name,
bidWinner.DestinationID,
Hub = bidWinner.Hub.Name,
bidWinner.SourceID,
bidWinner.Tariff,
bidWinner.BidID,
bidWinner.Position
}
into gr
select new
{
DestinationID = gr.Key.DestinationID,
Zone = gr.Key.Zone,
Woreda = gr.Key.Woreda,
SourceID = gr.Key.SourceID,
Hub = gr.Key.Hub,
Tariff = gr.Key.Tariff,
BidID = gr.Key.BidID,
Position = gr.Key.Position,
TransporterIDs = gr.Select(t => t.TransporterID).ToList(),
}
);
var bidWinnersList = bw.ToList();
var result = new List<BidWinnerViewingModel>();
foreach (var bidWinner in bidWinnersList)
{
var n = new BidWinnerViewingModel();
n.SourceWarehouse = bidWinner.Hub.ToString();
n.SourceId = bidWinner.SourceID.ToString();
n.Zone = bidWinner.Zone.ToString();
n.Woreda = bidWinner.Woreda.ToString();
n.DestinationId = bidWinner.DestinationID.ToString();
n.WinnerTariff = bidWinner.Tariff.ToString();
n.Rank = bidWinner.Position.ToString();
n.BidID = bidWinner.BidID.ToString();
foreach (var transporter in bidWinner.TransporterIDs)
{
n.TransporterID.Add(transporter.ToString());
n.TransporterName.Add(_transporterService.FindById(transporter).Name);
}
result.Add(n);
}
return result;
}
public ActionResult Bid_Read([DataSourceRequest] DataSourceRequest request,int id=0)
{
var bids = id==0?_bidService.Get(m => m.StatusID == (int)BidStatus.Open).OrderByDescending(m => m.BidID).ToList():_bidService.Get(m=>m.StatusID==id).ToList();
var bidsToDisplay = GetBids(bids).ToList();
return Json(bidsToDisplay.ToDataSourceResult(request));
}
public ActionResult BidDetail_Read(int bidID,[DataSourceRequest] DataSourceRequest request)
{
var bidDetails = _bidDetailService.GetAllBidDetail();
var bidsToDisplay = GetBidDetails(bidDetails).ToList();
return Json(bidsToDisplay.Where(p => p.BidID == bidID).ToDataSourceResult(request));
}
private IEnumerable<BidViewModel> GetBids(IEnumerable<Bid> bids)
{
var datePref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference;
return (from bid in bids
select new BidViewModel()
{
BidID = bid.BidID,
BidNumber = bid.BidNumber,
BidBondAmount = bid.BidBondAmount,
StartDate = bid.StartDate,
EndDate = bid.EndDate,
OpeningDate = bid.OpeningDate,
Status = _workflowStatusService.GetStatusName(WORKFLOW.BID, bid.StatusID),
StatusID = bid.StatusID,
StartDatePref = bid.StartDate.ToCTSPreferedDateFormat(datePref),
OpeningDatePref = bid.OpeningDate.ToCTSPreferedDateFormat(datePref),
EndDatePref = bid.EndDate.ToCTSPreferedDateFormat(datePref)
});
}
private IEnumerable<BidDetailViewModel> GetBidDetails(IEnumerable<BidDetail> bidDetails)
{
return (from bidDetail in bidDetails
select new BidDetailViewModel()
{
BidDetailID =bidDetail.BidDetailID,
BidID = bidDetail.BidID,
Region= bidDetail.Bid.AdminUnit.Name,
RegionID=bidDetail.Bid.AdminUnit.AdminUnitID,
AmountForReliefProgram = bidDetail.AmountForReliefProgram,
AmountForPSNPProgram = bidDetail.AmountForPSNPProgram,
BidDocumentPrice = bidDetail.BidDocumentPrice,
CPO = bidDetail.CPO
});
}
//update bid detail information
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BidDetail_Update([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<BidDetail> bidDetails)
{
if (bidDetails != null && ModelState.IsValid)
{
foreach (var details in bidDetails)
{
_bidDetailService.EditBidDetail(details);
}
}
return Json(ModelState.ToDataSourceResult());
}
public ActionResult Create(int id = 0)
{
ViewBag.RegionID = new SelectList(_adminUnitService.GetRegions(), "AdminUnitID", "Name");
var datePref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference;
var bid = new CreateBidViewModel();
bid.StartDate = DateTime.Now;
bid.EndDate = DateTime.Now.AddDays(10);
bid.OpeningDate = DateTime.Now.AddDays(11);
var regions = _adminUnitService.FindBy(t => t.AdminUnitTypeID == 2);
ViewBag.StatusID = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name", bid.StatusID = 1);
bid.BidNumber = _bidService.AutogenerateBidNo();
ViewBag.BidPlanID = id;
ViewBag.TransportBidPlanID = new SelectList(_transportBidPlanService.GetAllTransportBidPlan(), "TransportBidPlanID", "ShortName", id);
return View(bid);
}
//[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(CreateBidViewModel bidViewModel)
{
var bid = GetBid(bidViewModel);
if (!IsBidMadeForThisRegion(bid.RegionID, bid.TransportBidPlanID))
{
ModelState.AddModelError("Errors",@"This Region is already registered with this Bid Plan. Please choose another Region or Plan!");
ViewBag.StatusID = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name");
ViewBag.BidPlanID = bid.TransportBidPlanID;
ViewBag.TransportBidPlanID = new SelectList(_transportBidPlanService.GetAllTransportBidPlan(), "TransportBidPlanID", "ShortName", bid.TransportBidPlanID);
ViewBag.RegionID = new SelectList(_adminUnitService.GetRegions(), "AdminUnitID", "Name");
return View(bidViewModel);
}
if (ModelState.IsValid)
{
//var regions = _adminUnitService.FindBy(t => t.AdminUnitTypeID == 2);
var regions = _adminUnitService.FindBy(t => t.AdminUnitID == bid.RegionID);
bid.StatusID = (int)BidStatus.Open;
var bidDetails = (from detail in regions
select new BidDetail()
{
AmountForReliefProgram = (decimal)_transportBidPlanDetailService.GetRegionPlanTotal(bid.TransportBidPlanID, detail.AdminUnitID, 1),
AmountForPSNPProgram = (decimal)_transportBidPlanDetailService.GetRegionPlanTotal(bid.TransportBidPlanID, detail.AdminUnitID, 2),
BidDocumentPrice = 0,
CPO = 0
//RegionID = bid.RegionID
}).ToList();
bid.BidDetails = bidDetails;
bid.RegionID = bid.RegionID;
var user = (UserIdentity)System.Web.HttpContext.Current.User.Identity;
bid.UserProfileId = user.Profile.UserProfileID;
_bidService.AddBid(bid);
return RedirectToAction("Index");
}
ViewBag.StatusID = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name");
ViewBag.BidPlanID = bid.TransportBidPlanID;
ViewBag.TransportBidPlanID = new SelectList(_transportBidPlanService.GetAllTransportBidPlan(), "TransportBidPlanID", "ShortName", bid.TransportBidPlanID);
ViewBag.RegionID = new SelectList(_adminUnitService.GetRegions(), "AdminUnitID", "Name");
return View(bidViewModel);
//return View("Index", _bidService.GetAllBid());
}
private Bid GetBid(CreateBidViewModel bidViewModel)
{
var bid = new Bid()
{
RegionID = bidViewModel.RegionID,
StartDate = bidViewModel.StartDate,
startTime = bidViewModel.StartTime,
EndDate = bidViewModel.EndDate,
endTime = bidViewModel.EndTime,
BidNumber = bidViewModel.BidNumber,
BidBondAmount = bidViewModel.BidBondAmount,
OpeningDate = bidViewModel.OpeningDate,
BidOpeningTime = bidViewModel.BidOpningTime,
StatusID = bidViewModel.StatusID,
TransportBidPlanID = bidViewModel.TransportBidPlanID
};
return bid;
}
private Boolean IsBidMadeForThisRegion(int regionId,int bidPlanId)
{
var bidForThisRegion = _bidService.FindBy(b => b.RegionID == regionId && b.TransportBidPlanID == bidPlanId).ToList();
if (bidForThisRegion.Count > 0)
{
return false;
}
return true;
}
public ActionResult Edit(int id)
{
var bid = _bidService.Get(m => m.BidID == id, null, "BidDetails").FirstOrDefault();
ViewBag.BidNumber = bid.BidNumber;
ViewBag.StartDate = bid.StartDate;
ViewBag.EndDate = bid.EndDate;
ViewBag.OpeningDate = bid.OpeningDate;
var bidDetails = bid.BidDetails;
var input = (from detail in bidDetails
select new BidDetailsViewModel
{
BidDetailID = detail.BidDetailID,
BidID = detail.BidID,
Region = detail.Bid.AdminUnit.Name,
Edit = new BidDetailsViewModel.BidDetailEdit()
{
Number = detail.BidDetailID,
AmountForReliefProgram = detail.AmountForReliefProgram,
AmountForPSNPProgram = detail.AmountForPSNPProgram,
BidDocumentPrice = detail.BidDocumentPrice,
CPO = detail.CPO,
AmountForReliefProgramPlanned = (decimal)_transportBidPlanDetailService.GetRegionPlanTotal(bid.TransportBidPlanID, detail.Bid.AdminUnit.AdminUnitID, 1),
AmountForPSNPProgramPlanned = (decimal)_transportBidPlanDetailService.GetRegionPlanTotal(bid.TransportBidPlanID, detail.Bid.AdminUnit.AdminUnitID, 2)
}
}
);
ViewData["BidDetail"] = input;
return View(input);
}
[HttpPost]
public ActionResult Edit(List<BidDetailsViewModel.BidDetailEdit> input)
{
var bidId = 0;
foreach (var bidDetailEdit in input)
{
var bidDetail = _bidDetailService.FindById(bidDetailEdit.Number);
bidId = bidDetail.BidID;
bidDetail.AmountForReliefProgram = bidDetailEdit.AmountForReliefProgram;
bidDetail.AmountForPSNPProgram = bidDetailEdit.AmountForPSNPProgram;
bidDetail.BidDocumentPrice = bidDetailEdit.BidDocumentPrice;
bidDetail.CPO = bidDetailEdit.CPO;
}
_bidDetailService.Save();
return RedirectToAction("Edit", "Bid", new { id = bidId });
}
public ViewResult Details(int id = 0)
{
Bid bid = _bidService.Get(t => t.BidID == id, null, "BidDetails").FirstOrDefault();
ViewBag.BidStatus = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name", bid.StatusID);
ViewData["BidDetails"] = bid;
return View(bid);
}
public ActionResult EditBidStatus(int id)
{
Bid bid = _bidService.Get(t => t.BidID == id, null, "BidDetails").FirstOrDefault();
ViewBag.StatusID = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name", bid.StatusID);
ViewBag.TransportBidPlanID = new SelectList(_transportBidPlanService.GetAllTransportBidPlan(),
"TransportBidPlanID", "ShortName", bid.TransportBidPlanID);
ViewBag.RegionID = new SelectList(_adminUnitService.GetRegions(), "AdminUnitID", "Name",bid.RegionID);
return View(bid);
}
[HttpPost]
public ActionResult EditBidStatus(Bid bid)
{
if (ModelState.IsValid)
{
_bidService.EditBid(bid);
return RedirectToAction("Index");
}
ViewBag.StatusID = new SelectList(_statusService.GetAllStatus(), "StatusID", "Name", bid.StatusID);
ViewBag.TransportBidPlanID = new SelectList(_transportBidPlanService.GetAllTransportBidPlan(),
"TransportBidPlanID", "ShortName", bid.TransportBidPlanID);
ViewBag.RegionID = new SelectList(_adminUnitService.GetRegions(), "AdminUnitID", "Name");
// return View("Index", _bidService.GetAllBid());
return View(bid);
}
public ActionResult MakeActive(int id)
{
_bidService.ActivateBid(id);
// _applicationSettingService.SetValue("CurrentBid", ""+id);
return RedirectToAction("Index","bid",new {id=(int)BidStatus.Active});
}
public ActionResult ApproveBid(int id)
{
var bid = _bidService.FindById(id);
bid.StatusID = (int)BidStatus.Approved;
_bidService.EditBid(bid);
return RedirectToAction("Index", "bid", new { id = (int)BidStatus.Approved });
}
public ActionResult CloseBid(int id)
{
var bid = _bidService.FindById(id);
bid.StatusID = (int) BidStatus.Closed;
_bidService.EditBid(bid);
return RedirectToAction("Index", "Bid", new {id = (int) BidStatus.Closed});
}
}
}
| 50.130094 | 193 | 0.562205 | [
"Apache-2.0"
] | IYoni/cats | Web/App_Start/Areas/Procurement/Controllers/BidController.cs | 31,985 | C# |
using System;
using MSK.Core.Module.Domain;
namespace MSK.Samples.BiMonetary.Module.Social.Models
{
public class UserId : IdentityBase
{
private UserId()
{
}
public UserId(Guid authorId) : base(authorId)
{
}
}
}
| 16.176471 | 53 | 0.581818 | [
"MIT"
] | thangchung/modular-starter-kit | samples/bimonetary/MSK.Samples.BiMonetary.Module.Social/Models/UserId.cs | 277 | C# |
using System.Threading;
using System.Threading.Tasks;
namespace Synchronizzer.Implementation
{
internal interface IDestinationWriter : IObjectSource, IObjectWriter
{
string Address { get; }
Task TryLock(CancellationToken cancellationToken);
Task Unlock();
}
}
| 20 | 72 | 0.71 | [
"BSD-2-Clause"
] | drivenet/gridfs-sync-service | Synchronizzer/Implementation/IDestinationWriter.cs | 302 | C# |
using Celeste.Mod.Core;
using Ionic.Zip;
using MonoMod.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Celeste.Mod {
public static partial class Everest {
public static class Loader {
/// <summary>
/// The path to the Everest /Mods directory.
/// </summary>
public static string PathMods { get; internal set; }
/// <summary>
/// The path to the Everest /Mods/Cache directory.
/// </summary>
public static string PathCache { get; internal set; }
/// <summary>
/// The path to the Everest /Mods/blacklist.txt file.
/// </summary>
public static string PathBlacklist { get; internal set; }
internal static List<string> _Blacklist = new List<string>();
/// <summary>
/// The currently loaded mod blacklist.
/// </summary>
public static ReadOnlyCollection<string> Blacklist => _Blacklist?.AsReadOnly();
/// <summary>
/// The path to the Everest /Mods/whitelist.txt file.
/// </summary>
public static string PathWhitelist { get; internal set; }
internal static string NameWhitelist;
internal static List<string> _Whitelist;
/// <summary>
/// The currently loaded mod whitelist.
/// </summary>
public static ReadOnlyCollection<string> Whitelist => _Whitelist?.AsReadOnly();
internal static List<Tuple<EverestModuleMetadata, Action>> Delayed = new List<Tuple<EverestModuleMetadata, Action>>();
internal static int DelayedLock;
private static bool enforceOptionalDependencies;
internal static HashSet<string> FilesWithMetadataLoadFailures = new HashSet<string>();
internal static readonly Version _VersionInvalid = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);
internal static readonly Version _VersionMax = new Version(int.MaxValue, int.MaxValue);
/// <summary>
/// The path to the Everest /Mods/modoptionsorder.txt file.
/// </summary>
public static string PathModOptionsOrder { get; internal set; }
internal static List<string> _ModOptionsOrder = new List<string>();
/// <summary>
/// The currently loaded mod mod options order.
/// </summary>
public static ReadOnlyCollection<string> ModOptionsOrder => _ModOptionsOrder?.AsReadOnly();
/// <summary>
/// The path to the Everest /Mods/updaterblacklist.txt file.
/// </summary>
public static string PathUpdaterBlacklist { get; internal set; }
internal static List<string> _UpdaterBlacklist = new List<string>();
/// <summary>
/// The currently loaded mod updater blacklist.
/// </summary>
public static ReadOnlyCollection<string> UpdaterBlacklist => _UpdaterBlacklist?.AsReadOnly();
/// <summary>
/// All mods on this list with a version lower than the specified version will never load.
/// </summary>
internal static Dictionary<string, Version> PermanentBlacklist = new Dictionary<string, Version>() {
// Note: Most, if not all mods use Major.Minor.Build
// Revision is thus set to -1 and < 0
// Entries with a revision of 0 are there because there is no update / fix for those mods.
// Versions of the mods older than on this list no longer work with Celeste 1.3.0.0
{ "SpeedrunTool", new Version(1, 5, 7) },
{ "CrystalValley", new Version(1, 1, 3) },
{ "IsaGrabBag", new Version(1, 3, 2) },
{ "testroom", new Version(1, 0, 1, 0) },
{ "Elemental Chaos", new Version(1, 0, 0, 0) },
{ "BGswitch", new Version(0, 1, 0, 0) },
// Infinite Saves 1.0.0 does not work well with the "extra save slots" feature of Everest
{ "InfiniteSaves", new Version(1, 0, 1) }
};
/// <summary>
/// When both mods in the same row with versions lower than in the row are present, yell at the user.
/// </summary>
internal static HashSet<Tuple<string, Version, string, Version>> PermanentConflictlist = new HashSet<Tuple<string, Version, string, Version>>() {
// See above versioning note.
// I'm sorry. -ade
Tuple.Create("Nameguy's D-Sides", _VersionMax, "Monika's D-Sides", _VersionMax),
};
internal static FileSystemWatcher Watcher;
internal static event Action<string, EverestModuleMetadata> OnCrawlMod;
public static bool AutoLoadNewMods { get; internal set; }
internal static void LoadAuto() {
Directory.CreateDirectory(PathMods = Path.Combine(PathEverest, "Mods"));
Directory.CreateDirectory(PathCache = Path.Combine(PathMods, "Cache"));
PathBlacklist = Path.Combine(PathMods, "blacklist.txt");
if (File.Exists(PathBlacklist)) {
_Blacklist = File.ReadAllLines(PathBlacklist).Select(l => (l.StartsWith("#") ? "" : l).Trim()).ToList();
} else {
using (StreamWriter writer = File.CreateText(PathBlacklist)) {
writer.WriteLine("# This is the blacklist. Lines starting with # are ignored.");
writer.WriteLine("ExampleFolder");
writer.WriteLine("SomeMod.zip");
}
}
if (!string.IsNullOrEmpty(NameWhitelist)) {
PathWhitelist = Path.Combine(PathMods, NameWhitelist);
if (File.Exists(PathWhitelist)) {
_Whitelist = File.ReadAllLines(PathWhitelist).Select(l => (l.StartsWith("#") ? "" : l).Trim()).ToList();
}
}
PathModOptionsOrder = Path.Combine(PathMods, "modoptionsorder.txt");
if (File.Exists(PathModOptionsOrder)) {
_ModOptionsOrder = File.ReadAllLines(PathModOptionsOrder).Select(l => (l.StartsWith("#") ? "" : l).Trim()).ToList();
} else {
using (StreamWriter writer = File.CreateText(PathModOptionsOrder)) {
writer.WriteLine("# This is the Mod Options order file. Lines starting with # are ignored.");
writer.WriteLine("# Mod folders and archives in this file will be displayed in the same order in the Mod Options menu.");
writer.WriteLine("# To define the position of the \"Everest Core\" options, put \"Everest\" on a line.");
writer.WriteLine("ExampleFolder");
writer.WriteLine("SomeMod.zip");
}
}
PathUpdaterBlacklist = Path.Combine(PathMods, "updaterblacklist.txt");
if (File.Exists(PathUpdaterBlacklist)) {
_UpdaterBlacklist = File.ReadAllLines(PathUpdaterBlacklist).Select(l => (l.StartsWith("#") ? "" : l).Trim()).ToList();
} else {
using (StreamWriter writer = File.CreateText(PathUpdaterBlacklist)) {
writer.WriteLine("# This is the Updater Blacklist. Lines starting with # are ignored.");
writer.WriteLine("# If you put the name of a mod zip in this file, it won't be auto-updated and it won't show update notifications on the title screen.");
writer.WriteLine("SomeMod.zip");
}
}
Stopwatch watch = Stopwatch.StartNew();
enforceOptionalDependencies = true;
string[] files = Directory.GetFiles(PathMods);
for (int i = 0; i < files.Length; i++) {
string file = Path.GetFileName(files[i]);
if (!file.EndsWith(".zip") || _Blacklist.Contains(file))
continue;
if (_Whitelist != null && !_Whitelist.Contains(file))
continue;
LoadZip(Path.Combine(PathMods, file));
}
files = Directory.GetDirectories(PathMods);
for (int i = 0; i < files.Length; i++) {
string file = Path.GetFileName(files[i]);
if (file == "Cache" || _Blacklist.Contains(file))
continue;
if (_Whitelist != null && !_Whitelist.Contains(file))
continue;
LoadDir(Path.Combine(PathMods, file));
}
enforceOptionalDependencies = false;
Logger.Log(LogLevel.Info, "loader", "Loading mods with unsatisfied optional dependencies (if any)");
Everest.CheckDependenciesOfDelayedMods();
watch.Stop();
Logger.Log(LogLevel.Verbose, "loader", $"ALL MODS LOADED IN {watch.ElapsedMilliseconds}ms");
try {
Watcher = new FileSystemWatcher {
Path = PathMods,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
};
Watcher.Created += LoadAutoUpdated;
Watcher.EnableRaisingEvents = true;
AutoLoadNewMods = true;
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed watching folder: {PathMods}");
e.LogDetailed();
Watcher?.Dispose();
Watcher = null;
}
}
private static void LoadAutoUpdated(object source, FileSystemEventArgs e) {
if (!AutoLoadNewMods)
return;
Logger.Log(LogLevel.Info, "loader", $"Possible new mod container: {e.FullPath}");
QueuedTaskHelper.Do("LoadAutoUpdated:" + e.FullPath, () => AssetReloadHelper.Do($"{Dialog.Clean("ASSETRELOADHELPER_LOADINGNEWMOD")} {Path.GetFileName(e.FullPath)}", () => MainThreadHelper.Do(() => {
if (Directory.Exists(e.FullPath))
LoadDir(e.FullPath);
else if (e.FullPath.EndsWith(".zip"))
LoadZip(e.FullPath);
((patch_OuiMainMenu) (AssetReloadHelper.ReturnToScene as Overworld)?.GetUI<OuiMainMenu>())?.RebuildMainAndTitle();
})));
}
/// <summary>
/// Load a mod from a .zip archive at runtime.
/// </summary>
/// <param name="archive">The path to the mod .zip archive.</param>
public static void LoadZip(string archive) {
if (!Flags.SupportRuntimeMods) {
Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
return;
}
if (!File.Exists(archive)) // Relative path? Let's just make it absolute.
archive = Path.Combine(PathMods, archive);
if (!File.Exists(archive)) // It just doesn't exist.
return;
Logger.Log(LogLevel.Verbose, "loader", $"Loading mod .zip: {archive}");
EverestModuleMetadata meta = null;
EverestModuleMetadata[] multimetas = null;
using (ZipFile zip = new ZipFile(archive)) {
foreach (ZipEntry entry in zip.Entries) {
if (entry.FileName == "metadata.yaml") {
using (MemoryStream stream = entry.ExtractStream())
using (StreamReader reader = new StreamReader(stream)) {
try {
meta = YamlHelper.Deserializer.Deserialize<EverestModuleMetadata>(reader);
meta.PathArchive = archive;
meta.PostParse();
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed parsing metadata.yaml in {archive}: {e}");
FilesWithMetadataLoadFailures.Add(archive);
}
}
continue;
}
if (entry.FileName == "multimetadata.yaml" ||
entry.FileName == "everest.yaml" ||
entry.FileName == "everest.yml") {
using (MemoryStream stream = entry.ExtractStream())
using (StreamReader reader = new StreamReader(stream)) {
try {
if (!reader.EndOfStream) {
multimetas = YamlHelper.Deserializer.Deserialize<EverestModuleMetadata[]>(reader);
foreach (EverestModuleMetadata multimeta in multimetas) {
multimeta.PathArchive = archive;
multimeta.PostParse();
}
}
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed parsing everest.yaml in {archive}: {e}");
FilesWithMetadataLoadFailures.Add(archive);
}
}
continue;
}
}
}
ZipModContent contentMeta = new ZipModContent(archive);
EverestModuleMetadata contentMetaParent = null;
Action contentCrawl = () => {
if (contentMeta == null)
return;
if (contentMetaParent != null) {
contentMeta.Mod = contentMetaParent;
contentMeta.Name = contentMetaParent.Name;
}
OnCrawlMod?.Invoke(archive, contentMetaParent);
Content.Crawl(contentMeta);
contentMeta = null;
};
if (multimetas != null) {
foreach (EverestModuleMetadata multimeta in multimetas) {
multimeta.Multimeta = multimetas;
if (contentMetaParent == null)
contentMetaParent = multimeta;
LoadModDelayed(multimeta, contentCrawl);
}
} else {
if (meta == null) {
meta = new EverestModuleMetadata() {
Name = "_zip_" + Path.GetFileNameWithoutExtension(archive),
VersionString = "0.0.0-dummy",
PathArchive = archive
};
meta.PostParse();
}
contentMetaParent = meta;
LoadModDelayed(meta, contentCrawl);
}
}
/// <summary>
/// Load a mod from a directory at runtime.
/// </summary>
/// <param name="dir">The path to the mod directory.</param>
public static void LoadDir(string dir) {
if (!Flags.SupportRuntimeMods) {
Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
return;
}
if (!Directory.Exists(dir)) // Relative path?
dir = Path.Combine(PathMods, dir);
if (!Directory.Exists(dir)) // It just doesn't exist.
return;
Logger.Log(LogLevel.Verbose, "loader", $"Loading mod directory: {dir}");
EverestModuleMetadata meta = null;
EverestModuleMetadata[] multimetas = null;
string metaPath = Path.Combine(dir, "metadata.yaml");
if (File.Exists(metaPath))
using (StreamReader reader = new StreamReader(metaPath)) {
try {
meta = YamlHelper.Deserializer.Deserialize<EverestModuleMetadata>(reader);
meta.PathDirectory = dir;
meta.PostParse();
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed parsing metadata.yaml in {dir}: {e}");
FilesWithMetadataLoadFailures.Add(dir);
}
}
metaPath = Path.Combine(dir, "multimetadata.yaml");
if (!File.Exists(metaPath))
metaPath = Path.Combine(dir, "everest.yaml");
if (!File.Exists(metaPath))
metaPath = Path.Combine(dir, "everest.yml");
if (File.Exists(metaPath))
using (StreamReader reader = new StreamReader(metaPath)) {
try {
if (!reader.EndOfStream) {
multimetas = YamlHelper.Deserializer.Deserialize<EverestModuleMetadata[]>(reader);
foreach (EverestModuleMetadata multimeta in multimetas) {
multimeta.PathDirectory = dir;
multimeta.PostParse();
}
}
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed parsing everest.yaml in {dir}: {e}");
FilesWithMetadataLoadFailures.Add(dir);
}
}
FileSystemModContent contentMeta = new FileSystemModContent(dir);
EverestModuleMetadata contentMetaParent = null;
Action contentCrawl = () => {
if (contentMeta == null)
return;
if (contentMetaParent != null) {
contentMeta.Mod = contentMetaParent;
contentMeta.Name = contentMetaParent.Name;
}
OnCrawlMod?.Invoke(dir, contentMetaParent);
Content.Crawl(contentMeta);
contentMeta = null;
};
if (multimetas != null) {
foreach (EverestModuleMetadata multimeta in multimetas) {
multimeta.Multimeta = multimetas;
if (contentMetaParent == null)
contentMetaParent = multimeta;
LoadModDelayed(multimeta, contentCrawl);
}
} else {
if (meta == null) {
meta = new EverestModuleMetadata() {
Name = "_dir_" + Path.GetFileName(dir),
VersionString = "0.0.0-dummy",
PathDirectory = dir
};
meta.PostParse();
}
contentMetaParent = meta;
LoadModDelayed(meta, contentCrawl);
}
}
/// <summary>
/// Load a mod .dll given its metadata at runtime. Doesn't load the mod content.
/// If required, loads the mod after all of its dependencies have been loaded.
/// </summary>
/// <param name="meta">Metadata of the mod to load.</param>
/// <param name="callback">Callback to be executed after the mod has been loaded. Executed immediately if meta == null.</param>
public static void LoadModDelayed(EverestModuleMetadata meta, Action callback) {
if (!Flags.SupportRuntimeMods) {
Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
return;
}
if (meta == null) {
callback?.Invoke();
return;
}
if (Modules.Any(module => module.Metadata.Name == meta.Name)) {
Logger.Log(LogLevel.Warn, "loader", $"Mod {meta.Name} already loaded!");
return;
}
if (PermanentBlacklist.TryGetValue(meta.Name, out Version minver) && meta.Version < minver) {
Logger.Log(LogLevel.Warn, "loader", $"Mod {meta} permanently blacklisted by Everest!");
return;
}
Tuple<string, Version, string, Version> conflictRow = PermanentConflictlist.FirstOrDefault(row =>
(meta.Name == row.Item1 && meta.Version < row.Item2 && (_Modules.FirstOrDefault(other => other.Metadata.Name == row.Item3)?.Metadata.Version ?? _VersionInvalid) < row.Item4) ||
(meta.Name == row.Item3 && meta.Version < row.Item4 && (_Modules.FirstOrDefault(other => other.Metadata.Name == row.Item1)?.Metadata.Version ?? _VersionInvalid) < row.Item2)
);
if (conflictRow != null) {
throw new Exception($"CONFLICTING MODS: {conflictRow.Item1} VS {conflictRow.Item3}");
}
foreach (EverestModuleMetadata dep in meta.Dependencies)
if (!DependencyLoaded(dep)) {
Logger.Log(LogLevel.Info, "loader", $"Dependency {dep} of mod {meta} not loaded! Delaying.");
lock (Delayed) {
Delayed.Add(Tuple.Create(meta, callback));
}
return;
}
foreach (EverestModuleMetadata dep in meta.OptionalDependencies) {
if (!DependencyLoaded(dep) && (enforceOptionalDependencies || Everest.Modules.Any(module => module.Metadata?.Name == dep.Name))) {
Logger.Log(LogLevel.Info, "loader", $"Optional dependency {dep} of mod {meta} not loaded! Delaying.");
lock (Delayed) {
Delayed.Add(Tuple.Create(meta, callback));
}
return;
}
}
callback?.Invoke();
LoadMod(meta);
}
/// <summary>
/// Load a mod .dll given its metadata at runtime. Doesn't load the mod content.
/// </summary>
/// <param name="meta">Metadata of the mod to load.</param>
public static void LoadMod(EverestModuleMetadata meta) {
if (!Flags.SupportRuntimeMods) {
Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
return;
}
if (meta == null)
return;
// Add an AssemblyResolve handler for all bundled libraries.
AppDomain.CurrentDomain.AssemblyResolve += GenerateModAssemblyResolver(meta);
// Load the actual assembly.
Assembly asm = null;
if (!string.IsNullOrEmpty(meta.PathArchive)) {
bool returnEarly = false;
using (ZipFile zip = new ZipFile(meta.PathArchive)) {
foreach (ZipEntry entry in zip.Entries) {
string entryName = entry.FileName.Replace('\\', '/');
if (entryName == meta.DLL) {
using (MemoryStream stream = entry.ExtractStream())
asm = Relinker.GetRelinkedAssembly(meta, Path.GetFileNameWithoutExtension(meta.DLL), stream);
}
if (entryName == "main.lua") {
new LuaModule(meta).Register();
returnEarly = true;
}
}
}
if (returnEarly)
return;
} else {
if (!string.IsNullOrEmpty(meta.DLL) && File.Exists(meta.DLL)) {
using (FileStream stream = File.OpenRead(meta.DLL))
asm = Relinker.GetRelinkedAssembly(meta, Path.GetFileNameWithoutExtension(meta.DLL), stream);
}
if (File.Exists(Path.Combine(meta.PathDirectory, "main.lua"))) {
new LuaModule(meta).Register();
return;
}
}
if (asm == null) {
// Register a null module for content mods.
new NullModule(meta).Register();
return;
}
LoadModAssembly(meta, asm);
}
/// <summary>
/// Find and load all EverestModules in the given assembly.
/// </summary>
/// <param name="meta">The mod metadata, preferably from the mod metadata.yaml file.</param>
/// <param name="asm">The mod assembly, preferably relinked.</param>
public static void LoadModAssembly(EverestModuleMetadata meta, Assembly asm) {
if (!Flags.SupportRuntimeMods) {
Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
return;
}
if (string.IsNullOrEmpty(meta.PathArchive) && File.Exists(meta.DLL) && meta.SupportsCodeReload && CoreModule.Settings.CodeReload) {
try {
FileSystemWatcher watcher = meta.DevWatcher = new FileSystemWatcher {
Path = Path.GetDirectoryName(meta.DLL),
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
};
watcher.Changed += (s, e) => {
if (e.FullPath != meta.DLL)
return;
ReloadModAssembly(s, e);
// FIXME: Should we dispose the old .dll watcher?
};
watcher.EnableRaisingEvents = true;
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed watching folder: {Path.GetDirectoryName(meta.DLL)}");
e.LogDetailed();
meta.DevWatcher?.Dispose();
meta.DevWatcher = null;
}
}
ApplyModHackfixes(meta, asm);
Content.Crawl(new AssemblyModContent(asm) {
Mod = meta,
Name = meta.Name
});
Type[] types;
try {
types = asm.GetTypesSafe();
} catch (Exception e) {
Logger.Log(LogLevel.Warn, "loader", $"Failed reading assembly: {e}");
e.LogDetailed();
return;
}
for (int i = 0; i < types.Length; i++) {
Type type = types[i];
if (typeof(EverestModule).IsAssignableFrom(type) && !type.IsAbstract && !typeof(NullModule).IsAssignableFrom(type)) {
EverestModule mod = (EverestModule) type.GetConstructor(_EmptyTypeArray).Invoke(_EmptyObjectArray);
mod.Metadata = meta;
mod.Register();
}
}
}
internal static void ReloadModAssembly(object source, FileSystemEventArgs e, bool retrying = false) {
if (!File.Exists(e.FullPath))
return;
Logger.Log(LogLevel.Info, "loader", $"Reloading mod assembly: {e.FullPath}");
QueuedTaskHelper.Do("ReloadModAssembly:" + e.FullPath, () => {
EverestModule module = _Modules.FirstOrDefault(m => m.Metadata.DLL == e.FullPath);
if (module == null)
return;
AssetReloadHelper.Do($"{Dialog.Clean("ASSETRELOADHELPER_RELOADINGMODASSEMBLY")} {Path.GetFileName(e.FullPath)}", () => {
Assembly asm = null;
using (FileStream stream = File.OpenRead(e.FullPath))
asm = Relinker.GetRelinkedAssembly(module.Metadata, Path.GetFileNameWithoutExtension(e.FullPath), stream);
if (asm == null) {
if (!retrying) {
// Retry.
QueuedTaskHelper.Do("ReloadModAssembly:" + e.FullPath, () => {
ReloadModAssembly(source, e, true);
});
}
return;
}
((FileSystemWatcher) source).Dispose();
// be sure to save this module's save data and session before reloading it, so that they are not lost.
if (SaveData.Instance != null) {
Logger.Log("core", $"Saving save data slot {SaveData.Instance.FileSlot} for {module.Metadata} before reloading");
if (module.SaveDataAsync) {
module.WriteSaveData(SaveData.Instance.FileSlot, module.SerializeSaveData(SaveData.Instance.FileSlot));
} else {
#pragma warning disable CS0618 // Synchronous save / load IO is obsolete but some mods still override / use it.
if (CoreModule.Settings.SaveDataFlush ?? false)
module.ForceSaveDataFlush++;
module.SaveSaveData(SaveData.Instance.FileSlot);
#pragma warning restore CS0618
}
if (SaveData.Instance.CurrentSession?.InArea ?? false) {
Logger.Log("core", $"Saving session slot {SaveData.Instance.FileSlot} for {module.Metadata} before reloading");
if (module.SaveDataAsync) {
module.WriteSession(SaveData.Instance.FileSlot, module.SerializeSession(SaveData.Instance.FileSlot));
} else {
#pragma warning disable CS0618 // Synchronous save / load IO is obsolete but some mods still override / use it.
if (CoreModule.Settings.SaveDataFlush ?? false)
module.ForceSaveDataFlush++;
module.SaveSession(SaveData.Instance.FileSlot);
#pragma warning restore CS0618
}
}
}
Unregister(module);
LoadModAssembly(module.Metadata, asm);
});
AssetReloadHelper.ReloadLevel();
});
}
/// <summary>
/// Checks if all dependencies are loaded.
/// Can be used by mods manually to f.e. activate / disable functionality.
/// </summary>
/// <param name="meta">The metadata of the mod listing the dependencies.</param>
/// <returns>True if the dependencies have already been loaded by Everest, false otherwise.</returns>
public static bool DependenciesLoaded(EverestModuleMetadata meta) {
if (!Flags.SupportRuntimeMods) {
return false;
}
// enforce dependencies.
foreach (EverestModuleMetadata dep in meta.Dependencies)
if (!DependencyLoaded(dep))
return false;
// enforce optional dependencies: an optional dependency is satisfied if either of these 2 applies:
// - it is loaded (obviously)
// - enforceOptionalDependencies = false and no version of the mod is loaded (if one is, it might be incompatible and cause issues)
foreach (EverestModuleMetadata dep in meta.OptionalDependencies)
if (!DependencyLoaded(dep) && (enforceOptionalDependencies || Everest.Modules.Any(mod => mod.Metadata?.Name == dep.Name)))
return false;
return true;
}
/// <summary>
/// Checks if an dependency is loaded.
/// Can be used by mods manually to f.e. activate / disable functionality.
/// </summary>
/// <param name="dep">Dependency to check for. Name and Version will be checked.</param>
/// <returns>True if the dependency has already been loaded by Everest, false otherwise.</returns>
public static bool DependencyLoaded(EverestModuleMetadata dep) {
string depName = dep.Name;
Version depVersion = dep.Version;
lock (_Modules) {
foreach (EverestModule other in _Modules) {
EverestModuleMetadata meta = other.Metadata;
if (meta.Name != depName)
continue;
Version version = meta.Version;
return VersionSatisfiesDependency(depVersion, version);
}
}
return false;
}
/// <summary>
/// Checks if the given version number is "compatible" with the one required as a dependency.
/// </summary>
/// <param name="requiredVersion">The version required by a mod in their dependencies</param>
/// <param name="installedVersion">The version to check for</param>
/// <returns>true if the versions number are compatible, false otherwise.</returns>
public static bool VersionSatisfiesDependency(Version requiredVersion, Version installedVersion) {
// Special case: Always true if version == 0.0.*
if (installedVersion.Major == 0 && installedVersion.Minor == 0)
return true;
// Major version, breaking changes, must match.
if (installedVersion.Major != requiredVersion.Major)
return false;
// Minor version, non-breaking changes, installed can't be lower than what we depend on.
if (installedVersion.Minor < requiredVersion.Minor)
return false;
// "Build" is "PATCH" in semver, but we'll also check for it and "Revision".
if (installedVersion.Minor == requiredVersion.Minor && installedVersion.Build < requiredVersion.Build)
return false;
if (installedVersion.Minor == requiredVersion.Minor && installedVersion.Build == requiredVersion.Build && installedVersion.Revision < requiredVersion.Revision)
return false;
return true;
}
private static ResolveEventHandler GenerateModAssemblyResolver(EverestModuleMetadata meta)
=> (sender, args) => {
AssemblyName name = args?.Name == null ? null : new AssemblyName(args.Name);
if (string.IsNullOrEmpty(name?.Name))
return null;
string path = name.Name + ".dll";
if (!string.IsNullOrEmpty(meta.DLL))
path = Path.Combine(Path.GetDirectoryName(meta.DLL), path);
if (!string.IsNullOrEmpty(meta.PathArchive)) {
string zipPath = path.Replace('\\', '/');
using (ZipFile zip = new ZipFile(meta.PathArchive)) {
foreach (ZipEntry entry in zip.Entries) {
if (entry.FileName == zipPath)
using (MemoryStream stream = entry.ExtractStream())
return Relinker.GetRelinkedAssembly(meta, Path.GetFileNameWithoutExtension(zipPath), stream);
}
}
}
if (!string.IsNullOrEmpty(meta.PathDirectory)) {
string filePath = path;
if (!File.Exists(filePath))
path = Path.Combine(meta.PathDirectory, filePath);
if (File.Exists(filePath))
using (FileStream stream = File.OpenRead(filePath))
return Relinker.GetRelinkedAssembly(meta, Path.GetFileNameWithoutExtension(filePath), stream);
}
return null;
};
private static void ApplyModHackfixes(EverestModuleMetadata meta, Assembly asm) {
// Feel free to keep this as a reminder on mod hackfixes or whatever. -jade
/*
if (meta.Name == "Prideline" && meta.Version < new Version(1, 0, 0, 0)) {
// Prideline 1.0.0 has got a hardcoded path to /ModSettings/Prideline.flag
Type t_PridelineModule = asm.GetType("Celeste.Mod.Prideline.PridelineModule");
FieldInfo f_CustomFlagPath = t_PridelineModule.GetField("CustomFlagPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
f_CustomFlagPath.SetValue(null, Path.Combine(PathSettings, "modsettings-Prideline-Flag.celeste"));
}
*/
}
}
}
}
| 49.965071 | 214 | 0.497579 | [
"MIT"
] | JaThePlayer/Everest | Celeste.Mod.mm/Mod/Everest/Everest.Loader.cs | 38,625 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoggerConfigurationAmazonS3Extensions.cs" company="Hämmer Electronics">
// The project is licensed under the MIT license.
// </copyright>
// <summary>
// This class contains the Amazon S3 logger configuration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Serilog
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Amazon;
using Amazon.S3;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Sinks.AmazonS3;
using Serilog.Sinks.PeriodicBatching;
/// <summary>
/// This class contains the Amazon S3 logger configuration.
/// </summary>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
// ReSharper disable once UnusedMember.Global
public static class LoggerConfigurationAmazonS3Extensions
{
/// <summary>
/// The default output template.
/// </summary>
private const string DefaultOutputTemplate =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}";
/// <summary>
/// The default batch size limit.
/// </summary>
private const int DefaultBatchSizeLimit = 100;
/// <summary>
/// The default value to eagerly emit the first event.
/// </summary>
private const bool DefaultEagerlyEmitFirstEvent = true;
/// <summary>
/// The default queue size limit.
/// </summary>
private const int DefaultQueueSizeLimit = 10000;
/// <summary>
/// The default encoding.
/// </summary>
private static readonly Encoding DefaultEncoding = Encoding.UTF8;
/// <summary>
/// The default batching period.
/// </summary>
private static readonly TimeSpan DefaultBatchingPeriod = TimeSpan.FromSeconds(2);
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="endpoint">The Amazon S3 endpoint.</param>
/// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
/// <param name="awsSecretAccessKey">The Amazon S3 access key.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="outputTemplate">The output template.</param>
/// <param name="formatProvider">
/// (Optional)
/// Supplies culture-specific formatting information, or
/// null.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
RegionEndpoint endpoint,
string awsAccessKeyId,
string awsSecretAccessKey,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
LoggingLevelSwitch levelSwitch = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (endpoint is null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (string.IsNullOrWhiteSpace(awsAccessKeyId))
{
throw new ArgumentNullException(nameof(awsAccessKeyId));
}
if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
{
throw new ArgumentNullException(nameof(awsSecretAccessKey));
}
if (string.IsNullOrWhiteSpace(outputTemplate))
{
outputTemplate = DefaultOutputTemplate;
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
Endpoint = endpoint,
AwsAccessKeyId = awsAccessKeyId,
AwsSecretAccessKey = awsSecretAccessKey,
OutputTemplate = outputTemplate,
FormatProvider = formatProvider,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="endpoint">The Amazon S3 endpoint.</param>
/// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
/// <param name="awsSecretAccessKey">The Amazon S3 access key.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="formatter">The formatter.</param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
RegionEndpoint endpoint,
string awsAccessKeyId,
string awsSecretAccessKey,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
ITextFormatter formatter = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (endpoint is null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (string.IsNullOrWhiteSpace(awsAccessKeyId))
{
throw new ArgumentNullException(nameof(awsAccessKeyId));
}
if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
{
throw new ArgumentNullException(nameof(awsSecretAccessKey));
}
if (formatter is null)
{
throw new ArgumentNullException(nameof(formatter));
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
Endpoint = endpoint,
AwsAccessKeyId = awsAccessKeyId,
AwsSecretAccessKey = awsSecretAccessKey,
Formatter = formatter,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="endpoint">The Amazon S3 endpoint.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="outputTemplate">
/// (Optional)
/// A message template describing the format used to
/// write to the sink.
/// The default is "{Timestamp:yyyy-MM-dd
/// HH:mm:ss.fff zzz} [{Level:u3}]
/// {Message:lj}{NewLine}{Exception}".
/// </param>
/// <param name="formatProvider">
/// (Optional)
/// Supplies culture-specific formatting information, or
/// null.
/// </param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
RegionEndpoint endpoint,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (endpoint is null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (string.IsNullOrWhiteSpace(outputTemplate))
{
outputTemplate = DefaultOutputTemplate;
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
Endpoint = endpoint,
OutputTemplate = outputTemplate,
FormatProvider = formatProvider,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="endpoint">The Amazon S3 endpoint.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="formatter">The formatter.</param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
RegionEndpoint endpoint,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
ITextFormatter formatter = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (endpoint is null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (formatter is null)
{
throw new ArgumentNullException(nameof(formatter));
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
Endpoint = endpoint,
Formatter = formatter,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="serviceUrl">The Amazon S3 service url.</param>
/// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
/// <param name="awsSecretAccessKey">The Amazon S3 access key.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="outputTemplate">The output template.</param>
/// <param name="formatProvider">
/// (Optional)
/// Supplies culture-specific formatting information, or
/// null.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
string serviceUrl,
string awsAccessKeyId,
string awsSecretAccessKey,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
LoggingLevelSwitch levelSwitch = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (string.IsNullOrWhiteSpace(serviceUrl))
{
throw new ArgumentNullException(nameof(serviceUrl));
}
if (string.IsNullOrWhiteSpace(awsAccessKeyId))
{
throw new ArgumentNullException(nameof(awsAccessKeyId));
}
if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
{
throw new ArgumentNullException(nameof(awsSecretAccessKey));
}
if (string.IsNullOrWhiteSpace(outputTemplate))
{
outputTemplate = DefaultOutputTemplate;
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
ServiceUrl = serviceUrl,
AwsAccessKeyId = awsAccessKeyId,
AwsSecretAccessKey = awsSecretAccessKey,
OutputTemplate = outputTemplate,
FormatProvider = formatProvider,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="serviceUrl">The Amazon S3 service url.</param>
/// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
/// <param name="awsSecretAccessKey">The Amazon S3 access key.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="formatter">The formatter.</param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
string serviceUrl,
string awsAccessKeyId,
string awsSecretAccessKey,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
ITextFormatter formatter = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (string.IsNullOrWhiteSpace(serviceUrl))
{
throw new ArgumentNullException(nameof(serviceUrl));
}
if (string.IsNullOrWhiteSpace(awsAccessKeyId))
{
throw new ArgumentNullException(nameof(awsAccessKeyId));
}
if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
{
throw new ArgumentNullException(nameof(awsSecretAccessKey));
}
if (formatter is null)
{
throw new ArgumentNullException(nameof(formatter));
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
ServiceUrl = serviceUrl,
AwsAccessKeyId = awsAccessKeyId,
AwsSecretAccessKey = awsSecretAccessKey,
Formatter = formatter,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="serviceUrl">The Amazon S3 service url.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="outputTemplate">
/// (Optional)
/// A message template describing the format used to
/// write to the sink.
/// The default is "{Timestamp:yyyy-MM-dd
/// HH:mm:ss.fff zzz} [{Level:u3}]
/// {Message:lj}{NewLine}{Exception}".
/// </param>
/// <param name="formatProvider">
/// (Optional)
/// Supplies culture-specific formatting information, or
/// null.
/// </param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
string serviceUrl,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (string.IsNullOrWhiteSpace(serviceUrl))
{
throw new ArgumentNullException(nameof(serviceUrl));
}
if (string.IsNullOrWhiteSpace(outputTemplate))
{
outputTemplate = DefaultOutputTemplate;
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
ServiceUrl = serviceUrl,
OutputTemplate = outputTemplate,
FormatProvider = formatProvider,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="serviceUrl">The Amazon S3 service url.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="formatter">The formatter.</param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
string path,
string bucketName,
string serviceUrl,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
ITextFormatter formatter = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (string.IsNullOrWhiteSpace(serviceUrl))
{
throw new ArgumentNullException(nameof(serviceUrl));
}
if (formatter is null)
{
throw new ArgumentNullException(nameof(formatter));
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
Path = path,
BucketName = bucketName,
ServiceUrl = serviceUrl,
Formatter = formatter,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="client">The Amazon S3 client.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="outputTemplate">
/// (Optional)
/// A message template describing the format used to
/// write to the sink.
/// The default is "{Timestamp:yyyy-MM-dd
/// HH:mm:ss.fff zzz} [{Level:u3}]
/// {Message:lj}{NewLine}{Exception}".
/// </param>
/// <param name="formatProvider">
/// (Optional)
/// Supplies culture-specific formatting information, or
/// null.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
AmazonS3Client client,
string path,
string bucketName,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
LoggingLevelSwitch levelSwitch = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (client is null)
{
throw new ArgumentNullException(nameof(client));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (string.IsNullOrWhiteSpace(outputTemplate))
{
outputTemplate = DefaultOutputTemplate;
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
AmazonS3Client = client,
Path = path,
BucketName = bucketName,
OutputTemplate = outputTemplate,
FormatProvider = formatProvider,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>Write log events to the specified file.</summary>
/// <exception cref="ArgumentNullException">
/// Thrown when one or more required arguments are
/// null.
/// </exception>
/// <param name="sinkConfiguration">The logger sink configuration.</param>
/// <param name="client">The Amazon S3 client.</param>
/// <param name="path">The path to the file.</param>
/// <param name="bucketName">The Amazon S3 bucket name.</param>
/// <param name="restrictedToMinimumLevel">
/// (Optional)
/// The minimum level for
/// events passed through the sink. Ignored when
/// <paramref name="levelSwitch" /> is specified.
/// </param>
/// <param name="levelSwitch">
/// (Optional)
/// A switch allowing the pass-through minimum level
/// to be changed at runtime.
/// </param>
/// <param name="formatter">The formatter.</param>
/// <param name="rollingInterval">
/// (Optional)
/// The interval at which logging will roll over to a new
/// file.
/// </param>
/// <param name="encoding">
/// (Optional)
/// Character encoding used to write the text file. The
/// default is UTF-8 without BOM.
/// </param>
/// <param name="failureCallback">The failure callback.</param>
/// <param name="bucketPath">The Amazon S3 bucket path.</param>
/// <param name="batchSizeLimit">The batch size limit.</param>
/// <param name="batchingPeriod">The batching period.</param>
/// <param name="eagerlyEmitFirstEvent">A value indicating whether the first event should be emitted immediately or not.</param>
/// <param name="queueSizeLimit">The queue size limit.</param>
/// <returns>The configuration object allowing method chaining.</returns>
public static LoggerConfiguration AmazonS3(
this LoggerSinkConfiguration sinkConfiguration,
AmazonS3Client client,
string path,
string bucketName,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
ITextFormatter formatter = null,
RollingInterval rollingInterval = RollingInterval.Day,
Encoding encoding = null,
Action<Exception> failureCallback = null,
string bucketPath = null,
int? batchSizeLimit = DefaultBatchSizeLimit,
TimeSpan? batchingPeriod = null,
bool? eagerlyEmitFirstEvent = DefaultEagerlyEmitFirstEvent,
int? queueSizeLimit = DefaultQueueSizeLimit)
{
if (sinkConfiguration is null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
if (client is null)
{
throw new ArgumentNullException(nameof(client));
}
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
if (string.IsNullOrWhiteSpace(bucketName))
{
throw new ArgumentNullException(nameof(bucketName));
}
if (formatter is null)
{
throw new ArgumentNullException(nameof(formatter));
}
if (encoding is null)
{
encoding = DefaultEncoding;
}
if (batchingPeriod is null)
{
batchingPeriod = DefaultBatchingPeriod;
}
var options = new AmazonS3Options
{
AmazonS3Client = client,
Path = path,
BucketName = bucketName,
Formatter = formatter,
RollingInterval = rollingInterval,
Encoding = encoding,
FailureCallback = failureCallback,
BucketPath = bucketPath
};
var amazonS3Sink = new AmazonS3Sink(options);
var batchingOptions = new PeriodicBatchingSinkOptions
{
BatchSizeLimit = batchSizeLimit ?? DefaultBatchSizeLimit,
Period = (TimeSpan)batchingPeriod,
EagerlyEmitFirstEvent = eagerlyEmitFirstEvent ?? DefaultEagerlyEmitFirstEvent,
QueueLimit = queueSizeLimit ?? DefaultQueueSizeLimit
};
var batchingSink = new PeriodicBatchingSink(amazonS3Sink, batchingOptions);
return sinkConfiguration.Sink(batchingSink, restrictedToMinimumLevel, levelSwitch);
}
}
} | 40.534866 | 136 | 0.574001 | [
"MIT"
] | profet23/Serilog.Sinks.AmazonS3 | src/Serilog.Sinks.AmazonS3/LoggerConfigurationAmazonS3Extensions.cs | 54,644 | C# |
using System;
using Microsoft.Extensions.Logging;
using SummerBoot.Core;
namespace Example.Models
{
[Serializable]
public class WheelA : IWheel
{
public string Name { get; set; } = "A";
[Autowired]
private ILogger<Car> Logger { set; get; }
public void Scroll()
{
Logger.LogDebug("我是A轮胎,我正在滚");
}
}
} | 20.833333 | 49 | 0.581333 | [
"MIT"
] | sososu/SummerBoot | Example/Models/WheelA.cs | 395 | C# |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Serialization.Custom.TypeDeserializers
{
using System.Xml;
public class CharDeserializer :
IObjectDeserializer<char>
{
public object Deserialize(IDeserializerContext context)
{
var s = context.ReadElementAsString();
if (string.IsNullOrEmpty(s))
return default(char);
return XmlConvert.ToChar(s);
}
}
} | 33.482759 | 83 | 0.743563 | [
"Apache-2.0"
] | DavidChristiansen/MassTransit | src/MassTransit/Serialization/Custom/TypeDeserializers/CharDeserializer.cs | 971 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using QP8.Infrastructure.Extensions;
using QP8.Infrastructure.Web.Enums;
using QP8.Infrastructure.Web.Responses;
using Quantumart.QP8.BLL.Enums.Csv;
using Quantumart.QP8.BLL.Services.MultistepActions;
using Quantumart.QP8.BLL.Services.MultistepActions.Export;
using Quantumart.QP8.Constants;
using Quantumart.QP8.WebMvc.Extensions.Controllers;
using Quantumart.QP8.WebMvc.Infrastructure.ActionFilters;
using Quantumart.QP8.WebMvc.Infrastructure.Enums;
using Quantumart.QP8.WebMvc.ViewModels;
using Quantumart.QP8.WebMvc.ViewModels.MultistepSettings;
namespace Quantumart.QP8.WebMvc.Controllers
{
public class ExportSelectedArticlesController : AuthQpController
{
private readonly IMultistepActionService _service;
private const string FolderForTemplate = "MultistepSettingsTemplates";
public ExportSelectedArticlesController(ExportArticlesService service)
{
_service = service;
}
[HttpPost]
[ExceptionResult(ExceptionResultMode.OperationAction)]
[ActionAuthorize(ActionCode.ExportArticles)]
[BackendActionContext(ActionCode.ExportArticles)]
public ActionResult PreSettings(int parentId, [FromBody] SelectedItemsViewModel model)
{
return Json(_service.MultistepActionSettings(parentId, 0, model.Ids));
}
[HttpPost]
[ExceptionResult(ExceptionResultMode.OperationAction)]
[ActionAuthorize(ActionCode.ExportArticles)]
[BackendActionContext(ActionCode.ExportArticles)]
public async Task<ActionResult> Settings(string tabId, int parentId, [FromBody] SelectedItemsViewModel model)
{
return await JsonHtml($"{FolderForTemplate}/ExportTemplate", new ExportViewModel
{
ContentId = parentId,
Ids = model.Ids
});
}
[HttpPost]
[ExceptionResult(ExceptionResultMode.OperationAction)]
[ActionAuthorize(ActionCode.ExportArticles)]
[BackendActionContext(ActionCode.ExportArticles)]
public ActionResult Setup(int parentId, [FromBody] SelectedItemsViewModel model, bool? boundToExternal)
{
return Json(_service.Setup(parentId, 0, model.Ids, boundToExternal));
}
[HttpPost]
[ExceptionResult(ExceptionResultMode.OperationAction)]
[ActionAuthorize(ActionCode.ExportArticles)]
[BackendActionContext(ActionCode.ExportArticles)]
public JsonResult SetupWithParams(int parentId, [FromBody] ExportViewModel model)
{
var settings = new ExportSettings
{
Culture = ((CsvCulture)int.Parse(model.Culture)).Description(),
Delimiter = char.Parse(((CsvDelimiter)int.Parse(model.Delimiter)).Description()),
Encoding = ((CsvEncoding)int.Parse(model.Encoding)).Description(),
LineSeparator = ((CsvLineSeparator)int.Parse(model.LineSeparator)).Description(),
AllFields = model.AllFields,
OrderByField = model.OrderByField
};
if (!settings.AllFields)
{
settings.CustomFieldIds = model.CustomFields.ToList();
settings.ExcludeSystemFields = model.ExcludeSystemFields;
}
settings.FieldIdsToExpand = model.FieldsToExpand.ToList();
_service.SetupWithParams(parentId, model.Ids, settings);
return JsonCamelCase(new JSendResponse { Status = JSendStatus.Success });
}
[HttpPost]
[NoTransactionConnectionScope]
[ExceptionResult(ExceptionResultMode.OperationAction)]
public ActionResult Step([FromBody] MultiStepActionViewModel model)
{
return Json(_service.Step(model.Stage, model.Step));
}
[HttpPost]
public void TearDown(bool isError)
{
_service.TearDown();
}
}
}
| 39.106796 | 118 | 0.678997 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | QuantumArt/QP | siteMvc/Controllers/ExportSelectedArticlesController.cs | 4,028 | C# |
using System;
using System.Collections;
using Server.Network;
using Server.Items;
using Server.Mobiles;
using Server.Targeting;
namespace Server.Spells.Bushido
{
public class CounterAttack : SamuraiSpell
{
private static SpellInfo m_Info = new SpellInfo(
"CounterAttack", null,
-1,
9002
);
public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 0.25 ); } }
public override double RequiredSkill{ get{ return 40.0; } }
public override int RequiredMana{ get{ return 5; } }
public override bool CheckCast()
{
if ( !base.CheckCast() )
return false;
if ( Caster.FindItemOnLayer( Layer.TwoHanded ) as BaseShield != null )
return true;
if ( Caster.FindItemOnLayer( Layer.OneHanded ) as BaseWeapon != null )
return true;
if ( Caster.FindItemOnLayer( Layer.TwoHanded ) as BaseWeapon != null )
return true;
Caster.SendLocalizedMessage( 1062944 ); // You must have a weapon or a shield equipped to use this ability!
return false;
}
public CounterAttack( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnBeginCast()
{
base.OnBeginCast();
Caster.FixedEffect( 0x37C4, 10, 7, 4, 3 );
}
public override void OnCast()
{
if ( CheckSequence() )
{
Caster.SendLocalizedMessage( 1063118 ); // You prepare to respond immediately to the next blocked blow.
OnCastSuccessful( Caster );
StartCountering( Caster );
}
FinishSequence();
}
private static Hashtable m_Table = new Hashtable();
public static bool IsCountering( Mobile m )
{
return m_Table.Contains( m );
}
public static void StartCountering( Mobile m )
{
Timer t = (Timer)m_Table[m];
if ( t != null )
t.Stop();
t = new InternalTimer( m );
m_Table[m] = t;
t.Start();
}
public static void StopCountering( Mobile m )
{
Timer t = (Timer)m_Table[m];
if ( t != null )
t.Stop();
m_Table.Remove( m );
OnEffectEnd( m, typeof( CounterAttack ) );
}
private class InternalTimer : Timer
{
private Mobile m_Mobile;
public InternalTimer( Mobile m ) : base( TimeSpan.FromSeconds( 30.0 ) )
{
m_Mobile = m;
Priority = TimerPriority.TwoFiftyMS;
}
protected override void OnTick()
{
StopCountering( m_Mobile );
m_Mobile.SendLocalizedMessage( 1063119 ); // You return to your normal stance.
}
}
}
} | 20.810345 | 110 | 0.662386 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Spells/Bushido/CounterAttack.cs | 2,414 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Diagnostics;
namespace System.DirectoryServices.AccountManagement
{
//
// A collection of individual property filters
//
internal class QbeFilterDescription
{
private readonly ArrayList _filtersToApply = new ArrayList();
public QbeFilterDescription()
{
// Nothing to do
}
public ArrayList FiltersToApply
{
get
{
return _filtersToApply;
}
}
}
//
// Constructs individual property filters, given the name of the property
//
internal static class FilterFactory
{
private static readonly Hashtable s_subclasses = new Hashtable();
static FilterFactory()
{
s_subclasses[DescriptionFilter.PropertyNameStatic] = typeof(DescriptionFilter);
s_subclasses[DisplayNameFilter.PropertyNameStatic] = typeof(DisplayNameFilter);
s_subclasses[IdentityClaimFilter.PropertyNameStatic] = typeof(IdentityClaimFilter);
s_subclasses[SamAccountNameFilter.PropertyNameStatic] = typeof(SamAccountNameFilter);
s_subclasses[DistinguishedNameFilter.PropertyNameStatic] = typeof(DistinguishedNameFilter);
s_subclasses[GuidFilter.PropertyNameStatic] = typeof(GuidFilter);
s_subclasses[UserPrincipalNameFilter.PropertyNameStatic] = typeof(UserPrincipalNameFilter);
s_subclasses[StructuralObjectClassFilter.PropertyNameStatic] = typeof(StructuralObjectClassFilter);
s_subclasses[NameFilter.PropertyNameStatic] = typeof(NameFilter);
s_subclasses[CertificateFilter.PropertyNameStatic] = typeof(CertificateFilter);
s_subclasses[AuthPrincEnabledFilter.PropertyNameStatic] = typeof(AuthPrincEnabledFilter);
s_subclasses[PermittedWorkstationFilter.PropertyNameStatic] = typeof(PermittedWorkstationFilter);
s_subclasses[PermittedLogonTimesFilter.PropertyNameStatic] = typeof(PermittedLogonTimesFilter);
s_subclasses[ExpirationDateFilter.PropertyNameStatic] = typeof(ExpirationDateFilter);
s_subclasses[SmartcardLogonRequiredFilter.PropertyNameStatic] = typeof(SmartcardLogonRequiredFilter);
s_subclasses[DelegationPermittedFilter.PropertyNameStatic] = typeof(DelegationPermittedFilter);
s_subclasses[HomeDirectoryFilter.PropertyNameStatic] = typeof(HomeDirectoryFilter);
s_subclasses[HomeDriveFilter.PropertyNameStatic] = typeof(HomeDriveFilter);
s_subclasses[ScriptPathFilter.PropertyNameStatic] = typeof(ScriptPathFilter);
s_subclasses[PasswordNotRequiredFilter.PropertyNameStatic] = typeof(PasswordNotRequiredFilter);
s_subclasses[PasswordNeverExpiresFilter.PropertyNameStatic] = typeof(PasswordNeverExpiresFilter);
s_subclasses[CannotChangePasswordFilter.PropertyNameStatic] = typeof(CannotChangePasswordFilter);
s_subclasses[AllowReversiblePasswordEncryptionFilter.PropertyNameStatic] = typeof(AllowReversiblePasswordEncryptionFilter);
s_subclasses[GivenNameFilter.PropertyNameStatic] = typeof(GivenNameFilter);
s_subclasses[MiddleNameFilter.PropertyNameStatic] = typeof(MiddleNameFilter);
s_subclasses[SurnameFilter.PropertyNameStatic] = typeof(SurnameFilter);
s_subclasses[EmailAddressFilter.PropertyNameStatic] = typeof(EmailAddressFilter);
s_subclasses[VoiceTelephoneNumberFilter.PropertyNameStatic] = typeof(VoiceTelephoneNumberFilter);
s_subclasses[EmployeeIDFilter.PropertyNameStatic] = typeof(EmployeeIDFilter);
s_subclasses[GroupIsSecurityGroupFilter.PropertyNameStatic] = typeof(GroupIsSecurityGroupFilter);
s_subclasses[GroupScopeFilter.PropertyNameStatic] = typeof(GroupScopeFilter);
s_subclasses[ServicePrincipalNameFilter.PropertyNameStatic] = typeof(ServicePrincipalNameFilter);
s_subclasses[ExtensionCacheFilter.PropertyNameStatic] = typeof(ExtensionCacheFilter);
s_subclasses[BadPasswordAttemptFilter.PropertyNameStatic] = typeof(BadPasswordAttemptFilter);
s_subclasses[ExpiredAccountFilter.PropertyNameStatic] = typeof(ExpiredAccountFilter);
s_subclasses[LastLogonTimeFilter.PropertyNameStatic] = typeof(LastLogonTimeFilter);
s_subclasses[LockoutTimeFilter.PropertyNameStatic] = typeof(LockoutTimeFilter);
s_subclasses[PasswordSetTimeFilter.PropertyNameStatic] = typeof(PasswordSetTimeFilter);
s_subclasses[BadLogonCountFilter.PropertyNameStatic] = typeof(BadLogonCountFilter);
}
// Given a property name, constructs and returns the appropriate individual property
// filter
public static object CreateFilter(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "QbeFilterDescription", "FilterFactory.CreateFilter: name=" + propertyName);
Type type = (Type)s_subclasses[propertyName];
Debug.Assert(type != null);
return System.Activator.CreateInstance(type);
}
}
//
// The individual property filters
//
// Base class: Defines the external interface shared by all individual property filters
internal abstract class FilterBase
{
public object Value
{
get { return _value; }
set { _value = value; }
}
private object _value;
// Some providers need place to store extra state, e.g., a processed form of Value
public object Extra
{
get { return _extra; }
set { _extra = value; }
}
private object _extra;
public abstract string PropertyName { get; }
}
// The derived classes
internal class DescriptionFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalDescription;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class SidFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalSid;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class SamAccountNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalSamAccountName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class DistinguishedNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalDistinguishedName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class GuidFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalGuid;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class IdentityClaimFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalIdentityClaims;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class UserPrincipalNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalUserPrincipalName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class StructuralObjectClassFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalStructuralObjectClass;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class NameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class DisplayNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalDisplayName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class CertificateFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AuthenticablePrincipalCertificates;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class AuthPrincEnabledFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AuthenticablePrincipalEnabled;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class PermittedWorkstationFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoPermittedWorkstations;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class PermittedLogonTimesFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoPermittedLogonTimes;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class ExpirationDateFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoExpirationDate;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class SmartcardLogonRequiredFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoSmartcardRequired;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class DelegationPermittedFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoDelegationPermitted;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class HomeDirectoryFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoHomeDirectory;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class HomeDriveFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoHomeDrive;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class ScriptPathFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoScriptPath;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class PasswordNotRequiredFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoPasswordNotRequired;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class PasswordNeverExpiresFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoPasswordNeverExpires;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class CannotChangePasswordFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoCannotChangePassword;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class AllowReversiblePasswordEncryptionFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoAllowReversiblePasswordEncryption;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class GivenNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserGivenName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class MiddleNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserMiddleName;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class SurnameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserSurname;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class EmailAddressFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserEmailAddress;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class VoiceTelephoneNumberFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserVoiceTelephoneNumber;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class EmployeeIDFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.UserEmployeeID;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class GroupIsSecurityGroupFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.GroupIsSecurityGroup;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class GroupScopeFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.GroupGroupScope;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class ServicePrincipalNameFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.ComputerServicePrincipalNames;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class ExtensionCacheFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PrincipalExtensionCache;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class BadPasswordAttemptFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoLastBadPasswordAttempt;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class LastLogonTimeFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoLastLogon;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class LockoutTimeFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoAcctLockoutTime;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class ExpiredAccountFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoExpiredAccount;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class PasswordSetTimeFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.PwdInfoLastPasswordSet;
public override string PropertyName { get { return PropertyNameStatic; } }
}
internal class BadLogonCountFilter : FilterBase
{
public const string PropertyNameStatic = PropertyNames.AcctInfoBadLogonCount;
public override string PropertyName { get { return PropertyNameStatic; } }
}
}
| 43.145251 | 135 | 0.725042 | [
"MIT"
] | Jacksondr5/runtime | src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/QbeFilterDescription.cs | 15,446 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Demo.Core.Domain.Heroes;
namespace Demo.Core.Repositories
{
public interface IHeroRepository
{
Task<IEnumerable<Hero>> FindAllAsync();
}
}
| 19.25 | 47 | 0.731602 | [
"MIT"
] | thecodereaper/architecture-governance-unit-tests | src/Demo.Core/Repositories/IHeroRepository.cs | 233 | C# |
using System;
using System.Text.RegularExpressions;
using UCLouvain.KAOSTools.Core;
using UCLouvain.KAOSTools.Core.Agents;
using UCLouvain.KAOSTools.Parsing.Parsers;
namespace UCLouvain.KAOSTools.Parsing.Builders.Attributes
{
public class LinkAttributeBuilder : AttributeBuilder<Relation, ParsedLinkAttribute>
{
public LinkAttributeBuilder()
{
}
public override void Handle(Relation element, ParsedLinkAttribute attribute, KAOSModel model)
{
Entity entity;
if (attribute.Target is IdentifierExpression)
{
string id = ((IdentifierExpression)attribute.Target).Value;
if ((entity = model.entityRepository.GetEntity(id)) == null) {
entity = new Entity(model, id) { Implicit = true };
model.entityRepository.Add(entity);
}
element.Links.Add(new Link(model) { Target = entity, Multiplicity = attribute.Multiplicity });
}
else
{
throw new UnsupportedValue(element, attribute, attribute.Target);
}
}
}
}
| 30.971429 | 110 | 0.656827 | [
"Unlicense",
"MIT"
] | ancailliau/KAOSTools | Parsing/Builders/Attributes/LinkAttributeBuilder.cs | 1,086 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HI.Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ADAH")]
[assembly: AssemblyProduct("HI.Sample")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("05e6cae1-af58-4a88-b271-905be0cde19f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| 38.648649 | 85 | 0.725175 | [
"Apache-2.0"
] | frannkkiiee/SplunkCare | AssemblyInfo.cs | 1,433 | C# |
using NUnit.Framework;
using Opten.Core.Helpers;
using System;
namespace Opten.Core.Test.Helpers
{
[TestFixture]
public class DisplayTests
{
[Test]
public void AsCentimeters()
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-CH");
Assert.AreEqual("10.5cm", new decimal(10.50).AsCentimeters(true, 1));
Assert.AreEqual("1'001cm", new decimal(1000.50).AsCentimeters(false, 0));
Assert.AreEqual("10cm", 10.AsCentimeters(true));
Assert.AreEqual("1'000cm", 1000.AsCentimeters(false));
}
[Test]
public void AsKilograms()
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-CH");
Assert.AreEqual("10.5kg", new decimal(10.50).AsKilograms(true, 1));
Assert.AreEqual("1'001kg", new decimal(1000.50).AsKilograms(false, 0));
Assert.AreEqual("10kg", 10.AsKilograms(true));
Assert.AreEqual("1'000kg", 1000.AsKilograms(false));
}
[Test]
public void FullName()
{
Assert.AreEqual("Calvin Frei", DisplayHelper.FullNameWithFirstNameInFront("Calvin", "Frei"));
Assert.AreEqual("Frei Calvin", DisplayHelper.FullNameWithLastNameInFront("Calvin", "Frei"));
Assert.AreEqual("Calvin Frei", DisplayHelper.FullNameWithFirstNameInFront(" Calvin ", " Frei"));
Assert.AreEqual("Frei Calvin", DisplayHelper.FullNameWithLastNameInFront(" Calvin ", " Frei"));
Assert.AreEqual("Frei", DisplayHelper.FullNameWithFirstNameInFront(string.Empty, "Frei"));
Assert.AreEqual("Frei", DisplayHelper.FullNameWithLastNameInFront(string.Empty, "Frei"));
Assert.AreEqual("Calvin", DisplayHelper.FullNameWithFirstNameInFront("Calvin", null));
Assert.AreEqual("Calvin", DisplayHelper.FullNameWithLastNameInFront("Calvin", null));
}
[Test]
public void AsSwissDate()
{
DateTime dt = new DateTime(2015, 01, 25, 22, 10, 20);
DateTime? dtNullable = (DateTime?)dt;
DateTime birthday = new DateTime(1992, 01, 25, 22, 10, 20);
DateTime? birthdayNullable = (DateTime?)birthday;
DateTime? dtNull = null;
Assert.That("25.01.2015", Is.EqualTo(dt.AsSwissDate()));
Assert.That("25.01.2015 22:10", Is.EqualTo(dt.AsSwissDateTime()));
Assert.That("25.01.2015 22:10:20", Is.EqualTo(dt.AsSwissDateTime(includeSeconds: true)));
Assert.That("Sonntag, 25. Januar 2015", Is.EqualTo(dt.AsSwissDateLong()));
Assert.That("25.01", Is.EqualTo(dt.AsSwissDateShort()));
Assert.That("2015-01-25", Is.EqualTo(dt.AsUrl()));
Assert.That("25.01.1992", Is.EqualTo(birthday.AsSwissBirthday()));
Assert.That($"25.01.1992 ({birthday.GetAge()})", Is.EqualTo(birthday.AsSwissBirthday(showAge: true)));
// Nullable
Assert.That("25.01.2015", Is.EqualTo(dtNullable.AsSwissDate()));
Assert.That("25.01.2015 22:10", Is.EqualTo(dtNullable.AsSwissDateTime()));
Assert.That("25.01.2015 22:10:20", Is.EqualTo(dtNullable.AsSwissDateTime(includeSeconds: true)));
Assert.That("Sonntag, 25. Januar 2015", Is.EqualTo(dtNullable.AsSwissDateLong()));
Assert.That("25.01", Is.EqualTo(dtNullable.AsSwissDateShort()));
Assert.That("2015-01-25", Is.EqualTo(dtNullable.AsUrl()));
Assert.That("25.01.1992", Is.EqualTo(birthdayNullable.AsSwissBirthday()));
Assert.That($"25.01.1992 ({birthday.GetAge()})", Is.EqualTo(birthdayNullable.AsSwissBirthday(showAge: true)));
Assert.That(null, Is.EqualTo(dtNull.AsSwissDate()));
}
[Test]
public void AsTime()
{
TimeSpan ts = new TimeSpan(22, 00, 11);
TimeSpan? tsNull = null;
Assert.That("22:00", Is.EqualTo(ts.AsTime()));
Assert.That("22:00:11", Is.EqualTo(ts.AsTime(ignoreSeconds: false)));
Assert.That(null, Is.EqualTo(tsNull.AsTime()));
}
}
}
| 40.571429 | 113 | 0.707746 | [
"MIT"
] | OPTEN/Opten.Core | tests/Opten.Core.Test/Helpers/DisplayTests.cs | 3,694 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
//Handles the click events by the player e.g. for planting flowers. Attach this to the Character game object
public class Planting : MonoBehaviour
{
public List<GameObject> plantPrefabs = new List<GameObject>();
public List<Button> plantButtons = new List<Button>();
public List<Tilemap> levelTilemapsAscending = new List<Tilemap>();
private Mana myMana;
private int plantIndex = 100;
private bool[] plantable;
private float[] manaValues = { 15.0f, 30.0f, 22.0f, 25.0f, 40.0f };
//private Calculations calculation = new Calculations();
//the position the character is currently placed at in world coordinates
protected Vector3 characterPosition;
//the distance between the clicked spot and the character
private float distanceToCharacter = 0.0f;
private LevelManager levelManager;
[SerializeField]
private AudioSource plantingSound;
void Start()
{
plantable = new bool[plantPrefabs.Count];
for (int i = 0; i < plantable.Length; i++)
{
plantable[i] = true;
}
myMana = GetComponent<Mana>();
levelManager = LevelManager.GetInstance();
}
// Update is called once per frame
void Update()
{
//When the Input system detects the left mouse button is clicked, flowers are spawned
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse clicked.");
SpawnPlants();
}
}
//Plants a plant at the clicked location
void SpawnPlants()
{
//detect the position of the mouse and convert the coordinates to world coordinates
Vector3 clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
clickPosition.z = 0; //set to 0, because we are working with 2D
//get the current character position by accessing the transform of the game object this script is attached to
characterPosition = transform.position;
//calculate the distance
distanceToCharacter = Vector3.Distance(clickPosition, characterPosition);
Debug.Log("Click distance: " + distanceToCharacter);
//if the distance is small enough (value can be altered to need)
if (distanceToCharacter < 1.7)
{
//plant the selected plant
if (plantIndex < plantPrefabs.Count && plantable[plantIndex])
{
if (levelManager.GetCurrentMana() >= manaValues[plantIndex])
{
plantingSound.Play();
plantable[plantIndex] = false;
Instantiate(plantPrefabs[plantIndex], clickPosition, Quaternion.identity);
myMana.UseMana(manaValues[plantIndex]);
plantButtons[plantIndex].GetComponent<ButtonCooldown>().StartCooldown();
StartCoroutine(PlantCooldown(plantIndex));
}
else
{
Debug.Log("Not enough mana.");
//can't plant stuff cause not enough mana
}
}
}
}
public void SetPlantType (int newPlantIndex)
{
plantIndex = newPlantIndex;
}
IEnumerator PlantCooldown(int currentIndex)
{
//configure cooldown times for each type of plant seperately
switch (currentIndex)
{
case 0:
yield return new WaitForSeconds(3);
break;
case 1:
yield return new WaitForSeconds(12);
break;
case 2:
yield return new WaitForSeconds(7);
break;
case 3:
yield return new WaitForSeconds(7);
break;
case 4:
yield return new WaitForSeconds(17);
break;
}
plantable[currentIndex] = true;
}
}
| 34.118644 | 117 | 0.599851 | [
"MIT"
] | Liktoria/Anoixi | Assets/Scripts/Planting.cs | 4,028 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode
{
public static class Tools
{
public static char ToUpper(char c)
{
if('a' <= c && c <= 'z')
c = (char)(c & ~0x20);
return c;
}
public static char ToLower(char c)
{
if('A' <= c && c <= 'Z')
c = (char)(c | 0x20);
return c;
}
public static string Print(this int[,] m)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m.GetLength(0); i++)
{
for (int j = 0; j < m.GetLength(1); j++)
sb.Append((m[i, j]).ToString().PadLeft(4));
sb.AppendLine();
}
return sb.ToString();
}
public static string Print(this IList<int> l)
{
StringBuilder sb = new StringBuilder();
foreach (var item in l)
{
sb.AppendFormat("{0} ", item);
}
return sb.ToString();
}
public static string Print(this string[] l)
{
StringBuilder sb = new StringBuilder();
foreach(var item in l)
{
sb.AppendFormat("{0} ", item);
}
return sb.ToString();
}
public static string Print(this int[][] arr)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
sb.Append(arr[i][j].ToString().PadLeft(4));
sb.AppendLine();
}
return sb.ToString();
}
}
}
| 24.533333 | 63 | 0.429891 | [
"MIT"
] | YaoYilin/LeetCode | LeetCode/Tools.cs | 1,842 | C# |
// <copyright file="FirefoxExtension.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using OpenQA.Selenium.Internal;
using System.IO.Compression;
namespace OpenQA.Selenium.Firefox
{
/// <summary>
/// Provides the ability to install extensions into a <see cref="FirefoxProfile"/>.
/// </summary>
public class FirefoxExtension
{
private const string EmNamespaceUri = "http://www.mozilla.org/2004/em-rdf#";
private string extensionFileName;
private string extensionResourceId;
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxExtension"/> class.
/// </summary>
/// <param name="fileName">The name of the file containing the Firefox extension.</param>
/// <remarks>WebDriver attempts to resolve the <paramref name="fileName"/> parameter
/// by looking first for the specified file in the directory of the calling assembly,
/// then using the full path to the file, if a full path is provided.</remarks>
public FirefoxExtension(string fileName)
: this(fileName, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxExtension"/> class.
/// </summary>
/// <param name="fileName">The name of the file containing the Firefox extension.</param>
/// <param name="resourceId">The ID of the resource within the assembly containing the extension
/// if the file is not present in the file system.</param>
/// <remarks>WebDriver attempts to resolve the <paramref name="fileName"/> parameter
/// by looking first for the specified file in the directory of the calling assembly,
/// then using the full path to the file, if a full path is provided. If the file is
/// not found in the file system, WebDriver attempts to locate a resource in the
/// executing assembly with the name specified by the <paramref name="resourceId"/>
/// parameter.</remarks>
internal FirefoxExtension(string fileName, string resourceId)
{
this.extensionFileName = fileName;
this.extensionResourceId = resourceId;
}
/// <summary>
/// Installs the extension into a profile directory.
/// </summary>
/// <param name="profileDir">The Firefox profile directory into which to install the extension.</param>
public void Install(string profileDir)
{
DirectoryInfo info = new DirectoryInfo(profileDir);
string stagingDirectoryName = Path.Combine(Path.GetTempPath(), info.Name + ".staging");
string tempFileName = Path.Combine(stagingDirectoryName, Path.GetFileName(this.extensionFileName));
if (Directory.Exists(tempFileName))
{
Directory.Delete(tempFileName, true);
}
// First, expand the .xpi archive into a temporary location.
Directory.CreateDirectory(tempFileName);
Stream zipFileStream = ResourceUtilities.GetResourceStream(this.extensionFileName, this.extensionResourceId);
using (ZipStorer extensionZipFile = ZipStorer.Open(zipFileStream, FileAccess.Read))
{
List<ZipStorer.ZipFileEntry> entryList = extensionZipFile.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in entryList)
{
string localFileName = entry.FilenameInZip.Replace('/', Path.DirectorySeparatorChar);
string destinationFile = Path.Combine(tempFileName, localFileName);
extensionZipFile.ExtractFile(entry, destinationFile);
}
}
// Then, copy the contents of the temporarly location into the
// proper location in the Firefox profile directory.
string id = ReadIdFromInstallRdf(tempFileName);
string extensionDirectory = Path.Combine(Path.Combine(profileDir, "extensions"), id);
if (Directory.Exists(extensionDirectory))
{
Directory.Delete(extensionDirectory, true);
}
Directory.CreateDirectory(extensionDirectory);
FileUtilities.CopyDirectory(tempFileName, extensionDirectory);
// By deleting the staging directory, we also delete the temporarily
// expanded extension, which we copied into the profile.
FileUtilities.DeleteDirectory(stagingDirectoryName);
}
private static string ReadIdFromInstallRdf(string root)
{
string id = null;
try
{
string installRdf = Path.Combine(root, "install.rdf");
XmlDocument rdfXmlDocument = new XmlDocument();
rdfXmlDocument.Load(installRdf);
XmlNamespaceManager rdfNamespaceManager = new XmlNamespaceManager(rdfXmlDocument.NameTable);
rdfNamespaceManager.AddNamespace("em", EmNamespaceUri);
rdfNamespaceManager.AddNamespace("RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
XmlNode idNode = rdfXmlDocument.SelectSingleNode("//em:id", rdfNamespaceManager);
if (idNode == null)
{
XmlNode descriptionNode = rdfXmlDocument.SelectSingleNode("//RDF:Description", rdfNamespaceManager);
XmlAttribute idAttribute = descriptionNode.Attributes["id", EmNamespaceUri];
if (idAttribute == null)
{
throw new WebDriverException("Cannot locate node containing extension id: " + installRdf);
}
id = idAttribute.Value;
}
else
{
id = idNode.InnerText;
}
if (string.IsNullOrEmpty(id))
{
throw new FileNotFoundException("Cannot install extension with ID: " + id);
}
}
catch (Exception e)
{
throw new WebDriverException("Error installing extension", e);
}
return id;
}
}
}
| 45.322785 | 121 | 0.628543 | [
"Apache-2.0"
] | BlackSmith/selenium | dotnet/src/webdriver/Firefox/FirefoxExtension.cs | 7,163 | C# |
using Api.Domain.Interfaces.Services.User;
using Api.Service.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Api.CrossCutting.DependencyInjection
{
public class ConfigureService
{
public static void ConfigureDependenciesService(IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IUserService, UserService>();
serviceCollection.AddTransient<ILoginService, LoginService>();
}
}
}
| 28.789474 | 93 | 0.753199 | [
"MIT"
] | ronaldokz33/DDD | Api.CrossCutting/DependencyInjection/ConfigureService.cs | 549 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace StreamJsonRpc
{
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using StreamJsonRpc.Protocol;
/// <summary>
/// An abstract base class for for sending and receiving messages over a
/// reading and writing pair of <see cref="Stream"/> objects.
/// </summary>
public abstract class StreamMessageHandler : MessageHandlerBase
{
/// <summary>
/// Initializes a new instance of the <see cref="StreamMessageHandler"/> class.
/// </summary>
/// <param name="sendingStream">The stream used to transmit messages. May be null.</param>
/// <param name="receivingStream">The stream used to receive messages. May be null.</param>
/// <param name="formatter">The formatter to use to serialize <see cref="JsonRpcMessage"/> instances.</param>
protected StreamMessageHandler(Stream? sendingStream, Stream? receivingStream, IJsonRpcMessageFormatter formatter)
: base(formatter)
{
Requires.Argument(sendingStream is null || sendingStream.CanWrite, nameof(sendingStream), Resources.StreamMustBeWriteable);
Requires.Argument(receivingStream is null || receivingStream.CanRead, nameof(receivingStream), Resources.StreamMustBeReadable);
this.SendingStream = sendingStream;
this.ReceivingStream = receivingStream;
}
/// <summary>
/// Gets a value indicating whether this message handler has a receiving stream.
/// </summary>
public override bool CanRead => this.ReceivingStream is not null;
/// <summary>
/// Gets a value indicating whether this message handler has a sending stream.
/// </summary>
public override bool CanWrite => this.SendingStream is not null;
/// <summary>
/// Gets the stream used to transmit messages. May be null.
/// </summary>
protected Stream? SendingStream { get; }
/// <summary>
/// Gets the stream used to receive messages. May be null.
/// </summary>
protected Stream? ReceivingStream { get; }
/// <summary>
/// Disposes resources allocated by this instance.
/// </summary>
/// <param name="disposing"><c>true</c> when being disposed; <c>false</c> when being finalized.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.ReceivingStream?.Dispose();
this.SendingStream?.Dispose();
base.Dispose(disposing);
}
}
/// <summary>
/// Calls <see cref="Stream.FlushAsync()"/> on the <see cref="SendingStream"/>,
/// or equivalent sending stream if using an alternate transport.
/// </summary>
/// <returns>A <see cref="Task"/> that completes when the write buffer has been transmitted.</returns>
protected override ValueTask FlushAsync(CancellationToken cancellationToken)
{
Verify.Operation(this.SendingStream is not null, "No sending stream.");
return new ValueTask(this.SendingStream.FlushAsync(cancellationToken));
}
}
}
| 42.6375 | 139 | 0.635884 | [
"MIT"
] | Microsoft/vs-streamjsonrpc | src/StreamJsonRpc/StreamMessageHandler.cs | 3,413 | C# |
using System;
using System.IO;
using System.Security.Principal;
using System.Threading;
namespace Leayal.PSO2Launcher.AdminProcess
{
public static class AdminProcess
{
private const string UniqueName = "pso2lealauncher-v4-elevate";
public static readonly bool IsCurrentProcessAdmin;
static AdminProcess()
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
var principal = new WindowsPrincipal(identity);
// If is administrator, the variable updates from False to True
IsCurrentProcessAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
public static bool InitializeProcess(string[] args)
{
using (var mutex = new Mutex(true, Path.Combine("Local", UniqueName), out var isNew))
{
if (isNew)
{
try
{
if (args.Length == 2 && string.Equals(args[0], "--elevate-process", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(args[1]))
{
return true;
}
else
{
return false;
}
}
finally
{
mutex.ReleaseMutex();
}
}
}
return false;
}
public static bool IsRunning
{
get
{
if (Mutex.TryOpenExisting(UniqueName, out var mutex))
{
mutex.Dispose();
return true;
}
else
{
return false;
}
}
}
}
} | 29.907692 | 167 | 0.439815 | [
"MIT"
] | Leayal/PSO2-Launcher-CSharp | AdminProcess/AdminProcess.cs | 1,946 | C# |
using SF.Data.Models;
using SF.Metadata;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SF.Bizness.Accounting
{
public class BalanceNotEnough : PublicInvalidOperationException
{
public decimal Current { get; }
public decimal Required { get; }
public BalanceNotEnough(decimal Current, decimal Required) : base("余额不足") {
this.Current = Current;
this.Required = Required;
}
}
public class Account
{
public decimal Inbound { get; set; }
public decimal Outbound { get; set; }
}
[EntityObject("账户")]
public class AccountInternal : ObjectEntityBase
{
[Display(Name ="用户ID")]
[TableVisible]
[Key]
[EntityIdent("用户",nameof(OwnerName))]
public int OwnerId { get; set; }
[Key]
[EntityIdent("账户类别", nameof(TypeName))]
[TableVisible]
[Display(Name = "类别ID")]
public int TypeId { get; set; }
[Display(Name = "用户名")]
[TableVisible]
[Ignore]
public string OwnerName { get; set; }
[Display(Name = "类别")]
[TableVisible]
[Ignore]
public string TypeName { get; set; }
[Display(Name = "余额")]
[TableVisible]
public decimal Amount { get; set; }
[Display(Name = "转入")]
[TableVisible]
public decimal Inbound { get; set; }
[Display(Name = "转出")]
[TableVisible]
public decimal Outbound { get; set; }
}
}
| 24.373134 | 83 | 0.583588 | [
"Apache-2.0"
] | etechi/ServiceFramework | Projects/Server/Common/SF.Common.Abstractions/Bizness/Accounting/Account.cs | 1,689 | C# |
using System;
using System.IO;
using System.Windows.Media.Imaging;
namespace Image.Import
{
class Metadata
{
public Metadata(FileInfo file)
{
using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var frame = BitmapFrame.Create(fs);
var metadata = (BitmapMetadata)frame.Metadata;
DateTaken = DateTime.Parse(metadata.DateTaken);
}
}
public DateTime DateTaken { get; }
}
}
| 24.652174 | 107 | 0.559083 | [
"MIT"
] | Calteo/Image.Import | src/Image.Import/Metadata.cs | 569 | C# |
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.EndpointSpecifications
{
using System.Collections.Generic;
using System.Linq;
using Builders;
using GreenPipes;
using Pipeline;
public class EndpointConfiguration :
IEndpointConfiguration
{
protected EndpointConfiguration(ITopologyConfiguration topology, IConsumePipe consumePipe = null)
{
Topology = topology;
Consume = new ConsumePipeConfiguration(consumePipe);
Send = new SendPipeConfiguration(topology.Send);
Publish = new PublishPipeConfiguration(topology.Publish);
Serialization = new SerializationConfiguration();
}
protected EndpointConfiguration(IEndpointConfiguration parentConfiguration, ITopologyConfiguration topology, IConsumePipe consumePipe = null)
{
Topology = topology;
Consume = new ConsumePipeConfiguration(parentConfiguration.Consume.Specification, consumePipe);
Send = new SendPipeConfiguration(parentConfiguration.Send.Specification);
Publish = new PublishPipeConfiguration(parentConfiguration.Publish.Specification);
Serialization = parentConfiguration.Serialization.CreateSerializationConfiguration();
}
public IEnumerable<ValidationResult> Validate()
{
return Send.Specification.Validate()
.Concat(Publish.Specification.Validate())
.Concat(Consume.Specification.Validate())
.Concat(Topology.Send.Validate())
.Concat(Topology.Publish.Validate())
.Concat(Topology.Consume.Validate());
}
public IConsumePipeConfiguration Consume { get; }
public ISendPipeConfiguration Send { get; }
public IPublishPipeConfiguration Publish { get; }
public ITopologyConfiguration Topology { get; }
public ISerializationConfiguration Serialization { get; }
}
} | 42.238095 | 150 | 0.677565 | [
"Apache-2.0"
] | aallfredo/MassTransitPHP | src/MassTransit/Configuration/EndpointSpecifications/EndpointConfiguration.cs | 2,663 | C# |
using System.Collections.Generic;
namespace ClojureExtension.Repl
{
public class ReplState
{
private readonly int _promptPosition;
private readonly LinkedList<string> _history;
public ReplState() : this(0, new LinkedList<string>())
{
}
public ReplState(int promptPosition, LinkedList<string> history)
{
_promptPosition = promptPosition;
_history = history;
}
public LinkedList<string> History
{
get { return new LinkedList<string>(_history); }
}
public int PromptPosition
{
get { return _promptPosition; }
}
public ReplState ChangePromptPosition(int position)
{
return new ReplState(position, History);
}
public ReplState ChangeHistory(LinkedList<string> history)
{
return new ReplState(PromptPosition, history);
}
}
} | 20.268293 | 67 | 0.684717 | [
"MIT"
] | ragnard/vsClojure | ClojureExtension.Repl/ReplState.cs | 833 | C# |
namespace BookATable.GUI
{
using System;
using System.Globalization;
using System.Windows.Forms;
using BookATable.Common;
using Entities;
public partial class FormAddEditRestaurant : Form
{
private Restaurant restaurant;
private const string AddEditRestaurantDisplay = "Add-Edit Restaurant";
public FormAddEditRestaurant(Restaurant restaurant)
{
InitializeComponent();
this.restaurant = restaurant;
}
private void FormAddEditRestaurant_Load(object sender, EventArgs e)
{
try
{
this.Text = string.Format("{0} - Book a Table", restaurant.Id > 0 ? "Edit restaurant" : "Add restaurant");
textBoxRestaurantName.Text = restaurant.Name;
textBoxAddress.Text = restaurant.Address;
textBoxPhone.Text = restaurant.Phone;
numUpDownCapacity.Value = restaurant.Capacity;
if (restaurant.OpenHour != null && restaurant.CloseHour != null)
{
dateTimePickerOpen.Value = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + restaurant.OpenHour, CultureInfo.CurrentCulture);
dateTimePickerClose.Value = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + restaurant.CloseHour, CultureInfo.CurrentCulture);
}
}
catch (Exception ex)
{
throw new ApplicationException(string.Format(ErrorMessages.ErrorMessageTemplate, AddEditRestaurantDisplay), ex);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
restaurant.Name = textBoxRestaurantName.Text;
restaurant.Address = textBoxAddress.Text;
restaurant.Phone = textBoxPhone.Text;
restaurant.Capacity = (int)numUpDownCapacity.Value;
restaurant.OpenHour = dateTimePickerOpen.Value.ToString(GlobalConstants.HourFormat);
restaurant.CloseHour = dateTimePickerClose.Value.ToString(GlobalConstants.HourFormat);
if (string.IsNullOrEmpty(textBoxRestaurantName.Text) || string.IsNullOrEmpty(textBoxAddress.Text) || string.IsNullOrEmpty(textBoxPhone.Text))
{
this.DialogResult = DialogResult.Abort;
MessageBox.Show(ErrorMessages.EmptyInputFields);
}
else if ((int)numUpDownCapacity.Value <= 0)
{
this.DialogResult = DialogResult.Abort;
MessageBox.Show(ErrorMessages.InvalidCapacity);
}
}
catch (Exception ex)
{
throw new ApplicationException(string.Format(ErrorMessages.ErrorMessageTemplate, AddEditRestaurantDisplay), ex);
}
}
}
}
| 37.265823 | 157 | 0.596128 | [
"MIT"
] | PhilShishov/BookATable | BookATable/GUI/FormAddEditRestaurant.cs | 2,946 | C# |
namespace Poof.Snaps
{
/// <summary>
/// Snaps specific demands to specific tasks.
/// </summary>
public interface ISnap<TResult>
{
IOutcome<TResult> Convert(IDemand demand);
}
}
| 19.272727 | 50 | 0.608491 | [
"MIT"
] | g00fy88/Poof | src/Snaps/ISnap.cs | 214 | C# |
using EasyAbp.Abp.WeChat.MiniProgram.Infrastructure.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace EasyAbp.Abp.WeChat.MiniProgram.Services.Broadcast.Request
{
public class GetApprovedRequest : MiniProgramCommonRequest
{
[JsonProperty("offset")]
public int Offset { get; set; }
[JsonProperty("limit")]
public int Limit { get; set; }
[JsonProperty("status")]
public int Status { get; set; }
}
}
| 24.666667 | 67 | 0.683398 | [
"MIT"
] | Jy1233456/Abp.WeChat | src/MiniProgram/EasyAbp.Abp.WeChat.MiniProgram/Services/Broadcast/Request/GetApprovedRequest.cs | 520 | C# |
namespace Fabric.Terminology.API
{
using System;
using Catalyst.DosApi.Authorization;
using Catalyst.DosApi.Common;
using Catalyst.DosApi.Identity.Models;
using Fabric.Terminology.API.Configuration;
using Fabric.Terminology.Domain.DependencyInjection;
using Nancy.TinyIoc;
/// <summary>
/// Extension methods for Nancy's <see cref="TinyIoCContainer"/>
/// </summary>
public static partial class ApiExtensions
{
internal static TinyIoCContainer ComposeFrom<TComposition>(this TinyIoCContainer container)
where TComposition : class, IContainerComposition<TinyIoCContainer>, new()
{
var composition = new TComposition();
composition.Compose(container);
return container;
}
internal static TinyIoCContainer RegisterDosServices(
this TinyIoCContainer container,
IdentityServerSettings appConfigSettings,
Uri identityServiceUri,
Uri authorizationServiceUri,
ClientSettings webConfigSettings)
{
container.Register<ClientCredentials>(webConfigSettings.CreateClientCredentials(appConfigSettings, identityServiceUri));
container.Register<FabricServiceLocations>((c, p) => new FabricServiceLocations(identityServiceUri, authorizationServiceUri));
container.Register<IAuthenticatedApiClientFactory, AuthenticatedApiClientFactory>().AsSingleton();
container.Register<IUserPermissionsService>(
(c, p) => new UserPermissionsService(
c.Resolve<IAuthenticatedApiClientFactory>(),
c.Resolve<FabricServiceLocations>().AuthorizationServiceUri));
return container;
}
}
} | 39.533333 | 138 | 0.684092 | [
"Apache-2.0"
] | HealthCatalyst/Fabric.Terminology | Fabric.Terminology.API/ApiExtensions.TinyIoCContainer.cs | 1,779 | C# |
using System.Diagnostics;
using System.IO;
using System.Threading;
using Xunit;
namespace System.Tests
{
public class UnloadingAndProcessExitTests : RemoteExecutorTestBase
{
[Fact]
public void UnloadingEventMustHappenBeforeProcessExitEvent()
{
string fileName = GetTestFilePath();
File.WriteAllText(fileName, string.Empty);
Func<string, int> otherProcess = f =>
{
Action<int> OnUnloading = i => File.AppendAllText(f, string.Format("u{0}", i));
Action<int> OnProcessExit = i => File.AppendAllText(f, string.Format("e{0}", i));
AppDomain.CurrentDomain.ProcessExit += (sender, e) => OnProcessExit(0);
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += acl => OnUnloading(0);
AppDomain.CurrentDomain.ProcessExit += (sender, e) => OnProcessExit(1);
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += acl => OnUnloading(1);
return SuccessExitCode;
};
using (var remote = RemoteInvoke(otherProcess, fileName))
{
}
Assert.Equal(File.ReadAllText(fileName), "u0u1e0e1");
}
}
}
| 33.236842 | 101 | 0.602534 | [
"MIT"
] | cydhaselton/cfx-android | src/System.Runtime.Extensions/tests/System/UnloadingAndProcessExitTests.netcoreapp.cs | 1,265 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Serilog.Sinks.Queuing.Redis.ElasticHook.Extensions;
public static class ElasticExtensions
{
public static IServiceCollection AddElasticRedisStreamHook(this IServiceCollection services, Action<IServiceProvider, ElasticHookOptions> configure)
{
services.TryAddSingleton(provider =>
{
var options = new ElasticHookOptions();
configure?.Invoke(provider, options);
return options;
});
services.TryAddSingleton<IRedisStreamHook, ElasticRedisStreamHook>();
return services;
}
} | 35.043478 | 152 | 0.617866 | [
"MIT"
] | arenchen/Serilog.Sinks.Queuing.Redis | src/Serilog.Sinks.Queuing.Redis.ElasticHook/Extensions/ElasticExtensions.cs | 806 | C# |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.DatapointFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
public class DatapointTests
{
private void RunTestOnFixture(Type fixtureType)
{
ITestResult result = TestBuilder.RunTestFixture(fixtureType);
ResultSummary summary = new ResultSummary(result);
Assert.That(summary.Passed, Is.EqualTo(2));
Assert.That(summary.Inconclusive, Is.EqualTo(3));
Assert.That(result.ResultState, Is.EqualTo(ResultState.Success));
}
[Test]
public void WorksOnField()
{
RunTestOnFixture(typeof(SquareRootTest_Field_Double));
}
[Test]
public void WorksOnArray()
{
RunTestOnFixture(typeof(SquareRootTest_Field_ArrayOfDouble));
}
[Test]
public void WorksOnPropertyReturningArray()
{
RunTestOnFixture(typeof(SquareRootTest_Property_ArrayOfDouble));
}
[Test]
public void WorksOnMethodReturningArray()
{
RunTestOnFixture(typeof(SquareRootTest_Method_ArrayOfDouble));
}
[Test]
public void WorksOnIEnumerableOfT()
{
RunTestOnFixture(typeof(SquareRootTest_Field_IEnumerableOfDouble));
}
[Test]
public void WorksOnPropertyReturningIEnumerableOfT()
{
RunTestOnFixture(typeof(SquareRootTest_Property_IEnumerableOfDouble));
}
[Test]
public void WorksOnMethodReturningIEnumerableOfT()
{
RunTestOnFixture(typeof(SquareRootTest_Method_IEnumerableOfDouble));
}
[Test]
public void WorksOnEnumeratorReturningIEnumerableOfT()
{
RunTestOnFixture(typeof(SquareRootTest_Iterator_IEnumerableOfDouble));
}
[Test]
public void WorksOnInheritedDataPoint()
{
RunTestOnFixture(typeof(DatapointCanBeInherited));
}
[Test]
public void WorksOnInheritedDataPoints()
{
RunTestOnFixture(typeof(DatapointsCanBeInherited));
}
}
} | 28.487805 | 91 | 0.636558 | [
"MIT"
] | 304NotModified/nunit | src/NUnitFramework/tests/Attributes/DatapointTests.cs | 2,338 | C# |
using System.Windows.Forms;
using GuiLabs.Canvas.Events;
namespace GuiLabs.Canvas.Shapes
{
public class ShapeWithEvents : Shape, IShapeWithEvents
{
public ShapeWithEvents()
: base()
{
}
#region Events
public event MouseWithKeysEventHandler Click;
public event MouseWithKeysEventHandler DoubleClick;
public event MouseWithKeysEventHandler MouseDown;
public event MouseWithKeysEventHandler MouseMove;
public event MouseWithKeysEventHandler MouseUp;
public event MouseWithKeysEventHandler MouseHover;
public event MouseWithKeysEventHandler MouseWheel;
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event KeyEventHandler KeyUp;
#endregion
#region RaiseMouseEvent
protected void RaiseClick(MouseEventArgsWithKeys e)
{
if (Click != null)
{
Click(e);
}
}
protected void RaiseDoubleClick(MouseEventArgsWithKeys e)
{
if (DoubleClick != null)
{
DoubleClick(e);
}
}
protected void RaiseMouseDown(MouseEventArgsWithKeys e)
{
if (MouseDown != null)
{
MouseDown(e);
}
}
protected void RaiseMouseMove(MouseEventArgsWithKeys e)
{
if (MouseMove != null)
{
MouseMove(e);
}
}
protected void RaiseMouseUp(MouseEventArgsWithKeys e)
{
if (MouseUp != null)
{
MouseUp(e);
}
}
protected void RaiseMouseHover(MouseEventArgsWithKeys e)
{
if (MouseHover != null)
{
MouseHover(e);
}
}
protected void RaiseMouseWheel(MouseEventArgsWithKeys e)
{
if (MouseWheel != null)
{
MouseWheel(e);
}
}
#endregion
#region RaiseKeyEvent
public void RaiseKeyDown(KeyEventArgs e)
{
if (KeyDown != null)
{
KeyDown(this, e);
}
}
protected void RaiseKeyPress(KeyPressEventArgs e)
{
if (KeyPress != null)
{
KeyPress(this, e);
}
}
protected void RaiseKeyUp(KeyEventArgs e)
{
if (KeyUp != null)
{
KeyUp(this, e);
}
}
#endregion
#region OnMouseEvent
public override void OnClick(MouseEventArgsWithKeys e)
{
base.OnClick(e);
RaiseClick(e);
}
public override void OnDoubleClick(MouseEventArgsWithKeys e)
{
base.OnDoubleClick(e);
RaiseDoubleClick(e);
}
public override void OnMouseDown(MouseEventArgsWithKeys e)
{
base.OnMouseDown(e);
RaiseMouseDown(e);
}
public override void OnMouseMove(MouseEventArgsWithKeys e)
{
base.OnMouseMove(e);
RaiseMouseMove(e);
}
public override void OnMouseUp(MouseEventArgsWithKeys e)
{
base.OnMouseUp(e);
RaiseMouseUp(e);
}
public override void OnMouseHover(MouseEventArgsWithKeys e)
{
base.OnMouseHover(e);
RaiseMouseHover(e);
}
public override void OnMouseWheel(MouseEventArgsWithKeys e)
{
base.OnMouseWheel(e);
RaiseMouseWheel(e);
}
#endregion
#region OnKeyEvent
public override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
RaiseKeyDown(e);
}
public override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
RaiseKeyPress(e);
}
public override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
RaiseKeyUp(e);
}
#endregion
}
}
| 17.898396 | 63 | 0.651031 | [
"MIT"
] | KirillOsenkov/LiveGeometry | Reference/VB.NET/Canvas/Shapes/ShapeWithEvents.cs | 3,347 | C# |
namespace SqlStreamStore
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Streams;
using Xunit;
using static Streams.Deleted;
public partial class AcceptanceTests
{
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_message_then_message_should_be_removed_from_stream()
{
const string streamId = "stream";
var newStreamMessages = CreateNewStreamMessages(1, 2, 3);
await Store.AppendToStream(streamId, ExpectedVersion.NoStream, newStreamMessages);
var idToDelete = newStreamMessages[1].MessageId;
await Store.DeleteMessage(streamId, idToDelete);
var streamMessagesPage = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 3);
streamMessagesPage.Messages.Length.ShouldBe(2);
streamMessagesPage.Messages.Any(e => e.MessageId == idToDelete).ShouldBeFalse();
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_message_then_deleted_message_should_be_appended_to_deleted_stream()
{
const string streamId = "stream";
var newStreamMessages = CreateNewStreamMessages(1, 2, 3);
await Store.AppendToStream(streamId, ExpectedVersion.NoStream, newStreamMessages);
var messageIdToDelete = newStreamMessages[1].MessageId;
await Store.DeleteMessage(streamId, messageIdToDelete);
var page = await Store.ReadStreamBackwards(DeletedStreamId, StreamVersion.End, 1);
var message = page.Messages.Single();
var messageDeleted = await message.GetJsonDataAs<MessageDeleted>();
message.Type.ShouldBe(MessageDeletedMessageType);
messageDeleted.StreamId.ShouldBe(streamId);
messageDeleted.MessageId.ShouldBe(messageIdToDelete);
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_message_that_does_not_exist_then_nothing_should_happen()
{
const string streamId = "stream";
var newStreamMessages = CreateNewStreamMessages(1, 2, 3);
await Store.AppendToStream(streamId, ExpectedVersion.NoStream, newStreamMessages);
var initialHead = await Store.ReadHeadPosition();
await Store.DeleteMessage(streamId, Guid.NewGuid());
var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 3);
page.Messages.Length.ShouldBe(3);
var subsequentHead = await Store.ReadHeadPosition();
subsequentHead.ShouldBe(initialHead);
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_last_message_in_stream_and_append_then_it_should_have_subsequent_version_number()
{
const string streamId = "stream";
var messages = CreateNewStreamMessages(1, 2, 3);
await Store.AppendToStream(streamId, ExpectedVersion.NoStream, messages);
await Store.DeleteMessage(streamId, messages.Last().MessageId);
messages = CreateNewStreamMessages(4);
await Store.AppendToStream(streamId, 2, messages);
var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 3);
page.Messages.Length.ShouldBe(3);
page.LastStreamVersion.ShouldBe(3);
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_a_messages_from_stream_with_then_can_read_all_forwards()
{
string streamId = "stream-1";
await AppendMessages(Store, streamId, 2);
var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
await Store.DeleteMessage(streamId, page.Messages.First().MessageId);
page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
page.Messages.Length.ShouldBe(1);
page.LastStreamVersion.ShouldBe(1);
page.NextStreamVersion.ShouldBe(2);
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_all_messages_from_stream_with_1_messages_then_can_read_all_forwards()
{
string streamId = "stream-1";
await AppendMessages(Store, streamId, 1);
var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
await Store.DeleteMessage(streamId, page.Messages[0].MessageId);
page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
page.Messages.Length.ShouldBe(0);
page.LastStreamVersion.ShouldBe(0);
page.NextStreamVersion.ShouldBe(1);
}
[Fact, Trait("Category", "DeleteEvent")]
public async Task When_delete_all_messages_from_stream_with_multiple_messages_then_can_read_all_forwards()
{
string streamId = "stream-1";
await AppendMessages(Store, streamId, 2);
var page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
await Store.DeleteMessage(streamId, page.Messages[0].MessageId);
await Store.DeleteMessage(streamId, page.Messages[1].MessageId);
page = await Store.ReadStreamForwards(streamId, StreamVersion.Start, 2);
page.Messages.Length.ShouldBe(0);
page.LastStreamVersion.ShouldBe(1);
page.NextStreamVersion.ShouldBe(2);
}
[Theory, Trait("Category", "DeleteEvent")]
[InlineData("stream/id")]
[InlineData("stream%id")]
public async Task When_delete_stream_message_with_url_encodable_characters_then_should_not_throw(
string streamId)
{
var newStreamMessages = CreateNewStreamMessages(1);
await Store.AppendToStream(streamId, ExpectedVersion.NoStream, newStreamMessages);
await Store.DeleteMessage(streamId, newStreamMessages[0].MessageId);
}
}
} | 44.233577 | 119 | 0.666832 | [
"MIT"
] | ArneSchoonvliet/SQLStreamStore | tests/SqlStreamStore.AcceptanceTests/AcceptanceTests.DeleteEvent.cs | 6,062 | C# |
namespace ExaLearn.Dal.Entities
{
public class UserAnswer
{
public int Id { get; set; }
public int PassedTestId { get; set; }
public PassedTest PassedTest { get; set; }
public int QuestionId { get; set; }
public Question Question { get; set; }
public string ReportedMessage { get; set; }
public string Answer { get; set; }
public int Assessment { get; set; }
}
}
| 20.681818 | 59 | 0.571429 | [
"MIT"
] | ExadelSandbox/project | exalearn-api/ExaLearn.Dal/Entities/UserAnswer.cs | 457 | C# |
using System;
using Ministry;
using Umbraco.Core.Models;
using Umbraco.Pylon.Models;
using Umbraco.Web;
namespace Umbraco.Pylon
{
#region | Interface |
/// <summary>
/// Repository to access non-relative site content elements and collections.
/// </summary>
public interface IPublishedContentRepository
{
/// <summary>
/// Sets the umbraco helper.
/// </summary>
/// <remarks>
/// Used to set the helper within a view when using <see cref="PylonViewPage"/>.
/// </remarks>
UmbracoHelper Umbraco { set; }
/// <summary>
/// Gets or Sets the umbraco context.
/// </summary>
/// <remarks>
/// Used to set the context within a view when using <see cref="PylonViewPage"/>.
/// </remarks>
UmbracoContext Context { get; set; }
/// <summary>
/// Determines if a piece of media exists.
/// </summary>
/// <param name="nodeId">The media id.</param>
/// <returns>A flag</returns>
bool MediaExists(int? nodeId);
/// <summary>
/// Gets the media item.
/// </summary>
/// <param name="nodeId">The id of the item.</param>
/// <returns>Content</returns>
MediaFile MediaItem(int? nodeId);
/// <summary>
/// Determines if a piece of content exists.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns>A flag</returns>
bool ContentExists(int? nodeId);
/// <summary>
/// Returns the content at a specific node.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns>Content</returns>
IPublishedContent Content(int? nodeId);
}
#endregion
/// <summary>
/// Repository to access non-relative site content elements and collections.
/// </summary>
public class PublishedContentRepository : IPublishedContentRepository
{
private UmbracoContext context;
private UmbracoHelper umbraco;
#region | Construction |
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRepository" /> class.
/// </summary>
/// <param name="umbraco">The umbraco helper.</param>
/// <param name="context">The context.</param>
public PublishedContentRepository(UmbracoHelper umbraco, UmbracoContext context)
{
this.umbraco = umbraco.ThrowIfNull(nameof(umbraco));
this.context = context.ThrowIfNull(nameof(context));
}
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRepository"/> class.
/// </summary>
/// <param name="umbraco">The umbraco helper.</param>
public PublishedContentRepository(UmbracoHelper umbraco)
{
this.umbraco = umbraco.ThrowIfNull(nameof(umbraco));
}
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRepository"/> class.
/// </summary>
/// <remarks>
/// If constructed without an Umbraco helper instance, the helper must be set before any methods are called.
/// </remarks>
public PublishedContentRepository()
{ }
#endregion
/// <summary>
/// Gets or sets the umbraco helper.
/// </summary>
/// <remarks>
/// The set is used to set the helper within a view when using <see cref="PylonViewPage"/>.
/// </remarks>
public UmbracoHelper Umbraco
{
protected get
{
if (umbraco == null)
throw new ApplicationException("Unable to use methods on the Content Repository until the UmbracoHelper instance is set. " +
"Either use the constructor that thakes a helper or check your IoC configuration.");
return umbraco;
}
set => umbraco = value;
}
/// <summary>
/// Gets or sets the umbraco helper.
/// </summary>
/// <remarks>
/// The set is used to set the helper within a view when using <see cref="PylonViewPage"/>.
/// </remarks>
public UmbracoContext Context
{
get
{
if (context == null)
throw new ApplicationException("No context is available. " +
"Either use the constructor that thakes a context or check your IoC configuration.");
return context;
}
set => context = value;
}
/// <summary>
/// Determines if a piece of media exists.
/// </summary>
/// <param name="nodeId">The media id.</param>
/// <returns>A flag</returns>
public bool MediaExists(int? nodeId) => MediaItem(nodeId) != null;
/// <summary>
/// Gets the media item.
/// </summary>
/// <param name="nodeId">The id of the item.</param>
/// <returns>Content</returns>
public MediaFile MediaItem(int? nodeId)
=> nodeId == null || nodeId.Value == 0 ? null : new MediaFile(Umbraco.TypedMedia(nodeId));
/// <summary>
/// Determines if a piece of content exists.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns>A flag</returns>
public bool ContentExists(int? nodeId) => Content(nodeId) != null;
/// <summary>
/// Returns the content at a specific node.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns>Content</returns>
public IPublishedContent Content(int? nodeId)
=> nodeId == null || nodeId.Value == 0 ? null : Umbraco.TypedContent(nodeId);
}
}
| 34.736842 | 144 | 0.551178 | [
"MIT"
] | ministryotech/Umbraco.Pylon | Umbraco.Pylon/PublishedContentRepository.cs | 5,942 | C# |
// Generated by TankLibHelper
// ReSharper disable All
namespace TankLib.STU.Types
{
[STU(0x6B892D91, 8)]
public class STUUXObject : STUInstance
{
}
}
| 15.272727 | 42 | 0.678571 | [
"MIT"
] | Pandaaa2507/OWLib | TankLib/STU/Types/STUUXObject.cs | 168 | C# |
namespace UglyToad.PdfPig.Tests
{
using System.Collections.Generic;
using PdfPig.Filters;
using PdfPig.Tokens;
internal class TestFilterProvider : IFilterProvider
{
public IReadOnlyList<IFilter> GetFilters(DictionaryToken dictionary)
{
return new List<IFilter>();
}
public IReadOnlyList<IFilter> GetAllFilters()
{
return new List<IFilter>();
}
}
} | 23.473684 | 76 | 0.623318 | [
"Apache-2.0"
] | BenyErnest/PdfPig | src/UglyToad.PdfPig.Tests/TestFilterProvider.cs | 448 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Repository
* 容器镜像仓库相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Containerregistry.Model;
namespace JDCloudSDK.Containerregistry.Apis
{
/// <summary>
/// 描述用户指定 registry 下的 repository.
/// ///
/// </summary>
public class DescribeRepositoriesResult : JdcloudResult
{
///<summary>
/// Repositories
///</summary>
public List<Repository> Repositories{ get; set; }
///<summary>
/// TotalCount
///</summary>
public double? TotalCount{ get; set; }
}
} | 26.096154 | 76 | 0.670597 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Containerregistry/Apis/DescribeRepositoriesResult.cs | 1,393 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Container for the parameters to the AttachInstancesToLoadBalancer operation.
/// Attaches one or more Lightsail instances to a load balancer.
///
///
/// <para>
/// After some time, the instances are attached to the load balancer and the health check
/// status is available.
/// </para>
///
/// <para>
/// The <code>attach instances to load balancer</code> operation supports tag-based access
/// control via resource tags applied to the resource identified by <code>load balancer
/// name</code>. For more information, see the <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-controlling-access-using-tags">Lightsail
/// Developer Guide</a>.
/// </para>
/// </summary>
public partial class AttachInstancesToLoadBalancerRequest : AmazonLightsailRequest
{
private List<string> _instanceNames = new List<string>();
private string _loadBalancerName;
/// <summary>
/// Gets and sets the property InstanceNames.
/// <para>
/// An array of strings representing the instance name(s) you want to attach to your load
/// balancer.
/// </para>
///
/// <para>
/// An instance must be <code>running</code> before you can attach it to your load balancer.
/// </para>
///
/// <para>
/// There are no additional limits on the number of instances you can attach to your load
/// balancer, aside from the limit of Lightsail instances you can create in your account
/// (20).
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<string> InstanceNames
{
get { return this._instanceNames; }
set { this._instanceNames = value; }
}
// Check to see if InstanceNames property is set
internal bool IsSetInstanceNames()
{
return this._instanceNames != null && this._instanceNames.Count > 0;
}
/// <summary>
/// Gets and sets the property LoadBalancerName.
/// <para>
/// The name of the load balancer.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string LoadBalancerName
{
get { return this._loadBalancerName; }
set { this._loadBalancerName = value; }
}
// Check to see if LoadBalancerName property is set
internal bool IsSetLoadBalancerName()
{
return this._loadBalancerName != null;
}
}
} | 34.601942 | 173 | 0.62991 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/AttachInstancesToLoadBalancerRequest.cs | 3,564 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using RunChallenge.MVC.Models;
using RunChallenge.Models;
namespace RunChallenge.MVC.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
private ApplicationSignInManager _signInManager;
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { _signInManager = value; }
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
// model.UserName was model.Email
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());
if (user != null)
{
var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider);
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new User { UserName = model.UserName, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new User { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
} | 36.431915 | 173 | 0.559832 | [
"MIT"
] | bstaykov/RunChallenge | RunChallenge.MVC/Controllers/AccountController.cs | 17,125 | C# |
using MP.SimpleTokens.Token.Contracts;
using Refit;
namespace MP.SimpleTokens.Token.Clients
{
public interface IBasicDetailsClient
{
[Get("/basicdetails/{id}")]
Task<PublicTokenSummary> GetSummary(string id);
}
} | 22 | 55 | 0.698347 | [
"MIT-0"
] | mparker42/MP.SimpleTokens.Token | MP.SimpleTokens.Token.Clients/IBasicDetailsClient.cs | 244 | C# |
using DevelopmentInProgress.TradeView.Wpf.Common.Cache;
using DevelopmentInProgress.TradeView.Wpf.Common.Model;
using DevelopmentInProgress.TradeView.Wpf.Common.Services;
using DevelopmentInProgress.TradeView.Wpf.Common.ViewModel;
using DevelopmentInProgress.TradeView.Wpf.Controls.Messaging;
using DevelopmentInProgress.TradeView.Wpf.Host.Controller.Context;
using DevelopmentInProgress.TradeView.Wpf.Host.Controller.ViewModel;
using Prism.Logging;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
namespace DevelopmentInProgress.TradeView.Wpf.Dashboard.ViewModel
{
public class AccountsViewModel : DocumentViewModel
{
private readonly IAccountsService accountsService;
private readonly IWpfExchangeService exchangeService;
private readonly ISymbolsCacheFactory symbolsCacheFactory;
private readonly ILoggerFacade logger;
private bool disposed;
public AccountsViewModel(
ViewModelContext viewModelContext,
IAccountsService accountsService,
IWpfExchangeService exchangeService,
ISymbolsCacheFactory symbolsCacheFactory,
ILoggerFacade logger)
: base(viewModelContext)
{
this.accountsService = accountsService;
this.exchangeService = exchangeService;
this.symbolsCacheFactory = symbolsCacheFactory;
this.logger = logger;
Accounts = new ObservableCollection<AccountViewModel>();
}
public ObservableCollection<AccountViewModel> Accounts { get; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Exceptions are routed back to subscribers.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects get disposed in the Dispose method.")]
protected async override void OnPublished(object data)
{
IsBusy = true;
try
{
ClearAccounts();
var accounts = await accountsService.GetAccountsAsync().ConfigureAwait(true);
var loginTasks = new Task[accounts.Accounts.Count];
for (int i = 0; i < accounts.Accounts.Count; i++)
{
var userAccount = accounts.Accounts[i];
if (!string.IsNullOrWhiteSpace(userAccount.ApiKey))
{
var account = new Account(new Core.Model.AccountInfo { User = new Core.Model.User() })
{
AccountName = userAccount.AccountName,
ApiKey = userAccount.ApiKey,
ApiSecret = userAccount.ApiSecret,
ApiPassPhrase = userAccount.ApiPassPhrase,
Exchange = userAccount.Exchange
};
var accountViewModel = new AccountViewModel(
new AccountBalancesViewModel(exchangeService, symbolsCacheFactory, logger),
new OrdersViewModel(exchangeService, logger),
logger);
accountViewModel.Dispatcher = ViewModelContext.UiDispatcher;
accountViewModel.SetAccount(account);
loginTasks[i] = accountViewModel.Login();
Accounts.Add(accountViewModel);
}
}
await Task.WhenAll(loginTasks).ConfigureAwait(true);
}
catch (Exception ex)
{
ShowMessage(new Message { MessageType = MessageType.Error, Text = ex.Message, TextVerbose = ex.StackTrace });
}
finally
{
IsBusy = false;
}
}
protected override void OnDisposing()
{
if (disposed)
{
return;
}
ClearAccounts();
disposed = true;
}
private void ClearAccounts()
{
if (Accounts.Any())
{
var items = Accounts.Count;
for (int i = items - 1; i >= 0; i--)
{
var accountViewModel = Accounts[i];
accountViewModel.Dispose();
Accounts.Remove(accountViewModel);
}
}
}
}
}
| 37.737705 | 181 | 0.579713 | [
"Apache-2.0"
] | CasparsTools/tradeview | src/DevelopmentInProgress.TradeView.Wpf.Dashboard/ViewModel/AccountsViewModel.cs | 4,606 | C# |
using System.Collections.Generic;
using NFluent;
using NUnit.Framework;
namespace Diverse.Tests
{
/// <summary>
/// All about the deterministic capabilities of the <see cref="Fuzzer"/>.
/// <remarks>
/// This test fixture has lot of tests using a specific seed provided to
/// the Fuzzer instance.
///
/// This is not representative on how to use <see cref="Fuzzer"/> instances in your code
/// base (i.e. without fixing a seed in order to go full random), but made
/// for deterministic results instead.
/// </remarks>
/// </summary>
[TestFixture]
public class FuzzerWithItsOwnDeterministicCapabilitiesShould
{
[Test]
public void Be_able_to_expose_the_Seed_we_provide_but_also_the_one_we_did_not_provide()
{
var providedSeed = 428;
var fuzzer = new Fuzzer(428);
Check.That(fuzzer.Seed).IsEqualTo(providedSeed);
var otherFuzzer = new Fuzzer();
Check.That(fuzzer.Seed).IsNotEqualTo(otherFuzzer.Seed);
}
[Test]
public void Be_Deterministic_when_specifying_an_existing_seed()
{
var seed = 1226354269;
var fuzzer = new Fuzzer(seed);
var fuzzedIntegers = new List<int>();
for (var i = 0; i < 10; i++)
{
var positiveInteger = fuzzer.GeneratePositiveInteger();
fuzzedIntegers.Add(positiveInteger);
}
//Check.That(fuzzedDecimal).IsEqualTo(720612366.000000740230018m);
Check.That(fuzzedIntegers).ContainsExactly(33828652, 221134346, 1868176041, 1437724735, 1202622988, 974525956, 1605572379, 1127364048, 1453698000, 141079432);
}
[Test]
public void Provide_different_values_when_using_different_Fuzzer_instances()
{
var deterministicFuzzer = new Fuzzer(1226354269, "first");
var randomFuzzer = new Fuzzer(name: "second");
var anotherRandomFuzzer = new Fuzzer(name: "third");
var deterministicInteger = deterministicFuzzer.GeneratePositiveInteger();
var randomInteger = randomFuzzer.GeneratePositiveInteger();
var anotherRandomInteger = anotherRandomFuzzer.GeneratePositiveInteger();
Check.That(deterministicInteger).IsEqualTo(33828652);
Check.That(deterministicInteger).IsNotEqualTo(randomInteger).And.IsNotEqualTo(anotherRandomInteger);
Check.That(randomInteger).IsNotEqualTo(anotherRandomInteger);
}
[Test]
public void Be_Deterministic_when_specifying_an_existing_seed_whatever_the_specified_name_of_the_fuzzer()
{
var seed = 1226354269;
var fuzzer = new Fuzzer(seed);
var fuzzerWithSameFeedButDifferentName = new Fuzzer(seed, "Monte-Cristo");
var valueFuzzer = fuzzer.GenerateInteger();
var valueFuzzerWithNameSpecified = fuzzerWithSameFeedButDifferentName.GenerateInteger();
Check.That(fuzzerWithSameFeedButDifferentName.Name).IsNotEqualTo(fuzzer.Name);
Check.That(valueFuzzerWithNameSpecified).IsEqualTo(valueFuzzer);
}
}
} | 40.2625 | 170 | 0.654455 | [
"Apache-2.0"
] | 42skillz/Diverse | Diverse.Tests/FuzzerWithItsOwnDeterministicCapabilitiesShould.cs | 3,223 | C# |
using System.Collections.Generic;
using System.Linq;
using CentralBackup.Core.Entities;
using CentralBackup.Core.Interfaces.Repositories;
namespace CentralBackup.Core.Repositories
{
public class ConfigurationRepository : IConfigurationRepository
{
private readonly BackupContext _backupContext;
public ConfigurationRepository(BackupContext backupContext)
{
_backupContext = backupContext;
}
public IDictionary<string, string> GetByStep(Step step)
{
return _backupContext.Configurations
.Where(p => p.Step.Id == step.Id)
.Select(p => new KeyValuePair<string, string>(p.Key, p.Value))
.ToDictionary(p => p.Key, p => p.Value);
}
}
} | 30.92 | 78 | 0.653299 | [
"MIT"
] | curcas/CentralBackup | src/CentralBackup.Core/Repositories/ConfigurationRepository.cs | 775 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChildDeparenter : MonoBehaviour {
// Start is called before the first frame update
void Start() {
foreach (Transform child in transform) {
child.SetParent(null);
}
}
}
| 21.642857 | 52 | 0.669967 | [
"MIT"
] | kivik-beep/farmasia-vr | Assets/Scripts/ChildDeparenter.cs | 305 | C# |
#if WITH_EDITOR
#if PLATFORM_64BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
/// <summary>
/// Helper struct, since UnrealScript doesn't allow arrays of arrays, but
/// arrays of structs of arrays are okay.
/// </summary>
[StructLayout(LayoutKind.Explicit,Size=16)]
public partial struct FDelegateArray
{
}
}
#endif
#endif
| 19.571429 | 74 | 0.751825 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Editor_64bits/FDelegateArray.cs | 411 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AuthServer.Host.Migrations
{
public partial class Added_Feature_Management : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AbpFeatureValues",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(maxLength: 128, nullable: false),
ProviderName = table.Column<string>(maxLength: 64, nullable: true),
ProviderKey = table.Column<string>(maxLength: 64, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpFeatureValues", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_AbpFeatureValues_Name_ProviderName_ProviderKey",
table: "AbpFeatureValues",
columns: new[] { "Name", "ProviderName", "ProviderKey" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AbpFeatureValues");
}
}
}
| 36.552632 | 87 | 0.557955 | [
"MIT"
] | AbdallahYahyia/abp-samples | MicroserviceDemo/applications/AuthServer.Host/Migrations/20200304155131_Added_Feature_Management.cs | 1,391 | C# |
using UnityEngine;
namespace RogueLike.Inventory
{
public static class MouseData
{
public static UserInterface interfaceMouseIsOver;
public static GameObject tempItemBeingDragged;
public static GameObject slotHoverOver;
}
} | 23.636364 | 57 | 0.734615 | [
"MIT"
] | Westtly25/RPG-Inventory-Test | Assets/Scripts/Inventory/MouseData.cs | 260 | C# |
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TressFX
{
public class MaterialCreator : MonoBehaviour
{
/*[MenuItem("Assets/CreateMaterial")]
public static void CreateMat()
{
Material m = new Material(Shader.Find("Hidden/TressFX/ShadowMapTextureWriter"));
AssetDatabase.CreateAsset(m, "Assets/Material.mat");
AssetDatabase.SaveAssets();
}*/
}
}
| 25.222222 | 92 | 0.643172 | [
"Unlicense"
] | TagsRocks/TressFXUnity | Assets/TressFX/EditorExtension/Editor/MaterialCreator.cs | 456 | C# |
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net.Sockets;
using System.Text;
namespace Org.Mentalis.Network.ProxySocket.Authentication
{
/// <summary>
/// This class implements the 'username/password authentication' scheme.
/// </summary>
internal sealed class AuthUserPass : AuthMethod
{
/// <summary>
/// Initializes a new AuthUserPass instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use.</param>
/// <param name="pass">The password to use.</param>
/// <exception cref="ArgumentNullException"><c>user</c> -or- <c>pass</c> is null.</exception>
public AuthUserPass(Socket server, string user, string pass) : base(server)
{
Username = user;
Password = pass;
}
/// <summary>
/// Creates an array of bytes that has to be sent if the user wants to authenticate with the username/password
/// authentication scheme.
/// </summary>
/// <returns>
/// An array of bytes that has to be sent if the user wants to authenticate with the username/password
/// authentication scheme.
/// </returns>
private byte[] GetAuthenticationBytes()
{
byte[] buffer = new byte[3 + Username.Length + Password.Length];
buffer[0] = 1;
buffer[1] = (byte)Username.Length;
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, buffer, 2, Username.Length);
buffer[Username.Length + 2] = (byte)Password.Length;
Array.Copy(Encoding.ASCII.GetBytes(Password), 0, buffer, Username.Length + 3, Password.Length);
return buffer;
}
/// <summary>
/// Starts the authentication process.
/// </summary>
public override void Authenticate()
{
Server.Send(GetAuthenticationBytes());
byte[] buffer = new byte[2];
int received = 0;
while (received != 2)
{
received += Server.Receive(buffer, received, 2 - received, SocketFlags.None);
}
if (buffer[1] != 0)
{
Server.Close();
throw new ProxyException("Username/password combination rejected.");
}
return;
}
/// <summary>
/// Starts the asynchronous authentication process.
/// </summary>
/// <param name="callback">The method to call when the authentication is complete.</param>
public override void BeginAuthenticate(HandShakeComplete callback)
{
CallBack = callback;
Server.BeginSend(GetAuthenticationBytes(),
0,
3 + Username.Length + Password.Length,
SocketFlags.None,
OnSent,
Server);
return;
}
/// <summary>
/// Called when the authentication bytes have been sent.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnSent(IAsyncResult ar)
{
try
{
Server.EndSend(ar);
Buffer = new byte[2];
Server.BeginReceive(Buffer, 0, 2, SocketFlags.None, OnReceive, Server);
}
catch (Exception e)
{
CallBack(e);
}
}
/// <summary>
/// Called when the socket received an authentication reply.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReceive(IAsyncResult ar)
{
try
{
Received += Server.EndReceive(ar);
if (Received == Buffer.Length)
if (Buffer[1] == 0)
CallBack(null);
else
throw new ProxyException("Username/password combination not accepted.");
else
Server.BeginReceive(Buffer,
Received,
Buffer.Length - Received,
SocketFlags.None,
OnReceive,
Server);
}
catch (Exception e)
{
CallBack(e);
}
}
/// <summary>
/// Gets or sets the username to use when authenticating with the proxy server.
/// </summary>
/// <value>The username to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Username
{
get
{
return _username;
}
set
{
if (value == null)
throw new ArgumentNullException();
_username = value;
}
}
/// <summary>
/// Gets or sets the password to use when authenticating with the proxy server.
/// </summary>
/// <value>The password to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Password
{
get
{
return _password;
}
set
{
if (value == null)
throw new ArgumentNullException();
_password = value;
}
}
// private variables
/// <summary>Holds the value of the Username property.</summary>
private string _username;
/// <summary>Holds the value of the Password property.</summary>
private string _password;
}
}
| 36.607843 | 127 | 0.560525 | [
"MIT"
] | AkisKK/GMap.NET | GMap.NET/GMap.NET.Core/Internals/SocksProxySocket/AuthUserPass.cs | 7,471 | C# |
using NBitcoin;
using Purple.Bitcoin.Base;
using Purple.Bitcoin.Configuration;
using Purple.Bitcoin.Configuration.Logging;
using Purple.Bitcoin.Utilities;
using Xunit;
namespace Purple.Bitcoin.Features.Consensus.Tests
{
public class InitialBlockDownloadTest
{
private readonly ConsensusSettings consensusSettings;
private readonly Checkpoints checkpoints;
private readonly NodeSettings nodeSettings;
private readonly ChainState chainState;
private readonly Network network;
public InitialBlockDownloadTest()
{
this.network = Network.PurpleMain;
this.consensusSettings = new ConsensusSettings(NodeSettings.Default(), new ExtendedLoggerFactory());
this.checkpoints = new Checkpoints(this.network, this.consensusSettings);
this.nodeSettings = new NodeSettings("Purple", this.network);
this.chainState = new ChainState(new InvalidBlockHashStore(DateTimeProvider.Default));
}
[Fact]
public void NotInIBDIfChainStateIsNull()
{
var blockDownloadState = new InitialBlockDownloadState(null, this.network, this.nodeSettings, this.checkpoints);
Assert.False(blockDownloadState.IsInitialBlockDownload());
}
[Fact]
public void InIBDIfChainTipIsNull()
{
this.chainState.ConsensusTip = null;
var blockDownloadState = new InitialBlockDownloadState(this.chainState, this.network, this.nodeSettings, this.checkpoints);
Assert.True(blockDownloadState.IsInitialBlockDownload());
}
[Fact]
public void InIBDIfBehindCheckpoint()
{
this.chainState.ConsensusTip = new ChainedBlock(new BlockHeader(), uint256.Zero, 1000);
var blockDownloadState = new InitialBlockDownloadState(this.chainState, this.network, this.nodeSettings, this.checkpoints);
Assert.True(blockDownloadState.IsInitialBlockDownload());
}
[Fact]
public void InIBDIfChainWorkIsLessThanMinimum()
{
this.chainState.ConsensusTip = new ChainedBlock(new BlockHeader(), uint256.Zero, this.checkpoints.GetLastCheckpointHeight() + 1);
var blockDownloadState = new InitialBlockDownloadState(this.chainState, this.network, this.nodeSettings, this.checkpoints);
Assert.True(blockDownloadState.IsInitialBlockDownload());
}
}
}
| 41.661017 | 141 | 0.695281 | [
"MIT"
] | glasgowdev/purple | src/Purple.Bitcoin.Features.Consensus.Tests/InitialBlockDownloadTest.cs | 2,460 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.BigQuery.Reservation.V1.Snippets
{
using Google.Cloud.BigQuery.Reservation.V1;
public sealed partial class GeneratedReservationServiceClientStandaloneSnippets
{
/// <summary>Snippet for MoveAssignment</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void MoveAssignmentResourceNames()
{
// Create client
ReservationServiceClient reservationServiceClient = ReservationServiceClient.Create();
// Initialize request argument(s)
AssignmentName name = AssignmentName.FromProjectLocationReservationAssignment("[PROJECT]", "[LOCATION]", "[RESERVATION]", "[ASSIGNMENT]");
ReservationName destinationId = ReservationName.FromProjectLocationReservation("[PROJECT]", "[LOCATION]", "[RESERVATION]");
// Make the request
Assignment response = reservationServiceClient.MoveAssignment(name, destinationId);
}
}
}
| 43.725 | 150 | 0.70669 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/bigquery/reservation/v1/google-cloud-bigquery-reservation-v1-csharp/Google.Cloud.BigQuery.Reservation.V1.StandaloneSnippets/ReservationServiceClient.MoveAssignmentResourceNamesSnippet.g.cs | 1,749 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using GW2EIParser.EIData;
using GW2EIParser.Parser.ParsedData.CombatEvents;
namespace GW2EIParser.Parser.ParsedData
{
public class CombatData
{
public bool HasMovementData { get; }
//private List<CombatItem> _healingData;
//private List<CombatItem> _healingReceivedData;
private readonly StatusEventsContainer _statusEvents = new StatusEventsContainer();
private readonly MetaEventsContainer _metaDataEvents = new MetaEventsContainer();
private readonly HashSet<long> _skillIds;
private readonly Dictionary<long, List<AbstractBuffEvent>> _buffData;
private readonly Dictionary<long, List<BuffRemoveAllEvent>> _buffRemoveAllData;
private readonly Dictionary<AgentItem, List<AbstractBuffEvent>> _buffDataByDst;
private readonly Dictionary<AgentItem, List<AbstractDamageEvent>> _damageData;
private readonly Dictionary<long, List<AbstractDamageEvent>> _damageDataById;
private readonly Dictionary<AgentItem, List<AnimatedCastEvent>> _animatedCastData;
private readonly Dictionary<AgentItem, List<WeaponSwapEvent>> _weaponSwapData;
private readonly Dictionary<long, List<AbstractCastEvent>> _castDataById;
private readonly Dictionary<AgentItem, List<AbstractDamageEvent>> _damageTakenData;
private readonly Dictionary<AgentItem, List<AbstractMovementEvent>> _movementData;
private readonly List<RewardEvent> _rewardEvents = new List<RewardEvent>();
public bool HasStackIDs { get; } = false;
private void EIBuffParse(List<Player> players, SkillData skillData, FightData fightData)
{
var toAdd = new List<AbstractBuffEvent>();
foreach (Player p in players)
{
if (p.Prof == "Weaver")
{
toAdd = WeaverHelper.TransformWeaverAttunements(GetBuffDataByDst(p.AgentItem), p.AgentItem, skillData);
}
if (p.Prof == "Elementalist" || p.Prof == "Tempest")
{
ElementalistHelper.RemoveDualBuffs(GetBuffDataByDst(p.AgentItem), skillData);
}
}
toAdd.AddRange(fightData.Logic.SpecialBuffEventProcess(_buffDataByDst, _buffData, skillData));
var buffIDsToSort = new HashSet<long>();
var buffAgentsToSort = new HashSet<AgentItem>();
foreach (AbstractBuffEvent bf in toAdd)
{
if (_buffDataByDst.TryGetValue(bf.To, out List<AbstractBuffEvent> list1))
{
list1.Add(bf);
}
else
{
_buffDataByDst[bf.To] = new List<AbstractBuffEvent>()
{
bf
};
}
buffAgentsToSort.Add(bf.To);
if (_buffData.TryGetValue(bf.BuffID, out List<AbstractBuffEvent> list2))
{
list2.Add(bf);
}
else
{
_buffData[bf.BuffID] = new List<AbstractBuffEvent>()
{
bf
};
}
buffIDsToSort.Add(bf.BuffID);
}
foreach (long buffID in buffIDsToSort)
{
_buffData[buffID].Sort((x, y) => x.Time.CompareTo(y.Time));
}
foreach (AgentItem a in buffAgentsToSort)
{
_buffDataByDst[a].Sort((x, y) => x.Time.CompareTo(y.Time));
}
}
private void EIDamageParse(SkillData skillData, FightData fightData)
{
var toAdd = new List<AbstractDamageEvent>();
toAdd.AddRange(fightData.Logic.SpecialDamageEventProcess(_damageData, _damageTakenData, _damageDataById, skillData));
var idsToSort = new HashSet<long>();
var dstToSort = new HashSet<AgentItem>();
var srcToSort = new HashSet<AgentItem>();
foreach (AbstractDamageEvent de in toAdd)
{
if (_damageTakenData.TryGetValue(de.To, out List<AbstractDamageEvent> list1))
{
list1.Add(de);
}
else
{
_damageTakenData[de.To] = new List<AbstractDamageEvent>()
{
de
};
}
dstToSort.Add(de.To);
if (_damageData.TryGetValue(de.From, out List<AbstractDamageEvent> list3))
{
list1.Add(de);
}
else
{
_damageData[de.From] = new List<AbstractDamageEvent>()
{
de
};
}
srcToSort.Add(de.To);
if (_damageDataById.TryGetValue(de.SkillId, out List<AbstractDamageEvent> list2))
{
list2.Add(de);
}
else
{
_damageDataById[de.SkillId] = new List<AbstractDamageEvent>()
{
de
};
}
idsToSort.Add(de.SkillId);
}
foreach (long buffID in idsToSort)
{
_damageDataById[buffID].Sort((x, y) => x.Time.CompareTo(y.Time));
}
foreach (AgentItem a in dstToSort)
{
_damageTakenData[a].Sort((x, y) => x.Time.CompareTo(y.Time));
}
foreach (AgentItem a in srcToSort)
{
_damageData[a].Sort((x, y) => x.Time.CompareTo(y.Time));
}
}
private void EICastParse(List<Player> players, SkillData skillData)
{
var toAdd = new List<AnimatedCastEvent>();
foreach (Player p in players)
{
if (p.Prof == "Mirage")
{
toAdd = MirageHelper.TranslateMirageCloak(GetBuffData(40408), skillData);
break;
}
}
var castIDsToSort = new HashSet<long>();
var castAgentsToSort = new HashSet<AgentItem>();
foreach (AnimatedCastEvent cast in toAdd)
{
if (_animatedCastData.TryGetValue(cast.Caster, out List<AnimatedCastEvent> list1))
{
list1.Add(cast);
}
else
{
_animatedCastData[cast.Caster] = new List<AnimatedCastEvent>()
{
cast
};
}
castAgentsToSort.Add(cast.Caster);
if (_castDataById.TryGetValue(cast.SkillId, out List<AbstractCastEvent> list2))
{
list2.Add(cast);
}
else
{
_castDataById[cast.SkillId] = new List<AbstractCastEvent>()
{
cast
};
}
castIDsToSort.Add(cast.SkillId);
}
foreach (long buffID in castIDsToSort)
{
_castDataById[buffID].Sort((x, y) => x.Time.CompareTo(y.Time));
}
foreach (AgentItem a in castAgentsToSort)
{
_animatedCastData[a].Sort((x, y) => x.Time.CompareTo(y.Time));
}
}
private void EIStatusParse()
{
foreach (KeyValuePair<AgentItem, List<AbstractDamageEvent>> pair in _damageTakenData)
{
bool setDeads = false;
if (!_statusEvents.DeadEvents.TryGetValue(pair.Key, out List<DeadEvent> agentDeaths))
{
agentDeaths = new List<DeadEvent>();
setDeads = true;
}
bool setDowns = false;
if (!_statusEvents.DownEvents.TryGetValue(pair.Key, out List<DownEvent> agentDowns))
{
agentDowns = new List<DownEvent>();
setDowns = true;
}
foreach (AbstractDamageEvent evt in pair.Value)
{
if (evt.HasKilled)
{
if (!agentDeaths.Exists(x => Math.Abs(x.Time - evt.Time) < 500)) {
agentDeaths.Add(new DeadEvent(pair.Key, evt.Time));
}
}
if (evt.HasDowned)
{
if (!agentDowns.Exists(x => Math.Abs(x.Time - evt.Time) < 500))
{
agentDowns.Add(new DownEvent(pair.Key, evt.Time));
}
}
}
agentDowns.Sort((x,y) => x.Time.CompareTo(y.Time));
agentDeaths.Sort((x, y) => x.Time.CompareTo(y.Time));
if (setDeads && agentDeaths.Count > 0)
{
_statusEvents.DeadEvents[pair.Key] = agentDeaths;
}
if (setDowns && agentDowns.Count > 0)
{
_statusEvents.DownEvents[pair.Key] = agentDowns;
}
}
}
private void EIExtraEventProcess(List<Player> players, SkillData skillData, FightData fightData)
{
EIBuffParse(players, skillData, fightData);
EIDamageParse(skillData, fightData);
EICastParse(players, skillData);
EIStatusParse();
// master attachements
WarriorHelper.AttachMasterToWarriorBanners(players, _buffData, _castDataById);
EngineerHelper.AttachMasterToEngineerTurrets(players, _damageDataById, _castDataById);
RangerHelper.AttachMasterToRangerGadgets(players, _damageDataById, _castDataById);
ProfHelper.AttachMasterToRacialGadgets(players, _damageDataById, _castDataById);
}
public CombatData(List<CombatItem> allCombatItems, FightData fightData, AgentData agentData, SkillData skillData, List<Player> players)
{
_skillIds = new HashSet<long>(allCombatItems.Select(x => x.SkillID));
IEnumerable<CombatItem> noStateActiBuffRem = allCombatItems.Where(x => x.IsStateChange == ParseEnum.StateChange.None && x.IsActivation == ParseEnum.Activation.None && x.IsBuffRemove == ParseEnum.BuffRemove.None);
// movement events
_movementData = CombatEventFactory.CreateMovementEvents(allCombatItems.Where(x =>
x.IsStateChange == ParseEnum.StateChange.Position ||
x.IsStateChange == ParseEnum.StateChange.Velocity ||
x.IsStateChange == ParseEnum.StateChange.Rotation).ToList(), agentData);
HasMovementData = _movementData.Count > 1;
// state change events
CombatEventFactory.CreateStateChangeEvents(allCombatItems, _metaDataEvents, _statusEvents, _rewardEvents, agentData);
// activation events
List<AnimatedCastEvent> animatedCastData = CombatEventFactory.CreateCastEvents(allCombatItems.Where(x => x.IsActivation != ParseEnum.Activation.None).ToList(), agentData, skillData);
List<WeaponSwapEvent> wepSwaps = CombatEventFactory.CreateWeaponSwapEvents(allCombatItems.Where(x => x.IsStateChange == ParseEnum.StateChange.WeaponSwap).ToList(), agentData, skillData);
_weaponSwapData = wepSwaps.GroupBy(x => x.Caster).ToDictionary(x => x.Key, x => x.ToList());
_animatedCastData = animatedCastData.GroupBy(x => x.Caster).ToDictionary(x => x.Key, x => x.ToList());
var allCastEvents = new List<AbstractCastEvent>(animatedCastData);
allCastEvents.AddRange(wepSwaps);
_castDataById = allCastEvents.GroupBy(x => x.SkillId).ToDictionary(x => x.Key, x => x.ToList());
// buff remove event
var buffCombatEvents = allCombatItems.Where(x => x.IsBuffRemove != ParseEnum.BuffRemove.None && x.IsBuff != 0).ToList();
buffCombatEvents.AddRange(noStateActiBuffRem.Where(x => x.IsBuff != 0 && x.BuffDmg == 0 && x.Value > 0));
buffCombatEvents.AddRange(allCombatItems.Where(x => x.IsStateChange == ParseEnum.StateChange.BuffInitial));
buffCombatEvents.Sort((x, y) => x.Time.CompareTo(y.Time));
List<AbstractBuffEvent> buffEvents = CombatEventFactory.CreateBuffEvents(buffCombatEvents, agentData, skillData);
_buffDataByDst = buffEvents.GroupBy(x => x.To).ToDictionary(x => x.Key, x => x.ToList());
_buffData = buffEvents.GroupBy(x => x.BuffID).ToDictionary(x => x.Key, x => x.ToList());
// damage events
List<AbstractDamageEvent> damageData = CombatEventFactory.CreateDamageEvents(noStateActiBuffRem.Where(x => (x.IsBuff != 0 && x.Value == 0) || (x.IsBuff == 0)).ToList(), agentData, skillData);
_damageData = damageData.GroupBy(x => x.From).ToDictionary(x => x.Key, x => x.ToList());
_damageTakenData = damageData.GroupBy(x => x.To).ToDictionary(x => x.Key, x => x.ToList());
_damageDataById = damageData.GroupBy(x => x.SkillId).ToDictionary(x => x.Key, x => x.ToList());
/*healing_data = allCombatItems.Where(x => x.getDstInstid() != 0 && x.isStateChange() == ParseEnum.StateChange.Normal && x.getIFF() == ParseEnum.IFF.Friend && x.isBuffremove() == ParseEnum.BuffRemove.None &&
((x.isBuff() == 1 && x.getBuffDmg() > 0 && x.getValue() == 0) ||
(x.isBuff() == 0 && x.getValue() > 0))).ToList();
healing_received_data = allCombatItems.Where(x => x.isStateChange() == ParseEnum.StateChange.Normal && x.getIFF() == ParseEnum.IFF.Friend && x.isBuffremove() == ParseEnum.BuffRemove.None &&
((x.isBuff() == 1 && x.getBuffDmg() > 0 && x.getValue() == 0) ||
(x.isBuff() == 0 && x.getValue() >= 0))).ToList();*/
EIExtraEventProcess(players, skillData, fightData);
_buffRemoveAllData = _buffData.ToDictionary(x => x.Key, x => x.Value.OfType<BuffRemoveAllEvent>().ToList());
}
// getters
public HashSet<long> GetSkills()
{
return _skillIds;
}
public List<AliveEvent> GetAliveEvents(AgentItem key)
{
if (_statusEvents.AliveEvents.TryGetValue(key, out List<AliveEvent> list))
{
return list;
}
return new List<AliveEvent>();
}
public List<AttackTargetEvent> GetAttackTargetEvents(AgentItem key)
{
if (_statusEvents.AttackTargetEvents.TryGetValue(key, out List<AttackTargetEvent> list))
{
return list;
}
return new List<AttackTargetEvent>();
}
public List<DeadEvent> GetDeadEvents(AgentItem key)
{
if (_statusEvents.DeadEvents.TryGetValue(key, out List<DeadEvent> list))
{
return list;
}
return new List<DeadEvent>();
}
public List<DespawnEvent> GetDespawnEvents(AgentItem key)
{
if (_statusEvents.DespawnEvents.TryGetValue(key, out List<DespawnEvent> list))
{
return list;
}
return new List<DespawnEvent>();
}
public List<DownEvent> GetDownEvents(AgentItem key)
{
if (_statusEvents.DownEvents.TryGetValue(key, out List<DownEvent> list))
{
return list;
}
return new List<DownEvent>();
}
public List<EnterCombatEvent> GetEnterCombatEvents(AgentItem key)
{
if (_statusEvents.EnterCombatEvents.TryGetValue(key, out List<EnterCombatEvent> list))
{
return list;
}
return new List<EnterCombatEvent>();
}
public List<ExitCombatEvent> GetExitCombatEvents(AgentItem key)
{
if (_statusEvents.ExitCombatEvents.TryGetValue(key, out List<ExitCombatEvent> list))
{
return list;
}
return new List<ExitCombatEvent>();
}
public List<GuildEvent> GetGuildEvents(AgentItem key)
{
if (_metaDataEvents.GuildEvents.TryGetValue(key, out List<GuildEvent> list))
{
return list;
}
return new List<GuildEvent>();
}
public List<HealthUpdateEvent> GetHealthUpdateEvents(AgentItem key)
{
if (_statusEvents.HealthUpdateEvents.TryGetValue(key, out List<HealthUpdateEvent> list))
{
return list;
}
return new List<HealthUpdateEvent>();
}
public List<MaxHealthUpdateEvent> GetMaxHealthUpdateEvents(AgentItem key)
{
if (_statusEvents.MaxHealthUpdateEvents.TryGetValue(key, out List<MaxHealthUpdateEvent> list))
{
return list;
}
return new List<MaxHealthUpdateEvent>();
}
public List<PointOfViewEvent> GetPointOfViewEvents()
{
return _metaDataEvents.PointOfViewEvents;
}
public List<SpawnEvent> GetSpawnEvents(AgentItem key)
{
if (_statusEvents.SpawnEvents.TryGetValue(key, out List<SpawnEvent> list))
{
return list;
}
return new List<SpawnEvent>();
}
public List<TargetableEvent> GetTargetableEvents(AgentItem key)
{
if (_statusEvents.TargetableEvents.TryGetValue(key, out List<TargetableEvent> list))
{
return list;
}
return new List<TargetableEvent>();
}
public List<TeamChangeEvent> GetTeamChangeEvents(AgentItem key)
{
if (_statusEvents.TeamChangeEvents.TryGetValue(key, out List<TeamChangeEvent> list))
{
return list;
}
return new List<TeamChangeEvent>();
}
public List<BuildEvent> GetBuildEvents()
{
return _metaDataEvents.BuildEvents;
}
public List<LanguageEvent> GetLanguageEvents()
{
return _metaDataEvents.LanguageEvents;
}
public List<LogStartEvent> GetLogStartEvents()
{
return _metaDataEvents.LogStartEvents;
}
public List<LogEndEvent> GetLogEndEvents()
{
return _metaDataEvents.LogEndEvents;
}
public List<MapIDEvent> GetMapIDEvents()
{
return _metaDataEvents.MapIDEvents;
}
public List<RewardEvent> GetRewardEvents()
{
return _rewardEvents;
}
public List<ShardEvent> GetShardEvents()
{
return _metaDataEvents.ShardEvents;
}
public List<AbstractBuffEvent> GetBuffData(long key)
{
if (_buffData.TryGetValue(key, out List<AbstractBuffEvent> res))
{
return res;
}
return new List<AbstractBuffEvent>(); ;
}
public List<BuffRemoveAllEvent> GetBuffRemoveAllData(long key)
{
if (_buffRemoveAllData.TryGetValue(key, out List<BuffRemoveAllEvent> res))
{
return res;
}
return new List<BuffRemoveAllEvent>(); ;
}
public List<AbstractBuffEvent> GetBuffDataByDst(AgentItem key)
{
if (_buffDataByDst.TryGetValue(key, out List<AbstractBuffEvent> res))
{
return res;
}
return new List<AbstractBuffEvent>(); ;
}
public List<AbstractDamageEvent> GetDamageData(AgentItem key)
{
if (_damageData.TryGetValue(key, out List<AbstractDamageEvent> res))
{
return res;
}
return new List<AbstractDamageEvent>(); ;
}
public List<AbstractDamageEvent> GetDamageDataById(long key)
{
if (_damageDataById.TryGetValue(key, out List<AbstractDamageEvent> res))
{
return res;
}
return new List<AbstractDamageEvent>(); ;
}
public List<AnimatedCastEvent> GetAnimatedCastData(AgentItem key)
{
if (_animatedCastData.TryGetValue(key, out List<AnimatedCastEvent> res))
{
return res;
}
return new List<AnimatedCastEvent>(); ;
}
public List<WeaponSwapEvent> GetWeaponSwapData(AgentItem key)
{
if (_weaponSwapData.TryGetValue(key, out List<WeaponSwapEvent> res))
{
return res;
}
return new List<WeaponSwapEvent>(); ;
}
public List<AbstractCastEvent> GetCastDataById(long key)
{
if (_castDataById.TryGetValue(key, out List<AbstractCastEvent> res))
{
return res;
}
return new List<AbstractCastEvent>(); ;
}
public List<AbstractDamageEvent> GetDamageTakenData(AgentItem key)
{
if (_damageTakenData.TryGetValue(key, out List<AbstractDamageEvent> res))
{
return res;
}
return new List<AbstractDamageEvent>();
}
/*public List<CombatItem> getHealingData()
{
return _healingData;
}
public List<CombatItem> getHealingReceivedData()
{
return _healingReceivedData;
}*/
public List<AbstractMovementEvent> GetMovementData(AgentItem key)
{
if (_movementData.TryGetValue(key, out List<AbstractMovementEvent> res))
{
return res;
}
return new List<AbstractMovementEvent>();
}
}
}
| 39.652557 | 224 | 0.542543 | [
"MIT"
] | Flomix/GW2-Elite-Insights-Parser | GW2EIParser/Parser/ParsedData/CombatData.cs | 22,485 | C# |
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MyJetWallet.Sdk.Authorization.Http;
using NSwag.Annotations;
using Service.Core.Client.Services;
using Service.Education.Structure;
using Service.TimeLogger.Grpc.Models;
using Service.WalletApi.EducationMarketsApi.Controllers.Contracts;
using Service.Web;
namespace Service.WalletApi.EducationMarketsApi.Controllers
{
[Authorize]
[ApiController]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[SwaggerResponse(HttpStatusCode.Unauthorized, null, Description = "Unauthorized")]
public class BaseController : ControllerBase
{
public static readonly EducationTutorial Tutorial = EducationTutorial.FinanceMarkets;
private readonly ISystemClock _systemClock;
private readonly IEncoderDecoder _encoderDecoder;
private readonly ILogger _logger;
public BaseController(ISystemClock systemClock, IEncoderDecoder encoderDecoder, ILogger<EducationController> logger)
{
_systemClock = systemClock;
_encoderDecoder = encoderDecoder;
_logger = logger;
}
protected async ValueTask<IActionResult> Process<TGrpcResponse, TModelResponse>(
Func<string, ValueTask<TGrpcResponse>> grpcRequestFunc,
Func<TGrpcResponse, TModelResponse> responseFunc)
{
string userId = this.GetClientId();
if (userId == null)
return StatusResponse.Error(ResponseCode.UserNotFound);
TGrpcResponse response = await grpcRequestFunc.Invoke(userId);
return DataResponse<TModelResponse>.Ok(responseFunc.Invoke(response));
}
protected async ValueTask<IActionResult> ProcessTask<TGrpcResponse, TModelResponse>(
int unit, int task, TaskRequestBase request,
Func<string, TimeSpan, ValueTask<TGrpcResponse>> grpcRequestFunc,
Func<TGrpcResponse, TModelResponse> responseFunc)
{
string userId = this.GetClientId();
if (userId == null)
return StatusResponse.Error(ResponseCode.UserNotFound);
TimeSpan? duration = GetTimeTokenDuration(request.TimeToken, userId, unit, task);
if (duration == null)
return StatusResponse.Error(ResponseCode.InvalidTimeToken);
TGrpcResponse response = await grpcRequestFunc.Invoke(userId, duration.Value);
return DataResponse<TModelResponse>.Ok(responseFunc.Invoke(response));
}
private TimeSpan? GetTimeTokenDuration(string timeToken, string userId, int unit, int task)
{
TaskTimeLogGrpcRequest tokenData;
try
{
tokenData = _encoderDecoder.DecodeProto<TaskTimeLogGrpcRequest>(timeToken);
}
catch (Exception exception)
{
_logger.LogError("Can't decode time token ({token}) for user {user}, with message {message}", timeToken, userId, exception.Message);
return null;
}
if (tokenData.Tutorial != Tutorial || tokenData.Unit != unit || tokenData.Task != task)
return null;
TimeSpan span = _systemClock.Now.Subtract(tokenData.StartDate);
return span == TimeSpan.Zero ? (TimeSpan?) null : span;
}
}
} | 34.197802 | 136 | 0.779563 | [
"MIT"
] | MyJetEducation/Service.EducationMarketsApi | src/Service.WalletApi.EducationMarketsApi/Controllers/BaseController.cs | 3,114 | C# |
/* Copyright (c) 2010 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//#define USE_RELEASE_STATISTICS
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
#if !__NOIPENDPOINT__
using NetEndPoint = System.Net.IPEndPoint;
#endif
namespace Lidgren.Network
{
public partial class NetPeer
{
#if DEBUG
private readonly List<DelayedPacket> m_delayedPackets = new List<DelayedPacket>();
private class DelayedPacket
{
public byte[] Data;
public double DelayedUntil;
public NetEndPoint Target;
}
internal void SendPacket(int numBytes, NetEndPoint target, int numMessages, out bool connectionReset)
{
connectionReset = false;
// simulate loss
float loss = m_configuration.m_loss;
if (loss > 0.0f)
{
if ((float)MWCRandom.Instance.NextDouble() < loss)
{
LogVerbose("Sending packet " + numBytes + " bytes - SIMULATED LOST!");
return; // packet "lost"
}
}
m_statistics.PacketSent(numBytes, numMessages);
// simulate latency
float m = m_configuration.m_minimumOneWayLatency;
float r = m_configuration.m_randomOneWayLatency;
if (m == 0.0f && r == 0.0f)
{
// no latency simulation
// LogVerbose("Sending packet " + numBytes + " bytes");
bool wasSent = ActuallySendPacket(m_sendBuffer, numBytes, target, out connectionReset);
// TODO: handle wasSent == false?
if (m_configuration.m_duplicates > 0.0f && MWCRandom.Instance.NextDouble() < m_configuration.m_duplicates)
ActuallySendPacket(m_sendBuffer, numBytes, target, out connectionReset); // send it again!
return;
}
int num = 1;
if (m_configuration.m_duplicates > 0.0f && MWCRandom.Instance.NextSingle() < m_configuration.m_duplicates)
num++;
float delay = 0;
for (int i = 0; i < num; i++)
{
delay = m_configuration.m_minimumOneWayLatency + (MWCRandom.Instance.NextSingle() * m_configuration.m_randomOneWayLatency);
// Enqueue delayed packet
DelayedPacket p = new DelayedPacket();
p.Target = target;
p.Data = new byte[numBytes];
Buffer.BlockCopy(m_sendBuffer, 0, p.Data, 0, numBytes);
p.DelayedUntil = NetTime.Now + delay;
m_delayedPackets.Add(p);
}
// LogVerbose("Sending packet " + numBytes + " bytes - delayed " + NetTime.ToReadable(delay));
}
private void SendDelayedPackets()
{
if (m_delayedPackets.Count <= 0)
return;
double now = NetTime.Now;
bool connectionReset;
RestartDelaySending:
foreach (DelayedPacket p in m_delayedPackets)
{
if (now > p.DelayedUntil)
{
ActuallySendPacket(p.Data, p.Data.Length, p.Target, out connectionReset);
m_delayedPackets.Remove(p);
goto RestartDelaySending;
}
}
}
private void FlushDelayedPackets()
{
try
{
bool connectionReset;
foreach (DelayedPacket p in m_delayedPackets)
ActuallySendPacket(p.Data, p.Data.Length, p.Target, out connectionReset);
m_delayedPackets.Clear();
}
catch { }
}
internal bool ActuallySendPacket(byte[] data, int numBytes, NetEndPoint target, out bool connectionReset)
{
connectionReset = false;
IPAddress ba = default(IPAddress);
try
{
ba = NetUtility.GetCachedBroadcastAddress();
// TODO: refactor this check outta here
if (target.Address.Equals(ba))
{
// Some networks do not allow
// a global broadcast so we use the BroadcastAddress from the configuration
// this can be resolved to a local broadcast addresss e.g 192.168.x.255
target.Address = m_configuration.BroadcastAddress;
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
}
int bytesSent = m_socket.SendTo(data, 0, numBytes, SocketFlags.None, target);
if (numBytes != bytesSent)
LogWarning("Failed to send the full " + numBytes + "; only " + bytesSent + " bytes sent in packet!");
// LogDebug("Sent " + numBytes + " bytes");
}
catch (SocketException sx)
{
if (sx.SocketErrorCode == SocketError.WouldBlock)
{
// send buffer full?
LogWarning("Socket threw exception; would block - send buffer full? Increase in NetPeerConfiguration");
return false;
}
if (sx.SocketErrorCode == SocketError.ConnectionReset)
{
// connection reset by peer, aka connection forcibly closed aka "ICMP port unreachable"
connectionReset = true;
return false;
}
LogError("Failed to send packet: " + sx);
}
catch (Exception ex)
{
LogError("Failed to send packet: " + ex);
}
finally
{
if (target.Address == ba)
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
}
return true;
}
internal bool SendMTUPacket(int numBytes, NetEndPoint target)
{
try
{
m_socket.DontFragment = true;
int bytesSent = m_socket.SendTo(m_sendBuffer, 0, numBytes, SocketFlags.None, target);
if (numBytes != bytesSent)
LogWarning("Failed to send the full " + numBytes + "; only " + bytesSent + " bytes sent in packet!");
m_statistics.PacketSent(numBytes, 1);
}
catch (SocketException sx)
{
if (sx.SocketErrorCode == SocketError.MessageSize)
return false;
if (sx.SocketErrorCode == SocketError.WouldBlock)
{
// send buffer full?
LogWarning("Socket threw exception; would block - send buffer full? Increase in NetPeerConfiguration");
return true;
}
if (sx.SocketErrorCode == SocketError.ConnectionReset)
return true;
LogError("Failed to send packet: (" + sx.SocketErrorCode + ") " + sx);
}
catch (Exception ex)
{
LogError("Failed to send packet: " + ex);
}
finally
{
m_socket.DontFragment = false;
}
return true;
}
#else
internal bool SendMTUPacket(int numBytes, NetEndPoint target)
{
try
{
m_socket.DontFragment = true;
int bytesSent = m_socket.SendTo(m_sendBuffer, 0, numBytes, SocketFlags.None, target);
if (numBytes != bytesSent)
LogWarning("Failed to send the full " + numBytes + "; only " + bytesSent + " bytes sent in packet!");
}
catch (SocketException sx)
{
if (sx.SocketErrorCode == SocketError.MessageSize)
return false;
if (sx.SocketErrorCode == SocketError.WouldBlock)
{
// send buffer full?
LogWarning("Socket threw exception; would block - send buffer full? Increase in NetPeerConfiguration");
return true;
}
if (sx.SocketErrorCode == SocketError.ConnectionReset)
return true;
LogError("Failed to send packet: (" + sx.SocketErrorCode + ") " + sx);
}
catch (Exception ex)
{
LogError("Failed to send packet: " + ex);
}
finally
{
m_socket.DontFragment = false;
}
return true;
}
//
// Release - just send the packet straight away
//
internal void SendPacket(int numBytes, NetEndPoint target, int numMessages, out bool connectionReset)
{
#if USE_RELEASE_STATISTICS
m_statistics.PacketSent(numBytes, numMessages);
#endif
connectionReset = false;
IPAddress ba = default(IPAddress);
try
{
// TODO: refactor this check outta here
ba = NetUtility.GetCachedBroadcastAddress();
if (target.Address == ba)
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
int bytesSent = m_socket.SendTo(m_sendBuffer, 0, numBytes, SocketFlags.None, target);
if (numBytes != bytesSent)
LogWarning("Failed to send the full " + numBytes + "; only " + bytesSent + " bytes sent in packet!");
}
catch (SocketException sx)
{
if (sx.SocketErrorCode == SocketError.WouldBlock)
{
// send buffer full?
LogWarning("Socket threw exception; would block - send buffer full? Increase in NetPeerConfiguration");
return;
}
if (sx.SocketErrorCode == SocketError.ConnectionReset)
{
// connection reset by peer, aka connection forcibly closed aka "ICMP port unreachable"
connectionReset = true;
return;
}
LogError("Failed to send packet: " + sx);
}
catch (Exception ex)
{
LogError("Failed to send packet: " + ex);
}
finally
{
if (target.Address == ba)
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
}
return;
}
private void FlushDelayedPackets()
{
}
#endif
}
}
| 30.958333 | 128 | 0.666322 | [
"MIT"
] | FengYunHuanYu/lidgren-network-gen3 | Lidgren.Network/NetPeer.LatencySimulation.cs | 9,661 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Expansion;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : IExpansionClient
{
protected readonly IExpansionServiceProvider ExpansionServiceProvider;
protected readonly IContentType LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
public readonly IGlobalOptionService GlobalOptions;
protected bool _indentCaretOnCommit;
protected int _indentDepth;
protected bool _earlyEndExpansionHappened;
public IExpansionSession? ExpansionSession { get; private set; }
public AbstractSnippetExpansionClient(IContentType languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IExpansionServiceProvider expansionServiceProvider, IGlobalOptionService globalOptions)
{
LanguageServiceGuid = languageServiceGuid;
TextView = textView;
SubjectBuffer = subjectBuffer;
ExpansionServiceProvider = expansionServiceProvider;
GlobalOptions = globalOptions;
}
public abstract IExpansionFunction? GetExpansionFunction(XElement xmlFunctionNode, string fieldName);
protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan();
public void FormatSpan(SnapshotSpan span)
{
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
if (!TryGetSubjectBufferSpan(span, out var snippetSpan))
{
return;
}
Contract.ThrowIfNull(ExpansionSession);
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = ExpansionSession.GetSnippetSpan();
var isFullSnippetFormat = fullSnippetSpan == span;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, GlobalOptions, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
SetNewEndPosition(endPositionTrackingSpan);
}
}
private void SetNewEndPosition(ITrackingSpan? endTrackingSpan)
{
Contract.ThrowIfNull(ExpansionSession);
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out var endSpanInSurfaceBuffer))
{
return;
}
ExpansionSession.EndSpan = new SnapshotSpan(endSpanInSurfaceBuffer.Start, 0);
}
}
private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
_indentCaretOnCommit = true;
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var lineFormattingOptions = document.GetLineFormattingOptionsAsync(GlobalOptions, CancellationToken.None).AsTask().WaitAndGetResult(CancellationToken.None);
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, lineFormattingOptions.TabSize);
}
else
{
// If we don't have a document, then just guess the typical default TabSize value.
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);
}
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
_ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IExpansionSession pSession)
{
if (pSession.GetSnippetNode() is not XElement snippetNode)
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = pSession.GetSnippetSpan();
var newEndSpan = new SnapshotSpan(snippetSpan.End, 0);
pSession.EndSpan = newEndSpan;
return true;
}
public void PositionCaretForEditing(ITextView textView, SnapshotPoint point)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
var line = point.GetContainingLine();
PositionCaretForEditingInternal(line.GetText(), line.End);
}
/// <summary>
/// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/>
/// only extracts the <paramref name="endLineText"/> and <paramref name="point"/> from the provided <see cref="ITextView"/>.
/// Tests can call this method directly to avoid producing an IVsTextLines.
/// </summary>
/// <param name="endLineText"></param>
/// <param name="point"></param>
internal void PositionCaretForEditingInternal(string endLineText, SnapshotPoint point)
{
if (_indentCaretOnCommit && endLineText == string.Empty)
{
ITextViewExtensions.TryMoveCaretToAndEnsureVisible(TextView, new VirtualSnapshotPoint(point, _indentDepth));
}
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = ExpansionSession.GoToNextExpansionField(false);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(leaveCaret: true);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(leaveCaret: true);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(leaveCaret: true);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
if (ExpansionSession != null)
{
// Only move the caret if the enter was hit within the snippet fields.
var hitWithinField = ExpansionSession.GoToNextExpansionField(commitIfLast: false);
ExpansionSession.EndCurrentExpansion(leaveCaret: !hitWithinField);
ExpansionSession = null;
return hitWithinField;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return false;
}
// The expansion itself needs to be created in the data buffer, so map everything up
_ = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer);
_ = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer);
if (!TryGetSpanOnHigherBuffer(
SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer),
textViewModel.DataBuffer,
out var dataBufferSpan))
{
return false;
}
var expansion = ExpansionServiceProvider.GetExpansionService(TextView);
ExpansionSession = expansion.InsertExpansion(dataBufferSpan, this, LanguageServiceGuid);
if (ExpansionSession == null)
return false;
return true;
}
public void EndExpansion()
{
if (ExpansionSession == null)
{
_earlyEndExpansionHappened = true;
}
ExpansionSession = null;
_indentCaretOnCommit = false;
}
public void OnAfterInsertion(IExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
}
public void OnBeforeInsertion(IExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
this.ExpansionSession = pSession;
}
public void OnItemChosen(string title, string pszPath)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return;
}
var textSpan = TextView.Caret.Position.BufferPosition;
var expansion = ExpansionServiceProvider.GetExpansionService(TextView);
_earlyEndExpansionHappened = false;
ExpansionSession = expansion.InsertNamedExpansion(title, pszPath, new SnapshotSpan(textSpan, 0), this, LanguageServiceGuid, false);
if (_earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
ExpansionSession = null;
_earlyEndExpansionHappened = false;
}
}
protected static bool TryGetSnippetFunctionInfo(XElement xmlFunctionNode, [NotNullWhen(returnValue: true)] out string? snippetFunctionName, [NotNullWhen(returnValue: true)] out string? param)
{
if (xmlFunctionNode.Value.IndexOf('(') == -1 ||
xmlFunctionNode.Value.IndexOf(')') == -1 ||
xmlFunctionNode.Value.IndexOf(')') < xmlFunctionNode.Value.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.Value.Substring(0, xmlFunctionNode.Value.IndexOf('('));
var paramStart = xmlFunctionNode.Value.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.Value.LastIndexOf(')') - xmlFunctionNode.Value.IndexOf('(') - 1;
param = xmlFunctionNode.Value.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(SnapshotSpan snapshotSpan, out SnapshotSpan subjectBufferSpan)
{
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default;
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default;
return false;
}
}
}
| 41.788835 | 214 | 0.61689 | [
"MIT"
] | BillWagner/roslyn | src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs | 17,219 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.ApplicationSettings
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum WebAccountAction
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
Reconnect,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
Remove,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ViewDetails,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
Manage,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
More,
#endif
}
#endif
}
| 26.551724 | 62 | 0.687013 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.ApplicationSettings/WebAccountAction.cs | 770 | C# |
using System;
namespace _10_F
{
public class M2
{
//Pq MainWindow funcionou?
static void MainWindow(string[] args)
{
Console.WriteLine("Digite o valor de M ");
var M = int.Parse(Console.ReadLine());
Console.WriteLine("Digite o valor de R ");
var R = int.Parse(Console.ReadLine());
}
public static int Total(int M, int R)
{
var A = 3;
var total = M + A + R;
return total;
}
public static void Executar()
{
Console.WriteLine("O total de M + 3 + R é: ");
}
}
} | 23.214286 | 58 | 0.48 | [
"MIT"
] | jonataspiazzi/Aula | genesis/exercicios/10 F/M2.cs | 651 | C# |
namespace DapperPlayground.MsSql
{
using System.Data;
using System.Data.SqlClient;
public static class SqlServerConnectionFactory
{
public static IDbConnection OpenNew()
{
const string connectionString = "Data Source=localhost,1434;Initial Catalog=Northwind;User Id=SA;Password=Change_Me;";
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
}
} | 30.125 | 130 | 0.657676 | [
"Apache-2.0"
] | bbv-mmarkovic/DapperPlayground | src/DapperPlayground.MsSql.FullFrameworkTest/SqlServerConnectionFactory.cs | 484 | C# |
using GameCommands;
using GameModes;
using Ship;
using System;
using System.Linq;
using UnityEngine;
namespace SubPhases
{
public class SelectTargetForSecondAttackSubPhase : SelectShipSubPhase
{
public override void Prepare()
{
Selection.ThisShip.IsAttackPerformed = false;
Combat.IsAttackAlreadyCalled = false;
PrepareByParameters(
FinishActon,
FilterAttackTargets,
null,
Selection.ThisShip.Owner.PlayerNo,
ShowSkipButton,
AbilityName,
Description,
ImageSource
);
}
public override void Initialize()
{
// If not skipped
if (Phases.CurrentSubPhase == this) Selection.ThisShip.Owner.StartExtraAttack();
}
private bool FilterAttackTargets(GenericShip ship)
{
BoardTools.DistanceInfo distanceInfo = new BoardTools.DistanceInfo(Selection.ThisShip, ship);
return ship.Owner.PlayerNo != Selection.ThisShip.Owner.PlayerNo && distanceInfo.Range >= minRange && distanceInfo.Range <= maxRange;
}
private void FinishActon()
{
Selection.AnotherShip = TargetShip;
// TODO CHECK
Combat.ChosenWeapon = Selection.ThisShip.PrimaryWeapons.First();
Combat.ShotInfo = new BoardTools.ShotInfo(Selection.ThisShip, TargetShip, Combat.ChosenWeapon);
MovementTemplates.ShowFiringArcRange(Combat.ShotInfo);
ExtraAttackTargetSelected();
}
private void ExtraAttackTargetSelected()
{
var subphase = Phases.StartTemporarySubPhaseNew(
"Extra Attack",
typeof(ExtraAttackSubPhase),
delegate {
Phases.FinishSubPhase(typeof(ExtraAttackSubPhase));
Phases.FinishSubPhase(typeof(SelectTargetForSecondAttackSubPhase));
CallBack();
}
);
subphase.Start();
GameCommand command = Combat.GenerateIntentToAttackCommand(Selection.ThisShip.ShipId, Selection.AnotherShip.ShipId);
if (command != null) GameMode.CurrentGameMode.ExecuteCommand(command);
}
public override void RevertSubPhase() { }
public override void SkipButton()
{
UI.HideSkipButton();
Phases.FinishSubPhase(typeof(SelectTargetForSecondAttackSubPhase));
CallBack();
}
public override void Next()
{
Roster.AllShipsHighlightOff();
HideSubphaseDescription();
Combat.ExtraAttackFilter = null;
Phases.CurrentSubPhase = PreviousSubPhase;
}
public override void Resume()
{
base.Resume();
UpdateHelpInfo();
UI.ShowSkipButton();
IsReadyForCommands = true;
GameController.CheckExistingCommands();
}
}
} | 30.64 | 144 | 0.587794 | [
"MIT"
] | GeneralVryth/FlyCasual | Assets/Scripts/Model/Phases/SubPhases/Temporary/SelectTargetForSecondAttackSubPhase.cs | 3,066 | C# |
/* Problem 2. Concatenate text files
Write a program that concatenates two text files into another text file.
*/
namespace ConcatenateTextFiles
{
using System;
using System.IO;
class ConcatenateTextFiles
{
static void Main()
{
using (var output = File.Create("../../Result.txt"))
{
foreach (var file in new[] {
"../../TextFileOne.txt",
"../../TextFileTwo.txt"})
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
StreamReader reader = new StreamReader("../../Result.txt");
using (reader)
{
int lineNumber = 0;
string line = reader.ReadLine();
while (line != null)
{
lineNumber++;
Console.WriteLine(line);
line = reader.ReadLine();
}
}
}
}
}
| 23.125 | 76 | 0.412613 | [
"MIT"
] | KaloyanchoSt/Telerik-Academy-HW | 1. Programming C#/2. CSharp-Part-2/08. Text-Files/02. ConcatenateTextFiles/ConcatenateTextFiles .cs | 1,112 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.CosmosDB.Models
{
public partial class CosmosTableCreateOrUpdateContent : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
writer.WritePropertyName("location");
writer.WriteStringValue(Location);
writer.WritePropertyName("properties");
writer.WriteStartObject();
writer.WritePropertyName("resource");
writer.WriteObjectValue(Resource);
if (Optional.IsDefined(Options))
{
writer.WritePropertyName("options");
writer.WriteObjectValue(Options);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static CosmosTableCreateOrUpdateContent DeserializeCosmosTableCreateOrUpdateContent(JsonElement element)
{
IDictionary<string, string> tags = default;
AzureLocation location = default;
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
SystemData systemData = default;
TableResource resource = default;
Optional<CreateUpdateOptions> options = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("tags"))
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, property0.Value.GetString());
}
tags = dictionary;
continue;
}
if (property.NameEquals("location"))
{
location = new AzureLocation(property.Value.GetString());
continue;
}
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = new ResourceType(property.Value.GetString());
continue;
}
if (property.NameEquals("systemData"))
{
systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("resource"))
{
resource = TableResource.DeserializeTableResource(property0.Value);
continue;
}
if (property0.NameEquals("options"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
options = CreateUpdateOptions.DeserializeCreateUpdateOptions(property0.Value);
continue;
}
}
continue;
}
}
return new CosmosTableCreateOrUpdateContent(id, name, type, systemData, tags, location, resource, options.Value);
}
}
}
| 38.811475 | 125 | 0.497782 | [
"MIT"
] | damodaravadhani/azure-sdk-for-net | sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/Models/CosmosTableCreateOrUpdateContent.Serialization.cs | 4,735 | C# |
#region License
// Procedural planet generator.
//
// Copyright (C) 2015-2018 Denis Ovchinnikov [zameran]
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// Creation Date: 2017.03.07
// Creation Time: 10:30 PM
// Creator: zameran
#endregion
using SpaceEngine.Core.Exceptions;
using SpaceEngine.Core.Numerics.Vectors;
using SpaceEngine.Core.Storage;
using SpaceEngine.Core.Tile.Producer;
using SpaceEngine.Core.Tile.Storage;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace SpaceEngine.Core
{
public class ColorCoreProducer : TileProducer
{
public GameObject NormalsProducerGameObject;
public GameObject ElevationProducerGameObject;
private TileProducer NormalsProducer;
private TileProducer ElevationProducer;
public Material ColorMaterial;
public override void InitNode()
{
base.InitNode();
if (NormalsProducerGameObject != null)
{
if (NormalsProducer == null) { NormalsProducer = NormalsProducerGameObject.GetComponent<TileProducer>(); }
}
if (ElevationProducerGameObject != null)
{
if (ElevationProducer == null) { ElevationProducer = ElevationProducerGameObject.GetComponent<TileProducer>(); }
}
var tileSize = Cache.GetStorage(0).TileSize;
var normalsTileSize = NormalsProducer.Cache.GetStorage(0).TileSize;
var elevationTileSize = ElevationProducer.Cache.GetStorage(0).TileSize;
if (tileSize != normalsTileSize)
{
throw new InvalidParameterException("Tile size must equal normals tile size" + string.Format(": {0}-{1}", tileSize, normalsTileSize));
}
if (tileSize != elevationTileSize)
{
throw new InvalidParameterException("Tile size must equal elevation tile size" + string.Format(": {0}-{1}", tileSize, elevationTileSize));
}
if (GetBorder() != NormalsProducer.GetBorder())
{
throw new InvalidParameterException("Border size must be equal to normals border size");
}
if (GetBorder() != ElevationProducer.GetBorder())
{
throw new InvalidParameterException("Border size must be equal to elevation border size");
}
if (!(Cache.GetStorage(0) is GPUTileStorage))
{
throw new InvalidStorageException("Storage must be a GPUTileStorage");
}
}
public override bool HasTile(int level, int tx, int ty)
{
return ElevationProducer.HasTile(level, tx, ty) && NormalsProducer.HasTile(level, tx, ty);
}
public override int GetBorder()
{
return 2;
}
public override void DoCreateTile(int level, int tx, int ty, List<TileStorage.Slot> slot)
{
var gpuSlot = slot[0] as GPUTileStorage.GPUSlot;
var normalsTile = NormalsProducer.FindTile(level, tx, ty, false, true);
var elevationTile = ElevationProducer.FindTile(level, tx, ty, false, true);
GPUTileStorage.GPUSlot normalsGpuSlot = null;
if (normalsTile != null)
normalsGpuSlot = normalsTile.GetSlot(0) as GPUTileStorage.GPUSlot;
else { throw new MissingTileException("Find normals tile failed"); }
GPUTileStorage.GPUSlot elevationGpuSlot = null;
if (elevationTile != null)
elevationGpuSlot = elevationTile.GetSlot(0) as GPUTileStorage.GPUSlot;
else { throw new MissingTileException("Find elevation tile failed"); }
if (gpuSlot == null) { throw new NullReferenceException("gpuSlot"); }
if (elevationGpuSlot == null) { throw new NullReferenceException("elevationGpuSlot"); }
if (normalsGpuSlot == null) { throw new NullReferenceException("normalsGpuSlot"); }
var tileWidth = gpuSlot.Owner.TileSize;
var normalsTex = normalsGpuSlot.Texture;
var elevationTex = elevationGpuSlot.Texture;
var normalsOSL = new Vector4(0.25f / (float)normalsTex.width, 0.25f / (float)normalsTex.height, 1.0f / (float)normalsTex.width, 0.0f);
var elevationOSL = new Vector4(0.25f / (float)elevationTex.width, 0.25f / (float)elevationTex.height, 1.0f / (float)elevationTex.width, 0.0f);
var tileSize = tileWidth - (float)(1 + GetBorder() * 2);
var rootQuadSize = TerrainNode.TerrainQuadRoot.Length;
var tileWSD = Vector4.zero;
tileWSD.x = (float)tileWidth;
tileWSD.y = (float)rootQuadSize / (float)(1 << level) / (float)tileSize;
tileWSD.z = (float)tileSize / (float)(TerrainNode.ParentBody.GridResolution - 1);
tileWSD.w = 0.0f;
var tileScreenSize = (0.5 + (float)GetBorder()) / (tileWSD.x - 1 - (float)GetBorder() * 2);
var tileSD = new Vector2d(tileScreenSize, 1.0 + tileScreenSize * 2.0);
var offset = new Vector4d(((double)tx / (1 << level) - 0.5) * rootQuadSize,
((double)ty / (1 << level) - 0.5) * rootQuadSize,
rootQuadSize / (1 << level),
TerrainNode.ParentBody.Size);
ColorMaterial.SetTexture("_NormalsSampler", normalsTex);
ColorMaterial.SetVector("_NormalsOSL", normalsOSL);
ColorMaterial.SetTexture("_ElevationSampler", elevationTex);
ColorMaterial.SetVector("_ElevationOSL", elevationOSL);
ColorMaterial.SetFloat("_Level", level);
ColorMaterial.SetVector("_TileWSD", tileWSD);
ColorMaterial.SetVector("_TileSD", tileSD.ToVector2());
ColorMaterial.SetVector("_Offset", offset.ToVector4());
ColorMaterial.SetMatrix("_LocalToWorld", TerrainNode.FaceToLocal.ToMatrix4x4());
if (TerrainNode.ParentBody.TCCPS != null) TerrainNode.ParentBody.TCCPS.SetUniforms(ColorMaterial);
if (TerrainNode.ParentBody.TCCPS != null) TerrainNode.ParentBody.TCCPS.ToggleKeywords(ColorMaterial);
Graphics.Blit(null, gpuSlot.Texture, ColorMaterial);
base.DoCreateTile(level, tx, ty, slot);
}
}
} | 44.179775 | 154 | 0.65056 | [
"BSD-3-Clause"
] | CyberSys/SpaceW | Assets/Project/SpaceEngine/Code/Core/Producers/Color/ColorCoreProducer.cs | 7,866 | C# |
using System.Data.CRUD;
using MySql.Data.MySqlClient;
namespace GG.SSO.Entity.Table.Sso
{
[DataClassCRUD("sso","userclaims")]
public class UserClaims : Entity<UserClaims>
{
[DataMemberCRUD("Id", MySqlDbType.Int32, 10, true, true)]
public int Id { get; set; }
[DataMemberCRUD("Users_Id", MySqlDbType.VarChar, 450, true)]
public string Users_Id { get; set; }
[DataMemberCRUD("Type", MySqlDbType.VarChar, 7000)]
public string Type { get; set; }
[DataMemberCRUD("Value", MySqlDbType.VarChar, 7000)]
public string Value { get; set; }
[DataMemberCRUD("ValueType", MySqlDbType.VarChar, 7000)]
public string ValueType { get; set; }
public UserClaims()
{}
public UserClaims(int id,string users_Id,string type,string value,string valueType)
{
Id = id;
Users_Id = users_Id;
Type = type;
Value = value;
ValueType = valueType;
}
}
}
| 23.756757 | 85 | 0.691695 | [
"MIT"
] | guillermo-galvan/portafolio | src/GG.SSO.Entity/Table/Sso/Userclaims.cs | 879 | C# |
using Microsoft.Extensions.Logging;
using Phonebook.Common.Commands;
using Phonebook.Common.Events;
using Phonebook.Common.Exceptions;
using Phonebook.Services.Entry.Domain.Services;
using RawRabbit;
using System;
using System.Threading.Tasks;
namespace Phonebook.Services.Entry.Handlers
{
public class InsertEntryHandler : ICommandHandler<xEntry>
{
private readonly IBusClient _busClient;
private readonly IEntryService _service;
private readonly ILogger<InsertEntryHandler> _logger;
public InsertEntryHandler(IBusClient busClient,
IEntryService service,
ILogger<InsertEntryHandler> logger)
{
_busClient = busClient;
_service = service;
_logger = logger;
}
public async Task HandleAsync(xEntry command)
{
try
{
_logger.LogInformation($"Creating phonebook entry: {command.Name} {command.PhoneNumber}");
await _service.AddAsync(
command.Id,
command.Name,
command.PhoneNumber
);
var xEntry = await _service.GetAsync(command.Id);
await _busClient.PublishAsync(new EntryCreated(
xEntry.Id,
xEntry.Name,
xEntry.PhoneNumber
));
return;
}
catch (PhonebookException ex)
{
await _busClient.PublishAsync(new EntryRejected(
command.Id,
ex.Code,
ex.Message
));
_logger.LogError(ex.Message);
}
catch (Exception ex)
{
await _busClient.PublishAsync(new EntryRejected(
command.Id,
"error",
ex.Message
));
_logger.LogError(ex.Message);
}
}
}
}
| 29.463768 | 106 | 0.526808 | [
"MIT"
] | brentwhittaker/react-asp-net-core-phonebook | Phonebook.Services.Entry/Handlers/InsertEntryHandler.cs | 2,033 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WindowsFormsApp2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApp2")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef861190-0d8d-481f-8a23-7fbc48645b5c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.749286 | [
"MIT"
] | PedroVillacreces/PersonalOCR | WindowsFormsApp2/Properties/AssemblyInfo.cs | 1,403 | C# |
namespace AssetMonitoring.API.Controllers
{
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Results;
using AssetMonitoring.Contracts;
using AssetMonitoring.Services;
/// <summary>
/// Provide sensor rule APIs.
/// </summary>
/// <seealso cref="System.Web.Http.ApiController" />
public class SensorRuleController : ApiController
{
private readonly ISensorRuleService sensorRuleService;
/// <summary>
/// Initializes a new instance of the <see cref="SensorRuleController"/> class.
/// </summary>
/// <param name="sensorRuleService">The sensor rule service.</param>
public SensorRuleController(ISensorRuleService sensorRuleService)
{
this.sensorRuleService = sensorRuleService;
}
/// <summary>
/// Gets the specified sensor rule.
/// </summary>
/// <param name="id">The sensor rule identifier.</param>
/// <returns>The sensor rule detail if found else NotFound(404) status code.</returns>
[ResponseType(typeof(SensorRule))]
public IHttpActionResult Get(int id)
{
var sensor = this.sensorRuleService.Get(id);
if (sensor == null)
{
return this.NotFound();
}
return this.Ok(sensor);
}
/// <summary>
/// Gets all sensor rules.
/// </summary>
/// <returns>The sensor rule details.</returns>
public List<SensorRule> GetAll()
{
var sensorRules = this.sensorRuleService.GetAll();
return sensorRules;
}
/// <summary>
/// Creates the specified sensor rule.
/// </summary>
/// <param name="id">The sensor group identifier.</param>
/// <param name="sensorRules">The sensor rule.</param>
/// <returns>
/// The created(201) on successfully creation else BadRequest(400) status code.
/// </returns>
[ResponseType(typeof(StatusCodeResult))]
public async Task<IHttpActionResult> Post(int id, List<SensorRule> sensorRules)
{
if (id < 1)
{
return this.BadRequest("Sensor group id must be grater than 0.");
}
if (sensorRules == null || sensorRules.Count < 1 || sensorRules.Any(s => s.CapabilityFilterId < 1))
{
return this.BadRequest("Invalid sensor rule model.");
}
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState);
}
var operationStatus = await this.sensorRuleService.Create(id, sensorRules);
if (operationStatus.StatusCode == Contracts.Enums.StatusCode.Ok)
{
return this.StatusCode(HttpStatusCode.Created);
}
else
{
return this.BadRequest(operationStatus.Message);
}
}
/// <summary>
/// Updates the specified sensor rule.
/// Can not modify sensor group.
/// </summary>
/// <param name="sensorRule">The sensor rule.</param>
/// <returns>The updated(204) on successfully updation else BadRequest(400) status code.</returns>
[ResponseType(typeof(StatusCodeResult))]
public async Task<IHttpActionResult> Put(SensorRule sensorRule)
{
if (sensorRule == null || sensorRule.Id < 1)
{
return this.BadRequest("Invalid sensor rule model.");
}
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState);
}
var operationStatus = await this.sensorRuleService.Update(sensorRule);
if (operationStatus.StatusCode == Contracts.Enums.StatusCode.Ok)
{
return this.StatusCode(HttpStatusCode.NoContent);
}
else
{
return this.BadRequest(operationStatus.Message);
}
}
/// <summary>
/// Deletes the specified sensor rule.
/// </summary>
/// <param name="id">The sensor rule identifier.</param>
/// <returns>The deleted(204) on successfully deletion else BadRequest(400) status code.</returns>
[HttpDelete]
[ResponseType(typeof(StatusCodeResult))]
public async Task<IHttpActionResult> Delete(int id)
{
if (id < 1)
{
return this.BadRequest("Sensor rule id must be grater than 0.");
}
var operationStatus = await this.sensorRuleService.Delete(id);
if (operationStatus.StatusCode == Contracts.Enums.StatusCode.Ok)
{
return this.StatusCode(HttpStatusCode.NoContent);
}
else
{
return this.BadRequest(operationStatus.Message);
}
}
}
}
| 33.480519 | 111 | 0.560512 | [
"Apache-2.0"
] | MobiliyaTechnologies/AMSRESTServer | AssetMonitoring/AssetMonitoring.API/Controllers/SensorRuleController.cs | 5,158 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Doorway : MonoBehaviour {
public Animator anim;
public bool isOpen;
public bool showNotice;
public GameObject notice;
public bool unlocked = false;
private void Start()
{
anim = transform.parent.GetComponent<Animator>();
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
showNotice = true;
}
}
private void OnTriggerExit(Collider other)
{
if(other.gameObject.tag == "Player")
{
showNotice = false;
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player")
{
showNotice = true;
}
if (!isOpen && other.gameObject.tag == "Player")
{
if (Input.GetKey("joystick "+other.GetComponent<PlayerController>().player+" button 2"))
{
openDoor();
GetComponent<AudioSource>().Play();
}
}
}
private void Update()
{
if (notice)
{
notice.SetActive(!isOpen && showNotice && unlocked);
}
}
void openDoor()
{
if (unlocked)
{
isOpen = true;
anim.SetBool("isOpen", true);
}
}
}
| 20.405797 | 100 | 0.522727 | [
"Apache-2.0"
] | 12Cylinder/Darkfloor | Assets/Code/Doorway.cs | 1,410 | C# |
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace FamilyTree.WebUI.Hubs
{
public class PrivacyHub : Hub
{
public async Task SendPrivacyChangedNotification(int privacyId, string userId)
{
await Clients.User(userId)
.SendAsync("ReceivePrivacyChangedNotification", privacyId);
}
}
}
| 25.6 | 86 | 0.651042 | [
"MIT"
] | VuacheslavSichkarenko/FamilyTree | FamilyTree.WebUI/Hubs/PrivacyHub.cs | 386 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIManager : MonoBehaviourSingleton<UIManager>
{
public enum eScreens
{
Title = 0,
Gameover,
Win,
HUD,
MAX = HUD
}
[SerializeField]
private List<UIBaseScreen> m_ScreenPrefabs;
[SerializeField]
private Camera m_UICamera;
private UIBaseScreen m_CurrentScreen;
private eScreens m_CurrentScreenID = eScreens.Title;
// Start is called before the first frame update
void Start()
{
LoadScreen(eScreens.Title);
}
public void StartGameplay()
{
m_UICamera.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
public void LoadScreen(eScreens screen)
{
if (m_CurrentScreen != null)
{
m_CurrentScreen.Shutdown();
GameObject.Destroy(m_CurrentScreen.gameObject);
}
m_CurrentScreen = GameObject.Instantiate(m_ScreenPrefabs[(int)screen], this.transform, false).GetComponent<UIBaseScreen>();
m_CurrentScreen.Init();
}
}
| 18.622642 | 125 | 0.743668 | [
"MIT"
] | KXue/LDJam46 | Assets/Scripts/Systems/UIManager.cs | 989 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ejercicio6 : MonoBehaviour
{
//6. Realizá un programa que permita el ingreso por Inspector de
//un valor entero mayor que 0 en una variable llamada num1 y muestre
//un mensaje por pantalla indicando "el número es par"; o
//"el número es impar". Deberá utilizar el operador “módulo”
//es el caracter %.
public int num1;
void Start()
{
if((num1 % 2) == 0)
{
Debug.Log ("Es un número par");
}
else
{
Debug.Log ("Es un número impar");
}
}
// Update is called once per frame
void Update()
{
}
} | 24.3 | 73 | 0.576132 | [
"MIT"
] | OctavioSpano/Guia-de-Programacion-1 | Assets/Scripts/Ejercicio6.cs | 742 | C# |
using System;
namespace FritzBoxAPI.Model.Constants
{
public class XPathConstants
{
public const String PHONEBOOKTABLENODEID = "td/button[@class =\"icon edit\"]";
public const String PHONEBOOKTABLENODENAME = "td[@class =\"tname\"]";
public const String PHONEBOOKTABLENODENUMBER = "td[@class=\"tnum\"]";
public const String PHONEBOOKTABLENODETYPE = "td[@class=\"ttype\"]";
public const String PHONEBOOKMETADATA = "form";
public const String PHONEBOOKISLIST = "div[@class=\"formular\"]";
}
}
| 36.8 | 86 | 0.666667 | [
"MIT"
] | MagicMango/dotnetfrizboxapi | Model/Constants/XPathConstants.cs | 554 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Gigya.Common.Contracts.Exceptions;
using Gigya.Microdot.ServiceProxy;
using Metrics;
using Metrics.MetricData;
using NUnit.Framework;
using RichardSzalay.MockHttp;
// ReSharper disable UnusedVariable
namespace Gigya.Microdot.UnitTests.ServiceProxyTests
{
[TestFixture, Parallelizable(ParallelScope.None)]
public class MetricsTests : AbstractServiceProxyTest
{
[Test]
public async Task SuccessTest()
{
var resMessage = HttpResponseFactory.GetResponse(content:"''");
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
await CreateClient(messageHandler).ToUpper("aaaa");
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "Success", Unit = Unit.Calls });
expected.Timers.Add(new MetricDataEquatable {Name = "Deserialization", Unit = Unit.Calls});
GetMetricsData().AssertEquals(expected);
}
[Test]
public async Task RequestTimeoutTest()
{
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(a => { throw new TaskCanceledException(); });
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "Failed", Unit = Unit.Calls, SubCounters = new[] {"RequestTimeout"} });
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task NotGigyaServerBadRequestTest()
{
var resMessage = HttpResponseFactory.GetResponse(HttpStatusCode.ServiceUnavailable, isGigyaHost:false);
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "HostFailure", Unit = Unit.Calls });
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task NotGigyaServerFailureTest()
{
var resMessage = HttpResponseFactory.GetResponse(isGigyaHost: false);
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "HostFailure", Unit = Unit.Calls });
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task JsonSerializationExceptionTest()
{
var resMessage = HttpResponseFactory.GetResponse(content: "{");
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "Failed", Unit = Unit.Calls });
expected.Timers.Add(new MetricDataEquatable { Name = "Deserialization", Unit = Unit.Calls });
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task HostsFailureTest()
{
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(a => { throw new HttpRequestException(); });
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters = new List<MetricDataEquatable>()
{
new MetricDataEquatable { Name = "HostFailure", Unit = Unit.Calls }
};
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task NullExceptionReceivedTest()
{
var resMessage = HttpResponseFactory.GetResponseWithException(ExceptionSerializer, new NullReferenceException());
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (Exception)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "ApplicationException", Unit = Unit.Calls });
expected.Timers.Add(new MetricDataEquatable { Name = "Deserialization", Unit = Unit.Calls });
GetMetricsData().AssertEquals(expected);
}
}
[Test]
public async Task RequestExceptionReceivedTest()
{
var resMessage = HttpResponseFactory.GetResponseWithException(ExceptionSerializer, new RequestException("Post not allowed"), HttpStatusCode.MethodNotAllowed);
var messageHandler = new MockHttpMessageHandler();
messageHandler.When("*").Respond(resMessage);
try
{
await CreateClient(messageHandler).ToUpper("aaaa");
}
catch (RequestException)
{
var expected = DefaultExpected();
expected.Counters.Add(new MetricDataEquatable { Name = "ApplicationException", Unit = Unit.Calls });
expected.Timers.Add(new MetricDataEquatable { Name = "Deserialization", Unit = Unit.Calls});
GetMetricsData().AssertEquals(expected);
}
}
private static MetricsData GetMetricsData()
{
return
Metric.Context(ServiceProxyProvider.METRICS_CONTEXT_NAME)
.Context("DemoService")
.DataProvider.CurrentMetricsData;
}
private static MetricsDataEquatable DefaultExpected()
{
return new MetricsDataEquatable
{
Counters = new List<MetricDataEquatable>(),
Timers = new List<MetricDataEquatable> {
new MetricDataEquatable{Name = "Serialization",Unit= Unit.Calls},
new MetricDataEquatable{Name = "Roundtrip",Unit= Unit.Calls}
}
};
}
}
} | 33.808219 | 170 | 0.55443 | [
"Apache-2.0"
] | dinavinter/microdot | tests/Gigya.Microdot.UnitTests/ServiceProxyTests/MetricsTests.cs | 7,406 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class BTests
{
const int TimeLimit = 2000;
const double RelativeError = 1e-9;
[TestMethod, Timeout(TimeLimit)]
public void Test1()
{
const string input = @"4
";
const string output = @"1
3
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
[TestMethod, Timeout(TimeLimit)]
public void Test2()
{
const string input = @"7
";
const string output = @"1
2
4
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
[TestMethod, Timeout(TimeLimit)]
public void Test3()
{
const string input = @"1
2
4
";
const string output = @"1
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
}
}
| 19.297872 | 59 | 0.527012 | [
"CC0-1.0"
] | AconCavy/AtCoder.Tasks.CS | AGC-Like/CF16-FINAL/Tests/BTests.cs | 907 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace BuildXL.Cache.ContentStore.Distributed.Stores
{
/// <nodoc />
public enum CopyReason
{
/// <nodoc />
None,
/// <nodoc />
Pin,
/// <nodoc />
Put,
/// <nodoc />
Replication,
/// <nodoc />
Place,
/// <nodoc />
OpenStream,
/// <nodoc />
AsyncPin,
/// <nodoc />
CentralStorage,
}
}
| 16.117647 | 56 | 0.417883 | [
"MIT"
] | RobJellinghaus/BuildXL | Public/Src/Cache/ContentStore/Distributed/Stores/CopyReason.cs | 550 | C# |
namespace Bodoconsult.Core.Windows.Network.Dhcp.Native
{
/// <summary>
/// The DHCP_FAILOVER_MODE enumeration defines the DHCPv4 server mode operation in a failover relationship.
/// </summary>
internal enum DHCP_FAILOVER_MODE
{
/// <summary>
/// The DHCPv4 server failover relationship is in Load Balancing mode.
/// </summary>
LoadBalance,
/// <summary>
/// The DHCPv4 server failover relationship is in Hot Standby mode.
/// </summary>
HotStandby
}
}
| 30.166667 | 111 | 0.626151 | [
"MIT"
] | RobertLeisner/Bodoconsult.Core.Windows | Bodoconsult.Core.Windows/Network/Dhcp/Native/DHCP_FAILOVER_MODE.cs | 545 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace CrocCSharpBot
{
/// <summary>
/// Пользователь бота
/// </summary>
public class User
{ /// <summary>
/// Индетифекатор пользователя Telegram
/// </summary>
[XmlAttribute()]
public long ID;
/// <summary>
/// Имя
/// </summary>
[XmlElement(ElementName = "Name")]
public string FirstName;
/// <summary>
/// Фамилия
/// </summary>
[XmlElement(ElementName = "Family")]
public string LastName;
/// <summary>
/// Имя пользователя (nickname)
/// </summary>
public string UserName;
/// <summary>
/// Номер телефона пользователя
/// </summary>
public string PhoneNumber;
/// <summary>
/// Описание пользователя
/// </summary>
[XmlText()]
public string Description;
}
}
| 24.113636 | 47 | 0.540999 | [
"MIT"
] | marik1822/crocBot | CrocCSharpBot1/CrocCSharpBot/User.cs | 1,174 | C# |
/*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System.Threading.Tasks;
using CommandLine;
using Playwright.Tooling.Options;
namespace Playwright.Tooling
{
internal static class Program
{
internal static async Task Main(string[] args)
{
ParserResult<DownloadDriversOptions> result = Parser.Default.ParseArguments<DownloadDriversOptions>(args);
await result.WithParsedAsync(DriverDownloader.RunAsync).ConfigureAwait(false);
}
}
}
| 39.725 | 118 | 0.747011 | [
"MIT"
] | Archish27/playwright-dotnet | src/tools/Playwright.Tooling/Program.cs | 1,589 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace IL.Library.Amazon.SPAPI.Finances.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A credit given to a solution provider.
/// </summary>
public partial class SolutionProviderCreditEvent
{
/// <summary>
/// Initializes a new instance of the SolutionProviderCreditEvent
/// class.
/// </summary>
public SolutionProviderCreditEvent()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SolutionProviderCreditEvent
/// class.
/// </summary>
/// <param name="providerTransactionType">The transaction type.</param>
/// <param name="sellerOrderId">A seller-defined identifier for an
/// order.</param>
/// <param name="marketplaceId">The identifier of the marketplace where
/// the order was placed.</param>
/// <param name="marketplaceCountryCode">The two-letter country code of
/// the country associated with the marketplace where the order was
/// placed.</param>
/// <param name="sellerId">The Amazon-defined identifier of the
/// seller.</param>
/// <param name="sellerStoreName">The store name where the payment
/// event occurred.</param>
/// <param name="providerId">The Amazon-defined identifier of the
/// solution provider.</param>
/// <param name="providerStoreName">The store name where the payment
/// event occurred.</param>
/// <param name="transactionAmount">The amount of the credit.</param>
/// <param name="transactionCreationDate">The date and time that the
/// credit transaction was created, in ISO 8601 date time
/// format.</param>
public SolutionProviderCreditEvent(string providerTransactionType = default(string), string sellerOrderId = default(string), string marketplaceId = default(string), string marketplaceCountryCode = default(string), string sellerId = default(string), string sellerStoreName = default(string), string providerId = default(string), string providerStoreName = default(string), Currency transactionAmount = default(Currency), System.DateTime? transactionCreationDate = default(System.DateTime?))
{
ProviderTransactionType = providerTransactionType;
SellerOrderId = sellerOrderId;
MarketplaceId = marketplaceId;
MarketplaceCountryCode = marketplaceCountryCode;
SellerId = sellerId;
SellerStoreName = sellerStoreName;
ProviderId = providerId;
ProviderStoreName = providerStoreName;
TransactionAmount = transactionAmount;
TransactionCreationDate = transactionCreationDate;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the transaction type.
/// </summary>
[JsonProperty(PropertyName = "ProviderTransactionType")]
public string ProviderTransactionType { get; set; }
/// <summary>
/// Gets or sets a seller-defined identifier for an order.
/// </summary>
[JsonProperty(PropertyName = "SellerOrderId")]
public string SellerOrderId { get; set; }
/// <summary>
/// Gets or sets the identifier of the marketplace where the order was
/// placed.
/// </summary>
[JsonProperty(PropertyName = "MarketplaceId")]
public string MarketplaceId { get; set; }
/// <summary>
/// Gets or sets the two-letter country code of the country associated
/// with the marketplace where the order was placed.
/// </summary>
[JsonProperty(PropertyName = "MarketplaceCountryCode")]
public string MarketplaceCountryCode { get; set; }
/// <summary>
/// Gets or sets the Amazon-defined identifier of the seller.
/// </summary>
[JsonProperty(PropertyName = "SellerId")]
public string SellerId { get; set; }
/// <summary>
/// Gets or sets the store name where the payment event occurred.
/// </summary>
[JsonProperty(PropertyName = "SellerStoreName")]
public string SellerStoreName { get; set; }
/// <summary>
/// Gets or sets the Amazon-defined identifier of the solution
/// provider.
/// </summary>
[JsonProperty(PropertyName = "ProviderId")]
public string ProviderId { get; set; }
/// <summary>
/// Gets or sets the store name where the payment event occurred.
/// </summary>
[JsonProperty(PropertyName = "ProviderStoreName")]
public string ProviderStoreName { get; set; }
/// <summary>
/// Gets or sets the amount of the credit.
/// </summary>
[JsonProperty(PropertyName = "TransactionAmount")]
public Currency TransactionAmount { get; set; }
/// <summary>
/// Gets or sets the date and time that the credit transaction was
/// created, in ISO 8601 date time format.
/// </summary>
[JsonProperty(PropertyName = "TransactionCreationDate")]
public System.DateTime? TransactionCreationDate { get; set; }
}
}
| 41.323529 | 497 | 0.625623 | [
"Apache-2.0"
] | InventoryLab/selling-partner-api-models | clients/IL/Finances/Models/SolutionProviderCreditEvent.cs | 5,620 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
#if WINHTTPHANDLER_TEST
using HttpClientHandler = System.Net.Http.WinHttpClientHandler;
#endif
public abstract class HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_MaxResponseHeadersLength_Test(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void InvalidValue_ThrowsException(int invalidValue)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
}
}
[Theory]
[InlineData(1)]
[InlineData(65)]
[InlineData(int.MaxValue)]
public void ValidValue_SetGet_Roundtrips(int validValue)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.MaxResponseHeadersLength = validValue;
Assert.Equal(validValue, handler.MaxResponseHeadersLength);
}
}
[Fact]
public async Task SetAfterUse_Throws()
{
if (IsWinHttpHandler && UseVersion >= HttpVersion20.Value)
{
return;
}
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
using HttpClientHandler handler = CreateHttpClientHandler();
using HttpClient client = CreateHttpClient(handler);
handler.MaxResponseHeadersLength = 1;
(await client.GetStreamAsync(uri)).Dispose();
Assert.Throws<InvalidOperationException>(() => handler.MaxResponseHeadersLength = 1);
},
server => server.AcceptConnectionSendResponseAndCloseAsync());
}
[OuterLoop]
[Fact]
public async Task InfiniteSingleHeader_ThrowsException()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
var cts = new CancellationTokenSource();
Task serverTask = Task.Run(async delegate
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nMyInfiniteHeader: ");
try
{
while (!cts.IsCancellationRequested)
{
await connection.WriteStringAsync(new string('s', 16000));
await Task.Delay(1);
}
}
catch (Exception ex)
{
_output.WriteLine($"Ignored exception:{Environment.NewLine}{ex}");
}
});
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
cts.Cancel();
if (!IsWinHttpHandler)
{
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
}
await serverTask;
});
}
});
}
[OuterLoop]
[Theory, MemberData(nameof(ResponseWithManyHeadersData))]
public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int? maxResponseHeadersLength, bool shouldSucceed)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
if (maxResponseHeadersLength.HasValue)
{
handler.MaxResponseHeadersLength = maxResponseHeadersLength.Value;
}
Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
Task serverTask = connection.ReadRequestHeaderAndSendCustomResponseAsync(responseHeaders);
if (shouldSucceed)
{
(await getAsync).Dispose();
await serverTask;
}
else
{
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
if (!IsWinHttpHandler)
{
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
}
try
{
await serverTask;
}
catch (Exception ex)
{
_output.WriteLine($"Ignored exception:{Environment.NewLine}{ex}");
}
}
});
}
});
}
public static IEnumerable<object[]> ResponseWithManyHeadersData
{
get
{
foreach (int? max in new int?[] { null, 1, 31, 128 })
{
int actualSize = max.HasValue ? max.Value : 64;
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024 - 1), max, true }; // Small enough
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024), max, true }; // Just right
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024 + 1), max, false }; // Too big
}
}
}
private static string GenerateLargeResponseHeaders(int responseHeadersSizeInBytes)
{
var buffer = new StringBuilder();
buffer.Append("HTTP/1.1 200 OK\r\n");
buffer.Append("Content-Length: 0\r\n");
for (int i = 0; i < 24; i++)
{
buffer.Append($"Custom-{i:D4}: 1234567890123456789012345\r\n");
}
buffer.Append($"Custom-24: ");
buffer.Append(new string('c', responseHeadersSizeInBytes - (buffer.Length + 4)));
buffer.Append("\r\n\r\n");
string response = buffer.ToString();
Assert.Equal(responseHeadersSizeInBytes, response.Length);
return response;
}
}
}
| 41.089474 | 151 | 0.519918 | [
"MIT"
] | AlexanderSemenyak/runtime | src/libraries/Common/tests/System/Net/Http/HttpClientHandlerTest.MaxResponseHeadersLength.cs | 7,807 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tamago
{
public static class MathHelper
{
public static float ToRadians(float degrees)
{
return NormalizeAngle((float)(degrees * Math.PI / 180));
}
public static float NormalizeAngle(float angle)
{
var res = Math.IEEERemainder(angle, 2 * Math.PI);
if (res > Math.PI)
return (float)(res - (2 * Math.PI));
else if (res <= -Math.PI)
return (float)(res + (2 * Math.PI));
else
return (float)res;
}
}
}
| 25.75 | 69 | 0.524272 | [
"MIT"
] | echojc/Tamago | Tamago/MathHelper.cs | 723 | C# |
using System;
using Castle.Facilities.Logging;
using Abp;
using Abp.Castle.Logging.Log4Net;
using Abp.Collections.Extensions;
using Abp.Dependency;
namespace MetroStation.Migrator
{
public class Program
{
private static bool _quietMode;
public static void Main(string[] args)
{
ParseArgs(args);
using (var bootstrapper = AbpBootstrapper.Create<MetroStationMigratorModule>())
{
bootstrapper.IocManager.IocContainer
.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
);
bootstrapper.Initialize();
using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>())
{
var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
if (_quietMode)
{
// exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
var exitCode = Convert.ToInt32(!migrationSucceeded);
Environment.Exit(exitCode);
}
else
{
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
}
}
private static void ParseArgs(string[] args)
{
if (args.IsNullOrEmpty())
{
return;
}
foreach (var arg in args)
{
switch (arg)
{
case "-q":
_quietMode = true;
break;
}
}
}
}
}
| 29.138462 | 119 | 0.463569 | [
"MIT"
] | poxiaoqiu-px/metrostation | aspnet-core/src/MetroStation.Migrator/Program.cs | 1,896 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AzureWorker.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("https://cz3.vault.azure.net/")]
public string KeyVaultUrl {
get {
return ((string)(this["KeyVaultUrl"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("895a5b60-9798-4f21-9b8c-88f2278ebf68")]
public string AADApplicationId {
get {
return ((string)(this["AADApplicationId"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2eafe8e09fd3b416c68f4a375ac88fe06f05d0f8")]
public string AADApplicationCertThumbprint {
get {
return ((string)(this["AADApplicationCertThumbprint"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("connectionString")]
public string ConnectionStringSecretId {
get {
return ((string)(this["ConnectionStringSecretId"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("http://z3nightly.azurewebsites.net/")]
public string LinkPage {
get {
return ((string)(this["LinkPage"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string ReportRecipients {
get {
return ((string)(this["ReportRecipients"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("smtp.live.com")]
public string SmtpServerUrl {
get {
return ((string)(this["SmtpServerUrl"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("z3PerfEmailCredentials")]
public string SendEmailCredentialsSecretId {
get {
return ((string)(this["SendEmailCredentialsSecretId"]));
}
}
}
}
| 42.747475 | 151 | 0.619802 | [
"MIT"
] | Z3Prover/PerformanceTest | src/AzurePerformanceTest/AzureWorker/Properties/Settings.Designer.cs | 4,234 | C# |
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using BootstrapBlazor.Components;
using BootstrapBlazor.Shared.Common;
using BootstrapBlazor.Shared.Pages.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace BootstrapBlazor.Shared.Pages
{
/// <summary>
///
/// </summary>
public sealed partial class EditDialogs
{
private BindItem Model { get; set; } = new BindItem()
{
Name = "Name 1234",
Address = "Address 1234"
};
[Inject]
[NotNull]
private DialogService? DialogService { get; set; }
[NotNull]
private Logger? Trace { get; set; }
private async Task ShowDialog()
{
var option = new EditDialogOption<BindItem>()
{
Title = "编辑对话框",
Model = Model,
OnCloseAsync = () =>
{
Trace.Log("关闭按钮被点击");
return Task.CompletedTask;
},
OnSaveAsync = context =>
{
Trace.Log("保存按钮被点击");
return Task.FromResult(true);
}
};
await DialogService.ShowEditDialog(option);
}
/// <summary>
/// 获得属性方法
/// </summary>
/// <returns></returns>
private static IEnumerable<AttributeItem> GetAttributes() => new AttributeItem[]
{
// TODO: 移动到数据库中
new AttributeItem() {
Name = "ShowLabel",
Description = "是否显示标签",
Type = "bool",
ValueList = "true|false",
DefaultValue = "true"
},
new AttributeItem() {
Name = "Model",
Description = "泛型参数用于呈现 UI",
Type = "TModel",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "Items",
Description = "编辑项集合",
Type = "IEnumerable<IEditorItem>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "DialogBodyTemplate",
Description = "EditDialog Body 模板",
Type = "RenderFragment<TModel>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "CloseButtonText",
Description = "关闭按钮文本",
Type = "string",
ValueList = " — ",
DefaultValue = "关闭"
},
new AttributeItem() {
Name = "SaveButtonText",
Description = "保存按钮文本",
Type = "string",
ValueList = " — ",
DefaultValue = "保存"
},
new AttributeItem() {
Name = "OnSaveAsync",
Description = "保存回调委托",
Type = "Func<Task>",
ValueList = " — ",
DefaultValue = " — "
}
};
}
}
| 30.782609 | 111 | 0.464124 | [
"Apache-2.0"
] | 5118234/BootstrapBlazor | src/BootstrapBlazor.Shared/Pages/EditDialogs.razor.cs | 3,712 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Route53.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Route53.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AssociateVPCWithHostedZone operation
/// </summary>
public class AssociateVPCWithHostedZoneResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
AssociateVPCWithHostedZoneResponse response = new AssociateVPCWithHostedZoneResponse();
UnmarshallResult(context,response);
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, AssociateVPCWithHostedZoneResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 1;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("ChangeInfo", targetDepth))
{
var unmarshaller = ChangeInfoUnmarshaller.Instance;
response.ChangeInfo = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return;
}
}
return;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictingDomainExists"))
{
return ConflictingDomainExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInput"))
{
return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidVPCId"))
{
return InvalidVPCIdExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitsExceeded"))
{
return LimitsExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchHostedZone"))
{
return NoSuchHostedZoneExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotAuthorizedException"))
{
return NotAuthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("PublicZoneVPCAssociation"))
{
return PublicZoneVPCAssociationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonRoute53Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static AssociateVPCWithHostedZoneResponseUnmarshaller _instance = new AssociateVPCWithHostedZoneResponseUnmarshaller();
internal static AssociateVPCWithHostedZoneResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AssociateVPCWithHostedZoneResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.086667 | 162 | 0.622586 | [
"Apache-2.0"
] | Melvinerall/aws-sdk-net | sdk/src/Services/Route53/Generated/Model/Internal/MarshallTransformations/AssociateVPCWithHostedZoneResponseUnmarshaller.cs | 6,163 | C# |
using System.Text.Json;
using System.Text.Json.Serialization;
using Elsa.Management.Contracts;
namespace Elsa.Management.Serialization.Converters;
/// <summary>
/// Serializes <see cref="Type"/> objects to a simple alias representing said type.
/// </summary>
public class TypeJsonConverter : JsonConverter<Type>
{
private readonly IWellKnownTypeRegistry _wellKnownTypeRegistry;
public TypeJsonConverter(IWellKnownTypeRegistry wellKnownTypeRegistry)
{
_wellKnownTypeRegistry = wellKnownTypeRegistry;
}
public override Type? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var typeAlias = reader.GetString()!;
// Handle collection types.
if (typeAlias.EndsWith("[]"))
{
var elementTypeAlias = typeAlias[..^"[]".Length];
var elementType = _wellKnownTypeRegistry.TryGetType(typeAlias, out var t) ? t : Type.GetType(elementTypeAlias)!;
return typeof(List<>).MakeGenericType(elementType);
}
return _wellKnownTypeRegistry.TryGetType(typeAlias, out var type) ? type : Type.GetType(typeAlias);
}
public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options)
{
// Handle collection types.
if (value.IsGenericType)
{
var elementType = value.GenericTypeArguments.First();
var typedEnumerable = typeof(IEnumerable<>).MakeGenericType(elementType);
if (typedEnumerable.IsAssignableFrom(value))
{
var elementTypeAlias = _wellKnownTypeRegistry.TryGetAlias(elementType, out var elementAlias) ? elementAlias : value.AssemblyQualifiedName;
JsonSerializer.Serialize(writer, $"{elementTypeAlias}[]", options);
return;
}
}
var typeAlias = _wellKnownTypeRegistry.TryGetAlias(value, out var @alias) ? alias : value.AssemblyQualifiedName;
JsonSerializer.Serialize(writer, typeAlias, options);
}
} | 38.415094 | 154 | 0.685658 | [
"MIT"
] | elsa-workflows/experimental | src/core/Elsa.Management/Serialization/Converters/TypeJsonConverter.cs | 2,036 | C# |
using System;
using System.Linq.Expressions;
using StandardRepository.Models.Entities;
namespace StandardRepository.Models
{
public class OrderByInfo<T> where T : BaseEntity
{
public Expression<Func<T, object>> OrderByColumn { get; }
public bool IsAscending { get; }
public OrderByInfo(Expression<Func<T, object>> orderByColumn, bool isAscending = true)
{
OrderByColumn = orderByColumn;
IsAscending = isAscending;
}
}
} | 26.263158 | 94 | 0.663327 | [
"MIT"
] | anatolia/standard-repository | Sources/StandardRepository/Models/OrderByInfo.cs | 501 | C# |
#region Using Statements
using System;
using WaveEngine.Common;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Common.Media;
using WaveEngine.Components.Cameras;
using WaveEngine.Components.Graphics2D;
using WaveEngine.Components.Graphics3D;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Resources;
using WaveEngine.Framework.Services;
#endregion
namespace MusicProject
{
public class MyScene : Scene
{
protected override void CreateScene()
{
FixedCamera2D camera2d = new FixedCamera2D("camera");
camera2d.BackgroundColor = Color.CornflowerBlue;
EntityManager.Add(camera2d);
MusicInfo musicInfo = new MusicInfo("Content/ByeByeBrain.mp3");
WaveServices.MusicPlayer.Play(musicInfo);
}
}
}
| 28.290323 | 75 | 0.72634 | [
"MIT"
] | starostin13/Samples | Media/Music/Music/MusicProject/MyScene.cs | 877 | C# |
using System;
namespace Yuniql.PlatformTests.Setup
{
public class BulkTestDataRow
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? BirthDate { get; set; }
}
} | 17.428571 | 48 | 0.622951 | [
"Apache-2.0"
] | MariemKharrat/yuniql | yuniql-tests/platform-tests/Setup/BulkTestDataRow.cs | 246 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/xaudio2.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.CompilerServices;
namespace TerraFX.Interop
{
[NativeTypeName("struct IXAudio2MasteringVoice : IXAudio2Voice")]
[NativeInheritance("IXAudio2Voice")]
public unsafe partial struct IXAudio2MasteringVoice
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public void GetVoiceDetails(XAUDIO2_VOICE_DETAILS* pVoiceDetails)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, XAUDIO2_VOICE_DETAILS*, void>)(lpVtbl[0]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pVoiceDetails);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("HRESULT")]
public int SetOutputVoices([NativeTypeName("const XAUDIO2_VOICE_SENDS *")] XAUDIO2_VOICE_SENDS* pSendList)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, XAUDIO2_VOICE_SENDS*, int>)(lpVtbl[1]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pSendList);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("HRESULT")]
public int SetEffectChain([NativeTypeName("const XAUDIO2_EFFECT_CHAIN *")] XAUDIO2_EFFECT_CHAIN* pEffectChain)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, XAUDIO2_EFFECT_CHAIN*, int>)(lpVtbl[2]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pEffectChain);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
[return: NativeTypeName("HRESULT")]
public int EnableEffect([NativeTypeName("UINT32")] uint EffectIndex, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint, uint, int>)(lpVtbl[3]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), EffectIndex, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
[return: NativeTypeName("HRESULT")]
public int DisableEffect([NativeTypeName("UINT32")] uint EffectIndex, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint, uint, int>)(lpVtbl[4]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), EffectIndex, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public void GetEffectState([NativeTypeName("UINT32")] uint EffectIndex, [NativeTypeName("BOOL *")] int* pEnabled)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, uint, int*, void>)(lpVtbl[5]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), EffectIndex, pEnabled);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
[return: NativeTypeName("HRESULT")]
public int SetEffectParameters([NativeTypeName("UINT32")] uint EffectIndex, [NativeTypeName("const void *")] void* pParameters, [NativeTypeName("UINT32")] uint ParametersByteSize, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint, void*, uint, uint, int>)(lpVtbl[6]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), EffectIndex, pParameters, ParametersByteSize, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
[return: NativeTypeName("HRESULT")]
public int GetEffectParameters([NativeTypeName("UINT32")] uint EffectIndex, void* pParameters, [NativeTypeName("UINT32")] uint ParametersByteSize)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint, void*, uint, int>)(lpVtbl[7]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), EffectIndex, pParameters, ParametersByteSize);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
[return: NativeTypeName("HRESULT")]
public int SetFilterParameters([NativeTypeName("const XAUDIO2_FILTER_PARAMETERS *")] XAUDIO2_FILTER_PARAMETERS* pParameters, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, XAUDIO2_FILTER_PARAMETERS*, uint, int>)(lpVtbl[8]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pParameters, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
public void GetFilterParameters(XAUDIO2_FILTER_PARAMETERS* pParameters)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, XAUDIO2_FILTER_PARAMETERS*, void>)(lpVtbl[9]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pParameters);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(10)]
[return: NativeTypeName("HRESULT")]
public int SetOutputFilterParameters(IXAudio2Voice* pDestinationVoice, [NativeTypeName("const XAUDIO2_FILTER_PARAMETERS *")] XAUDIO2_FILTER_PARAMETERS* pParameters, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, IXAudio2Voice*, XAUDIO2_FILTER_PARAMETERS*, uint, int>)(lpVtbl[10]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pDestinationVoice, pParameters, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(11)]
public void GetOutputFilterParameters(IXAudio2Voice* pDestinationVoice, XAUDIO2_FILTER_PARAMETERS* pParameters)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, IXAudio2Voice*, XAUDIO2_FILTER_PARAMETERS*, void>)(lpVtbl[11]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pDestinationVoice, pParameters);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(12)]
[return: NativeTypeName("HRESULT")]
public int SetVolume(float Volume, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, float, uint, int>)(lpVtbl[12]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), Volume, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(13)]
public void GetVolume(float* pVolume)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, float*, void>)(lpVtbl[13]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pVolume);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(14)]
[return: NativeTypeName("HRESULT")]
public int SetChannelVolumes([NativeTypeName("UINT32")] uint Channels, [NativeTypeName("const float *")] float* pVolumes, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint, float*, uint, int>)(lpVtbl[14]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), Channels, pVolumes, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(15)]
public void GetChannelVolumes([NativeTypeName("UINT32")] uint Channels, float* pVolumes)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, uint, float*, void>)(lpVtbl[15]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), Channels, pVolumes);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(16)]
[return: NativeTypeName("HRESULT")]
public int SetOutputMatrix(IXAudio2Voice* pDestinationVoice, [NativeTypeName("UINT32")] uint SourceChannels, [NativeTypeName("UINT32")] uint DestinationChannels, [NativeTypeName("const float *")] float* pLevelMatrix, [NativeTypeName("UINT32")] uint OperationSet = 0)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, IXAudio2Voice*, uint, uint, float*, uint, int>)(lpVtbl[16]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pDestinationVoice, SourceChannels, DestinationChannels, pLevelMatrix, OperationSet);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(17)]
public void GetOutputMatrix(IXAudio2Voice* pDestinationVoice, [NativeTypeName("UINT32")] uint SourceChannels, [NativeTypeName("UINT32")] uint DestinationChannels, float* pLevelMatrix)
{
((delegate* unmanaged<IXAudio2MasteringVoice*, IXAudio2Voice*, uint, uint, float*, void>)(lpVtbl[17]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pDestinationVoice, SourceChannels, DestinationChannels, pLevelMatrix);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(18)]
public void DestroyVoice()
{
((delegate* unmanaged<IXAudio2MasteringVoice*, void>)(lpVtbl[18]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(19)]
[return: NativeTypeName("HRESULT")]
public int GetChannelMask([NativeTypeName("DWORD *")] uint* pChannelmask)
{
return ((delegate* unmanaged<IXAudio2MasteringVoice*, uint*, int>)(lpVtbl[19]))((IXAudio2MasteringVoice*)Unsafe.AsPointer(ref this), pChannelmask);
}
}
}
| 56.852071 | 274 | 0.699105 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/xaudio2/IXAudio2MasteringVoice.cs | 9,610 | C# |
namespace RpgMapEditor.Modules.Utilities
{
public class Coordinates
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public const int Step = 16;
public Coordinates Parent { get; set; }
public Coordinates() { X = 0; Y = -1; Z = 0; }
public Coordinates(Node node)
{
X = node.X;
Y = node.Y;
Z = node.Z;
}
public Coordinates(int x, int y) { X = x; Y = y; }
public Coordinates(int x, int y, int z) { X = x; Y = y; Z = z; }
public override string ToString()
{
return X.ToString() + "," + Y.ToString() + "," + Z.ToString();
}
public static Coordinates Parse(Node node)
{
return new Coordinates(node);
}
}
}
| 23 | 74 | 0.478261 | [
"MIT"
] | Szune/RpgMapEditor | Modules/Utilities/Coordinates.cs | 853 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.Diagnostics.CodeAnalysis;
namespace CatsListingDemo.PetOwner.Service
{
/// <summary>
/// Defines the contracts for generic HTTP GET and POST requests.
/// </summary>
[ExcludeFromCodeCoverage]
public class HttpHandler : IHttpHandler
{
private readonly HttpClient _httpClient;
/// <summary>
/// Default constructor. Used to inject any dependencies.
/// <param name="appConfiguration">The application configuration settings.</param>
/// </summary>
public HttpHandler(IConfiguration appConfiguration)
{
_httpClient = new HttpClient(new HttpRetryMessageHandler(new HttpClientHandler(), appConfiguration));
}
/// <inheritdoc />
public async Task<HttpResponseMessage> GetAsync(HttpRequestMessage request)
{
request.Method = HttpMethod.Get;
return await _httpClient.SendAsync(request);
}
/// <inheritdoc />
public Task<HttpResponseMessage> PostAsync(HttpRequestMessage request)
{
throw new NotImplementedException();
}
}
}
| 30.928571 | 113 | 0.668206 | [
"MIT"
] | mendezgabriel/cats-listing-demo-dotnet-core | CatsListingDemo.PetOwner.Service/HttpHandler.cs | 1,301 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.