text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace DataLayer.Conexion
{
public interface IOperacionesConexion
{
/// <summary>
/// Obtiene o establece el comando y la conexión de base de datos que se utilizan para rellenar System.Data.DataSet y actualizar el origen de datos.
/// </summary>
SqlDataAdapter propSqlDatAdapt { get; set; }
/// <summary>
/// Obtiene o establece el modo de lectura de una secuencia de filas de datos sólo avance de un origen de datos.
/// </summary>
SqlDataReader propSqlDatRead { get; set; }
/// <summary>
/// Obtiene o establece un comando SQL que se va a ejecutar en un origen de datos.
/// </summary>
SqlCommand propSqlCmd { get; set; }
/// <summary>
/// Obtiene o establece la cadena de conexión
/// </summary>
String cadenaConexion { get; set; }
/// <summary>
/// Asigna el nombre del procedimiento y sus parámetros a la propiedad propAccessCmd.
/// </summary>
/// <remarks>Si el procedimiento no requiere parámetros se envía null en su lugar.</remarks>
/// <param name="nombreStoreProcedure">Nombre del procedimiento</param>
/// <param name="parametros">Parámetros del procedimiento.</param>
/// <returns>System.Boolean.</returns>
bool FnAsignarStoreProcedureYParametros(string nombreStoreProcedure, SqlParameter[] parametros);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities.RelationTables;
namespace Voronov.Nsudotnet.BuildingCompanyIS.Entities
{
[Table("bcis.Vehicles")]
public partial class Vehicle : IEntity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors"
)]
public Vehicle()
{
VehicleJournal = new HashSet<VehicleJournal>();
}
public int Id { get; set; }
public int? VehicleCategoryId { get; set; }
public int? OrganizationUnitId { get; set; }
[Required]
[StringLength(30)]
public string ModelName { get; set; }
[Required]
[StringLength(30)]
public string VehicleManufacturer { get; set; }
[Required]
[StringLength(100)]
[Index("IX_SerialNumber", IsUnique = true)]
public string SerialNumber { get; set; }
public virtual OrganizationUnit OrganizationUnit { get; set; }
public virtual VehicleCategory VehicleCategory { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<VehicleJournal> VehicleJournal { get; set; }
public virtual ICollection<VehicleAttributeValue> VehicleAttributeValues { get; set; }
}
} |
using System;
using ServiceDesk.Core.Entities.RequestSystem;
using ServiceDesk.Core.Interfaces.Common;
using ServiceDesk.Core.Interfaces.Factories.RequestSystem;
namespace ServiceDesk.Infrastructure.Implementations.Factories.RequestSystem
{
public class RequestAttachmentData : IFactoryData
{
public string RealName { get; set; }
public string UnicalName { get; set; }
public string SizeMb { get; set; }
public string FilePath { get; set; }
public Guid RequestId { get; set; }
public string Reference { get; set; }
}
public class RequestAttachmentFactory : IRequestAttachmentFactory<RequestAttachmentData>
{
public RequestAttachment Create(RequestAttachmentData data)
{
var requestAttachment = new RequestAttachment()
{
RealName = data.RealName,
UnicalName = data.UnicalName,
SizeMb = data.SizeMb,
FilePath = data.FilePath,
RequestId = data.RequestId,
Reference = data.Reference
};
return requestAttachment;
}
}
}
|
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 restapi3
{
public partial class NewCar : Form
{
public Form1 ParentForm { get; set; }
public NewCar(Form1 parent)
{
this.InitializeComponent();
ParentForm = parent;
}
private void btn_send_Click(object sender, EventArgs e)
=> ParentForm.AddCar(txt_licensePlate.Text, txt_make.Text, txt_model.Text, txt_kw.Text, txt_km.Text, txt_ccm.Text, checkBox1.Checked, txt_pricePerHour.Text, txt_pricePerKilometer.Text, txt_category.Text, txt_type.Text, txt_status.Text);
}
}
|
using UnityEngine;
using System.Collections;
public class Instructions : MonoBehaviour {
public bool autoPlay = false;
Transform panel;
int index = 0;
void Start() {
panel = transform.FindChild("ParentPanel");
if (autoPlay) {
StartCoroutine("AutoPlay");
}
}
public void next() {
if (index < panel.childCount - 1) {
index++;
showPanel();
}
}
public void prev() {
if (index > 0) {
index--;
showPanel();
}
}
private void showPanel() {
foreach (Transform child in panel) {
child.gameObject.SetActive(false);
}
panel.GetChild(index).gameObject.SetActive(true);
}
IEnumerator AutoPlay() {
yield return new WaitForSeconds(2);
next();
StartCoroutine("AutoPlay");
}
}
|
using System;
using System.Runtime.Serialization;
namespace OmniSharp.Extensions.JsonRpc.Server
{
/// <summary>
/// Exception raised when an LSP request is made for a method not supported by the remote process.
/// </summary>
[Serializable]
public class MethodNotSupportedException
: RequestException
{
/// <summary>
/// Create a new <see cref="MethodNotSupportedException" />.
/// </summary>
/// <param name="requestId">
/// The LSP / JSON-RPC request Id (if known).
/// </param>
/// <param name="method">
/// The name of the target method.
/// </param>
public MethodNotSupportedException(object? requestId, string? method)
: base(ErrorCodes.MethodNotSupported, requestId, $"Method not found: '{method}'.") =>
Method = !string.IsNullOrWhiteSpace(method) ? method! : "(unknown)";
/// <summary>
/// Serialisation constructor.
/// </summary>
/// <param name="info">
/// The serialisation data-store.
/// </param>
/// <param name="context">
/// The serialisation streaming context.
/// </param>
protected MethodNotSupportedException(SerializationInfo info, StreamingContext context)
: base(info, context) =>
Method = info.GetString("Method");
/// <summary>
/// Get exception data for serialisation.
/// </summary>
/// <param name="info">
/// The serialisation data-store.
/// </param>
/// <param name="context">
/// The serialisation streaming context.
/// </param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Method", Method);
}
/// <summary>
/// The name of the method that was not supported by the remote process.
/// </summary>
public string Method { get; }
}
}
|
using KPI.Model.DAO;
using KPI.Model.ViewModel;
using MvcBreadCrumbs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace KPI.Web.Controllers
{
[BreadCrumb(Clear = true)]
public class OCCategoriesController : BaseController
{
OCCategoryDAO _dao;
public OCCategoriesController()
{
_dao = new OCCategoryDAO();
}
// GET: CategoryKPILevelAdmin
[BreadCrumb(Clear = true)]
public ActionResult Index()
{
BreadCrumb.Add(Url.Action("Index", "Home"), "Home");
BreadCrumb.SetLabel("OC Category");
var user = (UserProfileVM)Session["UserProfile"];
if (user.User.Permission == 1)
{
return View();
}
else
{
return Redirect("~/Error/NotFound");
}
}
public async Task<JsonResult> AddOCCategory(int OCID, int CategoryID)
{
return Json(await _dao.AddOCCategory(OCID, CategoryID), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> GetCategoryByOC(int page, int pageSize, int level, int ocID)
{
return Json(await _dao.GetCategoryByOC(page, pageSize, level, ocID), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> GetListTree()
{
return Json(await _dao.GetListTree(), JsonRequestBehavior.AllowGet);
}
}
} |
using CloneDeploy_Entities.DTOs.ImageSchemaBE;
namespace CloneDeploy_Entities.DTOs
{
public class MulticastArgsDTO
{
public string clientCount { get; set; }
public string Environment { get; set; }
public string ExtraArgs { get; set; }
public string groupName { get; set; }
public string ImageName { get; set; }
public string Port { get; set; }
public ImageSchema schema { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using TestApplicationDomain.Entities;
namespace TestApplicationInterface.Repository
{
public interface IPricingRepository : IRepository<Pricing>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace NetFabric.Hyperlinq
{
public static partial class AsyncEnumerableExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static AsyncValueEnumerableWrapper<TSource> AsAsyncValueEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
=> new(source);
[GeneratorIgnore] // TODO: to be removed
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static AsyncValueEnumerableWrapper<TEnumerable, TEnumerator, TSource> AsAsyncValueEnumerable<TEnumerable, TEnumerator, TSource>(this TEnumerable source, Func<TEnumerable, CancellationToken, TEnumerator> getAsyncEnumerator)
where TEnumerable : IAsyncEnumerable<TSource>
where TEnumerator : struct, IAsyncEnumerator<TSource>
=> new(source, getAsyncEnumerator);
public readonly partial struct AsyncValueEnumerableWrapper<TEnumerable, TEnumerator, TSource>
: IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerable : IAsyncEnumerable<TSource>
where TEnumerator : struct, IAsyncEnumerator<TSource>
{
readonly TEnumerable source;
readonly Func<TEnumerable, CancellationToken, TEnumerator> getAsyncEnumerator;
internal AsyncValueEnumerableWrapper(TEnumerable source, Func<TEnumerable, CancellationToken, TEnumerator> getAsyncEnumerator)
{
this.source = source;
this.getAsyncEnumerator = getAsyncEnumerator;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly TEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
=> getAsyncEnumerator(source, cancellationToken);
readonly IAsyncEnumerator<TSource> IAsyncEnumerable<TSource>.GetAsyncEnumerator(CancellationToken cancellationToken)
// ReSharper disable once HeapView.BoxingAllocation
=> getAsyncEnumerator(source, cancellationToken);
}
public readonly partial struct AsyncValueEnumerableWrapper<TSource>
: IAsyncValueEnumerable<TSource, AsyncValueEnumerableWrapper<TSource>.AsyncEnumerator>
{
readonly IAsyncEnumerable<TSource> source;
internal AsyncValueEnumerableWrapper(IAsyncEnumerable<TSource> source)
=> this.source = source;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly AsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
=> new(source, cancellationToken);
readonly IAsyncEnumerator<TSource> IAsyncEnumerable<TSource>.GetAsyncEnumerator(CancellationToken cancellationToken)
// ReSharper disable once HeapView.BoxingAllocation
=> new AsyncEnumerator(source, cancellationToken);
public readonly partial struct AsyncEnumerator
: IAsyncEnumerator<TSource>
{
readonly IAsyncEnumerator<TSource> enumerator;
internal AsyncEnumerator(IAsyncEnumerable<TSource> enumerable, CancellationToken cancellationToken)
=> enumerator = enumerable.GetAsyncEnumerator(cancellationToken);
public readonly TSource Current
=> enumerator.Current;
readonly TSource IAsyncEnumerator<TSource>.Current
=> enumerator.Current;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ValueTask<bool> MoveNextAsync()
=> enumerator.MoveNextAsync();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ValueTask DisposeAsync()
=> enumerator.DisposeAsync();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainMenuManager : MonoBehaviour
{
[SerializeField]
private GameObject mainMenuCamera;
[SerializeField]
private GameObject hubPrefab;
private GameObject hub;
private string playerParentPrefabPath;
private GameObject playerParentPrefab;
private MainMenuState state;
private Vector3 spawnPoint;
private MainMenuManager()
{
spawnPoint = Vector3.zero;
playerParentPrefabPath = "PlayerTemplatePrefab/PlayerTemplate";
}
private void Start()
{
state = MainMenuState.MAIN;
LoadPrefabs();
}
private void LoadPrefabs()
{
playerParentPrefab = Resources.Load<GameObject>(playerParentPrefabPath);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (state == MainMenuState.IN_GAME)
{
mainMenuCamera.SetActive(true);
PhotonNetwork.Destroy(StaticObjects.Player.transform.parent.gameObject);
StaticObjects.Player = null;
StaticObjects.PlayerCamera = null;
state = MainMenuState.CHARACTER_SELECT;
}
}
}
private void OnGUI()
{
switch (state)
{
case MainMenuState.MAIN:
if (GUILayout.Button("Connect", GUILayout.Height(40)))
{
state = MainMenuState.CONNECTING;
PhotonNetwork.ConnectUsingSettings("MOBA v1.0.0");
}
if (GUILayout.Button("Quit", GUILayout.Height(40)))
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
break;
case MainMenuState.CONNECTING:
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
break;
case MainMenuState.CHARACTER_SELECT:
GUILayout.Label("Ping: " + PhotonNetwork.GetPing().ToString() + " - Players: " + PhotonNetwork.room.PlayerCount);
if (GUILayout.Button("Fighter", GUILayout.Height(40)))
{
SpawnPlayer("Fighter");
}
if (GUILayout.Button("Gunner", GUILayout.Height(40)))
{
SpawnPlayer("Gunner");
}
if (GUILayout.Button("Mage", GUILayout.Height(40)))
{
SpawnPlayer("Mage");
}
if (GUILayout.Button("Quit", GUILayout.Height(30)))
{
PhotonNetwork.Disconnect();
Destroy(hub);
state = MainMenuState.MAIN;
}
break;
case MainMenuState.IN_GAME:
GUILayout.Label("Ping: " + PhotonNetwork.GetPing().ToString() + " - Players: " + PhotonNetwork.room.PlayerCount);
break;
}
}
private void OnJoinedLobby()
{
hub = Instantiate(hubPrefab, Vector2.zero, Quaternion.identity);
PhotonNetwork.JoinRandomRoom();
}
private void OnPhotonRandomJoinFailed()
{
PhotonNetwork.CreateRoom(null);
}
private void OnJoinedRoom()
{
if (PhotonNetwork.playerList.Length > 1)
{
StartCoroutine(LoadEntities());
}
state = MainMenuState.CHARACTER_SELECT;
}
private void SpawnPlayer(string characterName)
{
state = MainMenuState.IN_GAME;
GameObject playerTemplate = Instantiate(playerParentPrefab);
GameObject player = PhotonNetwork.Instantiate(characterName, spawnPoint, Quaternion.identity, 0);
player.transform.parent = playerTemplate.transform;
StaticObjects.Player = player.GetComponent<Player>();
StaticObjects.PlayerCamera = playerTemplate.GetComponentInChildren<Camera>();
StaticObjects.PlayerCamera.gameObject.SetActive(true);
mainMenuCamera.SetActive(false);
}
private IEnumerator LoadEntities()
{
yield return null;
foreach (Entity entity in FindObjectsOfType<Entity>())
{
entity.SendToServer_ConnectionInfoRequest();
}
}
}
enum MainMenuState
{
MAIN,
CONNECTING,
CHARACTER_SELECT,
IN_GAME,
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VBarcodeAufenthalt
{
public string Patientennummer { get; set; }
public string PatientNachname { get; set; }
public string PatientVorname { get; set; }
public DateTime? PatientGeburtsdatum { get; set; }
public string PatientGeburtsname { get; set; }
public string Aufenthaltsnummer { get; set; }
public DateTime? Aufnahmedatum { get; set; }
public DateTime? Entlassungsdatum { get; set; }
public string StationBezeichnung { get; set; }
public int? HausId { get; set; }
}
}
|
using InternDevelopmentProject.DataLogic;
using InternDevelopmentProject.Models;
using InternDevelopmentProject.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace InternDevelopmentProject.BusinessLogic
{
public class OperatorSignUpDetail
{
bool Flag = false;
public bool SetOperatorDetail(OperatorSignUp signUp)
{
var operatorRegistration = new OperatorRegistration();
operatorRegistration.Name = signUp.Name;
if (CheckEmailID(signUp.EmailID))
{
return false;
}
operatorRegistration.Email = signUp.EmailID;
string salt = null;
//Get the hash of password.
var passwordManager = new PasswordManager();
var passwordHash = passwordManager.GeneratePasswordHash(signUp.ConfirmPassword, out salt);
operatorRegistration.Hash = passwordHash;
//Defining the salt of password.
operatorRegistration.Salt = salt;
//Get password plus salt combination
operatorRegistration.Password = signUp.ConfirmPassword + salt;
var operatorSignUp = new OperatorSignUpOperation();
var IsOperatorAdded = operatorSignUp.SetOperatorDetail(operatorRegistration);
return IsOperatorAdded;
}
public bool CheckEmailID(string EmailID)
{
var IsValidEmailID = new SignUpEmailIDExistValidation();
return IsValidEmailID.IsEmailIDExist(EmailID);
}
}
} |
using BlazorUtils.Dev.Properties;
using System;
using System.Reflection;
using System.Threading.Tasks;
using static BlazorUtils.Dom.DomUtils;
namespace BlazorUtils.Dev
{
internal static class DevUtils
{
private static bool _isBooted = false;
internal enum TypeGroup
{
Numerics,
Boolean,
Others
}
internal static (object, TypeGroup) AsConverted(object value, Type type)
{
var stringValue = value.ToString();
if (type == typeof(int))
{
if (int.TryParse(stringValue, out var result))
{
return (result, TypeGroup.Numerics);
}
throw new Exception("BlazorUtils.Dev: Type and value not match");
}
if (type == typeof(bool))
{
if (bool.TryParse(stringValue, out var result))
{
return (result, TypeGroup.Boolean);
}
throw new Exception("BlazorUtils.Dev: Type and value not match");
}
else if (type == typeof(double))
{
if (double.TryParse(stringValue, out var result))
{
return (result, TypeGroup.Numerics);
}
throw new Exception("BlazorUtils.Dev: Type and value not match");
}
else if (type == typeof(float))
{
if (float.TryParse(stringValue, out var result))
{
return (result, TypeGroup.Numerics);
}
throw new Exception("BlazorUtils.Dev: Type and value not match");
}
else if (type == typeof(short))
{
if (short.TryParse(stringValue, out var result))
{
return (result, TypeGroup.Numerics);
}
throw new Exception("BlazorUtils.Dev: Type and value not match");
}
else return (stringValue, TypeGroup.Others);
}
internal static async Task DevBootAsync()
{
if (_isBooted) return;
await EvalAsync(Resources.LMTDevBoot);
_isBooted = true;
}
internal static void DevBoot()
{
if (_isBooted) return;
Eval(Resources.LMTDevBoot);
_isBooted = true;
}
internal static void DevWarn(string message) => Dev.Warn($"BlazorUtils.Dev: {message}");
internal static async Task DevWarnAsync(string message) => await Dev.WarnAsync($"BlazorUtils.Dev: {message}");
internal static void DevError(string message) => Dev.Error($"BlazorUtils.Dev: {message}");
internal static async Task DevErrorAsync(string message) => await Dev.ErrorAsync($"BlazorUtils.Dev: {message}");
internal static void InvokeMethod(object o, string methodName, object[] parameters = null)
{
GetMatchMethodFromAll(o, methodName).Invoke(o, parameters ?? new object[] { });
}
internal static MethodInfo GetMatchMethodFromAll(object o, string methodName) => o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
internal static PropertyInfo[] GetAllProperties(object o) => o.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
internal static FieldInfo[] GetAllFields(object o) => o.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
}
}
|
using System;
using fraction_calculator_dotnet.Entity;
using fraction_calculator_dotnet.Operators;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace fraction_calculator_dotnet.Tests
{
[TestClass]
public class CalculatorTests
{
private Calculator _calculator;
[TestInitialize]
public void Init()
{
_calculator = new Calculator();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddFraction_NullPassed_ThrowsException()
{
_calculator.AddFraction(null);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void AddFraction_FractionAddedTwice_ThrowsException()
{
var frac = new Fraction(1,1);
_calculator.AddFraction(frac);
_calculator.AddFraction(frac);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void AddOperation_NullPassed_ThrowsException()
{
_calculator.AddOperation(null);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void AddOperation_OperationAddedTwice_ThrowsException()
{
var op = new Mock<IOperator<Fraction>>();
_calculator.AddOperation(op.Object);
_calculator.AddOperation(op.Object);
}
}
} |
using Microsoft.Xna.Framework.Graphics;
using Nez;
using Nez.Sprites;
using Nez.Tiled;
namespace HackHW2018.Factories
{
public static class BackgroundFactory
{
public static Entity MakeBackground(Scene scene)
{
var entity = scene.createEntity("background");
var background = scene.content.Load<TiledMap>("dungeon");
var tiledMapComponent = new TiledMapComponent(background);
entity.addComponent(new TiledMapComponent(background, "TileLayer", true));
return entity;
}
}
}
|
using System;
namespace Exercise_1
{
class Program
{
static void Main(string[] args)
{
int score;
string result = "";
Console.Write("Write how many points you got : ");
score = int.Parse(Console.ReadLine());
if (score <= 50)
{
result = "E";
}
else if (score >= 51 && score <= 63)
{
result = "D";
}
else if (score >= 64 && score <= 76)
{
result = "C";
}
else if (score >= 77 && score <= 90)
{
result = "B";
}
else if (score >= 91 && score <= 63)
{
result = "A";
}
Console.WriteLine("Your's rating is : " + result.ToString());
}
}
}
|
using System;
using System.Windows.Media;
using WMagic.Brush.Basic;
namespace WMagic.Brush.Shape
{
public class GArch : AShape
{
#region 变量
// 粗细
private int thick;
// 颜色
private Color color;
// 填充
private Color stuff;
// 斜率
private double slope;
// 角度
private GAngle angle;
// 辐射
private GExtra extra;
// 中点
private GPoint point;
// 样式
private GLinear style;
#endregion
#region 属性方法
public int Thick
{
get { return this.thick; }
set { this.thick = value; }
}
public Color Color
{
get { return this.color; }
set { this.color = value; }
}
public Color Stuff
{
get { return this.stuff; }
set { this.stuff = value; }
}
public double Slope
{
get { return this.slope; }
set { this.slope = value; }
}
public GAngle Angle
{
get { return this.angle; }
set { this.angle = value; }
}
public GExtra Extra
{
get { return this.extra; }
set { this.extra = value; }
}
public GPoint Point
{
get { return this.point; }
set { this.point = value; }
}
public GLinear Style
{
get { return this.style; }
set { this.style = value; }
}
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="graph">图元画板</param>
public GArch(MagicGraphic graph)
: base(graph, new DrawingVisual())
{
this.thick = 1;
this.slope = 0;
this.color = Colors.Red;
this.style = GLinear.SOLID;
this.stuff = Colors.Transparent;
}
#endregion
#region 私有方法
/// <summary>
/// 中心角转离心角
/// </summary>
/// <param name="av">中心角</param>
/// <param name="ar">扇形所在椭圆辐射半径</param>
/// <returns>离心角</returns>
private double Ang2ecc(double av, GExtra ar)
{
double x = ar.Y * Math.Cos(av * Math.PI / 180), y = ar.X * Math.Sin(av * Math.PI / 180);
{
return Math.Atan2(Math.Abs(y), x) * (
y < 0 ? -1 : 1
);
}
}
#endregion
#region 函数方法
/// <summary>
/// 线条渲染
/// </summary>
protected sealed override void Render()
{
if (!MatchUtils.IsEmpty(this.point) && !MatchUtils.IsEmpty(this.extra) && !MatchUtils.IsEmpty(this.angle))
{
// 配置画笔
Pen pen = this.InitPen(this.style, this.color, this.thick);
if (pen != null)
{
// 配置填充
SolidColorBrush fill = this.InitStuff(this.stuff);
if (fill != null)
{
// 配置扇形
Geometry geom = (new GParse()).M(new GPoint(this.point.X + this.extra.X * Math.Cos(this.Ang2ecc(this.Angle.F, this.extra)), this.point.Y - this.extra.Y * Math.Sin(this.Ang2ecc(this.Angle.F, this.extra))))
.A(new GExtra(this.extra.X, this.extra.Y), 0, ((this.angle.T - this.angle.F) >= 180 ? 1 : 0), 0, new GPoint(this.point.X + this.extra.X * Math.Cos(this.Ang2ecc(this.Angle.T, this.extra)), this.point.Y - this.extra.Y * Math.Sin(this.Ang2ecc(this.Angle.T, this.extra))))
.L(new GPoint[] { new GPoint(this.point.X, this.point.Y) })
.Z().P();
if (geom != null)
{
// 绘制图形
using (DrawingContext dc = this.Brush.RenderOpen())
{
if (!this.Matte)
{
dc.DrawGeometry(fill, pen, geom);
}
}
// 旋转对象
if (this.Matte || this.slope == 0)
{
this.Brush.Transform = null;
}
else
{
this.Brush.Transform = new RotateTransform(-this.slope, this.point.X, this.point.Y);
}
}
}
}
}
}
#endregion
}
} |
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Runtime.InteropServices;
namespace NtApiDotNet.Utilities.Memory
{
internal static class UnmanagedUtils
{
internal static T ReadStruct<T>(this SafeBuffer buffer)
{
return ReadStruct<T>(buffer.DangerousGetHandle());
}
internal static T ReadStruct<T>(this IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return default;
return Marshal.PtrToStructure<T>(ptr);
}
internal static Guid? ReadGuid(this IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
return ReadStruct<Guid>(ptr);
}
internal static T[] ReadArray<T>(this IntPtr ptr, int count)
{
if (ptr == IntPtr.Zero)
return null;
T[] ret = new T[count];
int element_size = Marshal.SizeOf<T>();
for (int i = 0; i < count; ++i)
{
ret[i] = ReadStruct<T>(ptr + (i * element_size));
}
return ret;
}
internal static string[] ReadStringArray(this IntPtr ptr, int count)
{
if (ptr == IntPtr.Zero)
return null;
return ReadArray<IntPtr>(ptr, count).Select(p => Marshal.PtrToStringUni(p)).ToArray();
}
internal static T[] ReadArray<T, U>(this IntPtr ptr, int count, Func<U, T> map_func)
{
return ptr.ReadArray<U>(count).Select(map_func).ToArray();
}
}
}
|
using System;
using System.Data;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CRVCManager.DataModels;
using CRVCManager.Utilities;
namespace CRVCManager
{
/// <summary>
/// Interaction logic for PetWindow.xaml
/// </summary>
public partial class PetWindow : Window
{
private readonly Pet _currentPet;
private readonly User _currentUser;
private readonly bool _isEdit;
private readonly Client _owner;
private Consult _selectedConsult;
public PetWindow(User currentUser, Client owner, Pet currentPet = null)
{
_currentUser = currentUser;
_owner = owner;
InitializeComponent();
if (currentPet == null)
{
_isEdit = false;
WindowTitleLabel.Content = "New Pet";
DeleteButton.Content = "Cancel";
DeleteButton.Click += DeleteButton_Cancel_Click;
}
else
{
_isEdit = true;
WindowTitleLabel.Content = "Edit Pet";
DeleteButton.Content = "Delete";
DeleteButton.Click += DeleteButton_Click;
DeleteButton.Visibility = _currentUser.Group.Permissions.CanDeletePet ? Visibility.Visible : Visibility.Hidden;
_currentPet = currentPet;
}
ConsultsStackPanel.Visibility = Visibility.Collapsed;
PopulateFields();
}
public PetWindow(User currentUser, Pet currentPet) : this(currentUser, currentPet.Owner, currentPet)
{
}
private void DeleteButton_Cancel_Click(object sender, RoutedEventArgs e)
{
this.ConfirmClose("Are you sure you want to cancel? You will lose any unsaved changes.");
}
private void PopulateFields()
{
if (_isEdit)
{
OwnerTextBox.Text = $"{_currentPet.Owner.PrimaryFirstName} {_currentPet.Owner.PrimaryLastName}{(_currentPet.Owner.SecondaryFirstName != "" ? $" & {_currentPet.Owner.SecondaryFirstName} {_currentPet.Owner.SecondaryLastName}" : "")}";
NameTextBox.Text = _currentPet.Name;
SpeciesTextBox.Text = _currentPet.Species;
BreedTextBox.Text = _currentPet.Breed;
ColorTextBox.Text = _currentPet.Color;
SexTextBox.Text = _currentPet.Sex;
DesexedComboBox.SelectedItem = _currentPet.Desexed ? Yes : No;
TemperamentTextBox.Text = _currentPet.Temperament;
AllergiesTextBox.Text = _currentPet.Allergies;
NotesTextBox.Text = _currentPet.Notes;
DateOfBirthDatePicker.SelectedDate = _currentPet.DateOfBirth;
}
else
{
OwnerTextBox.Text = $"{_owner.PrimaryFirstName} {_owner.PrimaryLastName}{(_owner.SecondaryFirstName != "" ? $" & {_owner.SecondaryFirstName} {_owner.SecondaryLastName}" : "")}";
NameTextBox.Clear();
SpeciesTextBox.Clear();
BreedTextBox.Clear();
ColorTextBox.Clear();
SexTextBox.Clear();
DesexedComboBox.SelectedItem = No;
TemperamentTextBox.Clear();
AllergiesTextBox.Clear();
NotesTextBox.Clear();
DateOfBirthDatePicker.SelectedDate = null;
NameTextBox.Focus();
}
ValidateFields();
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
if (_isEdit)
{
try
{
_currentPet.Name = NameTextBox.Text.Trim();
_currentPet.Species = SpeciesTextBox.Text.Trim();
_currentPet.Breed = BreedTextBox.Text.Trim();
_currentPet.Color = ColorTextBox.Text.Trim();
_currentPet.Sex = SexTextBox.Text.Trim();
_currentPet.Desexed = Equals(DesexedComboBox.SelectedItem, Yes);
_currentPet.Temperament = TemperamentTextBox.Text.Trim();
_currentPet.Allergies = AllergiesTextBox.Text.Trim();
_currentPet.Notes = NotesTextBox.Text.Trim();
_currentPet.DateOfBirth = DateOfBirthDatePicker.SelectedDate;
Logging.Info("Pet was successfully updated");
Logging.Debug($"Pet with ID {_currentPet.Id} was updated by user with ID {_currentUser.Id}");
}
catch (Exception ex)
{
Logging.Error(new Exception("An error occured and some changes may not be saved", ex));
}
finally
{
Close();
}
}
else
{
var p = new Pet
{
Owner = _owner,
Name = NameTextBox.Text.Trim(),
Species = SpeciesTextBox.Text.Trim(),
Breed = BreedTextBox.Text.Trim(),
Color = ColorTextBox.Text.Trim(),
Sex = SexTextBox.Text.Trim(),
Temperament = TemperamentTextBox.Text.Trim(),
Allergies = AllergiesTextBox.Text.Trim(),
Notes = NotesTextBox.Text.Trim(),
DateOfBirth = DateOfBirthDatePicker.SelectedDate,
Desexed = Equals(DesexedComboBox.SelectedItem, Yes)
};
if (p.Exists)
{
Logging.Info("Pet was successfully created");
Logging.Debug($"Pet with ID {p.Id} was created by user with ID {_currentUser.Id}");
Close();
}
else
{
Logging.Error(new Exception("Unable to create new pet. An unexpected error occured"));
Close();
}
}
}
private void ValidateFields()
{
if (string.IsNullOrEmpty(NameTextBox.Text) && string.IsNullOrEmpty(SpeciesTextBox.Text))
{
SaveButton.IsEnabled = false;
}
else
{
SaveButton.IsEnabled = true;
}
if (string.IsNullOrEmpty(NameTextBox.Text))
{
NameLabel.HighlightInvalid();
}
else
{
NameLabel.HighlightNormal();
}
if (string.IsNullOrEmpty(SpeciesTextBox.Text))
{
SpeciesLabel.HighlightInvalid();
}
else
{
SpeciesLabel.HighlightNormal();
}
}
private void NameTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void AnimalTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void BreedTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void ColorTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void SexTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void TemperamentTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void AllergiesTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void DesexedComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ValidateFields();
}
private void NotesTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (this.ConfirmAction("Are you sure you want to delete this pet? \n\nAll consultation records will be removed"))
{
_currentPet?.Delete();
if (_currentPet?.Exists == false)
{
Logging.Info("Pet has been successfully deleted");
Close();
}
else
{
Logging.Error(new Exception("Pet could not be deleted"));
Close();
}
}
}
private void DateOfBirthDatePicker_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
ValidateFields();
}
private void ToggleConsultsButton_OnClick(object sender, RoutedEventArgs e)
{
if (ConsultsStackPanel.Visibility == Visibility.Collapsed)
{
ToggleConsultsButton.Content = "Hide Consults <<";
ConsultsStackPanel.Visibility = Visibility.Visible;
Task.Factory.StartNew(PopulateConsultsDataGrid);
}
else
{
ToggleConsultsButton.Content = "Show Consults >>";
ConsultsDataGrid.DataContext = null;
ConsultsStackPanel.Visibility = Visibility.Collapsed;
}
}
private async void PopulateConsultsDataGrid()
{
var d = await Consult.GetAllRecordsByPetFormattedAsync(_currentPet);
Dispatcher.Invoke(() =>
{
ConsultsDataGrid.DataContext = d;
ConsultsDataGrid.SelectedIndex = -1;
ConsultsDataGrid.HideColumn();
});
}
private void ConsultsDataGrid_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (!ConsultsDataGrid.IsEnabled || _selectedConsult == null)
{
return;
}
var consultRecordWindow = new ConsultWindow(_currentUser, _selectedConsult)
{
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Owner = this
};
consultRecordWindow.ShowDialog();
Task.Factory.StartNew(PopulateConsultsDataGrid);
}
private void ConsultsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Consult selectedConsult = null;
if (ConsultsDataGrid.SelectedIndex != -1)
{
if (ConsultsDataGrid.SelectedItem is DataRowView consultRowItem)
{
var consultFromDataGrid = new Consult(consultRowItem.Row.ItemArray[0].ToString().ParseGuid());
if (consultFromDataGrid.Exists)
{
selectedConsult = consultFromDataGrid;
}
}
}
_selectedConsult = selectedConsult;
}
private void ConsultsDataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
//Set properties on the columns during auto-generation
switch (e.Column.Header.ToString())
{
case "ID":
e.Column.Visibility = Visibility.Collapsed;
break;
}
}
private void CloseButton_OnClick(object sender, RoutedEventArgs e)
{
Close();
}
}
} |
namespace P01_HospitalDatabase.Data
{
public class Configurate
{
public const string ConnectionString = @"Server=DESKTOP-CP2NEHV\SQLEXPRESS;Database=Hospital;Integrated Security=True;";
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameMgr : MonoBehaviour
{
public float m_gameOverDuration = 5;
public AnimationCurve m_gameOverSlowdown = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1,0));
public static float Timer { get; private set; }
public static float DeltaTime { get; private set; }
public static bool IsPaused { get; private set; }
public static bool IsGameOver { get; private set; }
public static bool IsRoundEnd { get; private set; }
public static float TimeRatio { get; private set; }
private static GameMgr m_manager;
// ======================================================================================
// PUBLIC MEMBERS
// ======================================================================================
public void Start()
{
Debug.Assert(m_manager == null, this.gameObject.name + " - GameMgr : must be unique!");
m_manager = this;
PlayGame();
TimeRatio = 1f;
IsRoundEnd = false;
}
// ======================================================================================
void Update()
{
if (!IsPaused)
{
DeltaTime = TimeRatio * Time.deltaTime;
Timer += DeltaTime;
}
else
{
DeltaTime = 0;
}
if (Input.GetKeyDown(KeyCode.Escape))
{
//IsPaused = !IsPaused;
if (IsPaused)
{
QuitGame();
}
else
{
IsPaused = true;
}
}
}
// ======================================================================================
public static void QuitGame()
{
Application.Quit();
}
// ======================================================================================
public static void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
// ======================================================================================
public static void PauseGame()
{
IsPaused = true;
}
// ======================================================================================
public static void PlayGame()
{
IsPaused = false;
IsRoundEnd = false;
}
// ======================================================================================
public static void EndRound()
{
m_manager.StartCoroutine(m_manager.StartEndRound());
}
// ======================================================================================
public static void EndGame()
{
PauseGame();
IsGameOver = true;
}
// ======================================================================================
private IEnumerator StartEndRound()
{
float timer = m_gameOverDuration;
while (timer > 0)
{
TimeRatio = m_gameOverSlowdown.Evaluate(1 - timer / m_gameOverDuration);
yield return null;
timer -= Time.deltaTime;
}
TimeRatio = 1.0f;
PauseGame();
IsRoundEnd = true;
}
}
|
namespace Plus.Communication.Packets.Outgoing.Rooms.Settings
{
internal class RoomSettingsSavedComposer : MessageComposer
{
public int RoomId { get; }
public RoomSettingsSavedComposer(int roomId)
: base(ServerPacketHeader.RoomSettingsSavedMessageComposer)
{
RoomId = roomId;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(RoomId);
}
}
} |
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MyPage.Models.Infra
{
public class Usuario : IdentityUser
{
[Required]
public string Nome { get; set; }
[Required]
public string Sobrenome { get; set; }
public string Apelido { get; set; }
[DisplayName("Tipo de acesso")]
public int TpAcesso { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Acesso> Acessos { get; set; }
[DisplayName("Nome completo")]
public string NomeCompleto
{
get
{
return $"{this.Nome} {this.Sobrenome} ({this.Apelido})";
}
}
public Usuario()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EjemplosDelegados1
{
class Numeros
{
List<int> Numero = new List<int>()
{
1,2,3,4,5,6,7,8,9,0
};
}
}
|
using GaleService.DomainLayer.Managers.Models;
using GaleService.DomainLayer.Managers.Models.Request;
using GaleService.DomainLayer.Managers.Models.Response;
using System.Threading.Tasks;
namespace GaleService.DomainLayer.Managers.Services.Fitbit
{
internal abstract class FitbitGatewayBase
{
public async Task<GaleFitnessAccountResponse> GetFitnessAccount(GaleRequest galeRequest) => await GetFitnessAccountCore(galeRequest);
public async Task<GaleFitnessDevicesResponse> GetFitnessDevices(GaleRequest galeRequest) => await GetFitnessDevicesCore(galeRequest);
public async Task<GaleFitnessDeviceStatsResponse> GetFitnessDeviceStats(GaleFitnessDeviceStatsRequest galeRequest) => await GetFitnessDeviceStatsCore(galeRequest);
protected abstract Task<GaleFitnessAccountResponse> GetFitnessAccountCore(GaleRequest galeRequest);
protected abstract Task<GaleFitnessDevicesResponse> GetFitnessDevicesCore(GaleRequest galeRequest);
protected abstract Task<GaleFitnessDeviceStatsResponse> GetFitnessDeviceStatsCore(GaleFitnessDeviceStatsRequest galeRequest);
}
}
|
using Cotizacion.Domain;
using Cotizacion.Service.Interfaces;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace Cotizacion.Service.Services
{
public class CotizacionExtService: ICotizacionService
{
private readonly IOptions<ConfigurationService> _configurationService;
private Dictionary<string, string> _dicMonedas = new Dictionary<string, string>();
private string _baseUrl = "";
private string _key = "";
public CotizacionExtService(IOptions<ConfigurationService> configurationservice)
{
_configurationService = configurationservice;
_baseUrl = _configurationService.Value.CambioToday.URL;
_key = _configurationService.Value.CambioToday.Key;
_dicMonedas.Add("dolar", "USA");
_dicMonedas.Add("euro", "EUR");
_dicMonedas.Add("real", "BRA");
}
public CotizacionModel GetByMoneda(string sMoneda)
{
CotizacionModel hCotizacion = new CotizacionModel();
string sCodigoMoneda;
string sParametros = "quotes/ARG/{0}/json?quantity=1&key={1}";
try
{
sCodigoMoneda = _dicMonedas[sMoneda.ToLower()];
}
catch (Exception)
{
throw new Exception("No se ha encontrado la moneda que desea consultar.");
}
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseUrl);
hCotizacion.Moneda = sMoneda;
try
{
var httpResponse = client.GetAsync(sParametros.Replace("{0}", sMoneda).Replace("{1}", _key)).GetAwaiter().GetResult();
var content = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult().ToString();
dynamic cotizacion = JsonConvert.DeserializeObject(content);
hCotizacion.Precio = cotizacion.result.value;
}
catch (Exception)
{
throw new Exception("Error de comunicación.");
}
}
return hCotizacion;
}
}
}
|
using StudentSystem.Data.Repositories;
using StudentSystem.Model;
namespace StudentSystem.Data
{
public interface IStudentSystemData
{
IGenericRepository<Student> Students { get; }
IGenericRepository<Course> Courses { get; }
IGenericRepository<Homework> Homeworks { get; }
int SaveChanges();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WAO_Player.Class
{
public class Static_String
{
public static string[] URLSearch = { "http://www.nhaccuatui.com/tim-nang-cao?title=", "&singer=", "&type=", "&page=" };
public static string URLImageArtist = "http://mp3.zing.vn/tim-kiem/bai-hat.html?q=";
public static string Search_Songs(string key, short pageNumber)
{
string[] info = key.Split(new char[] { '-' }, 2);
string songTitle;
try
{
songTitle = info[0];
}
catch
{
songTitle = "";
}
string singerName;
try
{
singerName = info[1];
}
catch
{
singerName = "";
}
return URLSearch[0] + songTitle + URLSearch[1] + singerName + URLSearch[2] + "1" + URLSearch[3] + pageNumber.ToString();
}
public const string NHAC_CUA_TUI = "pack://application:,,,/Assets\\NCT_Image.png";
public const string MP3 = "pack://application:,,,/Assets\\XN.mp3";
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game1
{
public class Camera2d
{
protected float _zoom; // Camera Zoom
public Matrix _transform; // Matrix Transform
public Vector2 _pos; // Camera Position
protected float _rotation; // Camera Rotation
protected float targetZoom = 1;
public Camera2d()
{
_zoom = 1.0f;
_rotation = 0.0f;
_pos = new Vector2(1000,1000);
}
public float Zoom
{
get { return _zoom * 1920f / Game1.graphics.PreferredBackBufferWidth; }
set { _zoom = value * Game1.graphics.PreferredBackBufferWidth / 1920f; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
}
public float TargetZoom
{
get { return targetZoom * 1920f / Game1.graphics.PreferredBackBufferWidth; }
set { targetZoom = value * Game1.graphics.PreferredBackBufferWidth / 1920f; if (targetZoom < 0.1f) targetZoom = 0.1f; } // Negative zoom will flip image
}
public float Rotation
{
get { return _rotation; }
set { _rotation = value; }
}
// Auxiliary function to move the camera
public void Move(Vector2 amount)
{
_pos += amount;
}
// Get set position
public Vector2 Pos
{
get { return _pos; }
set { _pos = value; }
}
public void update()
{
if (_zoom < targetZoom) {
_zoom *= 1.1f;
if(_zoom > targetZoom)
{
_zoom = targetZoom;
}
}
if (_zoom > targetZoom)
{
_zoom /= 1.1f;
if (_zoom < targetZoom)
{
_zoom = targetZoom;
}
}
if (Game1.running)
{
Pos = Game1.getPlayer().getCenter();
_pos = Pos;
} else if(!EditorGui.saveText.isActive)
{
//Pos = Game1.getPlayer().getCenter() + offset;
KeyboardState state = Keyboard.GetState();
if (state.IsKeyDown(Keys.D))
Pos -= new Vector2(-8, 0);
if (state.IsKeyDown(Keys.A))
Pos -= new Vector2(+8, 0);
if (state.IsKeyDown(Keys.S))
Pos -= new Vector2(0,-8);
if (state.IsKeyDown(Keys.W))
Pos -= new Vector2(0,+8);
}
if (Pos.X < 0 + Game1.graphics.PreferredBackBufferWidth / 2 + 32)
_pos.X = Game1.graphics.PreferredBackBufferWidth / 2 + 32;
if (Pos.Y < 0 + Game1.graphics.PreferredBackBufferHeight / 2 + 32)
_pos.Y = Game1.graphics.PreferredBackBufferHeight / 2 + 32;
if (Pos.X > Game1.world.width * 16 - Game1.graphics.PreferredBackBufferWidth / 2 - 32)
_pos.X = Game1.world.width * 16 - Game1.graphics.PreferredBackBufferWidth / 2 - 32;
if (Pos.Y > Game1.world.height * 16 - Game1.graphics.PreferredBackBufferHeight / 2-32)
_pos.Y = Game1.world.height * 16 - Game1.graphics.PreferredBackBufferHeight / 2-32;
Rotation = -MapTools.VectorToAngle(WorldInfo.gravity) + MathHelper.Pi * 0.5f;
}
public Matrix get_transformation(GraphicsDevice graphicsDevice)
{
_transform = // Thanks to o KB o for this solution
Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateScale(new Vector3(_zoom, _zoom, 1)) *
Matrix.CreateTranslation(new Vector3((float)graphicsDevice.Viewport.Width * 0.5f, (float)graphicsDevice.Viewport.Height * 0.5f, 0));
return _transform;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.UI.Modules;
namespace DotNetNuke.ExtensionPoints
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:DefaultExtensionControl runat=server></{0}:DefaultExtensionControl>")]
public class DefaultExtensionControl : WebControl
{
[Bindable(true)]
[DefaultValue("")]
public string Module
{
get
{
var s = (string)ViewState["Module"];
return s ?? string.Empty;
}
set
{
ViewState["Module"] = value;
}
}
[Bindable(true)]
[DefaultValue("")]
public string Group
{
get
{
var s = (string)ViewState["Group"];
return s ?? string.Empty;
}
set
{
ViewState["Group"] = value;
}
}
[Bindable(true)]
[DefaultValue("")]
public string Name
{
get
{
var s = (string)ViewState["Name"];
return s ?? string.Empty;
}
set
{
ViewState["Name"] = value;
}
}
public ModuleInstanceContext ModuleContext { get; set; }
}
}
|
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 CoordControl.Core.Domains;
namespace CoordControl.Forms
{
public interface IFormPlanEdit
{
string PlanName { get; set; }
int Cycle { get; set; }
IList<Cross> CrossList { set; }
Cross SelectedCross { get; }
CrossPlan CrossPlanViewed { get; set; }
int PhaseOffset { get; set; }
int P1MainInterval { get; set; }
int P1MidInterval { get; set; }
int P2MainInterval { get; set; }
int P2MidInterval { get; set; }
void ComboBoxRefreshItems();
event EventHandler SaveButtonClick;
event EventHandler CrossListSelected;
event EventHandler CycleChanged;
}
public partial class FormPlanEdit : Form, IFormPlanEdit
{
public FormPlanEdit()
{
InitializeComponent();
}
#region экранирование полей
public string PlanName
{
get
{
return textBoxPlanName.Text;
}
set
{
textBoxPlanName.Text = value;
}
}
public int Cycle
{
get
{
return (int)numericUpDownCycle.Value;
}
set
{
numericUpDownCycle.Value = value;
}
}
public IList<Cross> CrossList
{
set
{
crossBindingSource.DataSource = value;
crossBindingSource.ResetBindings(false);
}
}
public Cross SelectedCross
{
get {
return (Cross)comboBoxCrosses.SelectedItem;
}
}
private CrossPlan crossPlan;
public CrossPlan CrossPlanViewed
{
get
{
crossPlan.PhaseOffset = PhaseOffset;
crossPlan.P1MainInterval = P1MainInterval;
crossPlan.P2MainInterval = P2MainInterval;
crossPlan.P1MediateInterval = P1MidInterval;
crossPlan.P2MediateInterval = P2MidInterval;
return crossPlan;
}
set
{
SetOffsetEnable();
crossPlan = value;
PhaseOffset = crossPlan.PhaseOffset;
P1MainInterval= crossPlan.P1MainInterval;
P2MainInterval = crossPlan.P2MainInterval;
P1MidInterval = crossPlan.P1MediateInterval;
P2MidInterval = crossPlan.P2MediateInterval;
}
}
public int PhaseOffset
{
get
{
return (int)numericUpDownOffset.Value;
}
set
{
numericUpDownOffset.Value = value;
}
}
public int P1MainInterval
{
get
{
return (int)numericUpDownP1MainInterval.Value;
}
set
{
numericUpDownP1MainInterval.Value = value;
}
}
public int P1MidInterval
{
get
{
return (int)numericUpDownP1MidInterval.Value;
}
set
{
numericUpDownP1MidInterval.Value = value;
}
}
public int P2MainInterval
{
get
{
return (int)numericUpDownP2MainInterval.Value;
}
set
{
numericUpDownP2MainInterval.Value = value;
}
}
public int P2MidInterval
{
get
{
return (int)numericUpDownP2MidInterval.Value;
}
set
{
numericUpDownP2MidInterval.Value = value;
}
}
#endregion
#region проброс событий
public event EventHandler SaveButtonClick;
public event EventHandler CrossListSelected;
private void comboBoxCrosses_SelectedIndexChanged(object sender, EventArgs e)
{
if (CrossListSelected != null) CrossListSelected(this, EventArgs.Empty);
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (SaveButtonClick != null) SaveButtonClick(this, EventArgs.Empty);
}
public event EventHandler CycleChanged;
private void numericUpDownCycle_ValueChanged(object sender, EventArgs e)
{
if (CycleChanged != null) CycleChanged(this, EventArgs.Empty);
}
#endregion
public void ComboBoxRefreshItems()
{
int selIndx = comboBoxCrosses.SelectedIndex;
crossBindingSource.ResetBindings(false);
if (selIndx < comboBoxCrosses.Items.Count)
comboBoxCrosses.SelectedIndex = selIndx;
}
private void numericUpDownP1MainInterval_ValueChanged(object sender, EventArgs e)
{
int value = Cycle - P1MainInterval - P1MidInterval - P2MidInterval;
if (value < 7)
{
P1MainInterval += value - 7;
}
else
P2MainInterval = value;
}
private void numericUpDownP2MainInterval_ValueChanged(object sender, EventArgs e)
{
int value = Cycle - P2MainInterval - P1MidInterval - P2MidInterval;
if (value < 7)
{
P2MainInterval += value - 7;
}
else
P1MainInterval = value;
}
private void numericUpDownP1MidInterval_ValueChanged(object sender, EventArgs e)
{
int value = Cycle - P2MainInterval - P1MidInterval - P2MidInterval;
if (value < 7)
{
MessageBox.Show("Длительность основного такта должна быть больше 7", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
P1MidInterval += value - 7;
}
else
P1MainInterval = value;
}
private void numericUpDownP2MidInterval_ValueChanged(object sender, EventArgs e)
{
int value = Cycle - P1MainInterval - P1MidInterval - P2MidInterval;
if (value < 7)
{
MessageBox.Show("Длительность основного такта должна быть больше 7", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
P2MidInterval += value - 7;
}
else
P2MainInterval = value;
}
private void SetOffsetEnable() {
numericUpDownOffset.Enabled = (SelectedCross.Position != 0);
}
}
}
|
using System.Net;
using Newtonsoft.Json;
using Xunit;
using StudentExercises.Models;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
namespace TestStudentExercises
{
public class TestInstructor
{
[Fact]
public async Task Test_Get_All_Instructors()
{
using (var client = new APIClientProvider().Client)
{
/*
ARRANGE
*/
/*
ACT
*/
var response = await client.GetAsync("/api/instructors");
string responseBody = await response.Content.ReadAsStringAsync();
var instructors = JsonConvert.DeserializeObject<List<Instructor>>(responseBody);
/*
ASSERT
*/
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(instructors.Count > 0);
}
}
[Fact]
public async Task Test_Get_One_Instructor()
{
using (var client = new APIClientProvider().Client)
{
/*
ARRANGE
*/
/*
ACT
*/
var responseWithAllInstructors = await client.GetAsync("/api/instructors");
string responseBodyWithAllInstructors = await responseWithAllInstructors.Content.ReadAsStringAsync();
var allInstructors = JsonConvert.DeserializeObject<List<Instructor>>(responseBodyWithAllInstructors);
var response = await client.GetAsync("/api/instructors/" + allInstructors.First().Id);
string responseBody = await response.Content.ReadAsStringAsync();
var instructor = JsonConvert.DeserializeObject<Instructor>(responseBody);
/*
ASSERT
*/
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(instructor.Id > 0);
}
}
[Fact]
public async Task Test_Add_One_Instructor()
{
using (var client = new APIClientProvider().Client)
{
/*
ARRANGE
*/
var newInstructor = new Instructor
{
FirstName = "Cavy",
LastName = "Baby",
SlackHandle = "cavy-baby",
cohort = new Cohort { CohortNum = 32 }
};
var newInstructorAsJSON = JsonConvert.SerializeObject(newInstructor);
/*
ACT
*/
var response = await client.PostAsync(
"/api/instructors",
new StringContent(newInstructorAsJSON, Encoding.UTF8, "application/json")
);
/*
ASSERT
*/
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Fact]
public async Task Test_Update_One_Instructor()
{
using (var client = new APIClientProvider().Client)
{
/*
ARRANGE
*/
string newHandle = "woof-woof";
var newInstructor = new Instructor
{
FirstName = "Cavy",
LastName = "Baby",
SlackHandle = newHandle
};
var newInstructorAsJSON = JsonConvert.SerializeObject(newInstructor);
/*
ACT
*/
var response = await client.PutAsync(
"/api/instructors/5",
new StringContent(newInstructorAsJSON, Encoding.UTF8, "application/json")
);
/*
ASSERT
*/
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Fact]
public async Task Test_Delete_One_Instructor()
{
using (var client = new APIClientProvider().Client)
{
/*
ARRANGE
*/
/*
ACT
*/
var response = await client.DeleteAsync(
"/api/instructors/6"
);
/*
ASSERT
*/
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
}
|
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Security;
using Microsoft.Reporting.WebForms;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using System.Data.SqlClient;
public partial class Admin_SALES_REPORT_VIEW : System.Web.UI.Page
{
public static int company_id = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["connection"]);
SqlCommand cmd = new SqlCommand("select * from user_details where Name='" + User.Identity.Name + "'", con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
company_id = Convert.ToInt32(dr["com_id"].ToString());
}
con.Close();
}
TextBox1.Text = Session["Name"].ToString();
TextBox2.Text = company_id.ToString();
ReportDocument rprt = new ReportDocument();
rprt.Load(Server.MapPath("CrystalReport.rpt"));
Sales_invoiceTableAdapters.DataTable1TableAdapter ta = new Sales_invoiceTableAdapters.DataTable1TableAdapter();
Sales_invoice.DataTable1DataTable table = ta.GetData(Convert.ToInt32(TextBox1.Text),Convert.ToInt32( TextBox2.Text));
rprt.SetDataSource(table.DefaultView);
CrystalReportViewer1.ReportSource = rprt;
CrystalReportViewer1.DataBind();
// CrystalReportViewer1.SeparatePages = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Admin/Sales_entry.aspx");
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UIImageButton : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_target(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.target);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_target(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
UISprite target;
LuaObject.checkType<UISprite>(l, 2, out target);
uIImageButton.target = target;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_normalSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.normalSprite);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_normalSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
string normalSprite;
LuaObject.checkType(l, 2, out normalSprite);
uIImageButton.normalSprite = normalSprite;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_hoverSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.hoverSprite);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_hoverSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
string hoverSprite;
LuaObject.checkType(l, 2, out hoverSprite);
uIImageButton.hoverSprite = hoverSprite;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_pressedSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.pressedSprite);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_pressedSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
string pressedSprite;
LuaObject.checkType(l, 2, out pressedSprite);
uIImageButton.pressedSprite = pressedSprite;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_disabledSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.disabledSprite);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_disabledSprite(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
string disabledSprite;
LuaObject.checkType(l, 2, out disabledSprite);
uIImageButton.disabledSprite = disabledSprite;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_pixelSnap(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.pixelSnap);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_pixelSnap(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
bool pixelSnap;
LuaObject.checkType(l, 2, out pixelSnap);
uIImageButton.pixelSnap = pixelSnap;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isEnabled(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIImageButton.isEnabled);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_isEnabled(IntPtr l)
{
int result;
try
{
UIImageButton uIImageButton = (UIImageButton)LuaObject.checkSelf(l);
bool isEnabled;
LuaObject.checkType(l, 2, out isEnabled);
uIImageButton.isEnabled = isEnabled;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UIImageButton");
LuaObject.addMember(l, "target", new LuaCSFunction(Lua_UIImageButton.get_target), new LuaCSFunction(Lua_UIImageButton.set_target), true);
LuaObject.addMember(l, "normalSprite", new LuaCSFunction(Lua_UIImageButton.get_normalSprite), new LuaCSFunction(Lua_UIImageButton.set_normalSprite), true);
LuaObject.addMember(l, "hoverSprite", new LuaCSFunction(Lua_UIImageButton.get_hoverSprite), new LuaCSFunction(Lua_UIImageButton.set_hoverSprite), true);
LuaObject.addMember(l, "pressedSprite", new LuaCSFunction(Lua_UIImageButton.get_pressedSprite), new LuaCSFunction(Lua_UIImageButton.set_pressedSprite), true);
LuaObject.addMember(l, "disabledSprite", new LuaCSFunction(Lua_UIImageButton.get_disabledSprite), new LuaCSFunction(Lua_UIImageButton.set_disabledSprite), true);
LuaObject.addMember(l, "pixelSnap", new LuaCSFunction(Lua_UIImageButton.get_pixelSnap), new LuaCSFunction(Lua_UIImageButton.set_pixelSnap), true);
LuaObject.addMember(l, "isEnabled", new LuaCSFunction(Lua_UIImageButton.get_isEnabled), new LuaCSFunction(Lua_UIImageButton.set_isEnabled), true);
LuaObject.createTypeMetatable(l, null, typeof(UIImageButton), typeof(MonoBehaviour));
}
}
|
using System.Threading.Tasks;
using Meziantou.Analyzer.Rules;
using TestHelper;
using Xunit;
namespace Meziantou.Analyzer.Test.Rules;
public sealed class UseStringCreateInsteadOfFormattableStringAnalyzerTests
{
private static ProjectBuilder CreateProjectBuilder()
{
return new ProjectBuilder()
.WithAnalyzer<UseStringCreateInsteadOfFormattableStringAnalyzer>()
.WithCodeFixProvider<UseStringCreateInsteadOfFormattableStringFixer>();
}
[Fact]
public async Task Net5_NoDiagnostic()
{
const string SourceCode = """
using System;
class TypeName
{
public void Test()
{
FormattableString.Invariant($"");
FormattableString.CurrentCulture($"");
}
}
""";
await CreateProjectBuilder()
.WithTargetFramework(TargetFramework.Net5_0)
.WithSourceCode(SourceCode)
.ValidateAsync();
}
[Fact]
public async Task FormattableString_NoDiagnostic()
{
const string SourceCode = """
using System;
class TypeName
{
public void Test()
{
FormattableString fs = default;
FormattableString.Invariant(fs);
FormattableString.CurrentCulture(fs);
}
}
""";
await CreateProjectBuilder()
.WithTargetFramework(TargetFramework.Net6_0)
.WithSourceCode(SourceCode)
.ValidateAsync();
}
[Fact]
public async Task Charp9_NoDiagnostic()
{
const string SourceCode = """
using System;
class TypeName
{
public void Test()
{
FormattableString.Invariant($"");
}
}
""";
await CreateProjectBuilder()
.WithTargetFramework(TargetFramework.Net6_0)
.WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp9)
.WithSourceCode(SourceCode)
.ValidateAsync();
}
#if CSHARP10_OR_GREATER
[Fact]
public async Task FormattableStringInvariant()
{
const string SourceCode = """
using System;
class TypeName
{
public void Test()
{
[|FormattableString.Invariant($"")|];
}
}
""";
const string Fix = """
using System;
using System.Globalization;
class TypeName
{
public void Test()
{
string.Create(CultureInfo.InvariantCulture, $"");
}
}
""";
await CreateProjectBuilder()
.WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp10)
.WithTargetFramework(TargetFramework.Net6_0)
.WithSourceCode(SourceCode)
.ShouldFixCodeWith(Fix)
.ValidateAsync();
}
[Fact]
public async Task FormattableStringCurrentCulture()
{
const string SourceCode = """
using System;
class TypeName
{
public void Test()
{
[|FormattableString.CurrentCulture($"")|];
}
}
""";
const string Fix = """
using System;
using System.Globalization;
class TypeName
{
public void Test()
{
string.Create(CultureInfo.CurrentCulture, $"");
}
}
""";
await CreateProjectBuilder()
.WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp10)
.WithTargetFramework(TargetFramework.Net6_0)
.WithSourceCode(SourceCode)
.ShouldFixCodeWith(Fix)
.ValidateAsync();
}
#endif
}
|
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class Tooltip : MonoBehaviour
{
public TextMeshProUGUI contentText;
public TextMeshProUGUI headerText;
public LayoutElement layoutElement;
public int characterWrapLimit;
public RectTransform rectTransform;
[TextArea]
[SerializeField] private string text;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
private void Start()
{
ShowTooltip(text);
}
private void ShowTooltip(string tooltipString)
{
gameObject.SetActive(true);
}
private void HideTooltip()
{
gameObject.SetActive(false);
}
public void SetText(string content, string header = "")
{
headerText.gameObject.SetActive(!string.IsNullOrEmpty(header));
headerText.text = header;
contentText.text = content;
var headerLength = headerText.text.Length;
var contentLength = contentText.text.Length;
layoutElement.enabled =
(headerLength > characterWrapLimit || contentLength > characterWrapLimit) ? true : false;
}
private void Update()
{
Vector2 position = Input.mousePosition;
var pivotX = position.x / Screen.width;
var pivotY = position.y / Screen.height - 0.3F;
rectTransform.pivot = new Vector2(pivotX, pivotY);
transform.position = position;
}
}
|
namespace ConsoleWebServer.Framework
{
using System.Collections.Generic;
/// <summary>
/// Basic Action Result interface that contains the method GetResponse();
/// </summary>
public interface IActionResult
{
/// <summary>
/// Response Headers are the headers passed to the Result.
/// </summary>
List<KeyValuePair<string, string>> ResponseHeaders { get; }
/// <summary>
/// Gets a http response from a given http request.
/// </summary>
/// <returns>Http Response.</returns>
HttpResponse GetResponse();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Idenz.Modules.Management
{
public partial class frmModules : Core.Windows.frmListBaseForm
{
public frmModules()
{
InitializeComponent();
this.Text = "Modules";
this.lblHeader.Text = "Modules";
this.lblHeaderDescription.Text = "List, Add, Edit Modules";
this.ListSpName = "sp_SelModules";
}
public override void LoadData(object sender, EventArgs e)
{
base.LoadData(sender, e);
}
}
}
|
using PMA.Store_Framework.Domain;
namespace PMA.Store_Domain.Photos.Entities
{
public class Photo : BaseEntity
{
public string Url { get; set; }
public int Size { get; set; }
}
}
|
namespace POS_SP.Models
{
public enum PaymentTypes
{
Cash,
CreditCard,
BKash,
Rocket,
EMI
};
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
//xml操作工具类
namespace XMLHelper
{
public static class XMLHelper
{
/// <summary>
/// 复制节点方法,等等(参数需要修改)
/// </summary>
/// <param name="cell">单元格</param>
/// <param name="height">单元格高度</param>
/// <param name="width">单元格宽度</param>
/// <returns>返回是否为合并单元格的布尔(Boolean)值</returns>
public static bool CopyNodeByID(string nodeid, out int height, out int width)
{
height = 0;
width = 0;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
public static class Logger
{
static string applicationpath = AppDomain.CurrentDomain.BaseDirectory;
static string filename = "BHS_Now_Emulator_Log_";
public static int counter {get;set;}
public static void WriteLine( string logtype, string threadname, string message,bool showdate)
{
DateTime now = DateTime.Now;
StreamWriter sw = File.AppendText(applicationpath + filename + DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (logtype == "[ERROR]")
{
//message += "\r\n";
// message += "\n" + Environment.StackTrace.ToString();
}
string prepstring;
string spacebuf = " ";
if (showdate)
{
prepstring = now.ToString("yyyy-mm-dd HH:mm:ss") + " " + logtype + " " + threadname;
}
else
{
prepstring = " " + spacebuf.Substring(0, logtype.Length + threadname.Length);//21 spaces
}
sw.WriteLine(prepstring + " : " + message);
sw.Close();
}
}
|
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.DB.Utils;
using PDV.DAO.Entidades.Estoque.Suprimentos;
using PDV.DAO.Enum;
using PDV.VIEW.App_Context;
using System;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Cadastro.Suprimentos
{
public partial class FCA_Almoxarifado : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CADASTRO DE ALMOXARIFADO";
private Almoxarifado Almoxarifado = null;
public FCA_Almoxarifado(Almoxarifado _Almoxarifado)
{
InitializeComponent();
Almoxarifado = _Almoxarifado;
PreencherTela();
}
private void PreencherTela()
{
ovTXT_Descricao.Text = Almoxarifado.Descricao;
switch(Convert.ToInt32(Almoxarifado.Tipo))
{
case 1:
ovCKB_Estoque.Checked = true;
break;
case 2:
ovCKB_Producao.Checked = true;
break;
case 3:
ovCKB_Quarentena.Checked = true;
break;
}
}
private void metroButton4_Click(object sender, System.EventArgs e)
{
Close();
}
private void metroButton3_Click(object sender, System.EventArgs e)
{
try
{
PDVControlador.BeginTransaction();
if (string.IsNullOrEmpty(ovTXT_Descricao.Text))
throw new Exception("Informe o Nome.");
TipoOperacao Op = TipoOperacao.UPDATE;
if (!FuncoesAlmoxarifado.Existe(Almoxarifado.IDAlmoxarifado))
{
Almoxarifado.IDAlmoxarifado = Sequence.GetNextID("ALMOXARIFADO", "IDALMOXARIFADO");
Op = TipoOperacao.INSERT;
}
Almoxarifado.Descricao = ovTXT_Descricao.Text;
Almoxarifado.Tipo = GetTipo();
if (!FuncoesAlmoxarifado.Salvar(Almoxarifado, Op))
throw new Exception("Não foi possível salvar o Almoxarifado.");
PDVControlador.Commit();
MessageBox.Show(this, "Almoxarifado salvo com sucesso.", NOME_TELA);
Close();
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, NOME_TELA);
PDVControlador.Rollback();
}
}
private decimal GetTipo()
{
if (ovCKB_Estoque.Checked) return 1;
if (ovCKB_Producao.Checked) return 2;
if (ovCKB_Quarentena.Checked) return 3;
return 0;
}
private void FCA_Almoxarifado_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
this.Close();
break;
}
}
}
}
|
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.JsonRpc;
using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer;
namespace OmniSharp.Extensions.DebugAdapter.Protocol
{
public abstract class DebugAdapterRpcOptionsBase<T> : JsonRpcServerOptionsBase<T> where T : IJsonRpcHandlerRegistry<T>
{
protected DebugAdapterRpcOptionsBase()
{
Services.AddLogging(builder => LoggingBuilderAction.Invoke(builder));
WithAssemblies(typeof(DebugAdapterRpcOptionsBase<T>).Assembly);
RequestProcessIdentifier = new ParallelRequestProcessIdentifier();
}
public ISerializer Serializer { get; set; } = new DapSerializer();
internal bool AddDefaultLoggingProvider { get; set; }
internal Action<ILoggingBuilder> LoggingBuilderAction { get; set; } = _ => { };
internal Action<IConfigurationBuilder> ConfigurationBuilderAction { get; set; } = _ => { };
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Project_1
{
public partial class ViewTickets : System.Web.UI.Page
{
Dictionary<string, string> ticket = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session.Count > 0)
{
Dictionary<string, string> ticket = new Dictionary<string, string>();
HtmlTable table = new HtmlTable();
table.Width = "100%";
HtmlTableCell cell1 = new HtmlTableCell();
cell1.Width = "15%";
HtmlTableCell cell2 = new HtmlTableCell();
cell2.Width = "15%";
HtmlTableCell cell3 = new HtmlTableCell();
cell3.Width = "15%";
HtmlTableCell cell4 = new HtmlTableCell();
cell4.Width = "15%";
HtmlTableCell cell5 = new HtmlTableCell();
cell5.Width = "15%";
HtmlTableCell cell6 = new HtmlTableCell();
cell6.Width = "15%";
HtmlTableCell cell7 = new HtmlTableCell();
cell7.Width = "15%";
HtmlTableRow row = new HtmlTableRow();
cell1.InnerHtml = "Name";
cell2.InnerHtml = "Department";
cell3.InnerHtml = "Phone Number";
cell4.InnerHtml = "E-Mail";
cell5.InnerHtml = "Type of Issue";
cell6.InnerHtml = "Short Description";
cell7.InnerHtml = "Priority";
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
row.Cells.Add(cell4);
row.Cells.Add(cell5);
row.Cells.Add(cell6);
row.Cells.Add(cell7);
table.Rows.Add(row);
int numOfTickets = (int)Session["ticketNum"];
for (int i = 1; i <= numOfTickets; i++)
{
ticket = (Dictionary<string, string>)Session["ticket" + i];
row = new HtmlTableRow();
cell1 = new HtmlTableCell();
cell1.InnerText = ticket["firstName"] + " " + ticket["lastName"];
row.Cells.Add(cell1);
cell2 = new HtmlTableCell();
cell2.InnerText = ticket["department"];
row.Cells.Add(cell2);
cell3 = new HtmlTableCell();
cell3.InnerText = ticket["phoneNum"];
row.Cells.Add(cell3);
cell4 = new HtmlTableCell();
cell4.InnerText = ticket["email"];
row.Cells.Add(cell4);
cell5 = new HtmlTableCell();
cell5.InnerText = ticket["typeIssue"];
row.Cells.Add(cell5);
cell6 = new HtmlTableCell();
cell6.InnerText = ticket["issue"];
row.Cells.Add(cell6);
cell7 = new HtmlTableCell();
cell7.InnerText = ticket["priority"];
row.Cells.Add(cell7);
table.Rows.Add(row);
}
ContentPlaceHolder cphContentPlaceHolder = (ContentPlaceHolder)Master.FindControl("MainContent");
cphContentPlaceHolder.Controls.Add(table);
}
}
}
}
} |
using Xamarin.Forms;
namespace Scoutworks.Views.MatchViews
{
public partial class MatchPageTab2Auto : ContentPage
{
public MatchPageTab2Auto()
{
InitializeComponent();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
namespace Proyek_Informatika.Models
{
public class PenilaianSidangContainer
{
public string NPM { get; set; }
public string nama { get; set; }
public string pembimbing { get; set; }
public string penguji1 { get; set; }
public string penguji2 { get; set; }
public string ruang { get; set; }
public string tanggal { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalModels
{
public class DiscussionT
{
/// <summary>
/// DTO Model for discussions backend - > frontend
/// </summary>
public DiscussionT()
{
Comments = new List<Comment>();
DiscussionTopics = new List<string>();
}
public string DiscussionId { get; set; }
public string MovieId { get; set; }
public string Userid { get; set; }
public DateTime CreationTime { get; set; }
public string Subject { get; set; }
public int Likes { get; set; }
public List<Comment> Comments { get; set; }
public List<string> DiscussionTopics { get; set; }
}
}
|
namespace HandCoded.Shared
{
/// <summary>
/// A constant class used on this demo.
/// </summary>
public static class Constants
{
/// <summary>
/// The name of the server.
/// </summary>
public const string Server = "(local)\\MSSQL01";
/// <summary>
/// The name of the Tutorial database.
/// </summary>
public const string TutorialDatabase = "Tutorial";
/// <summary>
/// The name of the AdventureWorks database.
/// </summary>
public const string AdventureWorksDatabase = "AdventureWorks2016";
}
}
|
using System;
using System.IO;
namespace HomeWork6._2
{
// Суханов
// Модифицировать программу нахождения минимума функции так, чтобы можно было передавать функцию в виде делегата.
// а) Сделать меню с различными функциями и представить пользователю выбор, для какой функции и на каком отрезке находить минимум.
// Использовать массив(или список) делегатов, в котором хранятся различные функции.
class Program : FunctionBase
{
static void Main(string[] args)
{
function[] F = { F1, F2 };
Console.WriteLine("Сделайте выбор: 1 - функция F1, 2 - функция F2");
int index = int.Parse(Console.ReadLine());
SaveFunc("data.bin", -100, 100, 0.5, F[index - 1]);
Console.WriteLine(Load("data.bin"));
Console.ReadKey();
}
}
} // б) * Переделать функцию Load, чтобы она возвращала массив считанных значений.
// Пусть она возвращает минимум через параметр(с использованием модификатора out).
// Как сделать это не знаю...
|
using System.Collections.Generic;
using AutoMapper;
using EnsureThat;
using L7.Domain;
using MediatR;
namespace L7.Business
{
public class GetProductsQueryHandler : RequestHandler<GetProductsQuery, IEnumerable<ProductModel>>
{
private readonly IProductRepository productRepository;
private readonly IMapper mapper;
public GetProductsQueryHandler(IProductRepository productRepository, IMapper mapper)
{
EnsureArg.IsNotNull(productRepository);
EnsureArg.IsNotNull(mapper);
this.productRepository = productRepository;
this.mapper = mapper;
}
protected override IEnumerable<ProductModel> Handle(GetProductsQuery request)
{
EnsureArg.IsNotNull(request);
var products = productRepository.GetAll();
return mapper.Map<IEnumerable<ProductModel>>(products);
}
}
} |
using System;
using System.Text.RegularExpressions;
namespace Gomoku.Commands.Classes
{
public class Turn : ACommand
{
public Turn()
:base(ECommand.TURN)
{}
public override DataCommand CreateDataCommand(string input)
{
Regex mRegex = new Regex("TURN (\\d{1,2}),(\\d{1,2})");
Match match = mRegex.Match(input);
if (match.Success)
return new DataCommand {CommandType = Type, Data = new Tuple<uint, uint>(Convert.ToUInt32(match.Groups[1].Value), Convert.ToUInt32(match.Groups[2].Value))};
return new DataCommand {CommandType = ECommand.ERROR, Data = null};
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
public class solve_me_first : Challenge
{
static int solveMeFirst(int a, int b)
{
// Hint: Type return a+b; below
return a + b;
}
public override void Main(String[] args)
{
int val1 = Convert.ToInt32(Console.ReadLine());
int val2 = Convert.ToInt32(Console.ReadLine());
int sum = solveMeFirst(val1, val2);
Console.WriteLine(sum);
}
public solve_me_first()
{
Name = "Solve Me First";
Path = "solve-me-first";
Difficulty = Difficulty.Easy;
Domain = Domain.Algorithms;
Subdomain = Subdomain.Warmup;
}
}
} |
using System.Collections.Generic;
using Logs.Models.Enumerations;
using NUnit.Framework;
namespace Logs.Models.Tests.UserTests
{
[TestFixture]
public class PropertiesTests
{
[Test]
public void TestProperties_ShouldSetLogCorrectly()
{
// Arrange
var log = new TrainingLog();
var user = new User();
// Act
user.TrainingLog = log;
// Assert
Assert.AreSame(log, user.TrainingLog);
}
[Test]
public void TestProperties_ShouldSetCommentsCorrectly()
{
// Arrange
var comments = new List<Comment>();
var user = new User();
// Act
user.Comments = comments;
// Assert
CollectionAssert.AreEqual(comments, user.Comments);
}
[Test]
public void TestProperties_ShouldSetEntriesCorrectly()
{
// Arrange
var entries = new List<LogEntry>();
var user = new User();
// Act
user.LogEntries = entries;
// Assert
CollectionAssert.AreEqual(entries, user.LogEntries);
}
[Test]
public void TestProperties_ShouldSetSubscriptionsCorrectly()
{
// Arrange
var subscriptions = new List<Subscription>();
var user = new User();
// Act
user.Subscriptions = subscriptions;
// Assert
CollectionAssert.AreEqual(subscriptions, user.Subscriptions);
}
[Test]
public void TestProperties_ShouldSetNutritionsCorrectly()
{
// Arrange
var nutritions = new List<Nutrition>();
var user = new User();
// Act
user.Nutritions = nutritions;
// Assert
CollectionAssert.AreEqual(nutritions, user.Nutritions);
}
[Test]
public void TestProperties_ShouldSetMeasurementsCorrectly()
{
// Arrange
var measurements = new List<Measurement>();
var user = new User();
// Act
user.Measurements = measurements;
// Assert
CollectionAssert.AreEqual(measurements, user.Measurements);
}
[Test]
public void TestVotes_ShouldInitializeCorrectly()
{
// Arrange
var votes = new List<Vote>();
var user = new User();
// Act
user.Votes = votes;
// Assert
CollectionAssert.AreEqual(votes, user.Votes);
}
[Test]
public void TestTrainingLogs_ShouldInitializeCorrectly()
{
// Arrange
var logs = new List<TrainingLog>();
var user = new User();
// Act
user.TrainingLogs = logs;
// Assert
CollectionAssert.AreEqual(logs, user.TrainingLogs);
}
[TestCase(GenderType.Female)]
[TestCase(GenderType.Male)]
[TestCase(GenderType.NotSelected)]
public void TestProperties_ShouldSetGenderTypeCorrectly(GenderType genderType)
{
// Arrange
var user = new User();
// Act
user.GenderType = genderType;
// Assert
Assert.AreEqual(genderType, user.GenderType);
}
}
}
|
using MediatR;
using Publicon.Core.Exceptions;
using Publicon.Core.Repositories.Abstract;
using Publicon.Infrastructure.DTOs;
using Publicon.Infrastructure.Managers.Abstract;
using Publicon.Infrastructure.Queries.Models.Publication;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Publicon.Infrastructure.Queries.Handlers.Publication
{
public class DownloadPublicationHandler : IRequestHandler<DownloadPublicationQuery, BlobInfoDTO>
{
private readonly IBlobManager _blobManager;
private readonly IPublicationRepository _publicationRepository;
public DownloadPublicationHandler(
IBlobManager blobManager,
IPublicationRepository publicationRepository)
{
_blobManager = blobManager;
_publicationRepository = publicationRepository;
}
public async Task<BlobInfoDTO> Handle(DownloadPublicationQuery request, CancellationToken cancellationToken)
{
var publication = await _publicationRepository.GetByIdAsync(request.PublicationId);
if (publication == null)
throw new PubliconException(ErrorCode.EntityNotFound(typeof(Core.Entities.Concrete.Publication)));
if (string.IsNullOrWhiteSpace(publication.FileName))
throw new PubliconException(ErrorCode.FileNotFound);
string regexSearch = new string(Path.GetInvalidFileNameChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
var blobDTO = await _blobManager.GetBlobAsync(publication.FileName);
blobDTO.FileName = r.Replace(publication.Title, "");
return blobDTO;
}
}
}
|
// ----------------------------------------------------------------------------
// <copyright file="RegionNames.cs" company="SOGETI Spain">
// Copyright © 2015 SOGETI Spain. All rights reserved.
// Build user interfaces with Prism by Osc@rNET.
// </copyright>
// ----------------------------------------------------------------------------
namespace SogetiRSS
{
/// <summary>
/// Represents the region names.
/// </summary>
public static class RegionNames
{
#region Fields
/// <summary>
/// Defines the RSS channels region name.
/// </summary>
public const string RSSChannels = "RSSChannels";
/// <summary>
/// Defines the RSS feed reader region name.
/// </summary>
public const string RSSFeedReader = "RSSFeedReader";
/// <summary>
/// Defines the RSS feeds region name.
/// </summary>
public const string RSSFeeds = "RSSFeeds";
#endregion Fields
}
} |
// Copyright (c) Russlan Akiev. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace ServiceBase.Plugins
{
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
/// <summary>
/// Contains <see cref="IApplicationBuilder"/> extenion methods.
/// </summary>
public static partial class ApplicationBuilderExtensions
{
/// <summary>
/// Adds services of each plugins to the
/// <see cref="IApplicationBuilder"/> request execution pipeline.
/// </summary>
public static void UsePlugins(
this IApplicationBuilder app)
{
IEnumerable<IConfigureAction> actions =
PluginAssembyLoader.GetServices<IConfigureAction>();
foreach (IConfigureAction action in actions)
{
action.Execute(app);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace mokiniu_sistema.Models
{
public class Vaikas
{
public int VaikasId { get; set; }
[Required]
public string Vardas { get; set; }
public string PridejimoKodas { get; set; }
public int? TevasId { get; set; }
public Tevas Tevas { get; set; }
[Required]
public int? MokyklaId { get; set; }
public Mokykla Mokykla { get; set; }
}
}
|
using System;
using BPiaoBao.Client.DomesticTicket.Model;
using BPiaoBao.Client.UIExt;
using GalaSoft.MvvmLight.Command;
using System.Threading.Tasks;
using BPiaoBao.AppServices.Contracts.DomesticTicket;
using GalaSoft.MvvmLight.Threading;
using BPiaoBao.AppServices.DataContracts.DomesticTicket.DataObject;
using BPiaoBao.Common.Enums;
namespace BPiaoBao.Client.DomesticTicket.ViewModel
{
public sealed class BuySingleInsuranceViewModel : BaseVM
{
#region 构造函数
public BuySingleInsuranceViewModel()
{
if (IsInDesignMode) return;
IsBusy = true;
Action action = () => CommunicateManager.Invoke<IInsuranceService>(service =>
{
#region 保险相关设置
var re = service.GetCurentInsuranceCfgInfo();
var leaveCount = service.GetCurentInsuranceCfgInfo(true).LeaveCount;
if (re.IsOpenCurrenCarrierInsurance && re.IsOpenUnexpectedInsurance && leaveCount > 0)
{
BuySingleInsuranceModel = new BuySingleInsuranceModel
{
FlightStartDate = DateTime.Now.Date,
BirthDay = DateTime.Now.AddYears(-16),
InsuranceCount = 1,
SumInsured = 400000,
IsAdultType = true,
Gender = true,
IsIdType = true,
};
}
else
{
UIManager.ShowMessage("剩余保险数量不足");
IsDone = true;
}
#endregion
}, UIManager.ShowErr);
Task.Factory.StartNew(action).ContinueWith(task =>
{
Action setBusyAction = () => { IsBusy = false; };
DispatcherHelper.UIDispatcher.Invoke(setBusyAction);
});
}
#endregion
#region 公开属性
#region IsDone
/// <summary>
/// The <see /> property's name.
/// </summary>
private const string IsDonePropertyName = "IsDone";
private bool _isDone;
public bool IsDone
{
get { return _isDone; }
set
{
if (_isDone == value) return;
RaisePropertyChanging(IsDonePropertyName);
_isDone = value;
RaisePropertyChanged(IsDonePropertyName);
}
}
#endregion
#region BuySingleInsuranceModel
private const string BuySingleInsuranceModelPropertyName = "BuySingleInsuranceModel";
private BuySingleInsuranceModel _buySingleInsuranceModel;
public BuySingleInsuranceModel BuySingleInsuranceModel
{
get { return _buySingleInsuranceModel; }
set
{
if (_buySingleInsuranceModel == value) return;
RaisePropertyChanging(BuySingleInsuranceModelPropertyName);
_buySingleInsuranceModel = value;
RaisePropertyChanged(BuySingleInsuranceModelPropertyName);
}
}
#endregion
#endregion
#region 公开命令
#region BuySingleInsuranceCommand
private RelayCommand _buySingleInsuranceCommand;
public RelayCommand BuySingleInsuranceCommand
{
get
{
return _buySingleInsuranceCommand ?? (_buySingleInsuranceCommand = new RelayCommand(ExecuteBuySingleInsuranceCommand, CanExecuteBuySingleInsuranceCommand));
}
}
public void ExecuteBuySingleInsuranceCommand()
{
if (BuySingleInsuranceModel == null) return;
if (!BuySingleInsuranceModel.Check()) return;
if (BuySingleInsuranceModel.BirthDay == null) return;
var rbim = new RequestBuyInsuranceManually
{
CardNo =
string.IsNullOrWhiteSpace(BuySingleInsuranceModel.IdNo) &&
(BuySingleInsuranceModel.IsBabyType || BuySingleInsuranceModel.IsChildType)
? BuySingleInsuranceModel.BirthDay.Value.ToString("yyyy-MM-dd")
: BuySingleInsuranceModel.IdNo,
Count = BuySingleInsuranceModel.InsuranceCount,
FlightNumber = BuySingleInsuranceModel.FlightNumber
};
if (BuySingleInsuranceModel.IsIdType)
rbim.IdType = EnumIDType.NormalId;
else if (BuySingleInsuranceModel.IsMilitaryIdType)
rbim.IdType = EnumIDType.MilitaryId;
else if (BuySingleInsuranceModel.IsPassportIdType)
rbim.IdType = EnumIDType.Passport;
else if (BuySingleInsuranceModel.IsOtherType)
rbim.IdType = EnumIDType.Other;
if (BuySingleInsuranceModel.IsAdultType)
rbim.PassengerType = EnumPassengerType.Adult;
else if (BuySingleInsuranceModel.IsChildType)
rbim.PassengerType = EnumPassengerType.Child;
else if (BuySingleInsuranceModel.IsBabyType)
rbim.PassengerType = EnumPassengerType.Baby;
rbim.InsuranceLimitEndTime = BuySingleInsuranceModel.FlightStartDate.Date.AddDays(1).AddSeconds(-1);
rbim.InsuranceLimitStartTime = BuySingleInsuranceModel.FlightStartDate.Date;
rbim.StartDateTime = BuySingleInsuranceModel.FlightStartDate;
rbim.InsuredName = BuySingleInsuranceModel.Name;
rbim.Mobile = BuySingleInsuranceModel.Mobile;
rbim.PNR = BuySingleInsuranceModel.PNR;
rbim.SexType = BuySingleInsuranceModel.Gender ? EnumSexType.Male : EnumSexType.Female;
rbim.Birth = BuySingleInsuranceModel.BirthDay;
rbim.ToCityName = BuySingleInsuranceModel.ToCityName;
IsBusy = true;
Action action = () => CommunicateManager.Invoke<IInsuranceService>(service =>
{
service.BuyInsuranceManually(rbim);
UIManager.ShowMessage("投保成功!");
IsDone = true;
}, UIManager.ShowErr);
Task.Factory.StartNew(action).ContinueWith(task =>
{
Action setBusyAction = () => { IsBusy = false; };
DispatcherHelper.UIDispatcher.Invoke(setBusyAction);
});
}
private bool CanExecuteBuySingleInsuranceCommand()
{
return !IsBusy;
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace bot_backEnd.Models.AppModels
{
public class AppInstitution
{
public int Id { get; set; }
public string Name { get; set; }
public int HeadquaterID { get; set; }
public string HeadquaterName { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public DateTime JoinDate { get; set; }
public string ImageURL { get; set; }
public int NumOfPosts { get; set; }
}
}
|
public static class Game
{
public enum Mode
{
FREE
}
public enum State
{
Paused,
Running
}
public static class Tag
{
public static readonly string Civilian = "Civilian";
public static readonly string Player = "Player";
}
} |
using REQFINFO.Domain;
using REQFINFO.Repository;
using REQFINFO.Repository.DataEntity;
using REQFINFO.Repository.Infrastructure.Contract;
using REQFINFO.Business.Interfaces;
using System.Collections.Generic;
using ExpressMapper;
using REQFINFO.Utility;
using System.Linq;
using System;
namespace REQFINFO.Business
{
public class StatusBusiness : StatusRepository, IStatusBusiness
{
#region property
private readonly StatusRepository StatusRepository;
#endregion
public StatusBusiness(IUnitOfWork _unitOfWork)
: base(_unitOfWork)
{
StatusRepository = this;
}
public List<StatusModel> GetAllStatus()
{
List<Tab> status = StatusRepository.GetAll().OrderBy(x => x.Sequence).ToList();
List<StatusModel> statusModel = new List<StatusModel>();
Mapper.Map(status, statusModel);
return statusModel;
}
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using PDTech.OA.Model;
namespace PDTech.OA.BLL
{
/// <summary>
/// 资金来源基础信息表
/// </summary>
public partial class FUNDS_INFO
{
private readonly PDTech.OA.DAL.FUNDS_INFO dal=new PDTech.OA.DAL.FUNDS_INFO();
public FUNDS_INFO()
{}
#region BasicMethod
/// <summary>
/// 获取资金来源数据列表
/// </summary>
/// <param name="where">条件</param>
/// <returns></returns>
public IList<Model.FUNDS_INFO> get_fundsList(Model.FUNDS_INFO where)
{
return dal.get_fundsList(where);
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
using SubSonic.Query;
namespace Pes.Core
{
public class Testt
{
public Permission Permission { set; get; }
public AccountPermission AccountPermission { set; get; }
public Account Account { set; get; }
}
public partial class Permission
{
public static List<Testt> Test(int accountID)
{
var permissions = (from p in Permission.All()
join ap in AccountPermission.All()
on p.PermissionID equals ap.PermissionID
join a in Account.All()
on ap.AccountID equals a.AccountID
where a.AccountID == accountID
select new
{
p,
ap,
a
}).Take(1);
List<Testt> list = new List<Testt>();
foreach (var item in permissions.ToList())
{
Testt t = new Testt();
t.Account = item.a;
t.AccountPermission = item.ap;
t.Permission = item.p;
list.Add(t);
}
return list;
}
public static List<Permission> GetPermissionsByAccountID(int accountID)
{
var permissions = from p in Permission.All()
join ap in AccountPermission.All()
on p.PermissionID equals ap.PermissionID
join a in Account.All()
on ap.AccountID equals a.AccountID
where a.AccountID == accountID
select p;
return permissions.ToList();
}
public static Permission GetPermissionByName(string name)
{
return Permission.Single(x => x.Name == name);
}
public static Permission GetPermissionByID(int permissionID)
{
return Permission.Single(x => x.PermissionID == permissionID);
}
}
} |
/**
*
* Copyright (c) SEIKO EPSON CORPORATION 2016 - 2017. All rights reserved.
*
*/
using UnityEngine;
using System.Collections;
#if UNITY_5_3_OR_NEWER
using UnityEngine.SceneManagement;
#endif
public class SceneSwitcher : MonoBehaviour
{
public string previousScene;
public string nextScene;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.LeftArrow))
{
Debug.Log(previousScene);
#if UNITY_5_3_OR_NEWER
SceneManager.LoadSceneAsync(previousScene, LoadSceneMode.Single);
#else
Application.LoadLevel(previousScene);
#endif
}
if (Input.GetKeyDown (KeyCode.RightArrow))
{
Debug.Log(nextScene);
#if UNITY_5_3_OR_NEWER
SceneManager.LoadSceneAsync(nextScene, LoadSceneMode.Single);
#else
Application.LoadLevel(nextScene);
#endif
}
}
}
|
using HangoutsDbLibrary.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace HangoutsDbLibrary.Data
{
public class HangoutsContext : DbContext
{
public HangoutsContext(DbContextOptions<HangoutsContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Chat> Chats { get; set; }
public DbSet<Plan> Plans { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Activity> Activities { get; set; }
public DbSet<Interest> Interests { get; set; }
public DbSet<GroupAdmin> GroupAdmins { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<Location> Location { get; set; }
public DbSet<GroupActivity> GroupActivities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Plan>().ToTable("Plan");
modelBuilder.Entity<Group>().ToTable("Group");
modelBuilder.Entity<Chat>().ToTable("Chat");
modelBuilder.Entity<Activity>().ToTable("Activity");
modelBuilder.Entity<Interest>().ToTable("Interest");
modelBuilder.Entity<GroupAdmin>().ToTable("GroupAdmin");
modelBuilder.Entity<Location>().ToTable("Location");
modelBuilder.Entity<UserGroup>().ToTable("UserGroup");
modelBuilder.Entity<GroupActivity>().ToTable("GroupActivity");
//Ignored Chat type
modelBuilder.Ignore<Chat>();
modelBuilder.Entity<User>()
.Property(u => u.Fullname)
.IsRequired();
modelBuilder.Entity<User>()
.Property(u => u.Username)
.IsRequired();
//Ont To Many Relationship
//One Group to Many Plans
modelBuilder.Entity<Plan>()
.HasOne(g => g.Group)
.WithMany(p => p.Plans);
//One Location to Many Activities
modelBuilder.Entity<Activity>()
.HasOne(l => l.Location)
.WithMany(a => a.Activities);
//One User to Many Interests
modelBuilder.Entity<Interest>()
.HasOne(u => u.User)
.WithMany(i => i.Interests);
//One to one
//GroupAdmin - Group
modelBuilder.Entity<Group>()
.HasOne(g => g.Admin)
.WithOne(ga => ga.Group)
.HasForeignKey<GroupAdmin>(g => g.GroupAdminForeignKey); //always specify a foreing key for one-to-one rel.
//Many To Many
//Group - UserGroup - User
//Many to many User -> Group(via UserGroup)
//User - Group Many to many
modelBuilder.Entity<UserGroup>()
.HasKey(ug => new { ug.UserId, ug.GroupId });
modelBuilder.Entity<UserGroup>()
.HasOne(ug => ug.Group)
.WithMany(u => u.UserGroups)
.HasForeignKey(ug => ug.GroupId);
modelBuilder.Entity<UserGroup>()
.HasOne(ug => ug.User)
.WithMany(u => u.UserGroups)
.HasForeignKey(ug => ug.UserId);
//Group - Activity many-to-many
modelBuilder.Entity<GroupActivity>()
.HasKey(ga => new { ga.ActivityId, ga.GroupId });
modelBuilder.Entity<GroupActivity>()
.HasOne(ga => ga.Group)
.WithMany(g => g.GroupActivity)
.HasForeignKey(ga => ga.GroupId);
modelBuilder.Entity<GroupActivity>()
.HasOne(ga => ga.Activity)
.WithMany(a => a.GroupActivity)
.HasForeignKey(ga => ga.ActivityId);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(Configuration.ConnectionString);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Extension_Methods_Delegates_Lambda_LINQ
{
/// <summary>
/// Problem 2. IEnumerable extensions
/// Implement a set of extension methods for IEnumerable<T> that implement the following group functions: sum, product, min, max, average.
/// </summary>
static class IEnumerableExtensions
{
public static T SumExt<T>(this IEnumerable<T> source)
{
T sum = (dynamic)0;
foreach (var item in source)
{
sum += (dynamic)item;
}
return sum;
}
public static T ProductExt<T>(this IEnumerable<T> source)
{
T sum = (dynamic)1;
foreach (var item in source)
{
sum *= (dynamic)item;
}
return sum;
}
public static T MinExt<T>(this IEnumerable<T> source)
{
return source.Min<T>();
}
public static T MaxExt<T>(this IEnumerable<T> source)
{
return source.Max<T>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIscript : MonoBehaviour {
private bool showBar;
private float showStamp;
private bool takingDamage;
public float fadeDelay;
public float xSize;
public float ySize;
public Texture image;
public float xOffset;
public float yOffset;
private float maxHP;
private float HP;
// Use this for initialization
void Start () {
if (this.gameObject.tag.Equals ("Player")) {
maxHP = this.gameObject.GetComponent<Player> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Enemy")) {
maxHP = this.gameObject.GetComponent<Enemy> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Alpaca")) {
maxHP = this.gameObject.GetComponent<Alpaca> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Boss")) {
maxHP = this.gameObject.GetComponent<Boss> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Slime")) {
maxHP = this.gameObject.GetComponent<Slime> ().getHealth ();
}
}
// Update is called once per frame
void Update () {
if (this.gameObject.tag.Equals ("Player")) {
HP = this.gameObject.GetComponent<Player> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Enemy")) {
HP = this.gameObject.GetComponent<Enemy> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Alpaca")) {
HP = this.gameObject.GetComponent<Alpaca> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Boss")) {
HP = this.gameObject.GetComponent<Boss> ().getHealth ();
} else if (this.gameObject.tag.Equals ("Slime")) {
HP = this.gameObject.GetComponent<Slime> ().getHealth ();
}
if (takingDamage == false) {
showStamp = Time.time;
}
if (takingDamage == true && Time.time - showStamp < fadeDelay) {
showBar = true;
} else {
showBar = false;
takingDamage = false;
}
}
public void takeDamage(){
takingDamage = true;
}
void OnGUI(){
if (showBar) {
GUI.DrawTexture (new Rect (
new Vector2(Camera.main.WorldToScreenPoint (new Vector3(this.gameObject.transform.position.x,
this.gameObject.transform.position.y, this.gameObject.transform.position.z)).x + xOffset,
Screen.height - Camera.main.WorldToScreenPoint(new Vector3(this.gameObject.transform.position.x,
this.gameObject.transform.position.y, this.gameObject.transform.position.z)).y + yOffset),
new Vector2 (xSize * HP / maxHP, ySize)), image);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using Whale.DAL.Models;
namespace Whale.Shared.Models
{
public class UserModel
{
[Required]
public string DisplayName { get; set; }
public string PhotoUrl { get; set; }
public LinkTypeEnum LinkType { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public string Phone { get; set; }
}
}
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace Squidex.Infrastructure.Caching
{
public sealed class ReplicatedCache : IReplicatedCache
{
private readonly Guid instanceId = Guid.NewGuid();
private readonly IMemoryCache memoryCache;
private readonly IPubSub pubSub;
private readonly ReplicatedCacheOptions options;
public class InvalidateMessage
{
public Guid Source { get; set; }
public string Key { get; set; }
}
public ReplicatedCache(IMemoryCache memoryCache, IPubSub pubSub, IOptions<ReplicatedCacheOptions> options)
{
Guard.NotNull(memoryCache, nameof(memoryCache));
Guard.NotNull(pubSub, nameof(pubSub));
Guard.NotNull(options, nameof(options));
this.memoryCache = memoryCache;
this.pubSub = pubSub;
if (options.Value.Enable)
{
this.pubSub.Subscribe(OnMessage);
}
this.options = options.Value;
}
private void OnMessage(object message)
{
if (message is InvalidateMessage invalidate && invalidate.Source != instanceId)
{
memoryCache.Remove(invalidate.Key);
}
}
public void Add(string key, object? value, TimeSpan expiration, bool invalidate)
{
if (!options.Enable)
{
return;
}
memoryCache.Set(key, value, expiration);
if (invalidate)
{
Invalidate(key);
}
}
public void Remove(string key)
{
if (!options.Enable)
{
return;
}
memoryCache.Remove(key);
Invalidate(key);
}
public bool TryGetValue(string key, out object? value)
{
if (!options.Enable)
{
value = null;
return false;
}
return memoryCache.TryGetValue(key, out value);
}
private void Invalidate(string key)
{
if (!options.Enable)
{
return;
}
pubSub.Publish(new InvalidateMessage { Key = key, Source = instanceId });
}
}
}
|
using UnityEngine;
public class Arrow : MonoBehaviour
{
private GameObject lightPrefab;
private GameObject light;
#region Unity lifecycle
private void Awake()
{
lightPrefab = Resources.Load<GameObject>("ArrowLight");
ArchTorso.Shoot += this.Shoot;
Light.AddLight += Arrow_OnAddLight;
Finish.FinishLevel += Arrow_OnFinishLevel;
PlayerManager.ReloadGame += Arrow_OnFinishLevel;
if (Managers.Player.HasLigth)
{
Arrow_OnAddLight();
}
}
private void OnDestroy()
{
ArchTorso.Shoot -= this.Shoot;
Light.AddLight -= Arrow_OnAddLight;
Finish.FinishLevel -= Arrow_OnFinishLevel;
PlayerManager.ReloadGame -= Arrow_OnFinishLevel;
}
#endregion
private void Shoot(float charge, int damage)
{
Vector3 force = !Player.instance.isLookingToTheRight ? -transform.right : transform.right;
force *= charge;
if (Managers.Player.HasLigth)
BulletFactory.CreateArrowWithLight(transform, damage, force, tag);
else
BulletFactory.CreateArrow(transform, damage, force, tag);
}
private void Arrow_OnAddLight()
{
if (light == null)
{
light = Instantiate(lightPrefab);
light.transform.parent = transform;
light.transform.localScale = Vector3.one;
light.transform.localEulerAngles = Vector3.zero;
light.transform.localPosition = Vector3.zero;
Managers.Player.HasLigth = true;
}
}
private void Arrow_OnFinishLevel()
{
if (Managers.Player.HasLigth)
{
Destroy(light);
Managers.Player.HasLigth = false;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace RedLine.Models.WMI
{
public class WmiProcessQuery : WmiQueryBase
{
private static readonly string[] COLUMN_NAMES = new string[5]
{
"CommandLine",
"Name",
"ExecutablePath",
"SIDType",
"ParentProcessId"
};
public WmiProcessQuery()
: base("Win32_Process", null, COLUMN_NAMES)
{
}
public WmiProcessQuery(IEnumerable<string> processNames)
: this()
{
base.SelectQuery.Condition = string.Join(" OR ", processNames.Select((string processName) => "Name LIKE '%" + processName + "%'"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Heresy {
public static class TaskExtensions {
// TODO : add other methods that tak cancellation tokens?
// *Functor* Map
public static async Task<B> Select<A, B>(this Task<A> it, Func<A, B> transform, CancellationToken token = default) =>
transform(await it);
// *Monad* Bind
// maybe im not completely crazy https://devblogs.microsoft.com/pfxteam/tasks-monads-and-linq/
public static async Task<B> SelectMany<A, B>(this Task<A> it, Func<A, CancellationToken, Task<B>> transform, CancellationToken token = default) =>
await transform(await it, token);
public static async Task<C> SelectMany<A, B, C>(this Task<A> it, Func<A, Task<B>> transform, Func<A, B, C> selector) {
var a = await it;
var b = await transform(a);
return selector(a, b);
}
// TODO - class and struct return
public static async Task<D?> Join<A, B, C, D>(
this Task<A> it,
Task<B> other,
Func<A, C> getItKey,
Func<B, C> getOtherKey,
Func<A, B, D> mapper) where D : struct {
await Task.WhenAll(it, other); // does this let them complete such that .Result is ok?
var itKey = getItKey(it.Result);
var otherKey = getOtherKey(other.Result);
return EqualityComparer<C>.Default.Equals(itKey, otherKey)
? mapper(it.Result, other.Result)
: default;
}
// TODO : Combine? Aggregate?
}
public static class TaskExtensionRef {
public static async Task<D?> Join<A, B, C, D>(
this Task<A> it,
Task<B> other,
Func<A, C> getItKey,
Func<B, C> getOtherKey,
Func<A, B, D> mapper) where D : class {
await Task.WhenAll(it, other);
var itKey = getItKey(it.Result);
var otherKey = getOtherKey(other.Result);
return EqualityComparer<C>.Default.Equals(itKey, otherKey)
? mapper(it.Result, other.Result)
: default;
}
}
public static class TaskReturn {
// *Monad*
// TODO : consequences of an extension method on everything?
public static Task<A> Return<A>(this A it) => Task.FromResult(it);
}
}
|
namespace FundManagerDashboard.Core.Model
{
public class Stock
{
public StockType Type { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public long Id { get; set; }
}
}
|
using System;
namespace NetSiege.Api.Data
{
/// <summary>
/// Record storing the summary statistics for the entire test.
/// </summary>
public class Statistics
{
#region Properties
/// <summary>
/// The number of test hits conducted.
/// </summary>
public int Requests;
/// <summary>
/// The total time in seconds for all requests.
/// </summary>
public double Total;
/// <summary>
/// The minimum request time in seconds.
/// </summary>
public double Min;
/// <summary>
/// The maximum request time in seconds.
/// </summary>
public double Max;
/// <summary>
/// The avarage request time in seconds.
/// </summary>
public double Average
{
get { return Requests == 0 ? 0 : Total / Requests; }
}
#endregion
#region Methods
/// <summary>
/// Updates these statistics to include the results from
/// one hit.
/// </summary>
public void Update(Hit result)
{
var s = result.Time.TotalSeconds;
if (Requests == 0) {
Min = s;
Max = s;
} else {
Min = Math.Min (Min, s);
Max = Math.Max (Max, s);
}
Requests++;
Total += s;
}
/// <summary>
/// Returns a string for displaying this stats as text.
/// </summary>
public override string ToString ()
{
return string.Format ("Stats:\n\tRequests={0}\n\tAverage={1:###0.00} secs\n\tMin:{2:###0.00} secs\n\tMax:{3:###0.00} secs\n\n]", Requests, Average, Min, Max);
}
#endregion
}
}
|
using System;
using Glimpse.Agent;
using Glimpse.Server;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Glimpse.AgentServer.Dnx.Sample
{
public class Startup
{
public Startup()
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("\nGLIMPSE AGENT+SERVER (ASPNET) RUNNING ON PORT 5100");
Console.WriteLine("==================================================\n");
Console.ResetColor();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddGlimpse();
}
public void Configure(IApplicationBuilder app)
{
app.UseGlimpse();
app.Use(next => new SamplePage().Invoke);
/*
app.Use(async (context, next) => {
var response = context.Response;
response.Headers.Set("Content-Type", "text/plain");
await response.WriteAsync("TEST!");
});
*/
app.UseWelcomePage();
}
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
}
}
|
using cryptoprime;
using main_tests;
using permutationsTest;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.IO;
using System.Security.AccessControl;
namespace Test_BytesBuilder
{
/*
* Тест касается разработки расширенного алгоритма на 4096 битный ключ
*
* Этот тест пытается посмотреть, что можно сделать с Tweak, чтобы дополнительно рандомозировать перестановки
* Данный тест подсчитывает количество вариантов 32-битного tweak при разных схемах его приращения
* */
unsafe class Test_BytesBuilder: MultiThreadTest<Test_BytesBuilder.SourceTask>
{
public Test_BytesBuilder(ConcurrentQueue<TestTask> tasks): base(tasks, "Test_BytesBuilder", new Test_BytesBuilder.SourceTaskFabric())
{
}
public new class SourceTask: MultiThreadTest<SourceTask>.SourceTask
{
public readonly int Size;
public SourceTask(int Size)
{
this.Size = Size;
}
}
public new class SourceTaskFabric: MultiThreadTest<SourceTask>.SourceTaskFabric
{
public override IEnumerable<SourceTask> GetIterator()
{
yield return new SourceTask(0);
yield return new SourceTask(1);
yield return new SourceTask(2);
yield return new SourceTask(3);
yield return new SourceTask(4);
yield return new SourceTask(5);
yield return new SourceTask(11);
yield return new SourceTask(4093);
yield return new SourceTask(4094);
yield return new SourceTask(4095);
yield return new SourceTask(4096);
yield return new SourceTask(4097);
}
}
public unsafe override void StartTests()
{
var po = new ParallelOptions();
po.MaxDegreeOfParallelism = Environment.ProcessorCount;
Parallel.ForEach
(
sources, po,
delegate (SourceTask task)
{
try
{
switch (task.Size)
{
case 0: test0(task);
break;
case 1: test0(task);
break;
default:
for (int i = 0; i < 2; i++)
{
testN1(task);
testN2(task);
testN3(task);
}
break;
}
}
catch (Exception ex)
{
var e = new Error() { ex = ex, Message = "Test_BytesBuilder.StartTests: exception " + ex.Message };
this.task.error.Add(e);
}
}
); // The end of Parallel.foreach sources running
GC.Collect();
}
private void test0(SourceTask task)
{
try
{
var t8 = new byte[8];
ulong data = 0xA5A5_B5A5_A5A5_B5B5;
BytesBuilder.ULongToBytes(data, ref t8);
BytesBuilder.BytesToULong(out ulong dt, t8, 0);
if (dt != data)
{
var e = new Error() { Message = "Test_BytesBuilder.test0: ULongToBytes != BytesToULong" };
this.task.error.Add(e);
}
BytesBuilder.BytesToUInt(out uint dt4, t8, 0);
if (dt4 != (uint) data)
{
var e = new Error() { Message = "Test_BytesBuilder.test0: ULongToBytes/4 != BytesToUInt" };
this.task.error.Add(e);
}
BytesBuilder.BytesToUInt(out dt4, t8, 4);
if (dt4 != (uint) (data >> 32))
{
var e = new Error() { Message = "Test_BytesBuilder.test0: ULongToBytes>>/4 != BytesToUInt" };
this.task.error.Add(e);
}
var fa = new BytesBuilderForPointers.Fixed_AllocatorForUnsafeMemory();
var b1 = new byte[8];
var r1 = fa.FixMemory(b1);
var r2 = fa.FixMemory(t8);
if (BytesBuilderForPointers.isArrayEqual_Secure(r1, r2))
{
var e = new Error() { Message = "Test_BytesBuilder.test0: isArrayEqual_Secure(r1, r2)" };
this.task.error.Add(e);
}
BytesBuilder.CopyTo(t8, b1, 0, 7);
if (BytesBuilderForPointers.isArrayEqual_Secure(r1, r2))
{
var e = new Error() { Message = "Test_BytesBuilder.test0: isArrayEqual_Secure(r1, r2) [2]" };
this.task.error.Add(e);
}
b1[7] = t8[7];
if (!BytesBuilderForPointers.isArrayEqual_Secure(r1, r2))
{
var e = new Error() { Message = "Test_BytesBuilder.test0: isArrayEqual_Secure(r1, r2) [3]" };
this.task.error.Add(e);
}
r1.Clear();
BytesBuilderForPointers.BytesToULong(out dt, r2, 0, 8);
if (dt != data)
{
var e = new Error() { Message = "Test_BytesBuilder.test0: ULongToBytes != BytesToULong (BytesBuilderForPointers)" };
this.task.error.Add(e);
}
r1.Dispose();
r2.Dispose();
using (new BytesBuilderStatic(task.Size))
{
var e = new Error() { Message = "Test_BytesBuilder.test0: нет исключения" };
this.task.error.Add(e);
}
}
catch (ArgumentOutOfRangeException)
{}
catch (Exception ex)
{
var e = new Error() { ex = ex, Message = "Test_BytesBuilder.test0: exception " + ex.Message };
this.task.error.Add(e);
}
}
private void testN1(SourceTask task)
{
using (var bbs = new BytesBuilderStatic(task.Size))
{
var bbp = new BytesBuilderForPointers();
var bbb = new BytesBuilder();
var allocator = new BytesBuilderForPointers.AllocHGlobal_AllocatorForUnsafeMemory();
var fix = new BytesBuilderForPointers.Fixed_AllocatorForUnsafeMemory();
for (int size = 1; size <= task.Size; size++)
{
BytesBuilderForPointers.Record res_bbs = null, res_bbb = null, res_bbp = null, res_bbs2 = null, r = null;
try
{
try
{
byte V = 1;
r = allocator.AllocMemory(size);
while (bbb.Count + size <= size)
{
for (int i = 0; i < r.len; i++)
r.array[i] = V++;
bbs.add(r);
bbp.addWithCopy(r, r.len, allocator);
for (int i = 0; i < r.len; i++)
bbb.addByte(r.array[i]);
}
r.Dispose();
res_bbs = bbs.getBytes();
res_bbp = bbp.getBytes();
res_bbb = fix.FixMemory(bbb.getBytes());
bbs.Resize(bbs.size + 1);
res_bbs2 = bbs.getBytes();
}
finally
{
bbs.Clear();
bbp.Clear();
bbb.Clear();
}
if (!BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbp) || !BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbb) || !BytesBuilderForPointers.isArrayEqual_Secure(res_bbs2, res_bbb))
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + " unequal");
}
finally
{
res_bbs ?.Dispose();
res_bbp ?.Dispose();
res_bbb ?.Dispose();
res_bbs2?.Dispose();
}
}
}
}
private void testN2(SourceTask task)
{
using (var bbs = new BytesBuilderStatic(task.Size))
{
var bbp = new BytesBuilderForPointers();
var bbb = new BytesBuilder();
var allocator = new BytesBuilderForPointers.AllocHGlobal_AllocatorForUnsafeMemory();
var fix = new BytesBuilderForPointers.Fixed_AllocatorForUnsafeMemory();
for (int size = 2; size <= task.Size; size++)
{
BytesBuilderForPointers.Record res_bbs = null, res_bbp = null, res_bbb = null;
try
{
try
{
byte V = 1;
var r = allocator.AllocMemory(size);
// var r2 = allocator.AllocMemory(size >> 1);
while (bbb.Count + size <= size)
{
for (int i = 0; i < r.len; i++)
r.array[i] = V++;
bbs.add(r);
bbp.addWithCopy(r, r.len, allocator);
for (int i = 0; i < r.len; i++)
bbb.addByte(r.array[i]);
}
r.Dispose();
r = null;
var remainder = size - ((size >> 1) << 1);
res_bbs = allocator.AllocMemory(size >> 1);
bbs.RemoveBytes(size >> 1);
bbs.getBytesAndRemoveIt(res_bbs, size >> 1);
if (bbs.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbs.Count > 1: " + bbs.Count);
res_bbp = allocator.AllocMemory(size >> 1);
bbp.getBytesAndRemoveIt(res_bbp);
bbp.getBytesAndRemoveIt(res_bbp);
if (bbp.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbp.Count > 1: " + bbp.Count);
bbb.getBytesAndRemoveIt(resultCount: size >> 1);
res_bbb = fix.FixMemory(bbb.getBytesAndRemoveIt(resultCount: size >> 1));
if (bbb.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbb.Count > 1: " + bbb.Count);
}
finally
{
bbs.Clear();
bbp.Clear();
bbb.Clear();
}
if (!BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbp) || !BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbb))
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + " unequal");
}
finally
{
res_bbs?.Dispose();
res_bbp?.Dispose();
res_bbb?.Dispose();
}
}
}
}
private void testN3(SourceTask task)
{
for (int cst = 1; cst < 11 && cst < task.Size; cst++)
using (var bbs = new BytesBuilderStatic(task.Size))
{
var bbp = new BytesBuilderForPointers();
var bbb = new BytesBuilder();
var allocator = new BytesBuilderForPointers.AllocHGlobal_AllocatorForUnsafeMemory();
var fix = new BytesBuilderForPointers.Fixed_AllocatorForUnsafeMemory();
int size = task.Size;
{
BytesBuilderForPointers.Record res_bbs = null, res_bbp = null, res_bbb = null;
try
{
try
{
byte V = 1;
var r = allocator.AllocMemory(size - 1);
// var r2 = allocator.AllocMemory(size >> 1);
while (bbb.Count < size - 1)
{
for (int i = 0; i < r.len; i++)
r.array[i] = V++;
bbs.add(r);
bbp.addWithCopy(r, r.len, allocator);
for (int i = 0; i < r.len; i++)
bbb.addByte(r.array[i]);
}
bbs.add(r.array, 1);
bbp.addWithCopy(r.array, 1, allocator);
bbb.addByte(r.array[0]);
r.Dispose();
r = null;
int remainder = size;
do
{
remainder -= cst;
try
{
res_bbs = allocator.AllocMemory(cst);
bbs.getBytesAndRemoveIt(res_bbs);
if (bbs.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbs.Count > 1: " + bbs.Count);
res_bbp = allocator.AllocMemory(cst);
bbp.getBytesAndRemoveIt(res_bbp);
if (bbp.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbp.Count > 1: " + bbp.Count);
res_bbb = fix.FixMemory(bbb.getBytesAndRemoveIt(resultCount: cst));
if (bbb.Count != remainder)
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + ", bbb.Count > 1: " + bbb.Count);
if (!BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbp) || !BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbb))
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + " unequal");
}
finally
{
res_bbs?.Dispose();
res_bbp?.Dispose();
res_bbb?.Dispose();
res_bbs = null;
res_bbp = null;
res_bbb = null;
}
try
{
res_bbs = bbs.getBytes();
res_bbp = bbp.getBytes();
res_bbb = fix.FixMemory(bbb.getBytes());
if (!BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbp) || !BytesBuilderForPointers.isArrayEqual_Secure(res_bbs, res_bbb))
throw new Exception("Test_BytesBuilder.testN: size = " + task.Size + " unequal [2]");
}
finally
{
res_bbs?.Dispose();
res_bbp?.Dispose();
res_bbb?.Dispose();
res_bbs = null;
res_bbp = null;
res_bbb = null;
}
}
while (bbs.Count > cst);
}
finally
{
bbs.Clear();
bbp.Clear();
bbb.Clear();
}
}
finally
{
res_bbs?.Dispose();
res_bbp?.Dispose();
res_bbb?.Dispose();
res_bbs = null;
res_bbp = null;
res_bbb = null;
}
}
}
}
}
}
|
using DevExpress.XtraLayout.Localization;
namespace TLF.Framework.ControlLocalization
{
/// <summary>
/// Layout Control Library를 한국어로 설정합니다.
/// </summary>
public class KoreanLayoutLocalizer : DevExpress.XtraLayout.Localization.LayoutLocalizer
{
#region :: 생성자 ::
/// <summary>
/// 생성자
/// </summary>
public KoreanLayoutLocalizer()
{
}
#endregion
#region :: GetLocalizedString :: Layout Control에서 보여지는 Text를 설정합니다.
/// <summary>
/// Layout Control에서 보여지는 Text를 설정합니다.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public override string GetLocalizedString(LayoutStringId id)
{
switch (id)
{
case LayoutStringId.CustomizationFormTitle: return "사용자 정의 Layout";
}
return base.GetLocalizedString(id);
}
#endregion
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ninject;
using System.Diagnostics;
using Webcorp.Business;
using Webcorp.Dal;
using Webcorp.Model;
using Webcorp.Controller;
using System.Threading.Tasks;
namespace Webcorp.erp.tests
{
/// <summary>
/// Description résumée pour TestCommandes
/// </summary>
[TestClass]
public class TestCommandes
{
public TestCommandes()
{
//
// TODO: ajoutez ici la logique du constructeur
//
}
private TestContext testContextInstance;
/// <summary>
///Obtient ou définit le contexte de test qui fournit
///des informations sur la série de tests active, ainsi que ses fonctionnalités.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Attributs de tests supplémentaires
//
// Vous pouvez utiliser les attributs supplémentaires suivants lorsque vous écrivez vos tests :
//
// Utilisez ClassInitialize pour exécuter du code avant d'exécuter le premier test de la classe
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Utilisez ClassCleanup pour exécuter du code une fois que tous les tests d'une classe ont été exécutés
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Utilisez TestInitialize pour exécuter du code avant d'exécuter chaque test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Utilisez TestCleanup pour exécuter du code après que chaque test a été exécuté
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
static IKernel kernel;
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
Debug.WriteLine("ClassInit " + context.TestName);
kernel = Helper.CreateKernel(new TestModule(), new BusinessIoc(), new DalIoc());
var auth = kernel.Get<IAuthenticationService>();
var uh = kernel.Get<IUtilisateurBusinessHelper<Utilisateur>>();
uh.DeleteAll().Wait();
uh.Create("999", "jcambert", "korben90", "Ambert", "Jean-Christophe", "jc.ambert@gmail.com")
.ContinueWith(x =>
{
uh.AddRole(x.Result, "Administrateur");
})
.ContinueWith(x =>
{
uh.Save();
}).ContinueWith(x =>
{
var islogin = auth.Login("999", "jcambert", "korben90");
Assert.IsTrue(islogin.Result);
}).Wait()
;
Helper.CreateStandardPParametres(true).Wait();
Helper.CreateStandardParametres(true).Wait();
}
[TestMethod]
public async Task TestCommande1()
{
try {
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
ch.DeleteAll().Wait();
Societe s = new Societe() { Nom = "Societe test" };
var cde = await ch.Create(CommandeType.Client);
Assert.IsNotNull(cde);
//cde.Numero = 1234;
cde.Tiers = s;
cde = await ch.Create(CommandeType.Fournisseur);
Assert.IsNotNull(cde);
ch.Save().Wait();
}catch(Exception )
{
}
}
[TestMethod]
public async Task TestCreateCommandeClient1()
{
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
ch.DeleteAll().Wait();
var cde = await ch.Create(CommandeType.Client);
Assert.IsNotNull(cde);
}
[TestMethod]
public async Task TestCommande2()
{
// try
// {
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
var bh = kernel.Get<IArticleBusinessHelper<Article>>();
ch.DeleteAll().Wait();
bh.DeleteAll().Wait();
var pf = await bh.Create("PF",ArticleType.ProduitFini);
var sf = await bh.Create("SF",ArticleType.ProduitSemiFini);
var ssf = await bh.Create("SSF",ArticleType.ProduitSemiFini);
pf.Libelle = "Libelle PF";
sf.Libelle = "Libelle SF";
ssf.Libelle = "Libelle SSF";
bh.Save().Wait();
sf.Nomenclatures.Add(new Nomenclature(ssf) { Ordre = 20, Libelle = ssf.Libelle, Quantite = 20 });
pf.Nomenclatures.Add(new Nomenclature(sf) { Ordre = 10, Libelle = sf.Libelle, Quantite = 10 });
bh.Save().Wait();
pf.Libelle = "Other Libelle PF";
bh.Save().Wait();
Societe s = new Societe() { Nom = "Societe test" };
var cde = await ch.Create(CommandeType.Client);
Assert.IsNotNull(cde);
cde.Tiers = s;
cde.Lignes.Add(new LigneCommande() { ArticleInner = pf, QuantiteCommandee = 10, Prixunitaire = new unite.Currency(15.5) });
ch.Save().Wait();
/* }
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
}*/
}
[TestMethod,ExpectedException(typeof(InvalidOperationException))]
public async Task TestCommandClientAvecArticleSST1()
{
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
var bh = kernel.Get<IArticleBusinessHelper<Article>>();
ch.DeleteAll().Wait();
bh.DeleteAll().Wait();
var sst = await bh.Create("ArticleST",ArticleType.SousTraitance);
sst.Libelle = "Peinture";
var result=await sst.Save();
Assert.IsTrue(result==1);
var cde = await ch.Create(CommandeType.Client);
var result0= await ch.Save();
Assert.IsTrue(result==1);
var ligne = new LigneCommande(cde) { ArticleInner = sst, QuantiteCommandee = 5, Prixunitaire = new unite.Currency(5) };
cde.Lignes.Add(ligne);
ch.Save().Wait();
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public async Task TestCommandeFournisseurAvecArticleNonSST1()
{
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
var bh = kernel.Get<IArticleBusinessHelper<Article>>();
ch.DeleteAll().Wait();
bh.DeleteAll().Wait();
var sst = await bh.Create("ArticleST",ArticleType.ProduitFini);
sst.Libelle = "Peinture";
var result = await sst.Save();
Assert.IsTrue(result==1);
var cde = await ch.Create(CommandeType.Fournisseur);
var result0 = await ch.Save();
Assert.IsTrue(result==1);
var ligne = new LigneCommande(cde) { ArticleInner = sst, QuantiteCommandee = 5, Prixunitaire = new unite.Currency(5) };
cde.Lignes.Add(ligne);
ch.Save().Wait();
}
[TestMethod]
public async Task TestCommandeFournisseurAvecArticleSST1()
{
var ch = kernel.Get<ICommandeBusinessHelper<Commande>>();
var bh = kernel.Get<IArticleBusinessHelper<Article>>();
ch.DeleteAll().Wait();
bh.DeleteAll().Wait();
var sst = await bh.Create("ArticleST",ArticleType.SousTraitance);
sst.Libelle = "Peinture";
var result = await sst.Save();
Assert.IsTrue(result==1);
var mp = await bh.Create("ArticleST",ArticleType.MatièrePremiere);
mp.Libelle = "Peinture";
var result0 = await sst.Save();
Assert.IsTrue(result0==1);
var cde = await ch.Create(CommandeType.Fournisseur);
//var result1 = await ch.Save();
// Assert.IsTrue(!result1.HasError());
ch.Save().Wait();
Assert.IsTrue(cde.Id != "");
var ligne0 = new LigneCommande(cde) { ArticleInner = sst, QuantiteCommandee = 5, Prixunitaire = new unite.Currency(5) };
cde.Lignes.Add(ligne0);
var ligne1 = new LigneCommande(cde) { ArticleInner = mp, QuantiteCommandee = 15, Prixunitaire = new unite.Currency(500) };
cde.Lignes.Add(ligne1);
ch.Save().Wait();
}
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public static class ChannelMappingMethods
{
private static JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddTHH:mm:ss.ffZ"};
}
} |
namespace Mutagen.Bethesda.FormKeys.SkyrimSE
{
public class AnimatedArmoury
{
public class Keyword
{
private static readonly ModKey AnimatedArmoury = ModKey.FromNameAndExtension("NewArmoury.esp");
public static readonly FormLink<IKeywordCommonGetter> WeapTypeCestus = AnimatedArmoury.MakeFormKey(0x19aab3);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeClaw = AnimatedArmoury.MakeFormKey(0x19aab4);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeHalberd = AnimatedArmoury.MakeFormKey(0x0e4580);
public static readonly FormLink<IKeywordCommonGetter> WeapTypePike = AnimatedArmoury.MakeFormKey(0x0e457e);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeQtrStaff = AnimatedArmoury.MakeFormKey(0x0e4581);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeRapier = AnimatedArmoury.MakeFormKey(0x000801);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeSpear = AnimatedArmoury.MakeFormKey(0x0e457f);
public static readonly FormLink<IKeywordCommonGetter> WeapTypeWhip = AnimatedArmoury.MakeFormKey(0x20f2a1);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace CarWash.PWA.Extensions
{
/// <summary>
/// Extension class to User.Claims
/// </summary>
public static class ClaimsExtension
{
/// <summary>
/// Checks whether user is admin
/// usage: httpContextAccessor.HttpContext.User.Claims.IsAdmin()
/// </summary>
/// <param name="claims">User.Claims</param>
/// <returns>true if admin</returns>
public static bool IsAdmin(this IEnumerable<Claim> claims)
{
var adminClaim = claims.SingleOrDefault(c => c.Type == "admin");
if (adminClaim == null) return false;
return adminClaim.Value == "true";
}
/// <summary>
/// Checks whether user is carwash admin
/// usage: httpContextAccessor.HttpContext.User.Claims.IsCarwashAdmin()
/// </summary>
/// <param name="claims">User.Claims</param>
/// <returns>true if carwash admin</returns>
public static bool IsCarwashAdmin(this IEnumerable<Claim> claims)
{
var adminClaim = claims.SingleOrDefault(c => c.Type == "carwashadmin");
if (adminClaim == null) return false;
return adminClaim.Value == "true";
}
}
}
|
using GetLabourManager.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
namespace GetLabourManager.Configuration
{
public class FieldContainersTypeConfiguration:EntityTypeConfiguration<FieldContainersType>
{
public FieldContainersTypeConfiguration()
{
Property(x => x.ContainerType).HasMaxLength(30).IsRequired();
}
}
} |
using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit.IocExtentions.Resolvers;
using Xunit.Sdk;
namespace Xunit.IocExtentions.Attributes
{
public class AutofacDataAttribute : DataAttribute
{
private readonly Type _typeToResolve;
private readonly object[] _data;
public AutofacDataAttribute(Type typeToResolve, params object[] data)
{
_typeToResolve = typeToResolve;
_data = data;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
var resultList = new List<object>();
var typeResolver = new AutofacTypeResolver(testMethod.GetCustomAttributes<DependencyAttribute>(), _typeToResolve);
resultList.Add(typeResolver.Resolve());
resultList.AddRange(_data);
return new object[1][] { resultList.ToArray() };
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Parser.main.BotClasses
{
public class RgDescriptions
{
public string appid { get; set; }
public string classid { get; set; }
public string appinstanceidid { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string type { get; set; }
public Descriptions[] descriptions { get; set; }
public Tags[] tags { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;
namespace AuthProject.Identities
{
public sealed class CustomIdentityUser : IdentityUser
{
public CustomIdentityUser()
{
PasswordHashEntity = string.Empty;
}
public CustomIdentityUser(string email, string username, string passwordHash)
{
Email = email;
UserName = username;
PasswordHash = passwordHash;
}
[NotMapped]
public string PasswordHashEntity { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Planning.AdvandcedProjectionActionSelection.PrivacyLeakageCalculation
{
class TraceVariable
{
public int agentID { get; set; }
public int varID { get; set; }
public string varName { get; set; }
public bool isPrivate { get; set; }
public int range { get; set; }
public Dictionary<int, string> vals { get; set; }
private static Dictionary<int, Dictionary<Predicate, TraceVariable>> agentsVariables = new Dictionary<int, Dictionary<Predicate, TraceVariable>>();
public TraceVariable(int agentID, int varID, string varName, bool isPrivate, int range, Dictionary<int, string> vals)
{
this.agentID = agentID;
this.varID = varID;
this.varName = varName;
this.isPrivate = isPrivate;
this.range = range;
this.vals = vals;
}
public static Tuple<List<TraceVariable>, int> getVariables(Agent agent)
{
HashSet<GroundedPredicate> publicPredicates = new HashSet<GroundedPredicate>(agent.PublicPredicates);
HashSet<GroundedPredicate> allPredicates = new HashSet<GroundedPredicate>(agent.Predicates);
HashSet<GroundedPredicate> privatePredicates = new HashSet<GroundedPredicate>(allPredicates.Except(publicPredicates));
RemoveNegations(publicPredicates);
RemoveNegations(privatePredicates);
int agentID = agent.getID();
int varID = 0;
Dictionary<Predicate, TraceVariable> myVariables = new Dictionary<Predicate, TraceVariable>();
agentsVariables.Add(agentID, myVariables);
List<TraceVariable> variables = createVariables(myVariables, publicPredicates, agentID, varID, false);
int amountOfPublicVariables = variables.Count;
varID = variables.Count;
variables.AddRange(createVariables(myVariables, privatePredicates, agentID, varID, true));
Tuple<List<TraceVariable>, int> tuple = new Tuple<List<TraceVariable>, int>(variables, amountOfPublicVariables);
return tuple;
}
public static void ClearTraces()
{
agentsVariables = new Dictionary<int, Dictionary<Predicate, TraceVariable>>();
}
private static List<TraceVariable> createVariables(Dictionary<Predicate, TraceVariable> myVariables, HashSet<GroundedPredicate> predicates, int agentID, int startVarID, bool isPrivate)
{
List<TraceVariable> variables = new List<TraceVariable>();
foreach(GroundedPredicate p in predicates)
{
Dictionary<int, string> vals = new Dictionary<int, string>();
vals.Add(0, p.ToString());
Predicate negation = p.Negate();
vals.Add(1, negation.ToString());
TraceVariable variable = new TraceVariable(agentID, startVarID, "var" + startVarID, isPrivate, 2, vals);
variables.Add(variable);
myVariables.Add(p, variable);
startVarID++;
}
return variables;
}
private static void RemoveNegations(HashSet<GroundedPredicate> set)
{
List<GroundedPredicate> removeList = new List<GroundedPredicate>();
foreach(GroundedPredicate groundedPredicate in set)
{
if (groundedPredicate.Negation)
{
removeList.Add(groundedPredicate);
}
}
foreach(GroundedPredicate p in removeList)
{
set.Remove(p);
}
}
public static TraceVariable GetVariable(int agentID, Predicate p)
{
if (!agentsVariables[agentID].ContainsKey(p))
{
return null;
}
return agentsVariables[agentID][p];
}
public static Dictionary<Predicate, TraceVariable> GetVariablesDict(int agentID)
{
return agentsVariables[agentID];
}
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using CGCN.Framework;
using Npgsql;
using NpgsqlTypes;
using CGCN.DataAccess;
using PhieuNhapKho.DataAccess;
using HoaDonDataAccess.BusinesLogic;
namespace PhieuNhapKho.BusinesLogic
{
/// <summary>
/// Mô tả thông tin cho bảng tblhangnhapkho
/// Cung cấp các hàm xử lý, thao tác với bảng tblhangnhapkho
/// Người tạo (C): tuanva
/// Ngày khởi tạo: 03/12/2015
/// </summary>
public class tblhangnhapkhoBL
{
private tblhangnhapkho objtblhangnhapkhoDA = new tblhangnhapkho();
public tblhangnhapkhoBL() { objtblhangnhapkhoDA = new tblhangnhapkho(); }
#region Public Method
/// <summary>
/// Lấy toàn bộ dữ liệu từ bảng tblhangnhapkho
/// </summary>
/// <returns>DataTable</returns>
public DataTable GetAll()
{
return objtblhangnhapkhoDA.GetAll();
}
/// <summary>
/// Hàm lấy tblhangnhapkho theo mã
/// </summary>
/// <returns>Trả về objtblhangnhapkho </returns>
public tblhangnhapkho GetByID(string strid)
{
return objtblhangnhapkhoDA.GetByID(strid);
}
/// <summary>
/// Hàm lấy danh sách mặt hàng theo mã phiếu nhập kho
/// </summary>
/// <param name="stridpn">Mã phiếu nhập kho kiểu string</param>
/// <returns>DataTable</returns>
public DataTable GetByIDPN(string stridpn)
{ return objtblhangnhapkhoDA.GetByIDPN(stridpn); }
/// <summary>
/// Thêm mới dữ liệu vào bảng: tblhangnhapkho
/// </summary>
/// <param name="obj">objtblhangnhapkho</param>
/// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns>
public string Insert(tblhangnhapkho objtblhangnhapkho)
{
return objtblhangnhapkhoDA.Insert(objtblhangnhapkho);
}
/// <summary>
/// Cập nhật dữ liệu vào bảng: tblhangnhapkho
/// </summary>
/// <param name="obj">objtblhangnhapkho</param>
/// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns>
public string Update(tblhangnhapkho objtblhangnhapkho)
{
return objtblhangnhapkhoDA.Update(objtblhangnhapkho);
}
/// <summary>
/// Xóa dữ liệu từ bảng tblhangnhapkho
/// </summary>
/// <returns></returns>
public string Delete(string strid)
{
return objtblhangnhapkhoDA.Delete(strid);
}
/// <summary>
/// Hàm lấy tất cả dữ liệu trong bảng tblhangnhapkho
/// </summary>
/// <returns>Trả về List<<tblhangnhapkho>></returns>
public List<tblhangnhapkho> GetList()
{
return objtblhangnhapkhoDA.GetList();
}
/// <summary>
/// Hàm lấy danh sách objtblhangnhapkho
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tblhangnhapkho>></returns>
public List<tblhangnhapkho> GetListPaged(int recperpage, int pageindex)
{
return objtblhangnhapkhoDA.GetListPaged(recperpage, pageindex);
}
/// <summary>
/// Hàm lấy danh sách objtblhangnhapkho
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tblhangnhapkho>></returns>
public DataTable GetDataTablePaged(int recperpage, int pageindex)
{
return objtblhangnhapkhoDA.GetDataTablePaged(recperpage, pageindex);
}
/// <summary>
/// Hàm tính tổng tiền mua hàng theo hóa đơn nhập
/// </summary>
/// <param name="sidpn">Mã phiếu nhập kiểu string</param>
/// <returns>Tổng tiền đã mua hàng kiểu double</returns>
public double GetTongTienByIDPN(string sidpn)
{
double tongtien = 0;
try
{
tienthanhtoanphieunhapBL ctr = new tienthanhtoanphieunhapBL();
DataTable dt = new DataTable();
dt = GetByIDPN(sidpn);
for (int i = 0; i < dt.Rows.Count; i++)
{
double tienofrow = 0;
try { tienofrow = Convert.ToDouble(dt.Rows[i]["soluong"].ToString().Trim()) * Convert.ToDouble(dt.Rows[i]["gianhap"].ToString().Trim()); }
catch { }
tongtien = tongtien + tienofrow;
}
return tongtien;
}
catch { return tongtien; }
}
#endregion
}
}
|
using System;
using System.Text;
using LePapeoGenNHibernate.CEN.LePapeo;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Exceptions;
using LePapeoGenNHibernate.EN.LePapeo;
using LePapeoGenNHibernate.Exceptions;
/*
* Clase HorarioDia:
*
*/
namespace LePapeoGenNHibernate.CAD.LePapeo
{
public partial class HorarioDiaCAD : BasicCAD, IHorarioDiaCAD
{
public HorarioDiaCAD() : base ()
{
}
public HorarioDiaCAD(ISession sessionAux) : base (sessionAux)
{
}
public HorarioDiaEN ReadOIDDefault (int id
)
{
HorarioDiaEN horarioDiaEN = null;
try
{
SessionInitializeTransaction ();
horarioDiaEN = (HorarioDiaEN)session.Get (typeof(HorarioDiaEN), id);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
return horarioDiaEN;
}
public System.Collections.Generic.IList<HorarioDiaEN> ReadAllDefault (int first, int size)
{
System.Collections.Generic.IList<HorarioDiaEN> result = null;
try
{
using (ITransaction tx = session.BeginTransaction ())
{
if (size > 0)
result = session.CreateCriteria (typeof(HorarioDiaEN)).
SetFirstResult (first).SetMaxResults (size).List<HorarioDiaEN>();
else
result = session.CreateCriteria (typeof(HorarioDiaEN)).List<HorarioDiaEN>();
}
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
return result;
}
// Modify default (Update all attributes of the class)
public void ModifyDefault (HorarioDiaEN horarioDia)
{
try
{
SessionInitializeTransaction ();
HorarioDiaEN horarioDiaEN = (HorarioDiaEN)session.Load (typeof(HorarioDiaEN), horarioDia.Id);
horarioDiaEN.Hora_ini_am = horarioDia.Hora_ini_am;
horarioDiaEN.Hora_fin_am = horarioDia.Hora_fin_am;
horarioDiaEN.Hora_ini_pm = horarioDia.Hora_ini_pm;
horarioDiaEN.Hora_fin_pm = horarioDia.Hora_fin_pm;
horarioDiaEN.Dia = horarioDia.Dia;
session.Update (horarioDiaEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
}
public int New_ (HorarioDiaEN horarioDia)
{
try
{
SessionInitializeTransaction ();
if (horarioDia.HorarioSemana != null) {
// Argumento OID y no colección.
horarioDia.HorarioSemana = (LePapeoGenNHibernate.EN.LePapeo.HorarioSemanaEN)session.Load (typeof(LePapeoGenNHibernate.EN.LePapeo.HorarioSemanaEN), horarioDia.HorarioSemana.Id);
horarioDia.HorarioSemana.HorarioDia
.Add (horarioDia);
}
session.Save (horarioDia);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
return horarioDia.Id;
}
public void Modify (HorarioDiaEN horarioDia)
{
try
{
SessionInitializeTransaction ();
HorarioDiaEN horarioDiaEN = (HorarioDiaEN)session.Load (typeof(HorarioDiaEN), horarioDia.Id);
horarioDiaEN.Hora_ini_am = horarioDia.Hora_ini_am;
horarioDiaEN.Hora_fin_am = horarioDia.Hora_fin_am;
horarioDiaEN.Hora_ini_pm = horarioDia.Hora_ini_pm;
horarioDiaEN.Hora_fin_pm = horarioDia.Hora_fin_pm;
horarioDiaEN.Dia = horarioDia.Dia;
session.Update (horarioDiaEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
}
public void Destroy (int id
)
{
try
{
SessionInitializeTransaction ();
HorarioDiaEN horarioDiaEN = (HorarioDiaEN)session.Load (typeof(HorarioDiaEN), id);
session.Delete (horarioDiaEN);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
}
public System.Collections.Generic.IList<LePapeoGenNHibernate.EN.LePapeo.HorarioDiaEN> GetHorariosDiaFromHorarioSemana (int p_horarioSemana)
{
System.Collections.Generic.IList<LePapeoGenNHibernate.EN.LePapeo.HorarioDiaEN> result;
try
{
SessionInitializeTransaction ();
//String sql = @"FROM HorarioDiaEN self where FROM HorarioDiaEN as hd where hd.HorarioSemana.Id= :p_horarioSemana";
//IQuery query = session.CreateQuery(sql);
IQuery query = (IQuery)session.GetNamedQuery ("HorarioDiaENgetHorariosDiaFromHorarioSemanaHQL");
query.SetParameter ("p_horarioSemana", p_horarioSemana);
result = query.List<LePapeoGenNHibernate.EN.LePapeo.HorarioDiaEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
//Sin e: ReadOID
//Con e: HorarioDiaEN
public HorarioDiaEN ReadOID (int id
)
{
HorarioDiaEN horarioDiaEN = null;
try
{
SessionInitializeTransaction ();
horarioDiaEN = (HorarioDiaEN)session.Get (typeof(HorarioDiaEN), id);
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
return horarioDiaEN;
}
public System.Collections.Generic.IList<HorarioDiaEN> ReadAll (int first, int size)
{
System.Collections.Generic.IList<HorarioDiaEN> result = null;
try
{
SessionInitializeTransaction ();
if (size > 0)
result = session.CreateCriteria (typeof(HorarioDiaEN)).
SetFirstResult (first).SetMaxResults (size).List<HorarioDiaEN>();
else
result = session.CreateCriteria (typeof(HorarioDiaEN)).List<HorarioDiaEN>();
SessionCommit ();
}
catch (Exception ex) {
SessionRollBack ();
if (ex is LePapeoGenNHibernate.Exceptions.ModelException)
throw ex;
throw new LePapeoGenNHibernate.Exceptions.DataLayerException ("Error in HorarioDiaCAD.", ex);
}
finally
{
SessionClose ();
}
return result;
}
}
}
|
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_37
{
public class Program
{
public static void Main()
{}
}
}
|
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using CIS420Redux.Mapping;
namespace CIS420Redux.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
#if DEBUG
////This will create database if one doesn't exist.
Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDbContext>());
////This will drop and re-create the database if model changes.
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());
#endif
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ClinicalComplianceMapping());
base.OnModelCreating(modelBuilder);
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Program> Program { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Campus> Campus { get; set; }
public DbSet<Event> Events { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.Admin> Admins { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.Advisor> Advisors { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.UdApplication> UDApplications { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.Alert> Alerts { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.Todo> Todoes { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.ClincalCompliance> ClincalCompliances { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.POS> POS { get; set; }
public System.Data.Entity.DbSet<CIS420Redux.Models.Document> Documents { get; set; }
}
} |
using Publicon.Core.Entities.Concrete;
namespace Publicon.Core.Repositories.Abstract
{
public interface INotificationRepository : IGenericRepository<Notification>, IRepository
{
}
}
|
using System;
namespace YongHongSoft.YueChi
{
/// <summary>
/// 代理人
/// </summary>
public class DLRClass
{
/// <summary>
/// 代理人姓名
/// </summary>
public string DLRXM { get; set; }
/// <summary>
///证件种类
/// </summary>
public string ZJZL { get; set; }
/// <summary>
/// 证件号
/// </summary>
public string ZJH { get; set; }
/// <summary>
/// 电话
/// </summary>
public string DHHM { get; set; }
/// <summary>
/// 宗地代码
/// </summary>
public string ZDDM { get; set; }
}
/// <summary>
/// 法定代表人
/// </summary>
public class FDDBRClass
{
/// <summary>
/// 法定代表人
/// </summary>
public string FDDBR { get; set; }
/// <summary>
/// 证件种类
/// </summary>
public string ZJZL { get; set; }
/// <summary>
/// 证件号
/// </summary>
public string ZJH { get; set; }
/// <summary>
/// 电话
/// </summary>
public string DHHM { get; set; }
/// <summary>
/// 宗地代码
/// </summary>
public string ZDDM { get; set; }
}
public class QLRClass
{
/// <summary>
/// 使用权
/// </summary>
public string SYQ { get; set; }
/// <summary>
/// 权利人类型
/// </summary>
public string QLRLX { get; set; }
/// <summary>
/// 证件种类
/// </summary>
public string ZJZL { get; set; }
/// <summary>
/// 证件号
/// </summary>
public string ZJH { get; set; }
/// <summary>
/// 通讯地址
/// </summary>
public string TXDZ { get; set; }
/// <summary>
/// 权利类型
/// </summary>
public string QLLX { get; set;}
/// <summary>
/// 权利性质
/// </summary>
public string QLXZ { get; set;}
/// <summary>
/// 土地权属来源证明材料
/// </summary>
public string ZMCL { get; set;}
/// <summary>
/// 宗地代码
/// </summary>
public string ZDDM { get; set; }
}
public class ZDFWXXClass
{/// <summary>
/// 宗地代码
/// </summary>
public string ZDDM { get; set;}
/// <summary>
/// 所有权
/// </summary>
public string SYQ { get; set; }
/// <summary>
/// 坐落
/// </summary>
public string ZL { get; set; }
/// <summary>
/// 权利设定方式
/// </summary>
public string QLSDFS { get; set; }
/// <summary>
/// 国民经济行业分类代码
/// </summary>
public string HYFL { get; set; }
/// <summary>
/// 预编宗地代码
/// </summary>
public string YBZDDM { get; set;}
/// <summary>
/// 不动产单元号
/// </summary>
public Int64 BDCDYH { get; set; }
/// <summary>
/// 比例尺
/// </summary>
public string BLC { get; set;}
/// <summary>
/// 图符号
/// </summary>
public string TFH { get; set; }
/// <summary>
/// 北至
/// </summary>
public string BZ { get; set; }
/// <summary>
/// 东至
/// </summary>
public string DZ { get; set; }
/// <summary>
/// 南至
/// </summary>
public string NZ { get; set; }
/// <summary>
/// 西至
/// </summary>
public double XZ { get; set; }
/// <summary>
/// 批准面积
/// </summary>
public double PZMJ { get; set; }
/// <summary>
/// 宗地面积
/// </summary>
public double ZDMJ { get; set;}
/// <summary>
/// 建筑占地面积
/// </summary>
public double JZZDMJ { get; set; }
/// <summary>
/// 建筑总面积
/// </summary>
public int JZZMJ { get; set; }
/// <summary>
/// 界址点个数
/// </summary>
public DateTime JZDGS { get; set; }
/// <summary>
/// 修建时间
/// </summary>
public string XJSJ { get; set; }
/// <summary>
/// 房屋结构
/// </summary>
public string FWJG { get; set; }
/// <summary>
/// 总层数
/// </summary>
public int ZCS { get; set; }
/// <summary>
/// 有无建设用地许可证
/// </summary>
public string JSYDXKZ { get; set; }
/// <summary>
/// 有无集体土地建设用地使用权证
/// </summary>
public string JTJSYDSYQZ { get; set; }
/// <summary>
/// 批准用地面积
/// </summary>
public double PZYDMJ { get; set; }
/// <summary>
/// 实测建筑面积
/// </summary>
public double SCJZMJ { get; set; }
/// <summary>
/// 有无建设规划许可证或房屋所有权证
/// </summary>
public string JSYDSYQZ { get; set; }
/// <summary>
/// 批准建筑面积
/// </summary>
public double PZJZMJ { get; set; }
/// <summary>
/// 调查员
/// </summary>
public string DCY { get; set; }
/// <summary>
/// 竣工时间
/// </summary>
public string JGSJ { get; set; }
/// <summary>
/// 备注
/// </summary>
public string BEIZHU { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Matikkapeli
{
static class Program
{
//public static string databaseFile = @"C:\Users\skype\source\repos\Matikkapeli\Matikkapeli\Database1.mdf";
public static string databaseFile = Path.GetDirectoryName(Application.ExecutablePath) + @"\Database1.mdf";
public static string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + databaseFile + ";Integrated Security=True";
public static MainMenu menu;
public static LogIn login;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
menu = new MainMenu();
login = new LogIn();
Application.Run(login);
}
public static void OpenMain(string username)
{
menu.SetUsername(username);
menu.Show();
}
public static void LogOut()
{
menu.Hide();
login.Show();
}
}
}
|
// Accord Imaging Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Imaging
{
using System;
using System.Collections.Generic;
using System.Linq;
using Accord.MachineLearning;
using Accord.Math;
using Accord.Math.Distances;
/// <summary>
/// Nearest neighbor feature point matching algorithm.
/// </summary>
///
/// <remarks>
/// <para>
/// This class matches feature points using a <see cref="KNearestNeighbors">
/// k-Nearest Neighbors</see> algorithm.</para>
/// </remarks>
///
/// <seealso cref="CorrelationMatching"/>
/// <seealso cref="RansacHomographyEstimator"/>
///
public class KNearestNeighborMatching<T>
{
/// <summary>
/// Gets or sets the number k of nearest neighbors.
/// </summary>
///
public int K { get; set; }
/// <summary>
/// Gets or sets the distance function used
/// as a distance metric between data points.
/// </summary>
///
public IDistance<T> Distance { get; set; }
/// <summary>
/// Gets or sets a minimum relevance threshold
/// used to find matching pairs. Default is 0.
/// </summary>
///
public double Threshold { get; set; }
/// <summary>
/// Constructs a new <see cref="KNearestNeighbors">
/// K-Nearest Neighbors matching</see> algorithm.
/// </summary>
///
/// <param name="k">The number of neighbors to use when matching points.</param>
/// <param name="distance">The distance function to consider between points.</param>
///
[Obsolete("Please specify the distance function using classes instead of lambda functions.")]
public KNearestNeighborMatching(int k, Func<T, T, double> distance)
: this(k, Accord.Math.Distance.GetDistance(distance))
{
}
/// <summary>
/// Constructs a new <see cref="KNearestNeighbors">
/// K-Nearest Neighbors matching</see> algorithm.
/// </summary>
///
/// <param name="k">The number of neighbors to use when matching points.</param>
/// <param name="distance">The distance function to consider between points.</param>
///
public KNearestNeighborMatching(int k, IDistance<T> distance)
{
this.K = k;
this.Distance = distance;
}
#if NET35
/// <summary>
/// Matches two sets of feature points.
/// </summary>
///
public IntPoint[][] Match<TFeaturePoint>(IEnumerable<TFeaturePoint> points1, IEnumerable<TFeaturePoint> points2)
where TFeaturePoint : IFeaturePoint<T>
{
// This overload exists to maintain compatibility with .NET 3.5 and
// is redundant when generics covariance/contravariance is available
//
return match(points1.Cast<IFeaturePoint<T>>().ToArray(),
points2.Cast<IFeaturePoint<T>>().ToArray());
}
#else
/// <summary>
/// Matches two sets of feature points.
/// </summary>
///
public IntPoint[][] Match(IEnumerable<IFeaturePoint<T>> points1, IEnumerable<IFeaturePoint<T>> points2)
{
return match(points1.ToArray(), points2.ToArray());
}
/// <summary>
/// Matches two sets of feature points.
/// </summary>
///
public IntPoint[][] Match(IFeaturePoint<T>[] points1, IFeaturePoint<T>[] points2)
{
return match(points1, points2);
}
#endif
/// <summary>
/// Matches two sets of feature points.
/// </summary>
///
private IntPoint[][] match(IFeaturePoint<T>[] points1, IFeaturePoint<T>[] points2)
{
if (points1.Length == 0 || points2.Length == 0)
throw new ArgumentException("Insufficient number of points to produce a matching.");
bool swap = false;
// We should build the classifiers with the highest number
// of training points. Thus, if we have more points in the
// second image than in the first, we'll have to swap them
if (points2.Length > points1.Length)
{
var aux = points1;
points1 = points2;
points2 = aux;
swap = true;
}
// Get the descriptors associated with each feature point
T[] features1 = new T[points1.Length];
for (int i = 0; i < features1.Length; i++)
features1[i] = points1[i].Descriptor;
T[] features2 = new T[points2.Length];
for (int i = 0; i < features2.Length; i++)
features2[i] = points2[i].Descriptor;
var knn = CreateNeighbors(features1);
double[] scores = new double[features2.Length];
int[] labels = new int[features2.Length];
for (int i = 0; i < features2.Length; i++)
labels[i] = knn.Compute(features2[i], out scores[i]);
int[] bestMatch = new int[points1.Length];
double[] bestScore = new double[points1.Length];
for (int i = 0; i < bestScore.Length; i++)
bestScore[i] = Double.PositiveInfinity;
// Get all points matching with this point
for (int j = 0; j < labels.Length; j++)
{
int i = labels[j];
if (scores[j] > Threshold)
{
if (scores[j] < bestScore[i])
{
bestScore[i] = scores[j];
bestMatch[i] = j;
}
}
}
var p1 = new List<IntPoint>(bestScore.Length);
var p2 = new List<IntPoint>(bestScore.Length);
// Get the two sets of points
for (int i = 0; i < bestScore.Length; i++)
{
IFeaturePoint<T> pi = points1[i];
if (bestScore[i] != Double.PositiveInfinity)
{
int j = bestMatch[i];
IFeaturePoint<T> pj = points2[j];
p1.Add(new IntPoint((int)pi.X, (int)pi.Y));
p2.Add(new IntPoint((int)pj.X, (int)pj.Y));
}
}
IntPoint[] m1 = p1.ToArray();
IntPoint[] m2 = p2.ToArray();
// Create matching point pairs
if (swap)
return new IntPoint[][] { m2, m1 };
return new IntPoint[][] { m1, m2 };
}
/// <summary>
/// Creates a nearest neighbor algorithm with the feature points as
/// inputs and their respective indices a the corresponding output.
/// </summary>
///
protected virtual KNearestNeighbors<T> CreateNeighbors(T[] features)
{
int classes = features.Length;
int[] outputs = new int[classes];
for (int i = 0; i < outputs.Length; i++)
outputs[i] = i;
// Create a k-Nearest Neighbor classifier to classify points
// in the second image to nearest points in the first image
return new KNearestNeighbors<T>(K, classes, features, outputs, Distance);
}
}
}
|
using DapperDB.CodeGen.Base;
using System;
using System.ComponentModel.DataAnnotations;
namespace DapperDB.Dal.Entities
{
public partial class SYS_FileDownloadLog : BaseModel
{
/// <summary>
///
/// </summary>
[Display(Name = "")]
public Int32 ID { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = "")]
public String FileName { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = "")]
public DateTime? DownDate { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = "")]
public Int32? DataCount { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using CallCenter.Common.Entities;
using CallCenterRepository.Controllers;
namespace CallCenter.Client.Communication
{
public class CustomerController : IEntityController<ICustomer>
{
private ICustomerController controller;
public CustomerController(ICustomerController controller)
{
if (controller == null)
{
throw new ArgumentNullException("controller");
}
this.controller = controller;
}
public IEnumerable<ICustomer> GetAll()
{
return this.controller.GetAll();
}
public ICustomer GetById(int id)
{
return this.controller.GetById(id);
}
public IEnumerable<ICustomer> GetByName(string entityName)
{
return this.controller.GetByName(entityName);
}
public int Insert(ICustomer customer)
{
return this.controller.Insert(customer);
}
public void DeleteById(int id)
{
this.controller.DeleteById(id);
}
}
} |
using ZJUTimetable.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Security.Credentials;
using ZJUTimetable.DataModel;
// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍
namespace ZJUTimetable
{
/// <summary>
/// 可独立使用或用于导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class Account : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public Account()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
}
/// <summary>
/// 获取与此 <see cref="Page"/> 关联的 <see cref="NavigationHelper"/>。
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
/// <summary>
/// 获取此 <see cref="Page"/> 的视图模型。
/// 可将其更改为强类型视图模型。
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// 使用在导航过程中传递的内容填充页。 在从以前的会话
/// 重新创建页时,也会提供任何已保存状态。
/// </summary>
/// <param name="sender">
/// 事件的来源; 通常为 <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">事件数据,其中既提供在最初请求此页时传递给
/// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数,又提供
/// 此页在以前会话期间保留的状态的
/// 字典。 首次访问页面时,该状态将为 null。</param>
private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
//PasswordVault value = new PasswordVault();
//if (value.FindAllByResource("zju") != null)
//{
// var passwordCredential = value.FindAllByResource("zju").First();
// UserName.Text = passwordCredential.UserName;
// MyPasswordBox.Password = passwordCredential.Password;
//}
}
/// <summary>
/// 保留与此页关联的状态,以防挂起应用程序或
/// 从导航缓存中放弃此页。值必须符合
/// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
/// </summary>
/// <param name="sender">事件的来源;通常为 <see cref="NavigationHelper"/></param>
///<param name="e">提供要使用可序列化状态填充的空字典
///的事件数据。</param>
private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
}
#region NavigationHelper 注册
/// <summary>
/// 此部分中提供的方法只是用于使
/// NavigationHelper 可响应页面的导航方法。
/// <para>
/// 应将页面特有的逻辑放入用于
/// <see cref="NavigationHelper.LoadState"/>
/// 和 <see cref="NavigationHelper.SaveState"/> 的事件处理程序中。
/// 除了在会话期间保留的页面状态之外
/// LoadState 方法中还提供导航参数。
/// </para>
/// </summary>
/// <param name="e">提供导航方法数据和
/// 无法取消导航请求的事件处理程序。</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
//change the seasonlabel
//int month = System.DateTime.Now.Month;
//if (month >= 2 && month <=8)
//{
// FirstTerm.Content = "春";
// SecondTerm.Content = "夏";
//}
//else
//{
// FirstTerm.Content = "秋";
// SecondTerm.Content = "冬";
//}
//load account info
Windows.Storage.ApplicationDataContainer localsettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (localsettings.Values.ContainsKey("userName") && localsettings.Values.ContainsKey("password"))
{
UserName.Text = localsettings.Values["userName"].ToString();
MyPasswordBox.Password = localsettings.Values["password"].ToString();
SaveButton.Content = "删除";
}
//load the season and weekNumber
if (localsettings.Values.ContainsKey("season"))
{
string season = localsettings.Values["season"].ToString();
Season.SelectedIndex = (int)Enum.Parse(typeof(Season), season) ;
}
if (localsettings.Values.ContainsKey("weekNumber")&& localsettings.Values.ContainsKey("weekDate"))
{
int weekDate = (int)localsettings.Values["weekDate"];
CurrentWeekNumber.SelectedIndex = Math.Abs((int)localsettings.Values["weekNumber"]+ (System.DateTime.Today.DayOfYear- weekDate)/7)%8;
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedFrom(e);
Windows.Storage.ApplicationDataContainer localsettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localsettings.Values["season"] = ((ComboBoxItem)Season.SelectedItem).Content;
localsettings.Values["weekNumber"] = CurrentWeekNumber.SelectedIndex;
localsettings.Values["weekDate"] = System.DateTime.Today.DayOfYear-(System.DateTime.Today.DayOfWeek==0?6:(int)System.DateTime.Today.DayOfWeek-1);//the day in year of this week's monday
}
private void UserName_GotFocus(object sender, RoutedEventArgs e)
{
UserName.SelectAll();
}
private void MyPasswordBox_GotFocus(object sender, RoutedEventArgs e)
{
MyPasswordBox.SelectAll();
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
//PasswordVault value = new PasswordVault();
Windows.Storage.ApplicationDataContainer localsettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (SaveButton.Content.ToString() == "确认")
{
if (UserName.Text != "" && MyPasswordBox.Password != "")
{
//PasswordCredential passwordCredential = new PasswordCredential("zju", UserName.Text, MyPasswordBox.Password);
//value.Add(passwordCredential);
localsettings.Values["userName"] = UserName.Text;
localsettings.Values["password"] = MyPasswordBox.Password;
SaveButton.Content = "删除";
}
else
{
var message = new Windows.UI.Popups.MessageDialog("不要卖萌,没有数据怎么确认~");
await message.ShowAsync();
}
}
else //the buton is a delete button
{
//var passwordCredentials = value.FindAllByResource("zju");
//foreach (var credential in passwordCredentials) //删除用户账户,防止可能有错误的用户密码,可能用户保存多次
//{
// value.Remove(credential);
//}
localsettings.Values.Remove("userName");
localsettings.Values.Remove("password");
await DataHelper.DeleteDatabaseAsync(); //删除用户数据
UserName.Text = "";
MyPasswordBox.Password = "";
SaveButton.Content = "确认";
}
}
private void Account_TextChanged(object sender, RoutedEventArgs e)
{
SaveButton.Content = "确认";
}
#endregion
}
}
|
using Owin;
using SimpleInjector;
using System.Web.Http;
using System;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Owin;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SimpleInjector.Integration.WebApi;
using api_baixo_acoplamento.Seguranca;
using api_baixo_acoplamento.Ioc;
[assembly: OwinStartup(typeof(api_baixo_acoplamento.Startup))]
namespace api_baixo_acoplamento
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
//Container de inversão de controller
var container = new Container();
//Configura a inversão de controller;
ConfigureDependencyInjetion(config, container);
ConfigureWebApi(config);
ConfigureOAuth(app, container);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private void ConfigureOAuth(IAppBuilder app, Container container)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
Provider = new AuthorizationApi(container)
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
private void ConfigureWebApi(HttpConfiguration config)
{
//config.MessageHandlers.Add(new LogApiHandler());
//Remover suporte ao XML
config.Formatters.Remove(config.Formatters.XmlFormatter);
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.Formatting = Formatting.Indented;
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
//ignora possivel loop de objetos (quando um objeto interno aponta para o objeto origem)
jsonSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.MapHttpAttributeRoutes();
}
private void ConfigureDependencyInjetion(HttpConfiguration config, Container container)
{
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
BootStrapper.RegisterWebApi(container);
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.