content stringlengths 23 1.05M |
|---|
/*
* 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 inspector2-2020-06-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Inspector2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Inspector2.Model.Internal.MarshallTransformations
{
/// <summary>
/// AggregationRequest Marshaller
/// </summary>
public class AggregationRequestMarshaller : IRequestMarshaller<AggregationRequest, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(AggregationRequest requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAccountAggregation())
{
context.Writer.WritePropertyName("accountAggregation");
context.Writer.WriteObjectStart();
var marshaller = AccountAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.AccountAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetAmiAggregation())
{
context.Writer.WritePropertyName("amiAggregation");
context.Writer.WriteObjectStart();
var marshaller = AmiAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.AmiAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetAwsEcrContainerAggregation())
{
context.Writer.WritePropertyName("awsEcrContainerAggregation");
context.Writer.WriteObjectStart();
var marshaller = AwsEcrContainerAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.AwsEcrContainerAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetEc2InstanceAggregation())
{
context.Writer.WritePropertyName("ec2InstanceAggregation");
context.Writer.WriteObjectStart();
var marshaller = Ec2InstanceAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.Ec2InstanceAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetFindingTypeAggregation())
{
context.Writer.WritePropertyName("findingTypeAggregation");
context.Writer.WriteObjectStart();
var marshaller = FindingTypeAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.FindingTypeAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetImageLayerAggregation())
{
context.Writer.WritePropertyName("imageLayerAggregation");
context.Writer.WriteObjectStart();
var marshaller = ImageLayerAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.ImageLayerAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetPackageAggregation())
{
context.Writer.WritePropertyName("packageAggregation");
context.Writer.WriteObjectStart();
var marshaller = PackageAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.PackageAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetRepositoryAggregation())
{
context.Writer.WritePropertyName("repositoryAggregation");
context.Writer.WriteObjectStart();
var marshaller = RepositoryAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.RepositoryAggregation, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetTitleAggregation())
{
context.Writer.WritePropertyName("titleAggregation");
context.Writer.WriteObjectStart();
var marshaller = TitleAggregationMarshaller.Instance;
marshaller.Marshall(requestObject.TitleAggregation, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static AggregationRequestMarshaller Instance = new AggregationRequestMarshaller();
}
} |
using System;
using System.IO;
using System.Threading.Tasks;
using EMS.Events;
using EMS.TemplateWebHost.Customization.EventService;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using Stripe;
namespace EMS.PaymentWebhook_Services.API.GraphQlQueries
{
[Route("webhook")]
[ApiController]
public class WebhookController : Controller
{
private readonly IEventService _eventService;
public WebhookController(IEventService eventService)
{
_eventService = eventService;
}
[Route("event")]
[HttpPost]
public async Task<IActionResult> eventCheat(EventCheatRequest request)
{
var e = new SignUpEventSuccessEvent()
{
UserId = request.UserId,
EventId = request.EventId
};
Log.Information("User: " + e.UserId + " signed up to eventId: " + e.EventId);
await _eventService.SaveEventAndDbContextChangesAsync(e);
await _eventService.PublishEventAsync(e);
return Ok();
}
[Route("sub")]
[HttpPost]
public async Task<IActionResult> subCheat(SubCheatRequest request)
{
var e = new SignUpSubscriptionSuccessEvent()
{
UserId = request.UserId,
ClubSubscriptionId = request.ClubSubscriptionId
};
Log.Information("User: " + e.UserId + " signed up to subscription: " + e.ClubSubscriptionId);
await _eventService.SaveEventAndDbContextChangesAsync(e);
await _eventService.PublishEventAsync(e);
return Ok();
}
[HttpPost]
public async Task<IActionResult> Index()
{
var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
Log.Information(json);
try
{
var stripeEvent = EventUtility.ParseEvent(json);
if (stripeEvent.Type == Stripe.Events.PaymentIntentSucceeded)
{
var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
if (paymentIntent.Metadata.Count == 2)
{
var e = new SignUpEventSuccessEvent()
{
UserId = new Guid(paymentIntent.Metadata["UserId"]),
EventId = new Guid(paymentIntent.Metadata["EventId"])
};
Log.Information("User: " + e.UserId + " signed up to eventId: " + e.EventId);
await _eventService.SaveEventAndDbContextChangesAsync(e);
await _eventService.PublishEventAsync(e);
}
}
else if (stripeEvent.Type == Stripe.Events.CustomerSubscriptionCreated)
{
var sub = stripeEvent.Data.Object as Subscription;
if (sub.Metadata.Count == 2)
{
var e = new SignUpSubscriptionSuccessEvent()
{
UserId = new Guid(sub.Metadata["UserId"]),
ClubSubscriptionId = new Guid(sub.Metadata["ClubSubscriptionId"])
};
Log.Information("User: " + e.UserId + " signed up to subscription: " + e.ClubSubscriptionId);
await _eventService.SaveEventAndDbContextChangesAsync(e);
await _eventService.PublishEventAsync(e);
}
}
else
{
Console.WriteLine("Unhandled event type: {0}", stripeEvent.Type);
}
return Ok();
}
catch
{
}
return BadRequest();
}
}
} |
namespace RelaxAndSport.Domain.Booking.Events
{
using RelaxAndSport.Domain.Common;
public class MassageAppointmentRemovedEvent : IDomainEvent
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SaleMTCommon
{
/// <summary>
/// Created by Luannv – 08/10/2013: Thông tin user đăng nhập.
/// </summary>
public static class UserImformation
{
#region member
private static string companyName;
private static string companyAdress;
private static string companyTelePhone;
private static string companyFax;
private static string businessTypeCode;
private static string userName;
private static string deptName;
private static string deptCode;
private static int deptNumber;
private static string storeCode;
private static string storeAdress;
private static string storeTelePhone;
private static string storeFax;
private static string logo;
private static string shiftCode;
private static string ftpServer;
private static string ftpUser;
private static string ftpPw;
private static string ftpExServer;
private static string ftpExUser;
private static string ftpExPw;
private static string ftpExportPath;
private static string ftpImportPath;
private static string clientExportPath;
private static string clientImportPath;
private static bool ftpImportSSL;
private static bool ftpExortSSL;
private static int ftpImportPort;
private static int ftpExportPort;
private static string webserviceAddress;
private static string webserviceUsername;
private static string webservicePassword;
private static bool openSynData;
private static string sysDataAfter;
private static string checkConectTime;
private static bool checkSyn;
private static string sbtnExitSynText;
private static string portName;
private static int baudRate;
private static int dataBits;
private static bool chekPole;
#endregion
#region properties
public static string PortName
{
get { return UserImformation.portName; }
set { UserImformation.portName = value; }
}
public static int BaudRate
{
get { return UserImformation.baudRate; }
set { UserImformation.baudRate = value; }
}
public static int DataBits
{
get { return UserImformation.dataBits; }
set { UserImformation.dataBits = value; }
}
public static bool ChekPole
{
get { return UserImformation.chekPole; }
set { UserImformation.chekPole = value; }
}
public static string SbtnExitSynText
{
get { return UserImformation.sbtnExitSynText; }
set { UserImformation.sbtnExitSynText = value; }
}
public static bool CheckSyn
{
get { return UserImformation.checkSyn; }
set { UserImformation.checkSyn = value; }
}
public static bool OpenSynData
{
get { return UserImformation.openSynData; }
set { UserImformation.openSynData = value; }
}
public static string SysDataAfter
{
get { return UserImformation.sysDataAfter; }
set { UserImformation.sysDataAfter = value; }
}
public static string CheckConectTime
{
get { return UserImformation.checkConectTime; }
set { UserImformation.checkConectTime = value; }
}
public static string WebServiceUsername
{
get { return UserImformation.webserviceUsername; }
set { UserImformation.webserviceUsername = value; }
}
public static string WebServicePassword
{
get { return UserImformation.webservicePassword; }
set { UserImformation.webservicePassword = value; }
}
public static string WebServiceAddress
{
get { return UserImformation.webserviceAddress; }
set { UserImformation.webserviceAddress = value; }
}
public static string CompanyFax
{
get { return UserImformation.companyFax; }
set { UserImformation.companyFax = value; }
}
public static string CompanyTelePhone
{
get { return UserImformation.companyTelePhone; }
set { UserImformation.companyTelePhone = value; }
}
public static string CompanyAdress
{
get { return UserImformation.companyAdress; }
set { UserImformation.companyAdress = value; }
}
public static string BusinessTypeCode
{
get { return businessTypeCode; }
set { businessTypeCode = value; }
}
public static string UserName
{
get { return userName; }
set { userName = value; }
}
public static string DeptName
{
get { return deptName; }
set { deptName = value; }
}
public static string DeptCode
{
get { return deptCode; }
set { deptCode = value; }
}
public static int DeptNumber
{
get { return deptNumber; }
set { deptNumber = value; }
}
public static string StoreCode
{
get { return storeCode; }
set { storeCode = value; }
}
public static string StoreAdress
{
get { return UserImformation.storeAdress; }
set { UserImformation.storeAdress = value; }
}
public static string StoreTelePhone
{
get { return UserImformation.storeTelePhone; }
set { UserImformation.storeTelePhone = value; }
}
public static string StoreFax
{
get { return UserImformation.storeFax; }
set { UserImformation.storeFax = value; }
}
public static string Logo
{
get { return UserImformation.logo; }
set { UserImformation.logo = value; }
}
public static string CompanyName
{
get { return UserImformation.companyName; }
set { UserImformation.companyName = value; }
}
public static string ShiftCode
{
get { return UserImformation.shiftCode; }
set { UserImformation.shiftCode = value; }
}
public static string FtpServer
{
get { return ftpServer; }
set { ftpServer = value; }
}
public static string FtpUser
{
get { return ftpUser; }
set { ftpUser = value; }
}
public static string FtpPassword
{
get { return ftpPw; }
set
{
ftpPw = value;
}
}
public static string FtpExServer
{
get { return ftpExServer; }
set { ftpExServer = value; }
}
public static string FtpExUser
{
get { return ftpExUser; }
set { ftpExUser = value; }
}
public static string FtpExPassword
{
get { return ftpExPw; }
set
{
ftpExPw = value;
}
}
public static string FtpExportPath
{
get { return ftpExportPath; }
set { ftpExportPath = value; }
}
public static string FtpImportPath
{
get { return ftpImportPath; }
set { ftpImportPath = value; }
}
public static string ClientExportPath
{
get { return clientExportPath; }
set { clientExportPath = value; }
}
public static string ClientImportPath
{
get { return clientImportPath; }
set { clientImportPath = value; }
}
public static bool FtpImportSSL
{
get { return ftpImportSSL; }
set { ftpImportSSL = value; }
}
public static bool FtpExportSSL
{
get { return ftpExortSSL; }
set { ftpExortSSL = value; }
}
public static int FtpExportPort
{
get { return ftpExportPort; }
set { ftpExportPort = value; }
}
public static int FtpImportPort
{
get { return ftpImportPort; }
set { ftpImportPort = value; }
}
#endregion
}
}
|
namespace MobileDevice
{
using System;
using System.Linq;
public class GSMCallHistoryTest
{
public static void DisplayInformation()
{
double fixedPrice = 0.37;
var smartphone = new Gsm("Fancy Phone", "Bulgaria");
string separator = new string('=', 100);
smartphone.AddCall(new Call(new DateTime(2015, 1, 18, 12, 01, 00), "+ 359 123 456 789", 60));
smartphone.AddCall(new Call(new DateTime(2016, 2, 19, 13, 02, 00), "+ 359 876 543 210", 90));
smartphone.AddCall(new Call(new DateTime(2017, 3, 20, 14, 03, 00), "+ 359 000 000 000", 10));
Console.WriteLine("Call History Information:");
foreach (var callHistoryItem in smartphone.CallHistoryInformation())
{
Console.WriteLine(callHistoryItem);
}
smartphone.CallHistoryInformation();
Console.WriteLine(separator);
Console.WriteLine("Total Price of Calls: {0} BGN", smartphone.TotalCallPrice(fixedPrice));
Console.WriteLine(separator);
Call longestCall = smartphone.CallHistory.OrderByDescending(x => x.Duration).First();
smartphone.DeleteCall(longestCall);
Console.WriteLine("Total Price after last call removed: {0} BGN", smartphone.TotalCallPrice(fixedPrice));
Console.WriteLine(separator);
Console.WriteLine("History cleared:");
smartphone.ClearHistory();
smartphone.CallHistoryInformation();
Console.WriteLine(separator);
}
}
} |
using System.Text.Json;
using Events.Ports.Commands;
using Paramore.Brighter;
namespace Events.Ports.Mappers
{
public class CompetingConsumerCommandMessageMapper : IAmAMessageMapper<CompetingConsumerCommand>
{
public Message MapToMessage(CompetingConsumerCommand request)
{
var header = new MessageHeader(messageId: request.Id, topic: "multipleconsumer.command", messageType: MessageType.MT_COMMAND);
var body = new MessageBody(JsonSerializer.Serialize(request, JsonSerialisationOptions.Options));
var message = new Message(header, body);
return message;
}
public CompetingConsumerCommand MapToRequest(Message message)
{
var greetingCommand = JsonSerializer.Deserialize<CompetingConsumerCommand>(message.Body.Value, JsonSerialisationOptions.Options);
return greetingCommand;
}
}
}
|
#region License
/* Copyright 2010, 2013 James F. Bellinger <http://www.zer7.com/software/hidsharp>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace HidSharp
{
/// <summary>
/// Detects USB HID class devices connected to the system.
/// </summary>
[ComVisible(true), Guid("CD7CBD7D-7204-473c-AA2A-2B9622CFC6CC")]
public class HidDeviceLoader
{
/// <summary>
/// Initializes a new instance of the <see cref="HidDeviceLoader"/> class.
/// </summary>
public HidDeviceLoader()
{
}
/// <summary>
/// Gets a list of connected USB devices.
/// This overload is meant for Visual Basic 6 and COM clients.
/// </summary>
/// <returns>The device list.</returns>
public IEnumerable GetDevicesVB()
{
return GetDevices();
}
/// <summary>
/// Gets a list of connected USB devices.
/// </summary>
/// <returns>The device list.</returns>
public IEnumerable<HidDevice> GetDevices()
{
return Platform.HidSelector.Instance.GetDevices();
}
/// <summary>
/// Gets a list of connected USB devices, filtered by some criteria.
/// </summary>
/// <param name="vendorID">The vendor ID, or null to not filter by vendor ID.</param>
/// <param name="productID">The product ID, or null to not filter by product ID.</param>
/// <param name="productVersion">The product version, or null to not filter by product version.</param>
/// <param name="serialNumber">The serial number, or null to not filter by serial number.</param>
/// <returns>The filtered device list.</returns>
public IEnumerable<HidDevice> GetDevices
(int? vendorID = null, int? productID = null, int? productVersion = null, string serialNumber = null)
{
int vid = vendorID ?? -1, pid = productID ?? -1, ver = productVersion ?? -1;
foreach (HidDevice hid in GetDevices())
{
if ((hid.VendorID == vendorID || vid < 0) &&
(hid.ProductID == productID || pid < 0) &&
(hid.ProductVersion == productVersion || ver < 0) &&
(hid.SerialNumber == serialNumber || string.IsNullOrEmpty(serialNumber)))
{
yield return hid;
}
}
}
/// <summary>
/// Gets the first connected USB device that matches specified criteria.
/// </summary>
/// <param name="vendorID">The vendor ID, or null to not filter by vendor ID.</param>
/// <param name="productID">The product ID, or null to not filter by product ID.</param>
/// <param name="productVersion">The product version, or null to not filter by product version.</param>
/// <param name="serialNumber">The serial number, or null to not filter by serial number.</param>
/// <returns>The device, or null if none was found.</returns>
public HidDevice GetDeviceOrDefault
(int? vendorID = null, int? productID = null, int? productVersion = null, string serialNumber = null)
{
return GetDevices(vendorID, productID, productVersion, serialNumber).FirstOrDefault();
}
}
}
|
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SlackLogger.Core {
internal class IncludePattern {
public string PropertyName { get; set; }
public string Pattern { get; set; }
public Regex Expression { get; set; }
public IncludePattern(XElement include) {
PropertyName = include.Attribute("property")?.Value ?? string.Empty;
Pattern = include.Value ?? string.Empty;
Expression = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.Http;
using Data.Models;
using System.Text.Json;
using System.Configuration;
namespace TestAPI
{
[TestClass]
public class SchoolsControllerTests
{
private static HttpClient client;
private static TestContext tc;
[ClassInitialize]
public static void ClassInit(TestContext tc)
{
SchoolsControllerTests.tc = tc;
//string path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var ApiUri = configFile.AppSettings.Settings["ApiUri"].Value.ToString();
client = new HttpClient();
client.BaseAddress = new Uri(ApiUri);
}
[TestInitialize]
public async Task InitializeData()
{
await PostData(new School("test school 1", "test1"));
await PostData(new School("test school 2", "test2"));
}
[TestCleanup]
public async Task CleanUpData()
{
await client.DeleteAsync("api/Schools/test1");
await client.DeleteAsync("api/Schools/test2");
await client.DeleteAsync("api/Schools/test3");
}
private async Task<HttpResponseMessage> PostData(School school)
{
string jsonString = JsonSerializer.Serialize(school);
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/Schools", httpContent);
return response;
}
private bool ContainsAnEqualSchool(List<School> list, School value)
{
foreach (School i in list)
{
if (SchoolsAreEqual(i, value))
{
return true;
}
}
return false;
}
private bool SchoolsAreEqual(School school1, School school2)
{
if ((school1.ID == school2.ID) && (school1.Name == school2.Name))
{
return true;
}
return false;
}
[TestMethod]
public async Task TestGetSchools()
{
var response = await client.GetAsync("api/Schools");
List<School> schools = await response.Content.ReadAsAsync<List<School>>();
Assert.IsTrue(response.IsSuccessStatusCode);
Assert.IsTrue(ContainsAnEqualSchool(schools, new School("test school 1", "test1")));
Assert.IsTrue(ContainsAnEqualSchool(schools, new School("test school 2", "test2")));
}
[TestMethod]
public async Task TestGetSchool()
{
//get school that exists
var response = await client.GetAsync("api/Schools/test1");
School school1 = await response.Content.ReadAsAsync<School>();
Assert.IsTrue(response.IsSuccessStatusCode);
Assert.IsTrue(SchoolsAreEqual(new School("test school 1", "test1"), school1));
var response2 = await client.GetAsync("api/Schools/test1");
School school2 = await response2.Content.ReadAsAsync<School>();
Assert.IsTrue(response2.IsSuccessStatusCode);
Assert.IsTrue(SchoolsAreEqual(new School("test school 1", "test1"), school2));
//get school that doesn't exist
var response3 = await client.GetAsync("api/Schools/thisSchoolDoesNotExist");
Assert.IsFalse(response3.IsSuccessStatusCode);
Assert.AreEqual("NotFound", response3.StatusCode.ToString());
}
[TestMethod]
public async Task TestPutSchool()
{
//case where the school exists
string jsonString = JsonSerializer.Serialize(new School("test school 0", "test1"));
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await client.PutAsync("api/Schools/test1", httpContent);
Assert.AreEqual("NoContent", response.StatusCode.ToString());
var response2 = await client.GetAsync("api/Schools");
List<School> schools = await response2.Content.ReadAsAsync<List<School>>();
Assert.IsTrue(response2.IsSuccessStatusCode);
Assert.IsTrue(ContainsAnEqualSchool(schools, new School("test school 0", "test1")));
//case where the URL doesn't match the school's ID
string jsonString2 = JsonSerializer.Serialize(new School("test school 0", "test1"));
var httpContent2 = new StringContent(jsonString2, Encoding.UTF8, "application/json");
var response3 = await client.PutAsync("api/Schools/1", httpContent2);
Assert.AreEqual("BadRequest", response3.StatusCode.ToString());
//case where the school does not exist
string jsonString3 = JsonSerializer.Serialize(new School("test school 0", "thisSchoolDoesNotExist"));
var httpContent3 = new StringContent(jsonString3, Encoding.UTF8, "application/json");
var response4 = await client.PutAsync("api/Schools/thisSchoolDoesNotExist", httpContent3);
Assert.AreEqual("NotFound", response4.StatusCode.ToString());
}
[TestMethod]
public async Task TestPostSchool()
{
//post a school that doesn't already exist
string jsonString = JsonSerializer.Serialize(new School("test school 3", "test3"));
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/Schools", httpContent);
Assert.IsTrue(response.IsSuccessStatusCode);
var response2 = await client.GetAsync("api/Schools");
List<School> schools = await response2.Content.ReadAsAsync<List<School>>();
Assert.IsTrue(response2.IsSuccessStatusCode);
Assert.IsTrue(ContainsAnEqualSchool(schools, new School("test school 3", "test3")));
//post a school that already exists
string jsonString2 = JsonSerializer.Serialize(new School("test school 3", "test3"));
var httpContent2 = new StringContent(jsonString2, Encoding.UTF8, "application/json");
var response3 = await client.PostAsync("api/Schools", httpContent2);
Assert.AreEqual("Conflict", response3.StatusCode.ToString());
}
[TestMethod]
public async Task TestDeleteSchool()
{
//delete an existing school
var response = await client.DeleteAsync("api/Schools/test1");
Assert.AreEqual("NoContent", response.StatusCode.ToString());
var getResponse = await client.GetAsync("api/Schools/test1");
Assert.AreEqual("NotFound", getResponse.StatusCode.ToString());
//delete a school that does not exist
var response2 = await client.DeleteAsync("api/Schools/test1");
Assert.AreEqual("NotFound", response2.StatusCode.ToString());
}
}
}
|
using System.ComponentModel;
using Conventional.Conventions;
namespace ZeroMVVM.Conventions
{
public class ViewModelConvention : Convention
{
public ViewModelConvention()
{
Must.HaveNameEndWith("ViewModel");
Should.Implement<INotifyPropertyChanged>();
BaseName = t => t.Name.Substring(0, t.Name.Length - 9);
Variants.HaveBaseNameAndEndWith("ViewModel");
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RecompildPOS.Resources.Constants;
using RecompildPOS.ViewModels.Products.GenerateCode;
using RecompildPOS.Views.Base;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ZXing;
namespace RecompildPOS.Views.Products.GenerateCode
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GenerateBarcodePage : BasePage
{
public GenerateCodeViewModel ViewModel => BindingContext as GenerateCodeViewModel;
public GenerateBarcodePage(string code, string format)
{
InitializeComponent();
if (format.Equals(AppConstants.BarCode))
{
BarcodeImageView.BarcodeFormat = BarcodeFormat.CODE_128;
}
if(format.Equals(AppConstants.QrCode))
{
BarcodeImageView.BarcodeFormat = BarcodeFormat.QR_CODE;
}
ViewModel.CodeValue = code;
BarcodeImageView.BarcodeValue = code;
}
private void SaveCode(object sender, EventArgs e)
{
}
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
} |
///===================================================================================================
///
/// Source https://github.com/PeterWaher/IoTGateway/tree/master/Security/Waher.Security.EllipticCurves
/// Owner https://github.com/PeterWaher
///
///===================================================================================================
using System;
using System.Numerics;
namespace Blockcoli.Libra.Net.Crypto
{
/// <summary>
/// Base class of Edwards curves (x²+y²=1+dx²y²) over a prime field.
/// </summary>
public abstract class EdwardsCurve : EdwardsCurveBase
{
private readonly BigInteger p34;
/// <summary>
/// Base class of Edwards curves (x²+y²=1+dx²y²) over a prime field.
/// </summary>
/// <param name="Prime">Prime base of field.</param>
/// <param name="BasePoint">Base-point in (X,Y) coordinates.</param>
/// <param name="d">Coefficient in the curve equation (x²+y²=1+dx²y²)</param>
/// <param name="Order">Order of base-point.</param>
/// <param name="Cofactor">Cofactor of curve.</param>
public EdwardsCurve(BigInteger Prime, PointOnCurve BasePoint, BigInteger d,
BigInteger Order, int Cofactor)
: this(Prime, BasePoint, d, Order, Cofactor, null)
{
}
/// <summary>
/// Base class of Edwards curves (x²+y²=1+dx²y²) over a prime field.
/// </summary>
/// <param name="Prime">Prime base of field.</param>
/// <param name="BasePoint">Base-point in (X,Y) coordinates.</param>
/// <param name="d">Coefficient in the curve equation (x²+y²=1+dx²y²)</param>
/// <param name="Order">Order of base-point.</param>
/// <param name="Cofactor">Cofactor of curve.</param>
/// <param name="Secret">Secret.</param>
public EdwardsCurve(BigInteger Prime, PointOnCurve BasePoint, BigInteger d,
BigInteger Order, int Cofactor, byte[] Secret)
: base(Prime, BasePoint, d, Order, Cofactor, Secret)
{
this.p34 = (this.p - 3) / 4;
}
/// <summary>
/// d coefficient of Edwards curve.
/// </summary>
protected abstract BigInteger D
{
get;
}
/// <summary>
/// Neutral point.
/// </summary>
public override PointOnCurve Zero
{
get
{
return new PointOnCurve(BigInteger.Zero, BigInteger.One);
}
}
/// <summary>
/// Adds <paramref name="Q"/> to <paramref name="P"/>.
/// </summary>
/// <param name="P">Point 1.</param>
/// <param name="Q">Point 2.</param>
/// <returns>P+Q</returns>
public override void AddTo(ref PointOnCurve P, PointOnCurve Q)
{
if (!P.IsHomogeneous)
P.Z = BigInteger.One;
if (!Q.IsHomogeneous)
Q.Z = BigInteger.One;
BigInteger A = this.modP.Multiply(P.Z, Q.Z);
BigInteger B = this.modP.Multiply(A, A);
BigInteger C = this.modP.Multiply(P.X, Q.X);
BigInteger D = this.modP.Multiply(P.Y, Q.Y);
BigInteger E = this.modP.Multiply(this.modP.Multiply(this.D, C), D);
BigInteger F = this.modP.Subtract(B, E);
BigInteger G = this.modP.Add(B, E);
BigInteger H = this.modP.Multiply(P.X + P.Y, Q.X + Q.Y);
P.X = this.modP.Multiply(A, this.modP.Multiply(F, H - C - D));
P.Y = this.modP.Multiply(A, this.modP.Multiply(G, D - C));
P.Z = this.modP.Multiply(F, G);
}
/// <summary>
/// Doubles a point on the curve.
/// </summary>
/// <param name="P">Point</param>
public override void Double(ref PointOnCurve P)
{
if (!P.IsHomogeneous)
P.Z = BigInteger.One;
BigInteger A = this.modP.Add(P.X, P.Y);
BigInteger B = this.modP.Multiply(A, A);
BigInteger C = this.modP.Multiply(P.X, P.X);
BigInteger D = this.modP.Multiply(P.Y, P.Y);
BigInteger E = this.modP.Add(C, D);
BigInteger H = this.modP.Multiply(P.Z, P.Z);
BigInteger J = this.modP.Subtract(E, H << 1);
P.X = this.modP.Multiply(B - E, J);
P.Y = this.modP.Multiply(E, C - D);
P.Z = this.modP.Multiply(E, J);
}
/// <summary>
/// Gets the X-coordinate that corresponds to a given Y-coordainte, and the
/// first bit of the X-coordinate.
/// </summary>
/// <param name="Y">Y-coordinate.</param>
/// <param name="X0">First bit of X-coordinate.</param>
/// <returns>X-coordinate</returns>
public override BigInteger GetX(BigInteger Y, bool X0)
{
BigInteger y2 = this.modP.Multiply(Y, Y);
BigInteger u = y2 - BigInteger.One;
if (u.Sign < 0)
u += this.p;
BigInteger v = this.modP.Multiply(this.D, y2) - BigInteger.One;
BigInteger v2 = this.modP.Multiply(v, v);
BigInteger v3 = this.modP.Multiply(v, v2);
BigInteger u2 = this.modP.Multiply(u, u);
BigInteger u3 = this.modP.Multiply(u, u2);
BigInteger u5 = this.modP.Multiply(u2, u3);
BigInteger x = this.modP.Multiply(this.modP.Multiply(u3, v),
BigInteger.ModPow(this.modP.Multiply(u5, v3), this.p34, this.p));
BigInteger x2 = this.modP.Multiply(x, x);
BigInteger Test = this.modP.Multiply(v, x2);
if (Test.Sign < 0)
Test += this.p;
if (Test != u)
throw new ArgumentException("Not a valid point.", nameof(Y));
if (X0)
{
if (x.IsZero)
throw new ArgumentException("Not a valid point.", nameof(Y));
if (x.IsEven)
x = this.p - x;
}
else if (!x.IsEven)
x = this.p - x;
return x;
}
}
} |
namespace ExcelX.AddIn.Command
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
/// <summary>
/// 「ファイルを選択して別ウィンドウの読み取り専用で開く」コマンド
/// </summary>
public class OpenSelectWorkbookReadOnlyCommand : OpenFileCommand, ICommand
{
/// <summary>
/// コマンドを実行します。
/// </summary>
public async void Execute()
{
// OpenFileDialogインスタンスを作成
var ofd = this.CreateOpenFileDialog();
// OK 以外は無視
if (ofd.ShowDialog() != DialogResult.OK)
{
return;
}
// 指定されたファイルを読み取り専用で開く
await this.OpenNewWindowAsync(ofd.FileName, true);
}
}
}
|
namespace ZazasCleaningService.Services.Data.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using ZazasCleaningService.Data;
using ZazasCleaningService.Data.Models;
using ZazasCleaningService.Services.Data.Tests.Common;
using ZazasCleaningService.Services.Mapping;
using ZazasCleaningService.Services.Models.Votes;
public class VotesServiceTests
{
private IVotesService votesService;
public VotesServiceTests()
{
MapperInitializer.InitializeMapper();
}
[Fact]
public async Task GetVotes_WithDummyData_ShouldReturnCorrectResult()
{
var errorMessagePrefix = "VotesService GetVotesAsync() method does not work properly.";
var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();
await this.SeedData(dbContext);
this.votesService = new VotesService(dbContext);
var expectedResult = dbContext.Votes.First().ServiceId;
var actualResult = await this.votesService.GetVotesAsync<VotesServiceModel>(expectedResult);
Assert.True(expectedResult == actualResult.Id, errorMessagePrefix + " " + "Id is not return properly.");
}
[Fact]
public async Task Create_WithDummyData_ShouldReturnCorrectResult()
{
var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();
await this.SeedData(dbContext);
this.votesService = new VotesService(dbContext);
var testVotesService = new VotesServiceModel
{
Type = VoteType.UpVote,
ServiceId = 1,
UserId = Guid.NewGuid().ToString(),
};
var expectedResult = 3;
var actualResult = await this.votesService.CreateVoteAsync(testVotesService);
Assert.Equal(expectedResult, actualResult);
}
[Fact]
public async Task Create_WithNoVotes_ShouldThrowArgumentNullException()
{
var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();
this.votesService = new VotesService(dbContext);
var testVotesService = new VotesServiceModel
{
Type = VoteType.UpVote,
ServiceId = 1,
UserId = Guid.NewGuid().ToString(),
};
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await this.votesService.CreateVoteAsync(testVotesService));
}
private async Task SeedData(ApplicationDbContext dbContext)
{
await dbContext.AddRangeAsync(this.GetDummyData());
await dbContext.SaveChangesAsync();
}
private List<Vote> GetDummyData()
{
return new List<Vote>()
{
new Vote
{
Type = VoteType.UpVote,
ServiceId = 1,
UserId = Guid.NewGuid().ToString(),
},
new Vote
{
Type = VoteType.DownVote,
ServiceId = 2,
UserId = Guid.NewGuid().ToString(),
},
};
}
}
}
|
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Runtime;
using Autodesk.RefineryToolkits.SpacePlanning.Graphs;
using Dynamo.Graph.Nodes;
using System;
using System.Collections.Generic;
using System.Linq;
using DSGeom = Autodesk.DesignScript.Geometry;
using GTGeom = Autodesk.RefineryToolkits.Core.Geometry;
namespace Autodesk.RefineryToolkits.SpacePlanning.Analyze
{
public static class PathFinding
{
private const string graphOutputPort = "path";
private const string lengthOutputPort = "length";
/// <summary>
/// Returns a graph representing the shortest path
/// between two points on a given Visibility Graph.
/// </summary>
/// <param name="visGraph">Visibility Graph</param>
/// <param name="origin">Origin point</param>
/// <param name="destination">Destination point</param>
/// <returns name="path">Graph representing the shortest path</returns>
/// <returns name="length">Length of path</returns>
[MultiReturn(new[] { graphOutputPort, lengthOutputPort })]
public static Dictionary<string, object> ShortestPath(
Visibility visGraph,
Point origin,
Point destination)
{
if (visGraph == null) throw new ArgumentNullException("visibility");
if (origin == null) throw new ArgumentNullException("origin");
if (destination == null) throw new ArgumentNullException("destination");
var gOrigin = GTGeom.Vertex.ByCoordinates(origin.X, origin.Y, origin.Z);
var gDestination = GTGeom.Vertex.ByCoordinates(destination.X, destination.Y, destination.Z);
var visibilityGraph = visGraph.graph as VisibilityGraph;
var baseGraph = new BaseGraph()
{
graph = VisibilityGraph.ShortestPath(visibilityGraph, gOrigin, gDestination)
};
return new Dictionary<string, object>()
{
{graphOutputPort, baseGraph },
{lengthOutputPort, baseGraph.graph.edges.Select(e => e.Length).Sum() }
};
}
/// <summary>
/// Returns a VisibilityGraph which is used as input for ShortestPath
/// </summary>
/// <param name="boundary"></param>
/// <param name="internals"></param>
/// <returns name = "visGraph">VisibilityGraph for use in ShortestPath</returns>
public static Visibility CreateVisibilityGraph(
List<DSGeom.Polygon> boundary,
List<DSGeom.Polygon> internals)
{
var graph = BaseGraph.ByBoundaryAndInternalPolygons(boundary, internals);
var visGraph = Visibility.ByBaseGraph(graph);
return visGraph;
}
/// <summary>
/// Returns the input graph as a list of lines
/// </summary>
/// <returns name="lines">List of lines representing the graph.</returns>
[NodeCategory("Query")]
public static List<Line> Lines(BaseGraph path)
{
List<Line> lines = new List<Line>();
foreach (GTGeom.Edge edge in path.graph.edges)
{
var start = GTGeom.Points.ToPoint(edge.StartVertex);
var end = GTGeom.Points.ToPoint(edge.EndVertex);
lines.Add(Line.ByStartPointEndPoint(start, end));
}
return lines;
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
[System.Serializable]
public struct SerializableVector3
{
public float x;
public float y;
public float z;
public SerializableVector3(float rX, float rY, float rZ)
{
x = rX;
y = rY;
z = rZ;
}
public override string ToString()
{
return String.Format("[{0}, {1}, {2}]", x, y, z);
}
public static implicit operator Vector3(SerializableVector3 rValue)
{
return new Vector3(rValue.x, rValue.y, rValue.z);
}
public static implicit operator SerializableVector3(Vector3 rValue)
{
return new SerializableVector3(rValue.x, rValue.y, rValue.z);
}
}
|
using System.Reflection;
using EdjCase.JsonRpc.Router.Abstractions;
namespace EdjCase.JsonRpc.Router.Swagger.Models
{
public class UniqueMethod
{
public string UniqueUrl { get; }
public IRpcMethodInfo Info { get; }
public UniqueMethod(string uniqueUrl, IRpcMethodInfo info)
{
this.UniqueUrl = uniqueUrl;
this.Info = info;
}
}
} |
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using SchedulerBot.Business.Entities;
using SchedulerBot.Business.Interfaces.Commands;
using SchedulerBot.Database.Interfaces;
namespace SchedulerBot.Business.Commands
{
/// <summary>
/// Basic implementation of <see cref="IBotCommand"/> interface.
/// </summary>
/// <seealso cref="IBotCommand" />
public abstract class BotCommand : IBotCommand
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="BotCommand"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="unitOfWork">The unit of work.</param>
/// <param name="logger">The logger.</param>
protected BotCommand(string name, IUnitOfWork unitOfWork, ILogger logger)
{
Name = name;
UnitOfWork = unitOfWork;
Logger = logger;
}
#endregion
#region Public Properties
/// <inheritdoc />
public string Name { get; }
#endregion
#region Protected Properties
/// <summary>
/// Gets the Unit of Work to work with a Database.
/// </summary>
protected IUnitOfWork UnitOfWork { get; }
/// <summary>
/// Gets the logger.
/// </summary>
protected ILogger Logger { get; }
#endregion
#region Public Methods
/// <inheritdoc />
public async Task<ExecutionResult<string>> ExecuteAsync(Activity activity, string arguments)
{
Logger.LogInformation("Executing '{0}' command with arguments '{1}'", Name, arguments);
ExecutionResult<string> executionResult = await ExecuteCoreAsync(activity, arguments);
Logger.LogInformation("Finished executing '{0}' command", Name);
return executionResult;
}
#endregion
#region Abstract Methods
/// <summary>
/// When overridden in a derived class, executes the core command logic.
/// </summary>
/// <param name="activity">The activity.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The result of the command execution.</returns>
protected abstract Task<ExecutionResult<string>> ExecuteCoreAsync(Activity activity, string arguments);
#endregion
}
}
|
using System;
using System.Threading.Tasks;
using Orleans.Providers;
using Orleans.SqlUtils.StorageProvider.GrainInterfaces;
namespace Orleans.SqlUtils.StorageProvider.GrainClasses
{
[StorageProvider(ProviderName = "MemoryStore")]
public class DeviceGrain : Grain<DeviceState>, IDeviceGrain
{
public Task<string> GetSerialNumber()
{
return Task.FromResult(State.SerialNumber);
}
public async Task SetOwner(ICustomerGrain customer)
{
if (customer == null)
throw new ArgumentNullException("customer");
State.Owner = customer;
await WriteStateAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestableCodeDemos.Module4.Shared
{
public class Session : ISession
{
private readonly Login _login;
public Session(Login login)
{
_login = login;
}
public Login GetLogin()
{
return _login;
}
}
}
|
namespace MicroLite.Tests.TypeConverters
{
using System;
using System.Data;
using MicroLite.TypeConverters;
using Moq;
using Xunit;
public class ObjectTypeConverterTests
{
private enum Status
{
Default = 0,
New = 1
}
public class WhenCallingCanConvert_WithATypeWhichIsAnEnum
{
[Fact]
public void TrueShouldBeReturned()
{
// Although an exlicit type converter exists for enums, ObjectTypeConverter should not discriminate against any type.
// This is so we don't have to modify it to ignore types for which there is a specific converter.
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(Status)));
}
}
public class WhenCallingCanConvert_WithATypeWhichIsAnInt
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(int)));
}
}
public class WhenCallingCanConvert_WithATypeWhichIsANullableInt
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(int?)));
}
}
public class WhenCallingConvertFromDbValue_AndTypeIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var typeConverter = new ObjectTypeConverter();
var exception = Assert.Throws<ArgumentNullException>(
() => typeConverter.ConvertFromDbValue(1, null));
Assert.Equal("type", exception.ParamName);
}
}
public class WhenCallingConvertFromDbValue_ForANullableIntWithANonNullValue
{
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValue_ForANullableIntWithANonNullValue()
{
this.result = typeConverter.ConvertFromDbValue(1, typeof(int?));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
}
public class WhenCallingConvertFromDbValue_ForANullableIntWithANullValue
{
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValue_ForANullableIntWithANullValue()
{
this.result = typeConverter.ConvertFromDbValue(DBNull.Value, typeof(int?));
}
[Fact]
public void NullShouldBeReturned()
{
Assert.Null(this.result);
}
}
public class WhenCallingConvertFromDbValue_WithAByteAndATypeOfInt
{
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValue_WithAByteAndATypeOfInt()
{
this.result = typeConverter.ConvertFromDbValue((byte)1, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeUpCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertFromDbValue_WithALongAndATypeOfInt
{
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValue_WithALongAndATypeOfInt()
{
this.result = typeConverter.ConvertFromDbValue((long)1, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeDownCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertFromDbValueWithReader_AndReaderIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var typeConverter = new ObjectTypeConverter();
var exception = Assert.Throws<ArgumentNullException>(
() => typeConverter.ConvertFromDbValue(null, 0, typeof(int)));
Assert.Equal("reader", exception.ParamName);
}
}
public class WhenCallingConvertFromDbValueWithReader_AndTypeIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var typeConverter = new ObjectTypeConverter();
var exception = Assert.Throws<ArgumentNullException>(
() => typeConverter.ConvertFromDbValue(new Mock<IDataReader>().Object, 0, null));
Assert.Equal("type", exception.ParamName);
}
}
public class WhenCallingConvertFromDbValueWithReader_ForANullableIntWithANonNullValue
{
private readonly Mock<IDataReader> mockReader = new Mock<IDataReader>();
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithReader_ForANullableIntWithANonNullValue()
{
this.mockReader.Setup(x => x[0]).Returns(1);
this.result = typeConverter.ConvertFromDbValue(this.mockReader.Object, 0, typeof(int?));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
}
public class WhenCallingConvertFromDbValueWithReader_ForANullableIntWithANullValue
{
private readonly Mock<IDataReader> mockReader = new Mock<IDataReader>();
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithReader_ForANullableIntWithANullValue()
{
this.mockReader.Setup(x => x.IsDBNull(0)).Returns(true);
this.result = typeConverter.ConvertFromDbValue(this.mockReader.Object, 0, typeof(int?));
}
[Fact]
public void NullShouldBeReturned()
{
Assert.Null(this.result);
}
}
public class WhenCallingConvertFromDbValueWithReader_WithAByteAndATypeOfInt
{
private readonly Mock<IDataReader> mockReader = new Mock<IDataReader>();
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithReader_WithAByteAndATypeOfInt()
{
this.mockReader.Setup(x => x[0]).Returns((byte)1);
this.result = typeConverter.ConvertFromDbValue(this.mockReader.Object, 0, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeUpCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertFromDbValueWithReader_WithALongAndATypeOfInt
{
private readonly Mock<IDataReader> mockReader = new Mock<IDataReader>();
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithReader_WithALongAndATypeOfInt()
{
this.mockReader.Setup(x => x[0]).Returns((long)1);
this.result = typeConverter.ConvertFromDbValue(this.mockReader.Object, 0, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeDownCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertToDbValue
{
private readonly object result;
private readonly ITypeConverter typeConverter = new ObjectTypeConverter();
private readonly string value = "Foo";
public WhenCallingConvertToDbValue()
{
this.result = this.typeConverter.ConvertToDbValue(value, typeof(string));
}
[Fact]
public void TheSameValueShouldBeReturned()
{
Assert.Same(this.value, this.result);
}
}
}
} |
using UnityEngine;
using System.Collections;
public class MusicControl : MonoBehaviour {
public AudioSource[] allSoundEffects;
public AudioSource music;
private int musicC;
private int FxSound;
// Use this for initialization
void Start () {
musicC = PlayerPrefs.GetInt("SoundGame");
FxSound = PlayerPrefs.GetInt("FxSound");
// Turn on / off music in the Game.
if (musicC == 1)
{
music.mute = false;
}
if (musicC == 2)
{
music.mute = true;
}
// Tuen on / off the Sound effect int the Game.
if (FxSound == 1)
{
for (int i = 0; i < allSoundEffects.Length; i++)
{
allSoundEffects[i].mute = false;
}
}
if (FxSound == 2)
{
for (int i = 0; i < allSoundEffects.Length; i++)
{
allSoundEffects[i].mute = true;
}
}
}
}
|
namespace Castaway.Components
{
public interface IContainer
{
}
} |
using System;
namespace UiBinding.Conversion
{
public class DefaultConverter : IValueConverter
{
private readonly Type _source;
private readonly Type _target;
public DefaultConverter(Type source, Type target)
{
_source = source;
_target = target;
}
public object Convert(object value)
{
return Convert(value, _target);
}
public object ConvertBack(object value)
{
return Convert(value, _source);
}
private object Convert(object value, Type to)
{
return System.Convert.ChangeType(value, to);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DemoRestSimonas.Data.Dtos.Posts;
using DemoRestSimonas.Data.Entities;
using DemoRestSimonas.Data.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace DemoRestSimonas.Controllers
{
[ApiController]
[Route("api/topics/{topicId}/posts")]
public class PostsController : ControllerBase
{
private readonly IPostsRepository _postsRepository;
private readonly IMapper _mapper;
private readonly ITopicsRepository _topicsRepository;
public PostsController(IPostsRepository postsRepository, IMapper mapper, ITopicsRepository topicsRepository)
{
_postsRepository = postsRepository;
_mapper = mapper;
_topicsRepository = topicsRepository;
}
[HttpGet]
public async Task<IEnumerable<PostDto>> GetAllAsync(int topicId)
{
var topics = await _postsRepository.GetAsync(topicId);
return topics.Select(o => _mapper.Map<PostDto>(o));
}
// /api/topics/1/posts/2
[HttpGet("{postId}")]
public async Task<ActionResult<PostDto>> GetAsync(int topicId, int postId)
{
var topic = await _postsRepository.GetAsync(topicId, postId);
if (topic == null) return NotFound();
return Ok(_mapper.Map<PostDto>(topic));
}
[HttpPost]
public async Task<ActionResult<PostDto>> PostAsync(int topicId, CreatePostDto postDto)
{
var topic = await _topicsRepository.Get(topicId);
if (topic == null) return NotFound($"Couldn't find a topic with id of {topicId}");
var post = _mapper.Map<Post>(postDto);
post.TopicId = topicId;
await _postsRepository.InsertAsync(post);
return Created($"/api/topics/{topicId}/posts/{post.Id}", _mapper.Map<PostDto>(post));
}
[HttpPut("{postId}")]
public async Task<ActionResult<PostDto>> PostAsync(int topicId, int postId, UpdatePostDto postDto)
{
var topic = await _topicsRepository.Get(topicId);
if (topic == null) return NotFound($"Couldn't find a topic with id of {topicId}");
var oldPost = await _postsRepository.GetAsync(topicId, postId);
if (oldPost == null)
return NotFound();
//oldPost.Body = postDto.Body;
_mapper.Map(postDto, oldPost);
await _postsRepository.UpdateAsync(oldPost);
return Ok(_mapper.Map<PostDto>(oldPost));
}
[HttpDelete("{postId}")]
public async Task<ActionResult> DeleteAsync(int topicId, int postId)
{
var post = await _postsRepository.GetAsync(topicId, postId);
if (post == null)
return NotFound();
await _postsRepository.DeleteAsync(post);
// 204
return NoContent();
}
}
}
|
using Java.Lang;
namespace Toggl.Droid.Extensions
{
public static class JavaUtils
{
public static Class ToClass<T>()
=> Class.FromType(typeof(T));
}
}
|
using AmorosRisk.Infrastructure;
using EmptyKeys.UserInterface.Controls;
using System;
using System.Collections.Generic;
using System.Text;
namespace AmorosRisk.Components.UIComponents
{
internal class UiScreenComponent
{
public UserControl WindowRoot { get; set; }
public SystemContext Context { get; set; }
public UiScreenComponent(UserControl windowRoot, SystemContext context)
{
WindowRoot = windowRoot;
Context = context;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZWave.Channel;
namespace Threax.Home.ZWave.Models
{
public class CommandClassReportView
{
public CommandClass Class { get; set; }
public byte NodeId { get; internal set; }
public byte Version { get; set; }
}
}
|
namespace HEF.Sql
{
public class SqlBuilderFactory : ISqlBuilderFactory
{
public ISelectSqlBuilder Select()
{
return new SelectSqlBuilder();
}
public IInsertSqlBuilder Insert()
{
return new InsertSqlBuilder();
}
public IUpdateSqlBuilder Update()
{
return new UpdateSqlBuilder();
}
public IDeleteSqlBuilder Delete()
{
return new DeleteSqlBuilder();
}
}
}
|
@{
ViewData["Title"] = "Cảnh báo truy cập";
}
<div style="margin-top:20vh;font-size:30px">
<h1 style="color:red">@ViewData["Title"]</h1>
<p style="color:red">Bạn bị chặn truy cập vào nội dung này !</p>
</div> |
// This source code was generated by ClangCaster
namespace NWindowsKits
{
// C:/Program Files (x86)/Windows Kits/10/Include/10.0.18362.0/um/d3d11.h:10014
public enum D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS
{
_DEINTERLACE_BLEND = 0x1,
_DEINTERLACE_BOB = 0x2,
_DEINTERLACE_ADAPTIVE = 0x4,
_DEINTERLACE_MOTION_COMPENSATION = 0x8,
_INVERSE_TELECINE = 0x10,
_FRAME_RATE_CONVERSION = 0x20,
}
}
|
using System;
using System.IO;
using System.Net;
using System.Windows.Media.Imaging;
using System.Threading;
namespace GlobalcachingApplication.Plugins.Maps.MapControl
{
public class BitmapStoreOSM : BitmapStore
{
protected override BitmapImage DownloadBitmap(Uri uri)
{
BeginDownload();
MemoryStream buffer = null;
try
{
// First download the image to our memory.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.UserAgent = UserAgent;
buffer = new MemoryStream();
using (var response = request.GetResponse())
{
var stream = response.GetResponseStream();
stream.CopyTo(buffer);
stream.Close();
}
// Then save a copy for future reference, making sure to rewind
// the stream to the start.
buffer.Position = 0;
SaveCacheImage(buffer, uri);
// Finally turn the memory into a beautiful picture.
buffer.Position = 0;
return GetImageFromStream(buffer);
}
catch (WebException)
{
RaiseDownloadError();
}
catch (NotSupportedException) // Problem creating the bitmap (messed up download?)
{
RaiseDownloadError();
}
finally
{
EndDownload();
if (buffer != null)
{
buffer.Dispose();
}
}
return null;
}
}
}
|
using System.Collections.Generic;
namespace UnityVolumeRendering
{
public enum ImageSequenceFormat
{
ImageSequence,
DICOM
}
public interface IImageSequenceFile
{
string GetFilePath();
}
public interface IImageSequenceSeries
{
IEnumerable<IImageSequenceFile> GetFiles();
}
/// <summary>
/// Importer for image sequence datasets, such as DICOM and image sequences.
/// These datasets usually contain one file per slice.
/// </summary>
public interface IImageSequenceImporter
{
/// <summary>
/// Read a list of files, and return all image sequence series.
/// Normally a directory will only contain a single series,
/// but if a folder contains multiple series/studies than this function will return all of them.
/// Each series should be imported separately, resulting in one dataset per series. (mostly relevant for DICOM)
/// </summary>
/// <param name="files">Files to load. Typically all the files stored in a specific (DICOM) directory.</param>
/// <returns>List of image sequence series.</returns>
IEnumerable<IImageSequenceSeries> LoadSeries(IEnumerable<string> files);
/// <summary>
/// Import a single image sequence series.
/// </summary>
/// <param name="series">The series to import</param>
/// <returns>Imported 3D volume dataset.</returns>
VolumeDataset ImportSeries(IImageSequenceSeries series);
}
}
|
// IValidateNewAccountMultipleAccountsError
using Disney.Mix.SDK;
public interface IValidateNewAccountMultipleAccountsError : IValidateNewAccountError
{
}
|
namespace WinformsControlsTest
{
partial class ToolTipTests
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.delaysNotSetButton = new System.Windows.Forms.Button();
this.automaticDelayButton = new System.Windows.Forms.Button();
this.autoPopDelayButton = new System.Windows.Forms.Button();
this.delaysNotSetToolTip = new System.Windows.Forms.ToolTip(this.components);
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.defaultAutomaticDelayButton = new System.Windows.Forms.Button();
this.defaultAutoPopDelayButton = new System.Windows.Forms.Button();
this.initialDelayButton = new System.Windows.Forms.Button();
this.automaticDelayToolTip = new System.Windows.Forms.ToolTip(this.components);
this.autoPopDelayToolTip = new System.Windows.Forms.ToolTip(this.components);
this.defaultAutoPopDelayToolTip = new System.Windows.Forms.ToolTip(this.components);
this.defaultAutomaticDelayToolTip = new System.Windows.Forms.ToolTip(this.components);
this.initialDelayToolTip = new System.Windows.Forms.ToolTip(this.components);
this.autoEllipsisButton = new System.Windows.Forms.Button();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// delaysNoSetButton
//
this.delaysNotSetButton.AutoSize = true;
this.delaysNotSetButton.Location = new System.Drawing.Point(8, 411);
this.delaysNotSetButton.Name = "delaysNoSetButton";
this.delaysNotSetButton.Size = new System.Drawing.Size(876, 183);
this.delaysNotSetButton.TabIndex = 2;
this.delaysNotSetToolTip.SetToolTip(this.delaysNotSetButton, "Persistent");
this.delaysNotSetButton.Text = "Delays ¬ set";
this.delaysNotSetButton.UseVisualStyleBackColor = true;
//
// automaticDelayButton
//
this.automaticDelayButton.AutoSize = true;
this.automaticDelayButton.Location = new System.Drawing.Point(8, 9);
this.automaticDelayButton.Name = "automaticDelayButton";
this.automaticDelayButton.Size = new System.Drawing.Size(1031, 183);
this.automaticDelayButton.TabIndex = 0;
this.automaticDelayToolTip.SetToolTip(this.automaticDelayButton, "Not persistent");
this.automaticDelayButton.Text = "&AutomaticDelay = 30";
this.automaticDelayButton.UseVisualStyleBackColor = true;
//
// autoPopDelayButton
//
this.autoPopDelayButton.AutoSize = true;
this.autoPopDelayButton.Location = new System.Drawing.Point(8, 210);
this.autoPopDelayButton.Name = "autoPopDelayButton";
this.autoPopDelayButton.Size = new System.Drawing.Size(949, 183);
this.autoPopDelayButton.TabIndex = 1;
this.autoPopDelayToolTip.SetToolTip(this.autoPopDelayButton, "Not persistent");
this.autoPopDelayButton.Text = "Auto&PopDelay = 300";
this.autoPopDelayButton.UseVisualStyleBackColor = true;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.automaticDelayButton);
this.flowLayoutPanel1.Controls.Add(this.autoPopDelayButton);
this.flowLayoutPanel1.Controls.Add(this.delaysNotSetButton);
this.flowLayoutPanel1.Controls.Add(this.defaultAutomaticDelayButton);
this.flowLayoutPanel1.Controls.Add(this.defaultAutoPopDelayButton);
this.flowLayoutPanel1.Controls.Add(this.initialDelayButton);
this.flowLayoutPanel1.Controls.Add(this.autoEllipsisButton);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(1417, 1577);
this.flowLayoutPanel1.TabIndex = 0;
//
// defaultAutomaticDelayButton
//
this.defaultAutomaticDelayButton.AutoSize = true;
this.defaultAutomaticDelayButton.Location = new System.Drawing.Point(8, 612);
this.defaultAutomaticDelayButton.Name = "defaultAutomaticDelayButton";
this.defaultAutomaticDelayButton.Size = new System.Drawing.Size(915, 183);
this.defaultAutomaticDelayButton.TabIndex = 3;
this.defaultAutomaticDelayToolTip.SetToolTip(this.defaultAutomaticDelayButton, "Persistent");
this.defaultAutomaticDelayButton.Text = "AutomaticDelay = 500";
this.defaultAutomaticDelayButton.UseVisualStyleBackColor = true;
//
// defaultAutoPopDelayButton
//
this.defaultAutoPopDelayButton.AutoSize = true;
this.defaultAutoPopDelayButton.Location = new System.Drawing.Point(8, 813);
this.defaultAutoPopDelayButton.Name = "defaultAutoPopDelayButton";
this.defaultAutoPopDelayButton.Size = new System.Drawing.Size(904, 183);
this.defaultAutoPopDelayButton.TabIndex = 4;
this.defaultAutoPopDelayToolTip.SetToolTip(this.defaultAutoPopDelayButton, "Persistent");
this.defaultAutoPopDelayButton.Text = "AutoPopDelay = 5000";
this.defaultAutoPopDelayButton.UseVisualStyleBackColor = true;
//
// initialDelayButton
//
this.initialDelayButton.AutoSize = true;
this.initialDelayButton.Location = new System.Drawing.Point(8, 1014);
this.initialDelayButton.Name = "initialDelayButton";
this.initialDelayButton.Size = new System.Drawing.Size(876, 183);
this.initialDelayButton.TabIndex = 5;
this.initialDelayToolTip.SetToolTip(this.initialDelayButton, "Persistent");
this.initialDelayButton.Text = "I&nitial delay = 10";
this.initialDelayButton.UseVisualStyleBackColor = true;
//
// autoEllipsisButton
//
this.autoEllipsisButton.AutoEllipsis = true;
this.autoEllipsisButton.AutoSize = false;
this.autoEllipsisButton.Location = new System.Drawing.Point(8, 1215);
this.autoEllipsisButton.Name = "autoEllipsisButton";
this.autoEllipsisButton.Size = new System.Drawing.Size(876, 183);
this.autoEllipsisButton.TabIndex = 6;
this.autoEllipsisButton.Text = "Auto&Ellipsis = true; 1234567890";
this.autoEllipsisButton.UseVisualStyleBackColor = true;
//
// automaticDelayToolTip
//
this.automaticDelayToolTip.AutomaticDelay = 30;
//
// autoPopDelayToolTip
//
this.autoPopDelayToolTip.AutoPopDelay = 300;
this.autoPopDelayToolTip.InitialDelay = 500;
this.autoPopDelayToolTip.ReshowDelay = 100;
//
// initialDelayToolTip
//
this.initialDelayToolTip.AutoPopDelay = 5000;
this.initialDelayToolTip.InitialDelay = 10;
this.initialDelayToolTip.ReshowDelay = 100;
//
// ToolTipTests
//
this.AutoScaleDimensions = new System.Drawing.SizeF(17F, 41F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1417, 1577);
this.Controls.Add(this.flowLayoutPanel1);
this.Name = "ToolTipTests";
this.Text = "ToolTips";
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button delaysNotSetButton;
private System.Windows.Forms.Button automaticDelayButton;
private System.Windows.Forms.Button autoPopDelayButton;
private System.Windows.Forms.Button autoEllipsisButton;
private System.Windows.Forms.Button defaultAutomaticDelayButton;
private System.Windows.Forms.Button defaultAutoPopDelayButton;
private System.Windows.Forms.Button initialDelayButton;
private System.Windows.Forms.ToolTip automaticDelayToolTip;
private System.Windows.Forms.ToolTip autoPopDelayToolTip;
private System.Windows.Forms.ToolTip defaultAutomaticDelayToolTip;
private System.Windows.Forms.ToolTip defaultAutoPopDelayToolTip;
private System.Windows.Forms.ToolTip delaysNotSetToolTip;
private System.Windows.Forms.ToolTip initialDelayToolTip;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
}
}
|
using Synergy.Contracts;
namespace Synergy.Sample.Web.API.Services.Users.Domain
{
public struct Login
{
public string Value { get; }
public Login(string value) => this.Value = value.OrFailIfWhiteSpace(nameof(Login));
public override string ToString() => this.Value;
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WebApp.Api.Contracts;
using WebApp.Api.Models;
namespace WebApp.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class MojangController : ControllerBase
{
IMojangService _mojangService;
public MojangController(IMojangService mojangService)
{
_mojangService = mojangService;
}
[HttpGet("playerProfile/{username}")]
[AllowAnonymous]
public async Task<ActionResult<PlayerProfile>> GetPlayer(string username)
{
try
{
var player = await _mojangService.GetPlayer(username).ConfigureAwait(false);
return Ok(player);
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
}
}
|
using FluentValidation;
using System.Linq;
namespace ScheduleGenerator.Shared.Validators
{
public static class CustomValidators
{
public static IRuleBuilderInitial<T, string> MatchPassword<T>(this IRuleBuilder<T, string> ruleBuilder)
{
return ruleBuilder.Custom((password, context) =>
{
if (!password.Any(char.IsDigit))
{
context.AddFailure("Password must contain at least one number");
}
if (!password.Any(char.IsLetter))
{
context.AddFailure("Password must contain at least one letter");
}
if (!password.Any(char.IsUpper))
{
context.AddFailure("Password must contain at least one upper letter");
}
});
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LobbyElement : MonoBehaviour
{
[SerializeField] private Text itemName;
[SerializeField] private Button _button;
public event Action<string> NeedToJoinRoom;
private void Start()
{
_button.onClick.AddListener(Join);
}
public void SetItem(string name)
{
itemName.text = name;
}
private void Join()
{
if (itemName.text!=""||itemName.text!=null)
{
NeedToJoinRoom.Invoke(itemName.text);
}
}
}
|
using UnityEngine;
public class CameraController : MonoBehaviour
{
//移动边框大小
public float GUISize = 25f;
//相机移动速度
public float cameraSpeed = 1f;
//相机缩放速度
public float zoomSpeed = 1f;
public float maxZoom = 100f;
public float minZoom = 15f;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
MoveUpdata();
ZoomUpdate();
}
void ZoomUpdate() {
if (Camera.main.fieldOfView > maxZoom) {
Camera.main.fieldOfView = maxZoom;
return;
}
if (Camera.main.fieldOfView < minZoom) {
Camera.main.fieldOfView = minZoom;
return;
}
float axis = Input.GetAxis("Mouse ScrollWheel");
Camera.main.fieldOfView -= axis * zoomSpeed;
}
void MoveUpdata() {
Rect rectDown = new Rect(0, 0, Screen.width, GUISize);
Rect rectUp = new Rect(0, Screen.height - GUISize, Screen.width, GUISize);
Rect rectLeft = new Rect(0, 0, GUISize, Screen.height);
Rect rectRight = new Rect(Screen.width - GUISize, 0, GUISize, Screen.height);
if (rectDown.Contains(Input.mousePosition)) {
transform.
transform.Translate(0, 0, cameraSpeed, Space.World);
}
if (rectUp.Contains(Input.mousePosition)) {
transform.Translate(0, 0, -cameraSpeed, Space.World);
}
if (rectLeft.Contains(Input.mousePosition)) {
transform.Translate(cameraSpeed, 0, 0, Space.World);
}
if (rectRight.Contains(Input.mousePosition)) {
transform.Translate(-cameraSpeed, 0, 0, Space.World);
}
}
}
|
namespace Fixie
{
using System;
/// <summary>
/// A discriminated union representing the result of a single run of a test.
/// <para>Use pattern matching to inspect:</para>
/// <list type="bullet">
/// <item>Passed</item>
/// <item>Failed (Exception Reason)</item>
/// </list>
/// </summary>
public abstract class TestResult
{
internal static readonly Passed Passed = new Passed();
internal static Failed Failed(Exception reason) => new Failed(reason);
}
/// <summary>
/// Represents the fact that a test has passed.
/// </summary>
public class Passed : TestResult
{
internal Passed() { }
}
/// <summary>
/// Represents the fact that a test has failed due to its throwing an exception.
/// </summary>
public class Failed : TestResult
{
internal Failed(Exception reason) => Reason = reason;
/// <summary>
/// The exception thrown by a failing test.
/// </summary>
public Exception Reason { get; }
}
} |
//--------------------------------------------------
// Motion Framework
// Copyright©2021-2021 何冠峰
// Licensed under the MIT license
//--------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using MotionFramework.IO;
namespace MotionFramework.Editor
{
public static class CollectorConfigImporter
{
private class CollectWrapper
{
public string CollectDirectory;
public string PackRuleName;
public string FilterRuleName;
public bool DontWriteAssetPath;
public string AssetTags;
public CollectWrapper(string directory, string packRuleName, string filterRuleName, bool dontWriteAssetPath, string assetTags)
{
CollectDirectory = directory;
PackRuleName = packRuleName;
FilterRuleName = filterRuleName;
DontWriteAssetPath = dontWriteAssetPath;
AssetTags = assetTags;
}
}
public const string XmlCollector = "Collector";
public const string XmlDirectory = "Directory";
public const string XmlPackRule = "PackRule";
public const string XmlFilterRule = "FilterRule";
public const string XmlDontWriteAssetPath = "DontWriteAssetPath";
public const string XmlAssetTags = "AssetTags";
public static void ImportXmlConfig(string filePath)
{
if (File.Exists(filePath) == false)
throw new FileNotFoundException(filePath);
if (Path.GetExtension(filePath) != ".xml")
throw new Exception($"Only support xml : {filePath}");
List<CollectWrapper> wrappers = new List<CollectWrapper>();
// 加载文件
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
// 解析文件
XmlElement root = xml.DocumentElement;
XmlNodeList nodeList = root.GetElementsByTagName(XmlCollector);
if (nodeList.Count == 0)
throw new Exception($"Not found any {XmlCollector}");
foreach (XmlNode node in nodeList)
{
XmlElement collect = node as XmlElement;
string directory = collect.GetAttribute(XmlDirectory);
string packRuleName = collect.GetAttribute(XmlPackRule);
string filterRuleName = collect.GetAttribute(XmlFilterRule);
string dontWriteAssetPath = collect.GetAttribute(XmlDontWriteAssetPath);
string assetTags = collect.GetAttribute(XmlAssetTags);
if (Directory.Exists(directory) == false)
throw new Exception($"Not found directory : {directory}");
if (collect.HasAttribute(XmlPackRule) == false)
throw new Exception($"Not found attribute {XmlPackRule} in collector : {directory}");
if (collect.HasAttribute(XmlFilterRule) == false)
throw new Exception($"Not found attribute {XmlFilterRule} in collector : {directory}");
if (collect.HasAttribute(XmlDontWriteAssetPath) == false)
throw new Exception($"Not found attribute {XmlDontWriteAssetPath} in collector : {directory}");
if (collect.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in collector : {directory}");
if (AssetBundleCollectorSettingData.HasPackRuleName(packRuleName) == false)
throw new Exception($"Invalid {nameof(IPackRule)} class type : {packRuleName}");
if (AssetBundleCollectorSettingData.HasFilterRuleName(filterRuleName) == false)
throw new Exception($"Invalid {nameof(IFilterRule)} class type : {filterRuleName}");
bool dontWriteAssetPathValue = StringConvert.StringToBool(dontWriteAssetPath);
CollectWrapper collectWrapper = new CollectWrapper(directory, packRuleName, filterRuleName, dontWriteAssetPathValue, assetTags);
wrappers.Add(collectWrapper);
}
// 导入配置数据
AssetBundleCollectorSettingData.ClearAllCollector();
foreach (var wrapper in wrappers)
{
AssetBundleCollectorSettingData.AddCollector(wrapper.CollectDirectory, wrapper.PackRuleName, wrapper.FilterRuleName, wrapper.DontWriteAssetPath, wrapper.AssetTags, false);
}
// 保存配置数据
AssetBundleCollectorSettingData.SaveFile();
Debug.Log($"导入配置完毕,一共导入{wrappers.Count}个收集器。");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TilePalette : MonoBehaviour
{
public Tile.Type paletteType;
// Start is called before the first frame update
void Start()
{
switch (paletteType)
{
case Tile.Type.Path:
GetComponent<SpriteRenderer>().color = Color.white;
break;
case Tile.Type.Wall:
GetComponent<SpriteRenderer>().color = Color.gray;
break;
case Tile.Type.Start:
GetComponent<SpriteRenderer>().color = Color.green;
break;
case Tile.Type.Finish:
GetComponent<SpriteRenderer>().color = Color.red;
break;
default:
break;
}
}
private void OnMouseDown()
{
if (!TileGenerator.instance.turnedOn) return;
TileGenerator.instance.selectedTileType = paletteType;
}
}
|
namespace NBASharp.Model;
public class InternalModel
{
public string PubDateTime { get; set; }
public string Xslt { get; set; }
public string EventName { get; set; }
} |
// Copyright Finbuckle LLC, Andrew White, and Contributors.
// Refer to the solution LICENSE file for more inforation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Finbuckle.MultiTenant.Strategies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using Constants = Finbuckle.MultiTenant.Internal.Constants;
namespace Finbuckle.MultiTenant.AspNetCore.Test.Extensions
{
public class MultiTenantBuilderExtensionsShould
{
public class TestTenantInfo : ITenantInfo
{
public string Id { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
public string ConnectionString { get; set; }
public string ChallengeScheme { get; set; }
public string CookiePath { get; set; }
public string CookieLoginPath { get; set; }
public string CookieLogoutPath { get; set; }
public string CookieAccessDeniedPath { get; set; }
public string OpenIdConnectAuthority { get; set; }
public string OpenIdConnectClientId { get; set; }
public string OpenIdConnectClientSecret { get; set; }
}
[Fact]
public void NotThrowIfOriginalPrincipalValidationNotSet()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddAuthentication().AddCookie();
services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>();
mtc.TenantInfo = new TenantInfo { Identifier = "abc" };
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
httpContextMock.Setup(c => c.Items).Returns(new Dictionary<object, object>());
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.True(true);
}
[Fact]
public void CallOriginalPrincipalValidation()
{
var services = new ServiceCollection();
services.AddLogging();
var called = false;
services.AddAuthentication().AddCookie(options =>
{
#pragma warning disable 1998
options.Events.OnValidatePrincipal = async _ =>
#pragma warning restore 1998
{
called = true;
};
});
services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>();
mtc.TenantInfo = new TenantInfo { Identifier = "abc" };
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
httpContextMock.Setup(c => c.Items).Returns(new Dictionary<object, object>());
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.True(called);
}
[Fact]
public void PassprincipalValidationIfTenantMatch()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddAuthentication().AddCookie();
services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>();
mtc.TenantInfo = new TenantInfo { Identifier = "abc" };
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
httpContextMock.Setup(c => c.Items).Returns(new Dictionary<object, object>());
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.NotNull(cookieValidationContext);
}
[Fact]
public void SkipPrincipalValidationIfBypassSet_WithPerTenantAuthentication()
{
var services = new ServiceCollection();
services.AddLogging();
var called = false;
#pragma warning disable 1998
services.AddAuthentication().AddCookie(o => o.Events.OnValidatePrincipal = async _ => called = true);
#pragma warning restore 1998
services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>();
mtc.TenantInfo = new TenantInfo { Identifier = "abc1" };
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
var httpContextItems = new Dictionary<object, object>();
httpContextItems[$"{Constants.TenantToken}__bypass_validate_principal__"] = true;
httpContextMock.Setup(c => c.Items).Returns(httpContextItems);
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc2";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.NotNull(cookieValidationContext.Principal);
Assert.False(called);
}
[Fact]
public void SkipPrincipalValidationIfBypassSet_WithClaimStrategy()
{
var services = new ServiceCollection();
services.AddLogging();
var called = false;
#pragma warning disable 1998
services.AddAuthentication().AddCookie(o => o.Events.OnValidatePrincipal = async _ => called = true);
#pragma warning restore 1998
services.AddMultiTenant<TenantInfo>()
.WithClaimStrategy();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>
{
TenantInfo = new TenantInfo { Identifier = "abc1" }
};
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
var httpContextItems = new Dictionary<object, object>();
httpContextItems[$"{Constants.TenantToken}__bypass_validate_principal__"] = true;
httpContextMock.Setup(c => c.Items).Returns(httpContextItems);
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc2";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.NotNull(cookieValidationContext.Principal);
Assert.False(called);
}
[Fact]
public void RejectPrincipalValidationIfTenantMatch()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddAuthentication().AddCookie();
services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
// Fake a resolved tenant
var mtc = new MultiTenantContext<TenantInfo>();
mtc.TenantInfo = new TenantInfo { Identifier = "abc1" };
sp.GetRequiredService<IMultiTenantContextAccessor<TenantInfo>>().MultiTenantContext = mtc;
// Trigger the ValidatePrincipal event
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(c => c.RequestServices).Returns(sp);
httpContextMock.Setup(c => c.Items).Returns(new Dictionary<object, object>());
var scheme = sp.GetRequiredService<IAuthenticationSchemeProvider>()
.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
var options = sp.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(new ClaimsIdentity());
var authTicket = new AuthenticationTicket(principal, CookieAuthenticationDefaults.AuthenticationScheme);
authTicket.Properties.Items[Constants.TenantToken] = "abc2";
var cookieValidationContext =
new CookieValidatePrincipalContext(httpContextMock.Object, scheme, options, authTicket);
options.Events.ValidatePrincipal(cookieValidationContext).Wait();
Assert.Null(cookieValidationContext.Principal);
}
[Fact]
public void ConfigurePerTenantAuthentication_RegisterServices()
{
var services = new ServiceCollection();
services.AddAuthentication();
services.AddLogging();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
var authService = sp.GetRequiredService<IAuthenticationService>(); // Throws if fail
Assert.IsType<MultiTenantAuthenticationService<TestTenantInfo>>(authService);
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>(); // Throws if fails
Assert.IsType<MultiTenantAuthenticationSchemeProvider>(schemeProvider);
var strategy = sp.GetServices<IMultiTenantStrategy>().Where(s => s.GetType() == typeof(RemoteAuthenticationCallbackStrategy)).Single();
Assert.NotNull(strategy);
}
[Fact]
public void ConfigurePerTenantAuthenticationCore_RegisterServices()
{
var services = new ServiceCollection();
services.AddAuthentication();
services.AddLogging();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthenticationCore();
var sp = services.BuildServiceProvider();
var authService = sp.GetRequiredService<IAuthenticationService>(); // Throws if fail
Assert.IsType<MultiTenantAuthenticationService<TestTenantInfo>>(authService);
var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>(); // Throws if fails
Assert.IsType<MultiTenantAuthenticationSchemeProvider>(schemeProvider);
}
[Fact]
public void AddRemoteAuthenticationCallbackStrategy()
{
var services = new ServiceCollection();
services.AddAuthentication();
services.AddLogging();
services.AddMultiTenant<TestTenantInfo>()
.WithRemoteAuthenticationCallbackStrategy();
var sp = services.BuildServiceProvider();
var strategy = sp.GetServices<IMultiTenantStrategy>().Where(s => s.GetType() == typeof(RemoteAuthenticationCallbackStrategy)).Single();
Assert.NotNull(strategy);
}
[Fact]
public void ConfigurePerTenantAuthentication_UseChallengeScheme()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddCookie().AddOpenIdConnect("customScheme", null);
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
ChallengeScheme = "customScheme"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IAuthenticationSchemeProvider>();
Assert.Equal(ti1.ChallengeScheme, options.GetDefaultChallengeSchemeAsync().Result.Name);
}
[Fact]
public void ConfigurePerTenantAuthenticationConventions_UseChallengeScheme()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddCookie().AddOpenIdConnect("customScheme", null);
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthenticationConventions();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
ChallengeScheme = "customScheme"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IAuthenticationSchemeProvider>();
Assert.Equal(ti1.ChallengeScheme, options.GetDefaultChallengeSchemeAsync().Result.Name);
}
[Fact]
public void ConfigurePerTenantAuthentication_UseOpenIdConnectConvention()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddOpenIdConnect();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
OpenIdConnectAuthority = "https://tenant",
OpenIdConnectClientId = "tenant",
OpenIdConnectClientSecret = "secret"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IOptionsSnapshot<OpenIdConnectOptions>>().Get(OpenIdConnectDefaults.AuthenticationScheme);
Assert.Equal(ti1.OpenIdConnectAuthority, options.Authority);
Assert.Equal(ti1.OpenIdConnectClientId, options.ClientId);
Assert.Equal(ti1.OpenIdConnectClientSecret, options.ClientSecret);
}
[Fact]
public void ConfigurePerTenantAuthenticationConventions_UseOpenIdConnectConvention()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddOpenIdConnect();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthenticationConventions();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
OpenIdConnectAuthority = "https://tenant",
OpenIdConnectClientId = "tenant",
OpenIdConnectClientSecret = "secret"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IOptionsSnapshot<OpenIdConnectOptions>>().Get(OpenIdConnectDefaults.AuthenticationScheme);
Assert.Equal(ti1.OpenIdConnectAuthority, options.Authority);
Assert.Equal(ti1.OpenIdConnectClientId, options.ClientId);
Assert.Equal(ti1.OpenIdConnectClientSecret, options.ClientSecret);
}
[Fact]
public void ConfigurePerTenantAuthentication_UseCookieOptionsConvention()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddCookie();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthentication();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
CookieLoginPath = "/path1",
CookieLogoutPath = "/path2",
CookieAccessDeniedPath = "/path3"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IOptionsSnapshot<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
Assert.Equal(ti1.CookieLoginPath, options.LoginPath);
Assert.Equal(ti1.CookieLogoutPath, options.LogoutPath);
Assert.Equal(ti1.CookieAccessDeniedPath, options.AccessDeniedPath);
}
[Fact]
public void ConfigurePerTenantAuthenticationConventions_UseCookieOptionsConvention()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddAuthentication().AddCookie();
services.AddMultiTenant<TestTenantInfo>()
.WithPerTenantAuthenticationConventions();
var sp = services.BuildServiceProvider();
var ti1 = new TestTenantInfo
{
Id = "id1",
Identifier = "identifier1",
CookieLoginPath = "/path1",
CookieLogoutPath = "/path2",
CookieAccessDeniedPath = "/path3"
};
var accessor = sp.GetRequiredService<IMultiTenantContextAccessor<TestTenantInfo>>();
accessor.MultiTenantContext = new MultiTenantContext<TestTenantInfo> { TenantInfo = ti1 };
var options = sp.GetRequiredService<IOptionsSnapshot<CookieAuthenticationOptions>>().Get(CookieAuthenticationDefaults.AuthenticationScheme);
Assert.Equal(ti1.CookieLoginPath, options.LoginPath);
Assert.Equal(ti1.CookieLogoutPath, options.LogoutPath);
Assert.Equal(ti1.CookieAccessDeniedPath, options.AccessDeniedPath);
}
[Fact]
public void WithPerTenantAuthentication_ThrowIfCantDecorateIAuthenticationService()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
Assert.Throws<MultiTenantException>(() => builder.WithPerTenantAuthentication());
}
[Fact]
public void AddBasePathStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
builder.WithBasePathStrategy();
var sp = services.BuildServiceProvider();
var strategy = sp.GetRequiredService<IMultiTenantStrategy>();
Assert.IsType<BasePathStrategy>(strategy);
}
[Fact]
public void AddClaimStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
builder.WithClaimStrategy();
var sp = services.BuildServiceProvider();
var strategy = sp.GetRequiredService<IMultiTenantStrategy>();
Assert.IsType<ClaimStrategy>(strategy);
}
[Fact]
public void AddHeaderStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
builder.WithHeaderStrategy();
var sp = services.BuildServiceProvider();
var strategy = sp.GetRequiredService<IMultiTenantStrategy>();
Assert.IsType<HeaderStrategy>(strategy);
}
[Fact]
public void AddHostStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
builder.WithHostStrategy();
var sp = services.BuildServiceProvider();
var strategy = sp.GetRequiredService<IMultiTenantStrategy>();
Assert.IsType<HostStrategy>(strategy);
}
[Fact]
public void ThrowIfNullParamAddingHostStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
Assert.Throws<ArgumentException>(()
=> builder.WithHostStrategy(null));
}
[Fact]
public void AddRouteStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
builder.WithRouteStrategy("routeParam");
var sp = services.BuildServiceProvider();
var strategy = sp.GetRequiredService<IMultiTenantStrategy>();
Assert.IsType<RouteStrategy>(strategy);
}
[Fact]
public void ThrowIfNullParamAddingRouteStrategy()
{
var services = new ServiceCollection();
var builder = new FinbuckleMultiTenantBuilder<TenantInfo>(services);
Assert.Throws<ArgumentException>(()
=> builder.WithRouteStrategy(null));
}
}
} |
namespace AIBehavior
{
public class LowHealthTrigger : HealthTrigger
{
public override bool IsThresholdCrossed(AIBehaviors fsm)
{
return fsm.GetHealthValue() <= healthThreshold;
}
public override string DefaultDisplayName()
{
return "Low Health";
}
#if UNITY_EDITOR
protected override string GetDescriptionText ()
{
return "Below Health";
}
protected override string GetToolTipText ()
{
return "Triggered if the health is less than or equal to this value.";
}
#endif
}
} |
using System;
using NDarrayLib;
namespace DustLore.Optimizers
{
public interface IOptimizer
{
string Name { get; }
IOptimizer Clone();
void Update(NDarray<double> w, NDarray<double> g);
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace DotNetCloud.SqsToolbox.Hosting
{
//public class SqsBatchDeleteBackgroundService : IHostedService
//{
// private readonly ISqsBatchDeleter _sqsBatchDeleter;
// public SqsBatchDeleteBackgroundService(ISqsBatchDeleter sqsBatchDeleter)
// {
// _sqsBatchDeleter = sqsBatchDeleter;
// }
// public Task StartAsync(CancellationToken cancellationToken)
// {
// _sqsBatchDeleter.Start(cancellationToken);
// return Task.CompletedTask;
// }
// public async Task StopAsync(CancellationToken cancellationToken)
// {
// await _sqsBatchDeleter.StopAsync();
// }
//}
}
|
using Haven;
using SharpHaven.UI.Widgets;
namespace SharpHaven.UI.Remote
{
public class ServerCalendar : ServerWidget
{
private Calendar widget;
public ServerCalendar(ushort id, ServerWidget parent) : base(id, parent)
{
}
public override Widget Widget
{
get { return null; }
}
public static ServerWidget Create(ushort id, ServerWidget parent)
{
return new ServerCalendar(id, parent);
}
protected override void OnInit(Point2D position, object[] args)
{
widget = Session.Screen.Calendar;
widget.Visible = true;
widget.Session = Session;
}
protected override void OnDestroy()
{
widget.Visible = false;
widget.Session = null;
}
}
}
|
using Microsoft.WindowsAzure.MediaServices.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MediaDashboard.Common.Data
{
public class MediaOrigin
{
static private int ReservedUnitCapacity = 160;
[JsonProperty("Health")]
public HealthStatus Health { get; set; }
[JsonProperty("Created")]
public DateTime Created { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
public string HostName { get; set; }
public string Id { get; set; }
[JsonProperty("LastModified")]
public DateTime LastModified { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
//Short name to display in seating chart.
public string NameShort { get; set; }
public int ReservedUnits { get; set; }
[JsonProperty("State")]
public string State { get; set; }
/// <summary>
/// Calculated values
/// </summary>
public int Capacity
{
get { return (this.ReservedUnits * ReservedUnitCapacity); }
}
public int Throughput // Bytes
{
get { return 83886080; }
}
public int Utilization
{
get
{
decimal temp = (Capacity == 0) ? 0: ((decimal)Throughput / (decimal)((Capacity * 1024)*1024));
return (int)(temp * 100);
}
}
public DateTime LastMetricUpdate;
public List<IMetricBase> Metrics;
public string IPAllowList { get; set; }
public List<AkamaiSignatureHeaderAuthenticationKey> AuthenticationKeys { get; set; }
public TimeSpan? MaxAge { get; set; }
}
}
|
using Cake.Core.IO;
using Cake.Core.IO.NuGet;
using Cake.Testing;
using NSubstitute;
using Xunit;
namespace Cake.Core.Tests.Unit.IO.NuGet
{
public sealed class NuGetToolResolverTests
{
public sealed class TheConstructor
{
[Fact]
public void Should_Throw_If_File_System_Is_Null()
{
// Given
var globber = Substitute.For<IGlobber>();
var environment = Substitute.For<ICakeEnvironment>();
// When
var result = Record.Exception(() => new NuGetToolResolver(null, environment, globber));
// Then
Assert.IsArgumentNullException(result, "fileSystem");
}
[Fact]
public void Should_Throw_If_Environment_Is_Null()
{
// Given
var fileSystem = Substitute.For<IFileSystem>();
var globber = Substitute.For<IGlobber>();
// When
var result = Record.Exception(() => new NuGetToolResolver(fileSystem, null, globber));
// Then
Assert.IsArgumentNullException(result, "environment");
}
[Fact]
public void Should_Throw_If_Globber_Is_Null()
{
// Given
var fileSystem = Substitute.For<IFileSystem>();
var environment = Substitute.For<ICakeEnvironment>();
// When
var result = Record.Exception(() => new NuGetToolResolver(fileSystem, environment, null));
// Then
Assert.IsArgumentNullException(result, "globber");
}
}
public sealed class TheResolveToolPathMethod
{
[Fact]
public void Should_Throw_If_NuGet_Exe_Could_Not_Be_Found()
{
// Given
var environment = Substitute.For<ICakeEnvironment>();
environment.WorkingDirectory.Returns("/Working");
environment.IsUnix().Returns(false);
environment.GetEnvironmentVariable("NUGET_EXE").Returns(c => null);
environment.GetEnvironmentVariable("path").Returns(c => null);
var fileSystem = new FakeFileSystem(environment);
var globber = Substitute.For<IGlobber>();
globber.GetFiles("./tools/**/NuGet.exe").Returns(new FilePath[] { });
var resolver = new NuGetToolResolver(fileSystem, environment, globber);
// When
var result = Record.Exception(() => resolver.ResolvePath());
// Assert
Assert.IsCakeException(result, "Could not locate nuget.exe.");
}
[Fact]
public void Should_Resolve_In_Correct_Order()
{
// Given
var environment = Substitute.For<ICakeEnvironment>();
environment.WorkingDirectory.Returns("/Working");
environment.IsUnix().Returns(false);
environment.GetEnvironmentVariable("NUGET_EXE").Returns(c => null);
environment.GetEnvironmentVariable("path").Returns(c => null);
var fileSystem = new FakeFileSystem(environment);
var globber = Substitute.For<IGlobber>();
globber.GetFiles("./tools/**/NuGet.exe").Returns(new FilePath[] { });
var resolver = new NuGetToolResolver(fileSystem, environment, globber);
// When
Record.Exception(() => resolver.ResolvePath());
// Then
Received.InOrder(() =>
{
// 1. Look in the tools directory.
globber.GetFiles("./tools/**/NuGet.exe");
// 2. Look for the environment variable NUGET_EXE.
environment.GetEnvironmentVariable("NUGET_EXE");
// 3. Panic and look in the path variable.
environment.GetEnvironmentVariable("path");
});
}
[Fact]
public void Should_Be_Able_To_Resolve_Path_From_The_Tools_Directory()
{
// Given
var environment = FakeEnvironment.CreateUnixEnvironment();
var fileSystem = new FakeFileSystem(environment);
var globber = Substitute.For<IGlobber>();
globber.Match("./tools/**/NuGet.exe").Returns(p => new FilePath[] { "/root/tools/nuget.exe" });
fileSystem.CreateFile("/root/tools/nuget.exe");
var resolver = new NuGetToolResolver(fileSystem, environment, globber);
// When
var result = resolver.ResolvePath();
// Then
Assert.Equal("/root/tools/nuget.exe", result.FullPath);
}
[Fact]
public void Should_Be_Able_To_Resolve_Path_Via_NuGet_Environment_Variable()
{
// Given
var globber = Substitute.For<IGlobber>();
var environment = Substitute.For<ICakeEnvironment>();
environment.WorkingDirectory.Returns("/Working");
environment.IsUnix().Returns(false);
environment.GetEnvironmentVariable("NUGET_EXE").Returns("/programs/nuget.exe");
var fileSystem = new FakeFileSystem(environment);
fileSystem.CreateFile("/programs/nuget.exe");
var resolver = new NuGetToolResolver(fileSystem, environment, globber);
// When
var result = resolver.ResolvePath();
// Then
Assert.Equal("/programs/nuget.exe", result.FullPath);
}
[Fact]
public void Should_Be_Able_To_Resolve_Path_Via_Environment_Path_Variable()
{
// Given
var globber = Substitute.For<IGlobber>();
var environment = Substitute.For<ICakeEnvironment>();
environment.WorkingDirectory.Returns("/Working");
environment.IsUnix().Returns(false);
environment.GetEnvironmentVariable("path").Returns("/temp;stuff/programs;/programs");
var fileSystem = new FakeFileSystem(environment);
fileSystem.CreateDirectory("stuff/programs");
fileSystem.CreateFile("stuff/programs/nuget.exe");
var resolver = new NuGetToolResolver(fileSystem, environment, globber);
// When
var result = resolver.ResolvePath();
// Then
Assert.Equal("stuff/programs/nuget.exe", result.FullPath);
}
}
}
} |
using ArkSavegameToolkitNet.DataTypes.Properties;
namespace ArkSavegameToolkitNet.DataReaders.Properties
{
static class VectorStructReader
{
public static VectorStructProperty Get(ArchiveReader ar)
{
var result = new VectorStructProperty();
ar.GetFloat(out result.x, "x");
ar.GetFloat(out result.y, "y");
ar.GetFloat(out result.z, "z");
return result;
}
}
}
|
using UnityEngine;
public class ScoreDisplayPack:ScriptableObject {
public Sprite[] images;
}
|
/*
* Copyright (c) 2019 Robotic Eyes GmbH software
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
*/
using UnityEngine;
namespace RoboticEyes.Rex.RexFileReader.Examples
{
[RequireComponent (typeof (LineRenderer))]
public class LineSetScaleByDistance : MonoBehaviour
{
private LineRenderer lineRenderer;
private AnimationCurve widthCurve;
private Vector3[] linePositions;
private float currentScale = 0f;
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
}
private void Start()
{
linePositions = new Vector3[lineRenderer.positionCount];
lineRenderer.GetPositions (linePositions);
widthCurve = new AnimationCurve();
widthCurve.AddKey (0f, 1f);
widthCurve.AddKey (1f, 1f);
lineRenderer.widthCurve = widthCurve;
}
void Update ()
{
if (currentScale == transform.lossyScale.x)
{
return;
}
currentScale = transform.lossyScale.x;
var key = new Keyframe (0f, Mathf.Max (0.05f, Mathf.Min (1.0f, currentScale)));
widthCurve.MoveKey (0, key);
key = new Keyframe (1f, Mathf.Max (0.05f, Mathf.Min (1.0f, currentScale)));
widthCurve.MoveKey (1, key);
lineRenderer.widthCurve = widthCurve;
}
}
} |
namespace AngleSharp.Dom.Css
{
/// <summary>
/// Available device update frequencies.
/// </summary>
public enum UpdateFrequency
{
/// <summary>
/// Once it has been rendered, the layout can no longer
/// be updated. Example: documents printed on paper.
/// </summary>
None,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, but the output device is not
/// able to render or display changes quickly enough for
/// them to be percieved as a smooth animation.
/// Example: E-ink screens or severely under-powered
/// devices.
/// </summary>
Slow,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, and the output device is not
/// unusually constrained in speed, so regularly-updating
/// things like CSS Animations can be used.
/// Example: computer screens.
/// </summary>
Normal
}
}
|
using System.Reflection;
using System.Threading.Tasks;
using Xbehave.Test.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace Xbehave.Test
{
public class AsyncCollectionFixtureFeature : Feature
{
[Background]
public void Background() =>
"Given no events have occurred"
.x(() => typeof(AsyncCollectionFixtureFeature).ClearTestEvents());
[Scenario]
public void AsyncCollectionFixture(string collectionName, ITestResultMessage[] results)
{
"Given features with an async collection fixture"
.x(() => collectionName = "AsyncCollectionFixtureTestFeatures");
"When I run the features"
.x(() => results = this.Run<ITestResultMessage>(
typeof(AsyncCollectionFixtureFeature).GetTypeInfo().Assembly, collectionName));
"Then the collection fixture is initialized, supplied as a constructor to each test class instance, and disposed"
.x(() =>
{
Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result));
Assert.Collection(
typeof(AsyncCollectionFixtureFeature).GetTestEvents(),
@event => Assert.Equal("initialized", @event),
@event => Assert.Equal("disposed", @event));
});
}
[CollectionDefinition("AsyncCollectionFixtureTestFeatures")]
public class AsyncCollectionFixtureTestFeatures : ICollectionFixture<AsyncFixture>
{
}
[Collection("AsyncCollectionFixtureTestFeatures")]
public class ScenarioWithACollectionFixture1
{
private readonly AsyncFixture fixture;
public ScenarioWithACollectionFixture1(AsyncFixture fixture)
{
Assert.NotNull(fixture);
this.fixture = fixture;
}
[Scenario]
public void Scenario1() =>
"Given"
.x(() => this.fixture.Feature1Executed());
}
[Collection("AsyncCollectionFixtureTestFeatures")]
public class ScenarioWithACollectionFixture2
{
private readonly AsyncFixture fixture;
public ScenarioWithACollectionFixture2(AsyncFixture fixture)
{
Assert.NotNull(fixture);
this.fixture = fixture;
}
[Scenario]
public void Scenario1() =>
"Given"
.x(() => this.fixture.Feature2Executed());
}
public sealed class AsyncFixture : IAsyncLifetime
{
private bool feature1Executed;
private bool feature2Executed;
public void Feature1Executed() => this.feature1Executed = true;
public void Feature2Executed() => this.feature2Executed = true;
public Task InitializeAsync()
{
Assert.False(this.feature1Executed);
Assert.False(this.feature2Executed);
typeof(AsyncCollectionFixtureFeature).SaveTestEvent("initialized");
return Task.CompletedTask;
}
public Task DisposeAsync()
{
Assert.True(this.feature1Executed);
Assert.True(this.feature2Executed);
typeof(AsyncCollectionFixtureFeature).SaveTestEvent("disposed");
return Task.CompletedTask;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EasyCooperation.Abstraction.Security
{
public interface IDecryptorOption
{
}
}
|
using System.Data;
using System.Data.SQLite;
using MechanicalObject.Sandbox.TodoWithSQLite.Extensions;
using NUnit.Framework;
namespace MechanicalObject.Sandbox.TodoWithSQLite.Tests
{
[TestFixture]
public class DbCommandExtensionsTest
{
[Test]
public void TestAddParameterWithValue()
{
IDbCommand command = new SQLiteCommand();
Assert.AreEqual(0, command.Parameters.Count);
command.AddParameterWithValue("@id", 1);
Assert.AreEqual(1,command.Parameters.Count);
Assert.AreEqual(1, ((SQLiteParameter)command.Parameters[0]).Value);
Assert.AreEqual("@id", ((SQLiteParameter)command.Parameters[0]).ParameterName);
}
}
}
|
using System;
using Boxters.Application.Interfaces;
using Boxters.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Configuration;
using Npgsql;
namespace Boxters.Persistance
{
public partial class BoxBoxContext : DbContext, IBoxBoxContext
{
public BoxBoxContext()
{
}
public BoxBoxContext(DbContextOptions<BoxBoxContext> options)
: base(options)
{
}
public virtual DbSet<Account> Account { get; set; }
public virtual DbSet<BranchOffice> BranchOffice { get; set; }
public virtual DbSet<Food> Food { get; set; }
public virtual DbSet<FoodType> FoodType { get; set; }
public virtual DbSet<Order> Order { get; set; }
public virtual DbSet<OrderFoodOperation> OrderFoodOperation { get; set; }
public virtual DbSet<OrderState> OrderState { get; set; }
public virtual DbSet<Sale> Sale { get; set; }
public virtual DbSet<SaleFood> SaleFood { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
var databaseUri = new Uri(databaseUrl);
var userInfo = databaseUri.UserInfo.Split(':');
var builder = new NpgsqlConnectionStringBuilder
{
Host = databaseUri.Host,
Port = databaseUri.Port,
Username = userInfo[0],
Password = userInfo[1],
Database = databaseUri.LocalPath.TrimStart('/')
};
optionsBuilder.UseNpgsql(builder.ToString());
// optionsBuilder.UseNpgsql("Host=localhost;Database=BoxBox;Username=postgres;Password=qwertyAhuel");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.HasSequence<int>("Sales_Id_seq");
modelBuilder.ApplyConfigurationsFromAssembly(typeof(BoxBoxContext).Assembly);
}
}
}
|
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets
{
using System.Management.Automation;
/// <summary>
/// <para type="synopsis">Creates a new object which represents a "microsoft.graph.onenote" (or one of its derived types).</para>
/// <para type="description">Creates a new object which represents a "microsoft.graph.onenote" (or one of its derived types).</para>
/// </summary>
[Cmdlet("New", "OnenoteObject", DefaultParameterSetName = @"microsoft.graph.onenote")]
[ODataType("microsoft.graph.onenote")]
public class New_OnenoteObject : ObjectFactoryCmdletBase
{
/// <summary>
/// <para type="description">The "notebooks" property, of type "microsoft.graph.notebook".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.notebook")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "notebooks" property, of type "microsoft.graph.notebook".")]
public System.Object[] notebooks { get; set; }
/// <summary>
/// <para type="description">The "sections" property, of type "microsoft.graph.onenoteSection".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.onenoteSection")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "sections" property, of type "microsoft.graph.onenoteSection".")]
public System.Object[] sections { get; set; }
/// <summary>
/// <para type="description">The "sectionGroups" property, of type "microsoft.graph.sectionGroup".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.sectionGroup")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "sectionGroups" property, of type "microsoft.graph.sectionGroup".")]
public System.Object[] sectionGroups { get; set; }
/// <summary>
/// <para type="description">The "pages" property, of type "microsoft.graph.onenotePage".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.onenotePage")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "pages" property, of type "microsoft.graph.onenotePage".")]
public System.Object[] pages { get; set; }
/// <summary>
/// <para type="description">The "resources" property, of type "microsoft.graph.onenoteResource".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.onenoteResource")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "resources" property, of type "microsoft.graph.onenoteResource".")]
public System.Object[] resources { get; set; }
/// <summary>
/// <para type="description">The "operations" property, of type "microsoft.graph.onenoteOperation".</para>
/// <para type="description">This property is on the "microsoft.graph.onenote" type.</para>
/// </summary>
[ODataType("microsoft.graph.onenoteOperation")]
[Selectable]
[Expandable]
[AllowEmptyCollection]
[Parameter(ParameterSetName = @"microsoft.graph.onenote", HelpMessage = @"The "operations" property, of type "microsoft.graph.onenoteOperation".")]
public System.Object[] operations { get; set; }
}
} |
using ObjCRuntime;
[assembly: LinkWith ("libLottie-tvos.a",
Frameworks = "UIKit",
IsCxx = true,
SmartLink = true,
LinkerFlags="-ObjC",
ForceLoad = true)]
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RC_SpeechToText.Models.DTO.Incoming
{
public class ConvertionDTO
{
public ConvertionDTO(IFormFile audioFile, string userEmail, string description, string title)
{
AudioFile = audioFile;
UserEmail = userEmail;
Description = description;
Title = title;
}
public IFormFile AudioFile { get; set; }
public string UserEmail { get; set; }
public string Description { get; set; }
public string Title { get; set; }
}
}
|
namespace SimpleLogger.Models.Contracts
{
using System;
internal interface ICustomLogger
{
void LogException(Exception ex, string additionalMessage);
void LogMessage(string message);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.DotNet.CodeFormatting
{
internal interface IFormatLogger
{
void Write(string format, params object[] args);
void WriteLine(string format, params object[] args);
void WriteLine();
void WriteErrorLine(string format, params object[] args);
}
/// <summary>
/// This implementation will forward all output directly to the console.
/// </summary>
internal sealed class ConsoleFormatLogger : IFormatLogger
{
public void Write(string format, params object[] args)
{
Console.Write(format, args);
}
public void WriteLine(string format, params object[] args)
{
Console.WriteLine(format, args);
}
public void WriteErrorLine(string format, params object[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Error: ");
Console.WriteLine(format, args);
Console.ResetColor();
}
public void WriteLine()
{
Console.WriteLine();
}
}
/// <summary>
/// This implementation just ignores all output from the formatter. It's useful
/// for unit testing purposes.
/// </summary>
internal sealed class EmptyFormatLogger : IFormatLogger
{
public void Write(string format, params object[] args)
{
}
public void WriteLine(string format, params object[] args)
{
}
public void WriteErrorLine(string format, params object[] argsa)
{
}
public void WriteLine()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchController : MonoBehaviour
{
public GameObject controlButtons;
//public MainMenu isTouchControlOn;
void Update()
{
if(MainMenu.instance.ReturnTouchControl() == true){
controlButtons.SetActive(true);
}
else{
controlButtons.SetActive(false);
}
}
}
|
using System;
using System.Windows.Markup;
namespace Nuclear.Wpf.Data {
/// <summary>
/// Implements a markup extension to declare an inlined object inside XAML markup.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
public class DataExtension<T> : MarkupExtension {
#region properties
/// <summary>
/// Gets the declared object that will be provided.
/// </summary>
public T Value { get; }
#endregion
#region ctors
/// <summary>
/// Creates a new instance of <see cref="DataExtension{T}"/>.
/// </summary>
/// <param name="value">The value that will be provided.</param>
public DataExtension(T value) {
Value = value;
}
#endregion
#region method
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public override Object ProvideValue(IServiceProvider serviceProvider) => Value;
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
#endregion
}
}
|
namespace ModPanel.App.Infrastructure.Validation.Posts
{
using SimpleMvc.Framework.Attributes.Validation;
public class TitleAttribute : PropertyValidationAttribute
{
public override bool IsValid(object value)
{
var title = value as string;
if (title == null)
{
return true;
}
return title.Length >= 3 && title.Length <= 100;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Swarmops.Basic.Types.Financial;
using Swarmops.Database;
using Swarmops.Logic.Support;
namespace Swarmops.Logic.Financial
{
public class HotBitcoinAddressUnspents: PluralBase<HotBitcoinAddressUnspents, HotBitcoinAddressUnspent, BasicHotBitcoinAddressUnspent>
{
static public HotBitcoinAddressUnspents ForAddress (HotBitcoinAddress address)
{
return FromArray (SwarmDb.GetDatabaseForWriting().GetHotBitcoinAddressUnspents (address)); // "ForWriting" is intentional here
}
public Int64 AmountSatoshisTotal
{
get { return this.Sum (item => item.AmountSatoshis); }
}
public BitcoinTransactionInputs AsInputs
{
get
{
BitcoinTransactionInputs result = new BitcoinTransactionInputs();
foreach (HotBitcoinAddressUnspent unspent in this)
{
result.Add (unspent.AsInput);
}
return result;
}
}
public void DeleteAll()
{
Dictionary<int, bool> addressIdLookup = new Dictionary<int, bool>();
this.ForEach (item => addressIdLookup[item.HotBitcoinAddressId] = true);
SwarmDb db = SwarmDb.GetDatabaseForWriting();
// Delete the unspents in this collection
this.ForEach (item => db.DeleteHotBitcoinAddressUnspent (item.Identity));
// Recalculate the amount remaining in the addresses
foreach (int addressId in addressIdLookup.Keys)
{
db.SetHotBitcoinAddressBalance (addressId,
HotBitcoinAddress.FromIdentity (addressId).Unspents.AmountSatoshisTotal);
}
}
}
}
|
using Apocalypse.Any.Domain.Server.Model.Interfaces;
namespace Apocalypse.Any.Infrastructure.Server.PubSub.Interfaces
{
public interface IEventQueue : IGenericTypeDataLayer
{
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="~/assets/img/apple-icon.png" />
<link rel="icon" type="image/png" href="~/assets/img/favicon.png" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>İlan Onay</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<!-- Bootstrap core CSS -->
<link href="~/assets/css/bootstrap.min.css" rel="stylesheet" />
<!-- Material Dashboard CSS -->
<link href="~/assets/css/material-dashboard.css?v=1.2.0" rel="stylesheet" />
<!-- CSS for Demo Purpose, don't include it in your project -->
<link href="~/assets/css/demo.css" rel="stylesheet" />
<!-- Fonts and icons -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700,300|Material+Icons" rel='stylesheet'>
</head>
<body>
@RenderBody()
<div class="wrapper">
@Html.Partial("_SideBar")
<div class="main-panel">
<nav class="navbar navbar-transparent navbar-absolute">
@Html.Partial("_Header")
</nav>
<div class="content">
<div class="container-fluid">
<div class="row">
@foreach(var ilan in @ViewBag.Ilanlar)
{
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="card card-stats">
<div class="card-headerr">
<img src="~/Resources/Images/Default_Emlak.png" alt="Emlak">
</div>
<div class="card-content">
<p class="category">@ilan.FIYAT ₺</p>
<h4 class="title">@ilan.KATEGORI</h4>
<h5 class="title">@ilan.BASLIK</h5>
</div>
<div class="card-footer">
<div class="stats">
<i class="material-icons">date_range</i> @ilan.YAYIN_SURESI
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
@Html.Partial("_Footer")
</div>
</div>
<!-- Core JS Files -->
<script src="~/assets/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="~/assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="~/assets/js/material.min.js" type="text/javascript"></script>
<!-- Charts Plugin -->
<script src="~/assets/js/chartist.min.js"></script>
<!-- Dynamic Elements plugin -->
<script src="~/assets/js/arrive.min.js"></script>
<!-- PerfectScrollbar Library -->
<script src="~/assets/js/perfect-scrollbar.jquery.min.js"></script>
<!-- Notifications Plugin -->
<script src="~/assets/js/bootstrap-notify.js"></script>
<!-- Google Maps Plugin -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
<!-- Material Dashboard javascript methods -->
<script src="~/assets/js/material-dashboard.js?v=1.2.0"></script>
<!-- Material Dashboard DEMO methods, don't include it in your project! -->
<script src="~/assets/js/demo.js"></script>
</body>
</html> |
<footer>
<section class="info">
<article class="contact-us">
<h3>Contact us</h3>
<ul>
<li><span>Address:</span> Sofia, Bulgaria <i class="fas fa-map-marker-alt"></i></li>
<li><span>E-mail:</span> cooking@gmail.com <i class="fas fa-envelope"></i></li>
<li><span>Phone:</span> +395 213 723 <i class="fas fa-phone"></i></li>
<li><span>Work time:</span> 09:00 - 17:30 <i class="far fa-clock"></i></li>
</ul>
</article>
<article class="subscribe">
<h3>Subscribe to The Daily Receipts</h3>
<form id="recipe-subscription" action="#">
<input type="email" name="email" placeholder="Enter Email Address">
<input type="submit" value="Submit">
<p class="subscription-message"></p>
</form>
</article>
<article class="follow-us">
<h3>Follow us</h3>
<div>
<i class="fab fa-facebook-f"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-youtube"></i>
<i class="fab fa-linkedin-in"></i>
</div>
</article>
</section>
<section class="rights">
<p>Copyright © 2018 <span>Cook</span>ing · All Rights Reserved.</p>
</section>
</footer> |
namespace mg.hr.Core
{
/// <summary>
/// DTO to pass to the UI
/// </summary>
public class EmployeeDTO
{
public int id { get; set; }
public string name { get; set; }
public string roleName { get; set; }
public decimal annualSalary { get; set; }
}
}
|
using Rehber.Model.MessageContracts;
using Rehber.Model.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Rehber.Model.DataModels
{
public class Units
{
public Units()
{
InverseParent = new HashSet<Units>();
}
public int UnitId { get; set; }
public string UnitName { get; set; }
public int? ParentId { get; set; }
public Units Parent { get; set; }
public ICollection<Units> InverseParent { get; set; }
}
}
|
namespace Libraries.Providers.Models.FlightAfiliateResponseModel
{
using System;
using IO.Swagger.Model;
public class CarierInfoResponseModel
{
public LogosResponseModel Logos { get; set; }
public string Name { get; set; }
public static Func<CarrierInfo, CarierInfoResponseModel> FromModel
{
get
{
return m => new CarierInfoResponseModel
{
Name = m.Name,
Logos = new LogosResponseModel
{
Medium = m.Logos.Medium,
Small = m.Logos.Small
}
};
}
}
}
}
|
using System.Configuration;
using System.IO;
using System.Reflection;
namespace SeekU.FileIO
{
internal static class FileUtility
{
private static readonly string BaseDirectory;
/// <summary>
/// Finds the base location on disk where events and snapshots should be stored
/// </summary>
static FileUtility()
{
if (ConfigurationManager.AppSettings["SeekU.FileIO.BaseDirectory"] != null)
{
BaseDirectory = ConfigurationManager.AppSettings["SeekU.FileIO.BaseDirectory"];
}
else
{
var codeBase = Assembly.GetExecutingAssembly().Location;
BaseDirectory = Path.GetDirectoryName(codeBase);
}
}
/// <summary>
/// Gets the event directory
/// </summary>
/// <returns>Path to the event directory</returns>
public static string GetEventDirectory()
{
return Path.Combine(BaseDirectory, "Events");
}
/// <summary>
/// Gets the snapshot directory
/// </summary>
/// <returns>Path to the snapshot directory</returns>
public static string GetSnapshotDirectory()
{
return Path.Combine(BaseDirectory, "Snapshots");
}
}
}
|
using System.Collections.Generic;
namespace Yuniql.Core
{
/// <summary>
/// Interface for implementing replacement of tokens in the script using the pattern ${TOKEN_KEY}.
/// Throws exception and fails the migration when some tokens not replaced due to missing token values passed from the client.
/// </summary>
public interface ITokenReplacementService
{
/// <summary>
/// Runs token replacement process.
/// </summary>
/// <param name="tokens">List of token Key/Value pairs.</param>
/// <param name="sqlStatement">Raw SQL statement where tokens maybe present.</param>
/// <returns>SQL statement where tokens are successfully replaced.</returns>
string Replace(List<KeyValuePair<string, string>> tokens, string sqlStatement);
}
} |
using System.Collections.Generic;
namespace Common.Messages
{
public class RespMsg_List<T> : IResponseMessage
{
public List<T> ResultObject { set; get; }
public List<(ServiceStatus ServiceStatus, string Message)> Messages { set; get; }
}
public class RespMsg<T> : IResponseMessage
{
public T ResultObject { set; get; }
public List<(ServiceStatus ServiceStatus, string Message)> Messages { set; get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
namespace Forum.WebApi.Middleware.Extensions
{
public static class FakeRemoteIpAddressMiddlewareExtension
{
public static IApplicationBuilder UseFakeRemoteIpAddressMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<FakeRemoteIpAddressMiddleware>();
}
}
}
|
using Microsoft.AspNetCore.Identity;
using System;
namespace Game_Store.Data.Entities
{
public class ApplicationRole : IdentityRole<Guid>
{
public ApplicationRole()
: this(null)
{
}
public ApplicationRole(string name)
: base(name)
{
Id = Guid.NewGuid();
IsDeleted = false;
}
public bool IsDeleted { get; set; }
}
}
|
using HaloEzAPI.Model.Response.MetaData.HaloWars2.Imaging;
using HaloEzAPI.Model.Response.MetaData.HaloWars2.Views;
namespace HaloEzAPI.Model.Response.MetaData.HaloWars2.Shared
{
public class HW2CSRDisplayInfoItem : HW2ApiItem<HW2CSRDesignationDisplayInfoView>
{
}
} |
using System;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace AntCrypter.Animations
{
class ImageChangeAnimations
{
public static void SelectedItemAnimation(Image CurrentControl)
{
string OldTooltip = CurrentControl.ToolTip.ToString();
string NewToolTip = OldTooltip.Replace("Disabled", "Enabled");
CurrentControl.ToolTip = NewToolTip;
string NewResource = CurrentControl.Source.ToString().Replace(".png","Ready.png");
CurrentControl.Source = new BitmapImage(new Uri(NewResource));
}
public static void DeselectedItemAnimation(Image CurrentControl)
{
string OldToolTip = CurrentControl.ToolTip.ToString();
string NewToolTip = OldToolTip.Replace("Enabled", "Disabled");
CurrentControl.ToolTip = NewToolTip;
string OldResource = CurrentControl.Source.ToString().Replace("Ready.png", ".png");
CurrentControl.Source = new BitmapImage(new Uri(OldResource));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallProvider : MonoBehaviour {
public Ball RegularBall;
public Ball[] BonusBalls;
private ObjectPool RegularBallPool;
private ObjectPool[] BonusBallPools;
void Awake()
{
BonusBallPools = new ObjectPool[ BonusBalls.Length ];
RegularBallPool = ScriptableObject.CreateInstance< ObjectPool> ();
RegularBall.myPool = RegularBallPool;
RegularBallPool.InitPieka (RegularBall, 50);
for (int i = 0; i < BonusBallPools.Length; i++)
{
BonusBallPools [i] = ScriptableObject.CreateInstance<ObjectPool> ();
Ball b = BonusBalls [i];
b.myPool = BonusBallPools [i];
BonusBallPools [i].InitPieka (b, 10);
}
}
[Range(0,1)]
public float bonusProbability = 0.2f;
public Ball ProvideBall()
{
Ball newBall;
float rand = Random.Range (0, 100) / 100f;
if (rand <= bonusProbability)
{
// newBall = (Ball) PiekaController.InstantiatePieka (BonusBalls [Random.Range (0, BonusBalls.Length)]);
newBall = (Ball) BonusBallPools[Random.Range (0, BonusBalls.Length)] .GetNextPieka();
}
else
{
// newBall = (Ball) PiekaController.InstantiatePieka (RegularBall);
newBall = (Ball) RegularBallPool.GetNextPieka();
}
return newBall;
}
}
|
using CommunalPayments.Common.Reports;
namespace CommunalPayments.Common.Interfaces
{
internal abstract class ReportCreator
{
public abstract void Create(Payment payment, BankInfo bank, string appDataPath, out string reportPath);
}
}
|
namespace ClashOfClans.Core.Labels.Interfaces
{
public interface IClashLabel
{
int Id { get; set; }
string Name { get; set; }
LabelBadges Icons { get; set; }
}
}
|
using Microsoft.Azure.Documents;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repsaj.Submerged.Common.SubscriptionSchema
{
public class SubscriptionModel
{
[JsonIgnore]
private List<TankModel> _tanks = new List<TankModel>();
[JsonIgnore]
private List<DeviceModel> _devices = new List<DeviceModel>();
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public SubscriptionPropertiesModel SubscriptionProperties;
public List<TankModel> Tanks { get { return _tanks; } set { _tanks = value; } }
public List<DeviceModel> Devices { get { return _devices; } set { _devices = value; } }
public SubscriptionModel() { }
public static SubscriptionModel BuildSubscription(Guid id, string name, string description, string user)
{
SubscriptionModel model = new SubscriptionModel();
model.SubscriptionProperties = new SubscriptionPropertiesModel()
{
SubscriptionID = id,
Name = name,
Description = description,
User = user,
CreatedTime = DateTime.Now
};
model.Tanks = new List<TankModel>();
model.Devices = new List<DeviceModel>();
return model;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.DotNet.XHarness.CLI.CommandArguments.Android
{
internal enum AndroidArchitecture
{
X86,
X86_64,
Arm64_v8a,
Armeabi_v7a
}
internal static class AndroidArchitectureHelper
{
public static AndroidArchitecture ParseAsAndroidArchitecture(this string target) => target switch
{
"x86" => AndroidArchitecture.X86,
"x86_64" => AndroidArchitecture.X86_64,
"arm64-v8a" => AndroidArchitecture.Arm64_v8a,
"armeabi-v7a" => AndroidArchitecture.Armeabi_v7a,
_ => throw new ArgumentOutOfRangeException(nameof(target))
};
public static string AsString(this AndroidArchitecture arch) => arch switch
{
AndroidArchitecture.X86 => "x86",
AndroidArchitecture.X86_64 => "x86_64",
AndroidArchitecture.Arm64_v8a => "arm64-v8a",
AndroidArchitecture.Armeabi_v7a => "armeabi-v7a",
_ => throw new ArgumentOutOfRangeException(nameof(arch))
};
}
}
|
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hotcakes.Commerce.Content;
using Hotcakes.Modules.Core.Admin.AppCode;
namespace Hotcakes.Modules.Core.Admin.Controls
{
public class BlankBlock : LiteralControl
{
public string bvin { get; set; }
}
partial class ContentColumnEditor : HccUserControl
{
#region Properties
public string ColumnId
{
get { return ViewState["ColumnId"] as string ?? string.Empty; }
set { ViewState["ColumnId"] = value; }
}
#endregion
#region Event Handlers
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
LoadBlockList();
LoadColumn();
}
}
protected void btnNew_Click(object sender, EventArgs e)
{
var column = HccApp.ContentServices.Columns.Find(ColumnId);
if (column != null)
{
var maxSortOrder = column.Blocks.Max(i => (int?) i.SortOrder) ?? 0;
var block = new ContentBlock();
block.ControlName = lstBlocks.SelectedValue;
block.ColumnId = ColumnId;
block.SortOrder = maxSortOrder + 1;
column.Blocks.Add(block);
HccApp.ContentServices.Columns.Update(column);
}
LoadColumn();
}
protected void gvBlocks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var b = (ContentBlock) e.Row.DataItem;
var controlFound = false;
var cell = e.Row.Cells[1];
e.Row.Attributes["id"] = b.Bvin;
// Control name gets spaces replaced for backwards compatibility
var viewControl = HccPartController.LoadContentBlockAdminView(b.ControlName.Replace(" ", string.Empty), Page);
if (viewControl == null)
{
//No admin view, try standard view
// Block views are now MVC partial so we need a way to render them here
// There are some tricks but since this page will eventually go MVC itself
// we'll just put in placeholders for now.
//viewControl = HccPartController.LoadContentBlock(b.ControlName, Page);
viewControl = new BlankBlock {bvin = b.Bvin, Text = "<div>Block: " + b.ControlName + "</div>"};
}
if (viewControl is HccContentBlockPart || viewControl is BlankBlock)
{
if (viewControl is HccContentBlockPart)
{
((HccContentBlockPart) viewControl).BlockId = b.Bvin;
}
controlFound = true;
cell.Controls.Add(viewControl);
}
if (controlFound)
{
// Check for Editor
var lnkEdit = (HyperLink) e.Row.FindControl("lnkEdit");
if (lnkEdit != null)
{
lnkEdit.Visible = EditorExists(b.ControlName);
}
}
else
{
cell.Controls.Add(new LiteralControl("Control " + b.ControlName + "could not be located"));
}
}
}
protected void gvBlocks_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var bvin = e.Keys[0].ToString();
HccApp.ContentServices.Columns.DeleteBlock(bvin);
LoadColumn();
}
#endregion
#region Implementation
private void LoadBlockList()
{
lstBlocks.DataSource = HccPartController.FindContentBlocks();
lstBlocks.DataBind();
}
public void LoadColumn()
{
var c = HccApp.ContentServices.Columns.Find(ColumnId);
lblTitle.Text = c.DisplayName;
gvBlocks.DataSource = c.Blocks;
gvBlocks.DataBind();
}
private bool EditorExists(string controlName)
{
var result = false;
Control editorControl;
editorControl = HccPartController.LoadContentBlockEditor(controlName.Replace(" ", string.Empty), Page);
if (editorControl != null)
{
if (editorControl is HccPart)
{
result = true;
}
}
return result;
}
#endregion
}
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
namespace AutoCrane.Models
{
public sealed class DataRepositorySource
{
public DataRepositorySource(string archiveFilePath, string hash, DateTimeOffset timestamp)
{
this.ArchiveFilePath = archiveFilePath;
this.Hash = hash;
this.Timestamp = timestamp;
}
public string ArchiveFilePath { get; set; }
public string Hash { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace BoardViewApplication.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
var client = new HttpClient();
var response = client.GetAsync("https://cards.floul.dev/api/v2.0/NewPlayer").Result;
var asd1 = response.Content.ReadAsStringAsync().Result;
var results = JsonConvert.DeserializeObject<List<Root>>(asd1);
asd = results;
}
public void OnGet()
{
}
public List<Root> asd;
}
public class Root
{
public int id { get; set; }
public string userName { get; set; }
public string realName { get; set; }
public double currentPosition { get; set; }
public double potentialPosition { get; set; }
public bool hideFromView { get; set; }
}
} |
/* see LICENSE notice in solution root */
using System;
using System.Collections.Generic;
using System.Text;
namespace VisualSquirrel.Debugger.Engine
{
public static class EngineConstants
{
public static readonly uint FACILITY_WIN32 = 7;
public static readonly uint ERROR_INVALID_NAME = 123;
public static readonly uint ERROR_ALREADY_INITIALIZED = 1247;
static uint HRESULT_FROM_WIN32(long x) {
return (uint)((x) <= 0 ? (x) : (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000));
}
public static readonly int S_OK = 0;
public static readonly int S_FALSE = 1;
public static readonly int E_NOTIMPL = unchecked((int)0x80004001);
public static readonly int E_FAIL = unchecked((int)0x80004005);
public static readonly int E_WIN32_INVALID_NAME = (int)HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
public static readonly int E_WIN32_ALREADY_INITIALIZED = (int)HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
public static readonly int RPC_E_SERVERFAULT = unchecked((int)0x80010105);
}
};
|
namespace PaymentGateway.Model.Entity
{
public class Phone
{
/// <summary>
/// Class constructor, requires all mandatory fields.
/// </summary>
public Phone(int type, int areaCode, int number)
{
Type = type;
AreaCode = areaCode;
Number = number;
}
/// <summary>
/// Sets the optional fields
/// </summary>
public void SetOptionalFields(int countryCode)
{
CountryCode = countryCode;
}
public int Type { get; set; }
public int AreaCode { get; set; }
public int Number { get; set; }
public int CountryCode { get; set; }
/// <summary>
/// Equality implementation.
/// </summary>
/// <param name="other">Other phone instance</param>
public bool Equals(Phone other)
{
return Type == other.Type
&& AreaCode == other.AreaCode
&& Number == other.Number
&& CountryCode == other.CountryCode;
}
} //class
} //namespace
|
using UnityEngine;
using Cuvium.Core;
using Cuvium.Behaviours;
namespace Cuvium.Commands
{
[CreateAssetMenu(menuName = "Cuvium/Move Command")]
public class MoveScriptableCommand : ScriptableCommand
{
private void OnEnable()
{
Name = "Move";
}
public override void Execute(CommandContext context, CuviumController controller)
{
var middle = context.Player.SelectedObjects.GetMiddlePoint();
Debug.Log("Middle: " + middle);
var destination = context.Target.Hit.point;
Debug.Log("Destination: " + destination);
var offset = controller.transform.position - middle;
var moveable = controller as IMoveable;
moveable.Move(destination + offset);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedisp
{
class RdpedispClient
{
bool forceRestriction = false; // Restriction in MS-RDPEDISP section 2.2.2.2.1 is forced or not
const uint FixedMonitorLayoutSize = 40; // Size of DISPLAYCONTROL_MONITOR_LAYOUT is fixed to 40
const String RdpedispChannelName = "Microsoft::Windows::RDS::DisplayControl";
const uint MinMonitorSize = 200;
const uint MaxMonitorSize = 8192;
private RdpedycClient rdpedycClient;
private DynamicVirtualChannel RdpedispDVC;
private List<RdpedispPdu> receivedList;
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="rdpedycClient"></param>
public RdpedispClient(RdpedycClient rdpedycClient)
{
this.rdpedycClient = rdpedycClient;
receivedList = new List<RdpedispPdu>();
}
#endregion Constructor
/// <summary>
/// Wait for creation of dynamic virtual channel for RDPEDISP
/// </summary>
/// <param name="timeout"></param>
/// <param name="transportType"></param>
/// <returns></returns>
public bool WaitForRdpedispDvcCreation(TimeSpan timeout, DynamicVC_TransportType transportType = DynamicVC_TransportType.RDP_TCP)
{
try
{
RdpedispDVC = rdpedycClient.ExpectChannel(timeout, RdpedispChannelName, transportType);
}
catch
{
}
if (RdpedispDVC != null)
{
return true;
}
return false;
}
/// <summary>
/// Clear ReceiveList
/// </summary>
public void ClearReceivedList()
{
if (this.receivedList != null)
{
this.receivedList.Clear();
}
}
#region Send/Receive Methods
/// <summary>
/// Send a RDPEDISP Pdu
/// </summary>
/// <param name="pdu"></param>
public void SendRdpedispPdu(RdpedispPdu pdu)
{
byte[] data = PduMarshaler.Marshal(pdu);
if (RdpedispDVC == null)
{
throw new InvalidOperationException("DVC instance of RDPEDISP is null, Dynamic virtual channel must be created before sending data.");
}
RdpedispDVC.Send(data);
}
/// <summary>
/// Method to expect a RdpedispPdu.
/// </summary>
/// <param name="timeout">Timeout</param>
public T ExpectRdpedispPdu<T>(TimeSpan timeout) where T : RdpedispPdu
{
DateTime endTime = DateTime.Now + timeout;
while (endTime > DateTime.Now)
{
if (receivedList.Count > 0)
{
lock (receivedList)
{
foreach (RdpedispPdu pdu in receivedList)
{
T response = pdu as T;
if (response != null)
{
receivedList.Remove(pdu);
return response;
}
}
}
}
System.Threading.Thread.Sleep(100);
}
return null;
}
#endregion Send/Receive Methods
#region Create Methods
/// <summary>
/// Method to create DISPLAYCONTROL_MONITOR_LAYOUT structure
/// </summary>
/// <param name="flags">A 32-bit unsigned integer that specifies monitor configuration flags.</param>
/// <param name="left">A 32-bit signed integer that specifies the x-coordinate of the upper-left corner of the display monitor.</param>
/// <param name="top">A 32-bit signed integer that specifies the y-coordinate of the upper-left corner of the display monitor.</param>
/// <param name="width">A 32-bit unsigned integer that specifies the width of the monitor in pixels. </param>
/// <param name="height">A 32-bit unsigned integer that specifies the height of the monitor in pixels. </param>
/// <param name="physicalWidth">A 32-bit unsigned integer that specifies the physical width of the monitor, in millimeters (mm).</param>
/// <param name="physicalHeight">A 32-bit unsigned integer that specifies the physical height of the monitor, in millimeters.</param>
/// <param name="orientation">A 32-bit unsigned integer that specifies the orientation of the monitor in degrees.</param>
/// <param name="desktopScaleFactor">A 32-bit, unsigned integer that specifies the desktop scale factor of the monitor.</param>
/// <param name="deviceScaleFactor">A 32-bit, unsigned integer that specifies the device scale factor of the monitor. </param>
/// <returns></returns>
public DISPLAYCONTROL_MONITOR_LAYOUT createMonitorLayout(
MonitorLayout_FlagValues flags,
int left,
int top,
uint width,
uint height,
uint physicalWidth,
uint physicalHeight,
MonitorLayout_OrientationValues orientation,
uint desktopScaleFactor,
uint deviceScaleFactor)
{
DISPLAYCONTROL_MONITOR_LAYOUT monitorLayout = new DISPLAYCONTROL_MONITOR_LAYOUT();
monitorLayout.Flags = flags;
monitorLayout.Left = left;
monitorLayout.Top = top;
if (forceRestriction && width >= MinMonitorSize && width <= MaxMonitorSize && width % 2 == 0)
{
monitorLayout.Width = width;
}
else
{
return null;
}
if (forceRestriction && height >= MinMonitorSize && height <= MaxMonitorSize)
{
monitorLayout.Height = height;
}
else
{
return null;
}
monitorLayout.PhysicalWidth = physicalWidth;
monitorLayout.PhysicalHeight = physicalHeight;
monitorLayout.Orientation = orientation;
monitorLayout.DesktopScaleFactor = desktopScaleFactor;
monitorLayout.DeviceScaleFactor = desktopScaleFactor;
return monitorLayout;
}
/// <summary>
/// Method to create DISPLAYCONTROL_MONITOR_LAYOUT_PDU structure
/// </summary>
/// <param name="monitors">Array of monitors</param>
/// <returns></returns>
public DISPLAYCONTROL_MONITOR_LAYOUT_PDU createMonitorLayoutPDU(DISPLAYCONTROL_MONITOR_LAYOUT[] monitors){
DISPLAYCONTROL_MONITOR_LAYOUT_PDU monitorLayoutPDU = new DISPLAYCONTROL_MONITOR_LAYOUT_PDU();
monitorLayoutPDU.Header.Type = PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_MONITOR_LAYOUT;
if (null == monitors || monitors.Length == 0)
{
monitorLayoutPDU.Header.Length = 16;
monitorLayoutPDU.MonitorLayoutSize = FixedMonitorLayoutSize;
// TODO: illegal NumMonitors?
monitorLayoutPDU.NumMonitors = 0;
return monitorLayoutPDU;
}else{
monitorLayoutPDU.Header.Length = 16 + FixedMonitorLayoutSize * (uint) monitors.Length;
monitorLayoutPDU.MonitorLayoutSize = FixedMonitorLayoutSize;
monitorLayoutPDU.NumMonitors = (uint) monitors.Length;
// TODO: illegal NumMonitors?
monitorLayoutPDU.Monitors = monitors;
return monitorLayoutPDU;
}
}
#endregion Create Methods
#region Private Methods
/// <summary>
/// The callback method to receive data from transport layer.
/// </summary>
private void OnDataReceived(byte[] data, uint channelID)
{
lock (receivedList)
{
RdpedispPdu basePDU = new RdpedispPdu();
bool fSucceed = false;
bool fResult = PduMarshaler.Unmarshal(data, basePDU);
if (fResult)
{
byte[] pduData = new byte[basePDU.Header.Length];
Array.Copy(data, pduData, basePDU.Header.Length);
if (basePDU.Header.Type == PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_CAPS)
{
DISPLAYCONTROL_CAPS_PDU capsPDU = new DISPLAYCONTROL_CAPS_PDU();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, capsPDU);
receivedList.Add(capsPDU);
}
catch (PDUDecodeException decodeException)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeException.DecodingData, unkonw);
receivedList.Add(unkonw);
}
}
else if (basePDU.Header.Type == PDUTypeValues.DISPLAYCONTROL_PDU_TYPE_MONITOR_LAYOUT)
{
DISPLAYCONTROL_MONITOR_LAYOUT_PDU monitorLayoutPDU = new DISPLAYCONTROL_MONITOR_LAYOUT_PDU();
try
{
fSucceed = PduMarshaler.Unmarshal(pduData, monitorLayoutPDU);
receivedList.Add(monitorLayoutPDU);
}
catch (PDUDecodeException decodeException)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(decodeException.DecodingData, unkonw);
receivedList.Add(unkonw);
}
}
else
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(pduData, unkonw);
receivedList.Add(unkonw);
}
}
if (!fSucceed || !fResult)
{
RdpedispUnkownPdu unkonw = new RdpedispUnkownPdu();
fSucceed = PduMarshaler.Unmarshal(data, unkonw);
receivedList.Add(unkonw);
}
}
}
#endregion Private Methods
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RequisicaoAX.Dynamics.Model
{
public class PurchReqLine
{
public decimal LINENUM { get; set; }
public string ITEMID { get; set; }
public string INVENTDIMID { get; set; }
public string NAME { get; set; }
public int LINETYPE { get; set; }
public decimal PURCHQTY { get; set; }
public decimal PURCHPRICE { get; set; }
public string CURRENCYCODE { get; set; }
public string VENDACCOUNT { get; set; }
public string URL { get; set; }
public string PURCHRFQCASEID { get; set; }
public DateTime REQUIREDDATE { get; set; }
public decimal LINEAMOUNT { get; set; }
public string DELIVERYNAME { get; set; }
public long ADDRESSREFRECID { get; set; }
public int ADDRESSREFTABLEID { get; set; }
public string ATTENTION { get; set; }
public decimal LINEDISC { get; set; }
public decimal LINEPERCENT { get; set; }
public decimal PRICEUNIT { get; set; }
public decimal PURCHMARKUP { get; set; }
public string TAXGROUP { get; set; }
public string TAXITEMGROUP { get; set; }
public int PURCHLINECREATED { get; set; }
public Guid LINEREFID { get; set; }
public string PURCHID { get; set; }
public string PROJID { get; set; }
public string PROJCATEGORYID { get; set; }
public string ACTIVITYNUMBER { get; set; }
public string PROJLINEPROPERTYID { get; set; }
public int LINECOMPLETE { get; set; }
public string PROJSALESCURRENCYID { get; set; }
public decimal PROJSALESPRICE { get; set; }
public string PROJTAXGROUPID { get; set; }
public string PROJTAXITEMGROUPID { get; set; }
public string PROJTRANSID { get; set; }
public string EXTERNALITEMID { get; set; }
public int ISSAVED { get; set; }
public int SEQUENCENUMBER { get; set; }
public DateTime TRANSDATE { get; set; }
public int PURCHREQCONSOLIDATIONSTATUS { get; set; }
public string VENDQUOTENUMBER { get; set; }
public long PROCUREMENTCATEGORY { get; set; }
public string INVENTLOCATIONID { get; set; }
public string ASSETGROUP { get; set; }
public long REASONREFRECID { get; set; }
public long BUSINESSJUSTIFICATION { get; set; }
public long SOURCEDOCUMENTLINE { get; set; }
public long DEFAULTDIMENSION { get; set; }
public long RECEIVINGOPERATINGUNIT { get; set; }
public long PURCHREQTABLE { get; set; }
public long BUYINGLEGALENTITY { get; set; }
public string ASSETGROUPDATAAREA { get; set; }
public string INVENTDIMIDDATAAREA { get; set; }
public string INVENTLOCATIONIDDATAAREA { get; set; }
public string ITEMIDDATAAREA { get; set; }
public string PROJCATEGORYIDDATAAREA { get; set; }
public string PROJTRANSIDDATAAREA { get; set; }
public string PROJLINEPROPERTYIDDATAAREA { get; set; }
public string PROJIDDATAAREA { get; set; }
public string PROJTAXGROUPIDDATAAREA { get; set; }
public string PROJTAXITEMGROUPIDDATAAREA { get; set; }
public string PURCHRFQCASEIDDATAAREA { get; set; }
public string PURCHIDDATAAREA { get; set; }
public string ACTIVITYNUMBERDATAAREA { get; set; }
public string TAXGROUPDATAAREA { get; set; }
public string VENDACCOUNTDATAAREA { get; set; }
public string TAXITEMGROUPDATAAREA { get; set; }
public int ISPREPAYMENT { get; set; }
public string PREPAYMENTDETAILS { get; set; }
public long PURCHAGREEMENT { get; set; }
public int RFQREQUIREMENT { get; set; }
public long REQUISITIONER { get; set; }
public long ASSETRULEQUALIFIEROPTION { get; set; }
public long ASSETRULEQUALIFIEROPTIONLOCAL { get; set; }
public string ITEMIDNONCATALOG { get; set; }
public int ISMODIFIED { get; set; }
public long ACCOUNTINGDISTRIBUTIONTEMPLATE { get; set; }
public long DELIVERYPOSTALADDRESS { get; set; }
public int REQUISITIONSTATUS { get; set; }
public int ISPREENCUMBRANCEREQUIRED { get; set; }
public long PURCHUNITOFMEASURE { get; set; }
public long PROJSALESUNITOFMEASURE { get; set; }
public int ISPURCHASEORDERGENERATIONMANUAL { get; set; }
public string TAXSERVICECODE_BR { get; set; }
public decimal MAXIMUMRETAILPRICE_IN { get; set; }
public int EXCISERECORDTYPE_IN { get; set; }
public decimal NONRECOVERABLEPERCENT_IN { get; set; }
public int GTASERVICECATEGORY_IN { get; set; }
public int EXCISETYPE_IN { get; set; }
public int VATGOODSTYPE_IN { get; set; }
public long COMPANYLOCATION_IN { get; set; }
public long SERVICECODETABLE_IN { get; set; }
public long EXCISETARIFFCODES_IN { get; set; }
public long CUSTOMSTARIFFCODETABLE_IN { get; set; }
public long SALESTAXFORMTYPES_IN { get; set; }
public long VENDORLOCATION_IN { get; set; }
public long CFOPTABLE_BR { get; set; }
public long CFPSTABLE_BR { get; set; }
public int DSA_IN { get; set; }
public int PRICEDISCOUNTTRANSFER { get; set; }
public int REQUISITIONPURPOSE { get; set; }
public long SALESPURCHOPERATIONTYPE_BR { get; set; }
public DateTime CREATEDDATETIME { get; set; }
public string CREATEDBY { get; set; }
public int RECVERSION { get; set; }
public long PARTITION { get; set; }
public long RECID { get; set; }
public long BUDGETRESERVATIONLINE_PSN { get; set; }
public PurchReqTable PurchreqTable { get; set; }
}
}
|
/**************************************************************************************
PdfPage
=======
Stores fonts and content tokens of a pdf page.
Written in 2021 by Jürgpeter Huber, Singapore
Contact: https://github.com/PeterHuberSg/PdfParser
To the extent possible under law, the author(s) have dedicated all copyright and
related and neighboring rights to this software to the public domain worldwide under
the Creative Commons 0 1.0 Universal license.
To view a copy of this license, read the file CopyRight.md or visit
http://creativecommons.org/publicdomain/zero/1.0
This software is distributed without any warranty.
**************************************************************************************/
using System;
using System.Collections.Generic;
namespace PdfParserLib {
public class PdfPage {
public IReadOnlyDictionary<string, PdfFont> Fonts => fonts;
readonly Dictionary<string, PdfFont> fonts = new Dictionary<string, PdfFont>();
public IReadOnlyList<PdfContent> Contents => contents;
readonly List<PdfContent> contents = new List<PdfContent>();
public readonly string? Exception;
public PdfPage(Tokeniser tokeniser, DictionaryToken pageToken) {
pageToken.PdfObject = this;
try {
if (pageToken.TryGetDictionary("Resources", out var resourcesDictionaryToken)) {
if (resourcesDictionaryToken.TryGetDictionary("Font", out var fontsDictionaryToken)) {
foreach (var fontName_Token in fontsDictionaryToken) {
if (fontName_Token.Value.PdfObject!=null) {
var pdfFont = (PdfFont) fontName_Token.Value.PdfObject;
fonts.Add(fontName_Token.Key, pdfFont);
} else {
fonts.Add(fontName_Token.Key, new PdfFont(fontName_Token.Value));
}
}
}
}
if (pageToken.TryGetValue("Contents", out var contentsToken)) {
if (contentsToken is ArrayToken contentsArrayToken) {
foreach (var contentToken in contentsArrayToken) {
contents.Add(new PdfContent((DictionaryToken)contentToken, Fonts));
}
} else if (contentsToken is DictionaryToken contentsDictionaryToken) {
contents.Add(new PdfContent(contentsDictionaryToken, Fonts));
} else {
throw new NotSupportedException();
}
}
} catch (Exception ex) {
if (Exception is null) {
Exception = "";
} else {
Exception += Environment.NewLine + Environment.NewLine;
}
if (ex is PdfStreamException || ex is PdfException) {
Exception = ex.ToDetailString();
} else {
Exception = ex.ToDetailString() + Environment.NewLine + tokeniser.ShowStreamContentAtIndex();
}
}
}
}
}
|
using MyNetworkLibrary;
using System;
using System.Collections.Generic;
using System.Text;
namespace ChatServer
{
class Program
{
static void Main()
{
Console.WriteLine("ChatServer started on port " + Settings.Port);
server = new Server();
server.ClientConnected += endPoint =>
Console.WriteLine("Client connected: " + endPoint);
server.ClientDisconnected += endPoint =>
Console.WriteLine("Client disconnected: " + endPoint);
server.ClientMessageReceived += ChatReceived;
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
static Server server;
private static void ChatReceived(Client client, Message message)
{
var text = new ChatMessage
{
Text = "Client " + client.EndPoint + ": " + ((ChatMessage)message).Text
};
Console.WriteLine(text.Text);
foreach (var other in server.clients)
if (other != client)
other.Send(text);
}
}
} |
namespace Endjin.Licensing.Specs.LicenseValidation
{
#region Using Directives
using System;
using System.Collections.Generic;
using Endjin.Licensing.Contracts.Crypto;
using Endjin.Licensing.Contracts.Validation;
using Endjin.Licensing.Domain;
using Endjin.Licensing.Exceptions;
using Endjin.Licensing.Extensions;
using Endjin.Licensing.Infrastructure.Contracts.Crypto;
using Endjin.Licensing.Infrastructure.Contracts.Generators;
using Endjin.Licensing.Infrastructure.Crypto;
using Endjin.Licensing.Infrastructure.Generators;
using Endjin.Licensing.Specs.Extensions;
using Endjin.Licensing.Specs.Shared;
using Endjin.Licensing.Validation;
using Endjin.Licensing.Validation.Rules;
using Should;
using TechTalk.SpecFlow;
#endregion
[Binding]
public class ValidateLicenseSteps
{
private readonly IServerLicenseGenerator serverLicenseGenerator;
private readonly IPrivateKeyProvider privateKeyProvider;
private readonly ILicenseValidator licenseValidator;
public ValidateLicenseSteps()
{
this.serverLicenseGenerator = new ServerLicenseGenerator();
this.privateKeyProvider = new RsaPrivateKeyProvider();
this.licenseValidator = new LicenseValidator();
}
[Given(@"they want a '(.*)' license")]
public void GivenTheyWantALicense(string licenseType)
{
ScenarioContext.Current.Set(licenseType, ContextKey.LicenseType);
}
[Given(@"their license was issued today")]
public void GivenTheirLicenseWasIssuedToday()
{
ScenarioContext.Current.Set(DateTimeOffset.UtcNow, ContextKey.LicenseIssueDate);
}
[Given(@"their license was issued a month ago")]
public void GivenTheirLicenseWasIssuedAMonthAgo()
{
ScenarioContext.Current.Set(DateTimeOffset.UtcNow.AddMonths(-1), ContextKey.LicenseIssueDate);
}
[Given(@"I generate their license")]
public void GivenIGenerateTheirLicense()
{
var subscriptionStartDate = ScenarioContext.Current.Get<DateTimeOffset>(ContextKey.LicenseIssueDate);
var licenseType = ScenarioContext.Current.Get<string>(ContextKey.LicenseType);
Dictionary<string, string> metadata;
if (!ScenarioContext.Current.TryGetValue(ContextKey.LicenseMetadata, out metadata))
{
metadata = new Dictionary<string, string>();
}
var licenseCriteria = new LicenseCriteria
{
ExpirationDate = subscriptionStartDate.LastDayOfMonth().EndOfDay(),
IssueDate = subscriptionStartDate,
Id = Guid.NewGuid(),
MetaData = metadata,
Type = licenseType
};
var privateKey = this.privateKeyProvider.Create();
var serverLicense = this.serverLicenseGenerator.Generate(privateKey, licenseCriteria);
var clientLicense = serverLicense.ToClientLicense();
ScenarioContext.Current.Set(serverLicense, ContextKey.ServerLicense);
ScenarioContext.Current.Set(privateKey.ExtractPublicKey(), ContextKey.PublicKey);
ScenarioContext.Current.Set(clientLicense, ContextKey.ClientLicense);
}
[Given(@"the user tampers with the expiration date of the license")]
public void GivenTheUserTampersWithTheExpirationDateOfTheLicense()
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
clientLicense.Content = clientLicense.Tamper(LicenseElements.ExpirationDate, DateTimeOffset.MaxValue.ToString("o"));
}
[Given(@"the user tampers with the issue date of the license")]
public void GivenTheUserTampersWithTheIssueDateOfTheLicense()
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
clientLicense.Content = clientLicense.Tamper(LicenseElements.IssueDate, DateTimeOffset.MinValue.ToString("o"));
}
[Given(@"the user tampers with the type of the license")]
public void GivenTheUserTampersWithTheTypeOfTheLicense()
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
clientLicense.Content = clientLicense.Tamper(LicenseElements.Type, "Enterprise");
}
[Given(@"the user tampers with the ID of the license")]
public void GivenTheUserTampersWithTheIDOfTheLicense()
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
clientLicense.Content = clientLicense.Tamper(LicenseElements.Id, Guid.NewGuid().ToString());
}
[Given(@"the user is issued with a valid '(.*)' license")]
public void GivenTheUserIsIssuedWithAValidLicense(string licenseType)
{
this.GivenTheyWantALicense(licenseType);
this.GivenTheirLicenseWasIssuedToday();
this.GivenIGenerateTheirLicense();
}
[Given(@"their username is '(.*)'")]
public void GivenTheirUsernameIs(string username)
{
Dictionary<string, string> metadata;
if (!ScenarioContext.Current.TryGetValue(ContextKey.LicenseMetadata, out metadata))
{
metadata = new Dictionary<string, string>();
}
metadata.Add("Username", username);
ScenarioContext.Current.Set(metadata, ContextKey.LicenseMetadata);
}
[Given(@"their email address is '(.*)'")]
public void GivenTheirEmailAddressIs(string emailAddress)
{
Dictionary<string, string> metadata;
if (!ScenarioContext.Current.TryGetValue(ContextKey.LicenseMetadata, out metadata))
{
metadata = new Dictionary<string, string>();
}
metadata.Add("EmailAddress", emailAddress);
ScenarioContext.Current.Set(metadata, ContextKey.LicenseMetadata);
}
[Given(@"the user tampers with the username of the license and sets it to ""(.*)""")]
public void GivenTheUserTampersWithTheUsernameOfTheLicenseAndSetsItTo(string newValue)
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
clientLicense.Content = clientLicense.Tamper("Username", newValue);
}
[When(@"they validate their license")]
public void WhenTheyValidateTheirLicense()
{
var clientLicense = ScenarioContext.Current.Get<ClientLicense>(ContextKey.ClientLicense);
var publicKey = ScenarioContext.Current.Get<ICryptoKey>(ContextKey.PublicKey);
try
{
this.licenseValidator.Validate(clientLicense, publicKey, new List<ILicenseValidationRule> { new LicenseHasNotExpiredRule() });
}
catch (Exception ex)
{
ScenarioContext.Current.Set(ex.GetBaseException(), ContextKey.LicenseValidatorException);
}
ScenarioContext.Current.Set(this.licenseValidator.LicenseCriteria, ContextKey.ClientLicenseCriteria);
}
[Then(@"it should be a valid license")]
public void ThenItShouldBeAValidLicense()
{
Exception exception;
ScenarioContext.Current.TryGetValue(ContextKey.LicenseValidatorException, out exception);
exception.ShouldBeNull();
}
[Then(@"it should have been issued today")]
public void ThenItShouldHaveBeenIssuedToday()
{
var clientLicenseCriteria = ScenarioContext.Current.Get<LicenseCriteria>(ContextKey.ClientLicenseCriteria);
clientLicenseCriteria.IssueDate.Date.ShouldEqual(DateTimeOffset.UtcNow.Date);
}
[Then(@"it should have been issued last month")]
public void ThenItShouldHaveBeenIssuedLastMonth()
{
var clientLicenseCriteria = ScenarioContext.Current.Get<LicenseCriteria>(ContextKey.ClientLicenseCriteria);
clientLicenseCriteria.IssueDate.Date.ShouldEqual(DateTimeOffset.UtcNow.AddMonths(-1).Date);
}
[Then(@"it should expire on the last day of this month")]
public void ThenItShouldExpireOnTheLastDayOfThisMonth()
{
var clientLicenseCriteria = ScenarioContext.Current.Get<LicenseCriteria>(ContextKey.ClientLicenseCriteria);
clientLicenseCriteria.ExpirationDate.ShouldEqual(DateTimeOffset.UtcNow.LastDayOfMonth().EndOfDay());
}
[Then(@"it should be an invalid license")]
public void ThenItShouldBeAnInvalidLicense()
{
var exception = ScenarioContext.Current.Get<Exception>(ContextKey.LicenseValidatorException);
exception.ShouldNotBeNull();
exception.ShouldBeType<InvalidLicenseException>();
}
[Then(@"it should be an expired license")]
public void ThenItShouldBeAnExpiredLicense()
{
var exception = ScenarioContext.Current.Get<Exception>(ContextKey.LicenseValidatorException);
exception.ShouldNotBeNull();
exception.ShouldBeType<LicenseExpiredException>();
}
[Then(@"the license should have expired on the last day of last month")]
public void ThenTheLicenseShouldHaveExpiredOnTheLastDayOfLastMonth()
{
var exception = ScenarioContext.Current.Get<Exception>(ContextKey.LicenseValidatorException);
var licenseExpiredException = exception as LicenseExpiredException;
licenseExpiredException.ShouldNotBeNull();
licenseExpiredException.LicenseCriteria.ExpirationDate.ShouldEqual(DateTimeOffset.UtcNow.AddMonths(-1).LastDayOfMonth().EndOfDay());
}
}
} |
namespace Cake.Core.IO.Globbing.Nodes
{
internal abstract class MatchableNode : GlobNode
{
public abstract bool IsMatch(string value);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using SpacyDotNet;
namespace Test
{
static class DisplaCy
{
public static void Run()
{
var spacy = new Spacy();
var nlp = spacy.Load("en_core_web_sm");
var doc = nlp.GetDocument("Apple is looking at buying U.K. startup for $1 billion");
var displacy = new Displacy();
displacy.Serve(doc, "dep");
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace MBaske.Sensors.Grid
{
/// <summary>
/// A <see cref="DetectionResult"/> is generated by an
/// <see cref="IDetector"/> and encoded by an <see cref="IEncoder"/>.
/// </summary>
public class DetectionResult
{
/// <summary>
/// Wrapper for a <see cref="IDetectable"/> object and its
/// associated normalized points list.
/// Note that this refers to any object implementing
/// <see cref="IDetectable"/>. It is not to be confused
/// with <see cref="DetectableGameObject"/> which is a
/// specific implementation of <see cref="IDetectable"/>.
/// </summary>
public class Item
{
/// <summary>
/// Detectable object.
/// </summary>
public IDetectable Detectable;
/// <summary>
/// List of normalized points, 0/0/0 to 1/1/1.
/// Will be converted to grid positions by <see cref="IEncoder"/>.
/// </summary>
public List<Vector3> NormPoints = new List<Vector3>();
/// <summary>
/// Whether this <see cref="Item"/> contains any points.
/// </summary>
public bool HasPoints => NormPoints.Count > 0;
}
/// <summary>
/// List of detectable tags.
/// </summary>
public IList<string> DetectableTags { get; private set; }
private readonly Stack<Item> m_ItemPool;
private readonly IList<IDetectable> m_Detectables;
private readonly IDictionary<string, IList<Item>> m_ItemsByTag;
/// <summary>
/// Creates a <see cref="DetectionResult"/> instance.
/// </summary>
/// <param name="detectableTags">List of detectable tags</param>
/// <param name="initCapacity">Initial capacity</param>
public DetectionResult(IList<string> detectableTags, int initCapacity)
{
DetectableTags = new List<string>(detectableTags);
int n = DetectableTags.Count;
m_Detectables = new List<IDetectable>(initCapacity);
m_ItemsByTag = new Dictionary<string, IList<Item>>(n);
m_ItemPool = new Stack<Item>(initCapacity);
for (int i = 0; i < n; i++)
{
m_ItemsByTag.Add(DetectableTags[i], new List<Item>(initCapacity));
}
}
/// <summary>
/// Clears the <see cref="DetectionResult"/>.
/// </summary>
public void Clear()
{
m_Detectables.Clear();
foreach (var list in m_ItemsByTag.Values)
{
foreach (var item in list)
{
item.NormPoints.Clear();
m_ItemPool.Push(item);
}
list.Clear();
}
}
/// <summary>
/// Adds an <see cref="IDetectable"/> and its associated normalized points.
/// </summary>
/// <param name="detectable">Detectable object</param>
/// <param name="normPoints">Normalized points list</param>
public void Add(IDetectable detectable, IList<Vector3> normPoints)
{
Item item = m_ItemPool.Count > 0 ? m_ItemPool.Pop() : new Item();
item.Detectable = detectable;
item.NormPoints.AddRange(normPoints);
m_ItemsByTag[detectable.Tag].Add(item);
m_Detectables.Add(detectable);
}
/// <summary>
/// Tries to retrieve <see cref="Item"/> instances associated
/// with a specific tag.
/// </summary>
/// <param name="tag">The specified tag</param>
/// <param name="items">List of items (output)</param>
/// <returns>Whether any items were found</returns>
public bool TryGetItems(string tag, out IList<Item> items)
{
if (m_ItemsByTag.TryGetValue(tag, out items) && items.Count > 0)
{
return true;
}
items = null;
return false;
}
/// <summary>
/// Whether the <see cref="DetectionResult"/> contains
/// a specific <see cref="IDetectable"/> object.
/// </summary>
/// <param name="detectable">Detectable object</param>
/// <returns>True if <see cref="IDetectable"/> was found</returns>
public bool Contains(IDetectable detectable)
{
return m_Detectables.Contains(detectable);
}
/// <summary>
/// Returns the <see cref="Item"/> instance count associated
/// with a specific tag.
/// </summary>
/// <param name="tag">The specified tag</param>
/// <returns>Number of items</returns>
public int Count(string tag)
{
if (m_ItemsByTag.TryGetValue(tag, out IList<Item> items))
{
return items.Count;
}
return 0;
}
/// <summary>
/// Returns the total <see cref="Item"/> instance count.
/// </summary>
/// <returns>Number of items</returns>
public int Count()
{
int sum = 0;
foreach (var list in m_ItemsByTag.Values)
{
sum += list.Count;
}
return sum;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.