text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2018 {
public class Problem16 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2018: 16"; }
}
public override string GetAnswer() {
return Answer1();
}
public override string GetAnswer2() {
return Answer2();
}
public string Answer1() {
var input = GetInstructions(Input());
var functions = GetFunctions();
int count = 0;
input.Instructions.ForEach(x => count += (Atleast3(x, functions) ? 1 : 0));
return count.ToString();
}
private string Answer2() {
var input = GetInstructions(Input());
var functions = GetFunctions();
var mapping = GetMapping(input.Instructions, functions);
var ops = ReduceMappings(mapping);
return RunOps(ops, input.Ops).ToString();
}
private int RunOps(InsFunction[] functions, List<int[]> ops) {
Instruction current = new Instruction();
current.After = new int[4];
foreach (var op in ops) {
var function = functions[op[0]];
current.Before = current.After;
current.Op = op;
function.Perform(current);
}
return current.After[0];
}
private InsFunction[] ReduceMappings(Dictionary<Instruction, HashSet<InsFunction>> mapping) {
var result = new InsFunction[16];
do {
var next = mapping.Where(x => x.Value.Count == 1).ToList();
if (next.Count() == 0) {
return result;
}
foreach (var map in next) {
if (map.Value.Count > 0) {
var toRemove = map.Value.First();
result[map.Key.Op[0]] = toRemove;
foreach (var sub in mapping) {
if (sub.Value.Contains(toRemove)) {
sub.Value.Remove(toRemove);
}
}
}
}
} while (true);
}
private Dictionary<Instruction, HashSet<InsFunction>> GetMapping(List<Instruction> instructions, List<InsFunction> functions) {
var hash = new Dictionary<Instruction, HashSet<InsFunction>>();
foreach (var ins in instructions) {
foreach (var function in functions) {
function.Perform(ins);
if (IsExpected(ins)) {
if (!hash.ContainsKey(ins)) {
hash.Add(ins, new HashSet<InsFunction>());
}
hash[ins].Add(function);
}
}
}
return hash;
}
private bool Atleast3(Instruction ins, List<InsFunction> functions) {
int count = 0;
foreach (var insFunc in functions) {
insFunc.Perform(ins);
if (IsExpected(ins)) {
count++;
if (count == 3) {
return true;
}
}
}
return false;
}
private bool IsExpected(Instruction ins) {
return ins.After[0] == ins.Exepcted[0]
&& ins.After[1] == ins.Exepcted[1]
&& ins.After[2] == ins.Exepcted[2]
&& ins.After[3] == ins.Exepcted[3];
}
private List<InsFunction> GetFunctions() {
var functions = new List<InsFunction>();
functions.Add(new InsFunctionAddr());
functions.Add(new InsFunctionAddi());
functions.Add(new InsFunctionMulr());
functions.Add(new InsFunctionMuli());
functions.Add(new InsFunctionBanr());
functions.Add(new InsFunctionBani());
functions.Add(new InsFunctionBorr());
functions.Add(new InsFunctionBori());
functions.Add(new InsFunctionSetr());
functions.Add(new InsFunctionSeti());
functions.Add(new InsFunctionGtir());
functions.Add(new InsFunctionGtri());
functions.Add(new InsFunctionGtrr());
functions.Add(new InsFunctionEqir());
functions.Add(new InsFunctionEqri());
functions.Add(new InsFunctionEqrr());
return functions;
}
private Inputs GetInstructions(List<string> input) {
var inputs = new Inputs();
int index = 0;
do {
var ins = new Instruction();
ins.Before = input[index].Replace("Before: [", "").Replace("]", "").Split(',').Select(x => Convert.ToInt32(x.Trim())).ToArray();
ins.Op = input[index + 1].Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
ins.Exepcted = input[index + 2].Replace("After: [", "").Replace("]", "").Split(',').Select(x => Convert.ToInt32(x.Trim())).ToArray();
ins.After = new int[4];
index += 4;
inputs.Instructions.Add(ins);
if (input[index] == "") {
break;
}
} while (true);
index += 2;
do {
inputs.Ops.Add(input[index].Split(' ').Select(x => Convert.ToInt32(x)).ToArray());
index++;
} while (index < input.Count);
return inputs;
}
private class Inputs {
public Inputs() {
Instructions = new List<Instruction>();
Ops = new List<int[]>();
}
public List<Instruction> Instructions { get; set; }
public List<int[]> Ops { get; set; }
}
private class Instruction {
public int[] Before { get; set; }
public int[] Op { get; set; }
public int[] After { get; set; }
public int[] Exepcted { get; set; }
}
private abstract class InsFunction {
public abstract void Perform(Instruction ins);
protected void Reset(Instruction ins) {
ins.After[0] = ins.Before[0];
ins.After[1] = ins.Before[1];
ins.After[2] = ins.Before[2];
ins.After[3] = ins.Before[3];
}
}
private class InsFunctionAddr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] + ins.Before[ins.Op[2]];
}
}
private class InsFunctionAddi : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] + ins.Op[2];
}
}
private class InsFunctionMulr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] * ins.Before[ins.Op[2]];
}
}
private class InsFunctionMuli : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] * ins.Op[2];
}
}
private class InsFunctionBanr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] & ins.Before[ins.Op[2]];
}
}
private class InsFunctionBani : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] & ins.Op[2];
}
}
private class InsFunctionBorr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] | ins.Before[ins.Op[2]];
}
}
private class InsFunctionBori : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]] | ins.Op[2];
}
}
private class InsFunctionSetr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Before[ins.Op[1]];
}
}
private class InsFunctionSeti : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = ins.Op[1];
}
}
private class InsFunctionGtir : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Op[1] > ins.Before[ins.Op[2]] ? 1 : 0);
}
}
private class InsFunctionGtri : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Before[ins.Op[1]] > ins.Op[2] ? 1 : 0);
}
}
private class InsFunctionGtrr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Before[ins.Op[1]] > ins.Before[ins.Op[2]] ? 1 : 0);
}
}
private class InsFunctionEqir : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Op[1] == ins.Before[ins.Op[2]] ? 1 : 0);
}
}
private class InsFunctionEqri : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Before[ins.Op[1]] == ins.Op[2] ? 1 : 0);
}
}
private class InsFunctionEqrr : InsFunction {
public override void Perform(Instruction ins) {
Reset(ins);
ins.After[ins.Op[3]] = (ins.Before[ins.Op[1]] == ins.Before[ins.Op[2]] ? 1 : 0);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class endGameRazonar : MonoBehaviour {
public float timer;
private GameObject global;
public GameObject game;
private float timeelap;
private void Start()
{
global = GameObject.FindGameObjectWithTag("global");
timeelap = timer + Time.time;
}
private void Update()
{
if (timeelap < Time.time)
{
//+1 Puntuaaciones
//Next Person
global.GetComponent<GameController>().point += 50;
global.GetComponent<GameController>().heatCorret();
Destroy(game);
}
}
}
|
namespace PFRCenterGlobal.ViewModels.Maps
{
public class Result
{
public Geometry geometry { get; set; }
public string icon { get; set; }
public string id { get; set; }
public string name { get; set; }
public Opening_Hours opening_hours { get; set; }
public Photo[] photos { get; set; }
public string place_id { get; set; }
public Plus_Code plus_code { get; set; }
public float rating { get; set; }
public string reference { get; set; }
public string[] types { get; set; }
public int user_ratings_total { get; set; }
public string vicinity { get; set; }
public string scope { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Attribute
{
public class ModelProxyAttribute : System.Runtime.Remoting.Proxies.ProxyAttribute
{
public override MarshalByRefObject CreateInstance(Type serverType)
{
AopProxy realProxy = new AopProxy(serverType);
if (!SettingConfig.UseAopProxy)
{
SettingConfig.UseAopProxy = true;
}
return realProxy.GetTransparentProxy() as MarshalByRefObject;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Webkit;
using Android.Support.V7.App;
using App1.Function.Adapter;
namespace App1
{
[Activity(Label = "")]
public class Webview : AppCompatActivity
{
WebView web_view;
ProgressBar circularbar;
CommonFunc commonFunc = new CommonFunc();
string backTo;
string actionBarTitle;
private void SetCustomActoinBar()
{
SupportActionBar.SetDisplayShowCustomEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(false);
SupportActionBar.SetDisplayShowTitleEnabled(false);
SupportActionBar.SetDisplayShowHomeEnabled(false);
View customActionBar = LayoutInflater.From(this).Inflate(Resource.Layout.layout_custom_actionbar, null);
customActionBar.FindViewById<TextView>(Resource.Id.customBackBtn).Click += delegate
{
if (backTo == "mainActivity")
{
commonFunc.MoveToActivity(this, typeof(MainActivity), new Dictionary<string, string>()
{
{"version","list"}
});
}
Finish();
};
customActionBar.FindViewById<TextView>(Resource.Id.customActionBarTitle).Text = actionBarTitle;
var customInfoBtn = customActionBar.FindViewById<TextView>(Resource.Id.customInfoBtn);
customInfoBtn.Visibility = ViewStates.Gone;
SupportActionBar.SetCustomView(customActionBar,
new Android.Support.V7.App.ActionBar.LayoutParams(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.WrapContent));
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
string url = Intent.Extras.GetString("url");
backTo = Intent.Extras.GetString("backTo");
actionBarTitle = Intent.Extras.GetString("actionBarTitle");
SetCustomActoinBar();
SetContentView(Resource.Layout.Webview);
circularbar = FindViewById<ProgressBar>(Resource.Id.progressBar);
circularbar.Visibility = ViewStates.Visible;
circularbar.BringToFront();
web_view = FindViewById<WebView>(Resource.Id.webview);
web_view.Settings.JavaScriptEnabled = true;
web_view.SetWebViewClient(new MyWebViewClient(circularbar));
web_view.LoadUrl(url);
}
}
} |
using ChatAppSample.Extensions;
using Sharpnado.Shades;
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace ChatAppSample.Views.Helpers
{
public partial class Fab : ContentView
{
#region CommandProperty
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(
propertyName: nameof(Command),
returnType: typeof(ICommand),
declaringType: typeof(Fab));
public ICommand Command
{
get => (ICommand)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
#endregion
#region ImageSourceProperty
public static readonly BindableProperty ImageSourceProperty =
BindableProperty.Create(
propertyName: nameof(ImageSource),
returnType: typeof(ImageSource),
declaringType: typeof(Fab));
public ImageSource ImageSource
{
get =>(ImageSource)GetValue(ImageSourceProperty);
set => SetValue(ImageSourceProperty, value);
}
#endregion
#region BackgroundColorProperty
public static readonly BindableProperty BackgroundColorProperty =
BindableProperty.Create(
propertyName: nameof(BackgroundColor),
returnType: typeof(Color),
declaringType: typeof(Fab ),
defaultValue: Color.Black);
public Color BackgroundColor
{
get => (Color)GetValue(BackgroundColorProperty);
set => SetValue(BackgroundColorProperty, value);
}
#endregion
public event EventHandler Clicked;
public Fab()
{
InitializeComponent();
}
protected async override void OnParentSet()
{
base.OnParentSet();
var page = await this.GetParentAsync<Page>();
await WaitForPageAnimationEndsAsync();
await ShowButtonAsync();
page.Appearing += Page_Appearing;
page.Disappearing += Page_Disappearing;
}
private async void Page_Appearing(object sender, EventArgs e)
{
await WaitForPageAnimationEndsAsync();
await ShowButtonAsync();
}
private void Page_Disappearing(object sender, EventArgs e)
{
this.Shadows.ScaleTo(0, easing: Easing.SpringIn);
}
private async Task WaitForPageAnimationEndsAsync()
{
await Task.Delay(300);
}
private async Task ShowButtonAsync()
{
await Shadows.ScaleTo(1, easing: Easing.SpringOut);
}
private void Button_Clicked(object sender, EventArgs e)
{
Clicked?.Invoke(this, EventArgs.Empty);
if(Command!= null && Command.CanExecute(null))
{
Command.Execute(null);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Utilities.Game
{
public class Constants
{
/// <summary>
/// Represents the name of the game.
/// </summary>
public static string NAME = "Game_Name";
/// <summary>
/// Represents wether the game is in debug mode or not
/// </summary>
public static bool DEBUG_MODE = false;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Entity : InteractableComponent {
Transform self;
protected float radius = 3;
protected float maturingTime = 1;
float lifeSpan;
public bool canSpread;
protected List<Interactable> canSpreadObjects = new List<Interactable>();
void Start()
{
Initialize();
}
private void OnEnable()
{
Initialize();
}
void Initialize()
{
main = GetComponent<Interactable>();
self = transform;
//StartCoroutine(CheckSpread());
}
// Update is called once per frame
void Update()
{
if (!canSpread)
{
if (lifeSpan < maturingTime)
lifeSpan += Time.deltaTime;
else
canSpread = true;
}
}
private void FixedUpdate()
{
CheckSpread();
}
void CheckSpread()
{
if (!this.enabled) return;
if (canSpread)
{
canSpreadObjects.Clear();
//Vector3 pos;
//if (main.parameters.nodes.Length > 0)
//{
// pos = main.parameters.nodes.position;
//}
//else
//{
// pos = self.position;
//}
Collider[] colliders = Physics.OverlapSphere(self.position, radius);
if (colliders.Length > 0) CheckObjects(colliders);
if (canSpreadObjects.Count > 0) Spread();
}
}
protected virtual void CheckObjects(Collider[] _colliders)
{
for (int i = 0; i < _colliders.Length; i++)
{
if (_colliders[i].GetComponent<Interactable>() != null)
{
Interact(_colliders[i].GetComponent<Interactable>());
}
}
}
protected virtual void Interact(Interactable _object) { }
protected virtual void Spread() { }
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Logcontent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("Login.aspx");
else
{
int logid = Convert.ToInt32(Session["logid"].ToString()); //获取传递的日志id
Logs log = new Logs(logid); //实例化日志
txtHeadline.Text = log.Headline;
txtContent.Text = log.Content;
lbTime.Text = log.Time;
if (!IsPostBack)
{
string sql = "select * from UsersLog where logid='" + logid + "'";
DataTable dt = DataClass.DataT(sql);
RptComment.DataSource = dt;
RptComment.DataBind();
}
}
}
protected void btnReply_Click(object sender, EventArgs e)
{
string content = txtComment.Text;
Users user = (Users)Session["user"];
int logid = Convert.ToInt32(Session["logid"].ToString()); //获取传递的日志id
Logs log = new Logs(logid); //实例化日志
int authorid = log.Userid;
if(user.Userid != authorid )
{
Friends friend = (Friends)Session["friend"];
int userid = user.Userid;
int friendid = friend.Friendid;
int result = DataClass.CheckAbleToComment(userid, friendid);
if (result == 0)
Response.Write("<script>alert('您没有权限评论该用户!')</script>");
else
{
DateTime time = DateTime.Now;
string sql = "insert into Logcomment values('" + logid + "','" + user.Userid + "',N'" + content + "','" + time + "')";
DataClass.Save(sql);
Response.Write("<script>alert('回复成功!');location='Logcontent.aspx'</script>");
}
}
else
{
DateTime time = DateTime.Now;
string sql = "insert into Logcomment values('" + logid + "','" + user.Userid + "',N'" + content + "','" + time + "')";
DataClass.Save(sql);
Response.Write("<script>alert('回复成功!');location='Logcontent.aspx'</script>");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace ManageWeb
{
public class OutApiBaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
int code = (int)ManageDomain.MExceptionCode.ServerError;
if (filterContext.Exception is ManageDomain.MException)
{
code = (filterContext.Exception as ManageDomain.MException).Code;
}
filterContext.HttpContext.Response.StatusCode = 200;
var vresult = Json(new JsonEntity() { code = code, data = null, msg = filterContext.Exception.Message }, JsonRequestBehavior.AllowGet);
vresult.ExecuteResult(filterContext.Controller.ControllerContext);
filterContext.Controller.ControllerContext.HttpContext.Response.End();
}
public JsonResult JsonError(string msg)
{
return Json(new JsonEntity() { code = -1, msg = msg });
}
public JsonResult JsonE(object data)
{
return Json(new JsonEntity() { code = 1, data = data, msg = "" });
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public abstract class BaseCardEffect : ScriptableObject
{
public abstract CardPotentialTarget EffectTarget { get; }
public abstract BaseCardEffectStats CardEffectDefaults { get; }
public abstract EffectData CurrentEffectData { get; }
public abstract CardPotentialState EffectPreferredState { get; }
public class EffectData
{
CardPotentialTarget target;
BaseCardEffectStats effect;
string effectName;
public BaseCardEffectStats Effect
{
get
{
return effect;
}
}
public string EffectName
{
get
{
return effectName;
}
}
public CardPotentialTarget Target
{
get
{
return target;
}
}
public EffectData(CardPotentialTarget t, BaseCardEffectStats e, string eN)
{
target = t;
effect = e;
effectName = eN;
}
public EffectData() { }
}
public abstract void InitialiseCardEffect();
public abstract EffectData InitiateCardEffect();
public abstract BaseCardEffect OnActivateCardEffect();
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Android.App;
using Microsoft.Intune.Mam.Client.App;
using Microsoft.Intune.Mam.Client.Notification;
using Microsoft.Intune.Mam.Policy;
using Microsoft.Intune.Mam.Policy.Notification;
namespace active_directory_xamarin_intune.Droid
{
#if DEBUG
/// <remarks>
/// Due to an issue with debugging the Xamarin bound MAM SDK the Debuggable = false attribute must be added to the Application in order to enable debugging.
/// Without this attribute the application will crash when launched in Debug mode. Additional investigation is being performed to identify the root cause.
/// </remarks>
// [Application(Debuggable = false)]
#else
[Application]
#endif
class IntuneSampleApp : MAMApplication
{
public IntuneSampleApp(IntPtr handle, Android.Runtime.JniHandleOwnership transfer)
: base(handle, transfer) { }
public override void OnMAMCreate()
{
// as per Intune SDK doc, callback registration must be done here.
// https://docs.microsoft.com/en-us/mem/intune/developer/app-sdk-android
IMAMEnrollmentManager mgr = MAMComponents.Get<IMAMEnrollmentManager>();
mgr.RegisterAuthenticationCallback(new MAMWEAuthCallback());
// Register the notification receivers to receive MAM notifications.
// Along with other, this will receive notification that the device has been enrolled.
var notificationRcvr = new EnrollmentNotificationReceiver();
IMAMNotificationReceiverRegistry registry = MAMComponents.Get<IMAMNotificationReceiverRegistry>();
registry.RegisterReceiver(notificationRcvr, MAMNotificationType.MamEnrollmentResult);
registry.RegisterReceiver(notificationRcvr, MAMNotificationType.ComplianceStatus);
base.OnMAMCreate();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AnimalAdditions.DAL
{
public class Animals
{
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TinhLuongDAL;
using TinhLuongINFO;
namespace TinhLuongBLL
{
public class ChotSoBLL
{
ChotSoDAL dal = new ChotSoDAL();
public List<DM_DonVi> Select_ByDonViCha(string donviid)
{
return dal.Select_ByDonViCha(donviid);
}
public List<DM_BangChotSo> GetByBangChot(decimal thang, decimal nam, string donviId)
{
return dal.GetByBangChot(thang, nam, donviId);
}
public DataTable GetListChotso(decimal thang, decimal nam, string donviId)
{
return dal.GetListChotso(thang, nam, donviId);
}
public DataTable GetListChotso_BangID(decimal thang, decimal nam, string donviId, string BangID)
{
return dal.GetListChotso_BangID(thang, nam, donviId, BangID);
}
public bool CapnhatBangChotSo(decimal Nam, decimal Thang, string BangID, string DonViID, int TinhTrang, string USERNAME)
{
return dal.CapnhatBangChotSo(Nam, Thang, BangID, DonViID, TinhTrang, USERNAME);
}
public List<ChotSoBS> GetList_ChotSoBS(int Nam)
{
return dal.GetList_ChotSoBS(Nam);
}
public Ouput Tuyen_Check_ChotSoBS(int Nam, int LoaiBS)
{
return dal.Tuyen_Check_ChotSoBS(Nam, LoaiBS);
}
public Ouput Tuyen_Update_ChotSoBS(int Nam, int LoaiBS,string Username)
{
return dal.Tuyen_Update_ChotSoBS(Nam, LoaiBS,Username);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Docller.Core.Common;
using Docller.Core.Repository;
using Docller.Core.Storage;
namespace Docller.Core.Services
{
public enum StorageServiceStatus
{
Unknown = RepositoryStatus.Unknown,
Success = RepositoryStatus.Success,
UploadInProgress = 1,
ExistingFile = RepositoryStatus.ExistingFile,
VersionPathNull = RepositoryStatus.VersionPathNull,
ExistingFolder = RepositoryStatus.ExistingFolder,
DownloadComplete = BlobStorageProviderStatus.DownloadComplete,
DownloadCanceled = BlobStorageProviderStatus.DownloadCanceled
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace streamdeck_client_csharp.Events
{
public class PropertyInspectorDidAppearEvent : BaseEvent
{
[JsonProperty("action")]
public string Action { get; private set; }
[JsonProperty("context")]
public string Context { get; private set; }
[JsonProperty("device")]
public string Device { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blog.Repositories
{
public interface IRepository
{
IQueryable<Post> GetAllPosts();
Post GetPostById(int postId);
IQueryable<Post> GetPostByKeyWords(string keyWords);
void SavePost(Post post);
void UpdatePost(Post post);
void DeletePost(int postId);
IEnumerable<Comment> GetComments(int postId);
void SaveComment(int postId, Comment comment);
void DeleteComment(int commentId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChainOfResponsibility
{
public class ConcreteHandler : Handler
{
public override void HandleRequest(int request)
{
if (request >= 0 && request < 10)
{
Console.WriteLine($"{GetType().Name} handled request {request}");
}
else if (_sucessor != null)
{
_sucessor.HandleRequest(request);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Train
{
class Program
{
static void Main(string[] args)
{
List<int> NumberOfPassengersInEachWagon = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
int MaxCapacityOfEachWagon = int.Parse(Console.ReadLine());
while(true)
{
string Input = Console.ReadLine();
if(Input=="end")
{
break;
}
string[] tokens = Input.Split();
string command = tokens[0];
if(command=="Add")
{
int passengersToAdd = int.Parse(tokens[1]);
NumberOfPassengersInEachWagon.Add(passengersToAdd);
}
else
{
int passengersToAdd = int.Parse(tokens[0]);
NumberOfPassengersInEachWagon.Insert(0, passengersToAdd);
for(int i=0;i<NumberOfPassengersInEachWagon.Count;i++)
{
if(NumberOfPassengersInEachWagon[i]>MaxCapacityOfEachWagon)
{
int sum = NumberOfPassengersInEachWagon[i] - MaxCapacityOfEachWagon;
NumberOfPassengersInEachWagon[i + 1] = NumberOfPassengersInEachWagon[i + 1] + sum;
NumberOfPassengersInEachWagon[i] = MaxCapacityOfEachWagon;
}
}
}
}
Console.WriteLine(string.Join(" ",NumberOfPassengersInEachWagon));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MobilePhoneRetailer;
using System.Configuration;
using MobilePhoneRetailer.BusinessLayer;
namespace MobilePhoneRetailer.WebPages
{
public partial class Register_User : System.Web.UI.Page
{
public Customer Customer
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
String email = EmailBox.Text;
String password = PasswordBox.Text;
String name = NameBox.Text;
String address = AddressBox.Text;
String Num = PhoneNumBox.Text;
int phoneNum = Convert.ToInt32(Num);
String notes = "notes test";
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
String sql = "INSERT INTO Customer VALUES(@Name, @Address, @PhoneNumber, @Notes, @EmailAddress, @Password)";
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@Name", SqlDbType.VarChar);
command.Parameters["@Name"].Value = name;
command.Parameters.Add("@Address", SqlDbType.VarChar);
command.Parameters["@Address"].Value = address;
command.Parameters.Add("@PhoneNumber", SqlDbType.Int);
command.Parameters["@PhoneNumber"].Value = phoneNum;
command.Parameters.Add("@Notes", SqlDbType.VarChar);
command.Parameters["@Notes"].Value = notes;
command.Parameters.Add("@EmailAddress", SqlDbType.VarChar);
command.Parameters["@EmailAddress"].Value = email;
command.Parameters.Add("@Password", SqlDbType.VarChar);
command.Parameters["@Password"].Value = password;
command.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Write("FAIL");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PromoServiceCosmos.Models
{
public class ProductPromoAction
{
public ProductPromoActionType type { get; set; }
public decimal quantity { get; set; }
public decimal amount { get; set; }
public string productId { get; set; }
public string catalogId { get; set; }
public override string ToString()
{
// return JsonConvert.DeserializeObject(this);
return JsonConvert.SerializeObject(this);
}
}
}
|
using BuisinessLogic.Interfaces;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
namespace Services.Implementations
{
public class TokenService : ItokenService
{
private readonly IBusinessLogicUnitOfWork _businessLogicUnitOfWork;
public TokenService(IBusinessLogicUnitOfWork businessLogicUnitOfWork)
{
_businessLogicUnitOfWork = businessLogicUnitOfWork;
}
public string GenerateAccessToken(IEnumerable<Claim> claims)
{
return _businessLogicUnitOfWork.TokenBsLogic.GenerateAccessToken(claims);
}
public string GenerateRefreshToken()
{
return _businessLogicUnitOfWork.TokenBsLogic.GenerateRefreshToken();
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
return _businessLogicUnitOfWork.TokenBsLogic.GetPrincipalFromExpiredToken(token);
}
}
}
|
using BusinessObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
class CommentDAO
{
private static CommentDAO instance = null;
private static readonly object instanceLock = new object();
public static CommentDAO Instance
{
get
{
lock (instanceLock)
{
if (instance == null)
{
instance = new CommentDAO();
}
return instance;
}
}
}
public Comment GetCommentByID(int commentID)
{
Comment _comment = null;
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
_comment = context.Comments.Where(cmt => cmt.CommentId == commentID).Single();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return _comment;
}
public IEnumerable<Comment> GetCommentsByPosts(int postId)
{
List<Comment> lst = new List<Comment>();
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
lst = context.Comments.Where(cmt => cmt.PostId == postId).OrderByDescending(cmt => cmt.CommentId).ToList();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return lst;
}
public void AddComment(Comment comment)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.Comments.Add(comment);
context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void DeleteComment(Comment comment)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.Comments.Remove(comment);
context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void EditComment(Comment updatedComment)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.Entry(updatedComment).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public int GetMaxCommentId()
{
int commentId = 0;
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
commentId = context.Comments.Max(c => c.CommentId);
if (commentId == 0)
{
throw new Exception("no comment");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return commentId;
}
}
}
|
using UnityEngine;
public class Bullet : MonoBehaviour
{
private Transform target;
[SerializeField] float speed = 70f;
private float distanceFactor = 1f;
public static bool isCollided = false;
public void SeekTarget(Transform newTarget)
{
target = newTarget;
}
// Update is called once per frame
void Update()
{
if (target == null)
{
return;
}
Vector3 dir = target.position - this.transform.position;
float distanceThisFrame = distanceFactor * speed * Time.deltaTime;
//normalized -> however close we are to the target doesnt have effect on how fast we are moving, bcs it should move with const speed
transform.Translate(dir.normalized * distanceThisFrame, Space.World);
//check for overshoot (in order to hit the bullet move pats the target)
if (dir.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
Destroy(gameObject, 3.5f); //TODO think about something smarter!
}
private void HitTarget()
{
Destroy(gameObject);
isCollided = true;
target.SendMessage("Collided", isCollided); //string refference with EnemyDamage
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TestBrokenApp.Models;
using TestBrokenApp.Views;
using TestBrokenApp.ViewModels;
using CustomXamarinControls;
using Prism.Navigation;
namespace TestBrokenApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Tasks : ContentPage
{
public Tasks()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
//Animation ZoomOut = new Animation { { 0, 1, new Animation(a => Opacity = a, .7, 1) },
// { 0, 1, new Animation(a => Scale = a, 2, 1) },
// { 0, 1, new Animation(a => HeightRequest = 1) },
// { 0, 1, new Animation(a => AnchorX = a, 2, 1) },
// { 0, 1, new Animation(a => AnchorY = 1) }
//};
//this.Animate("ZoomOut", ZoomOut, 16, 260, Easing.SinOut, null, null);
}
//protected override void OnDisappearing()
//{
// Animation ZoomIn = new Animation { { 0, 1, new Animation(a => Opacity = a, 1, 0) },
// { 0, 1, new Animation(a => Scale = a, 1, 2) },
// { 0, 1, new Animation(a => HeightRequest = 1) },
// { 0, 1, new Animation(a => AnchorX = a, 1, 2) },
// { 0, 1, new Animation(a => AnchorY = 1) }
// };
// this.Animate("ZoomIn", ZoomIn, 16, 600, Easing.SinIn, null, null);
// base.OnDisappearing();
//}
}
} |
using System;
namespace n1
{
class c1
{
public void func()
{
Console.WriteLine("namespace n1 class1 func");
Console.ReadKey();
}
}
}
namespace n2
{
class c2
{
public void func()
{
Console.WriteLine("namespace n2 class2 func");
n1.c1 yy = new n1.c1();
yy.func();
Console.ReadKey();
}
}
}
class TestClass
{
static void Main(string[] args)
{
n2.c2 o = new n2.c2();
o.func();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TestHouse.DTOs.Models
{
public class StepModel
{
/// <summary>
/// Step id
/// </summary>
public long Id { get; private set; }
/// <summary>
/// Step order
/// </summary>
public int Order { get; private set; }
/// <summary>
/// Step description
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Step expected result
/// </summary>
public string ExpectedResult { get; private set; }
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Pacman
{
public class Counter : GUIBox
{
protected double coinFrame;
protected CounterType counterType;
protected SpriteFont font;
protected Texture2D life, dead, coin, flash;
public Counter(int x, int y, Alignment alignment, SpriteFont font, CounterType type) : base(x, y, PacmanGame.ContentManager.Load<Texture2D>("textures/GUI/frame"), alignment, BoxStretch.Corners, 5, 5, 5, 5, type == CounterType.Coin ? 170 : 210, 80)
{
//the id is used to find the counter in the list of GUIElements in the HUD
id = counterType == CounterType.Coin ? "counter_coin" : "counter_life";
counterType = type;
this.font = font;
life = PacmanGame.ContentManager.Load<Texture2D>("textures/GUI/lifesprite");
dead = PacmanGame.ContentManager.Load<Texture2D>("textures/GUI/deadsprite");
coin = PacmanGame.ContentManager.Load<Texture2D>("textures/GUI/coinstring");
flash = PacmanGame.ContentManager.Load<Texture2D>("textures/GUI/reddeadsprite");
}
/// <summary>Update the counter.</summary>\
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
//Animates the coinsprite
coinFrame = (coinFrame + gameTime.ElapsedGameTime.TotalSeconds * 16) % 8;
}
/// <summary>Draw the counter and everything in it.</summary>
public override void Draw(SpriteBatch spriteBatch)
{
if (counterType == CounterType.Coin && PacmanGame.CurrentGameMode == GameMode.Survival)
return;
base.Draw(spriteBatch); // background
if (counterType == CounterType.Coin)
{
string text = "X " + PacmanGame.Maze.CoinCounter;
spriteBatch.Draw(coin, Position + new Vector2(15), new Rectangle((int)coinFrame * 50, 0, 50, 50), Color.White);
spriteBatch.DrawString(font, text, Position + new Vector2(80, 60), Color.Black, 0, new Vector2(0, font.MeasureString(text).Y), 1, SpriteEffects.None, 0);
}
else if (counterType == CounterType.Life)
{
if (PacmanGame.Maze.Pacman.Flash)
spriteBatch.Draw(dead, Position + new Vector2(15 + 65 * MathHelper.Clamp(PacmanGame.Maze.Pacman.Lives, 0, 3), 15), Color.White);
for (int i = 0; i < PacmanGame.Maze.Pacman.Lives; i++)
spriteBatch.Draw(life, Position + new Vector2(15 + 65 * i, 15), Color.White);
for (int i = PacmanGame.Maze.Pacman.Lives; i < 3; i++)
{
spriteBatch.Draw(dead, Position + new Vector2(15 + 65 * i, 15), Color.White);
}
if (PacmanGame.Maze.Pacman.Flash)
spriteBatch.Draw(life, Position + new Vector2(15 + 65 * MathHelper.Clamp(PacmanGame.Maze.Pacman.Lives,0,3), 15), new Rectangle(0, 0, dead.Width, dead.Height * ((int)PacmanGame.Maze.Pacman.FlashTimer) / 5), Color.Red);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace _7DRL_2021.Behaviors
{
class BehaviorKillTarget : Behavior, IDrawable
{
public ICurio Curio;
public double DrawOrder => 0;
public BehaviorKillTarget()
{
}
public BehaviorKillTarget(ICurio curio)
{
Curio = curio;
}
public bool IsCompleted()
{
//return true;
return Curio.IsDead();
}
public override void Apply()
{
Curio.AddBehavior(this);
}
public override void Clone(ICurioMapper mapper)
{
var curio = mapper.Map(Curio);
Apply(new BehaviorKillTarget(curio), Curio);
}
public void Draw(SceneGame scene, DrawPass pass)
{
var pos = Curio.GetVisualTarget();
SkillUtil.DrawPointer(scene, pos, "KILL");
}
public void DrawIcon(SceneGame scene, Vector2 pos)
{
throw new NotImplementedException();
}
public IEnumerable<DrawPass> GetDrawPasses()
{
yield return DrawPass.UI;
}
public bool ShouldDraw(SceneGame scene, Vector2 cameraPosition)
{
return Curio.GetMap() == scene.Map && !IsCompleted();
}
}
}
|
namespace Common.Infra
{
public static class Extension
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AnimEvent : MonoBehaviour
{
public UnityEvent[] events;
public void InvokeEvent(int i)
{
if (events[i] != null) events[i].Invoke();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oop._12_RefactoringBindAll
{
static class Int64Extentions
{
public static IEnumerable<int> DigitsFromLowest(this long number)
{
do
{
yield return (int)(number % 10);
number /= 10;
}
while (number > 0);
}
}
}
|
// This computer source code and related instructions and comments are the
// unpublished confidential and proprietary information of Autodesk, Inc.
// and are protected under Federal copyright and state trade secret law.
// They may not be disclosed to, copied or used by any third party without
// the prior written consent of Autodesk, Inc.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Autodesk.Forge.ARKit {
public class MessageBox : MonoBehaviour {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using Witsml.Data;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Models;
using WitsmlExplorer.Api.Query;
namespace WitsmlExplorer.Api.Services
{
public interface IWellService
{
Task<IEnumerable<Well>> GetWells();
Task<Well> GetWell(string wellUid);
}
// ReSharper disable once UnusedMember.Global
public class WellService : WitsmlService, IWellService
{
private readonly IWellboreService wellboreService;
public WellService(IWitsmlClientProvider witsmlClientProvider, IWellboreService wellboreService) : base(witsmlClientProvider)
{
this.wellboreService = wellboreService;
}
public async Task<IEnumerable<Well>> GetWells()
{
var getWellbores = wellboreService.GetWellbores();
var getWells = GetWellsInformation();
await Task.WhenAll(getWellbores, getWells);
var wells = getWells.Result.ToList();
foreach (var well in wells)
well.Wellbores = getWellbores.Result.Where(wb => wb.WellUid == well.Uid);
return wells.OrderBy(well => well.Name);
}
private async Task<IEnumerable<Well>> GetWellsInformation(string wellUid = null)
{
var start = DateTime.Now;
var witsmlWells = string.IsNullOrEmpty(wellUid) ? WellQueries.GetAllWitsmlWells() : WellQueries.GetWitsmlWellByUid(wellUid);
var result = await WitsmlClient.GetFromStoreAsync(witsmlWells, new OptionsIn(ReturnElements.Requested));
var wells = result.Wells
.Select(well => new Well
{
Uid = well.Uid,
Name = well.Name,
Field = well.Field,
Operator = well.Operator,
TimeZone = well.TimeZone,
DateTimeCreation = StringHelpers.ToDateTime(well.CommonData.DTimCreation),
DateTimeLastChange = StringHelpers.ToDateTime(well.CommonData.DTimLastChange),
ItemState = well.CommonData.ItemState
}
).ToList();
var elapsed = DateTime.Now.Subtract(start).Milliseconds / 1000.0;
Log.Debug("Fetched {Count} wells in {Elapsed} seconds", wells.Count, elapsed);
return wells;
}
public async Task<Well> GetWell(string wellUid)
{
var getWellbores = wellboreService.GetWellbores(wellUid);
var getWell = GetWellsInformation(wellUid);
await Task.WhenAll(getWellbores, getWell);
if (!getWell.Result.Any()) return null;
var well = getWell.Result.First();
well.Wellbores = getWellbores.Result;
return well;
}
}
}
|
using System.Collections.Generic;
using iRunes.Models;
using iRunes.ViewModels.Albums;
namespace iRunes.Services
{
public interface IAlbumsService
{
void Create(string cover, string name);
IEnumerable<AlbumInfoViewModel> GetAllAlbums();
AlbumDetailsViewModel GetAlbumDetails(string id);
}
} |
using Etherama.Common;
using System.Numerics;
using System.Threading.Tasks;
namespace Etherama.CoreLogic.Services.Blockchain.Ethereum {
public interface IEthereumWriter
{
Task<string> UpdateMaxGaxPrice(BigInteger gasPrice);
}
}
|
using System.Threading.Tasks;
using System;
using System.Threading;
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace AgentR.Server
{
public class InMemoryCallbackCordinator : IRequestCallbackCordinator
{
public static readonly IRequestCallbackCordinator Instance = new InMemoryCallbackCordinator();
private readonly ConcurrentDictionary<int, RequestCallback> callbacks = new ConcurrentDictionary<int, RequestCallback>();
private readonly ConcurrentDictionary<int, RequestCallback> accepted = new ConcurrentDictionary<int, RequestCallback>();
private int callbacksId = 1;
public async Task<bool> Accept(int id, string connectionId)
{
if (callbacks.TryRemove(id, out RequestCallback callback))
{
while (!accepted.TryAdd(id, callback))
{
await Task.Delay(1);
}
callback.AcceptedClient = connectionId;
Logging.Logger.LogInformation($"Request {id} accepted by {callback.AcceptedClient}");
return true;
}
return false;
}
public async Task<int> CreateCallback<TRequest, TResponse>(TRequest request, TaskCompletionSource<TResponse> taskCompletionSource)
{
var id = Interlocked.Increment(ref callbacksId);
bool CompletionCallback(object r, Exception ex)
{
try
{
if (null != ex) return taskCompletionSource.TrySetException(ex);
switch (r)
{
case TResponse v:
accepted.TryRemove(id, out _);
return taskCompletionSource.TrySetResult(v);
case Newtonsoft.Json.Linq.JObject jobject:
accepted.TryRemove(id, out _);
return taskCompletionSource.TrySetResult(jobject.ToObject<TResponse>());
default:
accepted.TryRemove(id, out _);
return taskCompletionSource.TrySetException(new ArgumentOutOfRangeException("result", r, ""));
}
}
finally
{
accepted.TryRemove(id, out _);
}
}
var callback = new RequestCallback<TRequest>(id, CompletionCallback, request);
while (!callbacks.TryAdd(id, callback))
{
await Task.Delay(1);
}
return id;
}
public Task<bool> Error(int id, Exception ex, string connectionId)
{
if (accepted.TryGetValue(id, out RequestCallback callback))
{
if (connectionId != callback.AcceptedClient)
{
throw new InvalidOperationException("Response was not accepted by client");
}
return Task.FromResult(callback.Callback(null, ex));
}
return Task.FromResult(false);
}
public Task<bool> IsAccepted(int id)
{
var isAccepted = accepted.ContainsKey(id) || !callbacks.ContainsKey(id);
return Task.FromResult(isAccepted);
}
public Task<bool> Response(int id, object response, string connectionId)
{
if (accepted.TryGetValue(id, out RequestCallback callback))
{
if (connectionId != callback.AcceptedClient)
{
throw new InvalidOperationException("Response was not accepted by client");
}
return Task.FromResult(callback.Callback(response, null));
}
return Task.FromResult(false);
}
internal class RequestCallback
{
private readonly Func<Object, Exception, bool> callback;
private readonly int id;
public RequestCallback(int id, Func<Object, Exception, bool> callback)
{
this.id = id;
this.callback = callback;
}
public int Id => this.id;
public Func<Object, Exception, bool> Callback => this.callback;
public string AcceptedClient { get; set; }
}
internal class RequestCallback<TRequest> : RequestCallback
{
private readonly TRequest request;
public RequestCallback(int id, Func<Object, Exception, bool> callback, TRequest request)
: base(id, callback)
{
this.request = request;
}
public TRequest Request => this.request;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace KartObjects
{
public partial class FormWait : Form
{
public FormWait(String caption)
{
InitializeComponent();
this.Text=caption;
Caption = caption;
NoControlFrame = false;
}
bool NoControlFrame;
public FormWait(String caption,Color BackGroundColor)
{
InitializeComponent();
this.Text = caption;
this.BackColor = BackGroundColor;
Caption = caption;
lblMessage.ForeColor = Color.White;
NoControlFrame = true;
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
/// <summary>
/// Заголовок
/// </summary>
String Caption
{
get;
set;
}
/// <summary>
/// Можно ли закрывать форму
/// </summary>
bool CanClose
{
get;
set;
}
/// <summary>
/// Закрытие формы
/// </summary>
public void CloseWaitForm()
{
if (InvokeRequired)
{
Invoke(new Action(InvokeCloseWaitForm));
}
else
{
InvokeCloseWaitForm();
}
}
//public delegate void dlgSetText(string text);
public void SetText(string text)
{
if (InvokeRequired)
Invoke(new Action(delegate {Caption=text;}));//dlgSetText(SetText), text);
else
this.Caption = text;
}
private void InvokeCloseWaitForm()
{
CanClose = true;
timer1.Stop();
Close();
}
public DateTime startTime
{
get;
set;
}
private void FormWait_Load(object sender, EventArgs e)
{
startTime = DateTime.Now;
timer1.Start();
CanClose = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = DateTime.Now.Subtract(startTime);
this.Text = Caption+ " "+ ts.Hours.ToString().PadLeft(2, '0') + ":" + ts.Minutes.ToString().PadLeft(2, '0') + ":" + ts.Seconds.ToString().PadLeft(2, '0');
}
private void FormWait_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !CanClose;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (NoControlFrame)
{
Rectangle rect = panel1.ClientRectangle;
rect.X = 2;
rect.Y = 2;
rect.Width = rect.Width - 5;
rect.Height = Height - 5;
e.Graphics.DrawRectangle(Pens.White, rect);
}
}
}
}
|
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using App1.Annotations;
using Xamarin.Forms;
namespace App1
{
public class ViewModel : INotifyPropertyChanged
{
public ViewModel(bool isInitiallyTapable)
{
ToggleIsLabelTapableCommand = new Command(ToggleIsLabelTapable);
ChangeSlaveTextCommand = new Command(TapLabel);
_isLabelTapable = isInitiallyTapable;
}
public ICommand ToggleIsLabelTapableCommand { get; }
public ICommand ChangeSlaveTextCommand { get; }
private bool _isLabelTapable;
public bool IsTapable
{
get { return _isLabelTapable; }
set
{
if (value != _isLabelTapable)
{
_isLabelTapable = value;
OnPropertyChanged();
}
}
}
private string _slaveLabelText = "Slave";
public string SlaveLabelText
{
get { return _slaveLabelText; }
set
{
if (_slaveLabelText != value)
{
_slaveLabelText = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void TapLabel()
{
SlaveLabelText = DateTime.Now.ToString();
}
private void ToggleIsLabelTapable()
{
IsTapable = !IsTapable;
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PortalScript : MonoBehaviour {
public Transform Exit;
[Tooltip("Optional segment that the car needs to have made contact with immediatly before entering")]
public LevelPieceSuperClass Segment;
// TODO: dynamically set (and unset) exit portals segment to allow entry from the entry portal segment, instead of triggering a reset
[HideInInspector]
public List<IObserver<PortalScript>> Observers = new List<IObserver<PortalScript>>();
private void OnTriggerEnter(Collider other) {
if (Segment && !LevelPieceSuperClass.CheckCurrentSegment(Segment)) {
// LevelPieceSuperClass.ResetToCurrentSegment();
return;
}
foreach (var item in Observers)
item.Notify(this);
var rb = other.attachedRigidbody;
rb.MovePosition(Exit.position);
rb.MoveRotation(Exit.rotation);
rb.velocity = Exit.rotation * Vector3.forward * rb.velocity.magnitude;
ResetTransition.StartTransition();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Teachermanager : MonoBehaviour
{
public static Teachermanager instance = null;
#region instance
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
#endregion
[Header("Teacher position")]
[SerializeField] private Vector3 tPossitionOfcet;
[Header("Randomize Number")]
[SerializeField] public int[] randomNum;
[Header("Teacher Skill's rarity")]
[SerializeField] public string[] skills;
[Header("Teacher prefabs")]
[SerializeField] public GameObject[] teacherPrefabs;
[Header("Teacher Name")]
[SerializeField] public Text[] Teachernames;
[Header("Teacher Pictures")]
[SerializeField] public Sprite[] teacherPortrait;
[Header("Teacher Icons")]
[SerializeField] public Image[] teacherIcons;
[Header("Teacher Skill's Rarity Text")]
[SerializeField] public Text[] teachertraitstxt;
[Header("Teacher Skill's Salary text")]
[SerializeField] public Text[] salaryTxt;
[Header("Teacher Skill's Salary")]
[SerializeField] public string[] salary;
[Header("Teacher Skill's Hire text")]
[SerializeField] public Text[] hireCostTxt;
[Header("Teacher Skill's Hiring Cost")]
[SerializeField] public string[] hiringCost;
private GameObject TeacherTohire;
TeacherMono teachermono;
public void teacherNames()
{
teacherPrefabs[0].name = "Vlad the Viking"; //Common
teacherPrefabs[1].name = "Goe the Goblin"; //Common
teacherPrefabs[2].name = "Wendy the Witch"; //Rare
teacherPrefabs[3].name = "Percy the Pirate"; //Legendary
teacherPrefabs[4].name = "Gill the Goblin"; //Rare
teacherPrefabs[5].name = "Will the Wizard"; //Common
teacherPrefabs[6].name = "Vicky the Viking"; //Rare
teacherPrefabs[7].name = "Cain the Cowboy"; //blue
teacherPrefabs[8].name = "Cyn the Cowgal"; //blue
teacherPrefabs[9].name = "Zoro the Legend"; //blue
}
public void RandomGenNum()
{
randomNum[0] = Random.Range(0, teacherPrefabs.Length);
randomNum[1] = Random.Range(0, teacherPrefabs.Length);
randomNum[2] = Random.Range(0, teacherPrefabs.Length);
//randomNum[3] = Random.Range(0, teacherPrefabs.Length);
}
//dont touch These two functions!
public void teacherAvatar()
{
teacherIcons[0].sprite = teacherPortrait[randomNum[0]];
teacherIcons[1].sprite = teacherPortrait[randomNum[1]];
teacherIcons[2].sprite = teacherPortrait[randomNum[2]];
//teacherIcons[3].sprite = teacherPortrait[randomNum[3]];
}
public void teacherUInames()
{
Teachernames[0].text = teacherPrefabs[randomNum[0]].ToString();
Teachernames[1].text = teacherPrefabs[randomNum[1]].ToString();
Teachernames[2].text = teacherPrefabs[randomNum[2]].ToString();
//Teachernames[3].text = teacherPrefabs[randomNum[3]].ToString();
}
public void teacherUItraits()
{
teachertraitstxt[0].text = skills[randomNum[0]];
teachertraitstxt[1].text = skills[randomNum[1]];
teachertraitstxt[2].text = skills[randomNum[2]];
//teachertraitstxt[3].text = "Rarity: " + skills[randomNum[3]];
}
public void teacherSalaryUI()
{
salaryTxt[0].text = "Salary/Day: $" + salary[randomNum[0]];
salaryTxt[1].text = "Salary/Day: $" + salary[randomNum[1]];
salaryTxt[2].text = "Salary/Day: $" + salary[randomNum[2]];
}
public void teacherHireCostUI()
{
hireCostTxt[0].text = "Hire for $" + hiringCost[randomNum[0]];
hireCostTxt[1].text = "Hire for $" + hiringCost[randomNum[1]];
hireCostTxt[2].text = "Hire for $" + hiringCost[randomNum[2]];
}
public void HireTeacherOne()
{
Instantiate(teacherPrefabs[randomNum[0]], tPossitionOfcet, Quaternion.identity);
}
public void HireTeacherTwo()
{
Instantiate(teacherPrefabs[randomNum[1]], tPossitionOfcet, Quaternion.identity);
}
public void HireTeacherThree()
{
Instantiate(teacherPrefabs[randomNum[2]], tPossitionOfcet, Quaternion.identity);
}
//public void HireTeacherFour()
//{
// Instantiate(teacherPrefabs[randomNum[3]], tPossitionOfcet, Quaternion.identity);
//}
public GameObject GetTeacherTohire()
{
return TeacherTohire;
}
public void SetTeacher(GameObject Staff)
{
TeacherTohire = Staff;
}
public void GenerateRanNum()
{
RandomGenNum();
}
void Start()
{
RandomGenNum(); //Generate Number (this applies to all the UI name and Avatar that goes along with it)
}
// Update is called once per frame
void Update()
{
//if (Input.GetButtonUp("R"))
//{
// RandomGenNum();
//}
teacherNames();
teacherUInames();
teacherAvatar();
teacherUItraits();
teacherSalaryUI();
teacherHireCostUI();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PatronAbstract_Factory
{
public class Cafe : IBebida
{
public string Nombre => "Cafe Descafeinado";
public string Marca =>"Juan Valdes" ;
public double Precio =>8000 ;
public double Azucar => 2.9;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CAPCO.Infrastructure.Domain;
using CAPCO.Infrastructure.Data;
namespace CAPCO.Areas.Admin.Controllers
{
public class ProductUsagesController : Controller
{
private readonly IRepository<ProductUsage> productusageRepository;
public ProductUsagesController(IRepository<ProductUsage> productusageRepository)
{
this.productusageRepository = productusageRepository;
}
public ViewResult Index()
{
return View(productusageRepository.All.ToList());
}
public ViewResult Show(int id)
{
return View(productusageRepository.Find(id));
}
public ActionResult New()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public ActionResult Create(ProductUsage productusage)
{
if (ModelState.IsValid) {
productusageRepository.InsertOrUpdate(productusage);
productusageRepository.Save();
this.FlashInfo("The product usage was successfully created.");
return RedirectToAction("Index");
} else {
this.FlashError("There was a problem creating the product usage.");
return View("New", productusage);
}
}
public ActionResult Edit(int id)
{
return View(productusageRepository.Find(id));
}
[HttpPut, ValidateAntiForgeryToken, ValidateInput(false)]
public ActionResult Update(ProductUsage productusage)
{
if (ModelState.IsValid) {
productusageRepository.InsertOrUpdate(productusage);
productusageRepository.Save();
this.FlashInfo("The product usage was successfully saved.");
return RedirectToAction("Index");
} else {
this.FlashError("There was a problem saving the product usage.");
return View("Edit", productusage);
}
}
public ActionResult Delete(int id)
{
productusageRepository.Delete(id);
productusageRepository.Save();
this.FlashInfo("The product usage was successfully deleted.");
return RedirectToAction("Index");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace CarShed
{
public partial class details : System.Web.UI.Page
{
Connection obj =new Connection();
String s;
String q;
DataSet g = new DataSet();
int a = 0;
protected void Page_Load(object sender, EventArgs e)
{
g = obj.Data_inventer(" Select max(bid) from buydetails");
s = g.Tables[0].Rows[0].ItemArray[0].ToString();
a = Convert.ToInt32(s);
a++;
q = Request.QueryString["cid"].ToString();
//T1.Text = Session["abcd"].ToString();
//e = T1.Text;
}
protected void buy_Click(object sender, EventArgs e)
{
obj.InsUpDel("Insert into buydetails('"+a+"')");
obj.InsUpDel("Update buydetails set Uid='Uid' where bid='"+a+"' select Uid from one where Email='" +e+ "'");
//obj.InsUpDel("Update buydetails set cid='cid', pic= 'picone', cname='cname', cmaker='cmaker', tprice='price' where bid='"+a+"' select cid, pic, cname, cmaker, price from cardetails where cid='" + q + "'");
Response.Redirect("cart.aspx", false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ResumeEditor.Models
{
public class UTorrent
{
private string _title;
private string _resumePath;
public string Title
{
get { return _title; }
set { _title = value; }
}
public string ResumePath
{
get { return _resumePath; }
set { _resumePath = value; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace renameAll
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("usage : renameAll [action] -o <string to replace> -n <new string> [options]");
Console.WriteLine();
Console.WriteLine("list of actions : ");
Console.WriteLine("\t -a \t\t rename files and directories");
Console.WriteLine("\t -f \t\t rename files ");
Console.WriteLine("\t -d \t\t rename directories ");
Console.WriteLine();
Console.WriteLine("specify a pattern for the target files");
Console.WriteLine("\t -pf \t\t pattern for the affected files ");
Console.WriteLine("\t -pd \t\t pattern for the affected directories ");
Console.WriteLine();
Console.WriteLine("specify the path of the target directory");
Console.WriteLine("\t -p \t\t path of the directory ");
return ;
}
var oldString = getArg("-o" , "",args) ;
var newString = getArg("-n" , oldString ,args) ;
var pattern = getArg("-pf" , "*",args) ;
var patternd = getArg("-pd","*",args);
var path = getArg("-p",".",args) ;
var target = "-a" ;
if(Array.IndexOf(args , "-d") > -1 ){
target = "-d" ;
}
if(Array.IndexOf(args , "-f") > -1 ){
target = "-f" ;
}
switch (target)
{
case "-a" :
renameDir(path, oldString, newString, patternd);
renameFiles(path, oldString, newString, pattern);
break;
case "-d":
renameDir(path, oldString, newString, patternd);
break;
case "-f":
renameFiles(path, oldString, newString, pattern);
break;
}
Console.WriteLine("DONE !");
Console.WriteLine("Happy Hacking :)");
}
static void renameDir(string dir , string old, string newName, string pattern)
{
var dirs = Directory.GetDirectories(dir, pattern , SearchOption.TopDirectoryOnly);
foreach (var d in dirs)
{
var paths = d.Split(Path.PathSeparator);
paths[paths.Length-1] = paths[paths.Length-1].Replace(old, newName);
var newd = string.Join(""+Path.PathSeparator, paths);
if (!newd.Equals(d))
Directory.Move(d, newd);
renameDir(newd, old, newName, pattern);
}
}
static void renameFiles(string dir ,string old , string newName , string pattern){
var files = Directory.GetFiles(dir, pattern, SearchOption.AllDirectories);
foreach (var f in files)
{
var paths = f.Split(Path.PathSeparator);
paths[paths.Length - 1] = paths[paths.Length - 1].Replace(old, newName);
var newf = string.Join("" + Path.PathSeparator, paths);
if(!newf.Equals(f))
Directory.Move(f, newf);
}
}
static string getArg(string cmd,string defaultVal , string[] args)
{
var p = Array.IndexOf(args,cmd);
if (p > -1 && p < args.Length - 1)
{
var pattern = args[p + 1];
if (pattern.IndexOf('-') != 0)
{
return pattern;
}
}
return defaultVal;
}
}
}
|
using System;
using System.Collections.Generic;
using EventFeed.Consumer.EventFeed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace EventFeed.Consumer.Infrastructure
{
internal class EventDispatcher: IEventDispatcher
{
public void Dispatch(Event @event, Action markEventAsProcessed)
{
_logger.LogDebug("Dispatching event {Id}", @event.Id);
var deserializedEvent = Deserialize();
if (deserializedEvent == null)
{
_logger.LogDebug("Unrecognized event type {Type}. Message will be skipped.", @event.Type);
markEventAsProcessed();
return;
}
using (var scope = _serviceProvider.CreateScope())
{
Type handlerType = GetHandlerType();
object handler = scope.ServiceProvider.GetRequiredService(handlerType);
dynamic handlerAsDynamic = handler;
dynamic eventAsDynamic = deserializedEvent;
handlerAsDynamic.HandleEvent(eventAsDynamic);
_logger.LogDebug("Dispatched event {Id} of type {Type}", @event.Id, @event.Type);
markEventAsProcessed();
}
object? Deserialize()
{
var type = GetEventType();
if (type == null)
return null;
return JsonConvert.DeserializeObject(@event.Payload, type);
}
Type GetEventType()
{
if (!_contentTypeMapping.TryGetValue(@event.Type, out var type))
throw new Exception($"Cannot find type for content type '{@event.Type}'.");
return type!;
}
Type GetHandlerType()
{
var type = GetEventType();
return typeof(IEventHandler<>).MakeGenericType(type);
}
}
public EventDispatcher(
IServiceProvider serviceProvider,
IReadOnlyDictionary<string, Type> contentTypeMapping,
ILogger<EventDispatcher> logger
)
{
_serviceProvider = serviceProvider;
_contentTypeMapping = contentTypeMapping;
_logger = logger;
}
private readonly IServiceProvider _serviceProvider;
private readonly IReadOnlyDictionary<string, Type> _contentTypeMapping;
private readonly ILogger<EventDispatcher> _logger;
}
}
|
using UnityEngine;
using System.Collections;
public class Pig : MonoBehaviour {
public float Speed = 3.0f;
public AudioClip DeathSound;
private Transform myTransform;
// Use this for initialization
void Start ()
{
this.myTransform = this.GetComponent<Transform>();
}
// Update is called once per frame
void Update ()
{
if (GameManager.Instance.IsPaused) return;
this.myTransform.Translate(Vector3.left * Speed * Time.deltaTime);
}
void Kill()
{
this.gameObject.SetActive(false);
}
void SmashPig()
{
GameManager.Instance.AddPig();
AudioSource.PlayClipAtPoint(DeathSound, Camera.main.transform.position, 0.10f);
BurgerPool.Instance.SpawnBurger(this.myTransform.position);
this.gameObject.SetActive(false);
}
}
|
using Atc.Collections;
using Xunit;
namespace Atc.Tests.Collections
{
public class ConcurrentHashSetTests
{
[Fact]
public void GetEnumerator()
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
var actual = list.GetEnumerator();
// Assert
Assert.Equal(0, actual.Current);
list.Dispose();
}
[Theory]
[InlineData(true, 27)]
public void TryAdd(bool expected, int input)
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
var actual = list.TryAdd(input);
// Assert
Assert.Equal(expected, actual);
list.Dispose();
}
[Theory]
[InlineData(false, 27)]
public void TryRemove(bool expected, int input)
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
var actual = list.TryRemove(input);
// Assert
Assert.Equal(expected, actual);
list.Dispose();
}
[Theory]
[InlineData(false, 27)]
public void Contains(bool expected, int input)
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
var actual = list.Contains(input);
// Assert
Assert.Equal(expected, actual);
list.Dispose();
}
[Fact]
public void Clear()
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
list.Clear();
// Assert
Assert.Empty(list);
list.Dispose();
}
[Theory]
[InlineData(0, 27)]
public void FirstOrDefault(int expected, int input)
{
// Arrange
var list = new ConcurrentHashSet<int>();
// Act
var actual = list.FirstOrDefault(x => x == input);
// Assert
Assert.Equal(expected, actual);
list.Dispose();
}
}
} |
namespace Fingo.Auth.Domain.Projects.Interfaces
{
public interface IDeleteProject
{
void Invoke(int id);
}
} |
namespace Ach.Fulfillment.Shared.Reflection
{
using System;
using System.Reflection;
public abstract class ReflectMember<T> where T : Attribute
{
protected MemberInfo MemberInfo;
public ReflectMember(T reflectAttribute, MemberInfo memberInfo)
{
this.ReflectAttribute = reflectAttribute;
this.MemberInfo = memberInfo;
}
public T ReflectAttribute { get; private set; }
public abstract Type Type { get; }
public string MemberName
{
get
{
return this.MemberInfo.Name;
}
}
public abstract void SetValue(object instance, object value);
public abstract object GetValue(object instance);
}
}
|
using System.Net;
namespace AxiEndPoint.EndPointClient
{
public class EndPointParameters
{
public IPEndPoint IPEndPoint { get; set; }
public bool Compress { get; set; }
public bool Crypt { get; set; }
public byte[] CryptKey { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exam
{
class Program
{
static void Main(string[] args)
{
var bombEffects = new Queue<int>(Console.ReadLine().Split( ", ",
StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse));
var bombCasings = new Stack<int>(Console.ReadLine().Split(", ",
StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse));
var bombPouch = new Dictionary<string, int>()
{
{"Datura Bombs", 0},
{"Cherry Bombs", 0},
{"Smoke Decoy Bombs", 0},
};
while (true)
{
if (bombPouch.All(x => x.Value >= 3))
{
Console.WriteLine("Bene! You have successfully filled the bomb pouch!");
break;
}
if (!bombCasings.Any() || !bombEffects.Any())
{
Console.WriteLine("You don't have enough materials to fill the bomb pouch.");
break;
}
var bombEff = bombEffects.Peek();
var bombCas = bombCasings.Peek();
var sum = bombEff + bombCas;
if (sum == 40)
{
bombPouch["Datura Bombs"]++;
bombEffects.Dequeue();
bombCasings.Pop();
}
else if (sum == 60)
{
bombPouch["Cherry Bombs"]++;
bombEffects.Dequeue();
bombCasings.Pop();
}
else if (sum == 120)
{
bombPouch["Smoke Decoy Bombs"]++;
bombEffects.Dequeue();
bombCasings.Pop();
}
else
{
bombCasings.Push(bombCasings.Pop() - 5);
}
}
if (bombEffects.Any())
{
Console.WriteLine($"Bomb Effects: {String.Join(", ",bombEffects)}");
}
else
{
Console.WriteLine($"Bomb Effects: empty");
}
if (bombCasings.Any())
{
Console.WriteLine($"Bomb Casings: {String.Join(", ", bombCasings)}");
}
else
{
Console.WriteLine($"Bomb Casings: empty");
}
foreach (var bomb in bombPouch.OrderBy(x => x.Key))
{
Console.WriteLine($"{bomb.Key}: {bomb.Value}");
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Collections.Generic;
using Aquamonix.Mobile.Lib.Database;
using Aquamonix.Mobile.Lib.Utilities;
namespace Aquamonix.Mobile.Lib.Domain
{
[DataContract]
public class User : ICloneable
{
[IgnoreDataMember]
public static User Current
{
get { return UserCache.CurrentUser;}
set { UserCache.CurrentUser = value; }
}
[IgnoreDataMember]
public bool HasConfig
{
get
{
return (!String.IsNullOrEmpty(this.Username) && !String.IsNullOrEmpty(this.Password) && !String.IsNullOrEmpty(this.ServerUri));
}
}
[DataMember]
public string Username { get; set;}
[DataMember]
public string Password { get; set; }
[DataMember]
public string ServerUri { get; set; }
[DataMember]
public string SessionId { get; set;}
[DataMember]
public string Name { get; set; }
//NOTUSED
[DataMember]
public ItemsDictionary<DeviceAccess> DevicesAccess { get; set; }
public User()
{
}
public void Save()
{
UserCache.Save();
}
public object Clone()
{
User clone = new User()
{
Password = this.Password,
Username = this.Username,
ServerUri = this.ServerUri,
SessionId = this.SessionId,
DevicesAccess = this.DevicesAccess,
Name = this.Name
};
return clone;
}
public void Clear()
{
this.Username = null;
this.Password = null;
this.Name = null;
this.SessionId = null;
this.ServerUri = null;
}
}
}
|
namespace SuperMario.Entities.Mario.MarioCondition
{
public enum PlayerCondition
{
Dead,
Small,
Super,
Fire,
StarSmall,
StarSuper,
StarFire
}
}
|
using System;
using WorkScheduleManagement.Data.Entities.Users;
namespace WorkScheduleManagement.Data.Entities.Requests
{
public class VacationRequest : Request
{
public VacationTypes VacationType { get; set; }
public ApplicationUser Replacer { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public bool IsShifting { get; set; }
}
} |
using Teste_CRUD_CiaTecnica.Domain.Entities;
namespace Teste_CRUD_CiaTecnica.Domain.Interfaces.Services
{
public interface IPessoaJuridicaService : IServiceBase<PessoaJuridica>
{
bool CNPJJaExiste(string cnpj);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MyWebApplication.Models.CatViewModels;
namespace MyWebApplication.Controllers
{
/*
* Start off by creating the backend logic which allows you to access the views via browser.
* To add a controller go to Solution explorer -> right click controllers folder -> Add -> Controller... -> click Add button
* Note that name of the controller matters. The link that you will access the controllers actions, depend on controller name. If necessary, you can set up custom routing
to be able to map the URL you wish to a specific controller action.
* Create a controller action to be able to view your page in the browser. If no data needs to be passed, a simple [return View();] as body of the action will do it.
* If data needs to be passed, as seen in the actions of the current controller, simply add them as View() method parameters.
* Action names do matter as well. The default URL mapping to controller action follows these rules -> localhost:[port]/{controller name - "Controller"}/{Action name}
* You should replicate the location of the view to match the location of the controller. Index action finds its view because the path for both view and controller are similar.
The path for Controller is Controllers/Cats/CatsController.cs. The path for the index view is Views/Cats/Index.cshtml. As you may have noticed the view name should match the controller's
action name.
* If it is necessary you can explictly specify which view the controller action needs to load by passing a string parameter as seen in Cat action.
* Continue to View/Cats/Index.cshml for further tips.
*/
public class CatsController : Controller
{
List<Cat> Cats = new List<Cat>()
{
new Cat()
{
Id = Guid.Parse("dcf62269-cf01-4551-9c32-3a618e497ab2"),
Title = "Cat in a bottle",
Description = "I R Cat in ze bottle. Fear my mighty meow!",
ImageSmallUrl = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQjWLw32X5V5KD5t6wsUBNlqsyQJ5EGd6THd0iVoYwrRQ_UHdAq3g",
ImageUrl = "http://monorailcat.com/wp-content/uploads/2014/10/funny-liquid-cats-17.jpg"
},
new Cat()
{
Id = Guid.Parse("eec1932d-ed54-4470-a933-7da79cfd3dd0"),
Title = "Dune cat",
Description = "I are dunecat. I controls the spice. I controls the universe.",
ImageSmallUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRVfElsnM1hTkVb1mql0-IL6mwLijp2MdzGL4cQyPbAqIy1rKDN",
ImageUrl = "http://cdn2-www.cattime.com/assets/uploads/gallery/25-funny-cat-memes/021-FUNNY-CAT-MEME.jpg"
},
new Cat()
{
Id = Guid.Parse("74dccaf8-9da6-47af-a828-58bda356731b"),
Title = "Joker cat",
Description = "Why so serious, son?!",
ImageSmallUrl = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQt76lWT_eRGMPr47W8o3L4JZLASmGPD7_jc6r34tIt70EpvFOH",
ImageUrl = "http://4.bp.blogspot.com/-C13G0vT9dy0/VnmoRVk7ldI/AAAAAAAACTs/DzKad8c2dAI/s640/funny-cat-pictures-027-021.jpg"
},
};
public ActionResult Index()
{
List<CatListViewModel> catsList = new List<CatListViewModel>();
foreach (Cat cat in Cats)
{
catsList.Add(new CatListViewModel() { Id = cat.Id, Title = cat.Title, ImageUrl = cat.ImageSmallUrl });
}
return View(catsList); /* catsList parameter is passed to View() method. This list will be available in the Model property inside the view. */
}
public ActionResult Cat(Guid catId)
{
Cat selectedCat = Cats.Single(item => item.Id == catId);
CatDetailsViewModel catViewModel = new CatDetailsViewModel()
{
Description = selectedCat.Description,
ImageUrl = selectedCat.ImageUrl,
Title = selectedCat.Title
};
return View("~/Views/Cats/Cat.cshtml", catViewModel); /* Explicitly specified view. It would work without the first string parameter, too!*/
}
}
public class Cat
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ImageSmallUrl { get; set; }
public string ImageUrl { get; set; }
}
} |
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector.Integration.ServiceCollection
{
using System;
using Microsoft.Extensions.DependencyInjection;
internal class DefaultServiceProviderAccessor : IServiceProviderAccessor
{
private readonly Container container;
private InstanceProducer? serviceScopeProducer;
internal DefaultServiceProviderAccessor(Container container)
{
this.container = container;
}
public IServiceProvider Current => this.CurentServiceScope.ServiceProvider;
private IServiceScope CurentServiceScope
{
get
{
if (this.serviceScopeProducer is null)
{
this.serviceScopeProducer = this.container.GetRegistration(typeof(IServiceScope), true)!;
}
try
{
// This resolved IServiceScope will be cached inside a Simple Injector Scope and will be
// disposed of when the scope is disposed of.
return (IServiceScope)this.serviceScopeProducer.GetInstance();
}
catch (Exception ex)
{
var lifestyle = this.container.Options.DefaultScopedLifestyle;
// PERF: Since GetIstance() checks the availability of the scope itself internally, we
// would be duplicating the check (and duplicate the local storage access call). Doing
// this inside the catch, therefore, prevents having to do the check on every resolve.
if (Lifestyle.Scoped.GetCurrentScope(this.container) is null)
{
throw new ActivationException(
"You are trying to resolve a cross-wired service, but are doing so outside " +
$"the context of an active ({lifestyle?.Name}) scope. To be able to resolve " +
"this service the operation must run in the context of such scope. " +
"Please see https://simpleinjector.org/scoped for more information about how " +
"to manage scopes.", ex);
}
else
{
throw;
}
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.EmployeeManagerService;
namespace WebApi.Controllers
{
[RoutePrefix("Employee")]
public class EmployeeManagerController : ApiController
{
EmployeeManagerClient emc = new EmployeeManagerClient();
[Route("GetAll")]
[HttpGet]
public Employee[] GetAllEmployee()
{
return emc.GetAllEmployee();
}
[Route("GetById")]
[HttpGet]
public Employee GetEmployeeById(int id)
{
return emc.GetEmployeeById(id);
}
[Route("Insert")]
[HttpPost]
public void Insert([FromBody]Employee emp)
{
emc.Insert(emp);
}
[Route("Update")]
[HttpPut]
public void Update([FromBody]Employee emp)
{
emc.Update(emp);
}
[Route("Delete")]
[HttpPut]
public void Delete(int id)
{
emc.Delete(id);
}
}
}
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
namespace HTTPServer
{
public class HTTPSession
{
System.Net.HttpListener httpListener = null;
System.Net.HttpListenerRequest httpRequest = null;
System.Net.HttpListenerResponse httpResponse = null;
System.Net.HttpListenerContext httpContext = null;
// 建構函式
public HTTPSession(HttpListener httpListener)
{
this.httpListener = httpListener;
}
public void HTTPSessionThread()
{
while (true)
{
try
{
// 以HttpListener類別的GetContext方法等待傳入之用戶端請求
httpContext = httpListener.GetContext();
// Set Thread for each HTTP client Connection
Thread clientThread = new Thread(new ThreadStart(this.processRequest));
clientThread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
}
private void processRequest()
{
// Set WWW Root Path
string rootPath = Directory.GetCurrentDirectory() + "\\WWWRoot\\";
// Set default page
string defaultPage = "index.html";
try
{
// 以Request屬性取得HTTP伺服端的輸入串流,則用戶端之請求
httpRequest = httpContext.Request;
//
// 顯示HttpListenerRequest類別的屬性取得HTTP請求之相關內容
//
// 用戶端所能接受的MIME類型
string[] types = httpRequest.AcceptTypes;
if (types != null)
{
Console.WriteLine("用戶端所能接受的MIME類型:");
foreach (string type in types)
{
Console.WriteLine(" {0}", type);
}
}
// Content Length
Console.WriteLine("Content Length {0}", httpRequest.ContentLength64);
// Content Type
if (httpRequest.ContentType != null)
{
Console.WriteLine("Content Type {0}", httpRequest.ContentType);
}
// Cookie
foreach (Cookie cookie in httpRequest.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine(" {0} = {1}", cookie.Name, cookie.Value);
Console.WriteLine(" 網域屬性: {0}", cookie.Domain);
Console.WriteLine(" 有效期限: {0} (expired? {1})", cookie.Expires, cookie.Expired);
Console.WriteLine(" URI路徑屬性: {0}", cookie.Path);
Console.WriteLine(" 通訊埠: {0}", cookie.Port);
Console.WriteLine(" 安全層級: {0}", cookie.Secure);
Console.WriteLine(" 發出的時間: {0}", cookie.TimeStamp);
Console.WriteLine(" 版本: RFC {0}", cookie.Version == 1 ? "2109" : "2965");
Console.WriteLine(" 內容: {0}", cookie.ToString());
}
// 用戶端所傳送資料內容的標題資訊
System.Collections.Specialized.NameValueCollection headers = httpRequest.Headers;
foreach (string key in headers.AllKeys)
{
string[] values = headers.GetValues(key);
if (values.Length > 0)
{
Console.WriteLine("用戶端所傳送資料內容的標題資訊:");
foreach (string value in values)
{
Console.WriteLine(" {0}", value);
}
}
}
Console.WriteLine("HTTP通訊協定方法: {0}", httpRequest.HttpMethod);
Console.WriteLine("HTTP請求是否自本機送出? {0}", httpRequest.IsLocal);
Console.WriteLine("是否保持持續性連結: {0}", httpRequest.KeepAlive);
Console.WriteLine("Local End Point: {0}", httpRequest.LocalEndPoint.ToString());
Console.WriteLine("Remote End Point: {0}", httpRequest.RemoteEndPoint.ToString());
Console.WriteLine("HTTP通訊協定的版本: {0}", httpRequest.ProtocolVersion);
Console.WriteLine("URL: {0}", httpRequest.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", httpRequest.RawUrl);
Console.WriteLine("Query: {0}", httpRequest.QueryString);
Console.WriteLine("Referred by: {0}", httpRequest.UrlReferrer);
//
// End of 顯示HttpListenerRequest類別的屬性取得HTTP請求之相關內容
//
// 取得相對URL
string url = httpRequest.RawUrl;
if (url.StartsWith("/"))
url = url.Substring(1);
if (url.EndsWith("/") || url.Equals(""))
url = url + defaultPage;
string request = rootPath + url;
sendHTMLResponse(request);
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.StackTrace.ToString());
}
}
// Send HTTP Response
private void sendHTMLResponse(string request)
{
try
{
// Get the file content of HTTP Request
FileStream fs = new FileStream(request, FileMode.Open, FileAccess.Read, FileShare.None);
BinaryReader br = new BinaryReader(fs);
// The content Length of HTTP Request
byte[] respByte = new byte[(int)fs.Length];
br.Read(respByte, 0, (int)fs.Length);
br.Close();
fs.Close();
// 以Response屬性取得HTTP伺服端的輸出串流,則HTTP伺服端之回應
httpResponse = httpContext.Response;
// HTTP回應資料內容的大小
httpResponse.ContentLength64 = respByte.Length;
// HTTP回應資料內容的MIME格式
httpResponse.ContentType = getContentType(request);
// 取得伺服端HTTP回應之資料串流
System.IO.Stream output = httpResponse.OutputStream;
// 回應HTML網頁內容至用戶端瀏覽器
output.Write(respByte, 0, respByte.Length);
output.Close();
httpResponse.Close();
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.StackTrace.ToString());
if (httpResponse != null)
httpResponse.Close();
}
}
// MIME: Get Content Type
private string getContentType(string request)
{
if (request.EndsWith("html"))
return "text/html";
else if (request.EndsWith("htm"))
return "text/html";
else if (request.EndsWith("txt"))
return "text/plain";
else if (request.EndsWith("gif"))
return "image/gif";
else if (request.EndsWith("jpg"))
return "image/jpeg";
else if (request.EndsWith("jpeg"))
return "image/jpeg";
else if (request.EndsWith("pdf"))
return "application/pdf";
else if (request.EndsWith("pdf"))
return "application/pdf";
else if (request.EndsWith("doc"))
return "application/msword";
else if (request.EndsWith("xls"))
return "application/vnd.ms-excel";
else if (request.EndsWith("ppt"))
return "application/vnd.ms-powerpoint";
else
return "text/plain";
}
}
} |
using UnityEngine;
using UnityEngine.U2D;
using System.Collections;
using System.Collections.Generic;
using MoreMountains.Tools;
using MoreMountains.MMInterface;
using MoreMountains.Feedbacks;
namespace MoreMountains.CorgiEngine
{
/// Teleporter with Pixel Perfect Camera pixel per unit custom value, allows you to simulate zooms on selected rooms (i.e. entering a little room)
/// v1.0 / Muppo (2020)
public class TeleporterWithZoom : Teleporter
{
[Header("Extra Settings")]
public Camera _mainCamera;
public int _pixelPerUnit;
protected PixelPerfectCamera _pixelPerfect;
///
protected override void Awake()
{
_pixelPerfect = _mainCamera.GetComponent<PixelPerfectCamera>();
base.Awake();
}
///
protected override void TeleportCollider(Collider2D collider)
{
_pixelPerfect.assetsPPU = _pixelPerUnit;
base.TeleportCollider(collider);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public GameObject menu;
public GameObject creditsmenu;
public GameObject controlsmenu;
public void entercredits()
{
menu.SetActive(false);
creditsmenu.SetActive(true);
}
public void exitcredits()
{
menu.SetActive(true);
creditsmenu.SetActive(false);
}
public void entercontrolsmenu()
{
menu.SetActive(false);
controlsmenu.SetActive(true);
}
public void exitcontrolsmenu()
{
menu.SetActive(true);
controlsmenu.SetActive(false);
}
public void enterGame()
{
Debug.Log("game time");
SceneManager.LoadScene(1);
}
public void exitGame()
{
Debug.Log("game over");
Application.Quit();
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Winter.Component
{
public class Tasks : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string message)
{
var data = await Task.Run(() => 1 == 1);
return View("Default", message);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fix : MonoBehaviour {
private bool fix = false;
public GameObject Player;
public GameObject FixOn;
Rigidbody2D rb;
public Sprite[] SpritesCount;
public int fixCount = 2;
// Use this for initialization
void Start () {
rb = Player.GetComponent<Rigidbody2D>();
GameObject.Find("FixCount").GetComponent<SpriteRenderer>().sprite = SpritesCount[fixCount];
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.F))
{
FIX();
}
}
public void FIX()
{
if (fix == false)
{
if (fixCount > 0)
{
fixCount--;
fix = !fix;
gameObject.GetComponent<Animation>().Play("To Fix");
StartCoroutine(AwaitFIX());
rb.velocity = new Vector2(0, 0);
rb.angularVelocity = 0;
rb.isKinematic = true;
FixOn.SetActive(true);
//GameObject.Find("Pause").GetComponent<AudioSource>().Play();
}
}
else
{
fix = !fix;
GameObject.Find("Fix").GetComponent<Animation>().Play("From Fix");
rb.isKinematic = false;
FixOn.SetActive(false);
//GameObject.Find("Continue").GetComponent<AudioSource>().Play();
}
}
public void refreshFix()
{
GameObject.Find("FixCount").GetComponent<SpriteRenderer>().sprite = SpritesCount[fixCount];
}
IEnumerator AwaitFIX()
{
yield return new WaitForSeconds(0.165f);
GameObject.Find("FixCount").GetComponent<SpriteRenderer>().sprite = SpritesCount[fixCount];
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebAppMedOffices.Models
{
[Table("TipoEnfermedades")]
public class TipoEnfermedad
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[MaxLength(50, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Index("Consultorio_Nombre_Index", IsUnique = true)]
[Display(Name = "Tipo")]
public string Nombre { get; set; }
public virtual ICollection<Enfermedad> Enfermedades { get; set; }
}
} |
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* 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.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Clifton.Core.Assertions;
using Clifton.Core.ExtensionMethods;
using Clifton.Core.Semantics;
using Clifton.Core.ModuleManagement;
using Clifton.Core.ServiceInterfaces;
using Clifton.Core.ServiceManagement;
namespace MeaningExplorer
{
public class AppConfigDecryption : ServiceBase, IAppConfigDecryptionService
{
public string Password { get; set; }
public string Salt { get; set; }
public string Decrypt(string text)
{
return text.Decrypt(Password, Salt);
}
}
static partial class Program
{
public static ServiceManager serviceManager;
static ServiceManager Bootstrap()
{
serviceManager = new ServiceManager();
serviceManager.RegisterSingleton<IServiceModuleManager, ServiceModuleManager>();
serviceManager.RegisterSingleton<IAppConfigDecryptionService, AppConfigDecryption>(d =>
{
d.Password = "abc!@1234";
d.Salt = "91827465";
});
try
{
IModuleManager moduleMgr = (IModuleManager)serviceManager.Get<IServiceModuleManager>();
List<AssemblyFileName> modules = GetModuleList(XmlFileName.Create("modules.xml"));
moduleMgr.RegisterModules(modules); //, OptionalPath.Create("dll"));
List<Exception> exceptions = serviceManager.FinishSingletonInitialization();
ShowAnyExceptions(exceptions);
}
catch (Exception ex)
{
Console.WriteLine("Initialization Error: " + ex.Message);
}
return serviceManager;
}
/// <summary>
/// Return the list of assembly names specified in the XML file so that
/// we know what assemblies are considered modules as part of the application.
/// </summary>
static private List<AssemblyFileName> GetModuleList(XmlFileName filename)
{
Assert.That(File.Exists(filename.Value), "Module definition file " + filename.Value + " does not exist.");
XDocument xdoc = XDocument.Load(filename.Value);
return GetModuleList(xdoc);
}
/// <summary>
/// Returns the list of modules specified in the XML document so we know what
/// modules to instantiate.
/// </summary>
static private List<AssemblyFileName> GetModuleList(XDocument xdoc)
{
List<AssemblyFileName> assemblies = new List<AssemblyFileName>();
(from module in xdoc.Element("Modules").Elements("Module")
select module.Attribute("AssemblyName").Value).ForEach(s => assemblies.Add(AssemblyFileName.Create(s)));
return assemblies;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace UnityAtoms.Tags
{
/// <summary>
/// This is an `IList` without everything that could mutate the it.
/// </summary>
/// <typeparam name="T">The type of the list items.</typeparam>
public class ReadOnlyList<T> : IEnumerable<T>
{
/// <summary>
/// Get the number of elements contained in the `ReadOnlyList<T>`.
/// </summary>
/// <value>The number of elements contained in the `ReadOnlyList<T>`.</value>
/// <example>
/// <code>
/// var readOnlyList = new ReadOnlyList<int>(new List<int>() { 1, 2, 3 });
/// Debug.Log(readOnlyList.Count); // Outputs: 3
/// </code>
/// </example>
public int Count { get => _referenceList.Count; }
/// <summary>
/// Determines if the `ReadOnlyList<T>` is read only or not.
/// </summary>
/// <value>Will always be `true`.</value>
public bool IsReadOnly { get => true; }
/// <summary>
/// Get the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <value>The element at the specified index.</value>
public T this[int index] { get => _referenceList[index]; }
private readonly IList<T> _referenceList = null;
/// <summary>
/// Creates a new class of the `ReadOnlyList<T>` class.
/// </summary>
/// <param name="list">The `IList<T>` to initialize the `ReadOnlyList<T>` with.</param>
public ReadOnlyList(IList<T> list)
{
_referenceList = list;
}
#region IEnumerable<T>
/// <summary>
/// Implements `GetEnumerator()` of `IEnumerable<T>`
/// </summary>
/// <returns>The list's `IEnumerator<T>`.</returns>
public IEnumerator<T> GetEnumerator()
{
return _referenceList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Determines whether an element is in the `ReadOnlyList<T>`.
/// </summary>
/// <param name="item">The item to check if it exists in the `ReadOnlyList<T>`.</param>
/// <returns>`true` if item is found in the `ReadOnlyList<T>`; otherwise, `false`.</returns>
public bool Contains(T item)
{
return _referenceList.Contains(item);
}
/// <summary>
/// Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.
/// </summary>
/// <param name="item">The one-dimensional array to search.</param>
/// <returns>The index of the first occurrence of value in array, if found; otherwise, the lower bound of the array minus 1.</returns>
public int IndexOf(T item)
{
return _referenceList.IndexOf(item);
}
/// <summary>
/// Copies all the elements of the current one-dimensional array to the specified one-dimensional array starting at the specified destination array index. The index is specified as a 32-bit integer.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the elements copied from the current array.</param>
/// <param name="arrayIndex">A 32-bit integer that represents the index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_referenceList.CopyTo(array, arrayIndex);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class initPos : MonoBehaviour
{
public Slider _slider;
public GameObject _bottle;
public Text _textPorcent;
public Text _textObjet;
private Camera _cam;
void Start()
{
_cam = Camera.main;
}
void Update()
{
Vector3 position1 = _cam.transform.position;
float _largeur = Screen.width;
float _hauteur = Screen.height;
_slider.transform.localPosition = new Vector3(0, 7.1f, -5);
_textPorcent.transform.localPosition = new Vector3(17, 6.8f, -5);
_textObjet.transform.localPosition = new Vector3(30, -8, -5);
_bottle.transform.localPosition = new Vector3(-20, 7, 0);
_slider.transform.localScale = new Vector3(0.2f, 0.2f, 1);
_textObjet.transform.localScale = new Vector3(0.1f, 0.1f, 1);
_bottle.transform.localScale = new Vector3(0.7f, 0.5f, 1);
}
}
|
using Microsoft.Extensions.Configuration;
using System.IO;
namespace RakutenVoucherDownload.Infra.CrossCutting.IoC
{
public class Configuracoes
{
public string UrlToken { get; set; }
public string UrlCoupon { get; set; }
public string CaminhoXML { get; set; }
public string Authorization { get; set; }
public Configuracoes()
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
UrlToken = config.GetSection("TokenRakuten:UrlToken").Value;
Authorization = config.GetSection("TokenRakuten:Authorization").Value;
UrlCoupon = config.GetSection("TokenRakuten:UrlCoupon").Value;
CaminhoXML = config.GetSection("TokenRakuten:CaminhoXML").Value;
}
}
}
|
using System;
namespace OperatorOverloading
{
public class Demo5
{
public static void Run()
{
Point p1 = new Point(100, 100);
Point p2 = new Point(40, 40);
Console.WriteLine("p1 > p2: {0}", p1 > p2);
Console.WriteLine("p1 < p2: {0}", p1 < p2);
Console.WriteLine("p1 >= p2: {0}", p1 >= p2);
Console.WriteLine("p1 <= p2: {0}", p1 <= p2);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Attendance
{
public partial class frm_Backup : Form
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
OpenFileDialog ofd = new OpenFileDialog();
public frm_Main frm_Main;
public frm_Backup()
{
InitializeComponent();
txt_Backup.Text = AppDomain.CurrentDomain.BaseDirectory + "BACKUP";
fbd.SelectedPath = txt_Backup.Text;
ofd.InitialDirectory = txt_Backup.Text;
}
private void btn_BrowseBackup_Click(object sender, EventArgs e)
{
if (fbd.ShowDialog() == DialogResult.OK)
{
txt_Backup.Text = fbd.SelectedPath;
}
}
private void btn_Backup_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(txt_Backup.Text.Trim()))
{
cls_BL.General g = new cls_BL.General();
g.BackupData();
}
else
{
MessageBox.Show("المسار غير موجود");
return;
}
}
private void btn_BrowseRestore_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
txt_Restore.Text = ofd.FileName;
}
}
private void btn_Restore_Click(object sender, EventArgs e)
{
if (System.IO.File.Exists(txt_Restore.Text.Trim()))
{
cls_BL.General g = new cls_BL.General();
g.RestoreData(txt_Restore.Text.Trim());
}
else
{
MessageBox.Show("مسار الملف غير صحيح");
return;
}
}
}
}
|
namespace NeuroLinker.Interfaces.Configuration
{
/// <summary>
/// Configuration for HttpClient
/// </summary>
public interface IHttpClientConfiguration
{
#region Properties
/// <summary>
/// The UserAgent string that should be used by the HttpClient when contacting the MAL API
/// </summary>
string UserAgent { get; }
#endregion
}
} |
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
using System;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace web_ioc
{
public static class AuthConfig
{
internal static void Setup(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["issuer"];
var validAudiences = ConfigurationManager.AppSettings["audiences"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var certificatePath = ConfigurationManager.AppSettings["certificatePath"];
var certificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certificatePath));
var key = new X509SecurityKey(certificate);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = validAudiences,
Realm = issuer,
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(issuer, certificate),
},
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
IssuerSigningKeyResolver = (a, b, c, d) => new X509SecurityKey(certificate),
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudiences = validAudiences,
ClockSkew = TimeSpan.Zero
}
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Marketplaces.Entityes;
using Welic.Dominio.Patterns.Service.Pattern;
namespace Welic.Dominio.Models.Marketplaces.Services
{
public interface IOrderService : IService<Order>
{
}
}
|
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Predictr.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Predictr.Data
{
public static class DbInitializer
{
public static void Initialize(ApplicationDbContext context)
{
//context.Database.EnsureDeleted();
//context.Database.EnsureCreated();
// create the two roles
var roleStore = new RoleStore<IdentityRole>(context);
if (!context.Roles.Any())
{
roleStore.CreateAsync(new IdentityRole("Admin"));
roleStore.CreateAsync(new IdentityRole("Player"));
}
// Look for any students.
if (!context.Teams.Any())
{
var teams = new Team[]
{
new Team { Name = "Russia" },
new Team { Name = "Egypt" },
new Team { Name = "Saudi Arabia" },
new Team { Name = "Uruguay" },
new Team { Name = "Morocco" },
new Team { Name = "Portugal" },
new Team { Name = "Iran" },
new Team { Name = "Spain" },
new Team { Name = "France" },
new Team { Name = "Argentina" },
new Team { Name = "Australia" },
new Team { Name = "Iceland" },
new Team { Name = "Peru" },
new Team { Name = "Croatia" },
new Team { Name = "Denmark" },
new Team { Name = "Nigeria" },
new Team { Name = "Costa Rica" },
new Team { Name = "Germany" },
new Team { Name = "Serbia" },
new Team { Name = "Mexico" },
new Team { Name = "Brazil" },
new Team { Name = "Sweden" },
new Team { Name = "Switzerland" },
new Team { Name = "South Korea" },
new Team { Name = "Belgium" },
new Team { Name = "Tunisia" },
new Team { Name = "Panama" },
new Team { Name = "England" },
new Team { Name = "Columbia" },
new Team { Name = "Poland" },
new Team { Name = "Japan" },
new Team { Name = "Senegal" }
};
foreach (Team t in teams)
{
context.Teams.Add(t);
}
context.SaveChanges();
}
// group fixtures
if (!context.Fixtures.Any()) {
var fixtures = new Fixture[] {
new Fixture { Group="A", Home="Russia", Away="Saudi Arabia", FixtureDateTime = Convert.ToDateTime("2018-06-14 16:00:00")},
new Fixture { Group="A", Home="Egypt", Away="Uruguay", FixtureDateTime = Convert.ToDateTime("2018-06-15 13:00:00")},
new Fixture { Group="B", Home="Morocco", Away="Iran", FixtureDateTime = Convert.ToDateTime("2018-06-15 16:00:00")},
new Fixture { Group="B", Home="Portugal", Away="Spain", FixtureDateTime = Convert.ToDateTime("2018-06-15 19:00:00")},
new Fixture { Group="C", Home="France", Away="Australia", FixtureDateTime = Convert.ToDateTime("2018-06-16 11:00:00")},
new Fixture { Group="D", Home="Argentina", Away="Iceland", FixtureDateTime = Convert.ToDateTime("2018-06-16 14:00:00")},
new Fixture { Group="C", Home="Peru", Away="Denmark", FixtureDateTime = Convert.ToDateTime("2018-06-16 17:00:00")},
new Fixture { Group="D", Home="Croatia", Away="Nigeria", FixtureDateTime = Convert.ToDateTime("2018-06-16 20:00:00")},
new Fixture { Group="E", Home="Costa Rica", Away="Serbia", FixtureDateTime = Convert.ToDateTime("2018-06-17 13:00:00")},
new Fixture { Group="F", Home="Germany", Away="Mexico", FixtureDateTime = Convert.ToDateTime("2018-06-17 16:00:00")},
new Fixture { Group="E", Home="Brazil", Away="Switzerland", FixtureDateTime = Convert.ToDateTime("2018-06-17 19:00:00")},
new Fixture { Group="F", Home="Sweden", Away="South Korea", FixtureDateTime = Convert.ToDateTime("2018-06-18 13:00:00")},
new Fixture { Group="G", Home="Belgium", Away="Panama", FixtureDateTime = Convert.ToDateTime("2018-06-18 16:00:00")},
new Fixture { Group="G", Home="Tunisia", Away="England", FixtureDateTime = Convert.ToDateTime("2018-06-18 19:00:00")},
new Fixture { Group="H", Home="Columbia", Away="Japan", FixtureDateTime = Convert.ToDateTime("2018-06-19 13:00:00")},
new Fixture { Group="H", Home="Poland", Away="Senegal", FixtureDateTime = Convert.ToDateTime("2018-06-19 16:00:00")},
new Fixture { Group="A", Home="Russia", Away="Egypt", FixtureDateTime = Convert.ToDateTime("2018-06-19 19:00:00")},
new Fixture { Group="A", Home="Portugal", Away="Morocco", FixtureDateTime = Convert.ToDateTime("2018-06-20 13:00:00")},
new Fixture { Group="B", Home="Uruguay", Away="Saudi Arabia", FixtureDateTime = Convert.ToDateTime("2018-06-20 16:00:00")},
new Fixture { Group="B", Home="Iran", Away="Spain", FixtureDateTime = Convert.ToDateTime("2018-06-20 19:00:00")},
new Fixture { Group="C", Home="Denmark", Away="Australia", FixtureDateTime = Convert.ToDateTime("2018-06-21 13:00:00")},
new Fixture { Group="C", Home="France", Away="Peru", FixtureDateTime = Convert.ToDateTime("2018-06-21 16:00:00")},
new Fixture { Group="D", Home="Argentina", Away="Croatia", FixtureDateTime = Convert.ToDateTime("2018-06-21 19:00:00")},
new Fixture { Group="E", Home="Brazil", Away="Costa Rica", FixtureDateTime = Convert.ToDateTime("2018-06-22 13:00:00")},
new Fixture { Group="D", Home="Nigeria", Away="Iceland", FixtureDateTime = Convert.ToDateTime("2018-06-22 16:00:00")},
new Fixture { Group="E", Home="Argentina", Away="Croatia", FixtureDateTime = Convert.ToDateTime("2018-06-22 19:00:00")},
new Fixture { Group="G", Home="Belgium", Away="Tunisia", FixtureDateTime = Convert.ToDateTime("2018-06-23 13:00:00")},
new Fixture { Group="F", Home="South Korea", Away="Mexico", FixtureDateTime = Convert.ToDateTime("2018-06-23 16:00:00")},
new Fixture { Group="F", Home="Germany", Away="Sweden", FixtureDateTime = Convert.ToDateTime("2018-06-23 19:00:00")},
new Fixture { Group="G", Home="England", Away="Panama", FixtureDateTime = Convert.ToDateTime("2018-06-24 13:00:00")},
new Fixture { Group="H", Home="Japan", Away="Senegal", FixtureDateTime = Convert.ToDateTime("2018-06-24 16:00:00")},
new Fixture { Group="H", Home="Poland", Away="Columbia", FixtureDateTime = Convert.ToDateTime("2018-06-24 19:00:00")},
// match day 3:
new Fixture { Group="A", Home="Saudi Arabia", Away="Egypt", FixtureDateTime = Convert.ToDateTime("2018-06-25 15:00:00")},
new Fixture { Group="A", Home="Uruguay", Away="Russia", FixtureDateTime = Convert.ToDateTime("2018-06-25 15:00:00")},
new Fixture { Group="B", Home="Iran", Away="Portugal", FixtureDateTime = Convert.ToDateTime("2018-06-25 19:00:00")},
new Fixture { Group="B", Home="Spain", Away="Morocco", FixtureDateTime = Convert.ToDateTime("2018-06-25 19:00:00")},
new Fixture { Group="C", Home="Australia", Away="Peru", FixtureDateTime = Convert.ToDateTime("2018-06-26 15:00:00")},
new Fixture { Group="C", Home="Denmark", Away="France", FixtureDateTime = Convert.ToDateTime("2018-06-26 15:00:00")},
new Fixture { Group="D", Home="Nigeria", Away="Argentina", FixtureDateTime = Convert.ToDateTime("2018-06-26 19:00:00")},
new Fixture { Group="D", Home="Iceland", Away="Croatia", FixtureDateTime = Convert.ToDateTime("2018-06-26 19:00:00")},
new Fixture { Group="E", Home="South Korea", Away="Germany", FixtureDateTime = Convert.ToDateTime("2018-06-27 15:00:00")},
new Fixture { Group="E", Home="Mexico", Away="Sweden", FixtureDateTime = Convert.ToDateTime("2018-06-27 15:00:00")},
new Fixture { Group="F", Home="Switzerland", Away="Costa Rica", FixtureDateTime = Convert.ToDateTime("2018-06-27 19:00:00")},
new Fixture { Group="F", Home="Serbia", Away="Brazil", FixtureDateTime = Convert.ToDateTime("2018-06-26 19:00:00")},
new Fixture { Group="G", Home="Senegal", Away="Columbia", FixtureDateTime = Convert.ToDateTime("2018-06-28 15:00:00")},
new Fixture { Group="G", Home="Japan", Away="Poland", FixtureDateTime = Convert.ToDateTime("2018-06-28 15:00:00")},
new Fixture { Group="H", Home="England", Away="Belgium", FixtureDateTime = Convert.ToDateTime("2018-06-28 19:00:00")},
new Fixture { Group="H", Home="Panama", Away="Tunisia", FixtureDateTime = Convert.ToDateTime("2018-06-28 19:00:00")},
};
foreach (Fixture f in fixtures)
{
context.Fixtures.Add(f);
}
context.SaveChanges();
}
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
namespace GrubTime.Migrations
{
public partial class TableStructure : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_StarredPlaces_Profiles_ProfileId",
table: "StarredPlaces");
migrationBuilder.DropForeignKey(
name: "FK_StarredPlaces_Places_StarredPlaceId",
table: "StarredPlaces");
migrationBuilder.DropTable(
name: "Places");
migrationBuilder.DropTable(
name: "Profiles");
migrationBuilder.DropIndex(
name: "IX_StarredPlaces_ProfileId",
table: "StarredPlaces");
migrationBuilder.DropIndex(
name: "IX_StarredPlaces_StarredPlaceId",
table: "StarredPlaces");
migrationBuilder.DropColumn(
name: "ProfileId",
table: "StarredPlaces");
migrationBuilder.DropColumn(
name: "StarredPlaceId",
table: "StarredPlaces");
migrationBuilder.DropColumn(
name: "UserId",
table: "StarredPlaces");
migrationBuilder.AlterColumn<string>(
name: "PlaceId",
table: "StarredPlaces",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AddColumn<bool>(
name: "IsStarred",
table: "StarredPlaces",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<string>(
name: "UserToken",
table: "StarredPlaces",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsStarred",
table: "StarredPlaces");
migrationBuilder.DropColumn(
name: "UserToken",
table: "StarredPlaces");
migrationBuilder.AlterColumn<int>(
name: "PlaceId",
table: "StarredPlaces",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AddColumn<int>(
name: "ProfileId",
table: "StarredPlaces",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "StarredPlaceId",
table: "StarredPlaces",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "UserId",
table: "StarredPlaces",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "Places",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
IsStarred = table.Column<bool>(nullable: false),
PlaceId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Places", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Profiles",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Avatar = table.Column<string>(nullable: true),
Username = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Profiles", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_StarredPlaces_ProfileId",
table: "StarredPlaces",
column: "ProfileId");
migrationBuilder.CreateIndex(
name: "IX_StarredPlaces_StarredPlaceId",
table: "StarredPlaces",
column: "StarredPlaceId");
migrationBuilder.AddForeignKey(
name: "FK_StarredPlaces_Profiles_ProfileId",
table: "StarredPlaces",
column: "ProfileId",
principalTable: "Profiles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_StarredPlaces_Places_StarredPlaceId",
table: "StarredPlaces",
column: "StarredPlaceId",
principalTable: "Places",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab2A
{// same as posted with changes
// o REMOVE SetData - prompt the user and call appropropriate constructor that will accept all appropirtae arguments
// o REMOVE Override of ToString - Not used here
// o VALIDATE derived class data in the Concrete classes
public abstract class Shape
{
public string Type { get; protected set; } //The type of shape
public static int Count { get; private set; } //
protected const double PI = 3.141592653589793; //Constant value for pi
//All this constructor does is increment the number of Shape instances
public Shape()
{
Shape.Count++;
}
public abstract double CalculateArea(); //Calculate the Shape's area (surface area if 3-d)
public abstract double CalculateVolume(); //Calculate the Shape's volume (if 3-d)
//Retrieves the current number of Shape instances
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Jose;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
namespace Zitadel.Authentication.Credentials
{
/// <summary>
/// Application for Zitadel. An application is an OIDC application type
/// that allows a backend (for example for some single page application) api to
/// check if sent credentials from a client are valid or not.
/// </summary>
public record Application
{
/// <summary>
/// The application type.
/// </summary>
public const string Type = "application";
/// <summary>
/// The client id associated with this application.
/// </summary>
#if NET5_0_OR_GREATER
public string ClientId { get; init; } = string.Empty;
#elif NETCOREAPP3_1_OR_GREATER
public string ClientId { get; set; } = string.Empty;
#endif
/// <summary>
/// The application id.
/// </summary>
#if NET5_0_OR_GREATER
public string AppId { get; init; } = string.Empty;
#elif NETCOREAPP3_1_OR_GREATER
public string AppId { get; set; } = string.Empty;
#endif
/// <summary>
/// This is unique ID (on Zitadel) of the key.
/// </summary>
#if NET5_0_OR_GREATER
public string KeyId { get; init; } = string.Empty;
#elif NETCOREAPP3_1_OR_GREATER
public string KeyId { get; set; } = string.Empty;
#endif
/// <summary>
/// The private key generated by Zitadel for this <see cref="Application"/>.
/// </summary>
#if NET5_0_OR_GREATER
public string Key { get; init; } = string.Empty;
#elif NETCOREAPP3_1_OR_GREATER
public string Key { get; set; } = string.Empty;
#endif
/// <summary>
/// Load an <see cref="Application"/> from a file at a given (relative or absolute) path.
/// </summary>
/// <param name="pathToJson">The relative or absolute filepath to the json file.</param>
/// <returns>The parsed <see cref="Application"/>.</returns>
/// <exception cref="FileNotFoundException">When the file does not exist.</exception>
/// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception>
/// <exception cref="System.Text.Json.JsonException">
/// Thrown when the JSON is invalid,
/// the <see cref="Application"/> type is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
public static async Task<Application> LoadFromJsonFileAsync(string pathToJson)
{
var path = Path.GetFullPath(
Path.IsPathRooted(pathToJson)
? pathToJson
: Path.Join(Directory.GetCurrentDirectory(), pathToJson));
if (!File.Exists(path))
{
throw new FileNotFoundException($"File not found: {path}.", path);
}
await using var stream = File.OpenRead(path);
return await LoadFromJsonStreamAsync(stream);
}
/// <inheritdoc cref="LoadFromJsonFileAsync"/>
public static Application LoadFromJsonFile(string pathToJson) => LoadFromJsonFileAsync(pathToJson).Result;
/// <summary>
/// Load an <see cref="Application"/> from a given stream (FileStream, MemoryStream, ...).
/// </summary>
/// <param name="stream">The stream to read the json from.</param>
/// <returns>The parsed <see cref="Application"/>.</returns>
/// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception>
/// <exception cref="System.Text.Json.JsonException">
/// Thrown when the JSON is invalid,
/// the <see cref="Application"/> type is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
public static async Task<Application> LoadFromJsonStreamAsync(Stream stream) =>
await JsonSerializer.DeserializeAsync<Application>(
stream,
new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) ??
throw new InvalidDataException("The json file yielded a 'null' result for deserialization.");
/// <inheritdoc cref="LoadFromJsonStreamAsync"/>
public static Application LoadFromJsonStream(Stream stream) => LoadFromJsonStreamAsync(stream).Result;
/// <summary>
/// Load an <see cref="Application"/> from a string that contains json.
/// </summary>
/// <param name="json">Json string.</param>
/// <returns>The parsed <see cref="Application"/>.</returns>
/// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception>
/// <exception cref="System.Text.Json.JsonException">
/// Thrown when the JSON is invalid,
/// the <see cref="Application"/> type is not compatible with the JSON,
/// or when there is remaining data in the Stream.
/// </exception>
public static async Task<Application> LoadFromJsonStringAsync(string json)
{
await using var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json), 0, json.Length);
return await LoadFromJsonStreamAsync(memoryStream);
}
/// <inheritdoc cref="LoadFromJsonStringAsync"/>
public static Application LoadFromJsonString(string json) => LoadFromJsonStringAsync(json).Result;
/// <inheritdoc cref="GetSignedJwtAsync"/>
public string GetSignedJwt(string issuer, TimeSpan? lifeSpan = null) =>
GetSignedJwtAsync(issuer, lifeSpan).Result;
/// <summary>
/// Create a signed JWT token. It is signed with the RSA private
/// key loaded from the key file / key content. The signed
/// JWT contains the needed information for Zitadel to verify
/// the application.
/// </summary>
/// <param name="issuer">The issuer that is targeted to verify the credentials.</param>
/// <param name="lifeSpan">The lifetime of the jwt token. Min: 1 second. Max: 1 hour. Defaults to 1 hour.</param>
/// <returns>A string with a signed JWT token.</returns>
public async Task<string> GetSignedJwtAsync(string issuer, TimeSpan? lifeSpan = null)
{
using var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(await GetRsaParametersAsync());
if (lifeSpan != null && (lifeSpan < TimeSpan.FromSeconds(1) || lifeSpan > TimeSpan.FromHours(1)))
{
throw new ArgumentException("The lifespan is below 1 second or above 1 hour.", nameof(lifeSpan));
}
return JWT.Encode(
new Dictionary<string, object>
{
{ "iss", ClientId },
{ "sub", ClientId },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
{ "exp", (DateTimeOffset.UtcNow + (lifeSpan ?? TimeSpan.FromHours(1))).ToUnixTimeSeconds() },
{ "aud", issuer },
},
rsa,
JwsAlgorithm.RS256,
new Dictionary<string, object>
{
{ "kid", KeyId },
});
}
private async Task<RSAParameters> GetRsaParametersAsync()
{
var bytes = Encoding.UTF8.GetBytes(Key);
await using var ms = new MemoryStream(bytes);
using var sr = new StreamReader(ms);
var pemReader = new PemReader(sr);
if (!(pemReader.ReadObject() is AsymmetricCipherKeyPair keyPair))
{
throw new("RSA Keypair could not be read.");
}
return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PurchaseSiteLookAndFeel
{
public partial class wfRequestNewLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void InsertButton_Click(object sender, EventArgs e)
{
Panel1.Visible = false;
Panel2.Visible = true;
}
protected void InsertButton_DataBinding(object sender, EventArgs e)
{
}
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["DateRequested"] = DateTime.Now;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dominio.EntidadesNegocio
{
public class Categoria
{
public string Descripcion{ get; set; }
public int Id{ get; set; }
public string Nombre{ get; set; }
//esto es un comen
}
}
|
using System.Collections.Generic;
using System.Linq;
using Data;
using Data.Infrastructure;
using Model.Models;
using Core.Common;
using System;
using Model;
using System.Threading.Tasks;
using Data.Models;
using Model.ViewModel;
namespace Service
{
public interface IModuleService : IDisposable
{
MenuModule Create(MenuModule pt);
void Delete(int id);
void Delete(MenuModule pt);
MenuModule Find(string Name);
MenuModule Find(int id);
void Update(MenuModule pt);
MenuModule Add(MenuModule pt);
IEnumerable<MenuModouleViewModel> GetModuleList();
IEnumerable<MenuModouleViewModel> GetModuleListForUser(List<string> Roles, int SiteId, int DivisionId);
MenuModule GetModuleByName(string terms);
}
public class ModuleService : IModuleService
{
ApplicationDbContext db = new ApplicationDbContext();
private readonly IUnitOfWorkForService _unitOfWork;
private readonly Repository<MenuModule> _ModuleRepository;
RepositoryQuery<MenuModule> ModuleRepository;
public ModuleService(IUnitOfWorkForService unitOfWork)
{
_unitOfWork = unitOfWork;
_ModuleRepository = new Repository<MenuModule>(db);
ModuleRepository = new RepositoryQuery<MenuModule>(_ModuleRepository);
}
public MenuModule GetModuleByName(string terms)
{
return (from p in db.MenuModule
where p.ModuleName == terms
select p).FirstOrDefault();
}
public MenuModule Find(string Name)
{
return ModuleRepository.Get().Where(i => i.ModuleName == Name).FirstOrDefault();
}
//public Module GetModuleByRoles()
//{
//}
public MenuModule Find(int id)
{
return _unitOfWork.Repository<MenuModule>().Find(id);
}
public MenuModule Create(MenuModule pt)
{
pt.ObjectState = ObjectState.Added;
_unitOfWork.Repository<MenuModule>().Insert(pt);
return pt;
}
public void Delete(int id)
{
_unitOfWork.Repository<MenuModule>().Delete(id);
}
public void Delete(MenuModule pt)
{
_unitOfWork.Repository<MenuModule>().Delete(pt);
}
public void Update(MenuModule pt)
{
pt.ObjectState = ObjectState.Modified;
_unitOfWork.Repository<MenuModule>().Update(pt);
}
public IEnumerable<MenuModouleViewModel> GetModuleList()
{
var pt = (from p in db.MenuModule
join t in db.Menu on p.ModuleId equals t.ModuleId
group p by p.ModuleId into g
orderby g.Max(m => m.ModuleId)
select new MenuModouleViewModel
{
IconName = g.FirstOrDefault().IconName,
IsActive = g.FirstOrDefault().IsActive,
ModuleId = g.FirstOrDefault().ModuleId,
ModuleName = g.FirstOrDefault().ModuleName,
Srl = g.FirstOrDefault().Srl,
URL = g.FirstOrDefault().URL,
}
);
return pt;
}
public IEnumerable<MenuModouleViewModel> GetModuleListForUser(List<string> Role, int SiteId, int DivisionId)
{
List<MenuModouleViewModel> ModuleList = new List<MenuModouleViewModel>();
//Testing Block
var Roles = (from p in db.Roles
select p).ToList();
var RoleId = string.Join(",", from p in Roles
where Role.Contains(p.Name)
select p.Id.ToString());
//End
var pt = (from p in db.RolesMenu
join t in db.Menu on p.MenuId equals t.MenuId
join t2 in db.MenuModule on t.ModuleId equals t2.ModuleId
where p.SiteId == SiteId && p.DivisionId == DivisionId && RoleId.Contains(p.RoleId)
group t2 by t2.ModuleId into g
select g.FirstOrDefault()
);
if (pt != null)
ModuleList = (from p in pt
select new MenuModouleViewModel
{
IconName = p.IconName,
IsActive = p.IsActive,
ModuleId = p.ModuleId,
ModuleName = p.ModuleName,
Srl = p.Srl,
URL = p.URL,
}).ToList();
return ModuleList;
}
public MenuModule Add(MenuModule pt)
{
_unitOfWork.Repository<MenuModule>().Insert(pt);
return pt;
}
public void Dispose()
{
}
}
}
|
using Automatonymous;
using MassTransit.Logging;
using SampleDistributedSystem.Contracts.Messages.Api;
using SampleDistributedSystem.Contracts.Messages.Commands;
using SampleDistributedSystem.Contracts.Messages.Core;
using SampleDistributedSystem.Contracts.Messages.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleDistributedSystem.Coordination {
public class ExecuteTransactionStateMachine : AutomatonymousStateMachine<ExecuteTransactionState> {
static readonly ILog _log = Logger.Get<ExecuteTransactionStateMachine>();
public ExecuteTransactionStateMachine(MessageHeader header) {
State(() => PendingExecution);
State(() => PendingGettingCustomerDetial);
State(() => PendingValidation);
State(() => Executed);
State(() => Failed);
Event(() => OnCustomerContactDetailsRetrieved);
Event(() => OnExecuteTransaction);
Event(() => OnTransactionExecutedOnHost);
Event(() => OnTransactionExecutionFailedOnHost);
Event(() => OnTransactionValidatedSuccessfully);
Event(() => OnTransactionValidationFailed);
Initially(
When(OnExecuteTransaction)
.Then((state, message) => {
_log.DebugFormat("Transaction execution requested from {0} on {1} with Id {2} via {3}",
message.Header.ServiceIdentity,
message.TimeStamp,
message.ReferenceTransactionId,
message.TransactionChannel);
state.AccountNumber = message.AccountNumber;
state.TransactionName = message.TransactionName;
state.TransactionAmount = message.TransactionAmount;
state.TransactionRequestTime = message.TimeStamp;
state.TransactionSourceChannel = message.TransactionChannel;
})
.Publish((_, message) => new ValidateTransaction(message.Header, message.ReferenceTransactionId, message.TransactionName, message.TransactionAmount, message.TransactionName))
.TransitionTo(PendingValidation));
During(PendingValidation,
When(OnTransactionValidationFailed)
.Then((state, message) => {
_log.DebugFormat("Transaction Request failed to pass Validation step by {0} on {1} with Id {2} => Error Code: {3}",
message.Header.ServiceIdentity,
message.TimeStamp,
message.ReferenceTransactionId,
message.ErrorCode);
state.ErrorCode = message.ErrorCode;
state.ErrorDescription = message.ErrorDescription;
state.FailureStep = message.Header.ServiceIdentity;
state.TransactionFailureTime = message.TimeStamp;
})
.Publish((state, message) => new TransactionFailed(message.OriginatingCommandId, message.ReferenceTransactionId, message.Header, state.ErrorDescription))
.TransitionTo(Failed),
When(OnTransactionValidatedSuccessfully)
.Then((state, message) => {
_log.DebugFormat("Transaction Request passed Validation step by {0} on {1} with Id {2}",
message.Header.ServiceIdentity,
message.TimeStamp,
message.ReferenceTransactionId);
})
.Publish((state, _) => new GetCustomerContactDetails(header, state.AccountNumber))
.TransitionTo(PendingGettingCustomerDetial));
}
public State PendingValidation { get; private set; }
public State PendingGettingCustomerDetial { get; private set; }
public State PendingExecution { get; private set; }
public State Executed { get; private set; }
public State Failed { get; private set; }
public Event<ExecuteTransaction> OnExecuteTransaction { get; private set; }
public Event<CustomerContactDetailsRetrieved> OnCustomerContactDetailsRetrieved { get; private set; }
public Event<TransactionExecutedOnHost> OnTransactionExecutedOnHost { get; private set; }
public Event<TransactionExecutionFailedOnHost> OnTransactionExecutionFailedOnHost { get; private set; }
public Event<TransactionValidatedSuccessfully> OnTransactionValidatedSuccessfully { get; private set; }
public Event<TransactionValidationFailed> OnTransactionValidationFailed { get; private set; }
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace S3.AutoBatcher
{
public interface IBatch<TBatchItem>
{
/// <summary>
/// Adds an item to the batch
/// </summary>
/// <param name="item"></param>
/// <param name="token"></param>
/// <param name="willAddMoreItemsWithThisToken">When false it completes implicitly <see cref="AddingItemsToBatchCompleted"/> </param>
Task Add(TBatchItem item, BatchAggregatorToken<TBatchItem> token,bool willAddMoreItemsWithThisToken=true);
/// <summary>
/// Obtains a token to contribute to the batch
/// </summary>
/// <returns></returns>
Task<BatchAggregatorToken<TBatchItem>> NewBatchAggregatorToken();
/// <summary>
/// Notifies the batch the producer holding the token has finalised
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task AddingItemsToBatchCompleted(BatchAggregatorToken<TBatchItem> token);
/// <summary>
/// Gets the currently enlisted items
/// </summary>
IReadOnlyCollection<TBatchItem> EnlistedItems { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AxisEq.POSScales;
namespace AxisEq
{
public enum ScaleStatus
{
Idle,
Off,
InternalError,
Unknown,
UnderWeight,
WeightChange,
Unstable,
Overload,
}
public enum ScaleError
{
/// <summary>
/// Ошибка соединения с сканер-весами
/// </summary>
OpenError = 1,
/// <summary>
/// Порт закрыт
/// </summary>
PortClosedError = 2,
/// <summary>
/// Ошибка протокола обмена
/// </summary>
ProtocolError = 3,
}
/// <summary>
/// Весы
/// </summary>
public abstract class AbstractScale
{
/// <summary>
/// Событие возникающее при сканировании товара на сканере
/// </summary>
public abstract event OnScanHandler OnScan;
public delegate void OnScanHandler(string barcode);
/// <summary>
/// Событие возникающее при ошибке в работе с сканнер-весами
/// </summary>
public abstract event OnErrorHandler OnError;
public delegate void OnErrorHandler(ScaleError err, string msg);
/// <summary>
/// Получить статус сканнера
/// </summary>
public virtual ScaleStatus GetScannerStatus()
{
throw new System.NotImplementedException();
}
/// <summary>
/// Получить вес с весов, в кг
/// </summary>
public virtual double GetWeight()
{
throw new System.NotImplementedException();
}
/// <summary>
/// Открыть подключение к сканнер-весам
/// </summary>
public virtual void Open(string scanPortName, string scanBaud, string scalePortName, string scaleBaud)
{
//throw new System.NotImplementedException();
}
/// <summary>
/// Закрыть подключение к сканнер-весам
/// </summary>
public virtual void Close()
{
throw new System.NotImplementedException();
}
/// <summary>
/// Получить экземпляр класса по имени весов
/// </summary>
public static AbstractScale GetInstanсe(string name)
{
if (name.ToUpper().Contains("CASPDS")) return (new CASPDSScale());
if (name.ToUpper().Contains("CAS")) return (new CASScale());
if (name.ToUpper().Contains("BIZERBA")) return (new Bizerba());
if (name.ToUpper().Contains("MT")) return (new MTScale());
if (name.ToUpper().Contains("DATALOGIC")) return (new Datalogic());
return null;
}
string extErrorCode;
/// <summary>
/// Реальный статус весов
/// </summary>
public string RealError
{
get
{
return extErrorCode;
}
set
{
extErrorCode = value;
}
}
/// <summary>
/// Получить статус весов
/// </summary>
public virtual ScaleStatus GetScaleStatus()
{
throw new System.NotImplementedException();
}
/// <summary>
/// Установка нуля
/// </summary>
public virtual int SetZero()
{
throw new System.NotImplementedException();
}
/// <summary>
/// Установка тары
/// </summary>
public virtual int SetTare()
{
throw new System.NotImplementedException();
}
}
}
|
using Api.Helpers.Contracts.ConfigurationManagerHelpers;
using Api.Helpers.Core.ConfigurationManagerHelpers;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Routing;
namespace Api.Versioned
{
internal class VersionConstraint : IHttpRouteConstraint
{
#region Fields
private readonly int allowedVersion;
#endregion
#region Constructor
public VersionConstraint(int allowedVersion)
{
this.allowedVersion = allowedVersion;
}
#endregion
#region Public Methods
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (routeDirection != HttpRouteDirection.UriResolution) return false;
IConfigurationManagerHelper configurationManagerHelper = request.GetDependencyScope().GetService(typeof(IConfigurationManagerHelper)) as IConfigurationManagerHelper;
if (configurationManagerHelper == null) configurationManagerHelper = new ConfigurationManagerHelper();
var version = GetVersionHeader(request, configurationManagerHelper) ?? configurationManagerHelper.GetSettingOrDefaultValue(VersionConstants.ConfVersionDefault, VersionConstants.VersionDefault);
return version == allowedVersion;
}
#endregion
#region Private Methods
private int? GetVersionHeader(HttpRequestMessage request, IConfigurationManagerHelper configurationManagerHelper)
{
string versionAsString;
IEnumerable<string> headerValues;
var headerApiVersion = configurationManagerHelper.GetSettingOrDefaultValue(VersionConstants.ConfVersionHeader, VersionConstants.VersionHeader);
if (request.Headers.TryGetValues(headerApiVersion, out headerValues) &&
headerValues.Count() == 1)
{
versionAsString = headerValues.First();
}
else
{
return null;
}
int version;
if (versionAsString != null && int.TryParse(versionAsString, out version))
{
return version;
}
return null;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSConsoleRL.Game.Managers;
using CSConsoleRL.Events;
using CSConsoleRL.Components.Interfaces;
using CSConsoleRL.Entities;
namespace CSConsoleRL.GameSystems
{
public abstract class GameSystem
{
protected List<Entity> _systemEntities;
public GameSystemManager SystemManager { get; set; }
public abstract void InitializeSystem();
public abstract void AddEntity(Entity entity);
public abstract void HandleMessage(IGameEvent gameEvent);
public void BroadcastMessage(IGameEvent evnt)
{
SystemManager.BroadcastEvent(evnt);
}
public void RemoveEntity(Entity entityToRemove)
{
if (_systemEntities.Contains(entityToRemove))
{
_systemEntities.Remove(entityToRemove);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using CODE.Framework.Core.Utilities;
using CODE.Framework.Services.Contracts;
namespace CODE.Framework.Services.Server
{
/// <summary>
/// Helper functionality needed for REST operations
/// </summary>
public static class RestHelper
{
/// <summary>
/// Gets the HTTP method/verb from operation description.
/// </summary>
/// <param name="operationDescription">The operation description.</param>
/// <returns>System.String.</returns>
public static string GetHttpMethodFromOperationDescription(OperationDescription operationDescription)
{
const string defaultMethod = "POST"; // CODE Framework default for REST operations
var contractType = operationDescription.DeclaringContract.ContractType;
var methodInfo = contractType.GetMethod(operationDescription.Name);
if (methodInfo == null) return defaultMethod;
var attributes = methodInfo.GetCustomAttributes(typeof (RestAttribute), true);
if (attributes.Length <= 0) return defaultMethod;
var restAttribute = attributes[0] as RestAttribute;
if (restAttribute == null) return defaultMethod;
var method = restAttribute.Method.ToString().ToUpper();
return method;
}
/// <summary>
/// Inspects the specified method in the contract for special configuration to see what the REST-exposed method name is supposed to be
/// </summary>
/// <param name="actualMethodName">Actual name of the method.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="contractType">Service contract type.</param>
/// <returns>REST-exposed name of the method</returns>
public static string GetExposedMethodNameFromContract(string actualMethodName, string httpMethod, Type contractType)
{
var methods = ObjectHelper.GetAllMethodsForInterface(contractType).Where(m => m.Name == actualMethodName).ToList();
foreach (var method in methods)
{
var restAttribute = GetRestAttribute(method);
if (string.Equals(restAttribute.Method.ToString(), httpMethod, StringComparison.OrdinalIgnoreCase))
{
if (restAttribute.Name == null) return method.Name;
if (restAttribute.Name == string.Empty) return string.Empty;
return restAttribute.Name;
}
}
return actualMethodName;
}
/// <summary>
/// Returns the exposed HTTP-method/verb for the provided method
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="contractType">Service contract type.</param>
/// <returns>HTTP Method/Verb</returns>
public static string GetHttpMethodFromContract(string methodName, Type contractType)
{
var method = ObjectHelper.GetAllMethodsForInterface(contractType).FirstOrDefault(m => m.Name == methodName);
return method == null ? "POST" : GetRestAttribute(method).Method.ToString().ToUpper();
}
/// <summary>
/// Extracts the name of the method a REST call was aimed at based on the provided url "fragment" (URL minus the root URL part),
/// the HTTP method (get, post, put, ...) and the contract type
/// </summary>
/// <param name="urlFragment">The URL fragment.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="contractType">Service contract type.</param>
/// <returns>Method picked as a match within the contract (or null if no matching method was found)</returns>
/// <remarks>
/// Methods are picked based on a number of parameters for each fragment and HTTP method.
///
/// Example URL Fragment: /CustomerSearch/Smith (HTTP-GET)
///
/// In this case, the "CustomerSearch" part of the fragment is considered a good candidate for a method name match.
/// The method thus looks at the contract definition and searches for methods of the same name (case insensitive!)
/// as well as the Rest(Name="xxx") attribute on each method to see if there is a match. If a match is found, the HTTP-Method is also
/// compared and has to be a match (there could be two methods of the same exposed name, but differing HTTP methods/verbs).
///
/// If no matching method is found, "CustomerSearch" is considered to be a parameter rather than a method name, and therefore, the method
/// name is assumed to be empty (the default method). Therefore, a method with a [Rest(Name="")] with a matching HTTP method is searched for.
/// For a complete match, the method in question would thus have to have the following attribute declared: [Rest(Name="", Method=RestMethods.Get)]
/// </remarks>
public static MethodInfo GetMethodNameFromUrlFragmentAndContract(string urlFragment, string httpMethod, Type contractType)
{
if (urlFragment.StartsWith("/")) urlFragment = urlFragment.Substring(1);
var firstParameter = string.Empty;
if (urlFragment.IndexOf("/", StringComparison.Ordinal) > -1) firstParameter = urlFragment.Substring(0, urlFragment.IndexOf("/", StringComparison.Ordinal));
else if (!string.IsNullOrEmpty(urlFragment)) firstParameter = urlFragment;
var methods = ObjectHelper.GetAllMethodsForInterface(contractType);
var methodInfos = methods as MethodInfo[] ?? methods.ToArray(); // Preventing multiple enumeration problems
// We first check for named methods
foreach (var method in methodInfos)
{
var restAttribute = GetRestAttribute(method);
var methodName = method.Name;
if (restAttribute != null && restAttribute.Name != null) methodName = restAttribute.Name;
var httpMethodForMethod = restAttribute?.Method.ToString().ToUpper() ?? "GET";
if (httpMethodForMethod == httpMethod && string.Equals(methodName, firstParameter, StringComparison.CurrentCultureIgnoreCase))
return method;
if (httpMethodForMethod == "POSTORPUT" && (string.Equals("POST", httpMethod, StringComparison.OrdinalIgnoreCase) || string.Equals("PUT", httpMethod, StringComparison.OrdinalIgnoreCase)) && string.Equals(methodName, firstParameter, StringComparison.CurrentCultureIgnoreCase))
return method;
}
// If we haven't found anything yet, we check for default methods
foreach (var method in methodInfos)
{
var restAttribute = GetRestAttribute(method);
if (!string.IsNullOrEmpty(restAttribute.Name)) continue; // We are now only intersted in the empty ones
var httpMethodForMethod = restAttribute.Method.ToString().ToUpper();
if (restAttribute.Name != null)
{
if (string.IsNullOrEmpty(restAttribute.Name) && string.Equals(httpMethodForMethod, httpMethod, StringComparison.OrdinalIgnoreCase))
return method;
if (string.IsNullOrEmpty(restAttribute.Name) && httpMethodForMethod == "POSTORPUT" && (string.Equals("POST", httpMethod, StringComparison.OrdinalIgnoreCase) || string.Equals("PUT", httpMethod, StringComparison.OrdinalIgnoreCase)))
return method;
}
}
return null;
}
/// <summary>
/// Extracts the RestAttribute from a method's attributes
/// </summary>
/// <param name="method">The method to be inspected</param>
/// <returns>The applied RestAttribute or a default RestAttribute.</returns>
public static RestAttribute GetRestAttribute(MethodInfo method)
{
var customAttributes = method.GetCustomAttributes(typeof (RestAttribute), true);
if (customAttributes.Length <= 0) return new RestAttribute();
var restAttribute = customAttributes[0] as RestAttribute;
return restAttribute ?? new RestAttribute();
}
/// <summary>
/// Extracts the RestUrlParameterAttribute from a property's attributes
/// </summary>
/// <param name="property">The property.</param>
/// <returns>The applied RestUrlParameterAttribute or a default RestUrlParameterAttribute</returns>
public static RestUrlParameterAttribute GetRestUrlParameterAttribute(PropertyInfo property)
{
var customAttributes = property.GetCustomAttributes(typeof(RestUrlParameterAttribute), true);
if (customAttributes.Length <= 0) return new RestUrlParameterAttribute();
var restAttribute = customAttributes[0] as RestUrlParameterAttribute;
return restAttribute ?? new RestUrlParameterAttribute();
}
/// <summary>
/// Gets a list of all properties that are to be used as inline parameters, sorted by their sequence
/// </summary>
/// <param name="contractType">Contract type</param>
/// <returns>List of properties to be used as inline URL parameters</returns>
public static List<PropertyInfo> GetOrderedInlinePropertyList(Type contractType)
{
var propertiesToSerialize = contractType.GetProperties();
var inlineParameterProperties = new List<PropertySorter>();
if (propertiesToSerialize.Length == 1) // If we only have one parameter, we always allow passing it as an inline parameter, unless it is specifically flagged as a named parameter
{
var parameterAttribute = GetRestUrlParameterAttribute(propertiesToSerialize[0]);
if (parameterAttribute == null || parameterAttribute.Mode == UrlParameterMode.Inline)
inlineParameterProperties.Add(new PropertySorter {Property = propertiesToSerialize[0]});
}
else
foreach (var property in propertiesToSerialize)
{
var parameterAttribute = GetRestUrlParameterAttribute(property);
if (parameterAttribute != null && parameterAttribute.Mode == UrlParameterMode.Inline)
inlineParameterProperties.Add(new PropertySorter {Sequence = parameterAttribute.Sequence, Property = property});
}
return inlineParameterProperties.OrderBy(inline => inline.Sequence).Select(inline => inline.Property).ToList();
}
/// <summary>
/// Returns a list of all properties of the provided object that are NOT flagged to be used as inline URL parameters
/// </summary>
/// <param name="contractType">Contract type</param>
/// <returns>List of named properties</returns>
public static List<PropertyInfo> GetNamedPropertyList(Type contractType)
{
var propertiesToSerialize = contractType.GetProperties();
var properties = new List<PropertyInfo>();
if (propertiesToSerialize.Length == 1) // If there is only one property, we allow passing it as a named parameter, unless it is specifically flagged with a mode
{
var parameterAttribute = GetRestUrlParameterAttribute(propertiesToSerialize[0]);
if (parameterAttribute == null || parameterAttribute.Mode == UrlParameterMode.Named)
properties.Add(propertiesToSerialize[0]);
}
else
foreach (var property in propertiesToSerialize)
{
var parameterAttribute = GetRestUrlParameterAttribute(property);
if (parameterAttribute == null || parameterAttribute.Mode != UrlParameterMode.Named) continue;
properties.Add(property);
}
return properties;
}
/// <summary>
/// Serializes an object to URL parameters
/// </summary>
/// <param name="objectToSerialize">The object to serialize.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <returns>System.String.</returns>
/// <remarks>This is used for REST GET operatoins</remarks>
public static string SerializeToUrlParameters(object objectToSerialize, string httpMethod = "GET")
{
var typeToSerialize = objectToSerialize.GetType();
var inlineParameterProperties = GetOrderedInlinePropertyList(typeToSerialize);
var namedParameterProperties = GetNamedPropertyList(typeToSerialize);
var sb = new StringBuilder();
foreach (var inlineProperty in inlineParameterProperties)
{
var propertyValue = inlineProperty.GetValue(objectToSerialize, null);
sb.Append("/");
if (propertyValue != null)
sb.Append(HttpHelper.UrlEncode(propertyValue.ToString())); // TODO: We need to make sure we are doing well for specific property types
}
if (httpMethod == "GET" && namedParameterProperties.Count > 0)
{
var isFirst = true;
foreach (var namedProperty in namedParameterProperties)
{
var propertyValue = namedProperty.GetValue(objectToSerialize, null);
if (propertyValue == null) continue;
if (isFirst) sb.Append("?");
if (!isFirst) sb.Append("&");
sb.Append(namedProperty.Name + "=" + HttpHelper.UrlEncode(propertyValue.ToString())); // TODO: We need to make sure we are doing well for specific property types
isFirst = false;
}
}
return sb.ToString();
}
private class PropertySorter
{
public int Sequence { get; set; }
public PropertyInfo Property { get; set; }
}
/// <summary>
/// Inspects the URL fragment, trims the method name (if appropriate) and returns the remaining parameters as a dictionary
/// of correlating property names and their values
/// </summary>
/// <param name="urlFragment">The URL fragment.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="contractType">Service contract types.</param>
/// <returns>Dictionary of property values</returns>
public static Dictionary<string, object> GetUrlParametersFromUrlFragmentAndContract(string urlFragment, string httpMethod, Type contractType)
{
if (urlFragment.StartsWith("/")) urlFragment = urlFragment.Substring(1);
var firstParameter = string.Empty;
if (urlFragment.IndexOf("/", StringComparison.Ordinal) > -1) firstParameter = urlFragment.Substring(0, urlFragment.IndexOf("/", StringComparison.Ordinal));
else if (!string.IsNullOrEmpty(urlFragment)) firstParameter = urlFragment;
var methods = ObjectHelper.GetAllMethodsForInterface(contractType);
MethodInfo foundMethod = null;
foreach (var method in methods)
{
var restAttribute = GetRestAttribute(method);
var httpMethodForMethod = restAttribute.Method.ToString().ToUpper();
if (!string.Equals(httpMethod, httpMethodForMethod, StringComparison.OrdinalIgnoreCase)) continue;
var methodName = method.Name;
if (!string.IsNullOrEmpty(restAttribute.Name)) methodName = restAttribute.Name;
if (!string.Equals(methodName, firstParameter, StringComparison.OrdinalIgnoreCase)) continue;
urlFragment = urlFragment.Substring(methodName.Length);
if (urlFragment.StartsWith("/")) urlFragment = urlFragment.Substring(1);
foundMethod = method;
break; // We found our methoid
}
if (foundMethod == null) // We haven't found our method yet. If there is a default method (a method with an empty REST name) that matches the HTTP method, we will use that instead
foreach (var method in methods)
{
var restAttribute = GetRestAttribute(method);
if (restAttribute.Name != "") continue;
var httpMethodForMethod = restAttribute.Method.ToString().ToUpper();
if (!string.Equals(httpMethod, httpMethodForMethod, StringComparison.OrdinalIgnoreCase)) continue;
foundMethod = method;
break; // We found our methoid
}
if (foundMethod == null) return new Dictionary<string, object>(); // We didn't find a match, therefore, we can't map anything
var foundMethodParameters = foundMethod.GetParameters();
if (foundMethodParameters.Length != 1) return new Dictionary<string, object>(); // The method signature has multiple parameters, so we can't handle it (Note: Other code in the chain will probably throw an exception about it, so we just return out here as we do not want duplicate exceptions)
var firstParameterType = foundMethodParameters[0].ParameterType;
// Ready to extract the parameters
var inlineParameterString = string.Empty;
var namedParameterString = string.Empty;
var separatorPosition = urlFragment.IndexOf("?", StringComparison.Ordinal);
if (separatorPosition > -1)
{
inlineParameterString = urlFragment.Substring(0, separatorPosition);
namedParameterString = urlFragment.Substring(separatorPosition + 1);
}
else
{
if (urlFragment.IndexOf("=", StringComparison.Ordinal) > -1) namedParameterString = urlFragment;
else inlineParameterString = urlFragment;
}
var dictionary = new Dictionary<string, object>();
// Parsing the inline parameters
if (!string.IsNullOrEmpty(inlineParameterString))
{
var inlineParameters = inlineParameterString.Split('/');
var inlineProperties = RestHelper.GetOrderedInlinePropertyList(firstParameterType);
for (var propertyCounter = 0; propertyCounter < inlineParameters.Length; propertyCounter++)
{
if (propertyCounter >= inlineProperties.Count) break; // We overshot the available parameters for some reason
var parameterString = HttpHelper.UrlDecode(inlineParameters[propertyCounter]);
var parameterValue = ConvertValue(parameterString, inlineProperties[propertyCounter].PropertyType);
dictionary.Add(inlineProperties[propertyCounter].Name, parameterValue);
}
}
// Parsing the named parameters
if (!string.IsNullOrEmpty(namedParameterString))
{
var parameterElements = namedParameterString.Split('&');
foreach (var parameterElement in parameterElements)
{
var parameterNameValuePair = parameterElement.Split('=');
if (parameterNameValuePair.Length != 2) continue;
var currentProperty = firstParameterType.GetProperty(parameterNameValuePair[0]);
if (currentProperty == null) continue;
var currentPropertyString = HttpHelper.UrlDecode(parameterNameValuePair[1]);
var currentPropertyValue = ConvertValue(currentPropertyString, currentProperty.PropertyType);
dictionary.Add(parameterNameValuePair[0], currentPropertyValue);
}
}
return dictionary;
}
private static object ConvertValue(string value, Type propertyType)
{
if (propertyType == typeof (string)) return value; // Very likely case, so we handle this right away, even though we are also handling it below
if (propertyType.IsEnum) return Enum.Parse(propertyType, value);
if (propertyType == typeof (Guid)) return Guid.Parse(value);
if (propertyType == typeof (bool)) return Convert.ToBoolean(value);
if (propertyType == typeof(byte)) return Convert.ToByte(value);
if (propertyType == typeof(char)) return Convert.ToChar(value);
if (propertyType == typeof(DateTime)) return Convert.ToDateTime(value);
if (propertyType == typeof(decimal)) return Convert.ToDecimal(value);
if (propertyType == typeof(double)) return Convert.ToDouble(value);
if (propertyType == typeof(Int16)) return Convert.ToInt16(value);
if (propertyType == typeof(Int32)) return Convert.ToInt32(value);
if (propertyType == typeof(Int64)) return Convert.ToInt64(value);
if (propertyType == typeof(sbyte)) return Convert.ToSByte(value);
if (propertyType == typeof(float)) return Convert.ToSingle(value);
if (propertyType == typeof(UInt16)) return Convert.ToUInt16(value);
if (propertyType == typeof(UInt32)) return Convert.ToUInt32(value);
if (propertyType == typeof(UInt64)) return Convert.ToUInt64(value);
return value;
}
}
/// <summary>
/// Endpoint behavior configuration specific to XML formatted REST calls
/// </summary>
public class RestXmlHttpBehavior : WebHttpBehavior
{
/// <summary>Handles REST XML formatting behavior</summary>
/// <param name="operationDescription"></param>
/// <param name="endpoint"></param>
/// <returns></returns>
protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
var webInvoke = GetBehavior<WebInvokeAttribute>(operationDescription);
if (webInvoke == null)
{
webInvoke = new WebInvokeAttribute();
operationDescription.Behaviors.Add(webInvoke);
}
webInvoke.RequestFormat = WebMessageFormat.Xml;
webInvoke.ResponseFormat = WebMessageFormat.Xml;
webInvoke.Method = RestHelper.GetHttpMethodFromOperationDescription(operationDescription);
var formatter = base.GetReplyDispatchFormatter(operationDescription, endpoint);
return formatter;
}
/// <summary>
/// Gets the request dispatch formatter.
/// </summary>
/// <param name="operationDescription">The operation description.</param>
/// <param name="endpoint">The endpoint.</param>
/// <returns>IDispatchMessageFormatter.</returns>
protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
if (IsGetOperation(operationDescription))
// no change for GET operations
return base.GetRequestDispatchFormatter(operationDescription, endpoint);
if (operationDescription.Messages[0].Body.Parts.Count == 0)
// nothing in the body, still use the default
return base.GetRequestDispatchFormatter(operationDescription, endpoint);
return new NewtonsoftJsonDispatchFormatter(operationDescription, true);
}
/// <summary>
/// Determines whether the operation is a GET operation.
/// </summary>
/// <param name="operation">The operation.</param>
/// <returns><c>true</c> if [is get operation] [the specified operation]; otherwise, <c>false</c>.</returns>
private static bool IsGetOperation(OperationDescription operation)
{
var wga = operation.Behaviors.Find<WebGetAttribute>();
if (wga != null) return true;
var wia = operation.Behaviors.Find<WebInvokeAttribute>();
if (wia != null) return wia.Method == "HEAD";
return false;
}
/// <summary>
/// Tries to find a behavior attribute of a certain type and returns it
/// </summary>
/// <typeparam name="T">Type of behavior we are looking for</typeparam>
/// <param name="operationDescription">Operation description</param>
/// <returns>Behavior or null</returns>
private static T GetBehavior<T>(OperationDescription operationDescription) where T : class
{
foreach (var behavior in operationDescription.Behaviors)
{
var webGetAttribute = behavior as T;
if (webGetAttribute != null)
return webGetAttribute;
}
return null;
}
}
/// <summary>
/// Endpoint behavior configuration specific to XML formatted REST calls
/// </summary>
public class RestJsonHttpBehavior : WebHttpBehavior
{
/// <summary>
/// Initializes a new instance of the <see cref="RestJsonHttpBehavior" /> class.
/// </summary>
/// <param name="rootUrl">The root URL.</param>
/// <param name="contractType">Type of the contract.</param>
public RestJsonHttpBehavior(string rootUrl, Type contractType)
{
_rootUrl = rootUrl;
_contractType = contractType;
}
private readonly string _rootUrl;
private readonly Type _contractType;
/// <summary>Handles REST JSON formatting behavior</summary>
/// <param name="operationDescription"></param>
/// <param name="endpoint"></param>
/// <returns></returns>
protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
var webInvoke = operationDescription.Behaviors.OfType<WebInvokeAttribute>().FirstOrDefault();
if (webInvoke == null)
{
webInvoke = new WebInvokeAttribute();
operationDescription.Behaviors.Add(webInvoke);
}
webInvoke.RequestFormat = WebMessageFormat.Json;
webInvoke.ResponseFormat = WebMessageFormat.Json;
webInvoke.Method = RestHelper.GetHttpMethodFromOperationDescription(operationDescription);
if (operationDescription.Messages.Count == 1 || operationDescription.Messages[1].Body.ReturnValue.Type == typeof(void))
return base.GetReplyDispatchFormatter(operationDescription, endpoint);
return new NewtonsoftJsonDispatchFormatter(operationDescription, false);
}
/// <summary>
/// Implements the <see cref="M:System.ServiceModel.Description.IEndpointBehavior.ApplyDispatchBehavior(System.ServiceModel.Description.ServiceEndpoint,System.ServiceModel.Dispatcher.EndpointDispatcher)" /> method to support modification or extension of the client across an endpoint.
/// </summary>
/// <param name="endpoint">The endpoint that exposes the contract.</param>
/// <param name="endpointDispatcher">The endpoint dispatcher to which the behavior is applied.</param>
public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
base.ApplyDispatchBehavior(endpoint, endpointDispatcher);
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new RestDispatchMessageInspector(_rootUrl, _contractType));
endpointDispatcher.DispatchRuntime.OperationSelector = new RestJsonOperationSelector(_rootUrl, _contractType);
//foreach (var operation in endpoint.Contract.Operations.Where(o => !o.Behaviors.Contains(typeof (RestJsonOperationInvokerBehavior))))
// operation.Behaviors.Add(new RestJsonOperationInvokerBehavior());
}
}
///// <summary>
///// This behavior allows adding a special method invoker for REST calls
///// </summary>
//public class RestJsonOperationInvokerBehavior : IOperationBehavior
//{
// /// <summary>
// /// Validates the specified operation description.
// /// </summary>
// /// <param name="operationDescription">The operation description.</param>
// public void Validate(OperationDescription operationDescription)
// {
// }
// /// <summary>
// /// Applies the dispatch behavior.
// /// </summary>
// /// <param name="operationDescription">The operation description.</param>
// /// <param name="dispatchOperation">The dispatch operation.</param>
// public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
// {
// dispatchOperation.Invoker = new RestJsonOperationInvoker(dispatchOperation.Invoker, operationDescription, dispatchOperation);
// }
// /// <summary>
// /// Applies the client behavior.
// /// </summary>
// /// <param name="operationDescription">The operation description.</param>
// /// <param name="clientOperation">The client operation.</param>
// public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
// {
// }
// /// <summary>
// /// Adds the binding parameters.
// /// </summary>
// /// <param name="operationDescription">The operation description.</param>
// /// <param name="bindingParameters">The binding parameters.</param>
// public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
// {
// }
//}
/// <summary>
/// This selector can match URL parameters on JSON requests to methods on a service
/// </summary>
public class RestJsonOperationSelector : IDispatchOperationSelector
{
/// <summary>
/// Initializes a new instance of the <see cref="RestJsonOperationSelector" /> class.
/// </summary>
/// <param name="rootUrl">The root URL.</param>
/// <param name="contractType">Type of the hosted service contract.</param>
public RestJsonOperationSelector(string rootUrl, Type contractType)
{
_rootUrl = rootUrl;
_rootUrlLower = rootUrl.ToLower();
_contractType = contractType;
}
private readonly Type _contractType;
private readonly string _rootUrl;
private readonly string _rootUrlLower;
/// <summary>
/// Associates a local operation with the incoming method.
/// </summary>
/// <param name="message">The incoming <see cref="T:System.ServiceModel.Channels.Message" /> to be associated with an operation.</param>
/// <returns>The name of the operation to be associated with the <paramref name="message" />.</returns>
public string SelectOperation(ref Message message)
{
var actionString = message.Headers.To.AbsoluteUri;
if (actionString.ToLower().StartsWith(_rootUrlLower))
{
actionString = actionString.Substring(_rootUrl.Length);
if (actionString.StartsWith("/")) actionString = actionString.Substring(1);
}
var httpMethod = "POST";
if (message.Properties != null && message.Properties.ContainsKey("httpRequest"))
{
var httpRequestInfo = message.Properties["httpRequest"] as HttpRequestMessageProperty;
if (httpRequestInfo != null) httpMethod = httpRequestInfo.Method.ToUpper();
}
var matchingMethod = RestHelper.GetMethodNameFromUrlFragmentAndContract(actionString, httpMethod, _contractType);
return matchingMethod != null ? matchingMethod.Name : string.Empty;
}
}
///// <summary>
///// Special operation invoker used to funnel REST calls to the appropriate actions in the service object
///// </summary>
//public class RestJsonOperationInvoker : IOperationInvoker
//{
// private readonly IOperationInvoker _originalInvoker;
// private readonly DispatchOperation _dispatcherOperation;
// private readonly OperationDescription _operationDescription;
// private readonly MethodInfo _methodInfo;
// /// <summary>
// /// Initializes a new instance of the <see cref="RestJsonOperationInvoker"/> class.
// /// </summary>
// /// <param name="originalInvoker">The original invoker.</param>
// /// <param name="operationDescription">The operation description.</param>
// /// <param name="dispatchOperation">The dispatch operation.</param>
// public RestJsonOperationInvoker(IOperationInvoker originalInvoker, OperationDescription operationDescription, DispatchOperation dispatchOperation)
// {
// _originalInvoker = originalInvoker;
// _operationDescription = operationDescription;
// _methodInfo = operationDescription.SyncMethod;
// _dispatcherOperation = dispatchOperation;
// }
// /// <summary>
// /// Returns an <see cref="T:System.Array" /> of parameter objects.
// /// </summary>
// /// <returns>The parameters that are to be used as arguments to the operation.</returns>
// public object[] AllocateInputs()
// {
// var inputs = new object[_methodInfo.GetParameters().Length];
// return inputs;
// }
// /// <summary>
// /// Returns an object and a set of output objects from an instance and set of input objects.
// /// </summary>
// /// <param name="instance">The object to be invoked.</param>
// /// <param name="inputs">The inputs to the method.</param>
// /// <param name="outputs">The outputs from the method.</param>
// /// <returns>The return value.</returns>
// public object Invoke(object instance, object[] inputs, out object[] outputs)
// {
// outputs = new object[0]; // We are not really doing anything with outputs. The real "output" is the return value
// // Making sure all the input parameters are set correctly
// // Making the actual call
// var result = _methodInfo.Invoke(instance, inputs);
// return result;
// }
// /// <summary>
// /// An asynchronous implementation of the <see cref="M:System.ServiceModel.Dispatcher.IOperationInvoker.Invoke(System.Object,System.Object[],System.Object[]@)" /> method.
// /// </summary>
// /// <param name="instance">The object to be invoked.</param>
// /// <param name="inputs">The inputs to the method.</param>
// /// <param name="callback">The asynchronous callback object.</param>
// /// <param name="state">Associated state data.</param>
// /// <returns>A <see cref="T:System.IAsyncResult" /> used to complete the asynchronous call.</returns>
// public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
// {
// throw new NotImplementedException("Async service invokation is not supported through the RestJsonOperationInvoker class");
// }
// /// <summary>
// /// The asynchronous end method.
// /// </summary>
// /// <param name="instance">The object invoked.</param>
// /// <param name="outputs">The outputs from the method.</param>
// /// <param name="result">The <see cref="T:System.IAsyncResult" /> object.</param>
// /// <returns>The return value.</returns>
// public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
// {
// throw new NotImplementedException("Async service invokation is not supported through the RestJsonOperationInvoker class");
// }
// /// <summary>
// /// Gets a value that specifies whether the <see cref="M:System.ServiceModel.Dispatcher.IOperationInvoker.Invoke(System.Object,System.Object[],System.Object[]@)" /> or <see cref="M:System.ServiceModel.Dispatcher.IOperationInvoker.InvokeBegin(System.Object,System.Object[],System.AsyncCallback,System.Object)" /> method is called by the dispatcher.
// /// </summary>
// /// <value><c>true</c> if this instance is synchronous; otherwise, <c>false</c>.</value>
// public bool IsSynchronous
// {
// get { return true; }
// }
//}
/// <summary>
/// Message inspector for REST messages
/// </summary>
public class RestDispatchMessageInspector : IDispatchMessageInspector
{
private readonly string _rootUrl;
private readonly string _rootUrlLower;
private readonly Type _contractType;
/// <summary>
/// Initializes a new instance of the <see cref="RestDispatchMessageInspector" /> class.
/// </summary>
/// <param name="rootUrl">The root URL.</param>
/// <param name="contractType">Type of the contract.</param>
public RestDispatchMessageInspector(string rootUrl, Type contractType)
{
_rootUrl = rootUrl;
_rootUrlLower = rootUrl.ToLower();
_contractType = contractType;
}
/// <summary>
/// Called after an inbound message has been received but before the message is dispatched to the intended operation.
/// </summary>
/// <param name="request">The request message.</param>
/// <param name="channel">The incoming channel.</param>
/// <param name="instanceContext">The current service instance.</param>
/// <returns>The object used to correlate state. This object is passed back in the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply(System.ServiceModel.Channels.Message@,System.Object)" /> method.</returns>
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
if (!request.Properties.ContainsKey("Via")) return request; // Nothing much we can do here
if (!request.Properties.ContainsKey("httpRequest")) return request; // Same here
var httpRequest = request.Properties["httpRequest"] as HttpRequestMessageProperty;
if (httpRequest == null) return request;
var httpMethod = httpRequest.Method.ToUpper();
var uri = request.Properties["Via"] as Uri;
if (uri == null) return request; // Still nothing much we can do
var url = uri.AbsoluteUri;
var urlFragment = url;
if (urlFragment.ToLower().StartsWith(_rootUrlLower)) urlFragment = urlFragment.Substring(_rootUrlLower.Length);
var operationInfo = RestHelper.GetMethodNameFromUrlFragmentAndContract(urlFragment, httpMethod, _contractType);
var urlParameters = RestHelper.GetUrlParametersFromUrlFragmentAndContract(urlFragment, httpMethod, _contractType);
if (httpMethod == "GET")
{
// TODO: Support GET if at all possible
throw new Exception("REST-GET operations are not currently supported in the chosen hosting environment. Please use a different HTTP Verb, or host in a different environment (such as WebApi). We hope to add this feature in a future version.");
// This is a REST GET operation. Therefore, there is no posted message. Instead, we have to decode the input parameters from the URL
var parameters = operationInfo.GetParameters();
if (parameters.Length != 1) throw new NotSupportedException("Only service methods/operations with a single input parameter can be mapped to REST-GET operations. Method " + operationInfo.Name + " has " + parameters.Length + " parameters. Consider changing the method to have a single object with multiple properties instead.");
var parameterType = parameters[0].ParameterType;
var parameterInstance = Activator.CreateInstance(parameterType);
foreach (var propertyName in urlParameters.Keys)
{
var urlProperty = parameterType.GetProperty(propertyName);
if (urlProperty == null) continue;
urlProperty.SetValue(parameterInstance, urlParameters[propertyName], null);
}
// Seralize the object back into a new request message
// TODO: We only need to do this for methods OTHER than GET
var format = GetMessageContentFormat(request);
switch (format)
{
case WebContentFormat.Xml:
var xmlStream = new MemoryStream();
var xmlSerializer = new DataContractSerializer(parameterInstance.GetType());
xmlSerializer.WriteObject(xmlStream, parameterInstance);
var xmlReader = XmlDictionaryReader.CreateTextReader(StreamHelper.ToArray(xmlStream), XmlDictionaryReaderQuotas.Max);
var newXmlMessage = Message.CreateMessage(xmlReader, int.MaxValue, request.Version);
newXmlMessage.Properties.CopyProperties(request.Properties);
newXmlMessage.Headers.CopyHeadersFrom(request.Headers);
if (format == WebContentFormat.Default)
{
if (newXmlMessage.Properties.ContainsKey(WebBodyFormatMessageProperty.Name)) newXmlMessage.Properties.Remove(WebBodyFormatMessageProperty.Name);
newXmlMessage.Properties.Add(WebBodyFormatMessageProperty.Name, WebContentFormat.Xml);
}
request = newXmlMessage;
break;
case WebContentFormat.Default:
case WebContentFormat.Json:
var jsonStream = new MemoryStream();
var serializer = new DataContractJsonSerializer(parameterInstance.GetType());
serializer.WriteObject(jsonStream, parameterInstance);
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(StreamHelper.ToArray(jsonStream), XmlDictionaryReaderQuotas.Max);
var newMessage = Message.CreateMessage(jsonReader, int.MaxValue, request.Version);
newMessage.Properties.CopyProperties(request.Properties);
newMessage.Headers.CopyHeadersFrom(request.Headers);
if (format == WebContentFormat.Default)
{
if (newMessage.Properties.ContainsKey(WebBodyFormatMessageProperty.Name)) newMessage.Properties.Remove(WebBodyFormatMessageProperty.Name);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, WebContentFormat.Json);
}
request = newMessage;
break;
default:
throw new NotSupportedException("Mesage format " + format.ToString() + " is not supported form REST/JSON operations");
}
}
return null;
}
private static WebContentFormat GetMessageContentFormat(Message message)
{
if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
{
var bodyFormat = message.Properties[WebBodyFormatMessageProperty.Name] as WebBodyFormatMessageProperty;
if (bodyFormat != null) return bodyFormat.Format;
}
return WebContentFormat.Default;
}
/// <summary>
/// Called after the operation has returned but before the reply message is sent.
/// </summary>
/// <param name="reply">The reply message. This value is null if the operation is one way.</param>
/// <param name="correlationState">The correlation object returned from the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest(System.ServiceModel.Channels.Message@,System.ServiceModel.IClientChannel,System.ServiceModel.InstanceContext)" /> method.</param>
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services;
using IdentityServer3.Shaolinq.DataModel;
using IdentityServer3.Shaolinq.DataModel.Interfaces;
using IdentityServer3.Shaolinq.Serialization;
using Newtonsoft.Json;
using Shaolinq;
namespace IdentityServer3.Shaolinq.Stores
{
public abstract class BaseTokenStore<TToken>
where TToken : class
{
protected readonly IIdentityServerOperationalDataAccessModel DataModel;
protected readonly DbTokenType TokenType;
private readonly IClientStore clientStore;
private readonly IScopeStore scopeStore;
private readonly JsonSerializerSettings jsonSerializerSettings;
protected BaseTokenStore(IIdentityServerOperationalDataAccessModel dataModel, DbTokenType tokenType, IClientStore clientStore, IScopeStore scopeStore)
{
this.DataModel = dataModel;
this.TokenType = tokenType;
this.clientStore = clientStore;
this.scopeStore = scopeStore;
this.jsonSerializerSettings = GetJsonSerializerSettings();
}
public abstract Task StoreAsync(string key, TToken value);
public async Task<TToken> GetAsync(string key)
{
var token = await DataModel.Tokens.SingleOrDefaultAsync(x => x.Key == key && x.TokenType == TokenType);
if (token == null || token.Expiry < DateTimeOffset.UtcNow)
{
return null;
}
return ConvertFromJson(token.JsonCode);
}
public async Task RemoveAsync(string key)
{
using (var scope = DataAccessScope.CreateReadCommitted())
{
await DataModel.Tokens.DeleteAsync(x => x.Key == key && x.TokenType == TokenType);
await scope.CompleteAsync();
}
}
public async Task<IEnumerable<ITokenMetadata>> GetAllAsync(string subject)
{
var tokens = DataModel.Tokens.Where(x => x.SubjectId == subject && x.TokenType == TokenType);
var results = (await tokens.ToListAsync()).Select(x => ConvertFromJson(x.JsonCode));
return results.Cast<ITokenMetadata>();
}
public async Task RevokeAsync(string subject, string client)
{
using (var scope = DataAccessScope.CreateReadCommitted())
{
await DataModel.Tokens.DeleteAsync(x => x.SubjectId == subject && x.ClientId == client && x.TokenType == TokenType);
await scope.CompleteAsync();
}
}
protected string ConvertToJson(TToken value)
{
return JsonConvert.SerializeObject(value, jsonSerializerSettings);
}
protected TToken ConvertFromJson(string json)
{
return JsonConvert.DeserializeObject<TToken>(json, jsonSerializerSettings);
}
private JsonSerializerSettings GetJsonSerializerSettings()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new ConverterContractResolver(clientStore, scopeStore)
};
return settings;
}
}
} |
using Oop.Loops;
using System.Collections.Generic;
namespace Oop.Collections
{
class ProgramX
{
static void Main2(string[] args)
{
IEnumerable<ProportionalPainter> painters = new ProportionalPainter[10];
IPainter painter = CompositePainterFactories.CreateGroup(painters);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Collections.Concurrent;
namespace Crawler
{
class Program
{
/*
相关文件默认路径;
*/
public static char sep = Path.DirectorySeparatorChar;//路径分隔符;
public static string ALL_ZIPS_URLS_SAVE_PATH = "E:" + sep + "ThinkGeo_All_ZipS_URL.xml"; //资源的超衔接信息;
public static string CategoryDirectoryPath = "E:" + sep + "Wiki zips";//资源下载到本地的保存路径;
public static string failed_download_zips_file = "e:" + sep + "failed.xml";//下载失败保存url;
//线程池开启线程个数;
public static int MAX_THREADS_COUNT = 3;
/// xml文件中用到的所有节点名字;
public const string ROOTNAME = "Category";
public const string NODENAME = "Zip";
public const string ATTRIBUTE_CHILDNUMBERS = "childNumbers";
// 下载用到的集合
private static ConcurrentQueue<Zip> ZipQueue = new ConcurrentQueue<Zip>();// 待下载
private static HashSet<Zip> DownloadingZipSet = new HashSet<Zip>();//正在下载
//用于线程同步的加锁对象;
public static object sycObj = new object();
//计时
public static TimeSpan startTime ;
public static TimeSpan endTime ;
// 汇报进度;
public static IDictionary<string, int> zipsWillDownloadTotal = new Dictionary<string, int>();
public static IDictionary<string, int> zipsHasDownload = new Dictionary<string, int>();
static void Main(string[] args)
{
// # 读取文件,提取zips的信息;
readZipsXml(ALL_ZIPS_URLS_SAVE_PATH);
// # 记录此时时间
startTime = new TimeSpan(DateTime.Now.Ticks);
// # 线程池执行下载;
Download();
Console.WriteLine("finished!!!");
}
/// <summary>
/// 使用线程池下载,并检测线程池;
/// </summary>
/// <param name="res_list"></param>
/// <returns></returns>
public static void Download()
{
// # 使用线程池执行下载;
int maxThreads, maxIoThread;// (辅助线程,i/o线程)的最大线程数
int availableThread, availableIoThread;// 可用线程数;
// 获取线程池最大线程数;
ThreadPool.GetMaxThreads(out maxThreads, out maxIoThread);
// 线程池启动线程;
for (int i = 0; i < MAX_THREADS_COUNT; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(threadWork));
}
// 进度汇报,线程池活动线程汇报;
while (true)
{
// 检测线程池是否都结束
ThreadPool.GetAvailableThreads(out availableThread, out availableIoThread);
if (maxThreads == availableThread)// 最大 = 可用
{
break;
}
Console.WriteLine("活跃线程数 = " + (maxThreads - availableThread));
//汇报下载进度
Thread.Sleep(5000);//每五秒汇报一次;
progressReport();
}
}
/// <summary>
/// 报告下载进度
/// </summary>
public static void progressReport()//只有主进程访问
{
int total,hasDownload;
double percentage;
//显示进度列表;
Console.WriteLine("{0,-25}{1,15}{2,15}{3,25}", "category", "will_count", "has_count", "percentage completion");
foreach (string key in zipsWillDownloadTotal.Keys)
{
zipsWillDownloadTotal.TryGetValue(key, out total);
lock (sycObj)
{
//while (!zipsHasDownload.TryGetValue(key, out hasDownload)) //一直取
//{ }
zipsHasDownload.TryGetValue(key,out hasDownload);
}
percentage = (hasDownload / (double)total) * 100;
if (percentage.ToString().Length>5)
{
Console.WriteLine(String.Format("{0,-25}{1,15}{2,15}{3,25}%", key,total, hasDownload, percentage.ToString().Substring(0, 4)));
}
else
{
Console.WriteLine(String.Format("{0,-25}{1,15}{2,15}{3,25}%", key,total, hasDownload, percentage.ToString()));
}
}
// 计算用时;
endTime = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = startTime.Subtract(endTime).Duration();
Console.WriteLine("\n已用时:"+ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒");
}
/// <summary>
/// 线程执行下载
/// </summary>
/// <param name="obj"> Resource res </param>
public static void threadWork(object obj)
{
Zip zip = null;
string category = null;
string dirPath = null;
string url = null;
Boolean isSuccess = true;
while (ZipQueue.Any<Zip>())
{
lock (sycObj)
{
// 从待下载队列取出分类
if (ZipQueue.Any<Zip>())
{
ZipQueue.TryDequeue(out zip);
DownloadingZipSet.Add(zip); //加入正在下载
}
else
{
if (!DownloadingZipSet.Any<Zip>())
{
Thread.CurrentThread.Abort();
//return;//队列为空,没有任务的线程都要退出; 下载失败的一直执行;
}
}
}
category = zip.category;
dirPath = CategoryDirectoryPath + Path.DirectorySeparatorChar + category;
url = zip.url;
//下载
isSuccess = DownloadRemoteFiles.download(url, dirPath, getFileNameFromUrl(url));
lock (sycObj)
{
//移除正在下载集合;
DownloadingZipSet.Remove(zip);
//下载成功从DownloadingZipSet移除zip
if (isSuccess)
{
//成功数加一;
zipsHasDownload[category]++;
}
//失败则放回ZipQueue
else
{
ZipQueue.Enqueue(zip);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="fileName">文件的绝对路径</param>
public static void readZipsXml(string fullPath)
{
foreach (string category in XmlOperations.getChildsName(fullPath,ROOTNAME))
{
//取每个分类下的url;
foreach (string url in XmlOperations.getChildsContent(fullPath, category))
{
ZipQueue.Enqueue(new Zip(category, url));
}
}
// 统计需要下载数目;
foreach (Zip zip in ZipQueue)
{
if (!zipsWillDownloadTotal.ContainsKey(zip.category))
{
zipsWillDownloadTotal.Add(zip.category, 0);
}
zipsWillDownloadTotal[zip.category]++;
}
// 初始化已经下载数目;
foreach (string category in zipsWillDownloadTotal.Keys)
{
zipsHasDownload.Add(category, 0);
}
}
public static string getFileNameFromUrl(string url)
{
string fileName = null;
fileName = url.Substring(url.LastIndexOf("/") + 1);
return fileName;
}
}
}
|
using System;
namespace Assets.Scripts.Models.Meds
{
public class Medicines : ConsumableItem
{
public override void Use(GameManager gameManager, Action<int> changeAmount = null)
{
base.Use(gameManager, changeAmount);
if (changeAmount != null)
changeAmount(1);
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Google.Maps;
using System.Web;
namespace DoGoService.Paths
{
public class WalkRequest
{
public List<DogWalk> DogWalks { get; set; }
public int OwnerId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Client_V10 = LightingBook.Test.Api.Client.v10.Models;
using Model = LightingBook.Test.Api.Common.Model;
namespace LightingBook.Test.Api.Library.Configuration
{
public class ClientModelMappingProfile : Profile
{
public ClientModelMappingProfile()
{
Setup_ClientModel_Model_V10();
}
private void Setup_ClientModel_Model_V10()
{
//// flight search response
//CreateMap<Client_V10.TravelCTMOBTApiModelsv5TravelTravelAvailabilityResponse, Model.Travel.TravelAvailabilityResponse>().ReverseMap();
//// flight search request
//CreateMap<Client_V10.TravelCTMOBTApiModelsv10TravelTravelAvailabilityRequest, Model.Travel.TravelAvailabilityRequest>().ReverseMap();
//// seat map search response
//CreateMap<Client_V10.TravelCTMOBTApiModelsv3SeatMapFlightSeatMap, Model.SeatMap.FlightSeatMap>()
// //.ForMember(dest => dest.Transport, opts => opts.MapFrom(src => src.Transport))
// .ReverseMap();
//// seat map search request
//CreateMap<Client_V10.TravelCTMOBTApiModelsv10SeatMapSeatMapSearchRequest, Model.SeatMap.SeatMapSearchRequest>().ReverseMap();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace SP_Bewegungserkennung
{
/**
* Class Geture, which describes a recoreded gesture consiting of points
*/
public class Gesture
{
public List<point> Points { get; set; }
public int gestureID { get; private set; }
public Gesture(int gestureID, List<point> p)
{
this.gestureID = gestureID;
Points = p;
Points.Sort(new pointComparer());
}
public void Add(point p)
{
int idx = Points.BinarySearch(p, new pointComparer());
if (idx < 0)
idx = ~idx;
Points.Insert(idx, p);
}
}
} |
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISE.SM.Common.DTO
{
public partial class RoleToGroupDto:BaseDto
{
public RoleToGroupDto()
{
this.PrimaryKeyName = "RgId";
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Linq;
namespace DemoWebApp.Models
{
public class DemoSystem
{
private ComposablePartCatalog _catalog;
private CompositionContainer _container;
public DemoSystem()
{
_catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin"));
_container = new CompositionContainer(_catalog);
}
public IEnumerable<string> ListDemos()
{
var exports = _container.GetExports<IDemo, IDemoMetadata>(null);
return from ex in exports
orderby ex.Metadata.DemoName
select ex.Metadata.DemoName;
}
public IEnumerable<string> RunDemo(string demoName)
{
var demos = _container.GetExports<IDemo,IDemoMetadata>();
var demo = demos.First(x => x.Metadata.DemoName == demoName);
return demo.Value.Run();
}
}
} |
using System;
using System.Collections.Generic;
namespace BSTree
{
public delegate void Traverse<Key, Value>(Key key, Value value) where Key : IComparable;
public interface IBSNode<Key, Value> where Key : IComparable
{
Value Find(Key key);
void Insert(Key key, Value value);
void Delete(Key key);
void InorderTraverse(Traverse<Key, Value> traverseFunc);
void PreorderTraverse(Traverse<Key, Value> traverseFunc);
void PostorderTraverse(Traverse<Key, Value> traverseFunc);
}
}
|
using System.CodeDom;
using InRule.Repository.Classifications;
namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering
{
public static partial class SdkCodeRenderingExtensions_ClassificationDef
{
public static CodeExpression ToCodeExpression(this ClassificationDef def, CodeTypeDeclarationEx outerClass)
{
outerClass.EnsureCreateClassificationDef();
//public DisplayName
//public Expression
//var value = new Func<InRule.Repository.Classifications.ClassificationDef>(() =>
//{
// var ret = new InRule.Repository.Classifications.ClassificationDef();
// ret.DisplayName = def.DisplayName;
// ret.Expression = def.Expression;
// return ret;
//}).Invoke();
var method = new CodeMethodReferenceExpression() {MethodName = "CreateClassificationDef"};
var invoke = new CodeMethodInvokeExpression() {Method = method};
invoke.Parameters.Add(def.DisplayName.ToCodeExpression());
invoke.Parameters.Add(def.Expression.ToCodeExpression());
return invoke;
}
public static void EnsureCreateClassificationDef(this CodeTypeDeclarationEx outerClass)
{
if (outerClass.ParentClass != null)
{
outerClass.ParentClass.EnsureCreateClassificationDef();
return;
}
var methodName = "CreateClassificationDef";
if (!outerClass.ContainsMethod(methodName))
{
var method = new CodeMemberMethodEx(outerClass);
method.Name = methodName;
method.Attributes |= MemberAttributes.Static;
method.ReturnType = typeof(ClassificationDef).ToCodeTypeReference();
method.Parameters.Add(new CodeParameterDeclarationExpression()
{
Name = "displayName",
Type = typeof(string).ToCodeTypeReference()
});
method.Parameters.Add(new CodeParameterDeclarationExpression()
{
Name = "expression",
Type = typeof(string).ToCodeTypeReference()
});
var type = typeof(ClassificationDef);
var codeTypeReference = type.ToCodeTypeReference();
var classificationDef = new CodeMethodVariableReferenceEx(method,
method.AddMethodVariable("classificationDef", codeTypeReference, type.CallCodeConstructor()));
classificationDef.SetProperty("DisplayName",
new CodeVariableReferenceExpression() {VariableName = "displayName"});
classificationDef.SetProperty("Expression",
new CodeVariableReferenceExpression() {VariableName = "expression"});
classificationDef.AddAsReturnStatement();
outerClass.AddMethod(method);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IslandProblem
{
public class AStarAlgo
{
public static List<Unit> Algo(Unit start, Unit goal, Map map)
{
List<Unit> openList = new List<Unit>() { start };
Dictionary<Unit, Unit> closedList = new Dictionary<Unit, Unit>();
start.G = 0;
start.F = Heuristic(start, goal);
while (openList.Count > 0)
{
Unit current = openList[0];
for (int i = 1; i < openList.Count; i++)
{
if (openList[i].F < current.F)
{
current = openList[i];
}
}
if (current == goal)
return ConstructPath(closedList, current);
openList.Remove(current);
foreach (Unit neighbour in current.Neighbours)
{
if (neighbour.Contents != 0)
{
int tempGCost = current.G + 1;
if (tempGCost < neighbour.G)
{
closedList.Add(neighbour, current);
neighbour.G = tempGCost;
neighbour.F = neighbour.G + Heuristic(neighbour, goal);
if (!openList.Contains(neighbour))
{
openList.Add(neighbour);
}
}
}
}
}
return null;
}
public static List<Unit> ConstructPath(Dictionary<Unit,Unit> closedList, Unit current)
{
List<Unit> path = new List<Unit>() { current };
while (closedList.ContainsKey(current))
{
current = closedList[current];
path.Insert(0, current);
}
return path;
}
/// <summary>
/// Euclidean Distance calculator
/// </summary>
/// <returns></returns>
public static double Heuristic(Unit a, Unit b) => Math.Sqrt(Math.Abs(((a.X - b.X) * 2) + ((a.Y - b.Y) * 2)));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.