text stringlengths 13 6.01M |
|---|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Security;
using System.Windows.Markup;
using JinHu.Visualization.Plotter2D;
[module: SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
[assembly: XmlnsDefinition(AssemblyConstants.DefaultXmlNamespace, "JinHu.Visualization.Plotter2D")]
[assembly: XmlnsDefinition(AssemblyConstants.DefaultXmlNamespace, "JinHu.Visualization.Plotter2D.Charts")]
[assembly: XmlnsDefinition(AssemblyConstants.DefaultXmlNamespace, "JinHu.Visualization.Plotter2D.DataSources")]
[assembly: XmlnsDefinition(AssemblyConstants.DefaultXmlNamespace, "JinHu.Visualization.Plotter2D.Common")]
[assembly: XmlnsPrefix(AssemblyConstants.DefaultXmlNamespace, "Plotter2D")]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers]
namespace JinHu.Visualization.Plotter2D
{
public static class AssemblyConstants
{
public const string DefaultXmlNamespace = "http://jinhuca.visualization.com/Plotter2D/1.0";
}
}
|
using System;
namespace Uintra.Infrastructure.Providers
{
public interface IClientTimezoneProvider
{
void SetClientTimezone(string ianaTimezoneId);
TimeZoneInfo ClientTimezone { get; }
}
}
|
using StardewModdingAPI;
using Microsoft.Xna.Framework;
using StardewModdingAPI.Events;
using StardewValley;
using System.Collections.Generic;
using StardewValley.Menus;
using StardewValley.Tools;
using System;
namespace MoreWeapons
{
public class ModEntry : Mod
{
public override void Entry(IModHelper helper)
{
MenuEvents.MenuChanged += MenuEvents_MenuChanged;
}
private void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e)
{
if (!Context.IsWorldReady)
return;
if (Game1.activeClickableMenu is ShopMenu)
{
ShopMenu shop = (ShopMenu)Game1.activeClickableMenu;
int mineLevelReached = Game1.mine?.lowestLevelReached ?? 0;
if (shop.portraitPerson is NPC && shop.portraitPerson.name == "Marlon")
{
Dictionary<Item, int> newItemsToSell = new Dictionary<Item, int>();
if (Game1.player.mailReceived.Contains("galaxySword"))
{
MeleeWeapon Waffe53 = new MeleeWeapon(53); //Galaxy Mace
newItemsToSell.Add(Waffe53, 15000);
}
if (mineLevelReached > 15)
{
MeleeWeapon Waffe55 = new MeleeWeapon(55); //Short Staff
newItemsToSell.Add(Waffe55, 2500);
}
if (mineLevelReached > 85)
{
MeleeWeapon Waffe56 = new MeleeWeapon(56); //Rogue Sword
newItemsToSell.Add(Waffe56, 7500);
}
if (mineLevelReached > 120)
{
MeleeWeapon Waffe58 = new MeleeWeapon(58); //Hero's Sword
newItemsToSell.Add(Waffe58, 450000);
}
if (mineLevelReached > 80)
{
MeleeWeapon Waffe59 = new MeleeWeapon(59); //Double edged Axe
newItemsToSell.Add(Waffe59, 7500);
}
if (mineLevelReached > 60)
{
MeleeWeapon Waffe64 = new MeleeWeapon(64); //Battle Axe
newItemsToSell.Add(Waffe64, 6500);
}
if (mineLevelReached > 25)
{
MeleeWeapon Waffe60 = new MeleeWeapon(60); //Basic Mace
newItemsToSell.Add(Waffe60, 3000);
}
if (mineLevelReached > 20)
{
MeleeWeapon Waffe62 = new MeleeWeapon(62); //Walking Stick
newItemsToSell.Add(Waffe62, 2500);
}
if (Game1.player.mailReceived.Contains("galaxySword"))
{
MeleeWeapon Waffe65 = new MeleeWeapon(65); //Galaxy Axe
newItemsToSell.Add(Waffe65, 15000);
}
if (mineLevelReached > 120)
{
MeleeWeapon Waffe63 = new MeleeWeapon(63); //Ice Sword
newItemsToSell.Add(Waffe63, 10000);
}
if (mineLevelReached > 5)
{
MeleeWeapon Waffe67 = new MeleeWeapon(66); //Forest Sword
newItemsToSell.Add(Waffe67, 750);
}
if (mineLevelReached > 90)
{
MeleeWeapon Waffe54 = new MeleeWeapon(54); //Steel Rapier
newItemsToSell.Add(Waffe54, 7000);
}
if (mineLevelReached > 10)
{
MeleeWeapon Waffe67 = new MeleeWeapon(67); //Old Dagger
newItemsToSell.Add(Waffe67, 200);
}
if (mineLevelReached > 80)
{
MeleeWeapon Waffe57 = new MeleeWeapon(57); //The blade of Wrath
newItemsToSell.Add(Waffe57, 10000);
}
if (mineLevelReached > 70)
{
MeleeWeapon Waffe68 = new MeleeWeapon(68); //The Death Reaper
newItemsToSell.Add(Waffe68, 5000);
}
if (mineLevelReached > 10)
{
MeleeWeapon Waffe69 = new MeleeWeapon(69); // Dark Katana
newItemsToSell.Add(Waffe69, 1500);
}
if (mineLevelReached > 50)
{
MeleeWeapon Waffe70 = new MeleeWeapon(70); // Mysterious Katana
newItemsToSell.Add(Waffe70, 5000);
}
if (mineLevelReached > 100)
{
MeleeWeapon Waffe71 = new MeleeWeapon(71); // Viking King Blade
newItemsToSell.Add(Waffe71, 10000);
}
Dictionary<Item, int[]> items = Helper.Reflection.GetPrivateValue<Dictionary<Item, int[]>>(shop, "itemPriceAndStock");
List<Item> selling = Helper.Reflection.GetPrivateValue<List<Item>>(shop, "forSale");
foreach (Item item in newItemsToSell.Keys)
{
items.Add(item, new int[] { newItemsToSell[item], int.MaxValue });
selling.Add(item);
}
}
}
}
}
}
|
using System;
using System.IO;
namespace DelegatesAndEvents.FileSearch
{
//new feature of .net core.
public class FileFoundArgs// : EventArgs
{
public string FoundFile { get; }
public bool CancelRequested { get; set; }
public FileFoundArgs(string fileName)
{
FoundFile = fileName;
}
}
internal class SearchDirectoryArgs : EventArgs
{
internal string CurrentSearchDirectory { get; }
internal int TotalDirs { get; }
internal int CompleteDirs { get; }
public SearchDirectoryArgs(string dir, int totalDirs, int completeDirs)
{
CurrentSearchDirectory = dir;
TotalDirs = totalDirs;
CompleteDirs = completeDirs;
}
}
public class FileSearcher
{
//public async EventHandler<FileFoundArgs> HandlerAsync;
public event EventHandler<FileFoundArgs> FileFound;
internal event EventHandler<SearchDirectoryArgs> DirectoryChanged
{
add { directoryChanged += value; }
remove { directoryChanged -= value; }
}
private EventHandler<SearchDirectoryArgs> directoryChanged;
public void Search(string directory, string searchPattern)
{
foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
{
FileFound?.Invoke(this, new FileFoundArgs(file));
}
}
public void Search(string directory, string searchPattern, bool searchSubDirs = false)
{
if (searchSubDirs)
{
var allDirectories = Directory.GetDirectories(directory, "*", SearchOption.AllDirectories);
var completeDirs = 0;
var totalDirs = allDirectories.Length + 1;
foreach (var dir in allDirectories)
{
System.Threading.Thread.Sleep(1);
directoryChanged?.Invoke(this,
new SearchDirectoryArgs(dir, totalDirs, completeDirs++));
//Recursively search this child directory
SearchDirectory(dir, searchPattern);
}
//Include the Current Directory
directoryChanged?.Invoke(this,
new SearchDirectoryArgs(directory, totalDirs, completeDirs++));
SearchDirectory(directory, searchPattern);
}
else
{
SearchDirectory(directory, searchPattern);
}
}
private void SearchDirectory(string directory, string searchPattern)
{
foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
{
var args = new FileFoundArgs(file);
FileFound?.Invoke(this, args);
if (args.CancelRequested) break;
}
}
public static void Run()
{
var filesFound = 1;
EventHandler<FileFoundArgs> onFileFound = (sender, eventArgs) =>
{
Console.WriteLine($"{filesFound}: {eventArgs.FoundFile}");
filesFound++;
};
var fileSearcher = new FileSearcher();
fileSearcher.FileFound += onFileFound;
fileSearcher.DirectoryChanged += (sender, eventArgs) =>
{
Console.Clear();
Console.Write($"Entering '{eventArgs.CurrentSearchDirectory}'.");
Console.WriteLine($" {eventArgs.CompleteDirs} of {eventArgs.TotalDirs} completed...");
};
fileSearcher.Search("/Users/jonatanmachado/estudo-react/counter-app", "*.js", true);
}
}
}
|
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using Phenix.Core.Net;
using Phenix.Core.Security;
namespace Phenix.Windows.Security
{
/// <summary>
/// 登录组件
/// </summary>
[Description("提供缺省登陆界面, 校验用户及升级服务")]
[ToolboxItem(true), ToolboxBitmap(typeof(LogOn), "Phenix.Services.Client.Security.LogOn")]
public sealed class LogOn : Component
{
/// <summary>
/// 初始化
/// </summary>
public LogOn()
: base() { }
/// <summary>
/// 初始化
/// </summary>
public LogOn(IContainer container)
: base()
{
if (container == null)
throw new ArgumentNullException("container");
container.Add(this);
}
#region 属性
/// <summary>
/// 登陆界面的标题
/// </summary>
[DefaultValue(null), Description("登陆界面的标题"), Category("Appearance")]
public string Title { get; set; }
/// <summary>
/// 登陆界面的标志
/// </summary>
[DefaultValue(null), Description("登陆界面的标志"), Category("Appearance")]
public Image Logo { get; set; }
/// <summary>
/// 升级文件的代理类型
/// 缺省为 null 代表将默认使用 Phenix.Core.Net.NetConfig.ProxyType
/// </summary>
[DefaultValue(null), Description("升级文件的代理类型\n默认为登录的代理类型"), Category("Behavior")]
public ProxyType? UpgradeProxyType { get; set; }
/// <summary>
/// 升级文件的服务地址
/// 缺省为 null 代表将默认使用 Phenix.Core.Net.NetConfig.ServicesAddress
/// </summary>
[DefaultValue(null), Description("升级文件的服务地址\n默认为登录的服务地址"), Category("Behavior")]
public string UpgradeServicesAddress { get; set; }
private readonly Collection<string> _upgradeFileFilters = new Collection<string>();
/// <summary>
/// 升级文件的过滤器集
/// </summary>
[Description("升级文件的过滤器集"), Category("Behavior")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor(typeof(UpgradeFileFiltersEditor), typeof(UITypeEditor))]
public Collection<string> UpgradeFileFilters
{
get { return _upgradeFileFilters; }
}
#endregion
#region 方法
/// <summary>
/// 执行
/// </summary>
public IPrincipal Execute()
{
return Execute<LogOnDialog>();
}
/// <summary>
/// 执行
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public IPrincipal Execute<T>()
where T : LogOnDialog
{
Csla.ApplicationContext.PropertyChangedMode = Csla.ApplicationContext.PropertyChangedModes.Windows;
return LogOnDialog.Execute<T>(Title, Logo, UpgradeProxyType, UpgradeServicesAddress, UpgradeFileFilters);
}
#endregion
#region 内嵌类
private class UpgradeFileFiltersEditor : CollectionEditor
{
public UpgradeFileFiltersEditor(Type type)
: base(type) { }
protected override Object CreateInstance(Type itemType)
{
return "*.dll";
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Constants
{
public const string GlobalDataContainer = "GlobalDataContainer";
public static readonly GlobalDataContainer dataContainer = FindDataContainer();
private static GlobalDataContainer FindDataContainer()
{
GameObject containerObject = GameObject.Find(GlobalDataContainer);
return containerObject.GetComponent<GlobalDataContainer>();
}
}
|
using UnityEngine;
using System.Collections;
public class platform : MonoBehaviour
{
float cont;
Animator animator;
public float time_bounce;
void Start ()
{
animator = gameObject.GetComponent<Animator>();
cont = time_bounce;
animator.SetBool("IsBounce",false);
}
void Update ()
{
cont += Time.deltaTime;
if (cont>=time_bounce)
{
animator.SetBool("IsBounce",false);
}
}
void OnCollisionEnter2D(Collision2D coll)
{
cont = 0.0f;
animator.SetBool("IsBounce",true);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebQLKhoaHoc;
using System.Data.Entity.Migrations;
using WebQLKhoaHoc.Models;
namespace WebQLKhoaHoc.Controllers
{
[CustomizeAuthorize(Roles = "1")]
public class AdminDSTacGiaController : Controller
{
private QLKhoaHocEntities db = new QLKhoaHocEntities();
// GET: AdminDSTacGia
public async Task<ActionResult> Index()
{
var dSTacGias = db.DSTacGias.Include(d => d.NhaKhoaHoc).Include(d => d.SachGiaoTrinh);
return View(await dSTacGias.ToListAsync());
}
// GET: AdminDSTacGia/Create
public ActionResult Create(int? id, int? manhakhoahoc )
{
var dsnguoidathamgia = db.DSTacGias.Where(p => p.MaSach == id).Select(p => p.MaNKH).ToList();
var lstAllNKH = db.NhaKhoaHocs.Where(p => !dsnguoidathamgia.Contains(p.MaNKH)).Select(p => new
{
p.MaNKH,
TenNKH = p.HoNKH + " " + p.TenNKH
}).ToList();
ViewBag.MaNKH = new SelectList(lstAllNKH, "MaNKH", "TenNKH");
ViewBag.manhakhoahoc = manhakhoahoc;
ViewBag.masach = id;
ViewBag.tensach = db.SachGiaoTrinhs.Find(id).TenSach;
return View();
}
// POST: AdminDSTacGia/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "MaSach,MaNKH,LaChuBien")] DSTacGia dSTacGia,int? manhakhoahoc )
{
if (ModelState.IsValid)
{
db.DSTacGias.Add(dSTacGia);
await db.SaveChangesAsync();
return RedirectToAction("Edit",new { id= dSTacGia.MaSach, manhakhoahoc = manhakhoahoc});
}
var dsnguoidathamgia = db.DSTacGias.Where(p => p.MaSach == dSTacGia.MaSach).Select(p => p.MaNKH).ToList();
var lstAllNKH = db.NhaKhoaHocs.Where(p => !dsnguoidathamgia.Contains(p.MaNKH)).Select(p => new
{
p.MaNKH,
TenNKH = p.HoNKH + " " + p.TenNKH
}).ToList();
ViewBag.MaNKH = new SelectList(lstAllNKH, "MaNKH", "TenNKH");
ViewBag.manhakhoahoc = manhakhoahoc;
ViewBag.masach = dSTacGia.MaSach;
ViewBag.tensach = db.SachGiaoTrinhs.Find(dSTacGia.MaSach).TenSach;
return View(dSTacGia);
}
// GET: AdminDSTacGia/Edit/5
public async Task<ActionResult> Edit(int? id, int? manhakhoahoc )
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
List<DSTacGia> dSTacGia = await db.DSTacGias.Where(p => p.MaSach == id).ToListAsync();
if (dSTacGia == null)
{
return HttpNotFound();
}
ViewBag.manhakhoahoc = manhakhoahoc;
ViewBag.masach = id;
ViewBag.tensach = db.SachGiaoTrinhs.Find(id).TenSach;
return View(dSTacGia);
}
// POST: AdminDSTacGia/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "MaSach,MaNKH,LaChuBien")] List<DSTacGia> dSTacGia,int? manhakhoahoc,int? masach)
{
if (ModelState.IsValid)
{
foreach (var x in dSTacGia) {
db.DSTacGias.AddOrUpdate(x);
}
await db.SaveChangesAsync();
return RedirectToAction("Edit",new { id = manhakhoahoc});
}
ViewBag.manhakhoahoc = manhakhoahoc;
ViewBag.masach = masach;
ViewBag.tensach = db.SachGiaoTrinhs.Find(masach).TenSach;
return View(dSTacGia);
}
// GET: AdminDSTacGia/Delete/5
public async Task<ActionResult> Delete(int? id,int? mankh, int? manhakhoahoc)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DSTacGia dSTacGia = await db.DSTacGias.Where(p => p.MaSach == id && p.MaNKH == mankh).FirstOrDefaultAsync();
if (dSTacGia == null)
{
return HttpNotFound();
}
ViewBag.manhakhoahoc = manhakhoahoc;
ViewBag.masach = id;
ViewBag.mankh = mankh;
return View(dSTacGia);
}
// POST: AdminDSTacGia/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id,int mankh,int? manhakhoahoc)
{
DSTacGia dSTacGia = await db.DSTacGias.Where(p => p.MaSach == id && p.MaNKH == mankh).FirstOrDefaultAsync();
db.DSTacGias.Remove(dSTacGia);
await db.SaveChangesAsync();
return RedirectToAction("Edit", new { id = id, manhakhoahoc = manhakhoahoc });
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Scr.PersonEntity
{
public class AdminScreeningRequestPersonEntityImport : Entity
{
public virtual ScreeningRequestPersonEntity ScreeningRequestPersonEntity { get; set; }
public virtual DateTime ImportDate { get; set; }
public virtual int PreviousID { get; set; }
public virtual string Notes { get; set; }
public virtual bool Archive { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace Parser_Console.Classes
{
public class Kad
{
public string Code { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public DateTime DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public List<string> Types => new List<string> { "Κύρια", "∆ευτερεύουσα", "Λοιπή","Βοηθητική"};
public bool isActive => DateEnd == null;
public bool isEligible => DateStart != null ? DateTime.Compare(DateStart, new DateTime(2020,1,31)) < 0 : false;
public bool isOk => isActive && isEligible;
public Kad()
{
}
public void Create(string text)
{
int nlIndex = text.IndexOf("\n");
if(nlIndex != -1)
{
CreateFromMulti(text);
}
else
{
CreateFromSingle(text);
}
}
private void CreateFromSingle(string text)
{
Code = text.Substring(0, text.IndexOf(" ")).Trim();
text = text.Replace(Code, "").Trim();
var typePair = Functions.GetIndexFromList(text, Types);
Description = text.Substring(0, typePair.Key).Trim();
text = text.Replace(Description, "").Trim();
Type = text.Substring(0, text.IndexOf(" ")).Trim();
text = text.Replace(Type, "").Trim();
GetDates(text);
}
private void CreateFromMulti(string text)
{
Code = text.Substring(0, text.IndexOf("\n")).Trim();
if (!Functions.IsAllDigits(Code))
{
Code = text.Substring(0, text.IndexOf(" ")).Trim();
}
text = text.Replace(Code, "").Trim();
var typePair = Functions.GetIndexFromList(text, Types);
int tIndex = typePair.Key;
Description = text.Substring(0, tIndex).Replace("\n"," ").Trim();
text = text.Substring(tIndex);
Type = text.Substring(0, text.IndexOf(" ")).Trim();
text = text.Replace(Type, "").Trim();
GetDates(text);
}
public void GetDates(string text)
{
MatchCollection matches = RegexCollection.DateLongYear.Matches(text);
DateStart = DateTime.ParseExact(matches[0].Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
if(matches.Count == 2)
{
DateEnd = DateTime.ParseExact(matches[1].Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyDev.EPS.Portal;
using EasyDev.EPS.Attributes;
namespace EasyDev.EPS.Portal
{
[DatabaseName("Oracle")]
public class Schema : AbstractModel
{
/// <summary>
/// SCHEMAID Field
/// </summary>
[KeyProperty]
public string SCHEMAID { get; set; }
/// <summary>
/// SCHEMANAME Field
/// </summary>
public string SCHEMANAME { get; set; }
/// <summary>
/// COMMENTS Field
/// </summary>
public string COMMENTS { get; set; }
/// <summary>
/// ISDEFAULT Field
/// </summary>
public string ISDEFAULT { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Web.UI;
namespace MVP.Sample.Web
{
public partial class _Default : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ucDependencyUC1.ParentControl = string.Format("Sample.{0}", ID); //Must be Unique
ucDependencyUC1.RelatedControls = new List<string>
{
"ucDependencyUC2"
};
ucDependencyUC2.ParentControl = string.Format("Sample.{0}", ID); //Must be Unique
ucDependencyUC2.RelatedControls = new List<string>
{
"ucDependencyUC1"
};
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class HeatmapLegendGenerator : MonoBehaviour {
[SerializeField]
private ColorVariable colorLow = null;
[SerializeField]
private ColorVariable colorMedium = null;
[SerializeField]
private ColorVariable colorHigh = null;
[SerializeField]
private RawImage img = null;
[SerializeField, Min(1)]
private int segments = 4;
private void Awake() {
int totalSegments = (this.segments * 2) + 1;
Texture2D text = new Texture2D(totalSegments, 1);
float fraction = 1f / (this.segments);
for(int i = 0; i < totalSegments; i++) {
Color color;
if(i < this.segments) {
color = Color.Lerp(this.colorLow, this.colorMedium, fraction * i);
} else if(i == segments) {
color = this.colorMedium;
} else {
color = Color.Lerp(this.colorMedium, this.colorHigh, fraction * (i - segments));
}
text.SetPixel(i, 0, color);
}
text.filterMode = FilterMode.Point;
text.Apply();
this.img.texture = text;
}
}
|
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public abstract class Class3DButton<T> : MonoBehaviour, IPointerClickHandler
{
[SerializeField]
protected UnityEvent<GameObject> _hitEventForPlayerContr;//Эвент для движения игрока
[SerializeField]
protected UnityEvent<T> _hitEventForMechanic;//Эвент для счета результата
[SerializeField]
protected UnityEvent<GameObject> _hitEventForCreatorText;//Эвент для создания объектов цифр
public GameObject TextNumOrSignOnScene;
public T WhatButton;
private bool _isLocked = false;
public void OnPointerClick(PointerEventData pointerEventData)
{
if(!_isLocked)
{
_hitEventForPlayerContr.Invoke(pointerEventData.pointerPress);
_hitEventForMechanic.Invoke(WhatButton);
_hitEventForCreatorText.Invoke(TextNumOrSignOnScene);
}
else
{
}
}
}
|
using Beeffective.Models;
using FluentAssertions;
using NUnit.Framework;
namespace Beeffective.Tests.Models.HoneycombModelTests
{
class RemoveCell : TestFixture
{
public override void SetUp()
{
base.SetUp();
CellModel1 = Sut.AddCell(CellModel1);
Sut.RemoveCell(CellModel1);
}
[Test]
public void Cells_DoesNotContain_AddedCellModel() =>
Sut.Cells.Should().NotContain(CellModel1);
}
}
|
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Application.Web.Services
{
public interface IEquipmentService
{
Task<TResult> GetAsync<TResult>(string url);
Task<HttpResponseMessage> PostAsJsonAsync<TModel>(string url, TModel model);
Task<HttpResponseMessage> GetAsync(string url);
void AddHeader(Dictionary<string,int> headerDictionary);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projekt_3_Schichten_Architektur
{
public interface IFachkonzept
{
List<Autor> GetAutoren();
List<Buch> GetBuecher(int Autoren_id = 0);
bool SpeichereAutor(string Name);
bool SpeichereBuch(int Autoren_id, string ISBN, string Titel);
bool LoescheAutor(int ID);
bool LoescheBuch(string ISBN);
bool AktualisiereAutor(int ID, string Name);
bool AktualisiereBuch(string ISBN, string Titel);
}
}
|
using System;
using System.Collections.Generic;
using SpatialEye.Framework.Client;
using SpatialEye.Framework.Features.Recipe;
using SpatialEye.Framework.Features;
namespace Lite
{
/// <summary>
/// A reques for displaying the details of a feature
/// </summary>
public class LiteDisplayFeatureDetailsRequestMessage : MessageBase
{
/// <summary>
/// Constructs the request
/// </summary>
/// <param name="sender">The originator of the request</param>
/// <param name="feature">The feature (recipe-holder) to show details for</param>
public LiteDisplayFeatureDetailsRequestMessage(Object sender, IFeatureRecipeHolder feature, FeatureGeometryFieldDescriptor geometryField = null, bool makeViewActive = false, bool startEditing = false)
: base(sender)
{
RecipeHolders = new List<IFeatureRecipeHolder> { feature };
SelectedGeometryFieldDescriptor = geometryField;
StartEditing = geometryField != null && startEditing;
MakeViewActive = makeViewActive;
}
/// <summary>
/// Constructs the request
/// </summary>
/// <param name="sender">The originator of the request</param>
/// <param name="feature">The features to show details for</param>
public LiteDisplayFeatureDetailsRequestMessage(Object sender, IList<IFeatureRecipeHolder> features, FeatureGeometryFieldDescriptor geometryField = null)
: base(sender)
{
RecipeHolders = new List<IFeatureRecipeHolder>(features);
SelectedGeometryFieldDescriptor = geometryField;
}
/// <summary>
/// The feature (recipe-holder) to show details for
/// </summary>
public IList<IFeatureRecipeHolder> RecipeHolders
{
get;
private set;
}
/// <summary>
/// The Geometry Field that was selected
/// </summary>
public FeatureGeometryFieldDescriptor SelectedGeometryFieldDescriptor
{
get;
private set;
}
/// <summary>
/// Make the view active
/// </summary>
public bool MakeViewActive
{
get;
private set;
}
/// <summary>
/// Start editing the geometry immediately
/// </summary>
public bool StartEditing
{
get;
private set;
}
}
}
|
using InRule.Runtime;
using InRuleLabs.AuthoringExtensions.RuleAppMetrics.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InRuleLabs.AuthoringExtensions.RuleAppMetrics.Models
{
internal class FactRuleExecution
{
public string HostMachine;
public string RuleAppSource;
public string RuleAppName;
public int? RuleAppRevision;
public int? RequestedRuleAppRevision;
public string RequestedRuleAppLabel;
public string RootEntityName;
public string RuleSetName;
public int RuleAppCacheCount;
public double RuleAppCacheUptimeMinutes;
public DateTime ExecutionFinishedTime;
public double RuleExecutionTimeMs;
public double TotalExecutionTimeMs;
public long CycleCount;
public long StateValueChanges;
public long TotalTraceFrames;
public long ValidationChanges;
public double MetadataCompileTimeMs;
public double FunctionCompileTimeMs;
public bool WasColdStart;
public double TotalCalculationFieldEvaluationTimeMs;
public double TotalActionExecutionTimeMs;
public double TotalRuleEvaluationTimeMs;
public int StateValueChangesCount;
public int ActionsExecutedCount;
public int CalculationFieldsEvaluatedCount;
public int ActiveValidationsCount;
public int ActiveNotificationsCount;
public int TrueRulesCount;
public int RuleSetsFiredCount;
public int RulesEvaluatedCount;
public double ExternalSmtpCallTimeMs;
public int ExternalSmtpCallCount;
public double ExternalMethodCallTimeMs;
public int ExternalMethodCallCount;
public double ExternalDataQueryCallTimeMs;
public int ExternalDataQueryCallCount;
public double ExternalWebServiceCallTimeMs;
public int ExternalWebServiceCallCount;
public double BoundStateRefreshTimeMs;
public int BoundStateRefreshCount;
public double ExternalWorkflowCallTimeMs;
public int ExternalWorkflowCallCount;
public bool HasErrors;
public string ErrorMessages;
public int TotalRuleElementCount;
public int HitRuleElementCount;
public void ImportExecutionLog(RuleExecutionLog log)
{
int numOfDecimalPlaces = 3;
RuleExecutionTimeMs = log.RuleExecutionTime.TotalMilliseconds.Round(numOfDecimalPlaces);
TotalExecutionTimeMs = log.TotalExecutionTime.TotalMilliseconds.Round(numOfDecimalPlaces);
CycleCount = log.CycleCount;
TotalTraceFrames = log.TotalTraceFrames;
StateValueChanges = log.StateValueChanges.Count;
ValidationChanges = log.ValidationChanges.Count;
if (log.Statistics != null)
{
MetadataCompileTimeMs = log.Statistics.MetadataCompileTime.TotalMilliseconds.Round(numOfDecimalPlaces);
FunctionCompileTimeMs = log.Statistics.FunctionCompileTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
WasColdStart = MetadataCompileTimeMs > 0 || FunctionCompileTimeMs > 0;
TotalCalculationFieldEvaluationTimeMs = log.Statistics.TotalCalculationFieldEvaluationTime.TotalMilliseconds.Round(numOfDecimalPlaces);
TotalActionExecutionTimeMs = log.Statistics.TotalActionExecutionTime.TotalMilliseconds.Round(numOfDecimalPlaces);
TotalRuleEvaluationTimeMs = log.Statistics.TotalRuleEvaluationTime.TotalMilliseconds.Round(numOfDecimalPlaces);
StateValueChangesCount = log.Statistics.StateValueChangesCount;
ActionsExecutedCount = log.Statistics.ActionsExecutedCount;
CalculationFieldsEvaluatedCount = log.Statistics.CalculationFieldsEvaluatedCount;
ActiveValidationsCount = log.Statistics.ActiveValidationsCount;
ActiveNotificationsCount = log.Statistics.ActiveNotificationsCount;
TrueRulesCount = log.Statistics.TrueRulesCount;
RuleSetsFiredCount = log.Statistics.RuleSetsFiredCount;
RulesEvaluatedCount = log.Statistics.RulesEvaluatedCount;
ExternalSmtpCallTimeMs = log.Statistics.ExternalSmtpCallTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
ExternalSmtpCallCount = log.Statistics.ExternalSmtpCallTime.SampleCount;
ExternalMethodCallTimeMs = log.Statistics.ExternalMethodCallTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
ExternalMethodCallCount = log.Statistics.ExternalMethodCallTime.SampleCount;
ExternalDataQueryCallTimeMs = log.Statistics.ExternalDataQueryCallTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
ExternalDataQueryCallCount = log.Statistics.ExternalDataQueryCallTime.SampleCount;
ExternalWebServiceCallTimeMs = log.Statistics.ExternalWebServiceCallTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
ExternalWebServiceCallCount = log.Statistics.ExternalWebServiceCallTime.SampleCount;
BoundStateRefreshTimeMs = log.Statistics.BoundStateRefreshTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
BoundStateRefreshCount = log.Statistics.BoundStateRefreshTime.SampleCount;
ExternalWorkflowCallTimeMs = log.Statistics.ExternalWorkflowCallTime.RunningTotal.TotalMilliseconds.Round(numOfDecimalPlaces);
ExternalWorkflowCallCount = log.Statistics.ExternalWorkflowCallTime.SampleCount;
}
HasErrors = log.HasErrors;
if (log.HasErrors)
{
ErrorMessages = string.Join("|", log.ErrorMessages.Select(m => $"{m.SourceElementId}:{m.Exception}"));
}
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace Mercadinho.DAO
{
class EnderecoDAO
{
private Model.Endereco enderecomodel;
private MySqlConnection con;
private Conexao.Conexao conexao;
public EnderecoDAO()
{
}
public void InserirDados(String Bairro, String Cidade, String Numero, String Cep, String Rua, String Cpfcliente)
{
con = new MySqlConnection();
enderecomodel = new Model.Endereco();
conexao = new Conexao.Conexao();
con.ConnectionString = conexao.getConnectionString();
String query = "INSERT INTO endereco(Bairro, Cidade, Numero, Cep, Rua, CPF)";
query += " VALUES (?Bairro, ?Cidade, ?Numero, ?Cep, ?Rua, ?CPF)";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("?Bairro", Bairro);
cmd.Parameters.AddWithValue("?Cidade", Cidade);
cmd.Parameters.AddWithValue("?Numero", Numero);
cmd.Parameters.AddWithValue("?Cep", Cep);
cmd.Parameters.AddWithValue("?Rua", Rua);
cmd.Parameters.AddWithValue("?CPF", Cpfcliente);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex);
}
finally
{
con.Close();
}
}
public void AtualizarDadosEndereco(String Bairro, String Cidade, String Numero, String Cep, String Rua, String Cpfcliente, int Id_Endereco)
{
con = new MySqlConnection();
conexao = new Conexao.Conexao();
con.ConnectionString = conexao.getConnectionString();
String query = "UPDATE endereco SET Bairro = ?Bairro, Cidade = ?Cidade, Numero = ?Numero, CEP = ?CEP, Rua = ?Rua, CPF = ?CPF WHERE Id_Endereco = ?Id_Endereco";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("?Bairro", Bairro);
cmd.Parameters.AddWithValue("?Cidade", Cidade);
cmd.Parameters.AddWithValue("?Numero", Numero);
cmd.Parameters.AddWithValue("?CEP", Cep);
cmd.Parameters.AddWithValue("?Rua", Rua);
cmd.Parameters.AddWithValue("?CPF", Cpfcliente);
cmd.Parameters.AddWithValue("?Id_Endereco", Id_Endereco);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex);
}
finally
{
con.Close();
}
}
public void RemoverDadosCliente(String CPF)
{
con = new MySqlConnection();
conexao = new Conexao.Conexao();
con.ConnectionString = conexao.getConnectionString();
String query = "DELETE FROM endereco where CPF = ?CPF";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("?CPF", CPF);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
finally
{
con.Close();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
/*
* @Author Jake Botka
*/
[HelpURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ")]
public class RoomSet : MonoBehaviour
{
public const string _StartingRoomTag = "Room Start";
public const string _RoomTag = "Room";
public enum Direction
{
Null, Left,Right,Down,Up
}
public GameObject _StartingRoom;
public GameObject[] _RoomTypePrefabs;
public GameObject[] _BossRoomPrefabs;
public GameObject[] _ShopRoomPrefabs;
public int _NumberOfRooms;
public Vector3 _Origin;
[HideInInspector] public FloorMapper _FloorMapper;
private Coroutine _WaitCoroutine;
[Header("DO NOT SET")]
public Room[] _Rooms;
public List<Room> _GeneratedRoomsOrdered;
public List<Room> _ActiveRooms;
public List<Room> _ExploredRooms;
public List<Room> _UnexploredRooms;
public List<Room> _DestroyedRooms;
public List<Direction> _DirectionPlacementHistroy;
public Room _CurrentRoom;
public bool[] _DirectionEnpointsBlocked;
private Vector3 _LastDirectionPos;
private Direction _LastDirection;
void Awake()
{
_Rooms = null;
_CurrentRoom = null;
if (_NumberOfRooms < 0)
{
_NumberOfRooms = 0;
}
_LastDirectionPos = Vector3.zero;
_GeneratedRoomsOrdered = new List<Room>();
_ActiveRooms = new List<Room>();
_ExploredRooms = new List<Room>();
_UnexploredRooms = new List<Room>();
_DestroyedRooms = new List<Room>();
_DirectionPlacementHistroy = new List<Direction>();
_LastDirection = Direction.Null;
_DirectionEnpointsBlocked = new bool[4];
_DirectionEnpointsBlocked[0] = false;
_DirectionEnpointsBlocked[1] = false;
_DirectionEnpointsBlocked[2] = false;
_DirectionEnpointsBlocked[3] = false;
}
void Start()
{
_Rooms = new Room[_NumberOfRooms];
_WaitCoroutine = StartCoroutine(WaitTillAllLoaded());
_FloorMapper = GetComponentInChildren<FloorMapper>();
GenerateMap();
StartCoroutine(BossCheck());
}
// Update is called once per frame
void FixedUpdate()
{
if (_WaitCoroutine == null)
{
}
}
private IEnumerator BossCheck()
{
yield return new WaitForSecondsRealtime(.1f);
PlayerInRoom[] piy = FindObjectsOfType<PlayerInRoom>();
bool hasBossRoom = false;
foreach (PlayerInRoom p in piy)
{
if (p.roomType == "Boss")
{
hasBossRoom = true;
}
}
if (!hasBossRoom)
{
Debug.Log("Boss bug happened");
Barrel[] allbarrels = FindObjectsOfType<Barrel>();
foreach (Barrel bar in allbarrels)
{
bar.itemToSpawn = null;
}
ItemDrops[] allItems = FindObjectsOfType<ItemDrops>();
foreach (ItemDrops itemDrop in allItems)
{
itemDrop.possibleCommonDrops = new GameObject[0];
itemDrop.possibleRareDrops = new GameObject[0];
itemDrop.possibleLegendaryDrops = new GameObject[0];
}
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
public IEnumerator WaitTillAllLoaded()
{
yield return new WaitUntil(() => IsRoomsLoaded());
//Debug.Log("Rooms Loadded");
if (_Rooms != null)
{
foreach (Room room in _Rooms)
{
if (room.gameObject.tag == _StartingRoomTag)
{
//Debug.Log(room.gameObject.tag);
ActivateRoom(room);
break;
}
}
}
_WaitCoroutine = null;
}
public bool IsRoomsLoaded()
{
if (_Rooms != null)
{
foreach (Room room in _Rooms)
{
if (room != null)
{
if (room.gameObject.tag == _StartingRoomTag)
{
if (room.enabled == false)
{
return true;
}
}
}
}
}
return false;
}
public void GenerateMap()
{
if (_Rooms != null && _RoomTypePrefabs != null)
{
GameObject prefab = null;
for (int i =0; i < _NumberOfRooms; i++)
{
if (IsAllEndpointsBlocked())
{
return;
}
prefab = RoomPicker.PickRoomAtRandom(_RoomTypePrefabs);
//GET RANDOM ROOM
if (i == 0)
{
prefab = _StartingRoom;
_FloorMapper.Init(prefab);
Tuple tuple = GetNewPosition(null, prefab, _FloorMapper._BranchEndpoints[0]);
AddRoom(i, prefab,tuple.pos, prefab.GetComponentInChildren<Room>(), Room.RoomType.Normal);
}
else if (i == Mathf.FloorToInt((float)_NumberOfRooms / 2)) // middle
{
GenerateRoom(i, prefab.GetComponentInChildren<Room>(), RoomPicker.PickRoomAtRandom(_ShopRoomPrefabs), _GeneratedRoomsOrdered.ToArray()[_GeneratedRoomsOrdered.Count - 1].gameObject, Direction.Null, Room.RoomType.Shop);
}
else if (i + 1 == _NumberOfRooms) // last room
{
//Debug.Log("Generating boss");
GenerateRoom(i, prefab.GetComponentInChildren<Room>(), RoomPicker.PickRoomAtRandom(_BossRoomPrefabs), _GeneratedRoomsOrdered.ToArray()[_GeneratedRoomsOrdered.Count - 1].gameObject, Direction.Null, Room.RoomType.Boss);
}
else
{
GenerateRoom(i, prefab.GetComponentInChildren<Room>(), prefab, _GeneratedRoomsOrdered.ToArray()[_GeneratedRoomsOrdered.Count - 1].gameObject, Direction.Null, Room.RoomType.Normal);
}
}
}
}
public void GenerateRoom(int index, Room room, GameObject prefab, GameObject lastRoom, Direction direction, Room.RoomType roomType)
{
Direction dir = direction;
dir = dir != Direction.Null ? dir : ChooseSide();
int i = -1;
switch (dir) // switch direction
{
case Direction.Null:
i = -1;
break;
case Direction.Left:
i = 3;
break;
case Direction.Right:
i = 1;
break;
case Direction.Up:
i = 0;
break;
case Direction.Down:
i = 2;
break;
}
GameObject chosenPreviousRoom = null;
if (!_DirectionEnpointsBlocked[i])
{
BranchEndPoint endPoint = _FloorMapper._BranchEndpoints[i];
//Debug.Log(endPoint);
chosenPreviousRoom = _FloorMapper._BranchEndpoints[i]._EndPoint;
Tuple tuple = GetNewPosition(chosenPreviousRoom, lastRoom, endPoint);
if (tuple != null)
{
Vector3 pos = tuple.pos;
if (pos != Vector3.zero)
{
lastRoom = endPoint._EndPoint;
_FloorMapper.Add(endPoint, AddRoom(index, prefab, pos, room,roomType), tuple.indeces, tuple.dir);
}
else
{
_DirectionEnpointsBlocked[i] = true;
GenerateRoom(index, room, prefab, lastRoom, ClockwiseChoice(dir),roomType);
}
}
}
else
{
if (!IsAllEndpointsBlocked())
GenerateRoom(index, room, prefab, lastRoom, ClockwiseChoice(dir),roomType);
//else
//Debug.Log("All endpoints are blocked");
}
}
public bool IsBlocking(BranchEndPoint endpoint, Direction dir)
{
int[] x = _FloorMapper.GetIndecies(endpoint._EndPointIndeces, dir);
return _FloorMapper.IsBLocking(x[0], x[1]);
}
public bool IsEndpointBlocking(GameObject endpoint)
{
int index = 0;
foreach (BranchEndPoint endP in _FloorMapper._BranchEndpoints)
{
GameObject obj = endP._EndPoint;
if (obj.name == endpoint.name)
{
return _DirectionEnpointsBlocked[index];
}
index++;
}
return false;
}
public bool IsAllEndpointsBlocked()
{
if (_DirectionEnpointsBlocked[0] == true && _DirectionEnpointsBlocked[1] == true && _DirectionEnpointsBlocked[2] == true && _DirectionEnpointsBlocked[3] == true )
{
return true;
}
return false;
}
public GameObject AddRoom(int index, GameObject prefab, Vector3 pos, Room room, Room.RoomType roomType)
{
//Debug.Log("Room Added");
if (_Rooms != null && index >= 0)
{
_Rooms[index] = room;
_GeneratedRoomsOrdered.Add(room);
GameObject x = ObjectSpawner.SpawnGameObject(prefab, pos, Quaternion.identity);
x.name = "Room - " + index;
switch (roomType)
{
case Room.RoomType.Normal:
x.name += "-Noraml Room";
break;
case Room.RoomType.Shop:
x.name += "-Shop Room";
break;
case Room.RoomType.Boss:
x.name += "-Boss Room";
break;
}
return x;
}
return null;
}
public void RemoveRoom(Room room)
{
Destroy(room.gameObject);
}
public Tuple GetNewPosition(GameObject previousSpawn, GameObject needSpawn, BranchEndPoint endP)
{
if (previousSpawn == null)
return new Tuple(_Origin, null, _LastDirection);
else
{
int count = 0;
while (true)
{
Direction dir = Direction.Null;
if (_LastDirection == Direction.Null)
{
dir = Direction.Left;
_DirectionPlacementHistroy.Add(dir);
_LastDirection = dir;
}
else
{
dir = ClockwiseChoice(_LastDirection);
_LastDirection = dir;
}
int[] indeces = _FloorMapper.GetIndecies(endP._EndPointIndeces, dir);
if (!_FloorMapper.IsBLocking(indeces[0], indeces[1]))
{
//Debug.Log(indeces[0] + "," + indeces[1] + "," + dir.ToString());
Vector3 pos = ProbeNewPosition(previousSpawn, needSpawn.GetComponentInChildren<Renderer>().bounds.size, dir);
return new Tuple(pos, indeces, dir);
}
else if (count < 4)
{
_LastDirection = ClockwiseChoice(_LastDirection);
}
else
{
return null;
}
count++;
}
}
//return Vector3.zero;
}
public Vector3 ProbeNewPosition(GameObject previousSpawn, Vector3 size2, Direction dir)
{
Vector3 size1 = previousSpawn.GetComponentInChildren<Renderer>().bounds.size;
float unitsToMoveX = (size1.x / 2) + (size2.x / 2);
float unitsToMoveY = (size1.y / 2) + (size2.y / 2);
switch (dir)
{
case Direction.Null:
break;
case Direction.Left:
return new Vector3(previousSpawn.transform.position.x - unitsToMoveX, previousSpawn.transform.position.y, previousSpawn.transform.position.z);
case Direction.Right:
return new Vector3(previousSpawn.transform.position.x + unitsToMoveX, previousSpawn.transform.position.y, previousSpawn.transform.position.z);
case Direction.Up:
return new Vector3(previousSpawn.transform.position.x, previousSpawn.transform.position.y + unitsToMoveY, previousSpawn.transform.position.z);
case Direction.Down:
return new Vector3(previousSpawn.transform.position.x, previousSpawn.transform.position.y - unitsToMoveY, previousSpawn.transform.position.z);
}
return Vector3.zero;
}
public Direction ChooseSide()
{
int num = Random.Range(0, 3);
switch (num)
{
case 0:
return Direction.Left;
case 1:
return Direction.Right;
case 2:
return Direction.Down;
case 3:
return Direction.Up;
default:
break;
}
return Direction.Null;
}
public Direction ClockwiseChoice(Direction prev)
{
Direction dir = prev;
switch (dir) // switch direction
{
case Direction.Null:
dir = Direction.Left;
break;
case Direction.Left:
dir = Direction.Up;
break;
case Direction.Right:
dir = Direction.Down;
break;
case Direction.Up:
dir = Direction.Right;
break;
case Direction.Down:
dir = Direction.Left;
break;
}
return dir;
}
public void EnterRoom(Room oldRoom ,Room newRoom)
{
if (IsInList(_UnexploredRooms, newRoom))
{
_UnexploredRooms.Remove(newRoom);
_ExploredRooms.Add(newRoom);
}
else
{
if (!IsInList(_ExploredRooms, newRoom))
{
_ExploredRooms.Add(newRoom);
}
}
}
public bool IsInList(List<Room> list, Room room)
{
foreach(Room r in list)
{
if (r.gameObject.name == room.gameObject.name)
{
return true;
}
}
return false;
}
public void ActivateRoom(Room room)
{
room.enabled = true;
DisableCurrentRoom();
_CurrentRoom = room;
}
public void DisableCurrentRoom()
{
if (_CurrentRoom != null)
{
DisableRoom(_CurrentRoom);
}
}
public void DisableRoom(Room room)
{
_CurrentRoom = null;
room.gameObject.SetActive(false);
}
}
public class Tuple
{
public Vector3 pos;
public int[] indeces;
public RoomSet.Direction dir;
public Tuple(Vector3 pos, int[] indeces, RoomSet.Direction dir)
{
this.pos = pos;
this.indeces = indeces;
this.dir = dir;
}
}
public static class RoomPicker
{
public static GameObject PickRoomAtRandom(GameObject[] prefabs)
{
GameObject room = null;
int index = Random.Range(0, prefabs.Length);
room = prefabs[index];
return room;
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.WorkFlow
{
public class WFCommEntity
{
/// <summary>
/// 文件编号
/// </summary>
[DataMember]
public string FileId;
/// <summary>
/// 文件层级
/// </summary>
[DataMember]
public string FileHierarchy;
/// <summary>
/// 适用类型
/// </summary>
[DataMember]
public string AreaType;
/// <summary>
/// 适用范围
/// </summary>
[DataMember]
public string Area;
/// <summary>
/// 公司名称
/// </summary>
[DataMember]
public string Company;
/// <summary>
/// 部门
/// </summary>
[DataMember]
public string Depart;
/// <summary>
/// 申请人AD
/// </summary>
[DataMember]
public string ApplicantAD;
/// <summary>
///审批人角色
/// </summary>
[DataMember]
public string ApproverRole;
/// <summary>
/// 审批人姓名
/// </summary>
[DataMember]
public string ApproverName;
/// <summary>
/// 审批选项
/// </summary>
[DataMember]
public string ApproverOpion;
/// <summary>
/// 审批步骤
/// </summary>
[DataMember]
public string Step;
/// <summary>
/// 流程类型
/// </summary>
[DataMember]
public string WFType;
/// <summary>
/// 文件标签
/// </summary>
[DataMember]
public string AssTag;
/// <summary>
/// 文件类型
/// </summary>
[DataMember]
public string FileName;
/// <summary>
/// 文件类型
/// </summary>
[DataMember]
public string FileType;
/// <summary>
/// 文件大类
/// </summary>
[DataMember]
public string BigClass;
/// <summary>
/// 文件小类
/// </summary>
[DataMember]
public string SmallClass;
/// <summary>
/// OEM厂商
/// </summary>
[DataMember]
public string OEM;
/// <summary>
/// OEM关键字
/// </summary>
[DataMember]
public string OEMKey;
/// <summary>
/// TC流程编码
/// </summary>
[DataMember]
public string AssWF;
/// <summary>
/// 分发编号
/// </summary>
[DataMember]
public string DisId;
/// <summary>
/// 分发类型
/// </summary>
[DataMember]
public string DisType;
/// <summary>
/// 分发类别
/// </summary>
[DataMember]
public string DisClass;
/// <summary>
/// 岗位
/// </summary>
[DataMember]
public string Job;
/// <summary>
/// 项目Ep号码
/// </summary>
[DataMember]
public string EPNum;
/// <summary>
/// 借阅编号
/// </summary>
[DataMember]
public string BorrowId;
/// <summary>
/// 文件等级
/// </summary>
[DataMember]
public string FileLevel;
/// <summary>
/// 涉及职能部门
/// </summary>
[DataMember]
public string ReFunction;
/// <summary>
/// 公司
/// </summary>
[DataMember]
public string AreaCompany;
/// <summary>
/// 直系部门
/// </summary>
[DataMember]
public string DirectDepartment;
/// <summary>
///特定人
/// </summary>
[DataMember]
public string DirectPeople;
/// <summary>
///流程编号
/// </summary>
[DataMember]
public string WFinstId;
/// <summary>
/// L1
/// </summary>
[DataMember]
public string L1;
/// <summary>
/// L2
/// </summary>
[DataMember]
public string L2;
/// <summary>
/// L3
/// </summary>
[DataMember]
public string L3;
/// <summary>
/// 产线
/// </summary>
[DataMember]
public string ProjectLine;
/// <summary>
///分发部门直接径路
/// </summary>
[DataMember]
public string ShareDepartManager;
/// <summary>
///分发部门高级经理
/// </summary>
[DataMember]
public string ShareDeparSM;
/// <summary>
///接收部门
/// </summary>
[DataMember]
public string AcceptDepartment;
}
}
|
using System;
using System.ComponentModel;
using SQLite;
namespace ContactListSample.Models
{
public class Contact : BaseModel
{
[PrimaryKey, AutoIncrement]
public int ContactId { get; set; }
public string Name { get; set; }
//public string Image { get; set; }
//public string[] Emails { get; set; }
public string[] PhoneNumbers { get; set; }
//public string Number { get; set; }
//public int Value { get; set; }
bool _isVisible;
public bool IsVisible
{
get
{
return _isVisible;
}
set
{
_isVisible = value;
OnPropertyChanged("IsVisible");
}
}
bool _isSelected;
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace VoxelSpace {
public class FPSCamera {
public Vector2 Look;
public float Sensitivity = 5;
public Matrix ViewMatrix =>
Matrix.Invert(Rotation);
Point _screenCenter;
public Matrix Rotation =>
Matrix.CreateRotationX(MathHelper.ToRadians(-Look.Y)) *
Matrix.CreateRotationY(MathHelper.ToRadians(-Look.X));
public FPSCamera(Point screenCenter) {
_screenCenter = screenCenter;
Mouse.SetPosition(screenCenter.X, screenCenter.Y);
}
Vector3 _input = Vector3.Zero;
public void Update(float deltaTime) {
var state = Mouse.GetState();
var point = state.Position;
point -= _screenCenter;
var delta = point.ToVector2();
delta *= deltaTime * Sensitivity;
Look.X += delta.X;
Look.Y += delta.Y;
Look.Y = MathHelper.Clamp(Look.Y, -90, 90);
Mouse.SetPosition(_screenCenter.X, _screenCenter.Y);
}
}
} |
using Alabo.Domains.Services;
using Alabo.Framework.Basic.Storages.Domain.Entities;
using Microsoft.AspNetCore.Http;
using MongoDB.Bson;
namespace Alabo.Framework.Basic.Storages.Domain.Services {
public interface IStorageFileService : IService<StorageFile, ObjectId> {
/// <summary>
/// 上传图片
/// </summary>
/// <param name="files"></param>
/// <param name="basePath"></param>
/// <returns></returns>
StorageFile Upload(IFormFileCollection files, string basePath);
}
} |
using System.Security.Claims;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Moq;
using NUnit.Framework;
using SFA.DAS.Provider.Shared.UI.Models;
using SFA.DAS.ProviderCommitments.Web.Authentication;
using SFA.DAS.ProviderCommitments.Web.Filters;
using SFA.DAS.ProviderCommitments.Web.UnitTests.Customisations;
using SFA.DAS.Testing.AutoFixture;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Filters
{
public class WhenAddingGoogleAnalyticsInformation
{
[Test, DomainAutoData]
public async Task ThenProviderIdIsAddedToViewBag(
uint ukPrn,
[ArrangeActionContext] ActionExecutingContext context,
[Frozen] Mock<ActionExecutionDelegate> nextMethod,
GoogleAnalyticsFilter filter)
{
//Arrange
var claim = new Claim(ProviderClaims.Ukprn, ukPrn.ToString());
context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }));
//Act
await filter.OnActionExecutionAsync(context, nextMethod.Object);
//Assert
var actualController = context.Controller as Controller;
Assert.IsNotNull(actualController);
var viewBagData = actualController.ViewBag.GaData as GaData;
Assert.IsNotNull(viewBagData);
Assert.AreEqual(ukPrn.ToString(), viewBagData.UkPrn);
}
[Test, DomainAutoData]
public async Task AndContextIsNonController_ThenNoDataIsAddedToViewbag(
long ukPrn,
[ArrangeActionContext] ActionExecutingContext context,
[Frozen] Mock<ActionExecutionDelegate> nextMethod,
GoogleAnalyticsFilter filter)
{
//Arrange
var claim = new Claim(ProviderClaims.Ukprn, ukPrn.ToString());
context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }));
var contextWithoutController = new ActionExecutingContext(
new ActionContext(context.HttpContext, context.RouteData, context.ActionDescriptor),
context.Filters,
context.ActionArguments,
"");
//Act
await filter.OnActionExecutionAsync(contextWithoutController, nextMethod.Object);
//Assert
Assert.DoesNotThrowAsync(() => filter.OnActionExecutionAsync(contextWithoutController, nextMethod.Object));
}
}
}
|
using Azure.Storage.Blobs;
using AzureAI.CallCenterTalksAnalysis.Infrastructure.Configuration.Interfaces;
using AzureAI.CallCenterTalksAnalysis.Infrastructure.Services.Storage;
using AzureAI.CallCenterTalksAnalysis.Infrastructure.Services.Storage.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace AzureAI.CallCenterTalksAnalysis.FunctionApps.Core.DependencyInjection
{
public static class StorageServiceCollectionExtensions
{
public static IServiceCollection AddStorageServices(this IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var storageConfiguration = serviceProvider.GetRequiredService<IStorageServiceConfiguration>();
services.TryAddSingleton(implementationFactory =>
{
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConfiguration.ConnectionString);
return blobServiceClient;
});
services.AddSingleton<IStorageService, StorageService>();
return services;
}
}
}
|
using MassTransit;
using SampleDistributedSystem.Contracts.Messages.Core;
using System;
namespace SampleDistributedSystem.Contracts.Messages.Events {
public class CustomerContactDetailsRetrieved:Event {
public CustomerContactDetailsRetrieved(Guid originatingCommandId,Guid referenceTransactionId, string emailAddress, string mobileNumber, MessageHeader header)
: base(originatingCommandId, NewId.NextGuid(), header) {
this.EmailAddress = emailAddress;
this.MobileNumber = mobileNumber;
this.ReferenceTransactionId = referenceTransactionId;
}
public Guid ReferenceTransactionId { get; private set; }
public string EmailAddress { get; private set; }
public string MobileNumber { get; private set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Control : MonoBehaviour {
public float speed = 1f;
private Vector2 axis;
[SerializeField]
private Debug debug = new Debug();
void Start () {
}
void Update () {
axis.y = 0 + (Input.GetKey (InputManager.up) ? 1 : 0) + (Input.GetKey (InputManager.down) ? -1 : 0);
axis.x = 0 + (Input.GetKey (InputManager.right) ? 1 : 0) + (Input.GetKey (InputManager.left) ? -1 : 0);
if (axis != Vector2.zero) {
GetComponent<Rigidbody2D> ().velocity = axis.normalized * speed;
}
debug.axis = axis;
}
[Serializable]
private class Debug {
public Vector2 axis;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gMediaTools.Services.AviSynth.VideoSource
{
public class AviSynthDirectShowVideoSourceService : IAviSynthVideoSourceService
{
public string GetAviSynthVideoSource(string filename, bool overWriteScriptFile)
{
return $"DirectShowSource(\"{filename}\", seek = true, video = true, audio = false, convertfps = false)";
}
}
}
|
using DobleHelix.Feature.Article.Models;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.Linq.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace DobleHelix.Feature.Article.Controllers
{
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
return View();
}
public ActionResult DobleComponent()
{
var item = Sitecore.Context.Database.GetItem("{167070A3-81D5-4289-9709-A430D7E32CDC}");
string str = item.Fields["Copyright"].Value;
string mytags = "";
Sitecore.Data.Fields.MultilistField multilistField = item.Fields["tags"];
if (multilistField != null)
{
foreach (Sitecore.Data.Items.Item city in multilistField.GetItems())
{
mytags += city.Name + "|";
}
}
List<GetItemsss> tag = new List<GetItemsss>() { new GetItemsss() { name = mytags } };
return View("~/Views/Article/DobleComponent.cshtml", tag);
}
public ActionResult DoSearch(string searchText)
{
var myResults = new SearchResults
{
Results = new List<SearchResult>()
};
var searchIndex = ContentSearchManager.GetIndex("sitecore_web_index"); // Get the search index
var searchPredicate = GetSearchPredicate(searchText); // Build the search predicate
using (var searchContext = searchIndex.CreateSearchContext()) // Get a context of the search index
{
//Select * from Sitecore_web_index Where Author="searchText" OR Description="searchText" OR Title="searchText"
//var searchResults = searchContext.GetQueryable<SearchModel>().Where(searchPredicate); // Search the index for items which match the predicate
var searchResults = searchContext.GetQueryable<SearchModel>()
.Where(x => x.Author.Contains(searchText) || x.Title.Contains(searchText) || x.Description.Contains(searchText)); //LINQ query
var fullResults = searchResults.GetResults();
// This is better and will get paged results - page 1 with 10 results per page
//var pagedResults = searchResults.Page(1, 10).GetResults();
foreach (var hit in fullResults.Hits)
{
myResults.Results.Add(new SearchResult
{
Description = hit.Document.Description,
Title = hit.Document.Title,
ItemName = hit.Document.ItemName,
Author = hit.Document.Author
});
}
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = myResults };
}
}
/// <summary>
/// Search logic
/// </summary>
/// <param name="searchText">Search term</param>
/// <returns>Search predicate object</returns>
public static Expression<Func<SearchModel, bool>> GetSearchPredicate(string searchText)
{
var predicate = PredicateBuilder.True<SearchModel>(); // Items which meet the predicate
// Search the whole phrase - LIKE
// predicate = predicate.Or(x => x.DispalyName.Like(searchText)).Boost(1.2f);
// predicate = predicate.Or(x => x.Description.Like(searchText)).Boost(1.2f);
// predicate = predicate.Or(x => x.Title.Like(searchText)).Boost(1.2f);
// Search the whole phrase - CONTAINS
predicate = predicate.Or(x => x.Author.Contains(searchText)); // .Boost(2.0f);
predicate = predicate.Or(x => x.Description.Contains(searchText)); // .Boost(2.0f);
predicate = predicate.Or(x => x.Title.Contains(searchText)); // .Boost(2.0f);
//Where Author="searchText" OR Description="searchText" OR Title="searchText"
return predicate;
}
}
} |
using System;
using System.IO;
using System.Xml;
namespace _4._2_XmlWriter
{
class Program
{
static void Main(string[] args)
{
/*
* StringWriter permite que você gravar em uma cadeia de caracteres, de forma síncrona ou assíncrona. Você pode escrever um caractere por vez com o Write(Char) ou o WriteAsync(Char) método, uma cadeia de caracteres em uma hora usando o Write(String) ou o WriteAsync(String) método.
*/
StringWriter stream = new StringWriter();
using(XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings(){Indent = true}))
{
writer.WriteStartDocument();
writer.WriteStartElement("people");
writer.WriteStartElement("person");
writer.WriteAttributeString("firstname", "john");
writer.WriteAttributeString("lastname", "silva");
writer.WriteStartElement("contactdetails");
writer.WriteElementString("emailaddress", "john@john.com");
//writer.WriteEndElement();
//writer.WriteEndElement();
//writer.WriteEndElement();
writer.Flush();
}
Console.WriteLine(stream.ToString());
Console.ReadLine();
}
}
}
|
using System;
using System.Data;
namespace Kaax
{
public static class DbConnectionProviderExtensions
{
public static IDbConnection OpenConnection(this IDbConnectionProvider dbConnectionProvider)
{
if (dbConnectionProvider is null)
{
throw new ArgumentNullException(nameof(dbConnectionProvider));
}
var connection = dbConnectionProvider.GetConnection();
connection.Open();
return connection;
}
}
}
|
using Alabo.Domains.Entities;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Cloud.Wikis.Settings.Domain.Entities
{
/// <summary>
/// 项目
/// </summary>
[BsonIgnoreExtraElements]
[Table("Wikis_WikiProject")]
[ClassProperty(Name = "Wiki", Description = "Wiki")]
public class WikiProject : AggregateMongodbUserRoot<WikiProject>
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 简介
/// </summary>
public string Intro { get; set; }
/// <summary>
/// 图标
/// </summary>
public string Icon { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using ReportService.Attributes;
using ReportService.Helpers;
namespace ReportService.Controllers
{
[AuthTokenFilter]
public class HonorsController : ApiController
{
// POST api/Honors/
public HttpResponseMessage Post([FromBody]Honors honors)
{
var parameters = new Dictionary<string, string>();
var reportName = "/Commencement/Honors";
// set the shared parameters
parameters.Add("term", honors.TermCode);
parameters.Add("honors_4590", honors.Honors4590.ToString(CultureInfo.InvariantCulture));
parameters.Add("honors_90135", honors.Honors90135.ToString(CultureInfo.InvariantCulture));
parameters.Add("honors_135", honors.Honors135.ToString(CultureInfo.InvariantCulture));
if (string.Equals(honors.CollegeId, "LS", StringComparison.OrdinalIgnoreCase))
{
reportName = "/Commencement/HonorsLS";
}
else
{
parameters.Add("coll", honors.CollegeId);
parameters.Add("highhonors_4590", honors.HighHonors4590.ToString());
parameters.Add("highhonors_90135", honors.HighHonors90135.ToString());
parameters.Add("highhonors_135", honors.HighHonors135.ToString());
parameters.Add("highesthonors_4590", honors.HighestHonors4590.ToString());
parameters.Add("highesthonors_90135", honors.HighestHonors90135.ToString());
parameters.Add("highesthonors_135", honors.HighestHonors135.ToString());
}
return ReturnBytes(ReportHelper.Get(reportName, parameters));
}
private HttpResponseMessage ReturnBytes(byte[] bytes)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
public class Honors
{
public string CollegeId { get; set; }
public string TermCode { get; set; }
public decimal Honors4590 { get; set; }
public decimal? HighHonors4590 { get; set; }
public decimal? HighestHonors4590 { get; set; }
public decimal Honors90135 { get; set; }
public decimal? HighHonors90135 { get; set; }
public decimal? HighestHonors90135 { get; set; }
public decimal Honors135 { get; set; }
public decimal? HighHonors135 { get; set; }
public decimal? HighestHonors135 { get; set; }
}
} |
using ApplicationServices.Command;
using ApplicationServices.Services.Interfaces;
using Infrostructure;
using Repository.Repository.Read.Interfaces;
namespace ApplicationServices.Services.Implementations
{
public class AccountService : IAccountServices
{
#region Constructor
readonly IUserRepositoryRead _userRepositoryRead;
public AccountService(IUserRepositoryRead userRepositoryRead)
{
_userRepositoryRead = userRepositoryRead;
}
#endregion
#region Login
public bool LoginUser(LoginCammand loginCammand)
{
var user = _userRepositoryRead.GetUserByUserNameAndPassword(loginCammand.UserName, loginCammand.Password);
if (user != null)
{
AuthenticationInformation.SetLoginInformation(user.Id, user.UserName);
return true;
}
return false;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
namespace CoreUI.Mvc.Models
{
public class SensorModel
{
private SensoresContext context;
public int M { get; set; }
public float T { get; set; }
public float H { get; set; }
public float I { get; set; }
public float O { get; set; }
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace FlippoIO
{
public class ExePlayer : Player
{
public readonly String path;
public readonly String name;
public ExePlayer(String path)
{
if(!File.Exists(path)) throw new Exception("The specified player file doesn't exist.");
this.path = path;
name = path;
}
public ExePlayer(String path, String name)
{
if(!File.Exists(path)) throw new Exception("The specified player file doesn't exist.");
this.path = path;
this.name = name;
}
public override string GetName() => name;
public override PlayerInstance GetInstance(Match match) => new ExePlayerInstance(this, match);
}
public class ExePlayerInstance : PlayerInstance
{
private ExePlayer player;
private Match match;
private bool white;
private String cmd;
private String args;
private Process program;
private Stopwatch timer;
private AsyncThread errorThread;
private EventWaitHandle outputDone = new EventWaitHandle(false, EventResetMode.ManualReset);
private String stdError;
public String PlayerLog => stdError;
public double Time => timer.Elapsed.TotalMilliseconds;
public ExePlayerInstance(ExePlayer player, Match match)
{
this.player = player;
this.match = match;
if(player.path.EndsWith(".jar"))
{
cmd = Settings.JavaCmd;
args = "-jar " + player.path;
}
else if(player.path.EndsWith(".py"))
{
cmd = Settings.PythonCmd;
args = player.path;
}
else if(player.path.EndsWith(".js"))
{
cmd = Settings.JavaScriptCmd;
args = "-nologo " + player.path;
}
else
{
cmd = player.path;
args = null;
}
}
private void WakeUp()
{
if(!Settings.SuspendPlayers) return;
foreach(ProcessThread pT in program.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if(pOpenThread == IntPtr.Zero)
continue;
int suspendCount = 0;
do
suspendCount = ResumeThread(pOpenThread);
while(suspendCount > 0);
CloseHandle(pOpenThread);
if(suspendCount < 0)
throw new Exception("Failed to resume a thread in program " + player.name);
}
}
private void Sleep()
{
if(!Settings.SuspendPlayers) return;
foreach(ProcessThread pT in program.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if(pOpenThread == IntPtr.Zero)
continue;
SuspendThread(pOpenThread);
CloseHandle(pOpenThread);
}
}
public void Start()
{
Stopwatch startTime = Stopwatch.StartNew();
ProcessStartInfo startInfo = new ProcessStartInfo(cmd)
{
Arguments = args,
UseShellExecute = false, // needs to be false to enable stream redirecting
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
program = Process.Start(startInfo);
timer = new Stopwatch();
Sleep();
program.Exited += new EventHandler((object src, EventArgs args) => { outputDone.Set(); }); // ensure the main match thread will wake up if the program crashes.
errorThread = AsyncThread.Borrow(ReadError);
startTime.Stop();
Debug.WriteLine(match.Prefix + "Started player " + player.name + " in " + startTime.ElapsedMilliseconds + " ms. Used command: " + cmd + " " + args);
}
private void Terminate() // TODO: access is denied sometimes...
{
bool success = false;
try
{
program.Kill();
success = true;
}
catch(InvalidOperationException e) // this could mean the program has already exited
{
if(!program.HasExited) throw e;
}
catch(Exception e)
{
Debug.WriteLine(match.Prefix + "Exception occured while trying to kill " + player.name);
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
if(success) Debug.WriteLine(match.Prefix + "Terminated player " + player.name + ".");
}
private void SendLine(String line)
{
program.StandardInput.WriteLine(line);
program.StandardInput.Flush();
}
private String ReadLine()
{
WakeUp();
timer.Start();
String line = program.StandardOutput.ReadLine();
timer.Stop();
Sleep();
bool potentialCrash = line == null ? true : line.Length == 0;
if(potentialCrash && program.HasExited) throw new Crash();
if(timer.ElapsedMilliseconds > Settings.TimeLimit) throw new Timeout();
return line;
}
private String ReadLineAsync()
{
String line = null;
AsyncThread thread = AsyncThread.Borrow(() =>
{
line = program.StandardOutput.ReadLine();
outputDone.Set();
});
WakeUp();
timer.Start();
while(timer.ElapsedMilliseconds <= Settings.TimeLimit)
{
bool success = outputDone.WaitOne((int)(Settings.TimeLimit + Settings.ReadTimeMargin - timer.ElapsedMilliseconds));
if(success) break; // success may also be true when the program crashes, see Start()
}
timer.Stop();
Sleep();
outputDone.Reset();
AsyncThread.Return(thread, line != null);
bool potentialCrash = line == null ? true : line.Length == 0;
if(potentialCrash && program.HasExited) throw new Crash();
if(timer.ElapsedMilliseconds > Settings.TimeLimit) throw new Timeout();
return line;
}
private void ReadError() // TODO: using ReadToEnd() causes logs to be lost...
{
//stdError = program.StandardError.ReadToEnd();
while(!program.StandardError.EndOfStream)
stdError += program.StandardError.ReadLine() + Environment.NewLine;
}
public void Designate(bool white)
{
this.white = white;
if(white)
SendLine("Start");
}
public Move GetMove()
{
String line = Settings.AsyncRead ? ReadLineAsync() : ReadLine();
int[] xy = Misc.ExtractCaiaString(line); // will throw the appropriate exception if the line sent wasn't a valid move
return new Move(xy[0], xy[1], white);
}
public void SendMove(Move move)
{
SendLine(Misc.GetCaiaString(move.x, move.y));
}
public void Quit()
{
try
{
Debug.WriteLine(match.Prefix + "Player " + player.name + " used " + timer.ElapsedMilliseconds + " ms.");
if(!program.HasExited)
{
SendLine("Quit");
WakeUp();
if(Settings.KillPrograms)
{
Thread.Sleep(Settings.MillisecondsBeforeKill);
Terminate();
}
program.WaitForExit();
}
}
finally
{
AsyncThread.Return(errorThread, program.HasExited);
}
}
// Win32 stuff
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200)
}
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ZY.OA.IDAL;
namespace ZY.OA.DALFactory
{
public partial class AbstractDALFactory
{
public static IActionInfoDal GetActionInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".ActionInfoDal") as IActionInfoDal;
}
public static IMenuInfoDal GetMenuInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".MenuInfoDal") as IMenuInfoDal;
}
public static IOrderInfoDal GetOrderInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".OrderInfoDal") as IOrderInfoDal;
}
public static IR_UserInfo_ActionInfoDal GetR_UserInfo_ActionInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".R_UserInfo_ActionInfoDal") as IR_UserInfo_ActionInfoDal;
}
public static IRoleInfoDal GetRoleInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".RoleInfoDal") as IRoleInfoDal;
}
public static IUserInfoDal GetUserInfoDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".UserInfoDal") as IUserInfoDal;
}
public static IUserInfoExtDal GetUserInfoExtDal()
{
return Assembly.Load(AssemblyName).CreateInstance(AssemblyName + ".UserInfoExtDal") as IUserInfoExtDal;
}
}
} |
using Citycykler.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CityCykler
{
public partial class vare : System.Web.UI.Page
{
DataLinqDB db = new DataLinqDB();
protected void Page_Load(object sender, EventArgs e)
{
int id = HelperClassAll.HelperClass.ReturnGetId();
RepeaterList.DataSource = db.Noticeables.Where(i => i.fk_kategori == id).OrderByDescending(i => i.id).ToList();
RepeaterList.DataBind();
var kategori = db.kategoris.FirstOrDefault(i => i.id == id);
if (kategori != null)
{
overskift.InnerText = kategori.text;
}
else
{
Response.Redirect("~/error.aspx?fejl404=true");
}
}
}
} |
using Com.Colin.Forms.Properties;
using System.Drawing;
using System.Windows.Forms;
namespace Com.Colin.Forms.Template
{
public partial class TableTemplate : UserControl
{
public TableTemplate()
{
InitializeComponent();
//tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
tabControl1.ItemSize = new Size((int)(tabControl1.Size.Width * 0.45), 24);
}
private void button1_Click(object sender, System.EventArgs e)
{
Button button = (Button)sender;
string value = button.Text;
if (value.Equals("查看记录"))
{
button.Text = "停止检测";
}
else
{
button.Text = "查看记录";
}
}
}
}
|
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 Hospital_Management_System
{
public partial class Dash_Board : Form
{
public Dash_Board()
{
InitializeComponent();
}
private void Doctor(object sender, EventArgs e)
{
this.Hide();
Doctor ss = new Doctor();
ss.Show();
}
private void Billing(object sender, EventArgs e)
{
this.Hide();
Patient aa = new Patient();
aa.Show();
}
private void Wardboy(object sender, EventArgs e)
{
this.Hide();
Wardboy dd = new Wardboy();
dd.Show();
}
private void Doctor_click(object sender, EventArgs e)
{
this.Hide();
Doctor qq = new Doctor();
qq.Show();
}
private void Billing_click(object sender, EventArgs e)
{
this.Hide();
Patient ww = new Patient();
ww.Show();
}
private void Wardboy_click(object sender, EventArgs e)
{
this.Hide();
Wardboy ee = new Wardboy();
ee.Show();
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form1 rr = new Form1();
rr.Show();
}
private void label10_Click(object sender, EventArgs e)
{
this.Hide();
Doctor ss = new Doctor();
ss.Show();
}
private void Patient_Click(object sender, EventArgs e)
{
this.Hide();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using LoLInfo.Models;
using LoLInfo.Services.Extensions;
using LoLInfo.Services.ServiceModels;
using LoLInfo.Services.WebServices;
using Newtonsoft.Json;
namespace LoLInfo.Services.WebServices
{
public class ChampionService : BaseService
{
//dictionary to get champion image in match history
public static Dictionary<int, string> ChampionImageDictionary = new Dictionary<int, string>();
public async Task<List<Champion>> GetChampions()
{
using (var client = new HttpClient())
{
var coreUrl = string.Format(ServiceConstants.GetChampionsUrl, ServiceConstants.CurrentRegionCode);
var queries = new List<string>() { "champData=all" };
var url = GetRequestUrl(coreUrl, queries);
var json = await client.GetStringAsync(url);
if (string.IsNullOrWhiteSpace(json))
return null;
var champsDto = JsonConvert.DeserializeObject<ChampionListDto>(json);
var champs = champsDto.ToChampions();
foreach (var champ in champs)
{
if (!ChampionImageDictionary.ContainsKey(champ.Id))
{
ChampionImageDictionary.Add(champ.Id, champ.SquareImageUrl);
}
}
return champs;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryDesignPattern
{
public class MsAccessDatabase : IDatabase
{
public DbCommand GetDatabaseCmd()
{
throw new NotImplementedException();
}
public DbDataReader GetDatabaseReader()
{
throw new NotImplementedException();
}
public DataSet GetDataset()
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Globalization;
namespace Vanhackaton
{
class DigitalWalletTransaction
{
private bool commonValidation(DigitalWallet digitalWallet, int amount) {
if (amount <= 0) {
return false;
}
if (digitalWallet.getUserAccessToken() == null) {
return false;
}
return true;
}
public string addMoney(DigitalWallet digitalWallet, int amount) {
if (!this.commonValidation(digitalWallet, amount)) {
return "We can not do this transaction";
}
digitalWallet.setBalance(digitalWallet.getWalletBalance() + amount);
return returnBalance(digitalWallet);
}
public string payMoney(DigitalWallet digitalWallet, int amount) {
if (!this.commonValidation(digitalWallet, amount)) {
return "We can not do this transaction";
}
// Final balance after possible transaction
int finalBalance = 0;
finalBalance = digitalWallet.getWalletBalance() - amount;
if (finalBalance < 0) {
return "Insufficient balance";
}
else {
digitalWallet.setBalance(finalBalance);
}
return returnBalance(digitalWallet);
}
public string transferMoney(DigitalWallet digitalWalletSend, int amount, DigitalWallet digitalWalletReceive) {
if (!this.commonValidation(digitalWalletSend, amount)) {
return "We can not do this transaction";
}
payMoney(digitalWalletSend, amount);
addMoney(digitalWalletReceive, amount);
return returnBalance(digitalWalletSend);
}
private string returnBalance(DigitalWallet digitalWallet) {
return "Your balance is: " + digitalWallet.getWalletBalance().ToString("C2", CultureInfo.CurrentCulture);
}
}
} |
using System;
using System.Threading.Tasks;
using FakeItEasy;
using NUnit.Framework;
using RestLogger.Domain;
using RestLogger.Infrastructure;
using RestLogger.Infrastructure.Helpers.PasswordHasher;
using RestLogger.Infrastructure.Helpers.PasswordHasher.Model;
using RestLogger.Infrastructure.Repository;
using RestLogger.Infrastructure.Service;
using RestLogger.Infrastructure.Service.Model.ApplicationDtos;
using RestLogger.Service;
namespace RestLogger.Tests.UnitTests
{
[TestFixture]
public class ApplicationServiceTests
{
[Test]
public async Task WhenAddingApplicationThenApplicationIsAddedToRepository()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync(A<string>.Ignored)).Returns(Task.FromResult<ApplicationEntity>(null));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
A.CallTo(() => fakePasswordHasher.HashPassword(A<string>.Ignored)).Returns(new HashWithSaltResult()
{
Hash = "TestHash",
Salt = "TestSalt"
});
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
ApplicationCreateDto applicationCreateDto = new ApplicationCreateDto()
{
DisplayName = "TestApplicationDisplayName",
Password = "TestPassword"
};
// Act
await applicationService.AddApplicationAsync(applicationCreateDto);
// Assert
A.CallTo(() => fakeApplicationRepository.Add(A<ApplicationEntity>.That.Matches(a => a.DisplayName == "TestApplicationDisplayName"
&& a.PasswordHash == "TestHash"
&& a.PasswordSalt == "TestSalt"
))).MustHaveHappened();
}
[Test]
public async Task WhenAddingApplicationThenUnitOfWorkIsCommitted()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync(A<string>.Ignored)).Returns(Task.FromResult<ApplicationEntity>(null));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
A.CallTo(() => fakePasswordHasher.HashPassword(A<string>.Ignored)).Returns(new HashWithSaltResult());
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
ApplicationCreateDto applicationCreateDto = new ApplicationCreateDto()
{
DisplayName = "TestApplicationDisplayName",
Password = "TestPassword"
};
// Act
await applicationService.AddApplicationAsync(applicationCreateDto);
// Assert
A.CallTo(() => fakeUnitOfWork.CommitAsync()).MustHaveHappened();
}
[Test]
public void WhenAddingExistingApplicationThenExceptionIsThrown()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync(A<string>.Ignored)).Returns(Task.FromResult(new ApplicationEntity()));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
ApplicationCreateDto applicationCreateDto = new ApplicationCreateDto()
{
DisplayName = "TestApplicationDisplayName",
Password = "TestPassword"
};
// Act
ArgumentException ex = Assert.CatchAsync<ArgumentException>(async () => await applicationService.AddApplicationAsync(applicationCreateDto));
// Assert
StringAssert.Contains("Application with DisplayName TestApplicationDisplayName already exists.", ex.Message);
}
[Test]
public async Task WhenFindingExistingApplicationWithValidPasswordThenValidApplicationIsReturned()
{
// Arrange
ApplicationEntity application = new ApplicationEntity()
{
Id = 0,
DisplayName = "TestApplicationDisplayName",
PasswordHash = "TestPasswordHash",
PasswordSalt = "TestPasswordSalt"
};
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync(A<string>.Ignored)).Returns(Task.FromResult(application));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
A.CallTo(() => fakePasswordHasher.CheckPassword("TestPassword", "TestPasswordHash", "TestPasswordSalt")).Returns(true);
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
// Act
ApplicationDto applicationDto = await applicationService.FindApplicationAsync("TestApplicationDisplayName", "TestPassword");
// Assert
Assert.IsNotNull(applicationDto);
Assert.AreEqual(0, applicationDto.Id);
Assert.AreEqual("TestApplicationDisplayName", applicationDto.DisplayName);
}
[Test]
public async Task WhenFindingExistingApplicationWithWrongPasswordThenNullIsReturned()
{
// Arrange
ApplicationEntity application = new ApplicationEntity()
{
Id = 0,
DisplayName = "TestApplicationDisplayName",
PasswordHash = "TestPasswordHash",
PasswordSalt = "TestPasswordSalt"
};
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync("TestApplicationDisplayName")).Returns(Task.FromResult(application));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
A.CallTo(() => fakePasswordHasher.CheckPassword(A<string>.Ignored, A<string>.Ignored, A<string>.Ignored)).Returns(false);
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
// Act
ApplicationDto applicationDto = await applicationService.FindApplicationAsync("TestApplicationDisplayName", "TestPassword");
// Assert
Assert.IsNull(applicationDto);
}
[Test]
public async Task WhenFindingAbsentApplicationThenNullIsReturned()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync("TestApplicationDisplayName")).Returns(Task.FromResult<ApplicationEntity>(null));
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
// Act
ApplicationDto applicationDto = await applicationService.FindApplicationAsync("TestApplicationId", "TestApplicationSecret");
// Assert
Assert.IsNull(applicationDto);
}
[Test]
public void WhenAddingNullApplicationThenExceptionIsThrown()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
// Act
ArgumentException ex = Assert.CatchAsync<ArgumentException>(async () => await applicationService.AddApplicationAsync(null));
// Assert
StringAssert.Contains("Application name and password must be provided.", ex.Message);
}
[Test]
public void WhenAddingApplicationWithEmptyDisplayNameThenExceptionIsThrown()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
ApplicationCreateDto applicationCreateDto = new ApplicationCreateDto()
{
DisplayName = "",
Password = "TestPassword"
};
// Act
ArgumentException ex = Assert.CatchAsync<ArgumentException>(async () => await applicationService.AddApplicationAsync(applicationCreateDto));
// Assert
StringAssert.Contains("Application name and password must be provided.", ex.Message);
}
[Test]
public void WhenAddingApplicationWithEmptyPasswordThenExceptionIsThrown()
{
// Arrange
IApplicationRepository fakeApplicationRepository = A.Fake<IApplicationRepository>();
IUnitOfWork fakeUnitOfWork = A.Fake<IUnitOfWork>();
IPasswordWithSaltHasher fakePasswordHasher = A.Fake<IPasswordWithSaltHasher>();
IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);
ApplicationCreateDto applicationCreateDto = new ApplicationCreateDto()
{
DisplayName = "TestApplicationDisplayName",
Password = ""
};
// Act
ArgumentException ex = Assert.CatchAsync<ArgumentException>(async () => await applicationService.AddApplicationAsync(applicationCreateDto));
// Assert
StringAssert.Contains("Application name and password must be provided.", ex.Message);
}
}
}
|
using System;
namespace LoLInfo.Models
{
public class Skin
{
public string Name { get; set; }
public string LoadingImageUrl { get; set; }
public string SplashImageUrl { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace DataLightning.Core;
public sealed class InputManager : IDisposable
{
private readonly List<ISubscription> _subscriptions = new();
public void Add<T>(string inputName, ISubscribable<T> subscribable, Action<string, T> callback)
{
var input = new InputBridge<T>
{
Name = inputName,
Callback = callback
};
_subscriptions.Add(subscribable.Subscribe(input));
}
public void Dispose()
{
_subscriptions.ForEach(s => s.Dispose());
_subscriptions.Clear();
}
} |
/*
* 2020 Microsoft Corp
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json.Linq;
namespace FHIRProxy
{
class FHIRProxyAuthorization : FunctionInvocationFilterAttribute
{
public override Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken)
{
var req = executingContext.Arguments.First().Value as HttpRequest;
ClaimsPrincipal principal = executingContext.Arguments["principal"] as ClaimsPrincipal;
ClaimsIdentity ci = (ClaimsIdentity)principal.Identity;
bool admin = ci.IsInFHIRRole(Environment.GetEnvironmentVariable("ADMIN_ROLE"));
bool reader = ci.IsInFHIRRole(Environment.GetEnvironmentVariable("READER_ROLE"));
bool writer = ci.IsInFHIRRole(Environment.GetEnvironmentVariable("WRITER_ROLE"));
string inroles = "";
if (admin) inroles += "A";
if (reader) inroles += "R";
if (writer) inroles += "W";
req.Headers.Remove(Utils.AUTH_STATUS_HEADER);
req.Headers.Remove(Utils.AUTH_STATUS_MSG_HEADER);
if (!principal.Identity.IsAuthenticated)
{
req.Headers.Add(Utils.AUTH_STATUS_HEADER, ((int)System.Net.HttpStatusCode.Unauthorized).ToString());
req.Headers.Add(Utils.AUTH_STATUS_MSG_HEADER, "User is not Authenticated");
}
else if (req.Method.Equals("GET") && !admin && !reader)
{
req.Headers.Add(Utils.AUTH_STATUS_HEADER, ((int)System.Net.HttpStatusCode.Unauthorized).ToString());
req.Headers.Add(Utils.AUTH_STATUS_MSG_HEADER, "User/Application must be in a reader role to access");
}
else if (!req.Method.Equals("GET") && !admin && !writer)
{
req.Headers.Add(Utils.AUTH_STATUS_HEADER, ((int)System.Net.HttpStatusCode.Unauthorized).ToString());
req.Headers.Add(Utils.AUTH_STATUS_MSG_HEADER, "User/Application must be in a writer role to update");
}
else
{
//Since we are proxying with service client need to ensure authenticated proxy principal is audited
req.Headers.Add(Utils.AUTH_STATUS_HEADER, ((int)System.Net.HttpStatusCode.OK).ToString());
req.Headers.Add(Utils.FHIR_PROXY_ROLES, inroles);
req.Headers.Add("X-MS-AZUREFHIR-AUDIT-USERID", principal.Identity.Name);
req.Headers.Add("X-MS-AZUREFHIR-AUDIT-TENANT", ci.Tenant());
req.Headers.Add("X-MS-AZUREFHIR-AUDIT-SOURCE", req.HttpContext.Connection.RemoteIpAddress.ToString());
req.Headers.Add("X-MS-AZUREFHIR-AUDIT-PROXY", $"{executingContext.FunctionName}");
}
return base.OnExecutingAsync(executingContext, cancellationToken);
}
}
}
|
using System;
namespace Facade.Classes.Tech
{
public class Sound
{
public void Enable()
{
Console.WriteLine("Sound enabled");
}
public void Disable()
{
Console.WriteLine("Sound disabled");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Wpf.Model;
using Wpf.ViewModel;
namespace Wpf
{
/// <summary>
/// CarInfoPage.xaml 的交互逻辑
/// 车辆信息操作窗口
/// </summary>
public partial class CarInfoPage : Page
{
CarViewModel carViewModel = new CarViewModel();
/// <summary>
/// 构造函数
/// </summary>
public CarInfoPage()
{
InitializeComponent();
this.DataContext = carViewModel;
}
/// <summary>
/// 筛选通用方法
/// </summary>
/// <param name="itemCombobox"></param>
/// <param name="itemList"></param>
private void filterKeyUp(ComboBox itemCombobox, List<string> itemList)
{
List<string> sourcesList = new List<string>();
foreach (var item in itemList)
{
if (item.Contains(itemCombobox.Text.Trim()) ||
item.Contains(itemCombobox.Text.ToLower()) ||
item.Contains(itemCombobox.Text.ToUpper()))
{
sourcesList.Add(item);
}
}
itemCombobox.ItemsSource = sourcesList;
itemCombobox.IsDropDownOpen = true;
}
/// <summary>
/// 编辑车辆信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EditClick(object sender, RoutedEventArgs e)
{
//获取当前数据传给修改窗口
Car car = this.carDataGrid.SelectedItem as Car;
CarWindow carWindow = new CarWindow(carViewModel, "Update", car);
carWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
carWindow.Show();
}
/// <summary>
/// 根据筛选条件筛选车辆信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SelectCarInfo(object sender, RoutedEventArgs e)
{
//触发Command更新数据,必须使用同一个视图数据模型
List<string> filterList = new List<string>();
filterList.Add(this.carType.Text);
filterList.Add(this.carNumber.Text);
var MyVM = carViewModel;
if (MyVM != null && MyVM.SelectCommand.CanExecute(filterList))
MyVM.SelectCommand.Execute(filterList);
}
/// <summary>
/// 增加车辆信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddCarInfo(object sender, RoutedEventArgs e)
{
CarWindow carWindow = new CarWindow(carViewModel, "Insert",null);
carWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
carWindow.Show();
}
/// <summary>
/// 当键盘抬起时触发车辆类型输入框的内容刷新
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void carTypeKeyUp(object sender, KeyEventArgs e)
{
var typeList = carViewModel.CarView.Select(t => t.Type).ToList();
filterKeyUp(this.carType, typeList);
}
/// <summary>
/// 当键盘抬起时触发车辆牌号输入框的内容刷新
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void carNumberKeyUp(object sender, KeyEventArgs e)
{
var numberList = carViewModel.CarView.Select(t => t.CarNumber).ToList();
filterKeyUp(this.carNumber, numberList);
}
}
}
|
using System;
namespace DtCms.Model
{
/// <summary>
/// 实体类Admin 。(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public class Admin
{
public Admin()
{}
#region Model
private int _id;
private string _username;
private string _userpwd;
private string _readname;
private string _useremail;
private int _usertype;
private string _userlevel;
private int _islock;
/// <summary>
/// 自增编号
/// </summary>
public int Id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
/// 登录帐号
/// </summary>
public string UserName
{
set{ _username=value;}
get{return _username;}
}
/// <summary>
/// 登录密码
/// </summary>
public string UserPwd
{
set{ _userpwd=value;}
get{return _userpwd;}
}
/// <summary>
/// 真实名称
/// </summary>
public string ReadName
{
set{ _readname=value;}
get{return _readname;}
}
/// <summary>
/// 电子邮件
/// </summary>
public string UserEmail
{
set{ _useremail=value;}
get{return _useremail;}
}
/// <summary>
/// 用户级别
/// </summary>
public int UserType
{
set{ _usertype=value;}
get{return _usertype;}
}
/// <summary>
/// 用户权限
/// </summary>
public string UserLevel
{
set{ _userlevel=value;}
get{return _userlevel;}
}
/// <summary>
/// 是否锁定
/// </summary>
public int IsLock
{
set{ _islock=value;}
get{return _islock;}
}
#endregion Model
}
}
|
using System;
using System.Buffers;
using System.Globalization;
using System.Text;
using MySql.Data.Serialization;
namespace MySql.Data.MySqlClient.Results
{
internal class Row : IDisposable
{
public Row(ResultSet resultSet) => ResultSet = resultSet;
public void SetData(int[] dataLengths, int[] dataOffsets, ArraySegment<byte> payload)
{
m_dataLengths = dataLengths;
m_dataOffsets = dataOffsets;
m_payload = payload;
}
public void BufferData()
{
// by default, m_payload, m_dataLengths, and m_dataOffsets are re-used to save allocations
// if the row is going to be buffered, we need to copy them
// since m_payload can span multiple rows, offests must recalculated to include only this row
var bufferDataLengths = new int[m_dataLengths.Length];
Buffer.BlockCopy(m_dataLengths, 0, bufferDataLengths, 0, m_dataLengths.Length * sizeof(int));
m_dataLengths = bufferDataLengths;
var bufferDataOffsets = new int[m_dataOffsets.Length];
for (var i = 0; i < m_dataOffsets.Length; i++)
{
// a -1 offset denotes null, only adjust positive offsets
if (m_dataOffsets[i] >= 0)
bufferDataOffsets[i] = m_dataOffsets[i] - m_payload.Offset;
else
bufferDataOffsets[i] = m_dataOffsets[i];
}
m_dataOffsets = bufferDataOffsets;
var bufferedPayload = new byte[m_payload.Count];
Buffer.BlockCopy(m_payload.Array, m_payload.Offset, bufferedPayload, 0, m_payload.Count);
m_payload = new ArraySegment<byte>(bufferedPayload);
}
public void Dispose() => ClearData();
public void ClearData()
{
m_dataLengths = null;
m_dataOffsets = null;
m_payload = default(ArraySegment<byte>);
}
public bool GetBoolean(int ordinal)
{
var value = GetValue(ordinal);
if (value is bool)
return (bool) value;
if (value is sbyte)
return (sbyte) value != 0;
if (value is byte)
return (byte) value != 0;
if (value is short)
return (short) value != 0;
if (value is ushort)
return (ushort) value != 0;
if (value is int)
return (int) value != 0;
if (value is uint)
return (uint) value != 0;
if (value is long)
return (long) value != 0;
if (value is ulong)
return (ulong) value != 0;
return (bool) value;
}
public sbyte GetSByte(int ordinal) => (sbyte) GetValue(ordinal);
public byte GetByte(int ordinal) => (byte) GetValue(ordinal);
public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
if (m_dataOffsets[ordinal] == -1)
throw new InvalidCastException("Column is NULL.");
var column = ResultSet.ColumnDefinitions[ordinal];
var columnType = column.ColumnType;
if ((column.ColumnFlags & ColumnFlags.Binary) == 0 ||
(columnType != ColumnType.String && columnType != ColumnType.VarString && columnType != ColumnType.TinyBlob &&
columnType != ColumnType.Blob && columnType != ColumnType.MediumBlob && columnType != ColumnType.LongBlob))
{
throw new InvalidCastException("Can't convert {0} to bytes.".FormatInvariant(columnType));
}
if (buffer == null)
{
// this isn't required by the DbDataReader.GetBytes API documentation, but is what mysql-connector-net does
// (as does SqlDataReader: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getbytes.aspx)
return m_dataLengths[ordinal];
}
if (bufferOffset + length > buffer.Length)
throw new ArgumentException("bufferOffset + length cannot exceed buffer.Length", nameof(length));
int lengthToCopy = Math.Min(m_dataLengths[ordinal] - (int) dataOffset, length);
Buffer.BlockCopy(m_payload.Array, checked((int) (m_dataOffsets[ordinal] + dataOffset)), buffer, bufferOffset, lengthToCopy);
return lengthToCopy;
}
public char GetChar(int ordinal) => (char) GetValue(ordinal);
public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) => throw new NotImplementedException();
public Guid GetGuid(int ordinal)
{
var value = GetValue(ordinal);
if (value is Guid guid)
return guid;
if (value is string stringValue && Guid.TryParse(stringValue, out guid))
return guid;
if (value is byte[] bytes && bytes.Length == 16)
return new Guid(bytes);
throw new MySqlException("The value could not be converted to a GUID: {0}".FormatInvariant(value));
}
public short GetInt16(int ordinal)
{
object value = GetValue(ordinal);
if (value is short)
return (short) value;
if (value is sbyte)
return (sbyte) value;
if (value is byte)
return (byte) value;
if (value is ushort)
return checked((short) (ushort) value);
if (value is int)
return checked((short) (int) value);
if (value is uint)
return checked((short) (uint) value);
if (value is long)
return checked((short) (long) value);
if (value is ulong)
return checked((short) (ulong) value);
if (value is decimal)
return (short) (decimal) value;
return (short) value;
}
public int GetInt32(int ordinal)
{
object value = GetValue(ordinal);
if (value is int)
return (int) value;
if (value is sbyte)
return (sbyte) value;
if (value is byte)
return (byte) value;
if (value is short)
return (short) value;
if (value is ushort)
return (ushort) value;
if (value is uint)
return checked((int) (uint) value);
if (value is long)
return checked((int) (long) value);
if (value is ulong)
return checked((int) (ulong) value);
if (value is decimal)
return (int) (decimal) value;
return (int) value;
}
public long GetInt64(int ordinal)
{
object value = GetValue(ordinal);
if (value is long)
return (long) value;
if (value is sbyte)
return (sbyte) value;
if (value is byte)
return (byte) value;
if (value is short)
return (short) value;
if (value is ushort)
return (ushort) value;
if (value is int)
return (int) value;
if (value is uint)
return (uint) value;
if (value is ulong)
return checked((long) (ulong) value);
if (value is decimal)
return (long) (decimal) value;
return (long) value;
}
public DateTime GetDateTime(int ordinal) => (DateTime) GetValue(ordinal);
public DateTimeOffset GetDateTimeOffset(int ordinal) => new DateTimeOffset(DateTime.SpecifyKind(GetDateTime(ordinal), DateTimeKind.Utc));
public string GetString(int ordinal) => (string) GetValue(ordinal);
public decimal GetDecimal(int ordinal) => (decimal) GetValue(ordinal);
public double GetDouble(int ordinal)
{
object value = GetValue(ordinal);
return value is float floatValue ? floatValue : (double) value;
}
public float GetFloat(int ordinal) => (float) GetValue(ordinal);
public int GetValues(object[] values)
{
int count = Math.Min(values.Length, ResultSet.ColumnDefinitions.Length);
for (int i = 0; i < count; i++)
values[i] = GetValue(i);
return count;
}
public bool IsDBNull(int ordinal) => m_dataOffsets[ordinal] == -1;
public object this[int ordinal] => GetValue(ordinal);
public object this[string name] => GetValue(GetOrdinal(name));
public int GetOrdinal(string name)
{
for (int column = 0; column < ResultSet.ColumnDefinitions.Length; column++)
{
if (ResultSet.ColumnDefinitions[column].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
return column;
}
// TODO: Correct exception
throw new IndexOutOfRangeException("The column name '{0}' does not exist in the result set.".FormatInvariant(name));
}
public object GetValue(int ordinal)
{
if (ordinal < 0 || ordinal > ResultSet.ColumnDefinitions.Length)
throw new ArgumentOutOfRangeException(nameof(ordinal), "value must be between 0 and {0}.".FormatInvariant(ResultSet.ColumnDefinitions.Length));
if (m_dataOffsets[ordinal] == -1)
return DBNull.Value;
var data = new ArraySegment<byte>(m_payload.Array, m_dataOffsets[ordinal], m_dataLengths[ordinal]);
var columnDefinition = ResultSet.ColumnDefinitions[ordinal];
var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0;
switch (columnDefinition.ColumnType)
{
case ColumnType.Tiny:
var value = int.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
if (Connection.TreatTinyAsBoolean && columnDefinition.ColumnLength == 1)
return value != 0;
return isUnsigned ? (object) (byte) value : (sbyte) value;
case ColumnType.Int24:
case ColumnType.Long:
return isUnsigned ? (object) uint.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture) :
int.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Longlong:
return isUnsigned ? (object) ulong.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture) :
long.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Bit:
// BIT column is transmitted as MSB byte array
ulong bitValue = 0;
for (int i = 0; i < m_dataLengths[ordinal]; i++)
bitValue = bitValue * 256 + m_payload.Array[m_dataOffsets[ordinal] + i];
return bitValue;
case ColumnType.String:
if (!Connection.OldGuids && columnDefinition.ColumnLength / SerializationUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36)
return Guid.Parse(Encoding.UTF8.GetString(data));
goto case ColumnType.VarString;
case ColumnType.VarString:
case ColumnType.VarChar:
case ColumnType.TinyBlob:
case ColumnType.Blob:
case ColumnType.MediumBlob:
case ColumnType.LongBlob:
if (columnDefinition.CharacterSet == CharacterSet.Binary)
{
var result = new byte[m_dataLengths[ordinal]];
Buffer.BlockCopy(m_payload.Array, m_dataOffsets[ordinal], result, 0, result.Length);
return Connection.OldGuids && columnDefinition.ColumnLength == 16 ? (object) new Guid(result) : result;
}
return Encoding.UTF8.GetString(data);
case ColumnType.Json:
return Encoding.UTF8.GetString(data);
case ColumnType.Short:
return isUnsigned ? (object) ushort.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture) :
short.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Date:
case ColumnType.DateTime:
case ColumnType.Timestamp:
return ParseDateTime(data);
case ColumnType.Time:
return ParseTimeSpan(data);
case ColumnType.Year:
return int.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Float:
return float.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Double:
return double.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
case ColumnType.Decimal:
case ColumnType.NewDecimal:
return decimal.Parse(Encoding.UTF8.GetString(data), CultureInfo.InvariantCulture);
default:
throw new NotImplementedException("Reading {0} not implemented".FormatInvariant(columnDefinition.ColumnType));
}
}
private DateTime ParseDateTime(ArraySegment<byte> value)
{
var parts = Encoding.UTF8.GetString(value).Split('-', ' ', ':', '.');
var year = int.Parse(parts[0], CultureInfo.InvariantCulture);
var month = int.Parse(parts[1], CultureInfo.InvariantCulture);
var day = int.Parse(parts[2], CultureInfo.InvariantCulture);
if (year == 0 && month == 0 && day == 0)
{
if (Connection.ConvertZeroDateTime)
return DateTime.MinValue;
throw new InvalidCastException("Unable to convert MySQL date/time to System.DateTime.");
}
if (parts.Length == 3)
return new DateTime(year, month, day);
var hour = int.Parse(parts[3], CultureInfo.InvariantCulture);
var minute = int.Parse(parts[4], CultureInfo.InvariantCulture);
var second = int.Parse(parts[5], CultureInfo.InvariantCulture);
if (parts.Length == 6)
return new DateTime(year, month, day, hour, minute, second);
var microseconds = int.Parse(parts[6] + new string('0', 6 - parts[6].Length), CultureInfo.InvariantCulture);
return new DateTime(year, month, day, hour, minute, second, microseconds / 1000).AddTicks(microseconds % 1000 * 10);
}
private static TimeSpan ParseTimeSpan(ArraySegment<byte> value)
{
var parts = Encoding.UTF8.GetString(value).Split(':', '.');
var hours = int.Parse(parts[0], CultureInfo.InvariantCulture);
var minutes = int.Parse(parts[1], CultureInfo.InvariantCulture);
if (hours < 0)
minutes = -minutes;
var seconds = int.Parse(parts[2], CultureInfo.InvariantCulture);
if (hours < 0)
seconds = -seconds;
if (parts.Length == 3)
return new TimeSpan(hours, minutes, seconds);
var microseconds = int.Parse(parts[3] + new string('0', 6 - parts[3].Length), CultureInfo.InvariantCulture);
if (hours < 0)
microseconds = -microseconds;
return new TimeSpan(0, hours, minutes, seconds, microseconds / 1000) + TimeSpan.FromTicks(microseconds % 1000 * 10);
}
public readonly ResultSet ResultSet;
public MySqlConnection Connection => ResultSet.Connection;
ArraySegment<byte> m_payload;
int[] m_dataLengths;
int[] m_dataOffsets;
}
}
|
namespace InterpreterSample
{
// <command> ::= <repeat command> || <primitive command>
public class CommandNode : Node
{
private Node _node;
public override void Parse(Context context)
{
if (context.CurrentToken().Equals("repeat"))
{
_node = new RepeatCommandNode();
_node.Parse(context);
}
else
{
_node = new PrimitiveCommandNode();
_node.Parse(context);
}
}
public override string ToString()
{
return _node.ToString();
}
}
} |
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;
using InRule.Repository;
using InRule.Repository.Classifications;
using InRule.Repository.Designer;
using InRule.Repository.EndPoints;
using InRule.Repository.RuleElements;
using InRule.Repository.UDFs;
using InRule.Repository.ValueLists;
using InRule.Repository.Vocabulary;
namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering
{
public static partial class SdkCodeRenderingExtensions
{
public static string ToSdkCode(this object testValue)
{
Errors.Clear();
var sb = new StringBuilder();
var writer = new StringWriter(sb);
var ruleAppProvider = CodeDomProvider.CreateProvider("csharp");
var ruleAppUnit = new CodeCompileUnit();
var ruleAppNS = new CodeNamespace("InRuleLabs.SDKCodeGen");
ruleAppNS.Types.Add(testValue.ToCodeClass());
ruleAppUnit.Namespaces.Add(ruleAppNS);
var options = new CodeGeneratorOptions();
try
{
ruleAppProvider.GenerateCodeFromCompileUnit(ruleAppUnit, writer, options);
}
catch (Exception ex)
{
sb.AppendLine(ex.ToString());
}
var value = "//------------------------------------------------------------------------------";
sb.Remove(0, sb.ToString().IndexOf(value, value.Length) + value.Length);
foreach (var err in Errors)
{
sb.AppendLine(err);
}
var ret = sb.ToString();
// Cleans up weird addition of "Referenced" and the end of lines assigning def.TemplateScope = InRule.Repository.Vocabulary.TemplateScope.Local;
ret = ret.Replace(", Referenced;" + Environment.NewLine, ";" + Environment.NewLine);
return ret;
}
public static string ToCSharpCode(this CodeExpression codeExpression)
{
var sb = new StringBuilder();
var writer = new StringWriter(sb);
var ruleAppProvider = CodeDomProvider.CreateProvider("csharp");
var options = new CodeGeneratorOptions();
try
{
ruleAppProvider.GenerateCodeFromExpression(codeExpression, writer, options);
}
catch (Exception ex)
{
sb.AppendLine(ex.ToString());
}
foreach (var err in Errors)
{
sb.AppendLine(err);
}
var ret = sb.ToString();
return ret;
}
public static string ToCSharpCode(this CodeStatement codeStatement)
{
var sb = new StringBuilder();
var writer = new StringWriter(sb);
var ruleAppProvider = CodeDomProvider.CreateProvider("csharp");
var options = new CodeGeneratorOptions();
try
{
ruleAppProvider.GenerateCodeFromStatement(codeStatement, writer, options);
}
catch (Exception ex)
{
sb.AppendLine(ex.ToString());
}
foreach (var err in Errors)
{
sb.AppendLine(err);
}
var ret = sb.ToString();
return ret;
}
public static CodeTypeDeclaration ToCodeClass(this object sourceDef)
{
var defClass = CodeTypeDeclarationEx.CreateRoot(sourceDef);
var createMethod = defClass.AddCreateMethod(sourceDef, true);
if (sourceDef is RuleRepositoryDefBase)
{
var def = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
AppendProperities(defClass, def, sourceDef);
def.AddAsReturnStatement();
}
else
{
var def = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
createMethod.AddStatement(new CodeAssignStatement(def.Variable, sourceDef.ToCodeExpression2(defClass)));
def.AddAsReturnStatement();
}
return defClass.InnerDeclaration;
}
private static HashSet<string> Errors = new HashSet<string>();
#region Core
public static CodeExpression NullCodeExpression = new CodePrimitiveExpression(null);
public static CodeTypeReferenceEx ToCodeTypeReference(this Type type) { return new CodeTypeReferenceEx(type);}
public static CodeExpression ToCodeExpression(this CodeTypeReference typeReference)
{
return new CodeTypeReferenceExpression(typeReference);
}
public static CodeObjectCreateExpression CallCodeConstructor(this Type type, params CodeExpression[] parameters)
{
return new CodeObjectCreateExpression(type, parameters);
}
public static CodeExpression GetCodeProperty(this CodeExpression expression, string propName)
{
return new CodePropertyReferenceExpression() { PropertyName = propName, TargetObject = expression };
}
#region Def Factory Methods
public static CodeDefPropertyDescriptor ToParameter<T>(this string propertyName)
{
return new CodeDefPropertyDescriptor(propertyName, typeof(T));
}
/// <summary>
/// Appends arguments to the method signiture and the property assignments
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="outerClass"></param>
/// <param name="factoryInvoke"></param>
/// <param name="requiredArgs"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void AppendFactoryDefPropertySetter<T>(this CodeTypeDeclarationEx outerClass, CodeMethodInvokeExpression factoryInvoke, List<CodeDefPropertyDescriptor> requiredArgs, string propertyName, T propertyValue)
{
factoryInvoke.Parameters.Add(propertyValue.ToCodeExpression2(outerClass));
requiredArgs.Add(new CodeDefPropertyDescriptor(propertyName, typeof(T)));
}
public static void EnsureSharedFactoryMethod(this CodeTypeDeclarationEx fromOuterClass, CodeTypeReferenceEx returnType, string methodName, params CodeDefPropertyDescriptor[] parameters)
{
var defFactory = fromOuterClass.GetDefFactory();
if (!defFactory.ContainsSharedFactoryMethod(methodName, parameters))
{
CodeMethodVariableReferenceEx returnVariable;
var method = defFactory.AddFactoryMethod(returnType, methodName, out returnVariable);
method.DefPropertyAssignments = parameters;
foreach (var arg in parameters)
{
AppendAssignPropertyFromParameter(method, returnVariable, arg);
}
returnVariable.AddAsReturnStatement();
}
}
#endregion
public static bool TryCreateCodeExpressionFrom<T>(this object sourceDef, Func<T, CodeExpression> renderDelgate, out CodeExpression render)
{
// return sourceDef.TryRenderToCodeExpression<ClassificationDef>((obj) => obj.ToCodeExpression(outerClass), out render);
if (sourceDef.IsInstanceOf<T>())
{
render = renderDelgate((T)sourceDef);
return true;
}
render = null;
return false;
}
public static bool TryToCodeExpressionDerivedFrom<T>(this object sourceDef, Func<T, CodeExpression> renderDelgate, out CodeExpression render)
{
if (sourceDef != null)
{
if (typeof(T).IsAssignableFrom(sourceDef.GetType()))
{
render = renderDelgate((T)sourceDef);
return true;
}
}
render = null;
return false;
}
public static void AddSetProperty(this CodeMemberMethodEx method, CodeExpression variable, string propertyName, CodeExpression value)
{
if (propertyName == "TemplateScope")
{
int a = 1;
}
var propRef = new CodePropertyReferenceExpression();
propRef.TargetObject = variable;
propRef.PropertyName = propertyName;
var setProp = new CodeAssignStatement(propRef, value);
method.Statements.Add(setProp);
var code = setProp.ToCSharpCode();
}
#endregion core
public static CodeExpression ToCodeExpression2(this object source, CodeTypeDeclarationEx outerClass)
{
CodeExpression codeExpression;
if (source == null) {return NullCodeExpression;}
if (source.TryCreateCodeExpressionFrom <Guid>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<Enum>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<DateTime>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<string>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<decimal>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom <DBNull>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom <bool>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<ulong>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<long>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<ushort>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<short>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<uint>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<int>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<double>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<float>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<char>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<byte>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<sbyte>((v) => v.ToCodeExpression(), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<DataSet>((v) => v.ToCodeExpression(outerClass), out codeExpression)) return codeExpression;
if (source.TryCreateCodeExpressionFrom<DataTable>((v) => v.ToCodeExpression(outerClass), out codeExpression)) return codeExpression;
if (TryRenderAsDefSpecific(source, outerClass, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<FieldDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<RuleApplicationDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<InRule.Repository.Decisions.DecisionDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<RuleSetDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<EntityDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<InRule.Repository.DecisionTables.DecisionTableDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<UdfLibraryDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderNamedDefAsClass<VocabularyDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsAuthoringSettings(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<AssemblyDef.InfoBase>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.DecisionTables.ConditionDimensionDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.DecisionTables.ConditionValueDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.DecisionTables.ActionValueDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.DecisionTables.DecisionDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.DecisionTables.ActionDimensionDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<RestrictionInfo>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<AssemblyDef.TypeConverterInfo>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<EntityDefsInfo>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<SecurityPermission>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.RuleFlow.RuleFlowDesignerLayout>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.RuleFlow.RuleFlowDesignerItemLayout>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.XmlQualifiedNameInfo>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Common.Xml.Schema.Xsd.EmbeddedXmlSchema>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.WebServiceDef.OperationDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.WebServiceDef.PortDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.WebServiceDef.ServicesDef>(outerClass, source, out codeExpression)) return codeExpression;
if (TryRenderAsClassType<InRule.Repository.EndPoints.RuleWriteInfo>(outerClass, source, out codeExpression)) return codeExpression;
if (source.TryRenderAsGenericDef(outerClass, out codeExpression)) return codeExpression;
if (source.TryRenderAsUnknownObject(outerClass, out codeExpression)) return codeExpression;
var type = source.GetType();
var message = "Unhandled Render Type " + type.FullName;
if (Errors.Add(message))
{
Debug.WriteLine(message);
}
return ("Unhandled Render Type " + type.FullName).ToCodeExpression();
}
private static bool TryRenderAsDefSpecific(object source, CodeTypeDeclarationEx outerClass, out CodeExpression codeExpression)
{
if (source.TryCreateCodeExpressionFrom<ValueListItemDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<SendMailActionAttachmentDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<string[]>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<InRule.Repository.DecisionTables.ConditionNodeDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<InRule.Repository.DecisionTables.ActionNodeDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<NameSortOrderDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<ClassificationDef>((v) => v.ToCodeExpression(outerClass), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<ExecuteSqlQueryActionParameterValueDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<NameExpressionPairDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<ExecuteMethodActionParamDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<TypeMapping>((v) => v.ToCodeExpression(outerClass), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<CalcDef>((v) => v.ToCodeExpression(outerClass), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<RuleSetParameterDef>((v) => v.ToCodeExpression(outerClass), out codeExpression)){return true;}
if (source.TryCreateCodeExpressionFrom<ExecuteRulesetParameterDef>((v) => v.ToCodeExpression(), out codeExpression)){return true;}
if (source.TryCreateCodeExpressionFrom<DataTypeValueDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
if (source.TryCreateCodeExpressionFrom<EntityValueDef>((v) => v.ToCodeExpression(), out codeExpression)) { return true; }
return false;
}
public static bool TryRenderAsGenericDef(this object sourceDef, CodeTypeDeclarationEx outerClass, out CodeExpression render)
{
if (typeof(RuleRepositoryDefBase).IsAssignableFrom(sourceDef.GetType()))
{
render = sourceDef.RenderGenericDefCreateMethod(outerClass);
return true;
}
render = null;
return false;
}
public static bool TryRenderAsUnknownObject(this object sourceDef, CodeTypeDeclarationEx outerClass, out CodeExpression render)
{
render = sourceDef.RenderGenericDefCreateMethod(outerClass);
return true;
}
public static CodeExpression RenderGenericDefCreateMethod(this object sourceDef, CodeTypeDeclarationEx outerClass)
{
var defClass = outerClass;
var createMethod = outerClass.AddCreateMethod(sourceDef);
var render = new CodeMethodInvokeExpression(null, createMethod.Name);
var factoryMethod = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
AppendProperities(defClass, factoryMethod, sourceDef);
factoryMethod.AddAsReturnStatement();
return render;
}
private static bool TryRenderNamedDefAsClass<T>(CodeTypeDeclarationEx outerClass, object sourceDef, out CodeExpression render) where T : RuleRepositoryDefBase
{
if (typeof(T).IsAssignableFrom(sourceDef.GetType()))
{
var typedValue = (T)sourceDef;
var defClass = outerClass.AddChildClass(sourceDef, typedValue.Name);
var createMethod = defClass.AddCreateMethod(sourceDef, true);
var retMethod = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(defClass.Name),
createMethod.Name);
var returnVariable = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
AppendProperities(defClass, returnVariable, sourceDef);
returnVariable.AddAsReturnStatement();
render = retMethod;
return true;
}
render = null;
return false;
}
#region Type Helpers
// Type Helpers
public static ConstructorInfo GetPublicDefaultConstructor(this Type type)
{
if (type == null) throw new ArgumentNullException("type");
var constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null || !constructor.IsPublic)
{
var ctors =
from ctor in type.GetConstructors().Where(cons=>cons.IsPublic)
let prms = ctor.GetParameters()
where prms.All(p => p.IsOptional)
orderby prms.Length
select ctor;
constructor = ctors.FirstOrDefault();
}
return constructor;
}
public static bool HasDefaultConstructor(this Type type)
{
return type.GetPublicDefaultConstructor() != null;
}
public static bool IsInstanceOf<T>(this object instance) { return instance is T;}
#endregion
#region // Primitives
#endregion
//Defs
#region Defs
public static void AppendAssignPropertyFromParameter(CodeMemberMethodEx method, CodeMethodVariableReferenceEx returnValue, CodeDefPropertyDescriptor parameter)
{
var parameterName = parameter.Name.Substring(0, 1).ToLower() + parameter.Name.Substring(1);
method.Parameters.Add(new CodeParameterDeclarationExpression()
{
Name = parameterName,
Type = parameter.Type.ToCodeTypeReference()
});
returnValue.SetProperty(parameter.Name, new CodeVariableReferenceExpression() { VariableName = parameterName });
}
public static void AppendAssignPropertyFromParameter(CodeMemberMethodEx method, CodeMethodVariableReferenceEx returnValue, string defPropName, Type dataType)
{
AppendAssignPropertyFromParameter(method, returnValue, new CodeDefPropertyDescriptor(defPropName, dataType));
}
#endregion
#region Tree Walkers
private static bool HasAttribute(MemberInfo propInfo, Type attributeType)
{
var attribs = propInfo.GetCustomAttributes();
foreach (var attrib in attribs)
{
if (attributeType.IsAssignableFrom(attrib.GetType()))
{
return true;
}
}
return false;
}
private static bool SkipBoringProperty(string name)
{
return false;
switch (name)
{
case "RuntimeEngine":
case "FeatureVersion":
case "CompatibilityVersion":
case "IndentUnboundCollectionXml":
case "AllowRuleInactivation":
case "UseRuleVersions":
case "UseVersionCreationDates":
case "HasContextVersionSettings":
case "RunawayCycleCount":
case "Timeout":
case "RuntimeErrorHandlingPolicy":
case "LastValidateContentCode":
case "LastValidateDateTimeUtc":
case "IsolatedTestDomain":
case "SchemaGuid":
case "SchemaRevision":
case "SchemaPublicRevision":
case "Id":
case "RepositoryAssemblyFileVersion":
case "UpgraderMessageList":
case "PublicRevision":
case "Revision":
{
return true;
}
}
return false;
}
private static bool ShouldWriteProperty(PropertyInfo propInfo)
{
if (propInfo.DeclaringType == typeof( RuleApplicationDef) && propInfo.Name == "Decisions")
{
return true;
}
if (SkipBoringProperty(propInfo.Name)) return false;
if (HasAttribute(propInfo, typeof(XmlIgnoreAttribute))) return false;
// There are some collections that do not have setters
if (IsDerivedFromObservableCollection(propInfo.PropertyType)) return true;
if (IsDerivedFromRuleDefCollection(propInfo.PropertyType)) return true;
if (!propInfo.CanWrite) return false;
if (!propInfo.SetMethod.IsPublic) return false;
if (propInfo.SetMethod.IsStatic) return false;
return true;
}
private static bool ShouldWriteField(FieldInfo propInfo)
{
if (SkipBoringProperty(propInfo.Name)) return false;
if (propInfo.IsLiteral) return false;
if (!propInfo.IsPublic) return false;
if (propInfo.IsStatic) return false;
if (HasAttribute(propInfo, typeof(XmlIgnoreAttribute))) return false;
return true;
}
private static void AppendProperities(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, object sourceDef)
{
foreach (var propInfo in sourceDef.GetType().GetProperties().Where(p => ShouldWriteProperty(p)))
{
HandleProperty(outerClass, target, sourceDef, propInfo);
}
foreach (var propInfo in sourceDef.GetType().GetFields().Where(p => ShouldWriteField(p)))
{
HandleField(outerClass, target, sourceDef, propInfo);
}
}
private static void HandleField(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, object sourceDef, FieldInfo fieldInfo)
{
if (IsSpecifiedFalse(sourceDef, fieldInfo.Name)) return;
var value = fieldInfo.GetValue(sourceDef);
if (TryRenderAsCollection(outerClass, target, fieldInfo.Name, value)) return;
SetProperty(target, fieldInfo.Name, value.ToCodeExpression2(outerClass));
}
private static void SetProperty(CodeMethodVariableReferenceEx target, string name, CodeExpression value)
{
target.Method.AddSetProperty(target.Variable, name, value);
}
private static void HandleProperty(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, object sourceDef, PropertyInfo propInfo)
{
if (IsSpecifiedFalse(sourceDef, propInfo.Name)) return;
var value = propInfo.GetValue(sourceDef);
if (TryRenderAsCollection(outerClass, target, propInfo.Name, value)) return;
SetProperty(target, propInfo.Name, value.ToCodeExpression2(outerClass));
}
private static bool IsSpecifiedFalse(object sourceDef, string name)
{
var specifiedProp = sourceDef.GetType().GetProperty(name + "Specified");
if (specifiedProp != null)
{
var specified = specifiedProp.GetValue(sourceDef);
if (specified is bool && ((bool)specified) == false)
{
return true;
}
}
var specifiedField = sourceDef.GetType().GetField(name + "Specified");
if (specifiedField != null)
{
var specified = specifiedField.GetValue(sourceDef);
if (specified is bool && ((bool)specified) == false)
{
return true;
}
}
return false;
}
#endregion
private static bool TryRenderAsCollection(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object sourceDef)
{
if (sourceDef == null) return false;
if (TryRenderAsRuleRepositoryDefCollection<RuleRepositoryDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderObservableCollectionProperty(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ConditionValueDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsRuleRepositoryDefCollection<SecurityPermissionCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsStringCollection(target, propertyName, sourceDef)) return true;
if (TryRenderAsDefMetaDataCollection(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.Utilities.ExpressionDictionary, KeyValuePair<string, string>>((outer, def) => def.Key.ToCodeExpression(), (outer, def) => def.Value.ToCodeExpression(), outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.EndPoints.AssemblyDef.ClassInfoCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.EntityDefInfoCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ConditionDimensionDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ActionDimensionDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.DecisionDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ConditionValueDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ActionValueDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ConditionNodeDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.DecisionTables.ActionNodeDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.WebServiceDef.OperationDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.WebServiceDef.PortDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<InRule.Repository.WebServiceDef.ServicesDefCollection>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderXmlSerializableStringDictionaryCollectionPropertyWithIndexer(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<AssemblyDef.ClassMethodInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<AssemblyDef.ClassPropertyInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<AssemblyDef.ClassFieldInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<InRule.Repository.EndPoints.RuleWriteInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<RestrictionInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<AssemblyDef.ClassParameterInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<InRule.Repository.XmlQualifiedNameInfo[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderAsSetArrayValue<InRule.Common.Xml.Schema.Xsd.EmbeddedXmlSchema[]>(outerClass, target, propertyName, sourceDef)) return true;
if (TryRenderCollectionProperty<List<DesignerItemLayout>>(outerClass, target, propertyName, sourceDef)) return true;
return false;
}
private static bool TryRenderAsSetArrayValue<TArray>(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object sourceDef) where TArray : IEnumerable
{
if (!typeof(TArray).IsAssignableFrom(sourceDef.GetType())) return false;
TArray typedValue;
try
{
typedValue = (TArray)sourceDef;
}
catch (Exception)
{
return false;
}
if (typedValue != null)
{
List<CodeExpression> vals = new List<CodeExpression>();
foreach (var val in typedValue)
{
vals.Add(val.ToCodeExpression2(outerClass));
}
var array = new CodeArrayCreateExpression(typeof(TArray).ToCodeTypeReference(), vals.ToArray());
SetProperty(target, propertyName, array);
return true;
}
return false;
}
private static bool TryRenderAsClassType<T>(CodeTypeDeclarationEx outerClass, object sourceDef, out CodeExpression render)
{
if (typeof(T).IsAssignableFrom(sourceDef.GetType()))
{
string name = null;
var defClass = outerClass;
var createMethod = outerClass.AddCreateMethod(sourceDef);
render = new CodeMethodInvokeExpression(null, createMethod.Name);
var renderedCalcDef = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
AppendProperities(defClass, renderedCalcDef, sourceDef);
renderedCalcDef.AddAsReturnStatement();
return true;
}
render = null;
return false;
}
private static bool TryRenderAsAuthoringSettings(CodeTypeDeclarationEx outerClass, object sourceDef,
out CodeExpression render)
{
var typedValue = sourceDef as RuleApplicationAuthoringSettings;
if (typedValue != null)
{
var createMethod = outerClass.AddCreateMethod(sourceDef);
render = new CodeMethodInvokeExpression(null, createMethod.Name);
var renderedCalcDef = createMethod.AddReturnVariable("def", sourceDef.GetType().CallCodeConstructor());
AppendProperities(outerClass, renderedCalcDef, sourceDef);
renderedCalcDef.AddAsReturnStatement();
return true;
}
render = null;
return false;
}
public static bool TryRenderAsDefMetaDataCollection(CodeTypeDeclarationEx outerClass,
CodeMethodVariableReferenceEx target, string propertyName, object sourceDef)
{
var typedValue = sourceDef as RuleRepositoryDefBase.DefMetadataCollectionCollection;
if (typedValue != null)
{
SetPropertyForAttributes(target, sourceDef);
return true;
}
return false;
}
public static bool RenderHintAttributes = true;
private static void SetPropertyForAttributes(CodeMethodVariableReferenceEx target, object propValue)
{
var propCollections = (RuleRepositoryDefBase.DefMetadataCollectionCollection)propValue;
foreach (
RuleRepositoryDefBase.DefMetadataCollectionCollection.CollectionItem propCollection in propCollections)
{
// DefaultAttributeGroupKey
// ReservedInRuleAttributeGroupKey
// ReservedInRuleTokenKey
// ReservedInRuleVersionConversionKey
// ReservedInRuleTemplateConversionKey
CodeMethodVariableReferenceEx collection = null;
if (propCollection.Key == RuleRepositoryDefBase.DefaultAttributeGroupKey)
{
collection = target.GetPropertyReference("Attributes");
}
else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleAttributeGroupKey)
{
collection =
target.GetPropertyReference("Attributes")
.GetIndexer(
typeof(RuleRepositoryDefBase).ToCodeTypeReference()
.ToCodeExpression()
.GetCodeProperty("ReservedInRuleAttributeGroupKey"));
}
else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleTokenKey)
{
if (RenderHintAttributes)
{
collection =
target.GetPropertyReference("Attributes")
.GetIndexer(
typeof(RuleRepositoryDefBase).ToCodeTypeReference()
.ToCodeExpression()
.GetCodeProperty("ReservedInRuleTokenKey"));
}
}
else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleVersionConversionKey)
{
collection =
target.GetPropertyReference("Attributes")
.GetIndexer(
typeof(RuleRepositoryDefBase).ToCodeTypeReference()
.ToCodeExpression()
.GetCodeProperty("ReservedInRuleVersionConversionKey"));
}
else if (propCollection.Key == RuleRepositoryDefBase.ReservedInRuleTemplateConversionKey)
{
collection =
target.GetPropertyReference("Attributes")
.GetIndexer(
typeof(RuleRepositoryDefBase).ToCodeTypeReference()
.ToCodeExpression()
.GetCodeProperty("ReservedInRuleTemplateConversionKey"));
}
else
{
var keyRef =
typeof(AttributeGroupKey).CallCodeConstructor(
propCollection.Key.Name.ToCodeExpression(), propCollection.Key.Guid.ToCodeExpression());
var keyRefVar = target.DeclareVariable("AttribKey_" + propCollection.Key.Name,
typeof(AttributeGroupKey),
keyRef);
collection = target.GetPropertyReference("Attributes").GetIndexer(keyRefVar);
}
foreach (
InRule.Repository.XmlSerializableStringDictionary.XmlSerializableStringDictionaryItem value in
propCollection.Collection)
{
collection.SetIndexerValue(value.Key.ToCodeExpression(), value.Value.ToCodeExpression());
}
}
}
public static bool TryRenderXmlSerializableStringDictionaryCollectionPropertyWithIndexer(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object value)
{
if (value.GetType() == typeof(XmlSerializableStringDictionary))
{
var typedPropValue = (XmlSerializableStringDictionary)value;
if (typedPropValue != null)
{
var collection = target.GetPropertyReference(propertyName);
foreach (InRule.Repository.XmlSerializableStringDictionary.XmlSerializableStringDictionaryItem def in typedPropValue)
{
collection.SetIndexerValue(def.Key.ToCodeExpression(), def.Value.ToCodeExpression());
}
}
return true;
}
return false;
}
public static bool TryRenderCollectionProperty<TCollection>(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object value) where TCollection : IEnumerable
{
if (value.GetType() == typeof(TCollection))
{
var typedPropValue = (TCollection)value;
if (typedPropValue != null)
{
foreach (object def in typedPropValue)
{
target.GetPropertyReference(propertyName)
.AddInvokeMethodStatement("Add", def.ToCodeExpression2(outerClass));
}
}
return true;
}
return false;
}
public static List<Type> GetInheritanceStack(Type type)
{
var ret = new List<Type>();
while (type != null)
{
ret.Add(type);
type = type.BaseType;
}
return ret;
}
public static bool IsDerivedFromRuleDefCollection(Type type)
{
var stack = GetInheritanceStack(type);
return stack.Any(r => r.Name.StartsWith("RuleRepositoryDefCollection"));
}
public static bool IsDerivedFromObservableCollection(Type type)
{
var stack = GetInheritanceStack(type);
return stack.Any(r => r.Name.StartsWith("ObservableCollection"));
}
public static bool TryRenderObservableCollectionProperty(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object value)
{
if (value == null) return false;
if (IsDerivedFromObservableCollection(value.GetType()))
{
var typedPropValue = (IEnumerable)value;
if (typedPropValue != null)
{
foreach (object def in typedPropValue)
{
target.GetPropertyReference(propertyName)
.AddInvokeMethodStatement("Add", def.ToCodeExpression2(outerClass));
}
}
return true;
}
return false;
}
public static bool TryRenderCollectionProperty<TCollection, TType>(Func<CodeTypeDeclarationEx, TType, CodeExpression> renderArg1, Func<CodeTypeDeclarationEx, TType, CodeExpression> renderArg2, CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object value) where TCollection : IEnumerable
{
if (value.GetType() == typeof(TCollection))
{
var typedPropValue = (TCollection)value;
if (typedPropValue != null)
{
foreach (TType def in typedPropValue)
{
target.GetPropertyReference(propertyName)
.AddInvokeMethodStatement("Add", renderArg1(outerClass, def), renderArg2(outerClass, def));
}
}
return true;
}
return false;
}
private static bool TryRenderAsRuleRepositoryDefCollection<T>(CodeTypeDeclarationEx outerClass, CodeMethodVariableReferenceEx target, string propertyName, object sourceDef) where T : IEnumerable
{
if (typeof(T).IsAssignableFrom(sourceDef.GetType()))
{
var typedValue = (T)sourceDef;
if (typedValue != null)
{
foreach (var def in typedValue)
{
target.GetPropertyReference(propertyName)
.AddInvokeMethodStatement("Add", def.ToCodeExpression2(outerClass));
}
return true;
}
}
return false;
}
private static bool TryRenderAsStringCollection(CodeMethodVariableReferenceEx target, string propertyName, object sourceDef)
{
var typedValue = sourceDef as StringCollection;
if (typedValue != null)
{
var collection = target.GetPropertyReference(propertyName);
List<CodeExpression> vals = new List<CodeExpression>();
foreach (var val in typedValue)
{
vals.Add(val.ToCodeExpression());
}
var array = new CodeArrayCreateExpression(typeof(String[]).ToCodeTypeReference(), vals.ToArray());
collection.AddInvokeMethodStatement("AddRange", array);
return true;
}
return false;
}
}
}
|
using System;
using System.Threading;
using StackExchange.Redis;
namespace RedLock4Net.Test
{
class Program
{
static void Main(string[] args)
{
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("127.0.0.0:6379,allowAdmin=true");
var redLockFactory = new RedLockFactory(connection);
using (var redLock = redLockFactory.GetLock("lock", TimeSpan.FromMinutes(10), 2, TimeSpan.FromSeconds(2)))
{
Console.WriteLine("[A] Try to get lock");
if (redLock.IsAcquired)
{
Console.WriteLine("[A] Geted lock");
Thread.Sleep(10000);
}
else
{
Console.WriteLine("[A] UnAcquired");
}
}
Console.WriteLine("[A] End");
Console.ReadLine();
}
}
}
|
using UnityEngine;
using System.Collections;
public class GroundTile : MonoBehaviour {
public float spinDuration = 1;
public float timeBetweenSpins = 1;
int randomizer;
public Color burnedColor;
// Use this for initialization
void Start () {
randomizer = Random.Range(0, 2) * 2 - 1;
}
// Update is called once per frame
void Update () {
}
public void StartRotation() {
StartCoroutine("Rotate");
}
IEnumerator Rotate() {
// Randomly choose either 1 or -1
gameObject.RotateTo(new Vector3(0, 0, 180 * randomizer), spinDuration, 0, EaseType.easeOutBack);
yield return new WaitForSeconds(timeBetweenSpins);
StartCoroutine("Rotate");
}
public void Cancel() {
StopCoroutine("Rotate");
}
public void GetBurned() {
GetComponent<SpriteRenderer>().color = burnedColor;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StatkiWseiLibrary.Style
{
public class SrodkowanieTeksu
{
public static void SrodkowanieTekstu(string wiadomosc)
{
int ekranSzerokosc = Console.WindowWidth;
int stringSzerokosc = wiadomosc.Length;
int miejsca = (ekranSzerokosc / 2) + (stringSzerokosc / 2);
Console.WriteLine("\n");
Console.WriteLine(wiadomosc.PadLeft(miejsca));
}
}
}
|
using System;
/*Write a method GetMax() with two parameters that returns the larger of two integers.
Write a program that reads 3 integers from the console and prints the largest of them
using the method GetMax().*/
class Program
{
static int GetMax(int integer1, int integer2)
{
int result = 0;
if (integer1 >= integer2)
result = integer1;
else
result = integer2;
return result;
}
static void Main()
{
Console.Write("First integer: ");
int integer1 = int.Parse(Console.ReadLine());
Console.Write("Second integer: ");
int integer2 = int.Parse(Console.ReadLine());
Console.WriteLine(GetMax(integer1, integer2));
}
}
|
using System;
using System.Linq;
using System.Reflection;
using DelftTools.Controls.Swf;
using DelftTools.TestUtils;
using NUnit.Framework;
namespace DelftTools.Tests.Controls.Swf
{
[TestFixture]
public class GridBasedDialogTest
{
private PropertyInfo[] properties;
#if ! MONO
[Test, Category(TestCategory.WindowsForms)]
public void ShowDialogWithStrings()
{
var dialog = new GridBasedDialog();
dialog.MasterSelectionChanged += dialog_SelectionChanged;
Type type = dialog.GetType();
properties = type.GetProperties();
dialog.MasterDataSource = properties;
WindowsFormsTestHelper.ShowModal(dialog);
}
#endif
void dialog_SelectionChanged(object sender, EventArgs e)
{
GridBasedDialog gridBasedDialog = (GridBasedDialog)sender;
if (1 == gridBasedDialog.MasterSelectedIndices.Count)
{
PropertyInfo propertyInfo = properties[gridBasedDialog.MasterSelectedIndices[0]];
Type type = propertyInfo.GetType();
PropertyInfo[] propertyInfoproperties = type.GetProperties();
//, Value = propertyInfo.GetValue(pi, null).ToString()
var ds = propertyInfoproperties.Select(pi => new { pi.Name }).ToArray();
//Type type = propertyInfo.GetType();
//PropertyInfo[] propertyInfoproperties =
//coverages.Select(c => new { c.Owner, Coverage = c }).ToArray();
gridBasedDialog.SlaveDataSource = ds;
}
}
}
} |
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace DbContextGeneratorWithCodeFirst
{
public partial class QAContext : DbContext
{
static QAContext()
{
Database.SetInitializer<QAContext>(new CreateDatabaseIfNotExists<QAContext>());
}
public QAContext()
: base("Name=QAContext")
{
}
public QAContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public DbSet<Answer> Answers { get; set; }
public DbSet<Question> Questions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
|
using UnityEngine;
using System.Collections;
public class KillBox : MonoBehaviour {
public float f_Damage;
private PlayerStates playerStates;
void Awake() {
playerStates = GameObject.FindWithTag("Player").GetComponent<PlayerStates>();
}
// Use this for initialization
void Start () {
f_Damage = playerStates.getMaxHP();
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other) {
if(other.tag == "Player")
{
Debug.Log("Player is dead! No");
playerStates.takeDamage(f_Damage);
}
else{
//Do nothing
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LHRLA.DAL;
using LHRLA.Core.Helpers;
namespace LHRLA.Controllers
{
[SessionAttribute]
public class CityController : Controller
{
// GET: BrachesSetup
[AuthOp]
public ActionResult List()
{
LHRLA.DAL.DataAccessClasses.CityDataAccess bda = new LHRLA.DAL.DataAccessClasses.CityDataAccess();
var list = bda.GetAllCity();
//ViewBag.City = null;
return View(list);
}
public ActionResult AddUpdateCity(tbl_City request)
{
LHRLA.DAL.DataAccessClasses.CityDataAccess bda = new LHRLA.DAL.DataAccessClasses.CityDataAccess();
var Name = request.Name.ToLower().Trim();
var CityExistData = bda.GetCitybyIDOfExistingName(request.ID, Name);
var NameExistValue = CityExistData.Select(o => o.Name).FirstOrDefault();
var NameData = bda.GetCitybyIDName(request.ID, Name);
var NameValue = NameData.Select(o => o.Name).FirstOrDefault();
var flag = true;
if (request.ID > 0)
{
if (NameValue != Name)
{
flag = bda.UpdateCity(request);
}
else if (NameExistValue == Name)
{
flag = bda.UpdateCity(request);
}
else
{
return Json(new { IsSuccess = false, ErrorMessage = (flag == false) ? CustomMessages.Success : CustomMessages.GenericErrorMessage, Response = (flag == true) ? Url.Action("Index", "CaseTags") : null }, JsonRequestBehavior.AllowGet);
}
}
// var flag = request.ID > 0 ? bda.UpdateBranch(request) : bda.AddBranch(request);
else
{
var CheckDuplicate = bda.CheckDuplicateData(Name);
if (CheckDuplicate.Count > 0)
{
return Json(new { IsSuccess = false, ErrorMessage = (flag == false) ? CustomMessages.DuplicateEmail : CustomMessages.GenericErrorMessage, Response = (flag == false) ? Url.Action("Index", "CaseTags") : null }, JsonRequestBehavior.AllowGet);
}
else
{
flag = bda.AddCity(request);
}
}
// var flag = request.ID > 0 ? bda.UpdateCity(request) : bda.AddCity(request);
return Json(new { IsSuccess = flag, ErrorMessage = (flag == true) ? CustomMessages.Success : CustomMessages.GenericErrorMessage, Response = (flag == true) ? Url.Action("Index", "City") : null }, JsonRequestBehavior.AllowGet);
}
[AuthOp]
public ActionResult Index(int ? id)
{
if (id == 0)
{
return View();
}
int Cityid = Convert.ToInt32(id);
LHRLA.DAL.DataAccessClasses.CityDataAccess bda = new LHRLA.DAL.DataAccessClasses.CityDataAccess();
var flag = bda.GetCitybyID(Cityid).FirstOrDefault();
return View(flag);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Diagnostics;
using System;
public class Pathfinding : MonoBehaviour
{
PathRequestManager requestManager;
Grid grid;
void Awake()
{
requestManager = GetComponent<PathRequestManager>();
grid = GetComponent<Grid>();
}
public void StartFindPath(Vector3 startPos, Vector3 targetPos)
{
FindPath(startPos, targetPos);
}
// スタートからゴールまでのパスを見つける
void FindPath(Vector3 startPos, Vector3 targetPos)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Vector3[] wayPoints = new Vector3[0];
bool pathSuccess = false;
Node startNode = grid.GetNodeFromWorldPoint(startPos);
Node targetNode = grid.GetNodeFromWorldPoint(targetPos);
if(startNode.m_Walkable && targetNode.m_Walkable)
{
Heap<Node> openSet = new Heap<Node>(grid.MaxSize);
// HashSet...要素の重複を防ぐ
HashSet<Node> closedSet = new HashSet<Node>();
openSet.Add(startNode);
// オープンリストが無くなるまで検索
while (openSet.Count > 0)
{
Node currentNode = openSet.RemoveFirst();
// クローズリストに追加
closedSet.Add(currentNode);
// 検索ノードがゴールに達したらパスを作る
if (currentNode == targetNode)
{
sw.Stop();
print("Path found: " + sw.ElapsedMilliseconds + " ms");
pathSuccess = true;
break;
}
foreach (Node neighbor in grid.GetNeighbours(currentNode))
{
// 歩けない場所であるか隣接ノードにクローズリストがあれば次へ
if (!neighbor.m_Walkable || closedSet.Contains(neighbor))
continue;
// 現在のノードから隣接ノードまでの距離コストを出す
int MovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbor);
/* 現在のノードから隣接ノードまでの距離コストより隣接頂点間ノードが高い
* 又は
* 隣接ノードがオープンノードになければ隣接ノードとして登録
*/
if (MovementCostToNeighbour < neighbor.gCost || !openSet.Contains(neighbor))
{
neighbor.gCost = MovementCostToNeighbour;
neighbor.hCost = GetDistance(neighbor, targetNode);
neighbor.parent = currentNode;
// Openノードに隣接ノードが入っていなければ追加
// Contains...要素の検索
if (!openSet.Contains(neighbor))
openSet.Add(neighbor);
}
}
}
}
if(pathSuccess)
{
wayPoints = RetracePath(startNode, targetNode);
}
requestManager.FinishedProcessingPath(wayPoints, pathSuccess);
}
// スタートからゴールまでのパスを作る
Vector3[] RetracePath(Node startNode, Node endNode)
{
List<Node> path = new List<Node>();
// ゴールのノードからスタート
Node currentNode = endNode;
// ゴールからスタートまでノードを辿る
while(currentNode != startNode)
{
path.Add(currentNode);
currentNode = currentNode.parent;
}
// 進むポイントを決める
Vector3[] wayPoints = SimplifyPath(path);
// 反転してスタートからゴールまでのパスを作る
Array.Reverse(wayPoints);
return wayPoints;
}
// 進むポイントを減らす
Vector3[] SimplifyPath(List<Node> path)
{
List<Vector3> wayPoints = new List<Vector3>();
Vector2 directionOld = Vector2.zero;
for(int i = 1; i < path.Count; i++)
{
// 次のノードの位置の差分を取る
Vector2 directionNew = new Vector2(path[i - 1].m_gridX - path[i].m_gridX, path[i - 1].m_gridY - path[i].m_gridY);
// 前回取った差分と不一致であれば、進むポイントとして登録する
if(directionNew != directionOld)
{
wayPoints.Add(path[i].m_WorldPosition);
}
directionOld = directionNew;
}
return wayPoints.ToArray();
}
int GetDistance(Node nodeA, Node nodeB)
{
int dstX = Mathf.Abs(nodeA.m_gridX - nodeB.m_gridX);
int dstY = Mathf.Abs(nodeA.m_gridY - nodeB.m_gridY);
// √2(三平方の定理)+直線の距離
if (dstX > dstY)
return 14 * dstY + 10 * (dstX - dstY);
return 14 * dstX + 10 * (dstY - dstX);
}
}
|
namespace AppStore.Infra.CrossCutting.Helpers
{
public static class StringExtension
{
public static string GetLast(this string source, int tailLength)
{
if (tailLength >= source.Length)
return source;
return source.Substring(source.Length - tailLength);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSTestFramework.DataProvider;
namespace MSTestFramework.Tests
{
[TestClass]
public class DataProviderAccessTests
{
[TestMethod]
public void DataProviderAccessTest()
{
var json = DataProviderAccess.GetData("testjson1.json");
Assert.AreEqual("testvalue10", json["key1"], "The key 1 value wasn't testvalue10");
Assert.AreEqual("testvalue20", json["key2"], "The key 2 value wasn't testvalue20");
}
}
}
|
using System;
namespace Phenix.Test.使用指南._11._3._2._2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("本程序为{0}位,请确认所连数据库客户端引擎是否与之匹配?(如不匹配可调整本程序的'平台目标'生成类型)", Environment.Is64BitProcess ? "64" : "32");
Console.WriteLine("请通过检索“//*”了解代码中的特殊处理");
Console.WriteLine("本案例中表结构未设置中文友好名,可通过数据库字典相关的Comments内容来自动设置上");
Console.WriteLine("测试过程中的日志保存在:" + Phenix.Core.AppConfig.TempDirectory);
Console.WriteLine("因需要初始化本地配置数据,第一次运行会比正常情况下稍慢,请耐心等待");
Console.WriteLine();
Console.WriteLine("设为调试状态");
Phenix.Core.AppConfig.Debugging = true;
Console.WriteLine();
Console.WriteLine("模拟登陆");
Phenix.Business.Security.UserPrincipal.User = Phenix.Business.Security.UserPrincipal.CreateTester();
Phenix.Services.Client.Library.Registration.RegisterEmbeddedWorker(false);
Console.WriteLine();
Console.WriteLine("**** 搭建测试环境 ****");
UserList users = UserList.Fetch(p => !p.Locked.Value);
Console.WriteLine("Fetch未被锁的User对象,业务对象数:" + users.Count);
Console.WriteLine();
Console.WriteLine("演示普通方法,可对照性能...");
DateTime dt = DateTime.Now;
foreach (User user in users)
{
Console.Write(user.Name + ", 拥有角色:");
if (user.UserRoleInfos_Normal.Count == 0)
Console.WriteLine("无");
else
foreach (UserRoleInfo userRoleInfo in user.UserRoleInfos_Normal)
Console.Write(userRoleInfo.RoleName + " ");
Console.WriteLine();
}
Console.WriteLine("普通方法用时:" + DateTime.Now.Subtract(dt).TotalSeconds + "秒");
Console.WriteLine();
Console.WriteLine("**** 测试从source业务对象集合中Fetch出从业务对象集合功能 ****");
dt = DateTime.Now;
foreach (User user in users)
{
Console.Write(user.Name + ", 拥有角色:");
if (user.UserRoleInfos_Special.Count == 0)
Console.WriteLine("无");
else
foreach (UserRoleInfo userRoleInfo in user.UserRoleInfos_Special)
Console.Write(userRoleInfo.RoleName + " ");
Console.WriteLine();
}
Console.WriteLine("特殊方法用时:" + DateTime.Now.Subtract(dt).TotalSeconds + "秒");
Console.WriteLine();
Console.WriteLine("结束, 与数据库交互细节见日志");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using ToDo.Entities.Concrete;
namespace ToDo.WebUI.Areas.Admin.Models
{
public class TaskAddViewModel
{
[Required(ErrorMessage ="Please enter task name")]
public string Name { get; set; }
public string Description { get; set; }
[Range(0,int.MaxValue,ErrorMessage ="Please select priority status")]
public int PriorityId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InterfaceExample
{
public class Student : IInformation, IPrinter
{
public string RegNo { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
public string Email { get; set; }
public string GetBasicInformation()
{
return "RegNo: " + RegNo + " Name: " + Name + " Roll: " + Roll;
}
public void Print()
{
throw new NotImplementedException();
}
public void SetIpAdress(string ip)
{
throw new NotImplementedException();
}
}
}
|
using Autofac;
using Autofac.Integration.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using YourContacts.Contracts;
using YourContacts.Models;
using YourContacts.Services.Database.Sql;
using YourContacts.Services.Database.Sql.Translators;
using YourContacts.Validators;
namespace YourContacts.App_Start
{
public static class AutofacWebapiConfig
{
public static IContainer Container;
public static void Initialize(HttpConfiguration config)
{
Initialize(config, RegisterServices(new ContainerBuilder()));
}
public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
//Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<SqlAdaptor>().As<IDataStore>().InstancePerRequest();
builder.RegisterType<ContactModelValidationContext>().As<IValidator<Contact>>().InstancePerRequest();
builder.RegisterType<ModelToSqlEntityTranslator>().As<ITranslator<Contact, ContactDetail>>().InstancePerRequest();
builder.RegisterType<SqlEntityToModelTranslator>().As<ITranslator<ContactDetail, Contact>>().InstancePerRequest();
//Set the dependency resolver to be Autofac.
Container = builder.Build();
return Container;
}
}
} |
namespace HotelBookingSystem.Models
{
using System;
using Interfaces;
public class Booking : AvailableDate, IBooking
{
private decimal totalPrice;
public Booking(
IUser client,
DateTime startBookDate,
DateTime endBookDate,
decimal totalPrice,
string comments) : base(startBookDate, endBookDate)
{
this.Client = client;
this.TotalPrice = totalPrice;
this.Comments = comments;
}
public int Id { get; set; }
public IUser Client { get; }
public string Comments { get; }
public decimal TotalPrice
{
get
{
return this.totalPrice;
}
private set
{
if (value < 0)
{
throw new ArgumentException("The total price must not be less than 0.");
}
this.totalPrice = value;
}
}
}
} |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System;
namespace Inventory.Data.Services
{
partial class DataServiceBase
{
public async Task<IList<OrderDish>> GetOrderDishesAsync(Guid orderGuid)
{
DataRequest<OrderDish> request = new DataRequest<OrderDish> { Where = (r) => r.OrderGuid == orderGuid };
IQueryable<OrderDish> items = GetOrderDishes(request);
// Execute
var records = await items
.Include(orderDish => orderDish.Dish)
.AsNoTracking()
.ToListAsync();
return records;
}
public async Task<OrderDish> GetOrderDishAsync(int id)
{
return await _dataSource.OrderDishes
.Include(orderDish => orderDish.Dish)
.FirstOrDefaultAsync(orderDish => orderDish.Id == id);
}
public async Task<IList<OrderDish>> GetOrderDishesAsync(int skip, int take, DataRequest<OrderDish> request)
{
IQueryable<OrderDish> items = GetOrderDishes(request);
// Execute
var records = await items.Skip(skip).Take(take)
.Include(orderDish => orderDish.Dish)
.AsNoTracking()
.ToListAsync();
return records;
}
public async Task<IList<OrderDish>> GetOrderDishKeysAsync(int skip, int take, DataRequest<OrderDish> request)
{
IQueryable<OrderDish> items = GetOrderDishes(request);
// Execute
var records = await items.Skip(skip).Take(take)
.Select(x => new OrderDish
{
Id = x.Id,
DishGuid = x.DishGuid,
OrderGuid = x.OrderGuid,
TaxTypeId = x.TaxTypeId
})
.AsNoTracking()
.ToListAsync();
return records;
}
private IQueryable<OrderDish> GetOrderDishes(DataRequest<OrderDish> request)
{
IQueryable<OrderDish> items = _dataSource.OrderDishes
.Include(orderDish => orderDish.Dish)
.Include(orderDish => orderDish.OrderDishGarnishes)
.Include(orderDish => orderDish.OrderDishIngredients);
// Query
// TODO: Not supported
//if (!String.IsNullOrEmpty(request.Query))
//{
// items = items.Where(r => r.SearchTerms.Contains(request.Query.ToLower()));
//}
// Where
if (request.Where != null)
{
items = items.Where(request.Where);
}
// Order By
if (request.OrderBy != null)
{
items = items.OrderBy(request.OrderBy);
}
if (request.OrderByDesc != null)
{
items = items.OrderByDescending(request.OrderByDesc);
}
return items;
}
public async Task<int> GetOrderDishesCountAsync(DataRequest<OrderDish> request)
{
IQueryable<OrderDish> items = _dataSource.OrderDishes
.Include(orderDish => orderDish.Dish);
// Query
// TODO: Not supported
//if (!String.IsNullOrEmpty(request.Query))
//{
// items = items.Where(r => r.SearchTerms.Contains(request.Query.ToLower()));
//}
// Where
if (request.Where != null)
{
items = items.Where(request.Where);
}
return await items.CountAsync();
}
public async Task<int> UpdateOrderDishAsync(OrderDish orderDish)
{
if (orderDish.Id > 0)
{
_dataSource.Entry(orderDish).State = EntityState.Modified;
}
else
{
// TODO:
//orderItem.CreateOn = DateTime.UtcNow;
_dataSource.Entry(orderDish).State = EntityState.Added;
}
// TODO:
//orderItem.LastModifiedOn = DateTime.UtcNow;
//orderItem.SearchTerms = orderItem.BuildSearchTerms();
return await _dataSource.SaveChangesAsync();
}
public async Task<int> DeleteOrderDishesAsync(params OrderDish[] orderDishes)
{
_dataSource.OrderDishes.RemoveRange(orderDishes);
return await _dataSource.SaveChangesAsync();
}
}
}
|
using System.Windows.Controls;
namespace WPFSampleLib
{
/// <summary>
/// UserControl1.xaml の相互作用ロジック
/// </summary>
public partial class Staff : UserControl
{
public Staff()
{
InitializeComponent();
}
}
}
|
namespace OddLines
{
using System.IO;
using BashSoft;
public class OddLines
{
public static void Main()
{
string myOutputPath = @"..\..\..\MyOutput.txt";
string inputPath = @"..\..\..\01_OddLinesIn.txt";
string expectedOutputPath = @"..\..\..\01_OddLinesOut.txt";
StreamReader reader = File.OpenText(inputPath);
StreamWriter writer = File.AppendText(myOutputPath);
using (reader)
{
using (writer)
{
string line = reader.ReadLine();
int counter = 0;
while (!string.IsNullOrEmpty(line))
{
if (counter % 2 != 0)
{
writer.WriteLine(line);
}
counter++;
line = reader.ReadLine();
}
}
}
Tester.CompareContent(myOutputPath, expectedOutputPath);
File.Delete(myOutputPath);
}
}
}
|
namespace _2.UnitTestingTask
{
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using _1.TaskSchool;
[TestClass]
class TestStudent
{
[TestMethod]
[ExpectedException(typeof(CustomSchoolExeption))]
public void TestStudentNullName()
{
string name = string.Empty;
int uniqueNumber = 12345;
Student student = new Student(name, uniqueNumber);
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using com.Sconit.SmartDevice.Properties;
using System.Reflection;
using System.Web.Services.Protocols;
using com.Sconit.SmartDevice.SmartDeviceRef;
namespace com.Sconit.SmartDevice
{
public class Utility
{
public static string WEBSERVICE_URL = "http://10.136.3.28/WebService/SD/SmartDeviceService.asmx";
// public static string WEBSERVICE_URL = "http://localhost:2015/WebService/SD/SmartDeviceService.asmx";
public static string GetBarCodeType(BarCodeType[] barCodeTypes, string barCode)
{
if (string.IsNullOrEmpty(barCode) || barCode.Length < 2)
{
return null;
}
else if (barCode.StartsWith("$"))
{
return barCode.Substring(1, 1);
}
else if (barCode.StartsWith(".."))
{
return CodeMaster.BarCodeType.DATE.ToString();
}
else if (barCode.StartsWith("W"))
{
return CodeMaster.BarCodeType.W.ToString();
}
else if (barCode.StartsWith("SP"))
{
return CodeMaster.BarCodeType.SP.ToString();
}
else if (barCode.StartsWith("HU"))
{
return CodeMaster.BarCodeType.HU.ToString();
}
else if (barCode.StartsWith("DC"))
{
return CodeMaster.BarCodeType.DC.ToString();
}
else if (barCode.StartsWith("COT"))
{
return CodeMaster.BarCodeType.COT.ToString();
}
else if (barCode.StartsWith("TP") || (barCode.StartsWith("UN")))
{
return CodeMaster.BarCodeType.TP.ToString();
}
else
{
foreach (var codeType in barCodeTypes)
{
if (barCode.ToUpper().StartsWith(codeType.PreFixed.ToUpper()))
{
return codeType.Type.ToString();
}
}
}
return null;
}
public static bool HasPermission(IpMaster ipMaster, User user)
{
return HasPermission(user.Permissions, ipMaster.OrderType, ipMaster.IsCheckPartyFromAuthority, ipMaster.IsCheckPartyToAuthority, ipMaster.PartyFrom, ipMaster.PartyTo);
}
public static bool HasPermission(OrderMaster orderMaster, User user)
{
return HasPermission(user.Permissions, orderMaster.Type, orderMaster.IsCheckPartyFromAuthority, orderMaster.IsCheckPartyToAuthority, orderMaster.PartyFrom, orderMaster.PartyTo, orderMaster.SubType == OrderSubType.Return ? true : false); ;
}
public static bool HasPermission(FlowMaster flowMaster, User user)
{
return HasPermission(user.Permissions, flowMaster.Type, flowMaster.IsCheckPartyFromAuthority, flowMaster.IsCheckPartyToAuthority, flowMaster.PartyFrom, flowMaster.PartyTo);
}
public static bool HasPermission(PickListMaster pickListMaster, User user)
{
return HasPermission(user.Permissions, pickListMaster.OrderType, pickListMaster.IsCheckPartyFromAuthority, pickListMaster.IsCheckPartyToAuthority, pickListMaster.PartyFrom, pickListMaster.PartyTo);
}
public static bool HasPermission(Permission[] permissions, OrderType? orderType, bool isCheckPartyFromAuthority, bool isCheckPartyToAuthority, string partyFrom, string partyTo)
{
return HasPermission(permissions, orderType, isCheckPartyFromAuthority, isCheckPartyToAuthority, partyFrom, partyTo, false);
}
public static bool HasPermission(Permission[] permissions, OrderType? orderType, bool isCheckPartyFromAuthority, bool isCheckPartyToAuthority, string partyFrom, string partyTo, bool isReturn)
{
bool hasPermission = true;
if (orderType == null || orderType == OrderType.Transfer || orderType == OrderType.Production || orderType == OrderType.SubContractTransfer)
{
if (orderType == null && partyFrom == null)
{
hasPermission = true;
}
else
{
if (isCheckPartyFromAuthority && isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyFrom)
&& permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyTo);
}
else if (isCheckPartyFromAuthority && !isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyFrom);
}
else if (!isCheckPartyFromAuthority && isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyTo);
}
else if (!isCheckPartyFromAuthority && !isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyFrom)
|| permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyTo);
}
}
}
else if (orderType == OrderType.Procurement || orderType == OrderType.SubContract || orderType == OrderType.ScheduleLine)
{
if (!isReturn)
{
if (isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Supplier).Select(t => t.PermissionCode).Contains(partyFrom)
&& permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyTo);
}
else
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Supplier).Select(t => t.PermissionCode).Contains(partyFrom);
}
}
else
{
if (isCheckPartyToAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Supplier).Select(t => t.PermissionCode).Contains(partyTo)
&& permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyFrom);
}
else
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Supplier).Select(t => t.PermissionCode).Contains(partyTo);
}
}
}
else if (orderType == OrderType.Distribution || orderType == OrderType.CustomerGoods)
{
if (!isReturn)
{
if (isCheckPartyFromAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyFrom)
&& permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Customer).Select(t => t.PermissionCode).Contains(partyTo);
}
else
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Customer).Select(t => t.PermissionCode).Contains(partyTo);
}
}
else
{
if (isCheckPartyFromAuthority)
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region).Select(t => t.PermissionCode).Contains(partyTo)
&& permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Customer).Select(t => t.PermissionCode).Contains(partyFrom);
}
else
{
hasPermission = permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Customer).Select(t => t.PermissionCode).Contains(partyFrom);
}
}
}
return hasPermission;
}
#region
public static void ShowMessageBox(string message)
{
message = FormatExMessage(message);
Sound sound = new Sound(Resources.Error);
sound.Play();
DialogResult dr = MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
}
public static void ShowMessageBox(BusinessException ex)
{
string message = FormatExMessage(ex.Message);
if (ex.MessageParams != null)
{
message = string.Format(message, ex.MessageParams);
}
ShowMessageBox(message);
}
public static void ShowMessageBox(Exception ex)
{
string message = FormatExMessage(ex.Message);
ShowMessageBox(message);
}
public static void ShowMessageBox(SoapException ex)
{
string message = FormatExMessage(ex.Message);
ShowMessageBox(message);
}
public static string FormatExMessage(string message)
{
try
{
if (message.StartsWith("System.Web.Services.Protocols.SoapException"))
{
message = message.Remove(0, 44);
int index = message.IndexOf("\n");
if (index > 0)
{
message = message.Remove(index, message.Length - index);
}
index = message.IndexOf("\r\n");
if (index > 0)
{
message = message.Remove(index, message.Length - index);
}
}
if (message.Contains("NHibernate.ObjectNotFoundException"))
{
message = "输入错误,没有找到此对象";
}
message = message.Replace("\\n", "\r\n");
return message;
}
catch (Exception)
{
return message;
}
}
public static string Md5(string originalPassword)
{
MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(originalPassword);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
public static void ValidatorDecimal(object sender, KeyPressEventArgs e)
{
if (e.KeyChar.ToString() == "\b" || e.KeyChar.ToString() == "." || e.KeyChar.ToString() == "-")
{
string str = string.Empty;
if (e.KeyChar.ToString() == "\b")
{
e.Handled = false;
return;
}
else
{
str = ((TextBox)sender).Text.Trim() + e.KeyChar.ToString();
}
if (Utility.IsDecimal(str) || str == "-")
{
e.Handled = false;
return;
}
}
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
public static bool IsDecimal(string str)
{
try
{
Convert.ToDecimal(str);
return true;
}
catch
{
return false;
}
}
#endregion
public static void SetKeyCodeDiff(int diff)
{
Microsoft.Win32.RegistryKey subKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SconitKeyCodeDiff", true);
if (subKey == null)
{
subKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SconitKeyCodeDiff");
}
subKey.SetValue("KeyCodeDiff", diff);
subKey.Close();
}
public static int GetKeyCodeDiff()
{
Microsoft.Win32.RegistryKey subKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SconitKeyCodeDiff");
if (subKey == null)
{
return 0;
}
int selectIndex = (int)(subKey.GetValue("KeyCodeDiff"));
subKey.Close();
return selectIndex;
}
}
public class Sound
{
private byte[] m_soundBytes;
private string m_fileName;
private enum Flags
{
SND_SYNC = 0x0000, /* play synchronously (default) */
SND_ASYNC = 0x0001, /* play asynchronously */
SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */
SND_MEMORY = 0x0004, /* pszSound points to a memory file */
SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */
SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */
SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */
SND_ALIAS = 0x00010000, /* name is a registry alias */
SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */
SND_FILENAME = 0x00020000, /* name is file name */
SND_RESOURCE = 0x00040004 /* name is resource name or atom */
}
[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]
private extern static int WCE_PlaySound(string szSound, IntPtr hMod, int flags);
[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]
private extern static int WCE_PlaySoundBytes(byte[] szSound, IntPtr hMod, int flags);
/// <summary>
/// Construct the Sound object to play sound data from the specified file.
/// </summary>
public Sound(string fileName)
{
m_fileName = fileName;
}
/// <summary>
/// Construct the Sound object to play sound data from the specified stream.
/// </summary>
public Sound(Stream stream)
{
// read the data from the stream
m_soundBytes = new byte[stream.Length];
stream.Read(m_soundBytes, 0, (int)stream.Length);
}
/// <summary>
/// Construct the Sound object to play sound data from the specified byte.
/// </summary>
public Sound(byte[] m_soundBytes)
{
this.m_soundBytes = m_soundBytes;
}
/// <summary>
/// Play the sound
/// </summary>
public void Play()
{
// if a file name has been registered, call WCE_PlaySound,
// otherwise call WCE_PlaySoundBytes
try
{
if (m_fileName != null)
{
WCE_PlaySound(m_fileName, IntPtr.Zero, (int)(Flags.SND_ASYNC | Flags.SND_FILENAME));
}
else
{
WCE_PlaySoundBytes(m_soundBytes, IntPtr.Zero, (int)(Flags.SND_ASYNC | Flags.SND_MEMORY));
}
}
catch (Exception)
{
//throw;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace CSF2BlackJackGame
{
class BlackJack
{
static void Main(string[] args)
{
// Create player hand
List<int> playerHand = new List<int> { getRandomCard(), getRandomCard() };
Console.WriteLine($"Player Hand: {playerHand[0]}\t{playerHand[1]}" +
$"\nPlayer total: {playerHand.Sum()}");
// We only show one of the dealer's cards until the end
int dealerTotal = getRandomCard();
int dealerHiddenCard = getRandomCard();
Console.WriteLine($"Dealers visible card: {dealerTotal}");
// Start the game
bool play = true;
do
{
// Ask user if they want to hit or stand
Console.WriteLine("Do you want to hit? Press Y or N");
string userChoice = Console.ReadLine().ToUpper();
switch (userChoice)
{
case "Y":
// Get a new card for the user
playerHand.Add(getRandomCard());
Console.WriteLine("Your new total: " + playerHand.Sum());
// Dealer must draw if their total hand (with hidden card) is less than 17
if (dealerTotal + dealerHiddenCard < 17)
{
dealerTotal += getRandomCard();
Console.WriteLine("Dealer's new visible total:" + dealerTotal);
if (dealerTotal + dealerHiddenCard > 21)
{
Console.WriteLine("Dealer busted");
play = false;
}
}
// Check if player busted
if (playerHand.Sum() > 21)
{
// Switch the ace if it will help
for (int i = 0; i < playerHand.Count; i++)
{
if (playerHand[i] == 11)
{
playerHand[i] = 1;
}
}
// Player busts if still over 21
if (playerHand.Sum() > 21)
{
play = false;
Console.WriteLine("Even with the swapped ace you busted!");
}
}
// Check if player got blackjack
else if (playerHand.Sum() == 21)
{
play = false;
}
break;
// Player wants to stand
case "N":
// Dealer still has to draw if their total hand is under 17
if (dealerTotal + dealerHiddenCard < 17)
{
dealerTotal += getRandomCard();
Console.WriteLine(dealerTotal + dealerHiddenCard);
}
play = false;
break;
default:
break;
}
} while (play);
// Score Cases
Console.WriteLine("Your total {0}\nDealer's Total: {1}", playerHand.Sum(), dealerHiddenCard + dealerTotal);
// If player didn't bust and player score is greater than or equal to dealer total
if (playerHand.Sum() >= dealerTotal + dealerHiddenCard && playerHand.Sum() < 22)
{
Console.WriteLine("You win!");
}
// If dealer busted and player did not
else if (dealerHiddenCard + dealerTotal >= 22 && playerHand.Sum() <= 21)
{
Console.WriteLine("You win!");
}
// Else both busted, dealer wins
else
{
Console.WriteLine("Dealer wins");
}
}
public static int getRandomCard()
{
int[] deck = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };
Random rand = new Random();
int card = deck[rand.Next(deck.Length)];
Thread.Sleep(25);
return card;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PADIbookCommonLib
{
public class FriendException : Exception
{
public FriendException(string message) : base(message)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DFrame;
namespace DPYM
{
/// <summary>
/// 产品手册
/// </summary>
public static class PYMMannual
{
/* 获取产品ID */
/// <summary>
/// 通过老鼠类型获取老鼠产品ID
/// </summary>
/// <param name="mouseType"></param>
/// <returns></returns>
public static EUID GetProductID(EMouseType mouseType)
{
return (EUID)mouseType;
}
/// <summary>
/// 通过工具类型获取工具产品ID
/// </summary>
/// <param name="toolType"></param>
/// <returns></returns>
public static EUID GetProductID(EToolType toolType)
{
return (EUID)toolType;
}
/// <summary>
/// 通过元素类型获取元素产品ID
/// </summary>
/// <param name="elementType"></param>
/// <returns></returns>
public static EUID GetProductID(EElementType elementType)
{
return (EUID)elementType;
}
/// <summary>
/// 返回默认值(无效ID)
/// </summary>
/// <returns></returns>
public static EUID GetProductID(int uid)
{
return (EUID)uid;
}
/// <summary>
/// 返回默认值(无效ID)
/// </summary>
/// <returns></returns>
public static EUID GetProductID()
{
return EUID.Uavailable;
}
/// <summary>
/// 通过字符串描述获取产品ID(用于地图读取部分)
/// </summary>
/// <param name="strDescription"></param>
/// <returns></returns>
public static EUID GetProductID(string strDescription)
{
return (EUID)Enum.Parse(typeof(EUID), strDescription);
}
/* 判定产品类型 */
/// <summary>
/// 检测该产品是否合法
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool CheckValid(EUID productID)
{
DLogger.DBGMD("[FATAL] PYMMannual.CheckValid( EUID ) : Not Impemented.");
return false;
}
/// <summary>
/// 检测该产品是否合法
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool CheckValid(int productID)
{
DLogger.DBGMD("[FATAL] PYMMannual.CheckValid( int ) : Not Impemented.");
return false;
}
/// <summary>
/// 是否为工具
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsTool(EUID productID)
{
return
(
(productID >= EUID.Tool_Start && productID <= EUID.Tool_End)
||(productID >= EUID.ToolCustomize_Start && productID <= EUID.ToolCustomize_End)
);
}
/// <summary>
/// 是否为老鼠
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsMouse(EUID productID)
{
return (productID >= EUID.Mouse_Start && productID <= EUID.Mouse_End);
}
/// <summary>
/// 是否为场景元素
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsElement(EUID productID)
{
return (productID >= EUID.ElementType_Start && productID <= EUID.ElementType_End);
}
/// <summary>
/// 是否为可通过元素
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsPassage(EUID productID)
{
return (productID >= EUID.EPassage_Start && productID <= EUID.EPassage_End);
}
/// <summary>
/// 是否为洞穴元素
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsHole(EUID productID)
{
return (productID >= EUID.EHole_Start && productID <= EUID.EHole_End);
}
/// <summary>
/// 是否为背景
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsBackground(EUID productID)
{
return (EUID.Background == productID);
}
/// <summary>
/// 是否为探测范围组件
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsDetectRegion(EUID productID)
{
return (EUID.COMDetectRegion == productID);
}
/// <summary>
/// 是否为影响范围组件
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsAffectRegion(EUID productID)
{
return (EUID.COMAffectRegion == productID);
}
/// <summary>
/// 是否为接受探测范围组件
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsDetectAcceptRegion(EUID productID)
{
return (EUID.COMDetectAcceptRegion == productID);
}
/// <summary>
/// 是否为接受影响范围组件
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsAffectAcceptRegion(EUID productID)
{
return (EUID.COMAffectAcceptRegion == productID);
}
/// <summary>
/// 是否为道具交互范围组件
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsToolInteractRegion(EUID productID)
{
return (EUID.COMToolInteractRegion == productID);
}
/// <summary>
/// 判断是否为技能
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsSkill(EUID productID)
{
return (productID >= EUID.SkillType_Start && productID <= EUID.SkillType_End);
}
/// <summary>
/// 判断是否为控制器
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
public static bool IsController(EUID productID)
{
return (productID >= EUID.ControllerType_Start && productID <= EUID.ControllerType_End);
}
/* 获取产品的字符串描述 */
public static string IDString(EUID uid)
{
return uid.ToString();
}
/* 获取反射类 */
public const string PYMNamespace = "DPYM";
public static Type GetType(EControllerType controller)
{
return Type.GetType(PYMNamespace + "." + controller.ToString() + "Controller", true, false);
}
public static Type GetType(ESkillType skill)
{
return Type.GetType(PYMNamespace + ".SK" + skill.ToString());
}
/* 私有组件 */
}
}
|
using MediatR;
using Schmidt.Template.Common.Abstraction;
using System.Threading.Tasks;
namespace Schmidt.Template.Common.Implementations
{
public class MyMediator : IMyMediator
{
private readonly IMediator _mediator;
public MyMediator(IMediator mediator)
{
_mediator = mediator;
}
public async Task<TResult> SendAsync<TResult>(ICommand<TResult> request)
{
return await _mediator.Send(request, default);
}
public Task SendAsync(ICommand request)
{
return _mediator.Send(request);
}
}
}
|
using SimpleSpace.NonECS;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SimpleSpace.Data
{
[CreateAssetMenu(fileName = "ShipData", menuName = "SimpleSpace/ShipData", order = 1)]
public class ShipData : BasePawnData
{
public SimpleWeaponData Weapon;
}
}
|
namespace Laan.Sql.Parser.Expressions
{
public class StringExpression : Expression
{
public StringExpression( string value, Expression parent ) : base ( parent )
{
Value = value;
}
public override bool CanInline
{
get { return true; }
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StarlightRiver.Abilities;
using System;
using System.Linq;
using Terraria;
using Terraria.DataStructures;
using Terraria.ModLoader;
using Terraria.ObjectData;
namespace StarlightRiver.Tiles.Overgrow
{
class ZapperTile : ModTile
{
public override void SetDefaults()
{
Main.tileLavaDeath[Type] = false;
Main.tileFrameImportant[Type] = true;
TileObjectData.newTile.Width = 5;
TileObjectData.newTile.Height = 2;
TileObjectData.newTile.CoordinateHeights = new int[] { 16, 16 };
TileObjectData.newTile.UsesCustomCanPlace = true;
TileObjectData.newTile.CoordinateWidth = 16;
TileObjectData.newTile.CoordinatePadding = 2;
TileObjectData.newTile.Origin = new Point16(0, 0);
TileObjectData.addTile(Type);
ModTranslation name = CreateMapEntryName();
name.SetDefault("");//Map name
AddMapEntry(new Color(0, 0, 0), name);
dustType = ModContent.DustType<Dusts.Gold2>();
disableSmartCursor = true;
}
public override void NearbyEffects(int i, int j, bool closer)
{
if(Main.tile[i,j].frameX == 0 && Main.tile[i, j].frameY == 0)
{
if(!(Main.projectile.Any(proj => proj.modProjectile is Projectiles.Zapper && (proj.modProjectile as Projectiles.Zapper).parent == Main.tile[i,j] && proj.active)))
{
int proj = Projectile.NewProjectile(new Vector2(i + 2,j + 2) * 16, Vector2.Zero, ModContent.ProjectileType<Projectiles.Zapper>(), 1, 1);
(Main.projectile[proj].modProjectile as Projectiles.Zapper).parent = Main.tile[i, j];
}
}
}
}
} |
using System;
using System.Threading.Tasks;
namespace OnboardingSIGDB1.Domain.Interfaces.Services
{
public interface IVinculacaoFuncionarioCargosService
{
Task Vincular(long funcionarioId, long cargoId, DateTime dataVinculacao);
}
}
|
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace WorkerServiceTest
{
public class Worker : BackgroundService
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public static Process getForegroundProcess()
{
uint processID = 0;
IntPtr hWnd = GetForegroundWindow(); // Get foreground window handle
uint threadID = GetWindowThreadProcessId(hWnd, out processID); // Get PID from window handle
Process fgProc = Process.GetProcessById(Convert.ToInt32(processID)); // Get it as a C# obj.
// NOTE: In some rare cases ProcessID will be NULL. Handle this how you want.
return fgProc;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
getForegroundProcess();
DateTime localDate = DateTime.Now;
Console.WriteLine(localDate);
string userID = Environment.UserName;
Console.WriteLine(userID);
//This runs once then exits.
Process[] processlist = Process.GetProcesses();
List<string> runningProcesses = new List<string>();
int numberOfProcesses = processlist.Length;
for(int i = 0; i < numberOfProcesses; i++)
{
if(processlist[i].MainWindowTitle.Length > 1)
{
string title = processlist[i].MainWindowTitle;
runningProcesses.Add(title);
}
}
Filter filter = new Filter();
filter.readData(runningProcesses, numberOfProcesses);
//Gives a list of every single process running on the taskbar
foreach (Process theprocess in processlist)
{
if (theprocess.MainWindowTitle.Length > 1)
{
string currentProcess = theprocess.ToString();
string running = runningProcesses.ToString();
//Check if theprocess is in the runningProcesses
if(running.Contains(currentProcess))
{
Console.WriteLine("Found a match");
} else if(running.Contains(currentProcess) == false)
{
Console.WriteLine("Adding now!");
runningProcesses.Add(theprocess.MainWindowTitle);
}
//Save the titles into strings and if the strings are different/any new ones append it.
//This prevents the same name from repeating over and over
File.AppendAllText("Test.txt" , theprocess.MainWindowTitle + localDate);
File.AppendAllText("Test.txt", "\n");
}
}
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
Console.WriteLine("Test");
await Task.Delay(1000, stoppingToken);
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Phenix.Test.使用指南._11._3._2._6
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("本程序为{0}位,请确认所连数据库客户端引擎是否与之匹配?(如不匹配可调整本程序的'平台目标'生成类型)", Environment.Is64BitProcess ? "64" : "32");
Console.WriteLine("请通过检索“//*”了解代码中的特殊处理");
Console.WriteLine("本案例中表结构未设置中文友好名,可通过数据库字典相关的Comments内容来自动设置上");
Console.WriteLine("测试过程中的日志保存在:" + Phenix.Core.AppConfig.TempDirectory);
Console.WriteLine("因需要初始化本地配置数据,第一次运行会比正常情况下稍慢,请耐心等待");
Console.WriteLine();
Console.WriteLine("设为调试状态");
Phenix.Core.AppConfig.Debugging = true;
Console.WriteLine();
Console.WriteLine("模拟登陆");
Phenix.Business.Security.UserPrincipal.User = Phenix.Business.Security.UserPrincipal.CreateTester();
Phenix.Services.Client.Library.Registration.RegisterEmbeddedWorker(false);
Console.WriteLine();
const string test = "test.11.3.2.6";
Console.WriteLine("**** 搭建测试环境 ****");
UserList users = UserList.Fetch();
Console.WriteLine("Fetch全景User集合对象,业务对象数:" + users.Count);
Console.WriteLine();
Console.WriteLine("**** 测试按条件表达式过滤出业务对象集合功能 ****");
Console.WriteLine();
UserList usersA = users.Filter(p => p.Usernumber == Phenix.Core.Security.UserIdentity.AdminUserNumber);
Console.WriteLine(usersA.Count == 1 ? "从业务对象集合中Filter出AdminUser对象A:ID=" + usersA[0].US_ID + ",Name=" + usersA[0].Name + " ok" : "未能从业务对象集合Filter出AdminUser对象 error");
UserList usersB = users.Filter(p => p.Usernumber == Phenix.Core.Security.UserIdentity.AdminUserNumber);
Console.WriteLine(usersB.Count == 1 ? "从业务对象集合中Filter出AdminUser对象B:ID=" + usersB[0].US_ID + ",Name=" + usersB[0].Name + " ok" : "未能从业务对象集合Filter出AdminUser对象 error");
usersA[0].Name = test;
Console.WriteLine(usersA[0].Name != usersB[0].Name ? "对象A和对象B是不同的对象 ok" : "对象A和对象B指向了同一个内存 error");
Console.WriteLine();
List<User> userList = new List<User>(users);
UserList usersC = UserList.Filter(userList, p => p.Usernumber == Phenix.Core.Security.UserIdentity.AdminUserNumber);
Console.WriteLine(usersC.Count == 1 ? "从IEnumerable<TBusiness>中Filter出AdminUser对象C:ID=" + usersC[0].US_ID + ",Name=" + usersC[0].Name + " ok" : "未能从IEnumerable<TBusiness>中Filter出AdminUser对象 error");
UserList usersD = UserList.Filter(userList, p => p.Usernumber == Phenix.Core.Security.UserIdentity.AdminUserNumber);
Console.WriteLine(usersD.Count == 1 ? "从IEnumerable<TBusiness>中Filter出AdminUser对象D:ID=" + usersD[0].US_ID + ",Name=" + usersD[0].Name + " ok" : "未能从IEnumerable<TBusiness>中Filter出AdminUser对象 error");
usersC[0].Name = test;
Console.WriteLine(usersC[0].Name != usersD[0].Name ? "对象C和对象D是不同的对象 ok" : "对象C和对象D指向了同一个内存 error");
Console.WriteLine();
Console.WriteLine("结束, 与数据库交互细节见日志");
Console.ReadLine();
}
}
}
|
using NfePlusAlpha.Application.ViewModels.ViewModel;
using NfePlusAlpha.Infra.Data.Retorno;
using NfePlusAlpha.UI.Wpf.Apoio.Controles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace NfePlusAlpha.UI.Wpf.Views.Gerenciamentos
{
/// <summary>
/// Interaction logic for winNFeProdutos.xaml
/// </summary>
public partial class winNFeProdutos : NfePlusAlphaWindow
{
public NotaFiscalEletronicaItemViewModel objItemViewModel;
public bool blnNovoItem { get; private set; }
public bool blnSalvou { get; private set; }
#region CONSTRUTOR
public winNFeProdutos(int intNumeroItem, int intCRT)
{
InitializeComponent();
this.objItemViewModel = new NotaFiscalEletronicaItemViewModel { nfi_item = intNumeroItem, intCRT = intCRT };
this.blnNovoItem = true;
this.blnSalvou = false;
}
public winNFeProdutos(NotaFiscalEletronicaItemViewModel objItem)
{
InitializeComponent();
this.objItemViewModel = objItem;
this.blnNovoItem = false;
this.blnSalvou = false;
}
#endregion
#region EVENTOS TELA
private void NfePlusAlphaWindow_Loaded(object sender, RoutedEventArgs e)
{
this.LayoutRoot.DataContext = this.objItemViewModel;
txtCodigoProduto.SelectAll();
txtCodigoProduto.Focus();
}
private void txtCodigoProduto_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var objText = (TextBox)sender;
int intCodigoProduto = 0;
if (int.TryParse(objText.Text, out intCodigoProduto) && intCodigoProduto > 0)
{
string strMensagem = string.Empty;
this.BuscaProduto(intCodigoProduto, out strMensagem);
}
}
}
private void btnBuscarProduto_Click(object sender, RoutedEventArgs e)
{
NFePlusAlphaPesquisa winBuscar = new NFePlusAlphaPesquisa("Produto");
winBuscar.enTipoBusca = enTipoPesquisa.Produto;
winBuscar.Owner = this;
winBuscar.ShowDialog();
if (winBuscar.objRetorno != null)
{
int intCodigoProduto = 0;
var objButton = (Button)sender;
if (int.TryParse(winBuscar.objRetorno.ToString(), out intCodigoProduto))
{
string strMensagem = string.Empty;
this.BuscaProduto(intCodigoProduto, out strMensagem);
if (!string.IsNullOrEmpty(strMensagem))
MessageBox.Show(strMensagem, "AVISO", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private void btnSair_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnSalvar_Click(object sender, RoutedEventArgs e)
{
this.blnSalvou = true;
this.Close();
}
#endregion
#region METODOS
private void BuscaProduto(int intCodigoProduto, out string strMensagem)
{
strMensagem = string.Empty;
if (!this.objItemViewModel.ObterProdutoPorCodigo(intCodigoProduto, out strMensagem))
{
if (!string.IsNullOrEmpty(strMensagem))
MessageBox.Show(strMensagem, "AVISO", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using API.Model;
using API.BL;
namespace coucheAPI.Controllers
{
[Route("api/[controller]")]
public class ForumDiscussionController : Controller
{
[HttpGet]
public List<Discussion> Get(int id)
{
return BL_Api.GetForumDiscussionMessage(id);
}
[HttpPost]
public void Post(Discussion d)
{
//BL_Api.PostForumDiscussionMessage(d);
}
}
}
|
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;
using System.IO;
using Newtonsoft.Json;
namespace VerifySign
{
public partial class SignatureDatabaseForm : Form
{
public SignatureDatabase sigDb = null;
public List<SignatureReference> sigRefList = new List<SignatureReference>();
public static string sigRefPath = Properties.Settings.Default.SignatureDatabase;
public SignatureDatabaseForm()
{
InitializeComponent();
}
private ListViewItem CreateListViewItem(SignatureReference sigRef)
{
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(sigRef.Name);
lvi.SubItems.Add(sigRef.Email);
if(sigRef.SigText != null && sigRef.SigText.Length > 50)
{
lvi.SubItems.Add(sigRef.SigText.Substring(0, 50) + "...");
}
else
{
lvi.SubItems.Add(" ");
}
return lvi;
}
private void LoadListView(List<SignatureReference> sigRefList)
{
if (sigRefList == null) return;
foreach(SignatureReference sigRef in sigRefList)
{
listView1.Items.Add(CreateListViewItem(sigRef));
}
}
public static SignatureDatabase LoadSignatureDatabase(string path)
{
if (CreateSigRefJsonFileIfNotExist() == false) return null;
try
{
StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
reader.Dispose();
SignatureDatabase db = JsonConvert.DeserializeObject<SignatureDatabase>(json);
return db;
}
catch(Exception ex)
{
MessageBox.Show("Unable to load signature database from " + path + "." + Environment.NewLine + ex.Message);
return null;
}
}
private static bool CreateSigRefJsonFileIfNotExist()
{
if (File.Exists(sigRefPath)) return true;
try
{
FileStream fs = File.Create(sigRefPath);
fs.Flush();
fs.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show("Unable to create signature database at " + sigRefPath + "." + Environment.NewLine + ex.Message);
return false;
}
}
private void UpdateListView(SignatureReference sig)
{
foreach(ListViewItem lvi in listView1.Items)
{
if(lvi.SubItems[0].Text == sig.Name && lvi.SubItems[1].Text == sig.Email)
{
lvi.SubItems[2].Text = sig.SigText;
return;
}
}
}
private void InsertIntoListView(SignatureReference sig)
{
listView1.Items.Add(CreateListViewItem(sig));
}
private bool SerializeSigRefListToFile()
{
try
{
sigDb.List = sigRefList.ToArray();
string json = JsonConvert.SerializeObject(sigDb, Formatting.Indented);
StreamWriter sw = new StreamWriter(sigRefPath, false, Encoding.UTF8);
sw.Write(json);
sw.Flush();
sw.Close();
return true;
}
catch(Exception ex)
{
MessageBox.Show("Unable to save signature list" + Environment.NewLine + ex.Message);
return false;
}
}
private bool SaveSignature(string name, string email, string sigText)
{
foreach (SignatureReference sigRef in sigRefList)
{
if (sigRef.Name == name && sigRef.Email == email)
{
sigRef.SigText = sigText;
if (SerializeSigRefListToFile())
{
UpdateListView(sigRef);
listView1.Refresh();
return true;
}
else
{
return false;
}
}
}
SignatureReference sig = new SignatureReference();
sig.Name = name;
sig.Email = email;
sig.SigText = sigText;
sigRefList.Add(sig);
if (SerializeSigRefListToFile())
{
InsertIntoListView(sig);
listView1.Refresh();
return true;
}
else
{
return false;
}
}
private bool CheckSignatureExist(string name, string email)
{
foreach(SignatureReference sigRef in sigRefList)
{
if(sigRef.Name == name && sigRef.Email == email)
{
return true;
}
}
return false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
SignatureCollectorForm collector = new SignatureCollectorForm();
collector.SignatureExistDelegate = CheckSignatureExist;
collector.SaveSignatureDelegate = SaveSignature;
collector.ShowDialog();
}
private void SignatureDatabaseForm_Load(object sender, EventArgs e)
{
sigDb = LoadSignatureDatabase(sigRefPath);
if (sigDb != null)
{
sigRefList = sigDb.List.ToList();
}
else
{
sigDb = new SignatureDatabase();
sigRefList = new List<SignatureReference>();
}
LoadListView(sigRefList);
}
private void listView1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
{
if (listView1.SelectedItems.Count > 0)
{
int selIndex = listView1.SelectedItems[0].Index;
sigRefList.RemoveAt(selIndex);
listView1.Items.RemoveAt(selIndex);
listView1.Refresh();
}
}
else if(e.KeyCode == Keys.Enter)
{
if(listView1.SelectedItems.Count > 0)
{
SignatureReference sigRef = sigRefList[listView1.SelectedItems[0].Index];
SignatureCollectorForm collector = new SignatureCollectorForm();
collector.SignatureExistDelegate = CheckSignatureExist;
collector.SaveSignatureDelegate = SaveSignature;
collector.ShowDialog(sigRef);
}
}
}
private void SignatureDatabaseForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.Owner == null) return;
if(this.Owner.GetType() == typeof(PDFViewer))
{
((PDFViewer)Owner).updateSigDb(sigDb);
}
}
}
}
|
namespace KBEngine
{
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/*
实体的Mailbox
关于Mailbox请参考API手册中对它的描述
https://github.com/kbengine/kbengine/tree/master/docs/api
*/
public class EntityMailbox
{
// Mailbox的类别
public enum MAILBOX_TYPE
{
MAILBOX_TYPE_CELL = 0, // CELL_MAILBOX
MAILBOX_TYPE_BASE = 1 // BASE_MAILBOX
}
public Int32 id = 0;
public string className = "";
public MAILBOX_TYPE type = MAILBOX_TYPE.MAILBOX_TYPE_CELL;
public Bundle bundle = null;
public EntityMailbox()
{
}
public virtual void __init__()
{
}
public virtual bool isBase()
{
return type == MAILBOX_TYPE.MAILBOX_TYPE_BASE;
}
public virtual bool isCell()
{
return type == MAILBOX_TYPE.MAILBOX_TYPE_CELL;
}
/*
创建新的mail
*/
public Bundle newMail()
{
if(bundle == null)
bundle = Bundle.createObject();
if(isCell())
bundle.newMessage(Messages.messages["Baseapp_onRemoteCallCellMethodFromClient"]);
else
bundle.newMessage(Messages.messages["Base_onRemoteMethodCall"]);
bundle.writeInt32(this.id);
return bundle;
}
/*
向服务端发送这个mail
*/
public void postMail(Bundle inbundle)
{
if(inbundle == null)
inbundle = bundle;
inbundle.send(KBEngineApp.app.networkInterface());
if(inbundle == bundle)
bundle = null;
}
public Bundle newMail(string methodName)
{
if(KBEngineApp.app.currserver == "loginapp")
{
Dbg.ERROR_MSG(className + "::newMail(" + methodName + "), currserver=!" + KBEngineApp.app.currserver);
return null;
}
ScriptModule module = null;
if(!EntityDef.moduledefs.TryGetValue(className, out module))
{
Dbg.ERROR_MSG(className + "::newMail: entity-module(" + className + ") error, can not find from EntityDef.moduledefs");
return null;
}
Method method = null;
if(isCell())
{
method = module.cell_methods[methodName];
}
else
{
method = module.base_methods[methodName];
}
UInt16 methodID = method.methodUtype;
newMail();
bundle.writeUint16(methodID);
return bundle;
}
}
}
|
using ProgFrog.Interface.Model;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ProgFrog.Interface.Data
{
public interface IProgrammingTaskRepository
{
Task<IEnumerable<ProgrammingTask>> GetAll();
Task<ProgrammingTask> Create(ProgrammingTask task);
Task<ProgrammingTask> GetById(IIdentifier identifier);
}
}
|
using ServiceDesk.Infrastructure;
using ServiceDesk.Ticketing.CommandStack.Commands;
using ServiceDesk.Ticketing.Domain.CategoryAggregate;
using ServiceDesk.Ticketing.Domain.TicketAggregate;
using ServiceDesk.Ticketing.Domain.UserAggregate;
namespace ServiceDesk.Ticketing.CommandStack.Handlers
{
public class CreateTicketCommandHandler : IMessageHandler<CreateTicketCommand>
{
private readonly IBus _bus;
private readonly ITicketRepository _ticketRepository;
private readonly IUserRepository _userRepository;
private readonly ICategoryRepository _categoryRepository;
public CreateTicketCommandHandler(IBus bus, ITicketRepository ticketRepository, IUserRepository userRepository, ICategoryRepository categoryRepository)
{
_ticketRepository = ticketRepository;
_userRepository = userRepository;
_categoryRepository = categoryRepository;
_bus = bus;
}
public void Handle(CreateTicketCommand message)
{
User requestor = _userRepository.GetByLoginName(message.RequestorLoginName);
User assignedTo = _userRepository.GetByLoginName(message.AssignedToLoginName);
Category category = _categoryRepository.GetByName(message.Category);
var ticket = new Ticket(message.Title, message.Description, (TicketStatus)message.Status, (TicketPriority)message.Priority, (TicketType)message.Type,
message.DueDate, message.ResolutionComments, requestor, assignedTo, category);
_ticketRepository.Add(ticket);
}
}
}
|
using System;
using SyslogLogging;
using WatsonWebserver;
namespace Uscale.Classes
{
/// <summary>
/// Metadata about connection from a client.
/// </summary>
public class Connection
{
#region Public-Members
/// <summary>
/// Thread ID.
/// </summary>
public int ThreadId { get; set; }
/// <summary>
/// Client's IP address.
/// </summary>
public string SourceIp { get; set; }
/// <summary>
/// Client's port number.
/// </summary>
public int SourcePort { get; set; }
/// <summary>
/// HTTP method.
/// </summary>
public HttpMethod Method { get; set; }
/// <summary>
/// Raw URL.
/// </summary>
public string RawUrl { get; set; }
/// <summary>
/// Hostname being accessed.
/// </summary>
public string HostName { get; set; }
/// <summary>
/// HTTP hostname as specified in the header.
/// </summary>
public string HttpHostName { get; set; }
/// <summary>
/// Name of the node to which this client is connected.
/// </summary>
public string NodeName { get; set; }
/// <summary>
/// Start time for the connection.
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// End time for the connection.
/// </summary>
public DateTime? EndTime { get; set; }
#endregion
#region Private-Members
#endregion
#region Constructors-and-Factories
/// <summary>
/// Instantiate the object.
/// </summary>
public Connection()
{
}
#endregion
#region Public-Methods
#endregion
#region Private-Methods
#endregion
}
}
|
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del adaptador de Flujo Aprobacion
/// </summary>
public sealed class FlujoAprobacionParticipanteAdapter
{
/// <summary>
/// Realiza la adaptación de campos para registrar o actualizar
/// </summary>
/// <param name="data">Datos a registrar o actualizar</param>
/// <returns>Entidad Datos a registrar</returns>
public static FlujoAprobacionParticipanteEntity RegistrarFlujoAprobacionParticipante(FlujoAprobacionParticipanteRequest data)
{
FlujoAprobacionParticipanteEntity flujoAprobacionParticipanteEntity = new FlujoAprobacionParticipanteEntity();
if (data.CodigoFlujoAprobacionParticipante != null)
{
flujoAprobacionParticipanteEntity.CodigoFlujoAprobacionParticipante = new Guid(data.CodigoFlujoAprobacionParticipante);
}
else
{
Guid code;
code = Guid.NewGuid();
flujoAprobacionParticipanteEntity.CodigoFlujoAprobacionParticipante = code;
}
flujoAprobacionParticipanteEntity.CodigoFlujoAprobacionEstadio = new Guid(data.CodigoFlujoAprobacionEstadio);
flujoAprobacionParticipanteEntity.CodigoTrabajador = new Guid(data.CodigoTrabajador);
flujoAprobacionParticipanteEntity.CodigoTipoParticipante = data.CodigoTipoParticipante;
flujoAprobacionParticipanteEntity.EstadoRegistro = data.EstadoRegistro;
flujoAprobacionParticipanteEntity.CodigoTrabajadorOriginal = flujoAprobacionParticipanteEntity.CodigoTrabajador;
return flujoAprobacionParticipanteEntity;
}
/// <summary>
/// Realiza la adaptación de campos para listar de logic a response
/// </summary>
/// <param name="data">Datos a listar</param>
/// <returns>Entidad Datos a registrar</returns>
public static FlujoAprobacionParticipanteResponse ObtenerFlujoAprobacionParticipanteResponse(FlujoAprobacionParticipanteLogic data)
{
FlujoAprobacionParticipanteResponse flujoAprobacionParticipanteResponse = new FlujoAprobacionParticipanteResponse();
flujoAprobacionParticipanteResponse.CodigoFlujoAprobacionEstadio = data.CodigoFlujoAprobacionEstadio.ToString();
flujoAprobacionParticipanteResponse.CodigoTrabajador = data.CodigoTrabajador;
flujoAprobacionParticipanteResponse.CodigoTipoParticipante = data.CodigoTipoParticipante;
flujoAprobacionParticipanteResponse.OrdenFirmante = data.OrdenFirmante;
flujoAprobacionParticipanteResponse.IndicadorEsFirmante = data.IndicadorEsFirmante;
return flujoAprobacionParticipanteResponse;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemController : MonoBehaviour {
PlayerInventoryController inventoryController;
// Use this for initialization
void Start () {
inventoryController = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerInventoryController> ();
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Player") {
inventoryController.AddItem (gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Product.Dto.TravelSearch
{
public class PolicyExceptionDetails
{
public bool InPolicy { get; set; }
public object PriceDifference { get; set; }
public bool MultipleCheapestOptions { get; set; }
public object MinimumTimeOfCheapestOption { get; set; }
public object MaximumTimeOfCheapestOption { get; set; }
public string NameOfCheapestOption { get; set; }
public object PriceOfCheapestOption { get; set; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SampleApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SampleApp")]
[assembly: AssemblyCopyright("Copyright Richasy © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
|
using Assets.Scripts.Ui;
#if FACEBOOK
using Facebook.Unity;
#endif
using UnityEngine;
namespace Assets.Scripts.UI.Dialogs
{
public class FbDialog : View
{
public GameObject FbLoginButton;
public GameObject FbLogOutButton;
public GameObject InviteFriendsButton;
public GameObject InviteFriendsWithCustomImageButton;
public GameObject RequestFriendsButton;
public GameObject AddfriendsRewardObject;
public override void Init(GameManager gameManager)
{
base.Init(gameManager);
UIEventListener.Get(FbLoginButton).onClick += OnLoginClick;
UIEventListener.Get(FbLogOutButton).onClick += OnLogOutClick;
UIEventListener.Get(InviteFriendsButton).onClick += OnInviteFriendsClick;
UIEventListener.Get(InviteFriendsWithCustomImageButton).onClick += OnInviteFriendsWithImageClick;
UIEventListener.Get(RequestFriendsButton).onClick += OnRequestClick;
}
public override void Show()
{
base.Show();
#if FACEBOOK
FbLoginButton.SetActive(!FB.IsLoggedIn);
AddfriendsRewardObject.SetActive(PlayerPrefs.GetInt("is_add_friends", 0) == 0);
#endif
}
private void OnInviteFriendsClick(GameObject go)
{
#if FACEBOOK
FbManager.InviteFriends();
#endif
}
private void OnInviteFriendsWithImageClick(GameObject go)
{
#if FACEBOOK
FbManager.InviteFriendsWithCustomImage();
#endif
}
private void OnRequestClick(GameObject go)
{
#if FACEBOOK
if (FB.IsLoggedIn)
{
FbManager.InviteFriendsRequest(result =>
{
if (!string.IsNullOrEmpty(result.RawResult))
{
if (PlayerPrefs.GetInt("is_add_friends", 0) == 0)
{
CurrencyManager.AddCurrency(100);
PlayerPrefs.SetInt("is_add_friends", 1);
AddfriendsRewardObject.SetActive(false);
}
}
});
}
else
{
FbManager.Login();
}
#endif
}
private void OnLogOutClick(GameObject go)
{
#if FACEBOOK
FbManager.LogOut();
#endif
}
private void OnLoginClick(GameObject go)
{
#if FACEBOOK
FbManager.Login();
#endif
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using FontAwesome5.Extensions;
namespace FontAwesome5.WinUI.Example.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
AllIcons = Enum.GetValues(typeof(EFontAwesomeIcon)).Cast<EFontAwesomeIcon>()
.OrderBy(i => i.GetStyle()).ThenBy(i => i.GetLabel()).ToList();
AllIcons.Remove(EFontAwesomeIcon.None);
SelectedIcon = AllIcons.First();
FlipOrientations = Enum.GetValues(typeof(EFlipOrientation)).Cast<EFlipOrientation>().ToList();
SpinDuration = 5;
PulseDuration = 5;
FontSize = 30;
Rotation = 0;
}
private EFontAwesomeIcon _selectedIcon;
public EFontAwesomeIcon SelectedIcon
{
get => _selectedIcon;
set
{
_selectedIcon = value;
RaisePropertyChanged(nameof(SelectedIcon));
RaisePropertyChanged(nameof(FontText));
}
}
private bool _spinIsEnabled;
public bool SpinIsEnabled
{
get => _spinIsEnabled;
set
{
_spinIsEnabled = value;
RaisePropertyChanged(nameof(SpinIsEnabled));
RaisePropertyChanged(nameof(FontText));
}
}
private double _spinDuration;
public double SpinDuration
{
get => _spinDuration;
set
{
_spinDuration = value;
RaisePropertyChanged(nameof(SpinDuration));
RaisePropertyChanged(nameof(FontText));
}
}
private bool _pulseIsEnabled;
public bool PulseIsEnabled
{
get => _pulseIsEnabled;
set
{
_pulseIsEnabled = value;
RaisePropertyChanged(nameof(PulseIsEnabled));
RaisePropertyChanged(nameof(FontText));
}
}
private double _pulseDuration;
public double PulseDuration
{
get => _pulseDuration;
set
{
_pulseDuration = value;
RaisePropertyChanged(nameof(PulseDuration));
RaisePropertyChanged(nameof(FontText));
}
}
private EFlipOrientation _flipOrientation;
public EFlipOrientation FlipOrientation
{
get => _flipOrientation;
set
{
_flipOrientation = value;
RaisePropertyChanged(nameof(FlipOrientation));
RaisePropertyChanged(nameof(FontText));
}
}
private double _fontSize;
public double FontSize
{
get => _fontSize;
set
{
_fontSize = value;
RaisePropertyChanged(nameof(FontSize));
RaisePropertyChanged(nameof(FontText));
}
}
private double _rotation;
public double Rotation
{
get => _rotation;
set
{
_rotation = value;
RaisePropertyChanged(nameof(Rotation));
RaisePropertyChanged(nameof(FontText));
}
}
public List<EFlipOrientation> FlipOrientations { get; set; } = new List<EFlipOrientation>();
public List<EFontAwesomeIcon> AllIcons { get; set; } = new List<EFontAwesomeIcon>();
public string FontText => $"<fa5:FontAwesome Icon=\"{SelectedIcon}\" Fontsize=\"{FontSize}\" Spin=\"{SpinIsEnabled}\" " +
$"SpinDuration=\"{SpinDuration}\" Pulse=\"{PulseIsEnabled}\" PulseDuration=\"{PulseDuration}\" FlipOrientation=\"{FlipOrientation}\" Rotation=\"{Rotation}\" >";
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
using E_LEARNING.Repo;
using E_LEARNING.Repository;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace E_LEARNING.Controllers
{
public class FormationnController : Controller
{
private readonly IRepoformation _repo;
public FormationnController(IRepoformation repo)
{
_repo = repo;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.