text stringlengths 13 6.01M |
|---|
namespace BettingSystem.Infrastructure.Identity.Services
{
using System.Threading.Tasks;
public interface IJwtGenerator
{
Task<string> GenerateToken(User user);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UcenikShuffle.Common.Exceptions;
namespace UcenikShuffle.Common
{
public class LvCombinationProcessor
{
public IEnumerable<LvCombination> LvCombinations
{
get
{
if (_lvCombinations == null)
{
_lvCombinations = GetLvCombinations(_groupSizes, _students);
}
return _lvCombinations;
}
}
private IEnumerable<LvCombination> _lvCombinations;
private readonly List<int> _groupSizes;
private readonly List<Student> _students;
private readonly int _maxCombinationCount;
public LvCombinationProcessor(IReadOnlyList<int> groupSizes, IReadOnlyList<Student> students, int maxCombinationCount = 0)
{
if (groupSizes == null || groupSizes.Count == 0 || groupSizes.Any(s => s <= 0))
{
throw new GroupSizeException();
}
if (students == null || students.Count <= 0)
{
throw new ArgumentException("Broj učenika mora biti pozitivni cijeli broj!");
}
_groupSizes = groupSizes.ToList();
_students = students.ToList();
_maxCombinationCount = maxCombinationCount;
}
/// <summary>
/// This method returns all student sitting combinations for a lv
/// </summary>
/// <param name="takeOffset">Offset of the number which will be taken. For example, if every second combination is taken and offset is 3, following combinations will be returned: 5th, 7th, 9th, 11th...</param>
/// <param name="takeEvery">Specifies which combinations will be returned. If there are 1000 combinations and <paramref name="maxCombinationCount"/> is 100, this parameter will be 10. That means that 10th, 20th, 30th etc. combinations will be returned</param>
/// <returns></returns>
private IEnumerable<LvCombination> GetLvCombinations(List<int> groupSizes, List<Student> students, double takeEvery = 0, double takeOffset = 0)
{
bool allGroupsAreSameSize = groupSizes.Distinct().Count() == 1;
var sameGroupSizes = groupSizes.Where(s => s == groupSizes[0]).ToList();
//Setting takeEvery value if this is the first time this method was called
if (takeEvery == 0 && takeOffset == 0)
{
takeEvery = (_maxCombinationCount <= 0) ? -1 : (double)new LvCombinationCountCalculator(groupSizes, groupSizes.Sum()).GetLvCombinationCount() / _maxCombinationCount;
takeEvery = (takeEvery <= 1) ? -1 : takeEvery;
}
//Going trough each combination for the first group and getting all possible combinations for other groups
Student currentFirstCombinationNumber = null;
var availableStudents = new List<Student>(students);
foreach (var firstGroupCombination in GetLvCombinationsForFirstGroup(groupSizes, students))
{
//Returning first group combination if there is only 1 number group
if (groupSizes.Count == 1)
{
//Skipping the combination if necessary
if (takeOffset > 0)
{
takeOffset--;
continue;
}
takeOffset += takeEvery - 1;
yield return new LvCombination(firstGroupCombination.Combination);
continue;
}
//Removing some available students if the first student in the combination changed
if (sameGroupSizes.Count > 1)
{
var firstCombinationNumber = firstGroupCombination.Combination[0][0];
if (firstCombinationNumber != currentFirstCombinationNumber)
{
currentFirstCombinationNumber = firstCombinationNumber;
availableStudents.Remove(firstCombinationNumber);
}
}
//Skipping the combination if all combinations in this group would be skipped
ulong combinationCount = GetCombinationCount(groupSizes, availableStudents);
if (takeOffset - combinationCount > 0)
{
takeOffset -= combinationCount;
continue;
}
//Getting all possible combinations for groups that have the same size as the first group
if (sameGroupSizes.Count > 1)
{
var tempAvailableStudents = availableStudents.Except(firstGroupCombination.Combination[0]).ToList();
var tempGroupSizes = new List<int>(sameGroupSizes);
tempGroupSizes.RemoveAt(0);
var sameSizeCombinations = GetLvCombinations(tempGroupSizes, tempAvailableStudents, takeEvery, takeOffset);
foreach (var sameSizeCombination in sameSizeCombinations)
{
var lvCombination = new LvCombination(new List<List<Student>>(firstGroupCombination.Combination));
lvCombination.Combination.AddRange(sameSizeCombination.Combination);
//Returning the combination if all groups have the same size
if (allGroupsAreSameSize)
{
takeOffset += takeEvery;
yield return lvCombination;
continue;
}
//Getting all possible combinations for the groups that don't have the same size as the first group
tempAvailableStudents = new List<Student>(students);
tempAvailableStudents.RemoveAll(i => firstGroupCombination.Combination[0].Contains(i));
sameSizeCombination.Combination.ForEach(g => tempAvailableStudents.RemoveAll(i => g.Contains(i)));
tempGroupSizes = groupSizes.Except(sameGroupSizes).ToList();
foreach (var otherGroupsCombination in GetLvCombinations(tempGroupSizes, tempAvailableStudents, takeEvery, takeOffset))
{
//Combining all of the group combinations into 1 combination
otherGroupsCombination.Combination.InsertRange(0, lvCombination.Combination);
takeOffset += takeEvery;
yield return otherGroupsCombination;
}
}
}
else
{
//Getting number combinations for other groups
var tempAvailableStudents = availableStudents.Except(firstGroupCombination.Combination[0]).ToList();
var tempGroupSizes = groupSizes.Where(s => s != groupSizes[0]).ToList();
foreach (var c in GetLvCombinations(tempGroupSizes, tempAvailableStudents, takeEvery, takeOffset))
{
//Combining all of the group combinations into 1 combination
c.Combination.Insert(0, firstGroupCombination.Combination[0]);
takeOffset += takeEvery;
yield return c;
}
}
takeOffset -= combinationCount;
}
}
private IEnumerable<LvCombination> GetLvCombinationsForGroup(int groupSize, List<Student> students)
{
var groupCombination = new List<Student>();
//If group size is bigger than the number of available numbers or if group size is 1
if (groupSize >= students.Count)
{
yield return new LvCombination(new List<List<Student>>() { students });
yield break;
}
//If group size is 1
if (groupSize == 1)
{
foreach (var student in students)
{
yield return new LvCombination(new List<List<Student>>() { new List<Student>() { student } });
}
yield break;
}
//Initial combination
for (int i = 0; i < groupSize; i++)
{
groupCombination.Add(students[i]);
}
yield return new LvCombination(new List<List<Student>>() { new List<Student>(groupCombination) });
//Getting all combinations
while (true)
{
bool noMoreCombinations = true;
for (int i = groupSize - 1; i >= 0; i--)
{
//lastStudent is the last possible student for this spot in the combination
var lastStudent = students[i + students.Count - groupSize];
if (groupCombination[i] != lastStudent)
{
noMoreCombinations = false;
var newIndex = students.IndexOf(groupCombination[i]) + 1;
groupCombination[i] = students[newIndex];
for (int j = 1; j < groupSize - i; j++)
{
groupCombination[i + j] = students[newIndex + j];
}
yield return new LvCombination(new List<List<Student>>() { new List<Student>(groupCombination) }); ;
break;
}
}
//If all combinations have been tried out
if (noMoreCombinations)
{
yield break;
}
}
}
private IEnumerable<LvCombination> GetLvCombinationsForFirstGroup(IList<int> groupSizes, IList<Student> students)
{
var sameGroupSizes = groupSizes.Where(s => s == groupSizes[0]).ToList();
//If the second group has the same size as the first one than all combinations for the first group are calculated, and all combinations for other groups are calculated later on
var tempStudents = new List<Student>(students);
//Max first number is the max number that can be used for the first place in the first group (max number limit is set so that all duplicates are removed)
int maxFirstStudent = students.Count - sameGroupSizes.Sum() + 1;
for (int i = 0; i < maxFirstStudent; i++)
{
var firstStudent = tempStudents[0];
tempStudents.RemoveAt(0);
var combinations = GetLvCombinationsForGroup(groupSizes[0] - 1, tempStudents).ToList();
foreach (var combination in combinations)
{
combination.Combination[0].Insert(0, firstStudent);
yield return combination;
}
}
}
private ulong GetCombinationCount(IList<int> groupSizes, IList<Student> availableStudents)
{
var sameGroupSizes = groupSizes.Where(s => s == groupSizes[0]).Skip(1);
var otherGroups = groupSizes.Where(s => s != groupSizes[0]);
if (sameGroupSizes.Count() == 0)
{
otherGroups = new List<int>(groupSizes.Skip(1));
}
ulong count1 = new LvCombinationCountCalculator(sameGroupSizes.ToList(), availableStudents.Count - groupSizes[0] + 1).GetLvCombinationCount();
ulong count2 = new LvCombinationCountCalculator(otherGroups.ToList(), otherGroups.Sum()).GetLvCombinationCount();
ulong combinationCount = (count1 == 0 ? 1 : count1) * (count2 == 0 ? 1 : count2);
return combinationCount;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTypeD : MonoBehaviour
{
public float bulletSpeed = 500;
public bool[] fireActive; // Up Down Left Right
public Transform[] firePoint; // Up Down Left Right
public GameObject bulletPrefab;
public float fireInterval = 1;
private float timer;
void Start()
{
timer = fireInterval;
}
void Update()
{
if(timer <= 0)
Attack();
if (timer > 0)
timer -= Time.deltaTime;
}
void Attack()
{
if (fireActive[0])
Fire(firePoint[0]);
if (fireActive[1])
Fire(firePoint[1]);
if (fireActive[2])
Fire(firePoint[2]);
if (fireActive[3])
Fire(firePoint[3]);
timer = fireInterval;
}
void Fire(Transform firePoint)
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
bullet.GetComponent<Rigidbody2D>().AddForce(firePoint.up * bulletSpeed);
}
}
|
using UnityEngine;
public class objectRotateToObject : MonoBehaviour
{
public GameObject observeObject;
public Vector3 offset;
void Update()
{
this.transform.position = new Vector3(this.transform.position.x + offset.x,observeObject.transform.position.y + offset.y,this.transform.position.z+offset.z);
//this.transform.LookAt(observeObject.transform);
}
}
|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Stiig;
public partial class user : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strUsername = Request.QueryString["user"];
decimal PostCount;
decimal PostCountTotal;
MembershipUser user = Membership.GetUser(strUsername);
ProfileCommon userprofile = Profile.GetProfile(strUsername);
DataAccessLayer dal = new DataAccessLayer();
if (strUsername != "")
{
if (Membership.FindUsersByName(strUsername).Count == 0)
{
Response.Redirect("error.aspx?error=1");
}
}
else
{
Response.Redirect("error.aspx?error=1");
}
lblUsername1.Text = strUsername;
lblUsername2.Text = strUsername;
lblUsername3.Text = strUsername;
lblRank.Text = Roles.GetRolesForUser(strUsername).GetValue(0).ToString();
hplFindPostsByUser.Text = "Find alle posts skrevet af " + user.UserName;
hplFindPostsByUser.NavigateUrl = "search.aspx?author=" + user.UserName;
if (userprofile.Options.ShowEmail & user.Email != "")
{
hplEmail.Visible = true;
hplEmail.NavigateUrl = "mailto:" + user.Email;
}
if (userprofile.Messenger != "")
{
lblMsn.Visible = true;
lblMsn.Text = userprofile.Messenger;
}
lblCreated.Text = Utilities.GetDate(user.CreationDate, true, false);
if (user.IsOnline)
{
lblLastOnline.Text = "Online nu!";
}
else
{
lblLastOnline.Text = Utilities.GetDate(user.LastActivityDate, true, true);
}
dal.AddParameter("Author", strUsername, DbType.String);
PostCount = Convert.ToDecimal(dal.ExecuteScalar("SELECT COUNT(*) FROM Posts WHERE Author = @Author"));
dal.ClearParameters();
PostCountTotal = Convert.ToDecimal(dal.ExecuteScalar("SELECT COUNT(*) FROM Posts"));
lblPostCount.Text = PostCount.ToString();
lblPostPercentOfTotal.Text = Convert.ToString(Math.Round(((PostCount / PostCountTotal) * 100),2));
lblPostsPerDay.Text = Convert.ToString(Math.Round((PostCount / Convert.ToInt32(Utilities.RemoveEndString(Convert.ToString(DateTime.Today.AddDays(1) - user.CreationDate.Date), ".00:00:00"))), 2));
lblLocation.Text = userprofile.Personal.Country;
if (userprofile.Homepage != "")
{
hplHomepage.Visible = true;
hplHomepage.NavigateUrl = userprofile.Homepage;
hplHomepage.Text = userprofile.Homepage;
}
lblOccupation.Text = userprofile.Occupation;
lblInterests.Text = userprofile.Interests;
}
} |
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Base;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Base;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del Adaptador de Proveedor
/// </summary>
public sealed class ProveedorAdapter
{
/// <summary>
/// Realiza la adaptación de campos para la búsqueda
/// </summary>
/// <param name="listadoContratoLogic">Entidad Lógica Proveedor</param>
/// <returns>Clase Proveedor Response con los datos de búsqueda</returns>
public static ProveedorResponse ObtenerProveedorPaginado(ProveedorLogic proveedorLogic)
{
var proveedorResponse = new ProveedorResponse();
proveedorResponse.CodigoProveedor = proveedorLogic.CodigoProveedor;
proveedorResponse.CodigoIdentificacion = proveedorLogic.CodigoIdentificacion;
proveedorResponse.Nombre = proveedorLogic.Nombre;
proveedorResponse.NombreComercial = proveedorLogic.NombreComercial;
proveedorResponse.TipoDocumento = proveedorLogic.TipoDocumento;
proveedorResponse.NumeroDocumento = proveedorLogic.NumeroDocumento;
return proveedorResponse;
}
/// <summary>
/// Realiza la adaptación de campos para la búsqueda
/// </summary>
/// <param name="plantillaLogic">Entidad Lógica Proveedor</param>
/// <returns>Clase Proveedor Response con los datos de búsqueda</returns>
public static ProveedorResponse ObtenerProveedor(ProveedorLogic proveedorLogic)
{
var proveedorResponse = new ProveedorResponse();
proveedorResponse.CodigoProveedor = proveedorLogic.CodigoProveedor;
proveedorResponse.CodigoIdentificacion = proveedorLogic.CodigoIdentificacion;
proveedorResponse.Nombre = proveedorLogic.Nombre;
proveedorResponse.NombreComercial = proveedorLogic.NombreComercial;
proveedorResponse.TipoDocumento = proveedorLogic.TipoDocumento;
proveedorResponse.NumeroDocumento = proveedorLogic.NumeroDocumento;
return proveedorResponse;
}
/// <summary>
/// Realiza la adaptación de campos para registrar o actualizar
/// </summary>
/// <param name="data">Datos a registrar o actualizar</param>
/// <returns>Entidad Proveedor con los datos a registrar</returns>
public static ProveedorEntity RegistrarProveedor(ProveedorRequest data)
{
var proveedorEntity = new ProveedorEntity();
if (data.CodigoProveedor != null)
{
proveedorEntity.CodigoProveedor = new Guid(data.CodigoProveedor.ToString());
}
else
{
Guid code;
code = Guid.NewGuid();
proveedorEntity.CodigoProveedor = code;
}
proveedorEntity.CodigoIdentificacion = data.CodigoIdentificacion;
proveedorEntity.Nombre = data.Nombre;
proveedorEntity.NombreComercial = data.Nombre;
proveedorEntity.TipoDocumento = data.TipoDocumento;
proveedorEntity.NumeroDocumento = data.NumeroDocumento;
return proveedorEntity;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication5.Interfaces;
using WebApplication5.Models;
namespace WebApplication5.Repository
{
public class ProductRepository : IDisposable, IProductRepository
{
private AppDbContext db = new AppDbContext();
public bool Add(Product product)
{
db.Product.Add(product);
int res = db.SaveChanges();
return res > 0 ? true : false;
}
public bool Delete(Product product)
{
db.Product.Remove(product);
int res = db.SaveChanges();
return res > 0 ? true : false;
}
//public IEnumerable<Product> GetAll()
//{
// return db.Product;
//}
//public Task<IEnumerable<Product>> GetAll()
//{
// return Task.FromResult(db.Product.AsEnumerable());
//}
//public Task<List<Product>> GetAll()
//{
// return Task.FromResult(db.Product.ToList());
//}
public IList<Product> GetAll()
{
return db.Product.ToList();
}
public Product GetById(int id)
{
return db.Product.FirstOrDefault(x => x.ProductId == id);
}
public bool Update(Product product)
{
db.Entry(product).State = EntityState.Modified;
try
{
int res = db.SaveChanges();
return res > 0 ? true : false;
}
catch (DbUpdateConcurrencyException)
{
throw;
}
}
protected void Dispose(bool disposing)
{
if (disposing)
{
if (db != null)
{
db.Dispose();
db = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FieldMapping
{
internal class FieldMapping<O,Q>
: FieldMapBase
where O : class
{
internal Func<O,Q,Q> filter {get;set; }
internal bool defset {get;set; }
internal Q defval {get;set; }
internal Func<string[],Q> converter {get;set; }
internal FieldMapping() : base() { defset = false; }
internal override void set(object obj, string[] x, bool exists)
{
O t = (O)obj;
var newx = default(Q);
object dest = null;
if (!exists && defset) { dest = newx = defval; }
else
{
if (converter != null) { dest = converter(x); }
else { dest = _GetValue(typeof(Q), x); }
}
if (filter != null)
{
/* only do cast if we can actually get a result. */
if (dest == null && !typeof(Q).IsValueType || dest != null)
{ newx = (Q)dest; }
dest = filter(t,newx);
}
_objchange(obj, dest);
}
}
}
|
using Anywhere2Go.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.DataAccess.MySqlEntity
{
public class TRAdvertise
{
public int TRAdvertiseID { get; set; }
public DateTime TRAdvertiseDate { get; set; }
public TimeSpan TRAdvertiseTime { get; set; }
public int ClaimType { get; set; }
//public int SurveryID { get; set; }
public string SurveyID { get; set; }
public int InsurerID { get; set; }
public string SurvJobNo { get; set; }
public string RefClaimNo { get; set; }
public string AccPolicyNo { get; set; }
public DateTime PolicyStart { get; set; }
public DateTime PolicyEnd { get; set; }
public string AssuredName { get; set; }
public string TxtCallPlace { get; set; }
public string TxtCallCause { get; set; }
public string TxtCallName { get; set; }
public string PolicyType { get; set; }
public int AdvertiseStatus { get; set; }
public string CreateBy { get; set; }
public DateTime CreateDate { get; set; }
public int TypeJob { get; set; }
public string TxtDriName1 { get; set; }
public string TxtDriTel1 { get; set; }
public DateTime TxtCallDate { get; set; }
//public string txtAdvertiseStatus { get; set; }
public string PrbNumber { get; set; }
//public TRAdvertisePersonSurvey TRAdvertisePersonSurvey { get; set; }
}
public class TRAdvertiseConfig : EntityTypeConfiguration<TRAdvertise>
{
public TRAdvertiseConfig()
{
ToTable("tbtradvertise");
Property(t => t.TRAdvertiseID).HasColumnName("TRAdvertiseID");
Property(t => t.TRAdvertiseDate).HasColumnName("TRAdvertiseDate");
Property(t => t.TRAdvertiseTime).HasColumnName("TRAdvertiseTime");
Property(t => t.ClaimType).HasColumnName("ClaimType");
//Property(t => t.SurveryID).HasColumnName("SurveryID");
Property(t => t.SurveyID).HasColumnName("SurveyID");
Property(t => t.InsurerID).HasColumnName("InsurerID");
Property(t => t.SurvJobNo).HasColumnName("Surv_JobNo");
Property(t => t.RefClaimNo).HasColumnName("Ref_Claim_No");
Property(t => t.AccPolicyNo).HasColumnName("Acc_Policy_No");
Property(t => t.PolicyStart).HasColumnName("Policy_Start");
Property(t => t.PolicyEnd).HasColumnName("Policy_End");
Property(t => t.AssuredName).HasColumnName("Assured_Name");
Property(t => t.TxtCallPlace).HasColumnName("txtCall_Place");
Property(t => t.TxtCallCause).HasColumnName("txtCall_Cause");
Property(t => t.TxtCallName).HasColumnName("txtCall_Name");
Property(t => t.PolicyType).HasColumnName("Policy_Type");
Property(t => t.CreateDate).HasColumnName("create_date");
Property(t => t.CreateBy).HasColumnName("CreateBy");
Property(t => t.AdvertiseStatus).HasColumnName("AdvertiseStatus");
Property(t => t.TypeJob).HasColumnName("TypeJob");
Property(t => t.TxtDriName1).HasColumnName("txtDriName1");
Property(t => t.TxtDriTel1).HasColumnName("txtDriTel1");
Property(t => t.TxtCallDate).HasColumnName("txtCall_Date");
Property(t => t.PrbNumber).HasColumnName("Prb_Number");
HasKey(t => new { t.TRAdvertiseID, t.ClaimType });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FXB.Data;
namespace FXB.Common
{
public enum CbSetMode
{
CBSM_Employee = 0, //员工
CBSM_Department = 1 //部门
}
class QtUtil
{
static public void SetComboxValue(ComboBox cb, CbSetMode mode)
{
if (mode == CbSetMode.CBSM_Employee)
{
cb.Items.Insert(0, QtString.None);
cb.Items.Insert(1, QtString.Salesman);
cb.Items.Insert(2, QtString.SmallCharge);
cb.Items.Insert(3, QtString.LargeCharge);
cb.Items.Insert(4, QtString.Majordomo);
cb.Items.Insert(5, QtString.ZhuchangZhuanyuan);
cb.Items.Insert(6, QtString.ZhuchangZhuguan);
cb.Items.Insert(7, QtString.ZhuchangZongjian);
cb.SelectedIndex = 0;
return;
}
if (mode == CbSetMode.CBSM_Department)
{
cb.Items.Insert(0, QtString.None);
cb.Items.Insert(1, QtString.SmallCharge);
cb.Items.Insert(2, QtString.LargeCharge);
cb.Items.Insert(3, QtString.Majordomo);
cb.Items.Insert(4, QtString.ZhuchangZhuguan);
cb.Items.Insert(5, QtString.ZhuchangZongjian);
cb.SelectedIndex = 0;
return;
}
}
static public int GetComboxIndex(ComboBox cb, QtLevel qtLevel)
{
for (int i=0; i<cb.Items.Count; i++)
{
string strItem = cb.Items[i] as string;
string strQtLevel = GetQTLevelString(qtLevel);
if (strItem == strQtLevel)
{
return i;
}
}
throw new CrashException("GetComboxIndex qtLevel exception");
}
static public QtLevel GetQTLevel(string str)
{
if (str == QtString.None)
{
return QtLevel.None;
}
else if (str == QtString.Salesman)
{
return QtLevel.Salesman;
}
else if (str == QtString.SmallCharge)
{
return QtLevel.SmallCharge;
}
else if (str == QtString.LargeCharge)
{
return QtLevel.LargeCharge;
}
else if (str == QtString.Majordomo)
{
return QtLevel.Majordomo;
}
else if (str == QtString.ZhuchangZhuanyuan)
{
return QtLevel.ZhuchangZhuanyuan;
}
else if (str == QtString.ZhuchangZhuguan)
{
return QtLevel.ZhuchangZhuguan;
}
else if (str == QtString.ZhuchangZongjian)
{
return QtLevel.ZhuchangZongjian;
}
throw new CrashException("错误QT级别字符串");
}
static public string GetQTLevelString(QtLevel level)
{
if (level == QtLevel.None)
{
return QtString.None;
}
else if (level == QtLevel.Salesman)
{
return QtString.Salesman;
}
else if (level == QtLevel.SmallCharge)
{
return QtString.SmallCharge;
}
else if (level == QtLevel.LargeCharge)
{
return QtString.LargeCharge;
}
else if (level == QtLevel.Majordomo)
{
return QtString.Majordomo;
}
else if (level == QtLevel.ZhuchangZhuanyuan)
{
return QtString.ZhuchangZhuanyuan;
}
else if (level == QtLevel.ZhuchangZhuguan)
{
return QtString.ZhuchangZhuguan;
}
else if (level == QtLevel.ZhuchangZongjian)
{
return QtString.ZhuchangZongjian;
}
throw new CrashException("错误QT级别字符串");
}
}
}
|
using System.Data;
using System.Web.Mvc;
using com.Sconit.Web.Util;
using Telerik.Web.Mvc;
using com.Sconit.Web.Models.SearchModels.SI.SAP;
using System.Data.SqlClient;
using System;
using System.Linq;
using com.Sconit.Web.Models;
using System.Collections.Generic;
using com.Sconit.Entity.SAP.TRANS;
using com.Sconit.Service;
using System.ComponentModel;
using System.Reflection;
using com.Sconit.Entity.SAP.ORD;
using com.Sconit.Entity.CUST;
namespace com.Sconit.Web.Controllers.SI.SAP
{
public class SAPOpReportController : WebAppBaseController
{
//
// GET: /SequenceOrder/
public IGenericMgr genericMgr { get; set; }
/// <summary>
///
/// </summary>
public SAPOpReportController()
{
}
//public IQueryMgr siMgr { get { return GetService<IQueryMgr>("siMgr"); } }
[SconitAuthorize(Permissions = "Url_CUST_OpReport_View")]
public ActionResult Index()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_CUST_OpReport_View")]
public ActionResult List(GridCommand command, OpReportSearchModel searchModel)
{
TempData["OpReportSearchModel"] = searchModel;
ViewBag.PageSize = 20;
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_CUST_OpReport_View")]
public ActionResult _AjaxList(GridCommand command, OpReportSearchModel searchModel)
{
string selectStatement = "select o from OperationReport as o where 1=1 ";
IList<object> param = new List<object>();
if (!string.IsNullOrEmpty(searchModel.OrderNo))
{
selectStatement += " and o.OrderNo=?";
param.Add(searchModel.OrderNo);
}
if (!string.IsNullOrEmpty(searchModel.ExtOrderNo))
{
selectStatement += " and o.ExternalOrderNo=?";
param.Add(searchModel.ExtOrderNo);
}
if (!string.IsNullOrEmpty(searchModel.Operation))
{
selectStatement += " and o.Operation=?";
param.Add(searchModel.Operation);
}
if (searchModel.StartDate != null & searchModel.EndDate != null)
{
selectStatement += " and o.CreateDate between ? and ?";
param.Add(searchModel.StartDate);
param.Add(searchModel.EndDate);
}
else if (searchModel.StartDate != null & searchModel.EndDate == null)
{
selectStatement += " and o.CreateDate >= ? ";
param.Add(searchModel.StartDate);
}
else if (searchModel.StartDate == null & searchModel.EndDate != null)
{
selectStatement += " and o.CreateDate <= ? ";
param.Add(searchModel.EndDate);
}
IList<OperationReport> list = genericMgr.FindAll<OperationReport>(selectStatement, param.ToArray());
return PartialView(new GridModel(list));
//return PartialView(GetAjaxPageData<ReceiptMaster>(searchStatementModel, command));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dokan;
using System.IO;
using System.Collections;
namespace GitHubFS
{
class GitHubFSDokan : DokanOperations
{
public GitHubFS git;
public GitHubFSDokan(GitHubFS git)
{
this.git = git;
}
public int CreateFile(String filename, FileAccess access, FileShare share,
FileMode mode, FileOptions options, DokanFileInfo info)
{
if (this.git.RepositoryTree.ContainsKey(filename))
{
info.IsDirectory = true;
return 0;
}
else if (
this.git.RepositoryTree.ContainsKey(PathAndFile.Path(filename)) &&
this.git.RepositoryTree[PathAndFile.Path(filename)].ContainsKey(PathAndFile.File(filename)))
{
return 0;
}
else
{
return -DokanNet.ERROR_FILE_NOT_FOUND;
}
}
public int OpenDirectory(String filename, DokanFileInfo info)
{
Console.WriteLine("OpenDirectory: " + filename);
if (this.git.RepositoryTree.ContainsKey(filename))
return 0;
else
return -DokanNet.ERROR_PATH_NOT_FOUND;
}
public int CreateDirectory(String filename, DokanFileInfo info)
{
return -1;
}
public int Cleanup(String filename, DokanFileInfo info)
{
//Console.WriteLine("%%%%%% count = {0}", info.Context);
return 0;
}
public int CloseFile(String filename, DokanFileInfo info)
{
return 0;
}
public int ReadFile(String filename, Byte[] buffer, ref uint readBytes,
long offset, DokanFileInfo info)
{
Console.WriteLine("ReadFile: " + filename);
Stream stream = new MemoryStream(this.git.GetFile(filename));
stream.Seek(offset, SeekOrigin.Begin);
readBytes = (uint)stream.Read(buffer, 0, buffer.Length);
return 0;
}
public int WriteFile(String filename, Byte[] buffer,
ref uint writtenBytes, long offset, DokanFileInfo info)
{
return -1;
}
public int FlushFileBuffers(String filename, DokanFileInfo info)
{
return -1;
}
public int GetFileInformation(String filename, FileInformation fileinfo, DokanFileInfo info)
{
Console.WriteLine("GetFileInformation: " + filename);
fileinfo.LastAccessTime = DateTime.Now;
fileinfo.LastWriteTime = DateTime.Now;
fileinfo.CreationTime = DateTime.Now;
if (this.git.RepositoryTree.ContainsKey(filename))
{
fileinfo.Attributes = System.IO.FileAttributes.Directory;
return 0;
}
else if (
this.git.RepositoryTree.ContainsKey(PathAndFile.Path(filename)) &&
this.git.RepositoryTree[PathAndFile.Path(filename)].ContainsKey(PathAndFile.File(filename))
) {
FileInformation f = (FileInformation)
this.git.RepositoryTree
[PathAndFile.Path(filename)]
[PathAndFile.File(filename)];
fileinfo.Attributes = System.IO.FileAttributes.Normal;
fileinfo.Length = f.Length;
return 0;
}
else
{
return -1;
}
}
public int FindFiles(String filename, ArrayList files, DokanFileInfo info)
{
Console.WriteLine("FindFiles: " + filename);
if (this.git.RepositoryTree.ContainsKey(filename))
{
foreach (KeyValuePair<string, object> item in this.git.RepositoryTree[filename])
{
FileInformation finfo = (FileInformation)item.Value;
files.Add(finfo);
}
return 0;
}
else
{
return -1;
}
}
public int SetFileAttributes(String filename, FileAttributes attr, DokanFileInfo info)
{
return -1;
}
public int SetFileTime(String filename, DateTime ctime,
DateTime atime, DateTime mtime, DokanFileInfo info)
{
return -1;
}
public int DeleteFile(String filename, DokanFileInfo info)
{
return -1;
}
public int DeleteDirectory(String filename, DokanFileInfo info)
{
return -1;
}
public int MoveFile(String filename, String newname, bool replace, DokanFileInfo info)
{
return -1;
}
public int SetEndOfFile(String filename, long length, DokanFileInfo info)
{
return -1;
}
public int SetAllocationSize(String filename, long length, DokanFileInfo info)
{
return -1;
}
public int LockFile(String filename, long offset, long length, DokanFileInfo info)
{
return 0;
}
public int UnlockFile(String filename, long offset, long length, DokanFileInfo info)
{
return 0;
}
public int GetDiskFreeSpace(ref ulong freeBytesAvailable, ref ulong totalBytes,
ref ulong totalFreeBytes, DokanFileInfo info)
{
freeBytesAvailable = 512 * 1024 * 1024;
totalBytes = 1024 * 1024 * 1024;
totalFreeBytes = 512 * 1024 * 1024;
return 0;
}
public int Unmount(DokanFileInfo info)
{
return 0;
}
}
}
|
using System;
namespace Ingentum.Instructors.Model
{
public class Instructor
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Hidden1.Value = "1";
Labele.Text = "curent value is:" + Hidden1.Value;
}
}
protected void button1_Click(object sender, EventArgs e)
{
int num = int.Parse(Hidden1.Value);
num++;
Hidden1.Value = num.ToString();
Labele.Text = "current value is:" + Hidden1.Value;
}
} |
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Dominio.Interfaces.Servicos
{
public interface IServicoAtribuicoes: IServicoBase<Atribuicoes>
{
}
}
|
namespace gView.Server.Services.Security
{
public class AccessTokenAuthServiceOptions
{
public string Authority { get; set; }
public string AccessTokenParameterName { get; set; }
public bool AllowAccessTokenAuthorization { get; set; }
}
}
|
/*
* Author: Generated Code
* Date Created: 22.03.2013
* Description: Represents a row in the tblProtokolPaymentType table
*/
namespace HTB.Database
{
public class tblProtokolPaymentType : Record
{
#region Property Declaration
[MappingAttribute(FieldType = MappingAttribute.FIELD_TYPE_ID, FieldAutoNumber = true)]
public int PptID{get; set; }
public int PptCode{get; set; }
public string PptCaption{get; set; }
#endregion
}
}
|
using System;
using System.Linq;
using System.Reflection;
using System.Text;
// ReSharper disable once CheckNamespace
namespace Aquarium.Util.Extension.ReflectionExtension
{
public static class SignatureExtension
{
/// <summary>A Type extension method that gets short declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The short declaraction.</returns>
internal static string GetShortSignature(this Type @this)
{
if (@this == typeof(bool)) return "bool";
if (@this == typeof(byte)) return "byte";
if (@this == typeof(char)) return "char";
if (@this == typeof(decimal)) return "decimal";
if (@this == typeof(double)) return "double";
if (@this == typeof(Enum)) return "enum";
if (@this == typeof(float)) return "float";
if (@this == typeof(int)) return "int";
if (@this == typeof(long)) return "long";
if (@this == typeof(object)) return "object";
if (@this == typeof(sbyte)) return "sbyte";
if (@this == typeof(short)) return "short";
if (@this == typeof(string)) return "string";
if (@this == typeof(uint)) return "uint";
if (@this == typeof(ulong)) return "ulong";
if (@this == typeof(ushort)) return "ushort";
return @this.Name;
}
public static string GetSignature(this ConstructorInfo @this)
{
// Example: [Name] [<GenericArguments] ([Parameters])
var sb = new StringBuilder();
// Name
sb.Append(@this.ReflectedType.IsGenericType
? @this.ReflectedType.Name.Substring(0, @this.ReflectedType.Name.IndexOf('`'))
: @this.ReflectedType.Name);
// Parameters
var parameters = @this.GetParameters();
sb.Append("(");
sb.Append(string.Join(", ", parameters.Select(x => x.GetSignature())));
sb.Append(")");
return sb.ToString();
}
public static string GetSignature(this EventInfo @this)
{
return null;
}
/// <summary>A FieldInfo extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this FieldInfo @this)
{
return @this.Name;
}
/// <summary>A MemberInfo extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this MemberInfo @this)
{
switch (@this.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo) @this).GetSignature();
case MemberTypes.Property:
return ((PropertyInfo) @this).GetSignature();
case MemberTypes.Constructor:
return ((ConstructorInfo) @this).GetSignature();
case MemberTypes.Method:
return ((MethodInfo) @this).GetSignature();
case MemberTypes.TypeInfo:
return ((Type) @this).GetSignature();
case MemberTypes.NestedType:
return ((Type) @this).GetSignature();
case MemberTypes.Event:
return ((EventInfo) @this).GetSignature();
default:
return null;
}
}
/// <summary>A MethodInfo extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this MethodInfo @this)
{
// Example: [Visibility] [Modifier] [Type] [Name] [<GenericArguments] ([Parameters])
var sb = new StringBuilder();
// Name
sb.Append(@this.Name);
if (@this.IsGenericMethod)
{
sb.Append("<");
var arguments = @this.GetGenericArguments();
sb.Append(string.Join(", ", arguments.Select(x => x.GetShortSignature())));
sb.Append(">");
}
// Parameters
var parameters = @this.GetParameters();
sb.Append("(");
sb.Append(string.Join(", ", parameters.Select(x => x.GetSignature())));
sb.Append(")");
return sb.ToString();
}
/// <summary>A ParameterInfo extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this ParameterInfo @this)
{
var sb = new StringBuilder();
@this.GetSignature(sb);
return sb.ToString();
}
internal static void GetSignature(this ParameterInfo @this, StringBuilder sb)
{
// retval attribute
string typeName;
var elementType = @this.ParameterType.GetElementType();
if (elementType != null)
typeName = @this.ParameterType.Name.Replace(elementType.Name, elementType.GetShortSignature());
else
typeName = @this.ParameterType.GetShortSignature();
if (@this.IsOut)
{
if (typeName.Contains("&"))
{
typeName = typeName.Replace("&", "");
sb.Append("out ");
}
}
else if (@this.ParameterType.IsByRef)
{
typeName = typeName.Replace("&", "");
sb.Append("ref ");
}
sb.Append(typeName);
}
/// <summary>A PropertyInfo extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this PropertyInfo @this)
{
// Example: [Name | Indexer[Type]]
var indexerParameter = @this.GetIndexParameters();
if (indexerParameter.Length == 0) return @this.Name;
var sb = new StringBuilder();
// Indexer
sb.Append(@this.Name);
sb.Append("[");
sb.Append(string.Join(", ", indexerParameter.Select(x => x.ParameterType.GetShortSignature())));
sb.Append("]");
return sb.ToString();
}
/// <summary>A Type extension method that gets a declaraction.</summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The declaraction.</returns>
public static string GetSignature(this Type @this)
{
// Example: [Visibility] [Modifier] [Type] [Name] [<GenericArguments>] [:] [Inherited Class] [Inherited Interface]
var sb = new StringBuilder();
// Variable
var hasInheritedClass = false;
// Name
sb.Append(@this.IsGenericType ? @this.Name.Substring(0, @this.Name.IndexOf('`')) : @this.Name);
// GenericArguments
if (@this.IsGenericType)
{
var arguments = @this.GetGenericArguments();
sb.Append("<");
sb.Append(string.Join(", ", arguments.Select(x =>
{
var constraints = x.GetGenericParameterConstraints();
foreach (var constraint in constraints)
{
var gpa = constraint.GenericParameterAttributes;
var variance = gpa & GenericParameterAttributes.VarianceMask;
if (variance != GenericParameterAttributes.None)
sb.Append((variance & GenericParameterAttributes.Covariant) != 0 ? "in " : "out ");
}
return x.GetShortDeclaraction();
})));
sb.Append(">");
}
return sb.ToString();
}
}
} |
using System.Xml.Serialization;
using Witsml.Data.Measures;
namespace Witsml.Data
{
public class WitsmlStnTrajValid
{
[XmlElement("magTotalFieldCalc")] public Measure MagTotalFieldCalc { get; set; }
[XmlElement("magDipAngleCalc")] public Measure MagDipAngleCalc { get; set; }
[XmlElement("gravTotalFieldCalc")] public Measure GravTotalFieldCalc { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FoodMachine
{
public enum SingleGoodType { Drink, Food}
class SingleGood:Good
{
public SingleGoodType type { get; private set; }
public List<Component> components { get; private set; }
public SingleGood(String name, int price, SingleGoodType type, List<Component> components)
{
this.name = name;
this.price = price;
this.type = type;
this.components = components;
}
}
}
|
using System.Net.NetworkInformation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using pet_hotel.Models;
using Microsoft.EntityFrameworkCore;
namespace pet_hotel.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class PetsController : ControllerBase
{
private readonly ApplicationContext _context;
public PetsController(ApplicationContext context)
{
_context = context;
}
[HttpPost]
public IActionResult MakePet([FromBody] Pet pet)
{
PetOwner petOwner = _context.PetOwners.Find(pet.petOwnerid);
if (petOwner == null)
{
ModelState.AddModelError("petOwnerid", "Invalid Owner ID");
return ValidationProblem(ModelState);
}
_context.Add(pet);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = pet.id }, pet);
}
[HttpGet]
public IEnumerable<Pet> GetPets()
{
return _context.Pets.Include(p => p.PetOwner).OrderBy(p => p.name);
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
Pet pet = _context.Pets.Include(p => p.PetOwner).SingleOrDefault(p => p.id == id);
if (pet == null)
{
return NotFound();
}
return Ok(pet);
}
[HttpDelete("{id}")]
public IActionResult DeleteById(int id)
{
Pet pet = _context.Pets.Include(p => p.PetOwner).SingleOrDefault(p => p.id == id);
if (pet == null)
{
return NotFound();
}
_context.Pets.Remove(pet);
_context.SaveChanges();
return NoContent();
}
[HttpPut("{id}/checkin")]
public IActionResult CheckinById(int id)
{
Pet pet = _context.Pets.Include(p => p.PetOwner).SingleOrDefault(p => p.id == id);
if (pet == null)
{
return NotFound();
}
pet.checkin();
_context.Update(pet);
_context.SaveChanges();
return Ok(pet);
}
[HttpPut("{id}")]
public IActionResult updatePet(int id, [FromBody] Pet pet)
{
if (!_context.Pets.Any(p => pet.id == id)) return NotFound();
_context.Pets.Update(pet);
_context.SaveChanges();
return Ok(pet);
}
[HttpPut("{id}/checkout")]
public IActionResult CheckoutById(int id)
{
Pet pet = _context.Pets.Include(p => p.PetOwner).SingleOrDefault(p => p.id == id);
if (pet == null)
{
return NotFound();
}
pet.checkout();
_context.Update(pet);
_context.SaveChanges();
return Ok(pet);
}
// [HttpGet]
// [Route("test")]
// public IEnumerable<Pet> GetPets() {
// PetOwner blaine = new PetOwner{
// name = "Blaine"
// };
// Pet newPet1 = new Pet {
// name = "Big Dog",
// petOwner = blaine,
// color = PetColorType.Black,
// breed = PetBreedType.Poodle,
// };
// Pet newPet2 = new Pet {
// name = "Little Dog",
// petOwner = blaine,
// color = PetColorType.Golden,
// breed = PetBreedType.Labrador,
// };
// return new List<Pet>{ newPet1, newPet2};
// }
}
}
|
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RecoveringDemo
{
class Patient : IRecoverable
{
public void Recover()
{
WriteLine("I'm the Patient...Hook me up doc! I'm not going to make it - Walter White");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace BassClefStudio.GameModel.Input.Basic
{
/// <summary>
/// An <see cref="IInput"/> detected from the keyboard (virtual or physical), containing information about the key that was pressed.
/// </summary>
public class KeyboardInput : IBinaryInput
{
/// <inheritdoc/>
public bool IsPressed { get; }
/// <summary>
/// A <see cref="KeyType"/> enum containing information about the key that was pressed or released.
/// </summary>
public KeyType Key { get; }
/// <summary>
/// Creates a new <see cref="KeyboardInput"/>.
/// </summary>
/// <param name="isPressed">A <see cref="bool"/> indicating whether the <see cref="IBinaryInput"/> represents a press ('true') or release ('false') input detection.</param>
/// <param name="key">A <see cref="KeyType"/> enum containing information about the key that was pressed or released.</param>
public KeyboardInput(bool isPressed, KeyType key)
{
IsPressed = isPressed;
Key = key;
}
}
/// <summary>
/// An enum containing every available key that a <see cref="KeyboardInput"/> input could represent.
/// </summary>
public enum KeyType
{
/// <summary>
/// The 'Enter' or 'Return' key.
/// </summary>
Enter = 13,
/// <summary>
/// The spacebar.
/// </summary>
Space = 32,
/// <summary>
/// The left arrow key.
/// </summary>
Left = 37,
/// <summary>
/// The up arrow key.
/// </summary>
Up = 38,
/// <summary>
/// The right arrow key.
/// </summary>
Right = 39,
/// <summary>
/// The down arrow key.
/// </summary>
Down = 40,
/// <summary>
/// The 'A' key.
/// </summary>
A = 65,
/// <summary>
/// The 'B' key.
/// </summary>
B = 66,
/// <summary>
/// The 'C' key.
/// </summary>
C = 67,
/// <summary>
/// The 'D' key.
/// </summary>
D = 68,
/// <summary>
/// The 'E' key.
/// </summary>
E = 69,
/// <summary>
/// The 'F' key.
/// </summary>
F = 70,
/// <summary>
/// The 'G' key.
/// </summary>
G = 71,
/// <summary>
/// The 'H' key.
/// </summary>
H = 72,
/// <summary>
/// The 'I' key.
/// </summary>
I = 73,
/// <summary>
/// The 'J' key.
/// </summary>
J = 74,
/// <summary>
/// The 'K' key.
/// </summary>
K = 75,
/// <summary>
/// The 'L' key.
/// </summary>
L = 76,
/// <summary>
/// The 'M' key.
/// </summary>
M = 77,
/// <summary>
/// The 'N' key.
/// </summary>
N = 78,
/// <summary>
/// The 'O' key.
/// </summary>
O = 79,
/// <summary>
/// The 'P' key.
/// </summary>
P = 80,
/// <summary>
/// The 'Q' key.
/// </summary>
Q = 81,
/// <summary>
/// The 'R' key.
/// </summary>
R = 82,
/// <summary>
/// The 'S' key.
/// </summary>
S = 83,
/// <summary>
/// The 'T' key.
/// </summary>
T = 84,
/// <summary>
/// The 'U' key.
/// </summary>
U = 85,
/// <summary>
/// The 'V' key.
/// </summary>
V = 86,
/// <summary>
/// The 'W' key.
/// </summary>
W = 87,
/// <summary>
/// The 'X' key.
/// </summary>
X = 88,
/// <summary>
/// The 'Y' key.
/// </summary>
Y = 89,
/// <summary>
/// The 'Z' key.
/// </summary>
Z = 90,
/// <summary>
/// The '0' number key.
/// </summary>
Num0 = 96,
/// <summary>
/// The '1' number key.
/// </summary>
Num1 = 97,
/// <summary>
/// The '2' number key.
/// </summary>
Num2 = 98,
/// <summary>
/// The '3' number key.
/// </summary>
Num3 = 99,
/// <summary>
/// The '4' number key.
/// </summary>
Num4 = 100,
/// <summary>
/// The '5' number key.
/// </summary>
Num5 = 101,
/// <summary>
/// The '6' number key.
/// </summary>
Num6 = 102,
/// <summary>
/// The '7' number key.
/// </summary>
Num7 = 103,
/// <summary>
/// The '8' number key.
/// </summary>
Num8 = 104,
/// <summary>
/// The '9' number key.
/// </summary>
Num9 = 105
}
}
|
using System;
using System.Collections.Generic;
namespace EPI.DynamicProgramming
{
/// <summary>
/// You are given a 2d array of integers, A and a sequence of integers, S.
/// S occurs in A if you can start from any entry in A and traverse neighboring entries in A to
/// find all elements in S.
/// Neighboring entries are top, down, left, right entries.
/// It is acceptable to visit an entry in A more than once.
/// </summary>
public static class SearchSequenceIn2DArray
{
public static List<Tuple<int, int>> FindSequenceInMaze(int[,] maze, int[] sequence)
{
for (int i = 0; i < maze.GetLength(0); i++)
{
for (int j = 0; j < maze.GetLength(1); j++)
{
List<Tuple<int, int>> list = new List<Tuple<int, int>>();
var result = MatchHelper(maze, sequence, i, j, 0, list);
if (result.Item1)
{
return result.Item2;
}
}
}
return null;
}
private static Tuple<bool, List<Tuple<int, int>>> MatchHelper(int[,] maze, int[] sequence, int i, int j, int k, List<Tuple<int, int>> listSoFar)
{
// base case
if ( k == sequence.Length)
{
return new Tuple<bool, List<Tuple<int, int>>>(true, listSoFar);
}
if ( i < 0 || i >= maze.GetLength(0) || j < 0 || j >= maze.GetLength(1))
{
return new Tuple<bool, List<Tuple<int, int>>>(false, null);
}
if (maze[i,j] == sequence[k])
{
List<Tuple<int, int>> updatedList = new List<Tuple<int, int>>();
foreach (var item in listSoFar)
{
updatedList.Add(item);
}
updatedList.Add(new Tuple<int, int>(i, j));
var result = MatchHelper(maze, sequence, i + 1, j, k + 1, updatedList);
if (result.Item1)
{
return result;
}
result = MatchHelper(maze, sequence, i - 1, j, k + 1, updatedList);
if (result.Item1)
{
return result;
}
result = MatchHelper(maze, sequence, i, j + 1, k + 1, updatedList);
if (result.Item1)
{
return result;
}
result = MatchHelper(maze, sequence, i, j - 1, k + 1, updatedList);
if (result.Item1)
{
return result;
}
}
return new Tuple<bool, List<Tuple<int, int>>>(false, null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DtCms.BLL;
namespace DtCms.Web
{
public partial class index : DtCms.Web.UI.BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
hotProductListBound();
hotNewsBound();
hotJiamenBound();
aboutUsBound();
}
}
private void hotProductListBound()
{
DtCms.BLL.Products bll = new DtCms.BLL.Products();
//查询绑定数据
this.productList.DataSource = bll.GetList(8, "classId=106 and IsLock = 0 and isRed=1", "isTop desc,ClassId asc,Id desc");
this.productList.DataBind();
}
private void hotNewsBound()
{
DtCms.BLL.Article bll = new DtCms.BLL.Article();
//查询绑定数据
DataSet ds = bll.GetList(7, "IsLock = 0 and isRed=1", "isTop desc,ClassId asc,Id desc");
this.newsList.DataSource = ds;
this.newsList.DataBind();
}
private void hotJiamenBound()
{
DtCms.BLL.Products bll = new DtCms.BLL.Products();
//查询绑定数据
this.jiamengList.DataSource = bll.GetList(8, "classId=107 and IsLock = 0 and isRed=1", "isTop desc,ClassId asc,Id desc");
this.jiamengList.DataBind();
}
private void aboutUsBound()
{
DtCms.BLL.Contents bll = new DtCms.BLL.Contents();
DtCms.Model.Contents model = new DtCms.Model.Contents();
model = bll.GetModel(1);
this.lbcontent.Text = model.Content;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AIPathCells : MonoBehaviour {
public List<GameObject> doors = new List<GameObject>();
void OnTriggerEnter(Collider myCollider)
{
if(myCollider.tag =="AIPathCell")
{
doors.Add(myCollider.gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using BlazorUI.Data;
using OnlineClinic.Data.Repositories;
using OnlineClinic.Data.Entities;
using OnlineClinic.Core.Services;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
using OnlineClinic.Core.Mappings;
using Microsoft.AspNetCore.Components.Authorization;
using OnlineClinic.Core.Utilities;
using Microsoft.AspNetCore.Components.Server;
namespace BlazorUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddDbContext<OnlineClinicDbContext>(options =>
{
options.UseLazyLoadingProxies();
options.UseSqlServer(Configuration.GetConnectionString("OnlineClinic"));
}
);
services.AddAutoMapper(typeof(OnlineClinicProfile));
services.AddScoped<IDoctorService, DoctorService>();
services.AddScoped<IDoctorRepository, DoctorRepository>();
services.AddScoped<IPersonService, PersonService>();
services.AddScoped<IPersonRepository, PersonRepository>();
services.AddScoped<ISpecializationService, SpecializationService>();
services.AddScoped<ISpecializationRepository, SpecializationRepository>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IPasswordEncryptionUtil>(opts =>
{
var passwordSecurityKey = Environment.GetEnvironmentVariable("PasswordSecurityKey");
return new PasswordEncryptionUtil(passwordSecurityKey);
});
services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
services.AddAuthentication();
services.AddAuthorization();
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
|
using System.Windows;
using SpatialEye.Framework.Client;
using SpatialEye.Framework.Geometry.CoordinateSystems;
using SpatialEye.Framework.Geometry;
using SpatialEye.Framework.Features;
using SpatialEye.Framework.Maps;
using System.Linq;
using System.Globalization;
namespace Lite
{
public class LiteFactibilidadViewModel : LiteMapViewModel
{
#region Constructor
public LiteFactibilidadViewModel(Messenger messenger, MapDefinition definition, MapInteractionHandler interactionHandler, EpsgCoordinateSystemReferenceCollection epsgCSs, World world = null, Envelope envelope = null, Feature owner = null)
: base(messenger, definition, false, interactionHandler, epsgCSs, world, envelope, owner)
{
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
using WebApi.Models;
using System.Configuration;
namespace WebApi.Controllers
{
public class TransactionController : ApiController
{
public HttpResponseMessage Get()
{
DataTable table = new DataTable();
string query = "select TransactionID, CustomerID, Amount, BankName, MerchantName,Currency from Transactions";
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PaymentDB"].ConnectionString))
using (var cmd = new SqlCommand(query, conn))
using (var adpt = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
adpt.Fill(table);
}
return Request.CreateResponse(HttpStatusCode.OK, table);
}
public HttpResponseMessage Get(int id)
{
DataTable table = new DataTable();
string query = "select TransactionID, CustomerID, Amount, BankName, MerchantName, Currency from Transactions where CustomerID='"+id+"'";
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PaymentDB"].ConnectionString))
using (var cmd = new SqlCommand(query, conn))
using(var adpt = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
adpt.Fill(table);
}
return Request.CreateResponse(HttpStatusCode.OK, table);
}
public string Post(Transaction trans)
{
try
{
DataTable table = new DataTable();
string query = "insert into dbo.Transactions Values('" + trans.TransactionID + @"'
,'"+trans.CustomerID+@"'
,'"+trans.Amount+@"'
,'" + trans.BankName+@"'
,'"+trans.MerchantName+ @"'
,'"+trans.Currency+ @"'
)";
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PaymentDB"].ConnectionString))
using (var cmd = new SqlCommand(query, conn))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table);
}
return "Add Successfully";
}
catch (Exception ex)
{
return "Failed to Add"+ex.ToString();
}
}
}
}
|
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Client.Helpers.Utils
{
public class KeyboardHelper
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
[DllImport("User32.Dll", EntryPoint = "PostMessageA")]
static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
public enum WMessages : int
{
WM_LBUTTONDOWN = 0x201,
WM_LBUTTONUP = 0x202,
WM_KEYDOWN = 0x100,
WM_KEYUP = 0x101,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14,
}
private const Int32 WM_SYSCOMMAND = 274;
private const UInt32 SC_CLOSE = 61536;
public static void HideKeyBoard()
{
IntPtr TouchhWnd = new IntPtr(0);
TouchhWnd = FindWindow("IPTip_Main_Window", null);
if (TouchhWnd == IntPtr.Zero)
return;
PostMessage(TouchhWnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
public static void RegisterShowKeyboard()
{
RegistryKey softwareKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\TabletTip\1.7", true);
if (softwareKey != null)
{
var reg=softwareKey.GetValue("EnableDesktopModeAutoInvoke");
if(reg==null || reg.ToString() !="1")
softwareKey.SetValue("EnableDesktopModeAutoInvoke", 1, RegistryValueKind.DWord);
}
string onScreenKeyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
Process proc = new Process();
string MainAppPath = "TabTip.exe";//the path of the exe file
proc.StartInfo.FileName = MainAppPath;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(onScreenKeyboardPath); ;
proc.Start();
}
public static void ShowKeyboard()
{
RegisterShowKeyboard();
}
public static void ShowKeyboardExtend()
{
var trayWnd = FindWindow("Shell_TrayWnd", null);
var nullIntPtr = new IntPtr(0);
if (trayWnd != nullIntPtr)
{
var trayNotifyWnd = FindWindowEx(trayWnd, nullIntPtr, "TrayNotifyWnd", null);
if (trayNotifyWnd != nullIntPtr)
{
var tIPBandWnd = FindWindowEx(trayNotifyWnd, nullIntPtr, "TIPBand", null);
if (tIPBandWnd != nullIntPtr)
{
PostMessage(tIPBandWnd, (UInt32)WMessages.WM_LBUTTONDOWN, 1, 65537);
PostMessage(tIPBandWnd, (UInt32)WMessages.WM_LBUTTONUP, 1, 65537);
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1._5_Throw
{
class Program
{
/*
* https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/keywords/throw
* Quando você lança apenas um throw está repassando a mesma exceção para frente e,
* dessa forma, outro trecho de código poderá capturar e saber o que vai fazer com a
* exceção original retendo todas as informações necessárias com o stack trace.
*/
static void Main(string[] args)
{
var s = new Sentence(null);
Console.WriteLine($"The first character is {s.GetFirstCharacter()}");
}
}
public class Sentence
{
public Sentence(string s)
{
Value = s;
}
public string Value { get; set; }
public char GetFirstCharacter()
{
try
{
return Value[0];
}
catch (Exception e)
{
throw;//Lança a exceção de origem... 'NullReferenceException'
}
}
}
}
|
// Copyright (c) Bruno Brant. All rights reserved.
using System;
namespace RestLittle.UI.Presenters
{
/// <summary>
/// Configuration for <see cref="ITrayIconView"/>.
/// </summary>
public interface ITrayIconViewConfiguration
{
/// <summary>
/// Gets the delay between consecutive warnings.
/// </summary>
TimeSpan WarningInterval { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolidPrinciples.InterfaceSegregation
{
interface ICreate
{
void CreateTask();
}
interface IAssign
{
void AssignTask();
}
interface ITaskProgress
{
void TaskProgress();
}
}
|
using System;
using System.Data;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Configuration;
namespace CIPMSOfficeObjects
{
public class CustomWord
{
private Application _wordApp = new Application();
private object _oMissing = System.Reflection.Missing.Value;
object _start = Type.Missing;
object _end = Type.Missing;
//object _count = Type.Missing;
//object _unit = Type.Missing;
readonly string _uploadFilePath = ConfigurationSettings.AppSettings["UploadFilePath"];
const int FontSize = 10;
const string StrFontName = "Franklin Gothic Book";
public string CreateWord(System.Data.DataTable dt)
{
object newTemplate = false;
//object fileName = "normal.dot";
object docType = WdNewDocumentType.wdNewBlankDocument;
object isVisible = false;
Document aDoc = _wordApp.Documents.Add(ref _oMissing, ref newTemplate, ref docType, ref isVisible);
//object fileToOpen = uploadFilePath + "Classic.dotx";
//Object missing = Type.Missing;
//object newTemplate = false; //if want to open a new template, please set this to True;
//Document aDoc = WordApp.Documents.Add(ref fileToOpen, ref newTemplate, ref oMissing, ref oMissing);
try
{
//Document aDoc = WordApp.Documents.Add(ref oMissing, ref newTemplate, ref docType, ref isVisible);
// need to see the created document, so make it visible
//WordApp.Visible = true;
aDoc.Activate();
Range rng = aDoc.Range(ref _start, ref _end);
rng.InsertBefore("Program Profile Information Report");
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
for (int iCount = 0; iCount < dt.Rows.Count; iCount++)
FillTable(aDoc, dt, dt.Rows[iCount], GetEndOfRange(rng, aDoc));
DocumentSaveAs(aDoc);
}
catch (Exception ex)
{
throw ex;
}
finally
{
_wordApp = null;
/*
newTemplate = null;
*/
//fileToOpen = null;
/*
docType = null;
*/
/*
isVisible = null;
*/
_oMissing = _start = _end = null;
/*
aDoc = null;
*/
}
return "success";
}
private Table CreateTable(_Document aDoc, int noOfRows, int noOfColumns, Range rng, int tblCount)
{
if (aDoc == null) throw new ArgumentNullException("aDoc");
//object start = Type.Missing;
//object end = Type.Missing;
//object count = Type.Missing;
//object unit = Type.Missing;
//aDoc.Range(ref start, ref end).Delete(ref unit, ref count);
//Range rng = aDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
rng.SetRange(rng.End, rng.End);
object defaultTableBehaviour = Type.Missing;
object autoFitBehaviour = Type.Missing;
aDoc.Tables.Add(rng, noOfRows, noOfColumns, ref defaultTableBehaviour, ref autoFitBehaviour);
Table tbl = aDoc.Tables[tblCount];
return tbl;
}
private void FillTable(Document aDoc, System.Data.DataTable dt, DataRow dr, Range rng)
{
GetEndOfRange(rng, aDoc);
//rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
Table tblMain = CreateTable(aDoc, 1, 2, GetEndOfRange(rng, aDoc), aDoc.Tables.Count + 1);
int drColNumber = 0;
Range rngCell;
int col = 1;
int row = 1;
tblMain.Range.Font.Size = FontSize;
tblMain.Range.Font.Name = StrFontName;
string tempFileName = _uploadFilePath + "temp" + DateTime.Now.Ticks + ".html";
for (int iCol = 0; iCol <= 3; iCol++)
{
tblMain.Rows.Add(ref _oMissing);
rngCell = tblMain.Cell(row, col).Range;
rngCell.Text = (iCol==0?"A\t":(iCol==1?"B\t":(iCol==2?"C\t":(iCol==3?"D\t":"")))) + dt.Columns[iCol].ColumnName;
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
rngCell.Bold = (int)WdConstants.wdToggle;
rngCell.Underline = WdUnderline.wdUnderlineSingle;
rngCell = tblMain.Cell(row, col + 1).Range;
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
rngCell.Text = dr.ItemArray.GetValue(iCol).ToString();
row++;
drColNumber = iCol;
}
//rng.SetRange(rng.End, rng.End);
drColNumber++;
if (!String.IsNullOrEmpty(dr[drColNumber].ToString()))
{
rng.InsertParagraphAfter();
Table tblSummary = CreateTable(aDoc, 1, 1, GetEndOfRange(rng, aDoc), aDoc.Tables.Count + 1);
tblSummary.Range.Font.Size = FontSize;
tblSummary.Range.Font.Name = StrFontName;
tblSummary.Rows.Add(ref _oMissing);
rngCell = tblSummary.Cell(1, 1).Range;
rngCell.Text = "E\tSummary Page Program Blurb:";
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
rngCell.Bold = (int)WdConstants.wdToggle;
rngCell.Underline = WdUnderline.wdUnderlineSingle;
rngCell = tblSummary.Cell(2, 1).Range;
CreateFile(tempFileName, dr[drColNumber].ToString());
//object rangeSummaryFile = tblSummary.Cell(2, 1).Range;
rngCell.InsertFile(tempFileName, ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing);// = dr[drColNumber].ToString();
DeleteFile(tempFileName);
}
drColNumber++;//For Summary
drColNumber++;//First timer (F:)
drColNumber++;//second timer(G:)
if (!String.IsNullOrEmpty(dr[drColNumber].ToString()))
{
rng.InsertParagraphAfter();
Table tblGrade = CreateTable(aDoc, 1, 2, GetEndOfRange(rng, aDoc), aDoc.Tables.Count + 1);
tblGrade.Range.Font.Size = FontSize;
tblGrade.Range.Font.Name = StrFontName;
tblGrade.Rows.Add(ref _oMissing);
rngCell = tblGrade.Cell(1, 1).Range;
rngCell.Text = "H\tGrade eligibility";
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
rngCell.Bold = (int)WdConstants.wdToggle;
rngCell.Underline = WdUnderline.wdUnderlineSingle;
rngCell = tblGrade.Cell(1, 2).Range;
rngCell.Text = "Eligible = " + dr[drColNumber];
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
drColNumber++;//For grade
if (!String.IsNullOrEmpty(dr[drColNumber].ToString()))
{
rng.InsertParagraphAfter();
Table tblDaySchool = CreateTable(aDoc, 1, 2, GetEndOfRange(rng, aDoc), aDoc.Tables.Count + 1);
tblDaySchool.Range.Font.Size = FontSize;
tblDaySchool.Range.Font.Name = StrFontName;
tblDaySchool.Rows.Add(ref _oMissing);
rngCell = tblDaySchool.Cell(1, 1).Range;
rngCell.Text = "M\tDay school eligibility";
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
rngCell.Bold = (int)WdConstants.wdToggle;
rngCell.Underline = WdUnderline.wdUnderlineSingle;
rngCell = tblDaySchool.Cell(1, 2).Range;
rngCell.Text = dr[drColNumber].ToString()=="true"?"yes":"no";
rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
//drColNumber++;//For dayschool
}
private void DocumentSaveAs(_Document aDoc)
{
aDoc.Save();
aDoc.Close(ref _oMissing, ref _oMissing, ref _oMissing);
_wordApp.Quit(ref _oMissing, ref _oMissing, ref _oMissing);
}
protected Range GetEndOfRange(Range dataRange, Document aDoc)
{
Object startofDoc = dataRange.End - 1;
Object endofDoc = dataRange.End - 1;
Range rng = aDoc.Range(ref startofDoc, ref endofDoc);
return rng;
}
public void CreateFile(string tempFileName,string fileString)
{
StreamWriter stream = File.CreateText(tempFileName);
stream.Write(fileString);
stream.Flush();
stream.Close();
}
public void DeleteFile(string tempFileName)
{
FileInfo fileInfo = new FileInfo(tempFileName);
if (fileInfo.Exists) fileInfo.Delete();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using UdpSimulator.Components;
using UdpSimulator.Models;
using UdpSimulator.Utilities;
namespace UdpSimulator.ViewModels
{
/// <summary>
/// MainWindow~UDP送信処理用DataContext.
/// </summary>
public class MainWindowDataContext : ModelBase, IUdpTransmitter
{
private readonly IWeakEventListener propertyChangedListener;
private readonly IUdpTransmitter udpTransmitter;
public MainWindowDataContext()
{
this.udpTransmitter = new UdpTransmitter()
{
CommandDialog = new RelayCommand<string>((_) =>
{
DialogService.Show("入力エラー", _);
})
};
this.propertyChangedListener = new PropertyChangedWeakEventListener(
this.RaisePropertyChanged);
PropertyChangedEventManager.AddListener(
this.udpTransmitter,
this.propertyChangedListener,
string.Empty);
}
public bool Connected { get => udpTransmitter.Connected; set => udpTransmitter.Connected = value; }
public string DestinationIpAddress { get => udpTransmitter.DestinationIpAddress; set => udpTransmitter.DestinationIpAddress = value; }
public int DestinationPort { get => udpTransmitter.DestinationPort; set => udpTransmitter.DestinationPort = value; }
public int TransmissionInterval { get => udpTransmitter.TransmissionInterval; set { udpTransmitter.TransmissionInterval = value; } }
public IEnumerable<SimulationObject> SimulationObjects => udpTransmitter.SimulationObjects;
public ICommand CommandConnection => udpTransmitter.CommandConnection;
public ICommand CommandSaveObjects => udpTransmitter.CommandSaveObjects;
/// <summary>
/// テキスト入力許可:0~9.
/// </summary>
/// <param name="sender">送信元コントロール(TextBox).</param>
/// <param name="e">EventArgs.</param>
public void IsAllowedUnsignedInput(object sender, TextCompositionEventArgs e)
{
this.IsAllowed(sender as TextBox, e, new Regex("[^0-9]+"));
}
/// <summary>
/// テキスト入力許可:0~9、ピリオド(.)、マイナス符号(-).
/// </summary>
/// <param name="sender">送信元コントロール(TextBox).</param>
/// <param name="e">EventArgs.</param>
public void IsAllowedNumericalInput(object sender, TextCompositionEventArgs e)
{
this.IsAllowed(sender as TextBox, e, new Regex("[^0-9.-]+"));
}
/// <summary>
/// テキスト入力許可.
/// </summary>
/// <param name="sender">TextBox.</param>
/// <param name="e">EventArgs.</param>
/// <param name="regex">入力可否判別.</param>
private void IsAllowed(TextBox textBox, TextCompositionEventArgs e, Regex regex)
{
var text = textBox.Text + e.Text;
e.Handled = regex.IsMatch(text);
}
/// <summary>
/// WeakEventListener(ViewModel破棄時メモリリーク対策用).
/// </summary>
private class PropertyChangedWeakEventListener : IWeakEventListener
{
private readonly Action<string> raisePropertyChangedAction;
public PropertyChangedWeakEventListener(Action<string> raisePropertyChangedAction)
{
this.raisePropertyChangedAction = raisePropertyChangedAction;
}
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
// PropertyChangedEventManager時のみ処理.
if (typeof(PropertyChangedEventManager) != managerType)
{
return false;
}
// PropertyChangedEventArgs時のみ処理.
if (!(e is PropertyChangedEventArgs evt))
{
return false;
}
// コンストラクタで渡されたコールバックを呼び出す.
this.raisePropertyChangedAction(evt.PropertyName);
return true;
}
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Atc.CodeDocumentation
{
internal static class XmlDocumentCommentParser
{
internal static XmlDocumentComment?[] ParseXmlComment(XDocument xDocument, string? namespaceMatch)
{
return xDocument.Descendants("member")
.Select(x =>
{
var attributeValue = x.Attribute("name")?.Value;
if (attributeValue == null)
{
return null;
}
var match = Regex.Match(attributeValue, @"(.):(.+)\.([^.()]+)?(\(.+\)|$)");
if (!match.Groups[1].Success)
{
return null;
}
var memberType = (MemberType)match.Groups[1].Value[0];
if (memberType == MemberType.None)
{
return null;
}
var summaryXml = x.Elements("summary").FirstOrDefault()?.ToString()
?? x.Element("summary")?.ToString()
?? string.Empty;
summaryXml = Regex.Replace(summaryXml, @"<\/?summary>", string.Empty);
summaryXml = Regex.Replace(summaryXml, @"<para\s*/>", Environment.NewLine);
summaryXml = Regex.Replace(summaryXml, @"<see cref=""\w:([^\""]*)""\s*\/>", m => ResolveSeeElement(m, namespaceMatch));
var summary = Regex.Replace(summaryXml, @"<(type)*paramref name=""([^\""]*)""\s*\/>", e => $"`{e.Groups[1].Value}`");
if (summary.Length > 0)
{
summary = string.Join(" ", summary.Split(new[] { "\r", "\n", "\t" }, StringSplitOptions.RemoveEmptyEntries).Select(y => y.Trim()));
}
var returns = ((string)x.Element("returns")) ?? string.Empty;
var remarks = ((string)x.Element("remarks")) ?? string.Empty;
var code = (string)x.Element("code") ?? string.Empty;
if (code.Length > 0)
{
code = TrimCode(code, true);
}
var example = (string)x.Element("example") ?? string.Empty;
if (example.Length > 0)
{
example = TrimCode(example, false);
}
var parameters = x.Elements("param")
.Select(e => Tuple.Create(e.Attribute("name")?.Value ?? "Unknown", e))
.Distinct(new TupleEqualityComparer<string, XElement>())
.ToDictionary(e => e.Item1, e => e.Item2.Value, StringComparer.Ordinal);
var className = (memberType == MemberType.Type)
? match.Groups[2].Value + "." + match.Groups[3].Value
: match.Groups[2].Value;
return new XmlDocumentComment
{
MemberType = memberType,
ClassName = className,
MemberName = match.Groups[3].Value,
Summary = summary.Trim(),
Remarks = remarks.Trim(),
Code = code,
Example = example,
Parameters = parameters,
Returns = returns.Trim(),
};
})
.Where(x => x != null)
.ToArray();
}
[SuppressMessage("Critical Code Smell", "S3776:Cognitive Complexity of methods should not be too high", Justification = "OK.")]
private static string TrimCode(string code, bool trimEachLine)
{
var sb = new StringBuilder();
var sa = code.Split(new[] { '\n' }, StringSplitOptions.None);
var ei = sa.Length - 1;
const string lineStartOverheadSpaces = " ";
for (var i = 0; i < sa.Length; i++)
{
if (i == 0 && sa[i].Length == 0)
{
continue;
}
if (i == ei && sa[i].TrimExtended().Length == 0)
{
continue;
}
if (trimEachLine)
{
sb.AppendLine(sa[i].TrimExtended());
}
else
{
sb.AppendLine(sa[i].StartsWith(lineStartOverheadSpaces, StringComparison.Ordinal)
? sa[i].Substring(lineStartOverheadSpaces.Length)
: sa[i]);
}
}
var s = sb.ToString();
var charsToRemove = 0;
if (s.EndsWith(Environment.NewLine, StringComparison.Ordinal))
{
charsToRemove += 2;
}
if (s.EndsWith(".", StringComparison.Ordinal))
{
charsToRemove++;
}
return charsToRemove > 0
? s.Substring(0, s.Length - charsToRemove)
: s;
}
private static string ResolveSeeElement(Match m, string? ns)
{
var typeName = m.Groups[1].Value;
if (string.IsNullOrWhiteSpace(ns))
{
return $"`{typeName}`";
}
return typeName.StartsWith(ns, StringComparison.Ordinal)
? $"[{typeName}]({Regex.Replace(typeName, "\\.(?:.(?!\\.))+$", me => me.Groups[0].Value.Replace(".", "#", StringComparison.Ordinal).ToLower(GlobalizationConstants.EnglishCultureInfo))})"
: $"`{typeName}`";
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BlazorShared.Models.Appointment;
using Microsoft.Extensions.Logging;
namespace FrontDesk.Blazor.Services
{
public class AppointmentService
{
private readonly HttpService _httpService;
private readonly ILogger<AppointmentService> _logger;
public AppointmentService(HttpService httpService, ILogger<AppointmentService> logger)
{
_httpService = httpService;
_logger = logger;
}
public async Task<AppointmentDto> CreateAsync(CreateAppointmentRequest appointment)
{
return (await _httpService.HttpPostAsync<CreateAppointmentResponse>("appointments", appointment)).Appointment;
}
public async Task<AppointmentDto> EditAsync(UpdateAppointmentRequest appointment)
{
return (await _httpService.HttpPutAsync<UpdateAppointmentResponse>("appointments", appointment)).Appointment;
}
public async Task DeleteAsync(Guid appointmentId)
{
await _httpService.HttpDeleteAsync<DeleteAppointmentResponse>("appointments", appointmentId);
}
public async Task<AppointmentDto> GetByIdAsync(Guid appointmentId)
{
return (await _httpService.HttpGetAsync<GetByIdAppointmentResponse>($"appointments/{appointmentId}")).Appointment;
}
public async Task<List<AppointmentDto>> ListPagedAsync(int pageSize)
{
_logger.LogInformation("Fetching appointments from API.");
return (await _httpService.HttpGetAsync<ListAppointmentResponse>($"appointments")).Appointments;
}
public async Task<List<AppointmentDto>> ListAsync()
{
_logger.LogInformation("Fetching appointments from API.");
return (await _httpService.HttpGetAsync<ListAppointmentResponse>($"appointments")).Appointments;
}
}
}
|
using UnityEngine;
namespace Assets.Scripts.Buildings.Controller
{
public class BuildingCreator : MonoBehaviour
{
public GameObject[] buildingVarieties; //Building listesi
private static BuildingCreator _instance;//GameManager için bir singleton
public static BuildingCreator Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<BuildingCreator>();
if (_instance == null) Debug.LogError("You need add BuildingCreator to a GameObject!");
}
return _instance;
}
}
/// <summary>
/// Building varieties indisine göre bina oluşturur.
/// </summary>
/// <param name="arrayIndex">buildingVarieties indexi</param>
public void CreateBuilding(int arrayIndex)
{
//Binamızın clonunu oluşturuyoruz
var buildingGameObject = Instantiate(buildingVarieties[arrayIndex], new Vector3(1000, 1000, 0),
Quaternion.identity);
//Sürükle bırak sisteminin çalışabilmesi için gerekli
buildingGameObject.GetComponent<MovableObject>().SetForCreating();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Choice represents a unique player's choice.
/// </summary>
public class Choice {
public static int suitCounter, valueCounter, colorCounter = 0;
public static int totalPoints = 0;
public static int orderCounter = 0;
public static int totalMatches = 0;
public static float precision = 0f;
/* public static float averageTimeToChoose = 0f;
public static float averageTimeToPlay = 0f;
public static float averageTimeToMemorize = 0f;
public static float[] rangeOfTimeToChoose = { 0f, 0f };
public static float[] rangeOfTimeToPlay = { 0f, 0f };
public static float[] rangeOfTimeToMemorize = { 0f, 0f };*/
public int[] objectiveCard = new int[3], choiceCard = new int[3];
public bool suitMatch, valueMatch, colorMatch, match;
public int pointMatch;
public int order;
public int numOptions;
/* public float timeToChoose;
public float timeToPlay;
public float timeToMemorize;*/
public static float AverageTimeToChoose = 0f;
public static float AverageTimeToPlay = 0f;
public static float AverageTimeToMemorize = 0f;
public static float TimeToRead = 0f;
public static float[] RangeTimeToChoose = {float.PositiveInfinity, float.NegativeInfinity};
public static float[] RangeTimeToPlay = {float.PositiveInfinity, float.NegativeInfinity};
public static float[] RangeTimeToMemorize = {float.PositiveInfinity, float.NegativeInfinity};
public float TimeToChoose = 0f;
public float TimeToPlay = 0f;
public float TimeToMemorize = 0f;
public float choiceChanged = 0f;
private const int suitScore = 5;
private const int colorScore = 5;
private const int valueScore = 10;
private const int extraScore = 10;
private const int timeScore = 10;
/// <summary>
/// Initializes a new instance of the <see cref="Choice"/> class comparing the card chosen with objective card and the number of options.
/// </summary>
/// <param name="objective">Objective card.</param>
/// <param name="choice">Chosen card.</param>
/// <param name="nOptions">Number of card options.</param>
public Choice(Card objective, Card choice, int nOptions, float timeToChoose, float timeToPlay, float timeToMemorize)
{
pointMatch = 0;
numOptions = nOptions;
objectiveCard[0] = objective.value;
objectiveCard[1] = objective.suit;
objectiveCard[2] = objective.color;
choiceCard[0] = choice.value;
choiceCard[1] = choice.suit;
choiceCard[2] = choice.color;
suitMatch = objective.suit == choice.suit;
valueMatch = objective.value == choice.value;
colorMatch = objective.color == choice.color;
if (suitMatch)
{
pointMatch += suitScore;
suitCounter++;
}
if (colorMatch)
{
pointMatch += colorScore;
colorCounter++;
}
if (valueMatch)
{
pointMatch += valueScore;
valueCounter++;
}
// Extra point for exact answer
if (pointMatch == suitScore + colorScore + valueScore)
{
match = true;
pointMatch += extraScore;
totalMatches++;
// Extra point for faster answer
pointMatch += Mathf.Clamp(Mathf.FloorToInt((timeScore + 1f - 2f * timeToChoose)), 0, timeScore);
}
else
match = false;
/*
this.timeToChoose = timeToChoose;
this.timeToPlay = timeToPlay;
this.timeToMemorize = timeToMemorize;
rangeOfTimeToChoose = CheckExtremes(rangeOfTimeToChoose, timeToChoose);
rangeOfTimeToPlay = CheckExtremes(rangeOfTimeToPlay, timeToPlay);
rangeOfTimeToMemorize = CheckExtremes(rangeOfTimeToMemorize, timeToPlay);
averageTimeToChoose = (averageTimeToChoose * orderCounter + timeToChoose) / (orderCounter + 1);
averageTimeToPlay = (averageTimeToPlay * orderCounter + timeToPlay) / (orderCounter + 1);
averageTimeToMemorize = (averageTimeToMemorize * orderCounter + timeToPlay) / (orderCounter + 1);
*/
TimeToChoose = timeToChoose;
TimeToPlay = timeToPlay;
TimeToMemorize = timeToMemorize;
AverageTimeToChoose = GameBase.Average(AverageTimeToChoose, timeToChoose, orderCounter);
AverageTimeToPlay = GameBase.Average(AverageTimeToPlay, timeToPlay, orderCounter);
AverageTimeToMemorize = GameBase.Average(AverageTimeToMemorize, timeToMemorize, orderCounter);
RangeTimeToChoose = GameBase.CheckExtremes(timeToChoose, RangeTimeToChoose);
RangeTimeToPlay = GameBase.CheckExtremes(timeToPlay, RangeTimeToPlay);
RangeTimeToMemorize = GameBase.CheckExtremes(timeToMemorize, RangeTimeToMemorize);
order = orderCounter;
orderCounter++;
totalPoints += pointMatch;
}
public Choice ()
{
objectiveCard = new int[3];
choiceCard = new int[3];
pointMatch = order = numOptions = 0;
suitMatch = false;
valueMatch = false;
colorMatch = false;
match = false;
TimeToChoose = 0f;
TimeToPlay = 0f;
TimeToMemorize = 0f;
}
public static bool operator ==(Choice A, Choice B)
{
if ((A.suitMatch == B.suitMatch) && (A.valueMatch == B.valueMatch) && (A.colorMatch == B.colorMatch))
return true;
else
return false;
}
public static bool operator !=(Choice A, Choice B)
{
if ((A.suitMatch != B.suitMatch) || (A.valueMatch != B.valueMatch) || (A.colorMatch != B.colorMatch))
return true;
else
return false;
}
public static implicit operator int(Choice choice)
{
return choice.pointMatch;
}
public static implicit operator bool(Choice choice)
{
if (choice.pointMatch == 30)
return true;
else
return false;
}
public override bool Equals(object choice)
{
try
{
return (this == (Choice)choice);
}
catch
{
return false;
}
}
public override int GetHashCode()
{
return (pointMatch);
}
public static int CountMatches(List<Choice> choices)
{
int numOfMatches = 0;
foreach (Choice choice in choices)
{
if (choice)
numOfMatches++;
}
return numOfMatches;
}
public static void ResetChoice()
{
suitCounter = valueCounter = colorCounter = 0;
totalPoints = 0;
orderCounter = 0;
totalMatches = 0;
precision = 0f;
AverageTimeToChoose = 0f;
AverageTimeToPlay = 0f;
AverageTimeToMemorize = 0f;
TimeToRead = 0f;
RangeTimeToChoose = new float[] {float.PositiveInfinity, float.NegativeInfinity};
RangeTimeToPlay = new float[] {float.PositiveInfinity, float.NegativeInfinity};
RangeTimeToMemorize = new float[] {float.PositiveInfinity, float.NegativeInfinity};
}
public static int CheckPoints(Card a, Card b)
{
int match = 0;
if (a.suit == b.suit)
match += suitScore;
if (a.value == b.value)
match += valueScore;
if (a.color == b.color)
match += colorScore;
if (match == suitScore + valueScore + colorScore)
match += extraScore + Mathf.RoundToInt(timeScore/2f);
return match;
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Vanara.Extensions;
using Vanara.InteropServices;
using static Vanara.PInvoke.IpHlpApi;
using static Vanara.PInvoke.Ws2_32;
namespace Vanara.PInvoke.Tests
{
public static class IPAddressExt
{
public static System.Net.IPAddress Convert(this SOCKET_ADDRESS sockAddr)
{
switch ((ADDRESS_FAMILY)Marshal.ReadInt16(sockAddr.lpSockAddr))
{
case ADDRESS_FAMILY.AF_INET:
return new System.Net.IPAddress((long)sockAddr.lpSockAddr.ToStructure<SOCKADDR_IN>().sin_addr);
case ADDRESS_FAMILY.AF_INET6:
return new System.Net.IPAddress(sockAddr.lpSockAddr.ToStructure<SOCKADDR_IN6>().sin6_addr);
default:
throw new Exception("Non-IP address family");
}
}
}
[TestFixture()]
public class IpHlpApiTests
{
private static readonly IntPtr NotifyData = new IntPtr(8943934);
private static IP_ADAPTER_ADDRESSES primaryAdapter;
[Test]
public void AddDeleteIPAddressTest()
{
var newIp = new IN_ADDR(192, 168, 0, 252);
var mask = new IN_ADDR(255, 255, 255, 0);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.That(AddIPAddress(newIp, mask, primaryAdapter.IfIndex, out var ctx, out var inst), Is.Zero);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.That(DeleteIPAddress(ctx), Is.Zero);
}
[Test]
public void SetGetIpInterfaceEntryTest()
{
var mibrow = new MIB_IPINTERFACE_ROW(ADDRESS_FAMILY.AF_INET, primaryAdapter.Luid);
Assert.That(GetIpInterfaceEntry(ref mibrow), Is.Zero);
var prev = mibrow.SitePrefixLength;
mibrow.SitePrefixLength = 0;
Assert.That(SetIpInterfaceEntry(mibrow), Is.Zero);
mibrow = new MIB_IPINTERFACE_ROW(ADDRESS_FAMILY.AF_INET, primaryAdapter.Luid);
Assert.That(GetIpInterfaceEntry(ref mibrow), Is.Zero);
Assert.That(mibrow.PathMtuDiscoveryTimeout, Is.EqualTo(600000));
mibrow.SitePrefixLength = prev;
Assert.That(SetIpInterfaceEntry(mibrow), Is.Zero);
}
[Test]
public void CreateSetDeleteIpNetEntry2Test()
{
var target = new IN_ADDR(192, 168, 0, 202);
Assert.That(GetBestRoute(target, 0, out var fwdRow), Is.Zero);
var mibrow = new MIB_IPNET_ROW2(new SOCKADDR_IN(target), fwdRow.dwForwardIfIndex, SendARP(target));
Assert.That(GetIpNetTable2(ADDRESS_FAMILY.AF_INET, out var t1), Is.Zero);
if (HasVal(t1, mibrow))
Assert.That(DeleteIpNetEntry2(ref mibrow), Is.Zero);
Assert.That(CreateIpNetEntry2(ref mibrow), Is.Zero);
GetIpNetTable2(ADDRESS_FAMILY.AF_INET, out var t2);
Assert.That(HasVal(t2, mibrow), Is.True);
Assert.That(DeleteIpNetEntry2(ref mibrow), Is.Zero);
GetIpNetTable2(ADDRESS_FAMILY.AF_INET, out var t3);
Assert.That(HasVal(t3, mibrow), Is.False);
bool HasVal(IEnumerable<MIB_IPNET_ROW2> t, MIB_IPNET_ROW2 r) =>
t.Any(tr => tr.Address.Ipv4.sin_addr == r.Address.Ipv4.sin_addr && tr.InterfaceIndex == r.InterfaceIndex && tr.PhysicalAddress.SequenceEqual(r.PhysicalAddress));
}
[Test]
public void CreateGetDeleteAnycastIpAddressEntryTest()
{
var target = new IN6_ADDR(new byte[] { 0xfe, 0x3f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0x00 });
var mibrow = new MIB_ANYCASTIPADDRESS_ROW(new SOCKADDR_IN6(target, 0), primaryAdapter.Luid);
Assert.That(GetAnycastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t1), Is.Zero);
if (t1.Contains(mibrow))
Assert.That(DeleteAnycastIpAddressEntry(ref mibrow), Is.Zero);
Assert.That(CreateAnycastIpAddressEntry(ref mibrow), Is.Zero);
GetAnycastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t2);
Assert.That(t2, Has.Member(mibrow));
Assert.That(GetAnycastIpAddressEntry(ref mibrow), Is.Zero);
Assert.That(DeleteAnycastIpAddressEntry(ref mibrow), Is.Zero);
GetAnycastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t3);
Assert.That(t3, Has.No.Member(mibrow));
}
[Test]
public void CreateSetGetDeleteUnicastIpAddressEntryTest()
{
var target = new IN6_ADDR(new byte[] { 0xfe, 0x3f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0x00 });
var mibrow = new MIB_UNICASTIPADDRESS_ROW(new SOCKADDR_IN6(target, 0), primaryAdapter.Luid);
Assert.That(GetUnicastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t1), Is.Zero);
if (t1.Contains(mibrow))
Assert.That(DeleteUnicastIpAddressEntry(ref mibrow), Is.Zero);
Assert.That(CreateUnicastIpAddressEntry(ref mibrow), Is.Zero);
GetUnicastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t2);
Assert.That(t2, Has.Member(mibrow));
mibrow.PreferredLifetime = 500000;
Assert.That(SetUnicastIpAddressEntry(mibrow), Is.Zero);
Assert.That(GetUnicastIpAddressEntry(ref mibrow), Is.Zero);
Assert.That(DeleteUnicastIpAddressEntry(ref mibrow), Is.Zero);
GetUnicastIpAddressTable(ADDRESS_FAMILY.AF_INET6, out var t4);
Assert.That(t4, Has.No.Member(mibrow));
}
[Test]
public void CreateSetDeleteIpForwardEntry2Test()
{
var target = new IN6_ADDR(new byte[] { 0xfe, 0x3f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0x00 });
var mibrow = new MIB_IPFORWARD_ROW2(new IP_ADDRESS_PREFIX((SOCKADDR_IN6)IN6_ADDR.Unspecified, 128), (SOCKADDR_IN6)target, primaryAdapter.Luid)
{
Protocol = MIB_IPFORWARD_PROTO.MIB_IPPROTO_NETMGMT,
Metric = 1
};
DeleteIpForwardEntry2(ref mibrow);
Assert.That(CreateIpForwardEntry2(ref mibrow), Is.Zero);
mibrow.PreferredLifetime = 500000;
Assert.That(SetIpForwardEntry2(mibrow), Is.Zero);
Assert.That(GetIpForwardEntry2(ref mibrow), Is.Zero);
Assert.That(DeleteIpForwardEntry2(ref mibrow), Is.Zero);
}
// TODO: [Test]
public void EnableUnenableRouterTest()
{
throw new NotImplementedException();
}
[Test]
public void FlushIpNetTable2Test()
{
Assert.That(FlushIpNetTable2(ADDRESS_FAMILY.AF_INET6, primaryAdapter.IfIndex), Is.Zero);
}
[Test]
public void FlushIpPathTableTest()
{
Assert.That(FlushIpPathTable(ADDRESS_FAMILY.AF_INET6), Is.Zero);
}
[Test]
public void GetAdapterIndexTest()
{
const string prefix = "\\DEVICE\\TCPIP_";
Assert.That(GetAdapterIndex(prefix + primaryAdapter.AdapterName, out var idx), Is.Zero);
Assert.That(idx, Is.EqualTo(primaryAdapter.IfIndex));
Assert.That(GetAdapterIndex(primaryAdapter.AdapterName, out idx), Is.EqualTo(Win32Error.ERROR_FILE_NOT_FOUND));
Assert.That(GetAdapterIndex("__Bogus**__", out idx), Is.EqualTo(Win32Error.ERROR_INVALID_PARAMETER));
}
[Test]
public void GetAdaptersAddressesTest()
{
Assert.That(() =>
{
foreach (var addrs in GetAdaptersAddresses(GetAdaptersAddressesFlags.GAA_FLAG_INCLUDE_PREFIX, ADDRESS_FAMILY.AF_UNSPEC))
{
Debug.WriteLine($"{addrs.IfIndex}) {addrs.AdapterName} ({addrs.FriendlyName});{addrs.Description};MAC:{PhysicalAddressToString(addrs.PhysicalAddress)}");
Debug.WriteLine(" Uni:" + string.Join(";", addrs.UnicastAddresses.Select(a => a.Address)));
Debug.WriteLine(" Any:" + string.Join(";", addrs.AnycastAddresses.Select(a => a.Address)));
Debug.WriteLine(" MCS:" + string.Join(";", addrs.MulticastAddresses.Select(a => a.Address)));
Debug.WriteLine(" DNS:" + string.Join(";", addrs.DnsServerAddresses.Select(a => a.Address)));
Debug.WriteLine(" Prfx:" + string.Join(";", addrs.Prefixes.Select(a => a.Address)));
Debug.WriteLine(" WINS:" + string.Join(";", addrs.WinsServerAddresses.Select(a => a.Address)));
Debug.WriteLine(" GTWY:" + string.Join(";", addrs.GatewayAddresses.Select(a => a.Address)));
Debug.WriteLine(" Sufx:" + string.Join(";", addrs.DnsSuffixes.Select(a => a.String)));
}
}, Throws.Nothing);
}
[Test]
public void GetAdaptersInfoTest()
{
uint len = 15000;
var mem = new SafeCoTaskMemHandle((int)len);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.That(GetAdaptersInfo((IntPtr)mem, ref len), Is.Zero);
Assert.That(((IntPtr)mem).LinkedListToIEnum<IP_ADAPTER_INFO>(i => i.Next), Is.Not.Empty);
#pragma warning restore CS0618 // Type or member is obsolete
}
[Test]
public void GetAnycastIpAddressEntryTableTest()
{
Assert.That(GetAnycastIpAddressTable(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.Zero);
var row = new MIB_ANYCASTIPADDRESS_ROW();
Assert.That(GetAnycastIpAddressEntry(ref row), Is.Not.Zero);
}
[Test]
public void GetBestInterfaceExTest()
{
#pragma warning disable CS0618 // Type or member is obsolete
var gw = primaryAdapter.GatewayAddresses.Select(a => a.Address.Convert()).FirstOrDefault();
#pragma warning restore CS0618 // Type or member is obsolete
var sa = new SOCKADDR(gw.GetAddressBytes(), 0, gw.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 0 : (uint)gw.ScopeId);
Assert.That(GetBestInterfaceEx(sa, out var idx), Is.Zero);
Assert.That(idx, Is.EqualTo(primaryAdapter.IfIndex));
}
[Test]
public void GetBestInterfaceTest()
{
#pragma warning disable CS0618 // Type or member is obsolete
var gw = (uint)primaryAdapter.GatewayAddresses.Select(a => a.Address.Convert()).FirstOrDefault().Address;
#pragma warning restore CS0618 // Type or member is obsolete
Assert.That(gw, Is.Not.Zero);
Assert.That(GetBestInterface(gw, out var idx), Is.Zero);
Assert.That(idx, Is.EqualTo(primaryAdapter.IfIndex));
}
[Test]
public void GetBestRoute2Test()
{
var addr = new SOCKADDR_INET { Ipv4 = new SOCKADDR_IN(new IN_ADDR(192, 168, 0, 202)) };
Assert.That(GetBestRoute2(IntPtr.Zero, primaryAdapter.IfIndex, IntPtr.Zero, ref addr, 0, out var rt, out var src), Is.Zero);
Assert.That(rt.InterfaceIndex, Is.EqualTo(primaryAdapter.IfIndex));
Assert.That(src.Ipv4.sin_addr, Is.EqualTo(new IN_ADDR(192, 168, 0, 203)));
}
[Test]
public void GetExtendedTcpTableTest()
{
Assert.That(() =>
{
var t1 = GetExtendedTcpTable<MIB_TCPTABLE>(TCP_TABLE_CLASS.TCP_TABLE_BASIC_ALL);
Assert.That(t1.dwNumEntries, Is.GreaterThan(0));
var t2 = GetExtendedTcpTable<MIB_TCPTABLE>(TCP_TABLE_CLASS.TCP_TABLE_BASIC_CONNECTIONS);
Assert.That(t2.dwNumEntries, Is.GreaterThan(0));
var t3 = GetExtendedTcpTable<MIB_TCPTABLE>(TCP_TABLE_CLASS.TCP_TABLE_BASIC_LISTENER);
Assert.That(t3.dwNumEntries, Is.GreaterThan(0));
var t4 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL);
Assert.That(t4.dwNumEntries, Is.GreaterThan(0));
var t5 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL, ADDRESS_FAMILY.AF_INET6);
Assert.That(t5.dwNumEntries, Is.GreaterThan(0));
var t6 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_CONNECTIONS);
Assert.That(t6.dwNumEntries, Is.GreaterThan(0));
var t7 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_CONNECTIONS, ADDRESS_FAMILY.AF_INET6);
Assert.That(t7.dwNumEntries, Is.GreaterThan(0));
var t8 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_LISTENER);
Assert.That(t8.dwNumEntries, Is.GreaterThan(0));
var t9 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_LISTENER, ADDRESS_FAMILY.AF_INET6);
Assert.That(t9.dwNumEntries, Is.GreaterThan(0));
var t10 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
Assert.That(t10.dwNumEntries, Is.GreaterThan(0));
var t11 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, ADDRESS_FAMILY.AF_INET6);
Assert.That(t11.dwNumEntries, Is.GreaterThan(0));
var t12 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_CONNECTIONS);
Assert.That(t12.dwNumEntries, Is.GreaterThan(0));
var t13 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_CONNECTIONS, ADDRESS_FAMILY.AF_INET6);
Assert.That(t13.dwNumEntries, Is.GreaterThan(0));
var t14 = GetExtendedTcpTable<MIB_TCPTABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_LISTENER);
Assert.That(t14.dwNumEntries, Is.GreaterThan(0));
var t15 = GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_PID>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_LISTENER, ADDRESS_FAMILY.AF_INET6);
Assert.That(t15.dwNumEntries, Is.GreaterThan(0));
}, Throws.Nothing);
Assert.That(() => GetExtendedTcpTable<MIB_TCPTABLE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL), Throws.InvalidOperationException);
Assert.That(() => GetExtendedTcpTable<MIB_TCP6TABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL), Throws.InvalidOperationException);
Assert.That(() => GetExtendedTcpTable<MIB_TCPTABLE_OWNER_MODULE>(TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL, ADDRESS_FAMILY.AF_INET6), Throws.InvalidOperationException);
}
[Test]
public void GetExtendedUdpTableTest()
{
Assert.That(() =>
{
var t1 = GetExtendedUdpTable<MIB_UDPTABLE>(UDP_TABLE_CLASS.UDP_TABLE_BASIC);
Assert.That(t1.dwNumEntries, Is.GreaterThan(0));
var t4 = GetExtendedUdpTable<MIB_UDPTABLE_OWNER_MODULE>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_MODULE);
Assert.That(t4.dwNumEntries, Is.GreaterThan(0));
var t5 = GetExtendedUdpTable<MIB_UDP6TABLE_OWNER_MODULE>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_MODULE, ADDRESS_FAMILY.AF_INET6);
Assert.That(t5.dwNumEntries, Is.GreaterThan(0));
var t10 = GetExtendedUdpTable<MIB_UDPTABLE_OWNER_PID>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
Assert.That(t10.dwNumEntries, Is.GreaterThan(0));
var t11 = GetExtendedUdpTable<MIB_UDP6TABLE_OWNER_PID>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, ADDRESS_FAMILY.AF_INET6);
Assert.That(t11.dwNumEntries, Is.GreaterThan(0));
}, Throws.Nothing);
Assert.That(() => GetExtendedUdpTable<MIB_UDPTABLE>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_MODULE), Throws.InvalidOperationException);
Assert.That(() => GetExtendedUdpTable<MIB_UDP6TABLE_OWNER_MODULE>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_MODULE), Throws.InvalidOperationException);
Assert.That(() => GetExtendedUdpTable<MIB_UDPTABLE_OWNER_MODULE>(UDP_TABLE_CLASS.UDP_TABLE_OWNER_MODULE, ADDRESS_FAMILY.AF_INET6), Throws.InvalidOperationException);
}
[Test]
public void GetIfEntry2ExTest()
{
var row = new MIB_IF_ROW2(primaryAdapter.IfIndex);
Assert.That(GetIfEntry2Ex(MIB_IF_ENTRY_LEVEL.MibIfEntryNormalWithoutStatistics, ref row), Is.Zero);
Assert.That(row.InterfaceLuid, Is.EqualTo(primaryAdapter.Luid));
}
[Test]
public void GetIfEntry2Test()
{
var row = new MIB_IF_ROW2(primaryAdapter.IfIndex);
Assert.That(GetIfEntry2(ref row), Is.Zero);
Assert.That(row.InterfaceLuid, Is.EqualTo(primaryAdapter.Luid));
}
[Test]
public void GetIfStackTableTest()
{
Assert.That(GetIfStackTable(out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
}
[Test]
public void GetIfTable2ExTest()
{
var e = GetIfTable2Ex(MIB_IF_TABLE_LEVEL.MibIfTableNormal, out var itbl);
Assert.That(e.Succeeded);
Assert.That(itbl.Table, Is.Not.Empty);
itbl.Dispose();
Assert.That(itbl.IsInvalid);
}
[Test]
public void GetIfTable2Test()
{
var e = GetIfTable2(out var itbl);
Assert.That(e.Succeeded);
Assert.That(itbl.Table, Is.Not.Empty);
itbl.Dispose();
Assert.That(itbl.IsInvalid);
}
[Test]
public void GetIfTableTest()
{
Assert.That(() =>
{
var t = GetIfTable();
Assert.That(t.dwNumEntries, Is.GreaterThan(0));
foreach (var r in t) ;
}, Throws.Nothing);
}
[Test]
public void GetInterfaceInfoTest()
{
Assert.That(() =>
{
var t = GetInterfaceInfo();
Assert.That(t.NumAdapters, Is.GreaterThan(0));
foreach (var r in t) ;
}, Throws.Nothing);
}
[Test]
public void GetInvertedIfStackTableTest()
{
Assert.That(GetInvertedIfStackTable(out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
}
[Test]
public void GetIpAddrTableTest()
{
Assert.That(() =>
{
var t = GetIpAddrTable();
Assert.That(t.dwNumEntries, Is.GreaterThan(0));
foreach (var r in t) ;
}, Throws.Nothing);
}
[Test]
public void GetIpForwardEntryTable2Test()
{
Assert.That(GetIpForwardTable2(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_IPFORWARD_ROW2 { DestinationPrefix = goodRow.DestinationPrefix, NextHop = goodRow.NextHop, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetIpForwardEntry2(ref row), Is.Zero);
Assert.That(row.InterfaceIndex, Is.Not.Zero.And.EqualTo(goodRow.InterfaceIndex));
}
[Test]
public void GetIpInterfaceEntryTableTest()
{
Assert.That(GetIpInterfaceTable(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_IPINTERFACE_ROW { Family = goodRow.Family, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetIpInterfaceEntry(ref row), Is.Zero);
Assert.That(row.InterfaceIndex, Is.Not.Zero.And.EqualTo(goodRow.InterfaceIndex));
}
[Test]
public void GetIpNetEntryTable2Test()
{
Assert.That(GetIpNetTable2(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_IPNET_ROW2 { Address = goodRow.Address, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetIpNetEntry2(ref row), Is.Zero);
Assert.That(row.InterfaceIndex, Is.Not.Zero.And.EqualTo(goodRow.InterfaceIndex));
}
[Test]
public void GetIpNetworkConnectionBandwidthEstimatesTest()
{
Assert.That(GetIpNetworkConnectionBandwidthEstimates(primaryAdapter.IfIndex, ADDRESS_FAMILY.AF_INET, out var est), Is.Zero);
Assert.That(est.InboundBandwidthInformation.Bandwidth, Is.GreaterThan(0));
Assert.That(est.OutboundBandwidthInformation.Bandwidth, Is.GreaterThan(0));
}
[Test]
public void GetIpPathEntryTableTest()
{
Assert.That(GetIpPathTable(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_IPPATH_ROW { Destination = goodRow.Destination, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetIpPathEntry(ref row), Is.Zero);
Assert.That((int)row.Source.si_family, Is.Not.Zero);
}
[Test]
public void GetMulticastIpAddressEntryTableTest()
{
Assert.That(GetMulticastIpAddressTable(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_MULTICASTIPADDRESS_ROW { Address = goodRow.Address, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetMulticastIpAddressEntry(ref row), Is.Zero);
Assert.That(row.InterfaceIndex, Is.Not.Zero.And.EqualTo(goodRow.InterfaceIndex));
}
[Test]
public void GetNetworkParamsTest()
{
Assert.That(() =>
{
var t = GetNetworkParams();
Assert.That(t.HostName, Is.Not.Null);
}, Throws.Nothing);
}
[Test]
public void GetPerAdapterInfoTest()
{
Assert.That(() =>
{
var info = GetPerAdapterInfo(primaryAdapter.IfIndex);
Assert.That(info.DnsServerList, Is.Not.Empty);
}, Throws.Nothing);
}
[Test]
public void GetTeredoPortTest()
{
Assert.That(GetTeredoPort(out var port), Is.Zero.Or.EqualTo(Win32Error.ERROR_NOT_READY));
}
[Test]
public void GetUnicastIpAddressEntryTableTest()
{
Assert.That(GetUnicastIpAddressTable(ADDRESS_FAMILY.AF_UNSPEC, out var table), Is.Zero);
Assert.That(table.NumEntries, Is.GreaterThan(0));
Assert.That(() => table.Table, Throws.Nothing);
var goodRow = table.Table[0];
var row = new MIB_UNICASTIPADDRESS_ROW { Address = goodRow.Address, InterfaceLuid = goodRow.InterfaceLuid };
Assert.That(GetUnicastIpAddressEntry(ref row), Is.Zero);
Assert.That(row.CreationTimeStamp, Is.Not.Zero.And.EqualTo(goodRow.CreationTimeStamp));
}
[Test]
public void GetUniDirectionalAdapterInfoTest()
{
Assert.That(() =>
{
var info = GetUniDirectionalAdapterInfo();
Assert.That(info.Address.Length, Is.GreaterThanOrEqualTo(0));
}, Throws.Nothing);
}
[Test]
public void if_indextonameANDif_nametoindexTest()
{
var sb = new StringBuilder(IF_MAX_STRING_SIZE, IF_MAX_STRING_SIZE);
Assert.That(if_indextoname(primaryAdapter.IfIndex, sb), Is.Not.EqualTo(IntPtr.Zero));
TestContext.WriteLine(sb);
Assert.That(if_nametoindex(sb.ToString()), Is.EqualTo(primaryAdapter.IfIndex));
}
[Test]
public void InitializeIpForwardEntryTest()
{
InitializeIpForwardEntry(out var entry);
Assert.That(entry.ValidLifetime, Is.Not.Zero);
Assert.That(entry.Loopback, Is.True);
}
[Test]
public void InitializeIpInterfaceEntryTest()
{
InitializeIpInterfaceEntry(out var entry);
Assert.That((int)entry.Family, Is.Zero);
Assert.That(entry.InterfaceIdentifier, Is.Not.Zero);
Assert.That(entry.SupportsNeighborDiscovery, Is.True);
}
[Test]
public void InitializeUnicastIpAddressEntryTest()
{
InitializeUnicastIpAddressEntry(out var entry);
Assert.That(entry.ValidLifetime, Is.Not.Zero);
Assert.That(entry.PrefixOrigin, Is.EqualTo(NL_PREFIX_ORIGIN.IpPrefixOriginUnchanged));
}
[Test]
public void IpReleaseRenewAddressTest()
{
var i = GetInterfaceInfo().First();
Assert.That(IpReleaseAddress(ref i), Is.Zero);
Assert.That(IpRenewAddress(ref i), Is.Zero);
var x = new IP_ADAPTER_INDEX_MAP() { Name = "Bogus" };
Assert.That(IpReleaseAddress(ref x), Is.EqualTo(Win32Error.ERROR_INVALID_PARAMETER));
Assert.That(IpRenewAddress(ref x), Is.EqualTo(Win32Error.ERROR_INVALID_PARAMETER));
}
// TODO: [Test]
public void NotifyAddrChangeTest()
{
throw new NotImplementedException();
}
[Test]
public void NotifyIpInterfaceChangeTest()
{
var fired = new ManualResetEvent(false);
var done = new ManualResetEvent(false);
new Thread(() =>
{
try
{
Assert.That(NotifyIpInterfaceChange(ADDRESS_FAMILY.AF_UNSPEC, NotifyFunc, NotifyData, true, out var hNot), Is.Zero);
fired.WaitOne(3000);
Assert.That(CancelMibChangeNotify2(hNot), Is.Zero);
}
finally
{
done.Set();
}
}).Start();
Assert.That(done.WaitOne(5000), Is.True);
void NotifyFunc(IntPtr CallerContext, IntPtr Row, MIB_NOTIFICATION_TYPE NotificationType)
{
Assert.That(CallerContext, Is.EqualTo(NotifyData));
TestContext.WriteLine(Row.ToString());
Assert.That(NotificationType, Is.EqualTo(MIB_NOTIFICATION_TYPE.MibInitialNotification));
fired.Set();
}
}
[Test]
public void NotifyRouteChange2Test()
{
var fired = new ManualResetEvent(false);
var done = new ManualResetEvent(false);
new Thread(() =>
{
try
{
Assert.That(NotifyRouteChange2(ADDRESS_FAMILY.AF_UNSPEC, NotifyFunc, NotifyData, true, out var hNot), Is.Zero);
fired.WaitOne(3000);
Assert.That(CancelMibChangeNotify2(hNot), Is.Zero);
}
finally
{
done.Set();
}
}).Start();
Assert.That(done.WaitOne(5000), Is.True);
void NotifyFunc(IntPtr CallerContext, ref MIB_IPFORWARD_ROW2 Row, MIB_NOTIFICATION_TYPE NotificationType)
{
Assert.That(CallerContext, Is.EqualTo(NotifyData));
TestContext.WriteLine(Row.ToString());
Assert.That(NotificationType, Is.EqualTo(MIB_NOTIFICATION_TYPE.MibInitialNotification));
fired.Set();
}
}
// TODO: [Test]
public void NotifyRouteChangeTest()
{
throw new NotImplementedException();
}
[Test]
public void NotifyStableUnicastIpAddressTableTest()
{
var fired = new ManualResetEvent(false);
var done = new ManualResetEvent(false);
new Thread(() =>
{
try
{
Assert.That(NotifyStableUnicastIpAddressTable(ADDRESS_FAMILY.AF_UNSPEC, out var table, NotifyFunc, NotifyData, out var hNot), Is.Zero.Or.EqualTo(Win32Error.ERROR_IO_PENDING));
if (table == IntPtr.Zero)
{
fired.WaitOne(3000);
Assert.That(CancelMibChangeNotify2(hNot), Is.Zero);
}
}
finally
{
done.Set();
}
}).Start();
Assert.That(done.WaitOne(5000), Is.True);
void NotifyFunc(IntPtr CallerContext, IntPtr Table)
{
Assert.That(CallerContext, Is.EqualTo(NotifyData));
TestContext.WriteLine(Table.ToString());
fired.Set();
}
}
[Test]
public void NotifyTeredoPortChangeTest()
{
var fired = new ManualResetEvent(false);
var done = new ManualResetEvent(false);
new Thread(() =>
{
try
{
Assert.That(NotifyTeredoPortChange(NotifyFunc, NotifyData, true, out var hNot), Is.Zero);
fired.WaitOne(3000);
Assert.That(CancelMibChangeNotify2(hNot), Is.Zero);
}
finally
{
done.Set();
}
}).Start();
Assert.That(done.WaitOne(5000), Is.True);
void NotifyFunc(IntPtr CallerContext, ushort Port, MIB_NOTIFICATION_TYPE NotificationType)
{
Assert.That(CallerContext, Is.EqualTo(NotifyData));
TestContext.WriteLine(Port.ToString());
Assert.That(NotificationType, Is.EqualTo(MIB_NOTIFICATION_TYPE.MibInitialNotification));
fired.Set();
}
}
[Test]
public void NotifyUnicastIpAddressChangeTest()
{
var fired = new ManualResetEvent(false);
var done = new ManualResetEvent(false);
new Thread(() =>
{
try
{
Assert.That(NotifyUnicastIpAddressChange(ADDRESS_FAMILY.AF_UNSPEC, NotifyFunc, NotifyData, true, out var hNot), Is.Zero);
fired.WaitOne(3000);
Assert.That(CancelMibChangeNotify2(hNot), Is.Zero);
}
finally
{
done.Set();
}
}).Start();
Assert.That(done.WaitOne(5000), Is.True);
void NotifyFunc(IntPtr CallerContext, IntPtr Row, MIB_NOTIFICATION_TYPE NotificationType)
{
Assert.That(CallerContext, Is.EqualTo(NotifyData));
TestContext.WriteLine(Row.ToString());
Assert.That(NotificationType, Is.EqualTo(MIB_NOTIFICATION_TYPE.MibInitialNotification));
fired.Set();
}
}
[Test]
public void ResolveIpNetEntry2Test()
{
var e = new MIB_IPNET_ROW2(new SOCKADDR_IN(new IN_ADDR(192, 168, 0, 202)), primaryAdapter.IfIndex);
Assert.That(ResolveIpNetEntry2(ref e), Is.Zero);
Assert.That(e.State, Is.EqualTo(NL_NEIGHBOR_STATE.NlnsReachable));
}
[Test]
public void SendARPTest()
{
Assert.That(() =>
{
var gw = primaryAdapter.GatewayAddresses.Select(a => a.Address.Convert().GetAddressBytes()).FirstOrDefault();
var mac = SendARP(new IN_ADDR(gw));
Assert.That(mac.Length, Is.EqualTo(6));
Assert.That(mac, Has.Some.Not.EqualTo(0));
}, Throws.Nothing);
}
[SetUp]
public void Setup()
{
primaryAdapter = GetAdaptersAddresses(GetAdaptersAddressesFlags.GAA_FLAG_INCLUDE_GATEWAYS).FirstOrDefault(r => r.OperStatus == IF_OPER_STATUS.IfOperStatusUp && r.TunnelType == TUNNEL_TYPE.TUNNEL_TYPE_NONE);
}
}
}
|
using EmberSqlite.Integration;
using Microsoft.EntityFrameworkCore;
using OsuSqliteDatabase.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace OsuSqliteDatabase.Database
{
public class OsuDatabaseContext : EmberDbContext
{
public DbSet<OsuDatabase> OsuDatabases { get; set; }
public DbSet<OsuDatabaseBeatmap> OsuDatabaseBeatmap { get; set; }
public DbSet<OsuDatabaseBeatmapStarRating> OsuDatabaseBeatmapStarRating { get; set; }
public DbSet<OsuDatabaseTimings> OsuDatabaseTimings { get; set; }
public OsuDatabaseContext(SqliteConfiguration config) : base(config) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OsuDatabase>().HasIndex(entity => entity.PlayerName);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.BeatmapId);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.BeatmapSetId);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.RankStatus);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.StandardRankRating);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.TaikoRankRating);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.CatchTheBeatRankRating);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.ManiaRankRating);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.NotPlayed);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.Artist);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.ArtistUnicode);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.Title);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.TitleUnicode);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.Creator);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => entity.Difficult);
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => new { entity.FolderName, entity.FileName });
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => new { entity.CircleCount, entity.SliderCount, entity.SpinnerCount });
modelBuilder.Entity<OsuDatabaseBeatmap>().HasIndex(entity => new { entity.ApproachRate, entity.CircleSize, entity.HPDrain, entity.OverallDifficulty });
modelBuilder.Entity<OsuDatabaseBeatmapStarRating>().HasIndex(entity => entity.Moderators);
modelBuilder.Entity<OsuDatabaseBeatmapStarRating>().HasIndex(entity => entity.StarRating);
modelBuilder.Entity<OsuDatabaseTimings>().HasIndex(entity => entity.BeatPreMinute);
base.OnModelCreating(modelBuilder);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Routing;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
private readonly ApplicationDbContext context;
public SampleController(ApplicationDbContext context)
{
this.context = context;
}
[HttpGet]
[Route("")]
public async Task<List<Sample>> GetPedidos()
{
var result = await context.Sample.ToListAsync();
return result;
}
[HttpGet]
[Route("{id}", Name = "GetSample")]
public async Task<Sample> GetSampleByID(int id)
{
Sample sample = new Sample();
if (await context.Sample.AnyAsync(s => s.ID == id.ToString()))
{
sample = await context.Sample.FirstOrDefaultAsync(s => s.ID == id.ToString());
}
return sample;
}
[HttpPut]
[Route("EditSample/{id}")]
public async Task<ActionResult> EditSample(string id, [FromBody] Sample sample)
{
try
{
if (await context.Sample.AnyAsync(s => s.ID == id))
{
context.Entry(sample).State = EntityState.Modified;
await context.SaveChangesAsync();
return CreatedAtRoute("GetSample", new { id = sample.ID }, sample);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost]
[Route("SaveSample")]
public async Task<ActionResult> SaveSample([FromBody] Sample sample)
{
try
{
await context.Sample.AddAsync(sample);
await context.SaveChangesAsync();
return CreatedAtRoute("GetSample", new { id = sample.ID }, sample);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete]
[Route("DeleteSample/{id}")]
public async Task<ActionResult> DeleteSample(int id)
{
try
{
var sample = await context.Sample.FirstOrDefaultAsync(s => s.ID == id.ToString());
if (sample != null)
{
context.Sample.Remove(sample);
await context.SaveChangesAsync();
return Ok();
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Practices.ServiceLocation;
using Profiling2.Domain.Contracts.Tasks.Screenings;
using Profiling2.Domain.Scr;
using Profiling2.Web.Mvc.Areas.Screening.Controllers.ViewModels;
namespace Profiling2.Web.Mvc.Validators
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class RequiresResponseAttribute : ValidationAttribute
{
public RequiresResponseAttribute()
{
this.ErrorMessage = "This request does not currently require a response.";
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (value.GetType() == typeof(RespondViewModel))
{
RespondViewModel vm = (RespondViewModel)value;
Request r = ServiceLocator.Current.GetInstance<IRequestTasks>().Get(vm.Id);
if (r != null)
if (!r.RequiresResponse)
return new ValidationResult(this.ErrorMessage);
}
}
return ValidationResult.Success;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public static class GUIHandler
{
private static List<bool> selectedObjectList = new List<bool>();
//public static int mySelectedObjectID;
public delegate void MyGUIDelegate<T>(List<T> items);
public static MyGUIDelegate<UnityEngine.Object> MyGUI;
private static float boxHeight = 300 + 20;
private static Vector2 scrollx;
public static void AddItemsToGUI(MyGUIDelegate<UnityEngine.Object> item)
{
MyGUI += item;
}
public static void ShowObjectList(List<UnityEngine.Object> items, float height)
{
GUILayout.BeginArea(new Rect(0, (boxHeight * height), 300, 300));
scrollx = EditorGUILayout.BeginScrollView(scrollx);
if (items != null)
{
for (int i = 0; i < items.Count; i++)
{
selectedObjectList.Add(false);
selectedObjectList[i] = GUILayout.Toggle(selectedObjectList[i], "" + items[i].name, "Button");
if (selectedObjectList[i] == true)
{
for (int k = 0; k < selectedObjectList.Count; k++)
{
if (k != i)
{
selectedObjectList[k] = false;
}
else
{
MapMaker.mySelectedObjectID = i;
MapMaker.objectSelected = true;
}
}
}
}
}
bool CheckSelectedObjectList(){
foreach(bool obj in selectedObjectList)
{
if(obj == true)
{
return true;
}
}
return false;
}
if (CheckSelectedObjectList() == false)
{
MapMaker.objectSelected = false;
}
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
public static void MainMenuItems(MapMaker myMapMaker,float height)
{
GUILayout.BeginArea(new Rect(0, (boxHeight * height), 300, 300));
if (GUILayout.Button("Load"))
{
myMapMaker.myStateMachine.Load();//LoadWindow
}
if (GUILayout.Button("Save"))
{
myMapMaker.myStateMachine.Save();//SaveWindow
}
if (GUILayout.Button("Place Mode"))
{
myMapMaker.myStateMachine.SwithState(1);//PlaceMode
}
if (GUILayout.Button("Builder Mode"))
{
myMapMaker.myObjectPool.myTileData = null;
myMapMaker.myStateMachine.SwithState(2);//BuilderMode
}
GUILayout.EndArea();
}
public static void BuilderModeItems(float height)
{
GUILayout.BeginArea(new Rect(0, (boxHeight * height), 300, 300));
if (GUILayout.Button("Floor Up"))
{
if(MapMaker.activefloor < StateBuilderEvents.size - 1)
{
MapMaker.activefloor = MapMaker.activefloor + StateBuilderEvents.floorsize;
for (int i = 0; i < StateBuilderEvents.floors.Length; i++)
{
if (i > MapMaker.activefloor)
{
StateBuilderEvents.floors[i].SetActive(false);
}
}
StateBuilderEvents.floors[MapMaker.activefloor].SetActive(true);
}
}
if (GUILayout.Button("Floor Down"))
{
if (MapMaker.activefloor > 0)
{
MapMaker.activefloor = MapMaker.activefloor - StateBuilderEvents.floorsize;
for (int i = 0; i < StateBuilderEvents.floors.Length; i++)
{
if (i > MapMaker.activefloor)
{
StateBuilderEvents.floors[i].SetActive(false);
}
}
StateBuilderEvents.floors[MapMaker.activefloor].SetActive(true);
}
}
if (GUILayout.Button("Toggle Building"))
{
for (int i = 0; i < StateBuilderEvents.floors.Length; i++)
{
StateBuilderEvents.floors[i].SetActive(!StateBuilderEvents.buildingToggle);
}
StateBuilderEvents.buildingToggle = !StateBuilderEvents.buildingToggle;
if (StateBuilderEvents.floors[MapMaker.activefloor].activeInHierarchy == false)
{
for (int i = 0; i < StateBuilderEvents.floors.Length; i++)
{
if (i <= MapMaker.activefloor)
{
StateBuilderEvents.floors[i].SetActive(true);
}
}
}
}
GUILayout.EndArea();
}
public static void PlaceModeItems(float height)
{
GUILayout.BeginArea(new Rect(0, (boxHeight * height), 300, 300));
if (GUILayout.Button("Clear Map"))
{
StatePlaceEvents.DestroyPlacedObjects(StatePlaceMode.myMapMaker.myObjectPool.placedObjects);
}
GUILayout.EndArea();
}
}
|
using System;
using System.Globalization;
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Common.CsvHelper.Helpers
{
public static class ValidationExtensions
{
public static bool IsDateTime(this string value)
{
return DateTime.TryParse(value, out _);
}
public static bool IsDateTimeWithFormat(this string value)
{
return DateTime.TryParseExact(value, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
}
public static DateTime ParseStringToDateTime(this string value)
{
DateTime.TryParseExact(value, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result);
return result;
}
public static DateTime ToDateTime(this string value)
{
return DateTime.Parse(value);
}
public static long ToLong(this string value)
{
return long.Parse(value);
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senai.Peoples.WebAp.Domains;
using Senai.Peoples.WebAp.Interfaces;
using Senai.Peoples.WebAp.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Senai.Peoples.WebAp.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class FuncionariosController : ControllerBase
{
private IFuncionarioRepository _funcionarioRepository { get; set; }
public FuncionariosController()
{
_funcionarioRepository = new FuncionarioRepository();
}
/// <summary>
/// Lista todos os funcionaris
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Get()
{
try
{
List<FuncionarioDomain> listaFuncionario = _funcionarioRepository.ListarTodos();
return Ok(listaFuncionario);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
/// <summary>
/// Procura um funcionario pelo seu id
/// </summary>
/// <param name="id">id do funcionario procurado</param>
/// <returns></returns>
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
FuncionarioDomain funcionaroBuscado = _funcionarioRepository.BuscarPorId(id);
try
{
if (funcionaroBuscado == null)
{
return NotFound("Nenhum Funcionario foi encontrado");
}
return Ok(funcionaroBuscado);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
/// <summary>
/// Cadastra novo funcionario
/// </summary>
/// <param name="novoFuncionaro">informacoes do novo funcionario</param>
/// <returns></returns>
[HttpPost]
public IActionResult Post(FuncionarioDomain novoFuncionaro)
{
try
{
_funcionarioRepository.Cadastrar(novoFuncionaro);
return StatusCode(201);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
/// <summary>
/// Deleta um funcionario
/// </summary>
/// <param name="id">id do funcionario para ser deletado</param>
/// <returns></returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
try
{
_funcionarioRepository.deletar(id);
return StatusCode(204);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
/// <summary>
/// Atualiza um funcionario
/// </summary>
/// <param name="id">id do funcionario para atualizar</param>
/// <param name="funcionarioAtualizado">novas informacoes do usuario</param>
/// <returns></returns>
[HttpPut("{id}")]
public IActionResult Put(int id, FuncionarioDomain funcionarioAtualizado)
{
FuncionarioDomain funcionarioBuscado = _funcionarioRepository.BuscarPorId(id);
try
{
_funcionarioRepository.AtualizarIdUrl(id, funcionarioAtualizado);
return NoContent();
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
}
}
|
//using WeifenLuo.WinFormsUI.Docking;
//namespace gView.Framework.system.UI
//{
// public partial class ToolWindow : DockContent
// {
// private IDockableWindow _window;
// public ToolWindow(IDockableWindow window)
// {
// InitializeComponent();
// _window = window;
// if (window is Form)
// {
// List<Control> controls = new List<Control>();
// foreach (Control control in ((Form)window).Controls)
// {
// controls.Add(control);
// }
// ((Form)window).Controls.Clear();
// foreach (Control control in controls)
// {
// this.Controls.Add(control);
// }
// }
// }
// }
//} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.ORD
{
[Serializable]
public partial class ActiveOrder : EntityBase
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Display(Name = "ActiveOrder_OrderNo", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string OrderNo { get; set; }
public Int32 OrderDetId { get; set; }
[Display(Name = "ActiveOrder_Flow", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string Flow { get; set; }
public CodeMaster.OrderType OrderType { get; set; }
[Display(Name = "ActiveOrder_LocationFrom", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string LocationFrom { get; set; }
[Display(Name = "ActiveOrder_LocationTo", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string LocationTo { get; set; }
[Display(Name = "ActiveOrder_Item", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string Item { get; set; }
[Display(Name = "ActiveOrder_StartTime", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public DateTime StartTime { get; set; }
[Display(Name = "ActiveOrder_WindowTime", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public DateTime WindowTime { get; set; }
[Display(Name = "ActiveOrder_OrderQty", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public Double OrderQty { get; set; }
[Display(Name = "ActiveOrder_ShippedQty", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public Double ShippedQty { get; set; }
[Display(Name = "ActiveOrder_ReceivedQty", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public Double ReceivedQty { get; set; }
//public Decimal TransitQty { get; set; }
[Display(Name = "ActiveOrder_SnapTime", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public DateTime SnapTime { get; set; }
[Display(Name = "ActiveOrder_PartyTo", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string PartyTo { get; set; }
[Display(Name = "ActiveOrder_PartyFrom", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public string PartyFrom { get; set; }
[Display(Name = "ActiveOrder_IsIndepentDemand", ResourceType = typeof(Resources.MRP.ActiveOrder))]
public Boolean IsIndepentDemand { get; set; }
public CodeMaster.ResourceGroup ResourceGroup { get; set; }
public string Shift { get; set; }
public string Bom { get; set; }
#endregion
}
}
|
using System.Data.Entity;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using ODL.ApplicationServices;
using ODL.ApplicationServices.DTOModel;
using ODL.DataAccess;
using ODL.DataAccess.Repositories;
using ODL.DomainModel.Adress;
[TestFixture]
public class AdressServiceTest
{
protected ODLDbContext context;
protected DbContextTransaction transaction;
[SetUp]
public void TransactionTestStart()
{
Database.SetInitializer<ODLDbContext>(null);
context = new ODLDbContext();
transaction = context.Database.BeginTransaction();
}
[Test]
[Category("LongRunning")]
public void SparaPersonAdress_WhenNew_ThenSaved()
{
var loggerMock = new Mock<ILogger<AdressService>>().Object;
var service = new AdressService(new AdressRepository(context), new PersonRepository(context), new OrganisationRepository(context), loggerMock);
var personGatauAdress = new AdressInputDTO
{
Personnummer = "197012123456",
Adressvariant = Adressvariant.Leveransadress.ToString(),
GatuadressInput = new GatuadressInputDTO
{
AdressRad1 = "Gatan 2",
AdressRad2 = "",
AdressRad3 = "",
AdressRad4 = "",
AdressRad5 = "",
Postnummer = "74141",
Stad = "Knivsta",
Land = "USA"
},
EpostInput = null,
TelefonInput = null,
SystemId = null,
UppdateradDatum = "2017-01-20 12:00",
UppdateradAv = "MAH",
SkapadDatum = "2017-01-20 12:00",
SkapadAv = "MAH"
};
service.SparaAdress(personGatauAdress);
var sparadPersonAdress = service.GetAdresserPerPersonnummer("197012123456");
Assert.That(sparadPersonAdress, Is.Not.Null);
}
[TearDown]
public void TransactionTestEnd()
{
transaction.Rollback();
transaction.Dispose();
context.Dispose();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Cue : IComparable<Cue> {
public int tick = 0;
public int tickLength = 120;
public int pitch = 0;
public int velocity = 20;
public Vector2 gridOffset;
public int handType = 0;
public int behavior = 0;
private int row = 0;
private int col = 0;
private void CalcPitch() {
pitch = row + (12 * col);
}
public int GetTick() {
return tick;
}
public int GetRow() {
return row;
}
public int GetCol() {
return col;
}
public int CompareTo(Cue other) {
return this.tick.CompareTo(other.tick);
}
public Cue SetTick(int tick) {
this.tick = tick;
return this;
}
public Cue SetPos(int row, int col) {
this.row = row;
this.col = col;
this.CalcPitch();
return this;
}
public Cue SetRow(int row) {
this.row = row;
this.CalcPitch();
return this;
}
public Cue SetCol(int col) {
this.col = col;
this.CalcPitch();
return this;
}
public Cue SetHandNone() {
this.handType = 0;
return this;
}
public Cue SetHandLeft() {
this.handType = 2;
return this;
}
public Cue SetHandRight() {
this.handType = 2;
return this;
}
// public string ToJson() {
// return "\t\t{\n" +
// "\t\t\t\"tick\": " + tick + ",\n" +
// "\t\t\t\"tickLength\": " + tickLength + ",\n" +
// "\t\t\t\"pitch\": " + pitch + ",\n" +
// "\t\t\t\"velocity\": " + velocity + ",\n" +
// "\t\t\t\"gridOffset\": {\n" +
// "\t\t\t\t\"x\": " + gridOffsetX + ",\n" +
// "\t\t\t\t\"y\": " + gridOffsetY + "\n" +
// "\t\t\t},\n" +
// "\t\t\t\"handType\": " + handType + ",\n" +
// "\t\t\t\"behavior\": " + behavior + "\n" +
// "\t\t}";
// }
}
|
namespace Students.Models
{
public class Grade
{
public int StudentNumber { get; set; }
public string Lesson { get; set; }
public decimal Score { get; set; }
}
} |
using DFC.ServiceTaxonomy.GraphSync.CosmosDb;
using DFC.ServiceTaxonomy.GraphSync.CosmosDb.Commands;
using DFC.ServiceTaxonomy.GraphSync.CosmosDb.Interfaces;
using DFC.ServiceTaxonomy.GraphSync.Interfaces;
using DFC.ServiceTaxonomy.GraphSync.Models;
using Microsoft.Extensions.DependencyInjection;
namespace DFC.ServiceTaxonomy.GraphSync.Extensions
{
public static class ServiceCollectionExtensions
{
public static void AddGraphCluster(this IServiceCollection services)
{
services.AddSingleton<ICosmosDbGraphClusterBuilder, CosmosDbGraphClusterBuilder>();
services.AddSingleton<IGraphCluster, CosmosDbGraphCluster>(
provider =>
{
var clusterBuilder = provider.GetRequiredService<ICosmosDbGraphClusterBuilder>().Build();
return (CosmosDbGraphCluster)clusterBuilder;
});
services.AddTransient<IMergeNodeCommand, CosmosDbMergeNodeCommand>();
services.AddTransient<IDeleteNodeCommand, CosmosDbDeleteNodeCommand>();
services.AddTransient<IDeleteNodesByTypeCommand, CosmosDbDeleteNodesByTypeCommand>();
services.AddTransient<IReplaceRelationshipsCommand, CosmosDbReplaceRelationshipsCommand>();
services.AddTransient<IDeleteRelationshipsCommand, CosmosDbDeleteRelationshipsCommand>();
services.AddTransient<ICustomCommand, CustomCommand>();
}
}
}
|
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 HeatNeuralNetwork
{
public partial class InputInformation : Form
{
MainWindow main;
public InputInformation(MainWindow mainWindow)
{
InitializeComponent();
main = mainWindow;
lBPlots.SelectedIndex = 0;
}
private void bSave_Click(object sender, EventArgs e)
{
main.plots[lBPlots.SelectedIndex].pipelineLength =
Convert.ToInt32(tBPipelineLength.Text);
main.plots[lBPlots.SelectedIndex].pipelineDiameter =
Convert.ToInt32(tBPipelineDiameter.Text);
main.plots[lBPlots.SelectedIndex].operatingPressure =
Convert.ToInt32(tBOperatingPressure.Text);
main.plots[lBPlots.SelectedIndex].workingTemperature =
Convert.ToInt32(tBWorkingTemperature.Text);
main.plots[lBPlots.SelectedIndex].lifeCycle =
Convert.ToInt32(tBLifeCycle.Text);
main.plots[lBPlots.SelectedIndex].numberDays =
Convert.ToInt32(tBNumberDays.Text);
main.plots[lBPlots.SelectedIndex].numberBreakdowns =
Convert.ToInt32(tBNumberBreakdowns.Text);
main.plots[lBPlots.SelectedIndex].placesBreakdowns =
Convert.ToInt32(tBPlacesBreakdowns.Text);
main.plots[lBPlots.SelectedIndex].price =
Convert.ToInt32(tBPrice.Text);
}
private void bInputTestInfo_Click(object sender, EventArgs e)
{
Plot buffPlot;
Random rand = new Random();
for (int i = 0; i < 9; i++)
{
buffPlot = new Plot();
buffPlot.namePlot = "Участок " + (i+1);
buffPlot.pipelineLength = rand.Next(1000)+100;
buffPlot.pipelineDiameter = rand.Next(100) + 1;
buffPlot.operatingPressure = rand.Next(100) + 1;
buffPlot.workingTemperature = rand.Next(100) + 1;
buffPlot.numberDays = rand.Next(80) + 1;
buffPlot.lifeCycle = rand.Next(buffPlot.numberDays, 200) + 20;
buffPlot.numberBreakdowns = rand.Next(10) + 1;
buffPlot.placesBreakdowns = rand.Next(buffPlot.pipelineLength-1) + 1;
buffPlot.price = rand.Next(500) + 1;
buffPlot.daysAnswer = 0;
buffPlot.pointAnswer = 0;
buffPlot.priceAnswer = 0;
main.plots[i] = buffPlot;
}
lPlot.Text = main.plots[lBPlots.SelectedIndex].namePlot;
tBPipelineLength.Text= Convert.ToString(
main.plots[lBPlots.SelectedIndex].pipelineLength);
tBPipelineDiameter.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].pipelineDiameter);
tBOperatingPressure.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].operatingPressure);
tBWorkingTemperature.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].workingTemperature);
tBLifeCycle.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].lifeCycle);
tBNumberDays.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].numberDays);
tBNumberBreakdowns.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].numberBreakdowns);
tBPlacesBreakdowns.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].placesBreakdowns);
tBPrice.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].price);
}
private void lBPlots_SelectedIndexChanged(object sender, EventArgs e)
{
lPlot.Text = main.plots[lBPlots.SelectedIndex].namePlot;
tBPipelineLength.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].pipelineLength);
tBPipelineDiameter.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].pipelineDiameter);
tBOperatingPressure.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].operatingPressure);
tBWorkingTemperature.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].workingTemperature);
tBLifeCycle.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].lifeCycle);
tBNumberDays.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].numberDays);
tBNumberBreakdowns.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].numberBreakdowns);
tBPlacesBreakdowns.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].placesBreakdowns);
tBPrice.Text = Convert.ToString(
main.plots[lBPlots.SelectedIndex].price);
}
}
}
|
using ResizetizerNT_svg_log_issue.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ResizetizerNT_svg_log_issue.Services
{
public class MockDataStore : IDataStore<Item>
{
readonly List<Item> items;
public MockDataStore()
{
var images = new string[]
{
"issue_39_0",
"issue_43_0",
"issue_43_1",
"issue_43_2",
"working_svg"
};
items = images.Select(x => new Item
{
Id = Guid.NewGuid().ToString(),
Text = $"file name: {x}",
Description = $"{x}.png"
}).ToList();
}
public async Task<bool> AddItemAsync(Item item)
{
items.Add(item);
return await Task.FromResult(true);
}
public async Task<bool> UpdateItemAsync(Item item)
{
var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
items.Remove(oldItem);
items.Add(item);
return await Task.FromResult(true);
}
public async Task<bool> DeleteItemAsync(string id)
{
var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
items.Remove(oldItem);
return await Task.FromResult(true);
}
public async Task<Item> GetItemAsync(string id)
{
return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
}
public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
{
return await Task.FromResult(items);
}
}
} |
using CarsIsland.WebApp.Common;
using CarsIsland.WebApp.Data;
using CarsIsland.WebApp.Extensions;
using CarsIsland.WebApp.Services.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace CarsIsland.WebApp.Services
{
public class CarsIslandApiService : ICarsIslandApiService
{
private readonly ITokenAcquisition _tokenAcquisition;
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;
public CarsIslandApiService(ITokenAcquisition tokenAcquisition,
HttpClient httpClient,
IConfiguration configuration)
{
_tokenAcquisition = tokenAcquisition;
_httpClient = httpClient;
_configuration = configuration;
}
public async Task<IReadOnlyCollection<Car>> GetAvailableCarsAsync()
{
var response = await _httpClient.GetAsync("api/car/all");
return await response.ReadContentAs<List<Car>>();
}
public async Task SendEnquiryAsync(string attachmentFileName, CustomerEnquiry enquiry)
{
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent(enquiry.Title), "title");
multipartContent.Add(new StringContent(enquiry.Content), "content");
multipartContent.Add(new StringContent(enquiry.CustomerContactEmail), "customerContactEmail");
if (enquiry.Attachment != null)
{
multipartContent.Add(new StreamContent(enquiry.Attachment), "Attachment", attachmentFileName);
}
await _httpClient.PostAsync("api/enquiry", multipartContent);
}
public async Task<OperationResponse> CreateNewCarReservationAsync(CarReservation carReservation)
{
await GetAndAddApiAccessTokenToAuthorizationHeaderAsync();
var response = await _httpClient.PostAsJson("api/carreservation", carReservation);
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.InternalServerError)
{
throw new ApplicationException($"Something went wrong calling the API: {response.ReasonPhrase}");
}
if (response.StatusCode == HttpStatusCode.BadRequest)
{
var operationError = await response.ReadContentAs<OperationError>();
return new OperationResponse().SetAsFailureResponse(operationError);
}
}
return new OperationResponse();
}
private async Task GetAndAddApiAccessTokenToAuthorizationHeaderAsync()
{
string[] scopes = new[] { _configuration["CarsIslandApi:Scope"] };
string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
}
}
|
using BattleEngine.Utils;
namespace BattleEngine.Records
{
public class BattleOwnerRecord
{
public int id;
public string name;
public int race;
public Vector<BattleUnitRecord> units;
public Vector<BattleSkillRecord> skills;
public Vector<BattleModifierRecord> modifiers;
}
}
|
using JhinBot.DiscordObjects;
using System.Collections.Generic;
namespace JhinBot.Database
{
public interface ISelfAssignedRoleRepository : IRepository<SelfAssignedRole>
{
bool DeleteByGuildAndRoleId(ulong guildId, ulong roleId);
IEnumerable<SelfAssignedRole> GetFromGuild(ulong guildId);
}
}
|
using UnityEngine;
using System.Collections;
public class Loading : MonoBehaviour
{
[SerializeField]
private Canvas canvas;
[SerializeField]
private ProgessBar progress;
public void Show(AsyncOperation operation = null)
{
canvas.gameObject.SetActive(true);
progress.Operation = operation;
}
public void Hide()
{
canvas.gameObject.SetActive(false);
progress.Operation = null;
}
public ProgessBar Progress
{
get { return progress; }
}
#region MonoBehaviour
void Awake()
{
GameSystem.RegisterModule(this);
Hide();
}
#endregion
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using ticketarena.lib.model;
namespace ticketarena.lib.services
{
public class VendService : IVendService
{
private List<Coin> _coins;
private ICoinService _coinService;
public VendService()
{
_coins = new List<Coin>();
_coinService = new CoinService();
}
public IEnumerable<Coin> Coins {
get {
return _coins;
}
}
public IEnumerable<CoinTypes> ListCoinsAccepted()
{
return new CoinTypes[] { CoinTypes.FiveCents, CoinTypes.TenCents, CoinTypes.FiftyCents, CoinTypes.OneDollar };
}
public ReturnResult Return()
{
var result = new ReturnResult { ResultType = ReturnResultTypes.Unknown, Coins = new Coin[]{}};
if (_coins.Count == 0)
{
result.ResultType = ReturnResultTypes.No_Coins;
}
else
{
result.ResultType = ReturnResultTypes.Returned;
result.Coins = _coins.ToArray();
_coins.Clear();
}
return result;
}
public decimal GetCurrentValue()
{
var all = (from c in _coinService.ListCoins()
join ct in _coins on new { c .Weight, c.Diameter } equals new { ct.Weight, ct.Diameter }
select c.Value).Sum();
return all;
}
public IEnumerable<Product> ListProducts()
{
return new Product[] {
new Product { Id = 1, Name = "cola", Price = 1.00m, Code="A1" },
new Product { Id = 2, Name = "chips", Price = 0.5m, Code="A2" },
new Product { Id = 3, Name = "candy", Price = 0.65m, Code="A3" }
};
}
public void AddCoin(Coin coin)
{
if (coin.CoinType != CoinTypes.FiveDollars) {
_coins.Add(coin);
}
else {
throw new ArgumentException("This coin type is not accepted.");
}
}
public VendResult Purchase(int productId)
{
var result = new VendResult { ResultType = VendResultTypes.Unknown, Change = 0};
if (_coins.Count == 0) {
result.ResultType = VendResultTypes.No_Coins;
}
else {
var product = ListProducts().SingleOrDefault(o => o.Id == productId);
var coinValue = GetCurrentValue();
result.ResultType = VendResultTypes.Unknown;
result.Change = 0;
if (product != null) {
if (product.Price <= coinValue) {
result.ResultType = VendResultTypes.Dispensed;
result.Change = coinValue - product.Price;
_coins.Clear();
}
else {
result.ResultType = VendResultTypes.Insufficient_Funds;
}
}
}
return result;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
[CreateAssetMenu(fileName = "Music_Configuration", menuName = "Music_Configuration")]
public class Music_Template : ScriptableObject
{
public Canciones[] listaCanciones;
}
[System.Serializable]
public class Canciones
{
public string sceneName = "Nombre de la escena";
public AudioClip cancion;
public float volume;
}
|
using Mercadinho.Model;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mercadinho.DAO
{
class CarrinhoProdutoDAO
{
private Model.CarrinhoProdutos carrinhoprodutos;
private MySqlConnection con;
private Conexao.Conexao conexao;
private List<Model.Produto> listadeprodutos;
private List<Model.Fatura> faturas;
public CarrinhoProdutoDAO()
{
listadeprodutos = new List<Produto>();
Faturas = new List<Fatura>();
}
internal List<Produto> Listadeprodutos { get => listadeprodutos; set => listadeprodutos = value; }
internal List<Fatura> Faturas { get => faturas; set => faturas = value; }
//METODO PARA INSERIR DADOS DO OBJETOCARRINHOPRODUTO PARA O MYSQL
public void InserirDadosCarrinho(CarrinhoProdutos carrinho)
{
con = new MySqlConnection();
carrinhoprodutos = new Model.CarrinhoProdutos();
conexao = new Conexao.Conexao();
con.ConnectionString = conexao.getConnectionString();
String query = "INSERT INTO carrinho(TotalCarrinho, CPF)";
query += " VALUES (?TotalCarrinho, ?CPF);SELECT LAST_INSERT_ID() as id;";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("?TotalCarrinho", carrinho.calcularcarrinho());
cmd.Parameters.AddWithValue("?CPF", carrinho.Cliente.CPF);
MySqlDataReader reader = cmd.ExecuteReader();
var idcarrinho = 0;
while (reader.Read())
{
idcarrinho = reader.GetInt32("id");//PEGAR O ULTIMO ID INSERIDO NO BANCO DO CARRINHO
}
cmd.Dispose();
reader.Close();
//INSERINDO DADOS NA TABELA CARRINHO PRODUTOS - ARMAZENEI O ULTIMO ID DO CARRINHO INSERIDO NA VARIAVEL idcarrinho
foreach (Produto prod in carrinho.Produtos1)
{
String query2 = "INSERT INTO carrinho_produtos(Id_Carrinho, Codigo_Barras)" +
" VALUES (?idCarrinho, ?Codigo_Barras);";
String query4 = "UPDATE produto SET Quantidade_estoque = Quantidade_estoque-1 WHERE Codigo_Barras = ?Codigo_Barras";
MySqlCommand cmd2 = new MySqlCommand(query2, con);
MySqlCommand cmd4 = new MySqlCommand(query4, con);
cmd4.Parameters.AddWithValue("?Codigo_Barras", prod.Codigobarras);
cmd2.Parameters.AddWithValue("?idCarrinho", idcarrinho);
cmd2.Parameters.AddWithValue("?Codigo_Barras", prod.Codigobarras);
cmd4.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd4.Dispose();
cmd2.Dispose();
}
// inserindo dados na fatura gerada usando tbm como base o ultimo id do carrinho inserido armazenado na variavel idcarrinho
foreach (Fatura fat in carrinho.Parcelas)
{
String query3 = "INSERT INTO fatura(Valor_Total, Data_Vencimento, FormaPagamento, EstaPago, Id_Carrinho, Data_Pagamento)" +
" VALUES (?Valor_Total, ?Data_Vencimento, ?FormaPagamento, ?EstaPago, ?Id_Carrinho, ?Data_Pagamento);";
MySqlCommand cmd3 = new MySqlCommand(query3, con);
cmd3.Parameters.AddWithValue("?Valor_Total", fat.Valorfatura);
cmd3.Parameters.AddWithValue("?Data_Vencimento", fat.DataVencimento1.Date);
cmd3.Parameters.AddWithValue("?FormaPagamento", fat.Formadepagamento);
cmd3.Parameters.AddWithValue("?EstaPago", fat.Estapago);
cmd3.Parameters.AddWithValue("?Id_Carrinho", idcarrinho);
cmd3.Parameters.AddWithValue("?Data_Pagamento", fat.DataPagamento1.Date);
cmd3.ExecuteNonQuery();
cmd3.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex);
}
finally
{
con.Close();
}
}
}
}
|
using System;
namespace Faker.ValueGenerator.PrimitiveTypes.LogicalType
{
public class BooleanGenerator : IPrimitiveTypeGenerator
{
private static readonly Random random = new Random();
public Type GenerateType { get; set; }
public object Generate()
{
var num = random.Next();
return num != 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Meerkats_Win.File_json_info;
namespace Meerkats_Win.Class
{
class Func
{
// stringhex(md5) => byte[]
public byte[] HexStrTobyte(string hexString)
{
try
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
return returnBytes;
////byte[] => stringhex(md5)
//byte[] buffer = {};
//StringBuilder strBuider = new StringBuilder();
//for (int index = 0; index < count; index++)
//{
// strBuider.Append(((int)buffer[index]).ToString("X2"));
//}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, FileMode.Open);
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
public string GetMD5Hash(byte[] bytedata)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(bytedata);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5Hash() fail,error:" + ex.Message);
}
}
public List<string> Get_file_block_md5(string Path,out string File_hash_str)
{
File_hash_str = null;
List<string> md5_list =new List<string>();
FileStream file = new FileStream(Path, FileMode.Open);
file.Seek(0, SeekOrigin.Begin);
long file_length = file.Length;
long block_size = 1024;
long round = file_length / block_size;
for (int index = 0; index < round; index++)
{
byte[] file_data = new byte[block_size];
file.Read(file_data, 0, file_data.Length);
string md5 = GetMD5Hash(file_data);
File_hash_str += md5;
md5_list.Add(md5);
}
file.Flush();
file.Close();
return md5_list;
}
public void Search_block_index(string Path,List<string> md5_list, out differ_info_json_list diff_json, out byte[] filedata,string filename)
{
diff_json = new differ_info_json_list();
filedata = null;
FileStream file = new FileStream(Path, FileMode.Open);
//differ_info_json_list diff_json = new differ_info_json_list();
diff_json.List = new List<Differ_info_json>();
diff_json.Name = filename;
diff_json.Num = 1;
diff_json.Idx = 0;
// long block_size = 1024;
int current_index = 0;
int tmp_start = 0;
bool flag = true;
bool flag_ex = false;
int matched = 0;
byte[] data = new byte[file.Length];
file.Read(data, 0, data.Length);
while(current_index + 1023 <= data.Length - 1)
{
byte[] temp = new byte[1024];
Buffer.BlockCopy(data, current_index, temp, 0, 1024);
string md5 = GetMD5Hash(temp);
for (int n = 0; n < md5_list.Count; n++)
{
if (md5_list[n] == md5)
{
flag_ex = true;
matched = n;
break;
}
}
if (flag_ex)
{
if (!flag)
{
flag = true;
//
diff_json.List.Add(new Differ_info_json()
{
Idx = tmp_start,
Typ = 1,
Len = current_index - tmp_start
});
byte[] tmp = new byte[current_index - tmp_start];
Buffer.BlockCopy(data, tmp_start, tmp, 0, tmp.Length);
if (filedata != null)
filedata = filedata.Concat(tmp).Where(a => '1' == '1').ToArray();
else
filedata = tmp;
}
diff_json.List.Add(new Differ_info_json()
{
Idx = matched,
Typ = 2,
Len = 1024
});
current_index += 1024;
tmp_start = current_index;
}
else
{
if (flag)
{
tmp_start = current_index;
flag = false;
}
current_index++;
}
}
if(current_index + 1023 > data.Length -1)
{
diff_json.List.Add(new Differ_info_json()
{
Idx = tmp_start,
Typ = 1,
Len = data.Length-tmp_start
});
byte[] tmp = new byte[data.Length - tmp_start];
Buffer.BlockCopy(data, tmp_start, tmp, 0, tmp.Length);
if (filedata != null)
filedata = filedata.Concat(tmp).Where(a => '1' == '1').ToArray();
else
filedata = tmp;
}
}
public void Differ_modifer_file(string Path, differ_info_json_list diff_json, byte[] filedata)
{
string Path_new = Path + "_new";
long block_size = 1024;
FileStream file_old = new FileStream(Path, FileMode.Open);
FileStream file_new = new FileStream(Path_new, FileMode.Create, FileAccess.Write);
long last_index = 0;
for (int i = 0; i < diff_json.List.Count; i++)
{
long len = 0;
switch (diff_json.List[i].Typ)
{
case 1:
len = diff_json.List[i].Len;
byte[] temp_data_1 = new byte[len];
Buffer.BlockCopy(filedata, (int)last_index, temp_data_1, 0, (int)len);
file_new.Write(temp_data_1, 0, temp_data_1.Length);
last_index += len;
break;
case 2:
len = diff_json.List[i].Len;
long Idx = diff_json.List[i].Idx;
byte[] temp_data_2 = new byte[len];
// move pointer to Idx * block_size
file_old.Seek(Idx * block_size, SeekOrigin.Begin);
file_old.Read(temp_data_2, 0, (int)block_size);
file_new.Write(temp_data_2, 0, temp_data_2.Length);
break;
}
}
file_old.Flush();
file_new.Flush();
file_old.Close();
file_new.Close();
File.Delete(Path);
File.Move(Path_new,Path);
}
}
}
|
using Newtonsoft.Json;
using System;
namespace Model.IntelligenceDiningTable
{
/// <summary>
/// 用户详细信息表
/// </summary>
[Serializable]
public partial class E_Personnel
{
[JsonProperty("id")]
public int userid { get; set; }
/// <summary>
/// 员工工号
/// </summary>
public string no { get; set;}
/// <summary>
/// 姓名
/// </summary>
public string name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string sex { get; set; }
/// <summary>
/// 体重
/// </summary>
public string weight { get; set; }
/// <summary>
/// 身高
/// </summary>
public string height { get; set; }
/// <summary>
/// 体质指数
/// </summary>
public double BMI { get; set; }
/// <summary>
/// 卡片物理卡号
/// </summary>
[JsonIgnore]
public string uid { get; set; }
/// <summary>
/// 状态 1停用 0正常
/// </summary>
[JsonIgnore]
public int status { get; set; }
/// <summary>
/// 员工工号
/// </summary>
[JsonIgnore]
public string employeeno { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using LTDemoData;
using LTDemoData.Models;
using LTDemoService.Services;
using Moq;
using Xunit;
namespace LTDemoServiceTests
{
public class PhotoServiceTests
{
[Fact]
public void GetPhotoOptions_ShouldEqualTestPhotos()
{
var mockWebServiceData = new Mock<IWebServiceData>();
mockWebServiceData.Setup(x => x.GetPhotos(It.IsAny<int>())).ReturnsAsync(TestPhotos());
var photoService = new PhotoService(mockWebServiceData.Object);
var photos = photoService.GetPhotoOptions(4).Result;
Assert.Collection(photos, photo1 =>
{
var testPhoto1 = TestPhotos().ElementAt(0);
Assert.Equal(testPhoto1.Id, photo1.Id);
Assert.Equal(testPhoto1.Title, photo1.Title);
},
photo2 =>
{
var testPhoto2 = TestPhotos().ElementAt(1);
Assert.Equal(testPhoto2.Id, photo2.Id);
Assert.Equal(testPhoto2.Title, photo2.Title);
});
}
private IEnumerable<Photo> TestPhotos() =>
new List<Photo>
{
new Photo{
Id=1,
Title="Testing photo id 1"
},
new Photo{
Id=2,
Title="Testing photo id 2"
}
};
}
} |
using Ninject.Modules;
using Slayer.Models;
using Slayer.Services;
using Slayer.ViewModels;
namespace Slayer.IoC
{
public class RunTimeModule : NinjectModule
{
public override void Load()
{
Bind<IViewModel>().To<ViewModel>().InSingletonScope();
Bind<IStorageService>().To<IsolatedStorageService>();
Bind<IGameSystem>().To<GameSystem>();
Bind<IFightViewModel>().To<FightViewModel>();
Bind<IStatsViewModel>().To<StatsViewModel>();
Bind<ILoadViewModel>().To<LoadViewModel>();
}
}
} |
using PersonasPhone.DAL;
using PersonasPhone.Entidades;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace PersonasPhone.BLL
{
public class PersonaBLL
{
public static bool Guardar(Persona persona)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
if (contexto.Per.Add(persona) != null)
{
contexto.SaveChanges();
paso = true;
}
}
catch (Exception)
{
throw;
}
return paso;
}
public static bool Eliminar(int id)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
var eliminar = contexto.Per.Find(id);
if (contexto.Per.Remove(eliminar) != null)
{
contexto.SaveChanges();
paso = true;
}
}
catch (Exception)
{
throw;
}
return paso;
}
public static bool Modificar(Persona persona)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
var anterior = contexto.Per.Find(persona.IdPersona);
foreach (var item in anterior.Telefonos)
{
if (!persona.Telefonos.Exists(d => d.Id == item.Id))
contexto.Entry(item).State = EntityState.Deleted;
}
contexto.Entry(persona).State = EntityState.Modified;
paso = (contexto.SaveChanges() > 0);
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static Persona Buscar(int id)
{
Contexto contexto = new Contexto();
Persona persona = new Persona();
try
{
persona = contexto.Per.Find(id);
}
catch (Exception)
{
throw;
}
return persona;
}
public static List<Persona> GetList(Expression<Func<Persona, bool>> per)
{
List<Persona> persona = new List<Persona>();
Contexto contexto = new Contexto();
try
{
persona = contexto.Per.Where(per).ToList();
}
catch (Exception)
{
throw;
}
return persona;
}
}
}
|
/*******************************************
*
* This class should only control Modules that involves Player Ground Controls
* NO CALCULATIONS SHOULD BE DONE HERE
*
*******************************************/
using UnityEngine;
using DChild.Gameplay.Objects;
using BP12.Events;
using System;
namespace DChild.Gameplay.Player.Controllers
{
[System.Serializable]
public class GroundDashController : PlayerControllerManager.Controller
{
[SerializeField]
private ParticleFX m_dashFX;
private IGroundDash m_dash;
private PlayerDashHandler m_dashHandle;
public bool isDashing => m_dashHandle.m_isDashing;
public override void Initialize()
{
m_dash = m_player.GetComponentInChildren<IGroundDash>();
m_dashHandle = new PlayerDashHandler(m_dash, m_player.animation.DoDash, m_player);
m_dash.DashStop += OnDashStop;
}
public void ForceStop()
{
m_dashHandle.ForceStop();
m_dashFX.Stop();
}
public void HandleDash()
{
if (m_input.skillInput.isDashPressed)
{
m_dashHandle.StartDash();
m_dashFX.Play();
}
}
public void HandleInterruptions()
{
if (m_player.facing == Direction.Right)
{
if (m_input.direction.isLeftPressed)
{
ForceStop();
}
}
else
{
if (m_input.direction.isRightPressed)
{
ForceStop();
}
}
}
private EventActionArgs OnDashStop(object sender, EventActionArgs eventArgs)
{
m_dashFX.Stop();
return eventArgs;
}
}
}
|
using EduHome.Models.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.ViewModels
{
public class PostDetailVM
{
public Post Post { get; set; }
public List<Category> Categories { get; set; }
public List<Post> LatestPosts { get; set; }
public List<PostMessage> PostMessages { get; set; }
public PostMessage PostMessage { get; set; }
}
}
|
using System.Data;
namespace Crystal.Plot2D.DataSources
{
/// <summary>
/// Data source that extracts sequence of points and their attributes from DataTable.
/// </summary>
public class TableDataSource : EnumerableDataSource<DataRow>
{
public TableDataSource(DataTable table) : base(table.Rows)
{
// Subscribe to DataTable events
table.TableNewRow += NewRowInsertedHandler;
table.RowChanged += RowChangedHandler;
table.RowDeleted += RowChangedHandler;
}
private void RowChangedHandler(object sender, DataRowChangeEventArgs e)
{
RaiseDataChanged();
}
private void NewRowInsertedHandler(object sender, DataTableNewRowEventArgs e)
{
// Raise DataChanged event. Plotter should redraw graph.
// This will be done automatically when rows are added to table.
RaiseDataChanged();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using ConsoleApp2.Model.Object;
using ConsoleApp1.Domain;
namespace ConsoleApp2.Model.Client
{
public class ClientImpl1 : IClient
{
public int ClientCommande { get; set; }
public Dish Repas { get; set; }
public bool Mange { get; set; }
public ClientImpl1()
{
Mange = false;
}
public void prendreRepas()
{
Mange = true;
}
public void choisirRepas(Menu menu)
{
Random random = new Random();
int rdmplat = random.Next(1, 3);
switch (rdmplat)
{
case 1:
ClientCommande = menu.Menu1[0].Id;
Repas = menu.Menu1[0];
break;
case 2:
ClientCommande = menu.Menu1[1].Id;
Repas = menu.Menu1[1];
break;
}
}
public void mangerPlat()
{
Mange = true;
Console.WriteLine("Le Client mange son repas");
Thread.Sleep(5000);
Mange = false;
Console.WriteLine("Le Client mange à fini son repas");
}
//public void commanderVin(Serveur serveur)
//{
// // chosir le vin sur la carte
// //serveur.servirVin();
//}
//public void commanderEau(Serveur serveur)
//{
// //serveur.servirEau();
//}
//public void commanderPain(Serveur serveur)
//{
// //serveur.servirPain();
//}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.SYS;
//TODO: Add other using statements here
namespace com.Sconit.Entity.FMS
{
public partial class FacilityOrderMaster
{
#region Non O/R Mapping Properties
public IList<FacilityOrderDetail> FacilityOrderDetails { get; set; }
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.FacilityOrderStatus, ValueField = "Status")]
[Display(Name = "FacilityOrderMaster_Status", ResourceType = typeof(Resources.FMS.FacilityOrderMaster))]
public string FacilityOrderStatusDescription { get; set; }
public void AddFacilityOrderDetail(FacilityOrderDetail facilityOrderDetail)
{
if (FacilityOrderDetails == null)
{
FacilityOrderDetails = new List<FacilityOrderDetail>();
}
FacilityOrderDetails.Add(facilityOrderDetail);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Discord.Commands;
using Discord.WebSocket;
namespace FifthBot.Resources.Preconditions
{
public class RequireChannelAttribute : PreconditionAttribute
{
private readonly string _channelName;
public RequireChannelAttribute(string name) => _channelName = name;
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
if(context.Channel.Name.Contains(_channelName))
{
return Task.FromResult(PreconditionResult.FromSuccess());
}
return Task.FromResult(PreconditionResult.FromError("You cannot run this command in this channel, sowwy!"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreatingAfarm
{
class horse
{
static string speak = "heewbrraa";
public void SpeakNow()
{
Console.WriteLine("This is the horse Salty ");
Console.WriteLine(" the horse goes " + speak);
}
public void Eatfood()
{
Console.WriteLine("The horse eats hay and grasss");
}
public void Weight()
{
Console.WriteLine("The horse ways 700lb");
}
public void Speed()
{
Console.WriteLine("The horse runs 30 miles per hour");
}
}
}
|
using Microsoft.EntityFrameworkCore;
using TCBlazor.DAL;
using TCBlazor.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace TCBlazor.BLL
{
public class NacionalidadesBLL
{
public static bool Guardar(Nacionalidades nacionalidad)
{
if (!Existe(nacionalidad.NacionalidadId))
{
return Insertar(nacionalidad);
}
else
{
return Modificar(nacionalidad);
}
}
private static bool Insertar(Nacionalidades nacionalidad)
{
Contexto contexto = new Contexto();
bool paso = false;
try
{
contexto.Nacionalidades.Add(nacionalidad);
paso = (contexto.SaveChanges() > 0);
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
private static bool Modificar(Nacionalidades nacionalidad)
{
Contexto contexto = new Contexto();
bool paso = false;
try
{
contexto.Entry(nacionalidad).State = EntityState.Modified;
paso = (contexto.SaveChanges() > 0);
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
private static bool Existe(int id)
{
Contexto contexto = new Contexto();
bool encontrado = false;
try
{
encontrado = contexto.Nacionalidades.Any(d => d.NacionalidadId == id);
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return encontrado;
}
public static bool Eliminar(int id)
{
Contexto contexto = new Contexto();
bool paso = false;
try
{
var eliminar = contexto.Nacionalidades.Find(id);
contexto.Entry(eliminar).State = EntityState.Deleted;
paso = (contexto.SaveChanges() > 0);
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static Nacionalidades Buscar(int id)
{
Contexto contexto = new Contexto();
Nacionalidades nacionalidad = new Nacionalidades();
try
{
nacionalidad = contexto.Nacionalidades.Find(id);
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return nacionalidad;
}
public static List<Nacionalidades> GetList(Expression<Func<Nacionalidades, bool>> nacionalidad)
{
Contexto contexto = new Contexto();
List<Nacionalidades> listado = new List<Nacionalidades>();
try
{
listado = contexto.Nacionalidades.Where(nacionalidad).ToList();
}
catch
{
throw;
}
finally
{
contexto.Dispose();
}
return listado;
}
}
} |
using System;
namespace FactoryMethod.Employes
{
public static class EmployeeFactory
{
public static Employee CreateEmployee(Employess employeeType)
{
Employee employee = null;
switch (employeeType)
{
case Employess.Nurse:
employee = new Nurse();
break;
case Employess.Policeman:
employee = new Policeman();
break;
case Employess.Fireman:
break;
default:
throw new IndexOutOfRangeException();
}
return employee;
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using ODL.DomainModel.Organisation;
namespace ODL.DataAccess.Mappningar
{
public class ResultatenhetMappning : EntityTypeConfiguration<Resultatenhet>
{
public ResultatenhetMappning()
{
ToTable("Organisation.Resultatenhet");
HasKey(m => m.OrganisationId)
.Property(m => m.OrganisationId).HasColumnName("OrganisationFKId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(m => m.KstNr).HasMaxLength(6).IsUnicode(false);
Ignore(m => m.Typ);
Property(m => m.KostnadsstalletypString).HasColumnName("Typ").HasMaxLength(1).IsUnicode(false).IsRequired();
}
}
} |
using Autofac;
namespace Ricky.Infrastructure.Core.ObjectContainer.Autofac.DependencyManagement
{
public interface IAutofacDependencyRegistrar
{
void Register(ContainerBuilder builder, ITypeFinder typeFinder);
int Order { get; }
}
}
|
using UnityEngine;
public class LockMouse : MonoBehaviour
{
void Awake ()
{
LockCursor();
}
void Update ()
{
LockCursor();
}
public void LockCursor ()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace Cognology.FlightBookingApp.Models
{
public class BookingWithFlightInformationDto
{
public int BookingId { get; set; }
[Required]
public string PassengerName { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public int NumberOfPassengers { get; set; }
public int FlightId { get; set; }
public FlightDto FlightInformation { get; set; }
}
} |
namespace MusicStore.Services
{
public class JwtConfiguration
{
public string JwtSecretKey { get; set; }
}
} |
namespace KartSystem.Presenters
{
public enum SearchCriterion
{
None,
Id,
Name,
Articul,
Code,
IdGood,
Barcode,
IdGoodGroup
}
} |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.Threading.Tasks;
using Inventory.Common;
using Inventory.Data.Services;
using Inventory.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
namespace Inventory.ViewModels
{
public class CreateDatabaseViewModel : ViewModelBase
{
public CreateDatabaseViewModel(ISettingsService settingsService, ICommonServices commonServices) : base(commonServices)
{
SettingsService = settingsService;
Result = Result.Error("Operation cancelled");
}
public ISettingsService SettingsService { get; }
public Result Result { get; private set; }
private string _progressStatus = null;
public string ProgressStatus
{
get => _progressStatus;
set => Set(ref _progressStatus, value);
}
private double _progressMaximum = 1;
public double ProgressMaximum
{
get => _progressMaximum;
set => Set(ref _progressMaximum, value);
}
private double _progressValue = 0;
public double ProgressValue
{
get => _progressValue;
set => Set(ref _progressValue, value);
}
private string _message = null;
public string Message
{
get { return _message; }
set { if (Set(ref _message, value)) NotifyPropertyChanged(nameof(HasMessage)); }
}
public bool HasMessage => _message != null;
private string _primaryButtonText;
public string PrimaryButtonText
{
get => _primaryButtonText;
set => Set(ref _primaryButtonText, value);
}
private string _secondaryButtonText = "Cancel";
public string SecondaryButtonText
{
get => _secondaryButtonText;
set => Set(ref _secondaryButtonText, value);
}
public async Task ExecuteAsync(string connectionString)
{
try
{
ProgressMaximum = 23;
ProgressStatus = "Connecting to Database";
using (var db = new SQLServerDb(connectionString))
{
var dbCreator = db.GetService<IDatabaseCreator>() as RelationalDatabaseCreator;
if (!await dbCreator.ExistsAsync())
{
ProgressValue = 1;
ProgressStatus = "Creating Database...";
await db.Database.EnsureCreatedAsync();
ProgressValue = 2;
await CopyDataTables(db);
ProgressValue = 23;
Message = "Database created successfully.";
Result = Result.Ok("Database created successfully.");
}
else
{
ProgressValue = 23;
Message = $"Database already exists. Please, delete database and try again.";
Result = Result.Error("Database already exist");
}
}
}
catch (Exception ex)
{
Result = Result.Error("Error creating database. See details in Activity Log");
Message = $"Error creating database: {ex.Message}";
LogException("Settings", "Create Database", ex);
}
PrimaryButtonText = "Ok";
SecondaryButtonText = null;
}
private async Task CopyDataTables(SQLServerDb db)
{
using (var sourceDb = new SQLiteDb(SettingsService.PatternConnectionString))
{
#region Common
ProgressStatus = "Создание таблицы Restaurants...";
foreach (var item in sourceDb.Restaurants.AsNoTracking())
{
await db.Restaurants.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 3;
ProgressStatus = "Создание таблицы TaxTypes...";
foreach (var item in sourceDb.TaxTypes.AsNoTracking())
{
await db.TaxTypes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 4;
ProgressStatus = "Создание таблицы Categories...";
foreach (var item in sourceDb.Cities.AsNoTracking())
{
await db.Cities.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 5;
ProgressStatus = "Создание таблицы TypeStreet...";
foreach (var item in sourceDb.StreetTypes.AsNoTracking())
{
await db.StreetTypes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 6;
ProgressStatus = "Создание таблицы Street...";
foreach (var item in sourceDb.Streets.AsNoTracking())
{
await db.Streets.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 7;
/*ProgressStatus = "Создание таблицы Address...";
foreach (var item in sourceDb.Address.AsNoTracking())
{
await db.Address.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 8;*/
ProgressStatus = "Создание таблицы Categories...";
foreach (var item in sourceDb.MenuFolders.AsNoTracking())
{
await db.MenuFolders.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 9;
ProgressStatus = "Создание таблицы PaymentTypes...";
foreach (var item in sourceDb.PaymentTypes.AsNoTracking())
{
await db.PaymentTypes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 10;
#endregion
#region Products
ProgressStatus = "Создание таблицы Products...";
foreach (var item in sourceDb.Dishes.AsNoTracking())
{
await db.Dishes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 11;
#endregion
#region Customer
ProgressStatus = "Создание таблицы Customers...";
foreach (var item in sourceDb.Customers.AsNoTracking())
{
await db.Customers.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 12;
#endregion
#region Communications
ProgressStatus = "Создание таблицы CommunicationTypes...";
foreach (var item in sourceDb.CommunicationTypes.AsNoTracking())
{
item.Id = 0;
await db.CommunicationTypes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 13;
ProgressStatus = "Создание таблицы Communications...";
foreach (var item in sourceDb.Communications.AsNoTracking())
{
item.Id = 0;
await db.Communications.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 14;
#endregion
#region Order
ProgressStatus = "Создание таблицы OrderSource...";
foreach (var item in sourceDb.Sources.AsNoTracking())
{
await db.Sources.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 15;
ProgressStatus = "Создание таблицы OrderStatus...";
foreach (var item in sourceDb.OrderStatuses.AsNoTracking())
{
await db.OrderStatuses.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 16;
ProgressStatus = "Создание таблицы OrderType...";
foreach (var item in sourceDb.DeliveryTypes.AsNoTracking())
{
await db.DeliveryTypes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 17;
ProgressStatus = "Создание таблицы Order...";
foreach (var item in sourceDb.Orders.AsNoTracking())
{
await db.Orders.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 18;
ProgressStatus = "Создание таблицы OrderItems...";
foreach (var item in sourceDb.OrderDishes.AsNoTracking())
{
await db.OrderDishes.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 19;
ProgressStatus = "Создание таблицы OrderStatusHistory...";
foreach (var item in sourceDb.OrderStatusHistories.AsNoTracking())
{
await db.OrderStatusHistories.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 20;
ProgressStatus = "Создание таблицы OrderStatusSequence...";
foreach (var item in sourceDb.OrderStatusSequences.AsNoTracking())
{
item.Id = 0;
await db.OrderStatusSequences.AddAsync(item);
}
await db.SaveChangesAsync();
ProgressValue = 21;
#endregion
#region DbVersion
ProgressStatus = "Запись версии базы данных...";
await db.DbVersion.AddAsync(await sourceDb.DbVersion.FirstAsync());
await db.SaveChangesAsync();
ProgressValue = 22;
#endregion
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelController : MonoBehaviour {
public int level;
public Sprite[] levelBitmaps;
//private MovePlayer mp;
bool paused;
// Use this for initialization
void Start () {
level = 0;
//mp = GameObject.FindGameObjectWithTag("Player").GetComponent<MovePlayer>();
paused = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Escape)) {
paused = !paused;
if (paused) {
PauseGame();
} else {
ResumeGame();
}
}
}
public void SetPaused(bool paused) {
this.paused = paused;
}
public void PauseGame() {
SceneManager.LoadScene("PauseScene", LoadSceneMode.Additive);
}
public void ResumeGame() {
SceneManager.UnloadSceneAsync("PauseScene");
}
}
|
using System.Collections.Generic;
using System.Windows;
using CaveDwellers.Core.Movement;
using CaveDwellers.Core.TimeManagement;
using CaveDwellers.Positionables;
namespace CaveDwellers.Core
{
public interface IWorldMatrix : IWantToBeNotifiedOfGameTimeElapsedEvents
{
void Add(int x, int y, IPositionable @object);
void Add(Point point, IPositionable @object);
IPositionable GetObjectAt(int x, int y);
IPositionable GetObjectAt(Point point);
Point? GetLocationOf(IPositionable @object);
void Move<T>(T @object)
where T : IAutoMoveable, IPositionable;
void Move(GoodGuy goodGuy, Direction direction);
IEnumerable<KeyValuePair<IPositionable, Point>> GetObjects();
}
} |
using System;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using RainyDay.Models;
namespace RainyDay
{
public class Algorithm
{
public string text;
public string pattern;
public string expr;
/** Melakukan pengecekan News di dalam news_list dan memasukkan hasil pengecekan ke dalam news_match.
*/
public void StringMatching(string keyword, string algorithm, List<News> news_list, List<NewsMatch> news_match)
{
foreach (News news in news_list)
{
text = news.content;
pattern = keyword;
NewsMatch berita = new NewsMatch();
if (algorithm.Equals("KMP"))
{
berita.start = kmpMatch(); // pencocokan isi berita
if (berita.start == -1) // isi not match
{
text = news.title;
berita.start = kmpMatch(); // pencocokan isi judul
if (berita.start > -1) // judul match
{
berita.isContent = 0;
berita.end = (berita.start + pattern.Length - 1);
}
}
else
{
berita.end = (berita.start + pattern.Length - 1);
berita.isContent = 1;
}
}
else if (algorithm.Equals("Boyer-Moore"))
{
berita.start = bmMatch(); // pencocokan isi berita
if (berita.start == -1) // isi not match
{
text = news.title;
berita.start = bmMatch(); // pencocokan isi judul
if (berita.start > -1) // judul match
{
berita.isContent = 0;
berita.end = (berita.start + pattern.Length - 1);
}
}
else
{
berita.end = (berita.start + pattern.Length - 1);
berita.isContent = 1;
}
}
else
{
int[] arrInt = new int[2];
buildRegex();
showMatch(news_match,arrInt); // pencocokan isi berita
if (arrInt[0] == -1) // isi not match
{
text = news.title;
buildRegex();
showMatch(news_match, arrInt); // pencocokan isi judul
if (arrInt[0] > -1) // judul match
{
berita.start = arrInt[0];
berita.end = arrInt[1];
berita.isContent = 0;
}
}
else
{
berita.start = arrInt[0];
berita.end = arrInt[1];
berita.isContent = 1;
}
}
news_match.Add(berita);
}
}
public int[] computeFail()
{
int[] fail = new int [pattern.Length];
fail[0] = 0;
int m = pattern.Length;
int j = 0;
int i = 1;
while (i < m)
{
if (pattern[j] == pattern[i])
{
fail[i] = j + 1;
i++;
j++;
}
else if (j > 0)
j = fail[j - 1];
else
{
fail[i] = 0;
i++;
}
}
return fail;
}
/** Melakukan pencocokan pattern dengan string text menggunakan KMP.
*/
public int kmpMatch()
{
int n = text.Length;
int m = pattern.Length;
int[] fail = computeFail();
int i = 0;
int j = 0;
while (i < n)
{
if (pattern[j] == text[i])
{
if (j == m - 1)
return i - m + 1;
i++;
j++;
}
else if (j > 0)
j = fail[j - 1];
else
i++;
}
return -1;
}
public int[] buildLast()
{
int[] last = new int[128];
for (int i = 0; i < 128; i++)
last[i] = -1;
for (int i = 0; i < pattern.Length; i++)
last[pattern[i]] = i;
return last;
}
/** Melakukan pencocokan pattern dengan string text menggunakan Boyer Moore.
*/
public int bmMatch()
{
int[] last = buildLast();
int n = text.Length;
int m = pattern.Length;
int i = m - 1;
if (i > n - 1)
return -1;
int j = m - 1;
do
{
if (pattern[j] == text[i])
{
if (j == 0)
return i;
else
{
i--;
j--;
}
}
else
{
int lo = last[text[i]];
i = i + m - Math.Min(j, 1+lo);
j = m - 1;
}
}
while (i <= n - 1);
return -1;
}
/** Melakukan pencocokan pattern dengan string text menggunakan Regex.
*/
public void showMatch(List<NewsMatch> news_match, int[] arrInt)
{
Regex r = new Regex(@expr, RegexOptions.IgnoreCase);
Match m = r.Match(text);
if (m.Success)
{
Capture c = m.Groups[0].Captures[0];
arrInt[0] = (c.Index);
arrInt[1] = (c.Index + c.Length - 1);
}
else
{
arrInt[0] = -1;
arrInt[1] = -1;
}
}
/** Membangun regex untuk melakukan pencarian pattern di dalam text.
*/
public void buildRegex()
{
expr = Regex.Replace(pattern,@"\s+","(?:\\s+[^\\s]+)*\\s+");
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Bank.Models
{
public class Account
{
[Key]
public int Id { get; set; }
[Required]
public int UserId { get; set; }
[Required]
public bool IsLocked { get; set; }
[Required]
public decimal Balance { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
public virtual ICollection<Transaction> TransactionsTo { get; set; }
public virtual ICollection<Transaction> TransactionsFrom { get; set; }
public Account()
{
TransactionsTo = new List<Transaction>();
TransactionsFrom = new List<Transaction>();
}
}
} |
using BDBak.Helpers;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BDBak.Jobs
{
public class BackupJob
{
private static IScheduler scheduler;
public static void StartdJobs(string _directory, string _dataBase, string[] intervalos)
{
RunProgramRunExample(_directory, _dataBase, intervalos).GetAwaiter().GetResult();
}
public static void StopJobs()
{
scheduler.Shutdown();
scheduler.Clear();
}
private static async Task RunProgramRunExample(string _directory, string _dataBase, string[] intervalos)
{
try
{
// Grab the Scheduler instance from the Factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
scheduler = await factory.GetScheduler();
// and start it off
await scheduler.Start();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<BackupDataBaseJob>()
.WithIdentity($"JOB_BAKCUP_{_dataBase}", $"GROUP_JOB_BACKUP_{_dataBase}")
.UsingJobData("directory", _directory)
.UsingJobData("database", _dataBase)
.Build();
IList<ITrigger> triggers = new List<ITrigger>();
foreach (var item in intervalos)
{
string[] splitTime = item.Split(':');
TimeSpan timeSpan = new TimeSpan(Convert.ToInt32(splitTime[0]), Convert.ToInt32(splitTime[1]), 0);
// Trigger the job to run now, and then repeat every 10 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity($"TRIGGER_BAKCUP_{_dataBase}_INTERVAL_{item}", $"GROUP_{_dataBase}_TRIGGER_BACKUP_INTERVAL")
.StartNow()
.WithCronSchedule($"0 {timeSpan.Minutes} {timeSpan.Hours} ? * *")
.Build();
triggers.Add(trigger);
// Tell quartz to schedule the job using our trigger
// some sleep to show what's happening
//await Task.Delay(TimeSpan.FromSeconds(60));
// and last shut down the scheduler when you are ready to close your program
//await scheduler.Shutdown();
}
IReadOnlyCollection<ITrigger> listOfTriggers = new ReadOnlyCollection<ITrigger>(triggers);
await scheduler.ScheduleJob(job, listOfTriggers, true);
}
catch (SchedulerException se)
{
Console.WriteLine(se);
}
}
}
public class BackupDataBaseJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
var _directory = context.JobDetail.JobDataMap.GetString("directory");
var _database = context.JobDetail.JobDataMap.GetString("database");
await DatabaseHelper.GerarBak(_directory, _database);
//await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : MonoBehaviour
{
[Header("Item Variables")]
public string itemType;
public float rotateSpeed = 10f;
void Update()
{
transform.Rotate(transform.up, rotateSpeed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
IncrementItem(other.gameObject);
Destroy(gameObject);
}
}
void IncrementItem(GameObject obj)
{
switch (itemType)
{
case "Food":
obj.GetComponent<Player>().foodCount++;
break;
case "Scrap":
obj.GetComponent<Player>().scrapCount++;
break;
case "Crate":
obj.GetComponent<Player>().crateCount++;
break;
default:
break;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cofre : MonoBehaviour
{
public SlotInventario[] Inventario;
public int CapacidadInventario;
private void Awake()
{
CapacidadInventario = int.Parse(GestorDatos.DatosGenericos["Cofres"]["Espacios"][gameObject.tag].ToString());
Inventario = new SlotInventario[CapacidadInventario];
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumPrepare4Crawler
{
[TestClass]
public class SearchTest
{
//[TestMethod]
//public void TestMethod1()
//{
// IWebDriver webDriver=new FirefoxDriver();
// webDriver.Navigate().GoToUrl("https://www.google.com");
// IWebElement webElement = webDriver.FindElement(By.Name("q"));
// webElement.SendKeys("facebook");
// webElement.Submit();
// System.Threading.Thread.Sleep(1000);
// webDriver.Quit();
//}
//[TestMethod]
//public void TestEdge()
//{
// IWebDriver driver = new EdgeDriver();
// driver.Navigate().GoToUrl("https://www.bing.com");
// var src = driver.PageSource;
// IWebElement webElement = driver.FindElement(By.Name("q"));
// webElement.SendKeys("facebook");
// webElement.Submit();
// System.Threading.Thread.Sleep(1000);
// // driver.Quit();
//}
//[TestMethod]
//public void TestYahooAutoLogin()
//{
// IWebDriver driver = new EdgeDriver();
// driver.Navigate().GoToUrl("https://login.yahoo.com/");
// IWebElement webElement = driver.FindElement(By.Id("login-username"));
// webElement.SendKeys("account");//account field
// System.Threading.Thread.Sleep(1000);
// driver.FindElement(By.Id("login-signin")).Click();
// driver.FindElement(By.Id("login-passwd")).SendKeys("password123");//password field
// driver.FindElement(By.Id("login-signin")).Click();
// webElement.Submit();
// driver.Close();
//}
/// <summary>
/// Tests the flip automatic chat.
/// </summary>
[TestMethod]
public void TestFlipAutoChat()
{
IWebDriver webDriver = new FirefoxDriver();
webDriver.Navigate().GoToUrl("https://fleep.io/chat");
webDriver.FindElement(By.XPath("//input[@placeholder='Username or email address']")).SendKeys("account");
webDriver.FindElement(By.XPath("//input[@placeholder='Password']")).SendKeys("passwd");
webDriver.FindElement(By.XPath("//button[contains(text(), 'SIGN IN')]")).Click();
//System.Threading.Thread.Sleep(9000);// the waiting for a threading time is not ideal
//webDriver.FindElement(By.XPath("//div[contains(text(),'讀書會')]")).Click();
//WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
//webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
string channelName = "讀書會";
var elem = FindElement(webDriver,By.XPath($"//div[contains(text(),'{channelName}')]"),10);
((IJavaScriptExecutor)webDriver).ExecuteScript("arguments[0].click();", elem);
elem = webDriver.FindElement(By.XPath("//textarea[@placeholder='Type your message']"));
elem.SendKeys("bootstrap " + DateTime.Now.ToLongDateString());
elem.FindElement(By.XPath("//div[contains(text(), 'Send')]")).Click();
webDriver.Quit();
//var elems = webDriver.FindElements(By.ClassName("conversation"));
//foreach (var elem in elems)
//{
// if (elem.GetAttribute("data-id") == "8ac9096d-41cf-476f-a666-15ef3a469a84")
// {
// elem.Click();
// // ((IJavaScriptExecutor)webDriver).ExecuteScript("arguments[0].click();", elem);
// }
//}
}
/// <summary>
/// Finds the element.
/// </summary>
/// <param name="driver">The driver.</param>
/// <param name="by">The by.</param>
/// <param name="timeoutInSeconds">The timeout in seconds.</param>
/// <returns>IWebElement.</returns>
public IWebElement FindElement( IWebDriver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
}
|
using NUnit.Framework.Constraints;
namespace Parser.Models
{
public class TokenModel
{
public string Text { get; set; }
public int Index { get; set; }
public TokenModel(string text, int index)
{
Text = text;
Index = index;
}
public TokenModel(string text)
{
Text = text;
Index = -1;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (!(obj is PartModel pm)) return false;
return pm.Index == Index && pm.Text == Text;
}
}
} |
using Microsoft.AspNet.SignalR;
namespace Condor.Web.Hubs
{
public class ChatHub: Hub
{
public void SubmitMessage(string message)
{
PublishMessage(message);
}
private void PublishMessage(string message)
{
Clients.All.onMessagePublished(message);
}
}
} |
using System;
public static class GlobalScope
{
public static int CUBE_SIZE = 16;
public static int CUBE_OFFSET = -1;
public static float SCRAMBLE_DELAY = .1f;
public static float MOVE_TIME = 5f;
} |
using System;
namespace hw1_j_oneill
{
class GamblersRuin
{
//Random object must be created at start of class to prevent RNG being seeded the same with each call
Random rand = new Random();
//Tosscoin() simulates a random coin flip and
//returns a true for heads or false for tails
private bool Tosscoin()
{
//Generate random positive int less than 2
//Either 0 or 1
int n = rand.Next(0, 2);
if (n == 1)
return true;
else
return false;
}
//Rungame simualtes 1 iteration of the gambers ruin.
//Returns true if player 1 wins.
//Returns false if player 2 wins.
//n1 = number of coins for player 1.
//n2 = number of coins for player 2.
public bool Rungame(int n1, int n2)
{
while (n1 > 0 && n2 > 0)
{
if (Tosscoin())
{
//Player 1 gains a coin
n1++;
//Player 2 loses a coin
n2--;
}
else
{
//Player 1 loses a coin
n1--;
//Player 2 gains a coin
n2++;
}
}
//End the game
if (n2 == 0)
{
//Player 1 wins
return true;
}
else
{
//Player 2 wins
return false;
}
}
}
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Gamblers Ruin\n");
//Create new GamblersRuin object
GamblersRuin gambler = new GamblersRuin();
int totalRuns;
int player1Wins;
/* Part 1
* n1 = n2 = 100
* 100 simulations of the gamblers ruin
* Outputs number of times player 1 wins and player 2 wins
*/
totalRuns = 100;
player1Wins = 0;
for (int i = 0; i < totalRuns; i++)
{
//Keep track of number of times player 1 wins
if (gambler.Rungame(100, 100))
player1Wins++;
}
//Output results
Console.WriteLine("Part 1 :");
Console.WriteLine("n1 = 100, n2 = 100");
Console.WriteLine("Player 1 won {0} times ", player1Wins);
Console.WriteLine("Player 2 won {0} times ", totalRuns - player1Wins);
/* Part 2
* n1 = 150, n2 = 50
* 100 simulations of the gamblers ruin
* Outputs number of times player 1 wins and player 2 wins
*/
totalRuns = 100;
player1Wins = 0;
for (int i = 0; i < totalRuns; i++)
{
//Keep track of number of times player 1 wins
if (gambler.Rungame(150, 50))
player1Wins++;
}
Console.WriteLine("\nPart 2 :");
Console.WriteLine("n1 = 150, n2 = 50");
Console.WriteLine("Player 1 won {0} times ", player1Wins);
Console.WriteLine("Player 2 won {0} times ", totalRuns - player1Wins);
}
}
}
|
using UnityEngine;
public class CellBehaviorBed : CellBehaviorOccupiable {
public override void onNeighborChange(CellState triggererCell, Position triggererPos) {
base.onNeighborChange(triggererCell, triggererPos);
CellData air = Main.instance.tileRegistry.getAir();
if(triggererPos == this.pos + Rotation.DOWN && this.world.getCellState(triggererPos).data == air) {
// The cell below this behavior was destroyed, remove this cell
print("removing top");
this.world.setCell(this.pos, air, false);
}
}
public override void onDestroy() {
base.onDestroy();
// Remove the bottom of bed
CellData air = Main.instance.tileRegistry.getAir();
Position pos1 = this.pos + Rotation.DOWN;
if(this.world.getCellState(pos1).data != air) {
print("removing bottom piece");
this.world.setCell(pos1, air, false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertiesIndexators
{
class Exc3
{
private int[] arr;
public Exc3(int num)
{
arr = new int[Math.Abs(num)];
for(int i = 0; i < arr.Length; i++)
{
arr[i] = i + 1;
}
}
public int Prop
{
get
{
int res = 0;
for(int i = 0; i < arr.Length; i++)
{
res += arr[i];
}
return res;
}
}
public static void Excs()
{
Exc3 Obj = new Exc3(-6);
Console.WriteLine(Obj.Prop);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.Model.Orders
{
public class FlowOrderViewModel
{
/// <summary>
/// 工單編號
/// </summary>
public string WorkNumber { get; set; }
/// <summary>
/// 流轉卡編號
/// </summary>
public string LotNo { get; set; }
/// <summary>
/// 投入數量
/// </summary>
public decimal InputQty { get; set; }
/// <summary>
/// 生產數量
/// </summary>
public decimal CurrentQty { get; set; }
/// <summary>
/// 包裝數量
/// </summary>
public decimal PackingQty { get; set; }
/// <summary>
/// 物料編碼
/// </summary>
public string MaterialCode { get; set; }
/// <summary>
/// 物料名稱
/// </summary>
public string MaterialName { get; set; }
/// <summary>
/// 流轉卡狀態
/// </summary>
public string Status { get; set; }
/// <summary>
/// 當前工序
/// </summary>
public string CurrentProcess { get; set; }
/// <summary>
/// 上個工序
/// </summary>
public string PrevProcess { get; set; }
/// <summary>
/// 下達時間
/// </summary>
public DateTime? DownTime { get; set; }
public string PartNumber { get; set; }
public string ProductCode { get; set; }
public bool IsSelected { get; set; }
//列印資訊
/// <summary>
/// 途程
/// </summary>
public List<string> Routes { get; set; }
/// <summary>
/// 工單數量
/// </summary>
public Nullable<decimal> WorkQty { get; set; }
/// <summary>
/// 預計開工
/// </summary>
public Nullable<DateTime> StartTime { get; set; }
/// <summary>
/// 預計完工
/// </summary>
public Nullable<DateTime> EndTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ideal.Ipos.RealTime.Skat.Model;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Concurrent;
namespace Ideal.Ipos.RealTime.Skat.Controller {
public class GameHub : Hub {
/// <summary>
/// wird aufgerufen, wenn sich ein Spieler indirekt abmeldet, indem er die Seite
/// verlässt, aber auch, wenn er die Seite aktualisiert
/// zu testen wäre noch, ob diese Methode auch dann aufgerufen wird, wenn die
/// Internet-Verbindung abbricht
/// </summary>
public override System.Threading.Tasks.Task OnDisconnected() {
var connectionId = Context.ConnectionId;
// anahnd der ConnectionID die SpielerID und daraus den Spieltisch ermitteln
var spielerId = Verbindungen.SpielerID(connectionId);
var spieltisch = Spieltische.SucheNachSpielerID(spielerId);
// ist der Spieler an einem Spieltisch
if (spieltisch != null) {
// Spieler aus der Gruppe entfernen
Groups.Remove(Context.ConnectionId, spieltisch.ID);
// Nachricht senden, dass sich der Spieler abgemeldet hat
var spieler = spieltisch.Spieler.First(sp => sp.ID == spielerId);
Clients.Group(spieltisch.ID).spielerHatSichAbgemeldet(spieler);
}
// die Verbindung loeschen
Verbindungen.VerbindungLoeschen(connectionId);
// der Spieler bleibt aber mit seiner SpielerID an seinem Spieltisch registriert
// TODO: wenn eine bestimmte Zeitspann abgelaufen ist, muss er auch vom Spieltisch entfernt werden
return base.OnDisconnected();
}
/// <summary>
/// wird aufgerufen, wenn ein Spieler die Spiel betritt, indem die Seite aufgerufen wird,
/// aber auch, wenn die Seite aktualisiert wird (dann wird vorher 'OnDisconnected' aufgerufen)
/// </summary>
/// <param name="spielerID">
/// die SpielerID, die in einem Cookie hinterlegt sein kann,
/// ist sie null, wird eine neue SpielerID generiert
/// </param>
public dynamic SpielInitialisieren(string spielerID) {
var wiedereinstieg = false;
// Überprüfen, ob das Spiel wiederaufgenommen wird (z.B. wg. Aktualisierung der Seite im Browser)
// das ist möglich, da die Spieler ja nicht sofort vom Spieltisch entfern wird
var spieltisch = spielerID != null ? Spieltisch(spielerID) : null;
if (spieltisch != null) {
wiedereinstieg = true;
// in Hub-Gruppe wiederaufnehmen mit neuer ConnectionID
Groups.Add(Context.ConnectionId, spieltisch.ID);
Clients.Caller.spielerHatSpielWiederaufgenommen(spieltisch); // zunächst erfolgt die Nachricht nur an den Aufrufer, evtl. müssen auch noch Nachrichten an die Gruppe gesendet werden
}
// neue SpielerID generieren, wenn noch keine bestand
if (spielerID == null) {
spielerID = Guid.NewGuid().ToString("N");
}
// die neuen Verbindung registrieren
Verbindungen.VerbindungHinzufuegen(spielerID, Context.ConnectionId);
return new {
spielerId = spielerID,
wiedereinstieg = wiedereinstieg
};
}
/// <summary>
/// wird aufgerufen, wenn ein Spieler einem Spiel beitreten will, indem er seinen Namen eingibt und auf den Button klickt
/// </summary>
/// <param name="spielerID">
/// die SpielerID, die bereits beim Seitenaufruf aus dem Cookie auusgelesen
/// bzw. in der Methode 'SpielInitialisieren' generiert wurde
/// </param>
/// <param name="name">
/// Name des Spielers
/// </param>
public void AmSpielAnmelden(string spielerID, string name) {
Spieler spieler;
// Überprüfen, ob der Spieler nicht doch bereits an einem Tisch sitzt
// kann eigentlich nicht vorkommen, da dieser Fall bereits in 'Spiel initialisieren' abgefangen wurde, aber wer weiß...
var spieltisch = Spieltisch(spielerID);
if (spieltisch != null) {
// wenn es doch kein neuer Spieler ist, Exception werfen...
// TODO: das muss a) geloggt werden, b) der Client muss eine Nachricht bekommen
throw new HttpException();
}
// freien Platz an bestehendem oder neuen Spieltisch suchen
spieltisch = Spieltische.SucheSpieltischMitFreiemPlatz();
// Spieler-Objekt erzeugen
spieler = new Spieler(spielerID, name);
// Spieler dem Tisch zuweisen
spieltisch.SpielerHinzufuegen(spieler);
// in die Kommunikations-Gruppe aufnehmen
Groups.Add(Context.ConnectionId, spieltisch.ID);
// Nachricht an alle in der Kommunikations-Gruppe senden, dass ein neuer Spieler hinzugekommen ist
Clients.Group(spieltisch.ID).spielerHatSichAngemeldet(spieltisch, spieler);
// wenn genügend Spieler am Tisch sind, neue Runde ankündigen
if (spieltisch.BenoetigteSpieleranzahlErreicht()) {
spieltisch.NeueRundeStarten();
Clients.Group(spieltisch.ID).neueRundeAnkuendigen(spieltisch);
}
}
/// <summary>
/// Text-Nachricht an alle aus der Gruppe senden
/// </summary>
/// <param name="spielerID">
/// die SpielerID des Absenders, wird benötigt um die passende Kommunikations-Gruppe
/// zu identifizieren und den Spieler-Namen zu ermitteln
/// </param>
/// <param name="nachricht">die Text-Nachricht</param>
public void NachrichtAnGruppeSenden(string spielerID, string nachricht) {
var spieltisch = Spieltisch(spielerID);
var spielerName = spieltisch.Spieler.First(sp => sp.ID == spielerID).Name;
Clients.Group(spieltisch.ID).nachrichtEmpfangen(spielerName, nachricht);
}
public void BereitFurNeueRunde(string spielerID) {
var spieltisch = Spieltisch(spielerID);
spieltisch.SpielerBereitFuerNeueRunde(spielerID);
if (spieltisch.AlleSpielerBereit()) {
kartenVerteilen(spieltisch);
} else {
Clients.Group(spieltisch.ID).spielerIstBereitFuerNeueRunde(spielerID);
}
}
private void kartenVerteilen(Spieltisch spieltisch) {
var kartenGeber = new Spielregeln.Austeilen();
// die Karten müssen auch serverseitig gespeichert werden
// nur zum Test an die Gruppe um zu sehen, ob der Dialog geschlossen wird
// die Karten müssen dann natürlich separat an die einzelnen Spieler übermittlt werden
Clients.Group(spieltisch.ID).kartenGeben(kartenGeber.KartenHinterhand);
}
/// <summary>
/// Hilfsmethode um Spieltisch eines bestimmten Spielers zu finden
/// </summary>
private static Spieltisch Spieltisch(string spielerID) {
return Spieltische.SucheNachSpielerID(spielerID);
}
private static SpieltischVerwaltung _Spieltische = null;
private static SpieltischVerwaltung Spieltische {
get {
if (_Spieltische == null) {
_Spieltische = new SpieltischVerwaltung();
}
return _Spieltische;
}
}
private static VerbindungsVerwaltung _Verbindungen = null;
private static VerbindungsVerwaltung Verbindungen {
get {
if (_Verbindungen == null) {
_Verbindungen = new VerbindungsVerwaltung();
}
return _Verbindungen;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.Formating_Numbers
{
class FormatingNumbers
{
static void Main()
{
short a = short.Parse(Console.ReadLine());
float b = float.Parse(Console.ReadLine());
float c = float.Parse(Console.ReadLine());
string Hex = a.ToString("X");
string binary = Convert.ToString(a, 2);
Console.WriteLine("{0,-10}|{1}|{2,10:F2}|{3,-10:F3}|",
Hex, binary.PadLeft(10, '0'), b, c);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.