text stringlengths 13 6.01M |
|---|
namespace KISSMp3MoverBefore.Contracts
{
public interface IFileMoveStrategyFactory
{
IFileMoveStrategy Get(string type);
}
} |
using Akka.Actor;
using Faux.Banque.Domain.Aggregates;
using Faux.Banque.Domain.Contacts;
using Faux.Banque.Domain.Storage;
using Faux.Banque.Domain.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Faux.Banque.Domain.Actors
{
public class CustomerActorTyped : TypedActor,
IHandle<CreateCustomer>,
IHandle<OpenSavingsAccount>,
IHandle<OpenCheckingAccount>,
IHandle<TransferMoney>
{
readonly IEventStore eventStore;
public CustomerActorTyped(IEventStore eventStore)
{
if (eventStore == null) throw new ArgumentNullException("eventStore");
this.eventStore = eventStore;
}
public void Handle(CreateCustomer message)
{
Customer customer = GetCustomer(message.CustomerId);
customer.CreateCustomer(message.CustomerId, message.FirstName, message.LastName);
AppendToStream(message.CustomerId, customer);
}
public void Handle(OpenSavingsAccount message)
{
Customer customer = GetCustomer(message.CustomerId);
customer.OpenCheckingAccount(message.CustomerId, message.AccountId, message.OpeningDeposit, DateTime.Now);
AppendToStream(message.CustomerId, customer);
}
public void Handle(TransferMoney message)
{
Customer customer = GetCustomer(message.CustomerId);
customer.TransferMoney(message.CustomerId, message.SourceAccount, message.DestinationAccount, message.AmountToTransfer);
AppendToStream(message.CustomerId, customer);
}
public void Handle(OpenCheckingAccount message)
{
Customer customer = GetCustomer(message.CustomerId);
customer.OpenCheckingAccount(message.CustomerId, message.AccountId,message.OpeningDeposit,DateTime.Now);
AppendToStream(message.CustomerId, customer);
}
private Customer GetCustomer(CustomerId customerId)
{
EventStream eventStream = eventStore.LoadEventStream(customerId);
Customer customer = new Customer(eventStream.Events);
return customer;
}
private void AppendToStream(CustomerId customerId,Customer customer)
{
EventStream eventStream = eventStore.LoadEventStream(customerId);
eventStore.AppendToStream(customerId, eventStream.Version, customer.Changes);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL_DAL;
namespace QLNHAHANG
{
public partial class frmNhanVien : Form
{
NhanVien_BLL_DAL qlnv = new NhanVien_BLL_DAL();
List<NHANVIEN> lstNhanVien;
public frmNhanVien()
{
InitializeComponent();
lstNhanVien = qlnv.loadListNhanVien();
}
private void txtMaNhaCungCap_TextChanged(object sender, EventArgs e)
{
}
private void gunaLabel1_Click(object sender, EventArgs e)
{
}
private void frmNhanVien_Load(object sender, EventArgs e)
{
reset();
loadListNhanVien();
loadCboNguoiDung();
setHeaderNV();
databingding(0);
txtSoDienThoai.KeyPress += txtSoDienThoai_KeyPress;
btnLuu.Enabled = false;
btnSua.Enabled = false;
btnXoa.Enabled = false;
txtMa.Enabled = false;
txtHoTen.Enabled = false;
txtDiaChi.Enabled = false;
txtMatKhau.Enabled = false;
txtSoDienThoai.Enabled = false;
cboLoaiNhanVien.Enabled = false;
dateTimePickerNgaySinh.Enabled = false;
}
private void loadDataGridViewNhanVien()
{
dataGridViewNhanVien.DataSource = qlnv.loadDataGridViewNhanVien();
}
private void loadListNhanVien()
{
dataGridViewNhanVien.DataSource = lstNhanVien;
}
private void loadCboNguoiDung()
{
cboLoaiNhanVien.DataSource = qlnv.loadCboNhomNhanVien();
cboLoaiNhanVien.DisplayMember = "TENNQ";
cboLoaiNhanVien.ValueMember = "MANQ";
}
public void reset()
{
txtMa.Clear();
txtHoTen.Clear();
txtSoDienThoai.Clear();
txtDiaChi.Clear();
txtMatKhau.Clear();
}
public void databingding(int rowindex)
{
txtMa.Text = dataGridViewNhanVien.Rows[rowindex].Cells["MANV"].FormattedValue.ToString();
txtHoTen.Text = dataGridViewNhanVien.Rows[rowindex].Cells["TENNV"].FormattedValue.ToString();
txtSoDienThoai.Text = dataGridViewNhanVien.Rows[rowindex].Cells["SDT"].FormattedValue.ToString();
txtDiaChi.Text = dataGridViewNhanVien.Rows[rowindex].Cells["DIACHI"].FormattedValue.ToString();
dateTimePickerNgaySinh.Value = Convert.ToDateTime(dataGridViewNhanVien.Rows[rowindex].Cells["NGAYSINH"].FormattedValue.ToString());
cboLoaiNhanVien.SelectedValue = dataGridViewNhanVien.Rows[rowindex].Cells["MANQ"].FormattedValue.ToString();
ckHoatDong.Checked = Convert.ToBoolean(dataGridViewNhanVien.Rows[rowindex].Cells["TINHTRANG"].FormattedValue.ToString());
txtMatKhau.Text = dataGridViewNhanVien.Rows[rowindex].Cells["MATKHAU"].FormattedValue.ToString();
}
public Boolean checkHoatDong()
{
if (ckHoatDong.Checked)
{
return true;
}
else
{
return false;
}
}
private void txtSoDienThoai_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void dataGridViewNhanVien_CellClick(object sender, DataGridViewCellEventArgs e)
{
btnSua.Enabled = true;
btnXoa.Enabled = true;
btnThem.Enabled = true;
try
{
if (dataGridViewNhanVien.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
dataGridViewNhanVien.CurrentRow.Selected = true;
databingding(e.RowIndex);
}
}
catch
{
return;
}
}
public void setHeaderNV()
{
dataGridViewNhanVien.Columns["MANV"].HeaderText = "Mã nhân viên";
dataGridViewNhanVien.Columns["TENNV"].HeaderText = "Họ và tên";
dataGridViewNhanVien.Columns["DIACHI"].HeaderText = "Địa chỉ";
dataGridViewNhanVien.Columns["SDT"].HeaderText = "Số điện thoại";
dataGridViewNhanVien.Columns["MANV"].HeaderText = "Mã nhân viên";
dataGridViewNhanVien.Columns["TINHTRANG"].Visible = false;
dataGridViewNhanVien.Columns["NHOMQUYEN"].Visible = false;
}
public bool kiemtraMa()
{
string input = txtMa.Text;
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Mã nhân viên không được bỏ trống");
return false;
}
else
{
return true;
}
}
public bool kiemtraTenNhanVien()
{
string input = txtHoTen.Text;
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Tên nhân viên không được bỏ trống");
return false;
}
else
{
return true;
}
}
public bool kiemtraSoDienThoai()
{
string input = txtSoDienThoai.Text;
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Số điện thoại không được bỏ trống");
return false;
}
else if (input.Length != 10)
{
MessageBox.Show("Số điện thoại bao gồm 10 số.");
return false;
}
else
{
return true;
}
}
public bool kiemtraDiaChi()
{
string input = txtDiaChi.Text;
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Địa chỉ không được bỏ trống");
return false;
}
else
{
return true;
}
}
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public bool kiemtraNgaySinh()
{
string input = dateTimePickerNgaySinh.Value.ToString();
TimeSpan difference = getDateDifference(DateTime.Now, dateTimePickerNgaySinh.Value);
int differenceInDay = difference.Days;
if (differenceInDay < 18)
{
MessageBox.Show("Nhân viên chưa đủ 18 tuổi.");
return false;
}
else
{
return true;
}
}
public bool kiemtraMatKhau()
{
string input = txtMatKhau.Text;
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Mật khẩu không được bỏ trống");
return false;
}
else
{
return true;
}
}
private void btnThem_Click(object sender, EventArgs e)
{
Random r = new Random();
reset();
int count = qlnv.demSoLuong() + 1;
txtMa.Text = "NV00" + count + r.Next(0, 100);
btnLuu.Enabled = true;
btnThem.Enabled = false;
txtHoTen.Enabled = true;
txtDiaChi.Enabled = true;
txtMatKhau.Enabled = true;
txtSoDienThoai.Enabled = true;
cboLoaiNhanVien.Enabled = true;
dateTimePickerNgaySinh.Enabled = true;
}
private void btnSua_Click(object sender, EventArgs e)
{
btnLuu.Enabled = true;
txtHoTen.Enabled = true;
txtDiaChi.Enabled = true;
txtMatKhau.Enabled = false;
txtSoDienThoai.Enabled = true;
cboLoaiNhanVien.Enabled = true;
dateTimePickerNgaySinh.Enabled = true;
btnThem.Enabled = btnXoa.Enabled = false;
}
private void btnLuu_Click(object sender, EventArgs e)
{
if (!kiemtraMa() || !kiemtraTenNhanVien() || !kiemtraSoDienThoai() || !kiemtraDiaChi()
|| !kiemtraNgaySinh() || !kiemtraMatKhau())
{
frmNhanVien_Load(sender, e);
return;
}
else
{
if (qlnv.kiemTraKhoaChinh(txtMa.Text) != 0)
{
qlnv.suaNhanVien(txtMa.Text, txtHoTen.Text, txtSoDienThoai.Text, txtDiaChi.Text,
dateTimePickerNgaySinh.Value, cboLoaiNhanVien.SelectedValue.ToString(),
checkHoatDong(), txtMatKhau.Text);
//MessageBox.Show(checkHoatDong() + "");
MessageBox.Show("Sửa thành công");
loadDataGridViewNhanVien();
btnThem.Enabled = true;
btnLuu.Enabled = false;
frmNhanVien_Load(sender, e);
}
else
{
string hashPW = Utils.Encrypt(txtMatKhau.Text);
qlnv.themNhanVien(txtMa.Text, txtHoTen.Text, txtSoDienThoai.Text, txtDiaChi.Text,
dateTimePickerNgaySinh.Value, cboLoaiNhanVien.SelectedValue.ToString(),
true, hashPW);
MessageBox.Show("Thêm thành công");
loadDataGridViewNhanVien();
btnSua.Enabled = false;
btnLuu.Enabled = false;
btnThem.Enabled = false;
frmNhanVien_Load(sender, e);
}
}
frmNhanVien_Load(sender, e);
}
private void btnXoa_Click(object sender, EventArgs e)
{
try
{
qlnv.xoaNhanVien(txtMa.Text);
MessageBox.Show("Xóa thành công");
loadDataGridViewNhanVien();
btnXoa.Enabled = false;
}
catch
{
MessageBox.Show("Nhân viên" + txtMa.Text + " không thể xóa");
}
frmNhanVien_Load(sender, e);
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text.Length == 0)
{
loadDataGridViewNhanVien();
}
else
{
dataGridViewNhanVien.DataSource = qlnv.loadGridViewTimKiemNhanVien(txtSearch.Text);
}
}
private void txtSoDienThoai_TextChanged(object sender, EventArgs e)
{
}
private void btnRP_Click(object sender, EventArgs e)
{
frm_rpNhanVien rp = new frm_rpNhanVien();
rp.Show();
}
}
}
|
using PyFarmaceutica.acceso_a_datos.interfaces;
using PyFarmaceutica.dominio;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PyFarmaceutica.acceso_a_datos.implementaciones
{
public class SuministroDao : ISuministroDao
{
private string CadenaConexion;
private SqlConnection cnn;
public SuministroDao()
{
CadenaConexion = HelperDao.Instancia().CadenaConeccion();
cnn = new SqlConnection(CadenaConexion);
}
public bool Update(Suministro suministro)
{
SqlTransaction transaccion = null;
bool flag = true;
try
{
cnn.Open();
transaccion = cnn.BeginTransaction();
SqlCommand cmd = new SqlCommand("SP_UPDATE_SUMINISTRO", cnn, transaccion);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id_suministro",suministro.IdSuministro);
cmd.Parameters.AddWithValue("@suministro", suministro.Nombre);
cmd.Parameters.AddWithValue("@venta_libre", suministro.VentaLibre);
cmd.Parameters.AddWithValue("@id_tipo_suministro", suministro.TipoSuministro.IdTipoSuministro);
cmd.Parameters.AddWithValue("@pre_unitario", suministro.Precio);
cmd.Parameters.AddWithValue("@descripcion", suministro.Descripcion);
cmd.ExecuteNonQuery();
transaccion.Commit();
}
catch
{
transaccion.Rollback();
flag = false;
}
finally
{
if (cnn != null && cnn.State == ConnectionState.Open)
cnn.Close();
}
return flag;
}
public bool Delete(int id)
{
SqlTransaction transaccion = null;
bool flag = true;
try
{
cnn.Open();
transaccion = cnn.BeginTransaction();
SqlCommand cmd = new SqlCommand("SP_DELETE_SUMINISTRO", cnn, transaccion);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id_suministro", id);
cmd.ExecuteNonQuery();
transaccion.Commit();
}
catch
{
transaccion.Rollback();
flag = false;
}
finally
{
if (cnn != null && cnn.State == ConnectionState.Open)
cnn.Close();
}
return flag;
}
public bool Insert(Suministro suministro)
{
SqlTransaction transaccion = null;
bool flag = true;
try
{
cnn.Open();
transaccion = cnn.BeginTransaction();
SqlCommand cmd = new SqlCommand("SP_INSERTAR_SUMINISTRO", cnn, transaccion);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id_suministro", suministro.IdSuministro);
cmd.Parameters.AddWithValue("@suministro", suministro.Nombre);
cmd.Parameters.AddWithValue("@venta_libre", suministro.VentaLibre);
cmd.Parameters.AddWithValue("@id_tipo_suministro", suministro.TipoSuministro.IdTipoSuministro);
cmd.Parameters.AddWithValue("@precio", suministro.Precio);
cmd.Parameters.AddWithValue("@descripcion", suministro.Descripcion);
cmd.ExecuteNonQuery();
transaccion.Commit();
}
catch
{
transaccion.Rollback();
flag = false;
}
finally
{
if (cnn != null && cnn.State == ConnectionState.Open)
cnn.Close();
}
return flag;
}
public DataTable Suministros()
{
SqlCommand cmd = new SqlCommand("SP_CONSULTAR_SUMINISTROS",cnn);
cmd.CommandType = CommandType.StoredProcedure;
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
public DataTable TiposSuministros()
{
SqlCommand cmd = new SqlCommand("SP_CONSULTAR_TIPOS_SUMINISTRO",cnn);
cmd.CommandType = CommandType.StoredProcedure;
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace SGA.Models
{
[NotMapped]
public class HorarioViewModel
{
public string Data { get; set; }
public string DiaDaSemana { get; set; }
public string Horario { get; set; }
public string Materia { get; set; }
public string Professor { get; set; }
public int? EmentaId { get; set; }
}
} |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Utilities.ASN1;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
#pragma warning disable 1591
/// <summary>
/// Type of Kerberos Host Address.
/// </summary>
public enum KerberosHostAddressType
{
IPv4 = 2,
Directional = 3,
ChaosNet = 5,
XNS = 6,
ISO = 7,
DECNETPhaseIV = 12,
AppleTalkDDP = 16,
NetBios = 20,
IPv6 = 24,
}
#pragma warning restore 1591
/// <summary>
/// Class representing a Kerberos Host Address.
/// </summary>
public class KerberosHostAddress
{
/// <summary>
/// Type of host address.
/// </summary>
public KerberosHostAddressType AddressType { get; }
/// <summary>
/// Address bytes.
/// </summary>
public byte[] Address { get; }
/// <summary>
/// ToString Method.
/// </summary>
/// <returns>The formatted string.</returns>
public override string ToString()
{
switch (AddressType)
{
case KerberosHostAddressType.IPv4:
if (Address.Length == 4)
{
return $"IPv4: {new IPAddress(Address)}";
}
break;
case KerberosHostAddressType.IPv6:
if (Address.Length == 16)
{
return $"IPv6: {new IPAddress(Address)}";
}
break;
}
return $"{AddressType} - {NtObjectUtils.ToHexString(Address)}";
}
private KerberosHostAddress(KerberosHostAddressType type, byte[] address)
{
AddressType = type;
Address = address;
}
internal static KerberosHostAddress Parse(DERValue value)
{
if (!value.CheckSequence())
throw new InvalidDataException();
KerberosHostAddressType type = 0;
byte[] data = null;
foreach (var next in value.Children)
{
if (next.Type != DERTagType.ContextSpecific)
throw new InvalidDataException();
switch (next.Tag)
{
case 0:
type = (KerberosHostAddressType)next.ReadChildInteger();
break;
case 1:
data = next.ReadChildOctetString();
break;
default:
throw new InvalidDataException();
}
}
if (type == 0 || data == null)
throw new InvalidDataException();
return new KerberosHostAddress(type, data);
}
internal static IReadOnlyList<KerberosHostAddress> ParseSequence(DERValue value)
{
if (!value.CheckSequence())
throw new InvalidDataException();
List<KerberosHostAddress> ret = new List<KerberosHostAddress>();
foreach (var next in value.Children)
{
ret.Add(Parse(next));
}
return ret.AsReadOnly();
}
}
}
|
/*--------------------------------------------------------------------------
Reactor.Fusion
The MIT License (MIT)
Copyright (c) 2015 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
using Reactor.Fusion.Protocol;
using System.Collections.Generic;
namespace Reactor.Fusion
{
public class Server
{
private Reactor.Udp.Socket socket;
private Reactor.Action<Reactor.Fusion.Socket> onsocket;
private Dictionary<System.Net.EndPoint, Reactor.Fusion.Socket> sockets { get; set; }
public Server()
{
this.socket = Reactor.Udp.Socket.Create();
this.onsocket = socket => { };
this.sockets = new Dictionary<System.Net.EndPoint, Reactor.Fusion.Socket>();
}
private void OnMessage(System.Net.EndPoint endpoint, byte[] message)
{
PacketType packetType;
var packet = Parser.Deserialize(message, out packetType);
if (packetType == PacketType.Syn) {
if (!this.sockets.ContainsKey(endpoint)) {
this.sockets[endpoint] = new Socket(this.socket, endpoint);
this.sockets[endpoint].OnConnect += () => {
this.onsocket(this.sockets[endpoint]);
};
}
}
if (this.sockets.ContainsKey(endpoint))
{
this.sockets[endpoint].Receive(message);
}
}
#region Setup
public void Listen(int port)
{
this.socket.Bind(System.Net.IPAddress.Any, port);
this.socket.OnMessage += this.OnMessage;
}
public static Server Create(Reactor.Action<Reactor.Fusion.Socket> callback)
{
var server = new Server();
server.onsocket = callback;
return server;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HomeWork05._05
{
class MyDictionary<TKey,TValue>
{
List<Entry<TKey,TValue>> entries = new List<Entry<TKey,TValue>>();
public IEnumerator<Entry<TKey,TValue>> GetEnumerator()
{
return entries.GetEnumerator();
}
//public IEnumerator GetEnumerator()
//{
// string[] array = new string[entries.Count];
// for(int i = 0; i < array.Length;i++)
// {
// array[i] = "[" + entries[i].Key.ToString() + "," + entries[i].Value.ToString() + "]";
// }
// return array.GetEnumerator();
//}
public List<TKey> Keys
{
get
{
List<TKey> n = new List<TKey>();
for (int i = 0; i < entries.Count; i++)
{
n.Add(entries[i].Key);
}
return n;
}
}
public List<TValue> Values
{
get
{
List<TValue> n = new List<TValue>();
for (int i = 0; i < entries.Count; i++)
{
n.Add(entries[i].Value);
}
return n;
}
}
public int Count { get { return entries.Count; } }
public TValue this[TKey index]
{
get
{
for (int i = 0; i < entries.Count; i++)
{
if (entries[i].Key == (dynamic)index)
return entries[i].Value;
}
throw new KeyNotFoundException();
}
set
{
int a = entries.Count;
for (int i = 0; i < entries.Count; i++)
{
if (entries[i].Key == (dynamic)index)
{
entries[i].Value = value;
}
else {
a--;
}
}
if(a==0)
throw new KeyNotFoundException();
}
}
public void Add(TKey keyy,TValue valuee)
{
entries.Add(new Entry<TKey, TValue>() { Key = keyy,Value = valuee});
}
}
class Entry<Tkey, TValue>
{
public Tkey Key;
public TValue Value;
}
}
|
using System.Collections.Generic;
namespace Howff.Navigation.Tests {
/// <summary>
/// This class fakes a navigation implementation and is used for tests on the abstract Navigation
/// base class. The navigation tree this class fakes looks like the tree below. Asterisks represents the selected path.
/// Hash characters marks not visible items.
///+---+
///|0 *|
///+--++
/// +-----------------+
/// v v
///+-----+ +------+ +------+
///|1-1 | |1-2 *| |1-3 #|
///+--+--+ +--+---+ +--+---+
/// +--------+ +--------+ +--------+
/// v v v v v v
///+------+ +------+ +------+ +------+ +------+ +------+
///|1-1-1 | |1-1-2 | |1-2-1 | |1-2-2*| |1-3-1 | |1-3-2#|
///+------+ +------+ +------+ +------+ +------+ +------+
/// | | | |
/// | | | +--------------------------------+---------+
/// | | +---------------------+---------+ | |
/// | +----------+---------+ | | | |
/// +-------+ | | | | | |
/// v v v v v v v v
///+-------+ +-------+ +-------+ +-------+ +-------+ +-------+ +-------+ +-------+
///|1-1-1-1| |1-1-1-2| |1-1-2-1| |1-1-2-2| |1-2-1-1| |1-2-1-2| |1-2-2-1| |1-2-2-2|
///+-------+ +-------+ +-------+ +-------+ +-------+ +-------+ +-------+ +-------+
/// </summary>
public class NavigationFake : Navigation {
private readonly NavigationItemFakes fakes;
public NavigationFake(NavigationItemFakes fakes) {
this.fakes = fakes;
}
protected override IList<INavigationItem> GetChildren(INavigationItem navigationItem) {
if(navigationItem == null) {
return null;
}
switch(navigationItem.Name) {
case "0-children-null":
return null;
case "0":
return ChildrenOfRoot;
case "1-1":
return ChildrenOfFirstChildOfRoot;
case "1-2":
return ChildrenOfSecondChildOfRoot;
case "1-3":
return ChildrenOfThirdChildOfRoot;
case "1-1-1":
return ChildrenOfFirstChildOfFirstChildOfRoot;
case "1-1-2":
return ChildrenOfSecondChildOfFirstChildOfRoot;
case "1-2-1":
return ChildrenOfFirstChildOfSecondChildOfRoot;
case "1-2-2":
return ChildrenOfSecondChildOfSecondChildOfRoot;
default:
return new INavigationItem[] { };
}
}
public IList<INavigationItem> PublicGetChildren(INavigationItem navigationItem) {
return GetChildren(navigationItem);
}
internal IList<INavigationItem> ChildrenOfRoot => new[] {
this.fakes.FirstChildOfRoot,
this.fakes.SecondChildOfRoot,
this.fakes.ThirdChildOfRoot
};
internal IList<INavigationItem> ChildrenOfFirstChildOfRoot => new[] {
this.fakes.FirstChildOfFirstChildOfRoot,
this.fakes.SecondChildOfFirstChildOfRoot
};
internal IList<INavigationItem> ChildrenOfSecondChildOfRoot => new[] {
this.fakes.FirstChildOfSecondChildOfRoot,
this.fakes.SecondChildOfSecondChildOfRoot
};
internal IList<INavigationItem> ChildrenOfThirdChildOfRoot => new[] {
this.fakes.FirstChildOfThirdChildOfRoot,
this.fakes.SecondChildOfThirdChildOfRoot
};
internal IList<INavigationItem> ChildrenOfFirstChildOfFirstChildOfRoot => new[] {
this.fakes.FirstChildOfFirstChildOfFirstChildOfRoot,
this.fakes.SecondChildOfFirstChildOfFirstChildOfRoot
};
internal IList<INavigationItem> ChildrenOfSecondChildOfFirstChildOfRoot => new[] {
this.fakes.FirstChildOfSecondChildOfFirstChildOfRoot,
this.fakes.SecondChildOfSecondChildOfFirstChildOfRoot
};
internal IList<INavigationItem> ChildrenOfFirstChildOfSecondChildOfRoot => new[] {
this.fakes.FirstChildOfFirstChildOfSecondChildOfRoot,
this.fakes.SecondChildOfFirstChildOfSecondChildOfRoot
};
internal IList<INavigationItem> ChildrenOfSecondChildOfSecondChildOfRoot => new[] {
this.fakes.FirstChildOfSecondChildOfSecondChildOfRoot,
this.fakes.SecondChildOfSecondChildOfSecondChildOfRoot
};
protected override IList<INavigationItemId> GetSelectedPath(INavigationItem rootItem, INavigationItem currentItem) {
return new[] {
this.fakes.Root.Id,
this.fakes.SecondChildOfRoot.Id,
this.fakes.SecondChildOfSecondChildOfRoot.Id
};
}
}
} |
using App.Entity.AttibutesProperty;
using System.ComponentModel;
using System.Data.Linq.Mapping;
namespace App.Entity
{
[Table(Name = "Permission")]
public class PermissionBE
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
[SettingProperties(
Label: "ID",
CausesValidation: true,
DefaultValue: 0,
IsAutoIncrement: true,
IsPrimaryKey: true,
IsReferenceKey: false,
PropertyName: "ID",
ReferenceColumn: "",
ReferenceTable: "",
Regex: @"[\d]",
Required: true,
TypeColumn: typeof(int))]
[Description("PRIMARY KEY")]
[Column(Name = "ID")]
public int ID { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
[SettingProperties(
Label: "Nombre",
CausesValidation: true,
DefaultValue: 0,
IsAutoIncrement: false,
IsPrimaryKey: false,
IsReferenceKey: false,
PropertyName: "Name",
ReferenceColumn: "",
ReferenceTable: "",
Regex: @"^[a-zA-Z]{3,20}$",
MaxSize: 20,
Required: true,
IsUnique: true,
TypeColumn: typeof(string))]
[Column(Name = "Name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
[SettingProperties(
Label: "Descripción",
CausesValidation: true,
DefaultValue: 0,
IsAutoIncrement: false,
IsPrimaryKey: false,
IsReferenceKey: false,
PropertyName: "Description",
ReferenceColumn: "",
ReferenceTable: "",
Regex: @"^[a-z- ']+$",
Required: true,
TypeColumn: typeof(string))]
[Column(Name = "Description")]
public string Description { get; set; }
[SettingProperties(
Label: "Id de formulario",
CausesValidation: true,
DefaultValue: 0,
IsAutoIncrement: false,
IsPrimaryKey: false,
MaxSize: 0,
PropertyName: "PathId",
Regex: @"[\d]",
Required: true,
TypeColumn: typeof(int))]
[Column(Name = "PathId")]
public int PathId { get; set; }
/// <summary>
/// Gets or sets the rol identifier.
/// </summary>
/// <value>
/// The rol identifier.
/// </value>
[SettingProperties(
Label: "Rol Id",
CausesValidation: true,
DefaultValue: 0,
IsAutoIncrement: false,
IsPrimaryKey: false,
IsReferenceKey: true,
MaxSize: 0,
PropertyName: "RolId",
ReferenceColumn: "ID",
ReferenceTable: "Rol",
Regex: @"[\d]",
Required: true,
TypeColumn: typeof(int))]
[Column(Name = "RolId")]
public int RolId { get; set; }
}
}
|
using UnityEngine;
public class GameStarter : MonoBehaviour {
[SerializeField]
bool isOffline;
[SerializeField]
GameMode gameMode;
[SerializeField]
bool destroyOnSetup;
[SerializeField]
bool displayNetworkStats;
void Start()
{
if ( isOffline && Application.isEditor )
{
InitializePlayerForFastDevelopment();
PhotonNetwork.offlineMode = isOffline;
} else
{
PhotonNetwork.automaticallySyncScene = true;
if (!PhotonNetwork.connected)
{ // obrir la escena directament per fer proves rapidament
InitializePlayerForFastDevelopment();
PhotonNetwork.ConnectUsingSettings(GamePreferences.GAME_VERSION);
}
else if (PhotonNetwork.isMasterClient) // obrir la escena des del menu principal on ja ens haviem connectat
InitializeGame();
}
}
void InitializePlayerForFastDevelopment()
{
ExitGames.Client.Photon.Hashtable customProperties = new ExitGames.Client.Photon.Hashtable();
customProperties.Add(PlayerProperties.skin, PlayerPrefs.GetString("Skin"));
PhotonNetwork.player.SetCustomProperties(customProperties);
PhotonNetwork.playerName = "Player " + Random.Range(0, 100);
}
void OnConnectedToMaster()
{
CreateRoom();
}
void CreateRoom()
{
RoomOptions roomOptions = GameModeFabric.ConstructRoomOptionsForGameMode(gameMode);
TypedLobby sqlLobby = GameModeFabric.ConstructTypedLobby();
PhotonNetwork.CreateRoom(null, roomOptions, sqlLobby);
}
void OnJoinedRoom()
{
if (!PhotonNetwork.offlineMode)
{
PhotonNetwork.room.visible = true;
PhotonNetwork.room.open = true;
}
InitializeGame();
}
void InitializeGame()
{
GetComponent<GameManager>().OnGameSetup();
if ( destroyOnSetup )
Destroy(this);
}
void OnGUI()
{
if (displayNetworkStats)
{
GUILayout.Box(PhotonNetwork.connectionStateDetailed.ToString());
GUILayout.Box("Ping: " + PhotonNetwork.GetPing());
}
}
}
|
using iBCNConsole.Command;
using iBCNConsole.CommandText;
using iBCNConsole.Device;
using Metocean.iBCN.Command;
using Metocean.iBCN.Command.Definition;
using Metocean.iBCN.Message;
using Metocean.iBCN.Message.Entity;
using Metocean.iBCN.Message.Interface;
using Metocean.iBCNLinkLayer.Link;
using ObjectPropertiesIteration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace iBCNConsole
{
/// <summary>
///
/// </summary>
public partial class Main : Form
{
/// <summary>
///
/// </summary>
private SerialLink link;
/// <summary>
///
/// </summary>
private const string datetimestyle = "yyyy/MM/dd HH:mm:ss.fff";
/// <summary>
///
/// </summary>
private readonly string spaceForDatetime;
/// <summary>
///
/// </summary>
private const int consoleWindowMaxLength = 1024 * 16;
/// <summary>
///
/// </summary>
private PropertiesIterator pi = new PropertiesIterator();
/// <summary>
///
/// </summary>
public Main()
{
InitializeComponent();
#region
//object iterator CB binding
//PropertiesIterator.CB += (prefixMsg, msg) =>
//{
// PrintOut(prefixMsg, msg, false);
// PrintOut_File(prefixMsg, msg);
//};
#endregion
//object iterator CB binding
pi.CB += (prefixMsg, msg) =>
{
PrintOut(prefixMsg, msg, false);
PrintOut_File(prefixMsg, msg);
};
//when a command is built, callback will be invoked
CommandBuilder.CB += (o) =>
{
AdvancedLogOutput(o, "*** Command Built ***");
};
//command set changed callback
Preprocessing.CommandSetChanged += (commands) =>
{
// initialize the commandinput box
comboBox_CommandInput.Items.Clear();
// combobox auto-complete
foreach (var c in commands)
{
comboBox_CommandInput.Items.Add(c);
}
};
//device info callback
DeviceInfo.CB += (info) =>
{
Invoke(new Action(() =>
{
if (info == null)
{
// set command set
Preprocessing.CurrentCommandSet = Preprocessing.CommandSupported_Common;
}
else
{
toolStripStatusLabel_Model.Text = "Model: " + ((Enum)info).ToString().Replace('_', '-');
// set command set, according to the device model
if (info == Metocean.iBCN.Device.DeviceEnum.MMI_513)
{
Preprocessing.CurrentCommandSet = Preprocessing.CommandSupported_MMI_513;
}
else
{
}
}
}));
};
//space initialization
spaceForDatetime = "";
for (int i = 0; i < 50; i++)
{
spaceForDatetime += " ";
}
//combobox is disabled
comboBox_CommandInput.Enabled = false;
comboBox_CommandInput.AutoCompleteSource = AutoCompleteSource.ListItems;
comboBox_CommandInput.AutoCompleteMode = AutoCompleteMode.Suggest;
closePortToolStripMenuItem.Enabled = false;
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
/// <param name="isError"></param>
private void PrintOut(string prefixMsg, string msg, bool isError = false)
{
richTextBox_ConsoleWindow.Invoke(new Action(() =>
{
if (richTextBox_ConsoleWindow.Text.Length > 3 * consoleWindowMaxLength)
{
richTextBox_ConsoleWindow.Text = new string(richTextBox_ConsoleWindow.Text.Skip(consoleWindowMaxLength).ToArray());
}
richTextBox_ConsoleWindow.SelectionStart = richTextBox_ConsoleWindow.Text.Length;
richTextBox_ConsoleWindow.SelectionColor = Color.White;
if (richTextBox_ConsoleWindow.Text.Length != 0)
{
richTextBox_ConsoleWindow.AppendText("\n");
richTextBox_ConsoleWindow.SelectionColor = Color.White;
richTextBox_ConsoleWindow.AppendText(prefixMsg);
}
else
{
richTextBox_ConsoleWindow.AppendText(prefixMsg);
}
if (isError)
{
richTextBox_ConsoleWindow.SelectionColor = Color.Red;
}
richTextBox_ConsoleWindow.AppendText(msg);
richTextBox_ConsoleWindow.ScrollToCaret();
}));
}
/// <summary>
/// output message to txt file
/// </summary>
/// <param name="prefixMsg"></param>
/// <param name="msg"></param>
private void PrintOut_File(string prefixMsg, string msg)
{
Invoke(new Action(() =>
{
try
{
if (!Directory.Exists("log"))
{
Directory.CreateDirectory("log");
}
File.AppendAllLines(@"log\console_" + System.DateTime.Now.ToString("yyyy_MM_dd") + ".txt", new string[] { prefixMsg + msg });
}
catch (Exception ex)
{
var timestamp = System.DateTime.Now.ToString(datetimestyle);
if (checkBox_ShowLogTime.Checked)
{
PrintOut(timestamp + ": ", ex.Message, true);
}
else
{
PrintOut("", ex.Message, true);
}
}
}));
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
private void SimpleLogOutput(string input)
{
var timestamp = System.DateTime.Now.ToString(datetimestyle);
if (checkBox_ShowLogTime.Checked)
{
PrintOut(timestamp + ": ", input, false);
}
else
{
PrintOut("", input, false);
}
PrintOut_File(timestamp + ": ", input);
}
/// <summary>
///
/// </summary>
private void AdvancedLogOutput(object o, string msgPrompt)
{
var timestamp = System.DateTime.Now.ToString(datetimestyle);
if (checkBox_ShowLogTime.Checked)
{
PrintOut(timestamp + ": ", msgPrompt, false);
PrintOut_File(timestamp + ": ", msgPrompt);
//PropertiesIterator.PrintIteration(o, 0, spaceForDatetime);
pi.PrintIteration(o, 0, spaceForDatetime);
}
else
{
PrintOut("", msgPrompt, false);
PrintOut_File(timestamp + ": ", msgPrompt);
//PropertiesIterator.PrintIteration(o, 0, "");
pi.PrintIteration(o, 0, spaceForDatetime);
}
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
private void PrintException(string msg)
{
var timestamp = System.DateTime.Now.ToString(datetimestyle);
if (checkBox_ShowLogTime.Checked)
{
PrintOut(timestamp + ": ", msg, true);
}
else
{
PrintOut("", msg, true);
}
PrintOut_File(timestamp + ": ", msg);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBox_CommandInput_KeyDown(object sender, KeyEventArgs e)
{
try
{
string input = "";
if (e.KeyCode == Keys.Enter)
{
//e.Handled = true;
input = comboBox_CommandInput.Text;
comboBox_CommandInput.Text = "";
if (richTextBox_ConsoleWindow.Text.Length > consoleWindowMaxLength)
{
richTextBox_ConsoleWindow.Text = new string(richTextBox_ConsoleWindow.Text.Skip(richTextBox_ConsoleWindow.Text.Length - consoleWindowMaxLength).ToArray());
}
SimpleLogOutput(input);
}
else
{
#region
/*
if ((e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Down))
{
//comboBox_CommandInput.SelectionStart = comboBox_CommandInput.Text.Length;
//e.Handled = true;
comboBox_CommandInput.SelectionStart = 0;
}
*/
#endregion
return;
}
//check if it is empty string[]
if (input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length == 0)
{
throw new Exception("Empty Input");
}
// get string array
string[] info = TextParser.GetSplittedStringArray(input);
if (Preprocessing.AnalyzeCommandMode(ref info, checkBox_EnableDefaultMode.Checked))
{
SimpleLogOutput("(Default Mode)");
}
// get cmd name, sequence number, payload
var cmdName = Preprocessing.GetCommandName(info);
var seq = Preprocessing.GetSequenceNum(info);
var payload = Preprocessing.GetPayload(info, DeviceInfo.CurrentDevice);
//build the command
var bytes = CommandBuilder.Build(cmdName, seq, payload, DeviceInfo.CurrentDevice);
//send the command on interface
link.SendWrappedBytes(bytes.Body);
//cmd sent, print it;
AdvancedLogOutput(bytes, "*** Command Sent ***");
}
catch (Exception ex)
{
PrintException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openPortToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
//pop up a window to select a port to open
var p = new Ports();
var r = p.ShowDialog(this);
if (r != DialogResult.OK)
{
return;
}
if (string.IsNullOrEmpty(p.PortName))
{
MessageBox.Show(this, "No port is selected", "Message", MessageBoxButtons.OK);
return;
}
link = new SerialLink();
link.AppDataBytesHandler += (bytes) =>
{
var msgPrompt = "*** Message Received ***";
var msg = MessageBuilder.GetMessage(bytes);
try
{
AdvancedLogOutput(msg, msgPrompt);
if (msg is IMsg<Identity>)
{
if (((IMsg<Identity>)msg).MessageEntity.ModelNumber == "MMI-513")
{
DeviceInfo.CurrentDevice = Metocean.iBCN.Device.DeviceEnum.MMI_513;
}
else if (((IMsg<Identity>)msg).MessageEntity.ModelNumber == "MMI-xxx")
{
DeviceInfo.CurrentDevice = Metocean.iBCN.Device.DeviceEnum.MMI_xxx;
}
else if (((IMsg<Identity>)msg).MessageEntity.ModelNumber == "MMI-yyy")
{
DeviceInfo.CurrentDevice = Metocean.iBCN.Device.DeviceEnum.MMI_yyy;
}
}
}
catch (Exception ex)
{
PrintException(ex.Message);
}
};
link.InvalidAppDataBytesHandler += (bytes) =>
{
var invalidMsgPrompt = "*** Invalid Message Received ***";
//var msg = "";
try
{
SimpleLogOutput(invalidMsgPrompt);
}
catch (Exception ex)
{
PrintException(ex.Message);
}
};
link.PlainTextBytesHandler += (bytes) =>
{
//var plainTextPrompt = "*** Plain Text Received ***";
var msg = Encoding.ASCII.GetString(bytes);
try
{
if (checkBox_ShowDiagnosticMsg.Checked)
{
//AdvancedLogOutput(msg, plainTextPrompt);
SimpleLogOutput(msg);
}
}
catch (Exception ex)
{
PrintException(ex.Message);
}
};
link.NoneStringDetectedHandler += (bytes) =>
{
//var msg = "";
try
{
}
catch (Exception ex)
{
PrintException(ex.Message);
}
};
var portName = p.PortName;
link.PortOpenHandler += () =>
{
toolStripStatusLabel_Com.Text = portName;
openPortToolStripMenuItem.Enabled = false;
closePortToolStripMenuItem.Enabled = true;
SimpleLogOutput(portName + " is opened");
//set commandset
Preprocessing.CurrentCommandSet = Preprocessing.CommandSupported_Common;
comboBox_CommandInput.Enabled = true;
toolStripStatusLabel_Model.Text = "Model: Unknown";
//get the identification
link.SendWrappedBytes(Command<GetIdentification>.GetCommandBytes(0).Body);
};
link.PortCloseHandler += () =>
{
DeviceInfo.CurrentDevice = null;
openPortToolStripMenuItem.Enabled = true;
closePortToolStripMenuItem.Enabled = false;
comboBox_CommandInput.Enabled = false;
toolStripStatusLabel_Com.Text = "Not Connected";
toolStripStatusLabel_Model.Text = ""; //"Model: Unknown"
SimpleLogOutput("Port is closed");
};
link.ExceptionHandler += (ex) =>
{
PrintException(ex.Message);
};
link.Open(portName);
}
catch (Exception ex)
{
PrintException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void closePortToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
link.Close();
link = null;
}
catch (Exception ex)
{
PrintException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openLogDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (!Directory.Exists("log"))
{
Directory.CreateDirectory("log");
}
System.Diagnostics.Process.Start(@"log");
}
catch (Exception ex)
{
PrintException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
new About().ShowDialog();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (closePortToolStripMenuItem.Enabled)
{
closePortToolStripMenuItem_Click(sender, e);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void fontSizeToolStripMenuItem_Click(object sender, EventArgs e)
{
var f = new FontSize();
var r = f.ShowDialog(this);
if (r != DialogResult.OK)
{
return;
}
Invoke(new Action(() =>
{
richTextBox_ConsoleWindow.Clear();
richTextBox_ConsoleWindow.Font = new Font("Arial", f.Font_Size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
}));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameConfig {
//这里可以定义一些游戏数据
public static int levelCount = 3;
public enum MapSize
{
SMALL, //400*400
MIDDLE, //800*800
LARGE //1000*1000
}
public enum Level
{
LEVEL1,
LEVEL2,
LEVEL3
}
public enum LevelState
{
PASS,
FAILE
}
public enum PropsState
{
STARTGAME,
RESTART,
ONPAUSE,
PAUSE_RELEASE,
RUNTIME,
}
public enum PlayerState
{
NORMAL,
DIE,
MOVE,
STAND,
FIGHT,
TURNDIRECTION
}
public enum TurnDirection
{
LEFT,
RIGHT
}
public enum CoreEvent
{
GAME_START,
GAME_UPDATE,
GAME_OVER,
GAME_RESTART,
LOADING,
PAUSE,
USER_INPUT
}
public enum OperationEvent
{
MOVE,
STOP,
ATTACK,
BEATTACKED,
PICK,
USEITEM,
USEWEAPON
}
}
|
using System;
using System.Collections;
namespace GraphTheory
{
/// <summary>
/// Summary description for Vertex.
/// </summary>
public class Vertex : Element, IComparable
{
public Vertex(
object key )
{
_key = key;
}
public
object Key
{
get
{
return _key;
}
}
public
int
CompareTo(
object other )
{
Comparer comparer = new Comparer( System.Globalization.CultureInfo.CurrentCulture );
Vertex otherVertex = (Vertex) other;
return comparer.Compare(
_key,
otherVertex._key );
}
protected object _key;
}
}
|
using System.Xml.Linq;
using PlatformRacing3.Common.Stamp;
using PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Exceptions;
using PlatformRacing3.Web.Extensions;
using PlatformRacing3.Web.Responses;
using PlatformRacing3.Web.Responses.Procedures.Stamps;
namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Stamps;
public class DeleteStampProcedure : IProcedure
{
public async Task<IDataAccessDataResponse> GetResponseAsync(HttpContext httpContext, XDocument xml)
{
uint userId = httpContext.IsAuthenicatedPr3User();
if (userId > 0)
{
XElement data = xml.Element("Params");
if (data != null)
{
uint stampId = (uint?)data.Element("p_stamp_id") ?? throw new DataAccessProcedureMissingData();
await StampManager.DeleteStampAsync(stampId, userId);
return new DataAccessDeleteStampResponse();
}
else
{
throw new DataAccessProcedureMissingData();
}
}
else
{
return new DataAccessErrorResponse("You are not logged in!");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using BindingOriented.SyncLinq.Debugging.Model.Events;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
namespace BindingOriented.SyncLinq.Debugging.Model.Nodes
{
internal class IteratorQueryNode : IQueryNode
{
private IBindableCollection _iterator;
private ObservableCollection<IQueryNodeEvent> _events;
private IBindableCollection<IQueryNode> _childNodes;
public IteratorQueryNode(IBindableCollection query)
{
_iterator = query;
_events = new ObservableCollection<IQueryNodeEvent>();
_iterator.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
{
_events.Add(new NotifyCollectionChangedQueryNodeEvent(e));
};
_iterator.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
_events.Add(new PropertyChangedQueryNodeEvent(e));
};
_childNodes = _iterator.AsBindable<object>()
.Select(c => QueryNodeFactory.Create(c));
}
public Type Type
{
get { return _iterator.GetType(); }
}
public IEnumerable<IQueryNodeEvent> Events
{
get { return _events; }
}
public IEnumerable<IQueryNode> ChildNodes
{
get { return _childNodes; }
}
public string DumpInformation()
{
using (StringWriter sw = new StringWriter())
{
ObjectDumper.Write(_iterator, 3, sw);
return sw.ToString();
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace ACO.UI
{
public class ErrorMessagePopUpInstance : MonoBehaviour
{
public Text textMessage, detailsMessage;
public WindowBase window;
public void Apply(string text, string details)
{
textMessage.text = text;
detailsMessage.text = details;
window.Open();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TemporaryEmploymentCorp.Models.Editable;
namespace TemporaryEmploymentCorp.Models.Qualification
{
public class NewQualificationModel : QualificationEditModel
{
public NewQualificationModel() : base(new DataAccess.EF.Qualification())
{
InitializeRequiredFields();
}
private void InitializeRequiredFields()
{
QualificationCode = string.Empty;
QualificationDescription = string.Empty;
}
}
public class QualificationEditModel:EditModelBase<DataAccess.EF.Qualification>
{
protected QualificationEditModel() : base(new DataAccess.EF.Qualification())
{
}
public QualificationEditModel(DataAccess.EF.Qualification model) : base(model)
{
ModelCopy = CreateCopy(model);
}
public string QualificationCode
{
get { return _ModelCopy.QualificationCode; }
set
{
// if(value.Contains("z"))
// SetErrors(nameof(Name), "Name should not contain z");
// else
// {
// ClearErrors(nameof(Name));
//
// }
string tmp = value;
string newValue = ValidateInputAndAddErrors(ref tmp, value, nameof(QualificationCode),
() => string.IsNullOrWhiteSpace(value), "Qualification Code should not be empty.");
_ModelCopy.QualificationCode = newValue;
}
}
public string QualificationDescription
{
get { return _ModelCopy.QualificationDescription; }
set
{
string tmp = value;
string newValue = ValidateInputAndAddErrors(ref tmp, value, nameof(QualificationDescription),
() => string.IsNullOrWhiteSpace(value), "Description should not be empty");
_ModelCopy.QualificationDescription = newValue;
}
}
private DataAccess.EF.Qualification CreateCopy(DataAccess.EF.Qualification model)
{
var copy = new DataAccess.EF.Qualification()
{
QualificationId = model.QualificationId,
QualificationCode = model.QualificationCode,
QualificationDescription = model.QualificationDescription
};
return copy;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace LR3_CSaN
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly SynchronizationContext context;
private volatile bool aliveUdpTask;
private volatile bool aliveTcpTask;
private const int CONNECT = 1;
private const int MESSAGE = 2;
private const int EXIT_USER = 3;
private const int SEND_HISTORY = 4;
private const int SHOW_HISTORY = 5;
private object synlock = new object();
public string Username { get; set; }
public string IpAddress { get; set; }
public List<ChatUser> ChatUsers { get; set; }
public string History { get; set; }
/// <summary>
/// Инициализация окна
/// </summary>
public MainWindow()
{
InitializeComponent();
context = SynchronizationContext.Current;
ChatUsers = new List<ChatUser>();
tbMessage.IsEnabled = false;
}
#region Получение IP-адреса пользователя и Broadcast адреса
/// <summary>
/// Получение локального IP-адреса пользователя
/// </summary>
private void GetIpAddress()
{
Socket tempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
try
{
tempSocket.Connect("8.8.8.8", 8100);
IpAddress = ((IPEndPoint)tempSocket.LocalEndPoint).Address.ToString();
}
catch
{
IpAddress = ((IPEndPoint)tempSocket.LocalEndPoint).Address.ToString();
}
tempSocket.Shutdown(SocketShutdown.Both);
tempSocket.Close();
}
private string GetBroadcastAddress(string localIP)
{
string temp = localIP.Substring(0, localIP.LastIndexOf(".") + 1);
return temp + "255";
}
#endregion
#region Отправка и получение UDP-пакетов
/// <summary>
/// Отправление UDP-пакета всем пользователям
/// </summary>
private void SendFirstNotification()
{
const int LOCAL_PORT = 8501;
const int REMOTE_PORT = 8502;
try
{
IPEndPoint sourceEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), LOCAL_PORT);
UdpClient udpSender = new UdpClient(sourceEndPoint);
IPEndPoint destEndPoint = new IPEndPoint(IPAddress.Parse(GetBroadcastAddress(IpAddress)), REMOTE_PORT);
udpSender.EnableBroadcast = true;
UdpMessage udpMessage = new UdpMessage(IpAddress, Username);
byte[] messageBytes = udpMessage.ToBytes();
udpSender.Send(messageBytes, messageBytes.Length, destEndPoint);
udpSender.Dispose();
string messageChat = "Вы успешно подключились!\r\n";
tbChat.AppendText(messageChat);
string datetime = DateTime.Now.ToString();
History += string.Format("{0} {1} присоединился к чату\r\n", datetime, Username);
}
catch
{
throw new Exception("Не удалось отправить уведомление о новом пользователе.");
}
}
/// <summary>
/// Приём UDP-пакетов от новых пользователей
/// </summary>
private void ListenUdpMessages()
{
const int REMOTE_UDP_PORT = 8501;
const int LOCAL_UDP_PORT = 8502;
const int TCP_PORT = 8503;
aliveUdpTask = true;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), LOCAL_UDP_PORT);
UdpClient udpReceiver = new UdpClient(localEndPoint);
while (aliveUdpTask)
{
try
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, REMOTE_UDP_PORT);
byte[] message = udpReceiver.Receive(ref remoteEndPoint);
UdpMessage receiveMessage = new UdpMessage(message);
// Устанавливаем подключение с новым пользователем
ChatUser newUser = new ChatUser(receiveMessage.Username, receiveMessage.Ip, TCP_PORT);
newUser.Connect();
// Отправляем новому пользователю своё имя
TcpMessage tcpMessage = new TcpMessage(CONNECT, IpAddress, Username);
newUser.SendMessage(tcpMessage);
ChatUsers.Add(newUser);
Task.Factory.StartNew(() => ListenUser(newUser));
context.Post(delegate (object state)
{
string datetime = DateTime.Now.ToString();
string messageChat = string.Format("{0} {1} присоединился к чату\r\n", datetime, newUser.Username);
tbChat.AppendText(messageChat);
}, null);
}
catch (Exception ex)
{
throw ex;
}
}
udpReceiver.Dispose();
}
#endregion
#region Отправка и получение TCP-пакетов
/// <summary>
/// Прослушивание TCP-пакетов
/// </summary>
private void ListenTcpMessages()
{
const int TCP_PORT = 8503;
aliveTcpTask = true;
try
{
TcpListener tcpListener = new TcpListener(IPAddress.Parse(IpAddress), TCP_PORT);
tcpListener.Start();
while (aliveTcpTask)
{
if (tcpListener.Pending())
{
ChatUser newUser = new ChatUser(tcpListener.AcceptTcpClient(), TCP_PORT);
Task.Factory.StartNew(() => ListenUser(newUser));
}
}
tcpListener.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Прослушивание пользователя чата
/// </summary>
/// <param name="user">Пользователь чата</param>
private void ListenUser(ChatUser user)
{
bool firstUser = true;
while (user.IsOnline)
{
try
{
if (user.Stream.DataAvailable)
{
byte[] message = user.RecieveMessage();
TcpMessage tcpMessage = new TcpMessage(message);
int code = tcpMessage.Code;
switch (code)
{
case CONNECT:
user.Ip = tcpMessage.Ip;
user.Username = tcpMessage.Username;
ChatUsers.Add(user);
if (firstUser)
{
GetHistory(SEND_HISTORY, user);
firstUser = false;
}
break;
case MESSAGE:
ShowInChat(code, user.Username, tcpMessage.MessageText);
break;
case EXIT_USER:
user.Dispose();
ChatUsers.Remove(user);
ShowInChat(code, user.Username, tcpMessage.MessageText);
break;
case SEND_HISTORY:
GetHistory(SHOW_HISTORY, user);
break;
case SHOW_HISTORY:
ShowInChat(code, user.Username, tcpMessage.MessageText);
break;
default:
break;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
/// <summary>
/// Отправка TCP-пакетов
/// </summary>
private void SendTcpMessage()
{
string userMessage = tbMessage.Text;
TcpMessage tcpMessage = new TcpMessage(MESSAGE, userMessage);
foreach (ChatUser user in ChatUsers)
{
try
{
user.SendMessage(tcpMessage);
}
catch
{
MessageBox.Show(string.Format("Не удалось отправить сообщение пользователю {0}.", user.Username));
}
}
string datetime = DateTime.Now.ToString();
string messageChat = string.Format("{0} Вы: {1}\r\n", datetime, userMessage);
tbChat.AppendText(messageChat);
tbMessage.Clear();
History += string.Format("{0} {1}: {2}\r\n", datetime, Username, userMessage);
}
#endregion
#region Вывод принятой информации в чат пользователя
/// <summary>
/// Вывод информации в чат (сообщения пользователей, сообщения о выходе из чата,
/// история пользователя из чата)
/// </summary>
/// <param name="code">Код сообщения</param>
/// <param name="username">Имя пользователя, от кого пришло сообщение</param>
/// <param name="message">Текст принятого сообщения</param>
private void ShowInChat(int code, string username, string message)
{
string datetime = DateTime.Now.ToString();
switch (code)
{
case MESSAGE:
context.Post(delegate (object state)
{
string messageChat = string.Format("{0} {1}: {2}\r\n", datetime, username, message);
History += messageChat;
tbChat.AppendText(messageChat);
}, null);
break;
case EXIT_USER:
context.Post(delegate (object state)
{
string messageChat = string.Format("{0} {1}\r\n", datetime, message);
History += messageChat;
tbChat.AppendText(messageChat);
}, null);
break;
case SHOW_HISTORY:
if (message != "")
{
context.Post(delegate (object state)
{
History = message + History;
tbChat.Text = message + tbChat.Text;
}, null);
}
break;
default:
break;
}
}
#endregion
#region Обработка событий формы
/// <summary>
/// Нажтие на кнопку "Подключиться"
/// </summary>
private void ButtonConnect_Click(object sender, RoutedEventArgs e)
{
tbUserName.Text = tbUserName.Text.Trim();
Username = tbUserName.Text;
if (Username.Length > 0)
{
GetIpAddress();
tbUserName.IsReadOnly = true;
try
{
SendFirstNotification();
Task listenUdpTask = new Task(ListenUdpMessages);
listenUdpTask.Start();
Task listenTcpTask = new Task(ListenTcpMessages);
listenTcpTask.Start();
btnConnect.IsEnabled = false;
tbMessage.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ExitChat();
}
}
}
/// <summary>
/// Нажтие на кнопку "Отправить"
/// </summary>
private void ButtonSend_Click(object sender, RoutedEventArgs e)
{
SendTcpMessage();
}
/// <summary>
/// Закрытие окна
/// </summary>
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (aliveUdpTask && aliveTcpTask)
ExitChat();
}
#endregion
#region Дополнительные методы (выход из чата, запрос истории)
/// <summary>
/// Запрос истории
/// </summary>
/// <param name="code">Код, отвечающий за запрос истории или её отправку</param>
/// <param name="user">Пользователь в чате, который отправляет или получает историю</param>
private void GetHistory(int code, ChatUser user)
{
try
{
TcpMessage tcpHistoryMessage;
if (code == SEND_HISTORY)
{
tcpHistoryMessage = new TcpMessage(code, "History");
}
else // SHOW_HISTORY
{
tcpHistoryMessage = new TcpMessage(code, History);
}
user.SendMessage(tcpHistoryMessage);
}
catch { }
}
/// <summary>
/// Выход из чата
/// </summary>
private void ExitChat()
{
aliveUdpTask = false;
aliveTcpTask = false;
string datetime = DateTime.Now.ToString();
string message = string.Format("{0} покинул чат", Username);
string exit = string.Format("{0} {1}\r\n", datetime, message);
tbChat.AppendText(exit);
lock (synlock)
{
TcpMessage tcpMessage = new TcpMessage(EXIT_USER, message);
foreach (ChatUser user in ChatUsers)
{
try
{
user.SendMessage(tcpMessage);
user.Dispose();
}
catch
{
MessageBox.Show("Ошибка отправки уведомления о выходе из чата.");
}
}
ChatUsers.Clear();
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linnworks_API.Model
{
// todo temp
public class HealthResponse
{
public string Process { get; set; }
public TimeSpan Uptime { get; set; }
public string Health { get; set; }
}
public enum StateType {AVAILABLE,LOCKED,MAINTENANCE,FAILED };
public enum LocalityType { EU, US, AS};
public class StatusDetails
{
public StateType State;
public string Reason;
public Dictionary<string, string> Parameters;
}
public class AuthorizeResponse
{
public DateTime LastActivity { get; set; }
public string Device { get; set; }
public string DeviceType { get; set; }
public string Server { get; set; }
public StatusDetails Status { get; set; }
public string BsonId { get; set; }
public Guid Id { get; set; }
public string Email { get; set; }
public Guid UserId { get; set; }
public string UserName { get; set; }
public string UserType { get; set; }
public Guid Token { get; set; }
public Guid EntityId { get; set; }
public string GroupName { get; set; }
public LocalityType Locality { get; set; }
public Dictionary<string, string> Properties { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
namespace Sample.Domain.Shared
{
public static class Data
{
public static Dictionary<Type, List<dynamic>> DB = new Dictionary<Type, List<dynamic>>();
public static Dictionary<Type, Dictionary<Guid, List<DomainEvent>>> Events = new Dictionary<Type, Dictionary<Guid, List<DomainEvent>>>();
}
public class MyRepository<T> where T : class
{
public void Add(T item)
{
//Printer.Print(ConsoleColor.Yellow);
if (Data.DB.ContainsKey(typeof(T)))
{
Data.DB[typeof(T)].Add(item);
}
else
{
Data.DB.Add(typeof(T), new List<dynamic> { item });
}
}
public void Update(T item)
{
//Printer.Print(ConsoleColor.Yellow);
var itemToUpdate = Data.DB[typeof(T)].Single(i => i.Id == ((dynamic)item).Id);
Data.DB[typeof(T)].Remove(itemToUpdate);
Data.DB[typeof(T)].Add(item);
}
public T Fetch(Guid id)
{
return Data.DB[typeof(T)].Single(i => i.Id == id);
}
public IEnumerable<T> FetchAll()
{
return Data.DB[typeof(T)].Select(i => (T)i);
}
}
public static class Cloner
{
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FiguresArea.Exeptions;
using FiguresArea.Interfaces;
namespace FiguresArea.Figures
{
/// <summary>
/// Построение треугольника
/// </summary>
public class Triangle : IFigure, IFigureBySides
{
public double[] sides { get; private set; }
public Triangle(double a, double b, double c)
{
this.sides = new double[] { a, b, c };
if (a <= 0 || b<=0 || c<= 0)
{
throw new InvalidFigureParameters("Стороны треугольника должны быть больше нуля.");
}
if ((sides.Max() * 2) >= sides.Sum())
{
throw new InvalidFigureParameters("Длина одной стороны не может быть больше, чем сумма длин других.");
}
}
/// <summary>
/// Рассчет площади треугольника
/// </summary>
public double Area()
{
double area = 0;
double sp = (sides[0] + sides[1] + sides[2])/2;
area = Math.Sqrt(sp * (sp - sides[0]) * (sp - sides[1]) * (sp - sides[2]));
if (area <= .0)
{
throw new InvalidFigureParameters("Площадь треугольника не может быть меньше нуля.");
}
return area;
}
/// <summary>
/// Проверка, является ли треугольник прямоугольным
/// </summary>
public bool IsRight()
{
return Math.Pow(sides.Max(), 2) * 2 == Math.Pow(sides[0], 2) + Math.Pow(sides[1], 2) + Math.Pow(sides[2], 2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Input;
using System.Linq;
using System.Text;
using MicroMvvm;
using FPModel.Entity;
using FPDataAccess;
using System.Collections.ObjectModel;
namespace FPViewModel
{
public class CustomerViewModel : ObservableObject
{
//members
#region Members
private Customer _customer;
private ObservableCollection<ForumViewModel> _forums ;
private string errorMessge;
private CustomerDAO customerDao;
#endregion
//properties
#region Properties
public Customer Customer
{
get
{
return _customer;
}
set
{
_customer = value;
}
}
public string Username
{
get
{
return _customer.Username;
}
set
{
_customer.Username = value;
RaisePropertyChanged("Username");
}
}
public string Password
{
get
{
return _customer.Password;
}
set
{
_customer.Password = value;
RaisePropertyChanged("Password");
}
}
public ObservableCollection<ForumViewModel> Forums
{
get
{
if (_forums == null)
{
_forums = new ObservableCollection<ForumViewModel>();
foreach (var f in _customer.Forums)
{
_forums.Add(new ForumViewModel()
{
Forum = f
});
}
}
return _forums;
}
set
{
_forums = value;
}
}
public ObservableCollection<AccountForumViewModel> Accounts
{
get
{
return Forums[0].AccountForums;
}
set
{
Forums[0].AccountForums = value;
}
}
public string Message
{
get
{
return errorMessge;
}
set
{
errorMessge = value;
RaisePropertyChanged("Message");
}
}
#endregion
//constructors
#region Constuctors
public CustomerViewModel()
{
if (_customer == null)
{
_customer = new Customer() { Username = "", Password = "" };
}
if (customerDao == null)
{
customerDao = new CustomerDAO();
}
}
#endregion
//Event
#region Events
//public event Action RequestClose;
public delegate void ActionWithArg(Customer cus);
public event ActionWithArg RequestClose;
#endregion
//Command
#region Commands
public ICommand CustomerLogin { get { return new RelayCommand(Login, CanLogin); } }
#endregion
//executeMethods
#region Methods
private bool CanLogin()
{
return true;
}
private void Login()
{
Customer cus = IsValidCustomer(_customer);
if (cus!=null)
{
if (RequestClose != null)
{
RequestClose(cus);
}
}
}
private Customer IsValidCustomer(Customer loged)
{
try
{
Customer selectedCustomer = customerDao.GetCustomer(loged.Username, loged.Password);
if (selectedCustomer != null)
{
return selectedCustomer;
}
else
{
Message = "Wrong username or password plz try again .";
return null;
}
}
catch (Exception ex)
{
Message = ex.Message;
return null;
}
}
#endregion
}
}
|
namespace FileSearch.Common
{
public class ExtendedFile : ExtendedFileInfo
{
public ExtendedFile(IExtendedFileInfo extendedFileInfo)
: base(extendedFileInfo.FullName)
{
}
public ExtendedFile(string fullname)
: base(fullname, false)
{
}
public ExtendedFile(string fullname, bool allinfo)
: base(fullname, allinfo)
{
}
public ExtendedFile()
{
}
public int Id { get; set; }
}
} |
/** 版本信息模板在安装目录下,可自行修改。
* API_MESSAGES.cs
*
* 功 能: N/A
* 类 名: API_MESSAGES
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014-7-11 15:35:20 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace PDTech.OA.Model
{
/// <summary>
/// 外部接口表
/// </summary>
[Serializable]
public partial class API_MESSAGES
{
public API_MESSAGES()
{}
#region Model
private decimal _api_message_id;
private string _message_type;
private string _from_type;
private decimal? _from_id;
private string _to_type;
private decimal? _to_id;
private DateTime _insert_time;
private DateTime? _try_time;
private decimal? _trials;
private string _response;
private string _data1;
private string _data2;
private string _data3;
private string _data4;
private decimal _message_stat;
private decimal? _creator;
private string _data5;
/// <summary>
/// 对外接口消息ID主键
/// </summary>
public decimal API_MESSAGE_ID
{
set{ _api_message_id=value;}
get{return _api_message_id;}
}
/// <summary>
/// 接口消息类型eg: COM_SMS:串口短信、.....
/// </summary>
public string MESSAGE_TYPE
{
set{ _message_type=value;}
get{return _message_type;}
}
/// <summary>
/// 消息来源类型如(OA_ARCHIVE,OA_MESSAGE)
/// </summary>
public string FROM_TYPE
{
set{ _from_type=value;}
get{return _from_type;}
}
/// <summary>
/// 任务来源ID,
/// </summary>
public decimal? FROM_ID
{
set{ _from_id=value;}
get{return _from_id;}
}
/// <summary>
/// 消息接收者类型如(OA_USER系统用户,其它外部系统)
/// </summary>
public string TO_TYPE
{
set{ _to_type=value;}
get{return _to_type;}
}
/// <summary>
/// 消息接收方ID
/// </summary>
public decimal? TO_ID
{
set{ _to_id=value;}
get{return _to_id;}
}
/// <summary>
/// 消息生成时间
/// </summary>
public DateTime INSERT_TIME
{
set{ _insert_time=value;}
get{return _insert_time;}
}
/// <summary>
/// 预计消息发送时间
/// </summary>
public DateTime? TRY_TIME
{
set{ _try_time=value;}
get{return _try_time;}
}
/// <summary>
/// 消息发送次数
/// </summary>
public decimal? TRIALS
{
set{ _trials=value;}
get{return _trials;}
}
/// <summary>
/// 消息发送回执
/// </summary>
public string RESPONSE
{
set{ _response=value;}
get{return _response;}
}
/// <summary>
/// 扩展数据1:如可用做存储发送消息的内容
/// </summary>
public string DATA1
{
set{ _data1=value;}
get{return _data1;}
}
/// <summary>
/// 扩展数据2
/// </summary>
public string DATA2
{
set{ _data2=value;}
get{return _data2;}
}
/// <summary>
/// 扩展数据3
/// </summary>
public string DATA3
{
set{ _data3=value;}
get{return _data3;}
}
/// <summary>
/// 扩展数据4
/// </summary>
public string DATA4
{
set{ _data4=value;}
get{return _data4;}
}
/// <summary>
/// 消息状态0:待发送 1:已发送
/// </summary>
public decimal MESSAGE_STAT
{
set{ _message_stat=value;}
get{return _message_stat;}
}
/// <summary>
/// 创建人
/// </summary>
public decimal? CREATOR
{
set{ _creator=value;}
get{return _creator;}
}
/// <summary>
/// 扩展数据5
/// </summary>
public string DATA5
{
set{ _data5=value;}
get{return _data5;}
}
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 16
namespace One_to_N_Scrambled_Numbers
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
int[] arraySort = new int[n];
Console.Write("The array before shuffling: ");
for (int i = 0; i < n; i++)
{
arraySort[i] = i + 1;
Console.Write(arraySort[i] + " ");
}
Console.WriteLine();
Random rand = new Random();
int[] arrayShuffled = Enumerable.Range(1, n).OrderBy(c => rand.Next()).ToArray();
Console.Write("The shuffled array: ");
for (int i = 0; i < arrayShuffled.Length; i++)
{
Console.Write(arrayShuffled[i] + " ");
}
}
}
}
|
using System;
namespace CoreEngine.Math
{
[Serializable]
public abstract class BaseVector2<TImpl,T> : BaseVector<TImpl,T> where T:struct, IConvertible where TImpl:BaseVector2<TImpl,T>,new()
{
public T x = default(T);
public T y = default(T);
public override T this[int i]
{
get {
switch( i )
{
case 0: return x;
case 1: return y;
default: return default(T);
}
}
set {
switch( i )
{
case 0: x = value; break;
case 1: y = value; break;
}
}
}
public BaseVector2()
{
Dimensions = 2;
}
public BaseVector2( T x, T y ) : this()
{
this.x = x;
this.y = y;
}
}
}
|
using BPiaoBao.SystemSetting.Domain.Models.SMS;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
namespace BPiaoBao.SystemSetting.EFRepository.BusinessmenMap
{
public class SMSTemplateMap : EntityTypeConfiguration<SMSTemplate>
{
public SMSTemplateMap()
{
this.Property(t => t.TemplateName).HasMaxLength(50);
this.Property(t => t.TemplateContents).HasMaxLength(1000);
this.Property(t => t.CreateName).HasMaxLength(50);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ADOX;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection baglanti = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\kullanıcı girişli 2\WindowsFormsApplication1\bin\Debug\mert.accdb");
baglanti.Open();
string sorgu = ("INSERT INTO bilgiler(tc_kımlık_no,Ad,Soyad,ogrenci_no,anne_adı,baba_adı,dogum_yeri,dogum_tarıhı,ıl,ılce,semt)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox10.Text + "','" + textBox11.Text + "')");
OleDbCommand komut = new OleDbCommand(sorgu, baglanti);
komut.ExecuteNonQuery();
baglanti.Close();
MessageBox.Show("VERİLER EKLENDİ");
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
textBox7.Text = string.Empty;
textBox8.Text = string.Empty;
textBox9.Text = string.Empty;
textBox10.Text = string.Empty;
textBox11.Text = string.Empty;
}
}
}
|
using Dapper.FluentMap.Mapping;
using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Common.Mappings
{
// This name... I know...
public class HomeyMappingMap : EntityMap<HomeyMapping>
{
public HomeyMappingMap()
{
Map(u => u.HumTopic).ToColumn("hum_topic");
Map(u => u.TempTopic).ToColumn("temp_topic");
Map(u => u.MotionTopic).ToColumn("motion_topic");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TheWorldRoom : MonoBehaviour
{
public GameObject P1, P2, P3, P4;
public List<GameObject> travellingBalls = new List<GameObject>();
float timeinterval, lfTime, speed;
GameObject tball;
public GameObject aimLine, bigLine;
public TheBarrier plane;
public TravellerControl TravellerCtrl;
public XFormControl xformCtrl;
private void Start()
{
aimLine = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
bigLine = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
startup();
}
void startup()
{
setTimeInterval(1f);
set_LifeTime(10f);
setSpeed(15f);
InvokeRepeating("duplicateTBall", 0f, timeinterval);
}
public void setTimeInterval(float t)
{
CancelInvoke();
timeinterval = t;
InvokeRepeating("duplicateTBall", 0f, timeinterval);
}
public float getTimeInterval() { return timeinterval; }
public void set_LifeTime(float t) { lfTime = t; }
public float get_LifeTime() { return lfTime; }
public void setSpeed(float dt) { speed = (16 - dt) * 60; }
public float getSpeed() { return Mathf.Abs(speed / 60 - 16); }
private void Update()
{
if (Input.GetKey("escape"))
Application.Quit();
drawLine(P1.transform.localPosition, P2.transform.localPosition, 0.2f, ref aimLine);
drawLine(P3.transform.localPosition, P4.transform.localPosition, 3f, ref bigLine);
}
public void drawLine(Vector3 one, Vector3 two, float radius, ref GameObject line)
{
Vector3 v = two - one;
float D = v.magnitude;
v.Normalize();
line.transform.localScale = new Vector3(radius, D , radius);
line.transform.localRotation = Quaternion.FromToRotation(Vector3.up, v);
line.transform.localPosition = one + D * v;
line.GetComponent<Renderer>().material.color = Color.black;
}
void duplicateTBall()
{
tball = Instantiate(Resources.Load("3d/travellingBalls")) as GameObject;
tball.transform.localPosition = P1.transform.localPosition;
travellingBalls.Add(tball);
tball.GetComponent<TravellingBallControl>().P1 = P1;
tball.GetComponent<TravellingBallControl>().P2 = P2;
tball.GetComponent<TravellingBallControl>().P3 = P3;
tball.GetComponent<TravellingBallControl>().P4 = P4;
tball.GetComponent<TravellingBallControl>().bigline = bigLine;
tball.GetComponent<TravellingBallControl>().plane = plane;
tball.GetComponent<TravellingBallControl>().setLifeTime(lfTime);
tball.GetComponent<TravellingBallControl>().setSpeed(speed);
tball.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
public void destroyBall(GameObject TBALL)
{
Destroy(TBALL);
}
public void moveEndPoints(GameObject obj, Vector3 pt)
{
if (obj.GetComponent<QuadControl>() != null)
// Debug.Log("");
obj.GetComponent<QuadControl>().MovePoint(pt);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RLookout;
public class RUnit : MonoBehaviour {
//key parameters for the unit
public UnitType unitType;
public int strength;
public Mark allegiance;
public string coords;
public int numMoves = 0;
public int defensiveBonus;
public int id;
public void AddDefensiveBonus(int bonusAmount){
defensiveBonus += bonusAmount;
}
public void RemoveDefensiveBonus(){
defensiveBonus = 0;
}
}
|
// Project Prolog
// Name: Spencer Carter
// CS 1400 Section 003
// Project: Lab_04
// Date: 1/21/2015
//
// I declare that the following code was written by me, provided
// by the instructor, or provided in the textbook for this project.
// I also declair understand that copying source
// code from any other source constitutes cheating, and that I will receive
// a zero on this project if I am found in violation of this policy.
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 Lab_04
{
public partial class FrmLearnMnuStrip : Form
{
/// <summary>
/// Purpose: Entry point into the application.
/// </summary>
public FrmLearnMnuStrip()
{
InitializeComponent();
}//End FrmLearnMnuStrip()
/// <summary>
/// Purpose: To respond to the Exit menu event and close the program
/// </summary>
/// <param name="sender">Exit Menue</param>
/// <param name="e">Not Used</param>
private void MnuExit_Click(object sender, EventArgs e)
{
// close program when the exit menu button is clicked
Close();
}//End MnuExit_Click()
/// <summary>
/// Purpose: To respond to the About menu click event and display a message box
/// </summary>
/// <param name="sender">About Menu Click Event</param>
/// <param name="e">EventArgs Object</param>
private void MnuAbout_Click(object sender, EventArgs e)
{
// display a message about who wrote the program in a popup, and have it exit by clicking either yes or no
string aboutMsg = "Spencer Carter\nCS1400\nLab #04";
string headerMsg = "About Dialog Box";
MessageBox.Show(aboutMsg,headerMsg,MessageBoxButtons.YesNo,MessageBoxIcon.Information);
}//End MnuAbout_Click()
}//end of CS1400_Lab_04 : Form
}//end of namespace
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Data.Services.Client;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Events.Helpers;
namespace Events.Controllers
{
[Authorize]
public class UsersController : Controller
{
public async Task<ActionResult> ShowThumbnail(string id)
{
try
{
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
IUser user = await client.Users.GetByObjectId(id).ExecuteAsync();
try
{
DataServiceStreamResponse response = await user.ThumbnailPhoto.DownloadAsync();
if(response != null)
{
return File(response.Stream, "image/jpeg");
}
}
catch
{
var file = Server.MapPath("~/Images/user-placeholder.png");
return File(file, "image/png", Path.GetFileName(file));
}
}
catch
{
}
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tindero.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Tindero.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StartupPage : ContentPage
{
private readonly BaseViewModel vm;
public StartupPage()
{
InitializeComponent();
vm = new StartupViewModel();
BindingContext = vm;
}
protected override void OnAppearing()
{
base.OnAppearing();
vm.OnAppearing();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using ProductPricing.ViewModels;
using ProductPricing.BusinessLogic;
using ProductPricing.Models;
namespace ProductPricing.Controllers
{
public class BulkTestController : Controller
{
private IHostingEnvironment hostingEnv;
/* public BulkTestController(IHostingEnvironment env)
{
this.hostingEnv = env;
}
*/
private readonly ABHIPricingDBContext _context;
public BulkTestController(ABHIPricingDBContext context, IHostingEnvironment env)
{
_context = context;
this.hostingEnv = env;
}
public IActionResult Index()
{
ViewData["Message"] = "Default Index";
return View();
}
public IActionResult Help()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(IFormFile testFile)
{
if(testFile == null)
{
ViewData["Message"] = "No File Selected";
return View();
}
//List<BultTestViewModel> btvms = new List<BultTestViewModel>();
BultTesterHeadViewModel bulkTester = new BultTesterHeadViewModel();
PremiumCalculator pc = new PremiumCalculator(_context);
String inLine;
StreamReader fs = new StreamReader(testFile.OpenReadStream());
int inx = 0;
try
{
for (inx = 0; (inLine = fs.ReadLine()) != null; inx++)
{
if (inx > 0)
{
string[] fields = inLine.Split(',');
BultTestViewModel btvm = new BultTestViewModel
{
ID = fields[0],
ProductName = fields[1],
PlanName = fields[2],
PlanType = fields[5],
Condition = fields[4],
Gender = fields[6],
familyString = fields[19],
Age = Int32.Parse(fields[7]),
Channel = fields[11],
Term = Int32.Parse(fields[12]),
SumInsured = Int32.Parse(fields[3])
};
decimal de;
Decimal.TryParse(fields[18], out de);
btvm.inputPremium = de;
if (btvm.PlanType == "FF") btvm.PlanType = "Family Floater";
if (btvm.Gender == "M") btvm.Gender = "Male";
else if (btvm.Gender == "F") btvm.Gender = "Female";
string[] conditions = fields[4].Split('&');
for (int i = 0; conditions != null && i < conditions.Length; i++)
{
switch (conditions[i].Trim())
{
case "Diabetes":
case "Diabetic":
btvm.Diabetes = true;
break;
case "Hypertension":
btvm.Hypertension = true;
break;
case "Hyperlipidemia":
case "Hyperlipidaemia":
btvm.Hyperlipidaemia = true;
break;
case "Asthma":
btvm.Asthma = true;
break;
}
}
if (btvm.familyString != null && btvm.familyString.Length > 0)
{
string[] fams = btvm.familyString.Split('+');
bool selfFound = false;
int ffNo = 0;
for (int i = 0; fams != null && i < fams.Length; i++)
{
string sFam = fams[i].Trim().ToLower();
if (sFam.Length > 1 && sFam.Substring(0, 3) == "kid") { sFam = "kid"; }
switch (sFam)
{
case "self":
selfFound = true;
ffNo++;
break;
case "spouse":
if (selfFound) btvm.Spouse = true;
ffNo++;
break;
case "father":
btvm.Father = true;
ffNo++;
break;
case "mother":
btvm.Mother = true;
ffNo++;
break;
case "fatherinlaw":
case "father-in-law":
btvm.FatherInLaw = true;
ffNo++;
break;
case "motherinlaw":
case "mother-in-law":
btvm.MotherInLaw = true;
ffNo++;
break;
case "kid":
btvm.Kids += 1;
break;
}
}
if (btvm.Kids > 0) ffNo++;
if (ffNo == 2 && ((btvm.Father && btvm.Mother) || (btvm.MotherInLaw && btvm.FatherInLaw)))
{
btvm.Spouse = false;
btvm.Father = false;
btvm.Mother = false;
btvm.FatherInLaw = false;
btvm.MotherInLaw = false;
btvm.Spouse = true;
}
}
switch (fields[9].Trim())
{
case "I":
btvm.Zone = 1;
break;
case "II":
btvm.Zone = 2;
break;
case "III":
btvm.Zone = 3;
break;
}
switch (fields[10].Trim())
{
case "Single":
btvm.RoomType = 1;
break;
case "Any":
btvm.RoomType = 4;
break;
case "Shared":
btvm.RoomType = 2;
break;
case "Economy":
btvm.RoomType = 3;
break;
}
if (btvm.Channel == "Direct") { btvm.Staff = true; }
int tInt = 0;
Int32.TryParse(fields[13], out tInt);
btvm.Deductible = tInt;
Int32.TryParse(fields[14], out tInt);
btvm.OPD = tInt;
Int32.TryParse(fields[15], out tInt);
btvm.HospitalCash = tInt;
if (fields[16] == "Yes") btvm.Maternity = true;
if (fields[17] == "Yes") btvm.PremiumWaiver = true;
getASinglePremium(btvm, pc);
bulkTester.TotalTests++;
if (btvm.TestPass) { bulkTester.TotalPass++; } else { bulkTester.TotalFail++; }
//if (!btvm.TestPass)
//{
bulkTester.bulkTest.Add(btvm);
//}
}
}
ViewData["Info"] = testFile.Name + ",Test Scenarios = " + inx + ",Length=" + testFile.Length;
}
catch (FormatException fe)
{
ViewData["Error"] = "Input File " + testFile.Name + " format error! -->" + fe.ToString();
bulkTester = null;
}
return View(bulkTester);
}
private void getASinglePremium(BultTestViewModel btvm, PremiumCalculator pc)
{
PremiumViewModel pvm = new PremiumViewModel();
pvm.ProductName = btvm.ProductName;
pvm.PlanName = btvm.PlanName;
pvm.PlanType = btvm.PlanType;
pvm.SumInsured = btvm.SumInsured;
pvm.Term = btvm.Term;
pvm.Age = btvm.Age;
pvm.Gender = btvm.Gender;
pvm.Diabetes = btvm.Diabetes;
pvm.Hyperlipidaemia = btvm.Hyperlipidaemia;
pvm.Hypertension = btvm.Hypertension;
pvm.Asthma = btvm.Asthma;
pvm.Spouse = btvm.Spouse;
pvm.Father = btvm.Father;
pvm.Mother = btvm.Mother;
pvm.FatherInLaw = btvm.FatherInLaw;
pvm.MotherInLaw = btvm.MotherInLaw;
pvm.Kids = btvm.Kids;
pvm.RoomType = btvm.RoomType;
pvm.Zone = btvm.Zone;
pvm.Channel = btvm.Channel;
pvm.Staff = btvm.Staff;
pvm.Deductible = btvm.Deductible;
pvm.OPD = btvm.OPD;
pvm.HospitalCash = btvm.HospitalCash;
pvm.Maternity = btvm.Maternity;
pvm.PremiumWaiver = btvm.PremiumWaiver;
pc.calculatePremium(pvm);
//PremiumCalc prem = null;
foreach (PremiumCalc prem in pvm.Premiums){
if(prem.name == "Total")
{
btvm.TotalPremium = prem;
}
}
btvm.Premiums = pvm.Premiums;
btvm.TestPass = System.Math.Round(btvm.TotalPremium.NetAmount, 2) == System.Math.Round(btvm.inputPremium, 2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SnowProCorp.ShipmentsWeb.Models;
namespace SnowProCorp.ShipmentsWeb.ViewModel
{
public class GenericPagingInfo<T>
{
public PagingInfo PagingInfo { get; set; }
public T Data { get; set; }
}
} |
using System;
//For MethodImpl
using System.Runtime.CompilerServices;
namespace Unicorn
{
enum RENDERTYPE
{
SOLID = 0,
TEXTURED
}
public class Graphics
{
// Native handle for this component
private IntPtr native_handle = IntPtr.Zero;
public bool isActive
{
get { return get_isActive_Internal(this.native_handle); }
set { set_isActive_Internal(this.native_handle, value); }
}
public bool renderEmission
{
get { return get_renderEmission_Internal(this.native_handle); }
set { set_renderEmission_Internal(this.native_handle, value); }
}
public Vector3 GetEmissiveColor()
{
return get_EmissiveColor_Internal(this.native_handle);
}
public void SetEmissiveColor(Vector3 val)
{
set_EmissiveColor_Internal(this.native_handle, val);
}
public float emissiveIntensity
{
get { return get_EmissiveIntensity_Internal(this.native_handle); }
set { set_EmissiveIntensity_Internal(this.native_handle, value); }
}
public float alpha
{
get { return get_Alpha_Internal(this.native_handle); }
set { set_Alpha_Internal(this.native_handle, value); }
}
public void AddModel(string file)
{
csAddModel(native_handle, file);
}
public void AddAlbedoTexture(string file)
{
csAddAlbedoTexture(native_handle, file);
}
public void AddNormalTexture(string file)
{
csAddNormalTexture(native_handle, file);
}
public void AddMetallicTexture(string file)
{
csAddMetallicTexture(native_handle, file);
}
public void AddRoughnessTexture(string file)
{
csAddRoughnessTexture(native_handle, file);
}
public void AddAOTexture(string file)
{
csAddAOTexture(native_handle, file);
}
public void AddSpecularTexture(string file)
{
csAddSpecularTexture(native_handle, file);
}
// Getter/Setter for isActive
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_isActive_Internal(IntPtr native_handle);
// Getter/Setter for isActive
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_isActive_Internal(IntPtr native_handle, bool val);
// Getter/Setter for render emission
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_renderEmission_Internal(IntPtr native_handle);
// Getter/Setter for render emission
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_renderEmission_Internal(IntPtr native_handle, bool val);
// Getter/Setter for emissive color
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 get_EmissiveColor_Internal(IntPtr native_handle);
// Getter/Setter for emissive color
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_EmissiveColor_Internal(IntPtr native_handle, Vector3 val);
// Getter/Setter for emission intensity
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_EmissiveIntensity_Internal(IntPtr native_handle);
// Getter/Setter for emission intensity
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_EmissiveIntensity_Internal(IntPtr native_handle, float val);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddModel(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddAlbedoTexture(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddNormalTexture(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddMetallicTexture(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddRoughnessTexture(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddAOTexture(IntPtr native_handle, string file);
// Graphics Functions
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void csAddSpecularTexture(IntPtr native_handle, string file);
// Getter/Setter for emission intensity
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_Alpha_Internal(IntPtr native_handle);
// Getter/Setter for emission intensity
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Alpha_Internal(IntPtr native_handle, float val);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
namespace WCFConsoleRest
{
class ErrorHandler : IErrorHandler
{
/// <summary>
/// The method that's get invoked if any unhandled exception raised in service
/// Here you can do what ever logic you would like to.
/// For example logging the exception details
/// Here the return value indicates that the exception was handled or not
/// Return true to stop exception propagation and system considers
/// that the exception was handled properly
/// else return false to abort the session
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
public bool HandleError(Exception error)
{
Console.WriteLine(error.Message);
return true;
}
/// <summary>
/// If you want to communicate the exception details to the service client
/// as proper fault message
/// here is the place to do it
/// If we want to suppress the communication about the exception,
/// set fault to null
/// </summary>
/// <param name="error"></param>
/// <param name="version"></param>
/// <param name="fault"></param>
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
Error e = new Error { Message = $"Exception caught at Service Application GlobalErrorHandler Method: {error.TargetSite.Name} Message: {error.Message}" };
fault = Message.CreateMessage(version, "", e, new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Error)));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
var httpResponseMessageproperty = new HttpResponseMessageProperty
{
StatusCode = System.Net.HttpStatusCode.PaymentRequired,
};
httpResponseMessageproperty.Headers[System.Net.HttpResponseHeader.ContentType] = "application/json";
fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponseMessageproperty);
}
}
}
|
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace ExpenseTracker.ViewModels
{
public class SettingsViewModel : INotifyPropertyChanged
{
// Model.DataQuery_Mod DataQuery;
public Model.DataQuery_Mod DataQuery;
private bool _IsBusy = false;
public bool IsBusy { get { return _IsBusy; } set { _IsBusy = value; OnPropertyChanged(nameof(IsBusy)); } }
private ObservableCollection<Users> _UsersInfo;
public ObservableCollection<Users> UsersInfo
{
get { return _UsersInfo; }
set
{
_UsersInfo = value;
OnPropertyChanged(nameof(UsersInfo));
}
}
private ObservableCollection<Exp_Inc_Category> _ExpenseCategoryInfo;
public ObservableCollection<Exp_Inc_Category> ExpenseCategoryInfo
{
get { return _ExpenseCategoryInfo; }
set
{
_ExpenseCategoryInfo = value;
OnPropertyChanged(nameof(ExpenseCategoryInfo));
}
}
private ObservableCollection<Exp_Inc_Category> _Categories;
public ObservableCollection<Exp_Inc_Category> Categories
{
get
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
DataQuery.expenseSelect = "SELECT * FROM [dbo].[ExpenseCategory]";
DataQuery.expenseWhere = "WHere User_ID = 40 or User_ID = " + Preferences.Get("ExpenseT_UserID", " -1");
_Categories = DataQuery.ExecuteAQuery<Exp_Inc_Category>();
}
else
{
DependencyService.Get<IToast>().Show("No Internet Connection.");
_Categories = new ObservableCollection<Exp_Inc_Category>();
}
return _Categories;
}
set { _Categories = value; }
}
private ObservableCollection<Exp_Inc_Category> _CategoriesI;
public ObservableCollection<Exp_Inc_Category> CategoriesI
{
get
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
DataQuery.expenseSelect = "SELECT * FROM [dbo].[IncomeCategory]";
DataQuery.expenseWhere = "WHere User_ID = 40 or User_ID = " + Preferences.Get("ExpenseT_UserID", " -1");
_Categories = DataQuery.ExecuteAQuery<Exp_Inc_Category>();
}
else
{
DependencyService.Get<IToast>().Show("No Internet Connection.");
_CategoriesI = new ObservableCollection<Exp_Inc_Category>();
}
return _CategoriesI;
}
set { _CategoriesI = value; }
}
public DateTime PickerStartDate {
get
{
var dat = DateTime.Now;
dat = dat.AddMonths(-1);
return Preferences.Get("start_date", dat);
}
set
{
if (value.ToString("d") == DateTime.Now.ToString("d"))
Preferences.Remove("start_date");
else
Preferences.Set("start_date", value);
OnPropertyChanged(nameof(PickerStartDate));
}
}
public DateTime PickerEndDate
{
get
{
var dat = DateTime.Now;
return Preferences.Get("end_date", dat);
}
set
{
if (value.ToString("d") == DateTime.Now.ToString("d"))
Preferences.Remove("end_date");
else
Preferences.Set("end_date", value);
OnPropertyChanged(nameof(PickerEndDate));
}
}
private string _CategoryName;
public string CategoryName
{
get { return _CategoryName; }
set
{
_CategoryName = value;
OnPropertyChanged(nameof(CategoryName));
}
}
private string _CategoryPicker;
public string CategoryPicker
{
get { return _CategoryPicker; }
set
{
_CategoryPicker = value;
OnPropertyChanged(nameof(CategoryPicker));
}
}
public int NumberTrans { get { return Preferences.Get("trans_num", 1000); } set { Preferences.Set("trans_num", value); OnPropertyChanged(nameof(NumberTrans)); } }
public SettingsViewModel()
{
DataQuery = new Model.DataQuery_Mod();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void token ( string strtok)
{
string str1;
string str2;
strtok.Split(str1, string str2, string str3, int n);
}
static void Main(string[] args)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineShopping
{
public class UserProfileDialog
{
}
}
|
using ComPC2MC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ovan_P1
{
class ComModule
{
ComPC dllCom = new ComPC();
MessageDialog messageDialog = new MessageDialog();
Constant constants = new Constant();
private string comport = "COM6";
private string strLog = "";
private string logPath = "";
private byte[] recvData = null;
private int nRepeat = 0;
private int[] paperBLdata = new int[5];
private bool bActive = false;
private Thread getDepositTh = null;
private bool bWithdraw = false;
private bool bPermit = true;
public int depositAmount = 0;
public int[] depositArr = new int[8];
private int orderTotalPrice = 0;
SaleScreen pSs = null;
public void Initialize( SaleScreen ss )
{
logPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
logPath += "\\";
dllCom.GetHexArray();
StartCommunication();
pSs = ss;
}
public void OrderChange(string orderPrice)
{
orderTotalPrice = int.Parse(orderPrice);
if (!bPermit && InitCommand())
PermitAndProhCommand(0x01, 0x01);
if (getDepositTh == null)
{
getDepositTh = new Thread(GetDepositStateThread);
getDepositTh.Start();
}
}
public void TicketRun(int iAmount)
{
if (getDepositTh != null)
{
getDepositTh.Abort();
getDepositTh = null;
}
if (iAmount <= 0) return;
if (!InitCommand()) return;
LogResult("SEND : ", "01-FE-02-00-00-02");
bool bstop = dllCom.SendReceivePermissionAndProhibition(0x00, 0x00);
if (bstop)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
bstop = false;
bstop = ReceivedDataAnalProc();
if (bstop)
{
GetDetailDepositStatus(0x01);
if (!bPermit)
WithdrawChangeAmount(iAmount);
}
}
else
MessageBox.Show(dllCom.GetErrorMessage());
}
public void OrderCancel(int iAmount = 0)
{
if (getDepositTh != null)
{
getDepositTh.Abort();
getDepositTh = null;
}
if (!InitCommand()) return;
bool bstop = dllCom.SendReceivePermissionAndProhibition(0x00, 0x00);
LogResult("SEND : ", "01-FE-02-00-00-02");
if (bstop)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
bstop = false;
bstop = ReceivedDataAnalProc();
if (bstop)
{
GetDetailDepositStatus(0x01);
if (!bPermit)
WithdrawRefund(iAmount);
}
}
else
MessageBox.Show(dllCom.GetErrorMessage());
}
private void GetDepositStateThread()
{
while (!bActive)
{
GetDetailDepositStatus(0x01);
Thread.Sleep(1000);
depositAmount = dllCom.moneyAmount;
depositArr = dllCom.balanceData;
Console.WriteLine(dllCom.moneyAmount.ToString());
pSs.SetDepositAmount(depositAmount);
}
}
private void StartCommunication()
{
if (!OpenComport())
return;
if (!InitCommand())
return;
if (!PermitAndProhCommand(0x01, 0x01))
return;
GetDetailDepositStatus(0x01);
}
private void SaveLogData()
{
string fileName = logPath + "log_Byte_Mode.txt";
try
{
// Check if file already exists. If yes, delete it.
if (File.Exists(fileName))
File.Delete(fileName);
// Create a new file
using (FileStream fs = File.Create(fileName))
{
Byte[] title = new UTF8Encoding(true).GetBytes(strLog);
fs.Write(title, 0, title.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
Console.WriteLine(s);
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
private bool OpenComport()
{
bool bexist = false;
List<string> allPorts = new List<String>();
allPorts = dllCom.GetAllPorts();
foreach (String portName in allPorts)
if (portName == "COM6")
{
bexist = true;
break;
}
if( !bexist )
{
MessageBox.Show("Please check comport and restart");
return false;
}
bool ret = false;
if (comport != "")
{
dllCom.OpenComport(comport);
ret = true;
}
else
MessageBox.Show("Select Comport!");
return ret;
}
private bool InitCommand()
{
LogResult("SEND : ", "00-FF-01-01-00");
bool bret = dllCom.SendReceiveInitData();
if (bret)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
bret = ReceivedDataAnalProc();
}
else
MessageBox.Show(dllCom.GetErrorMessage());
return bret;
}
private bool InitDataAnal(byte b)
{
bool ret = false;
if (b == 0x11)
ret = true;
else if (b == 0x22)
{
Thread.Sleep(2000);
ret = InitCommand();
}
else if (b == 0xDD)
ret = InitCommand();
else if (b == 0xEE)
{
REPEAT:
if (nRepeat < 5)
{
nRepeat++;
if (dllCom.SendResetCommand())
{
byte result = dllCom.ptReceiveData[3];
if (result == 0x11)
{
Thread.Sleep(5000);
ret = InitCommand();
}
else if (result == 0xDD)
goto REPEAT;
else if (result == 0xEE)
{
nRepeat = 5;
goto REPEAT;
}
}
}
else
GetErrorStatus(0x07, 0);
nRepeat = 0;
}
return ret;
}
private bool PermitAndProhCommand(byte b1, byte b2)
{
LogResult("SEND : ", "01-FE-02-01-01-02");
bool ret = false;
ret = dllCom.SendReceivePermissionAndProhibition(b1, b2);
if (ret)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
ret = ReceivedDataAnalProc();
}
else
MessageBox.Show(dllCom.GetErrorMessage());
return ret;
}
private bool PermitAndProhDataAnal(byte b1, byte b2)
{
bool ret = false;
if ((b1 == 0x11 && b2 == 0x11) || (b1 == 0x22 && b2 == 0x22))
{
if (b1 == 0x11 && b2 == 0x11) bPermit = true;
if (b1 == 0x22 && b2 == 0x22) bPermit = false;
ret = true;
}
else if (b1 == 0x55 && b2 == 0x55)
{
if (bPermit)
GetDetailDepositStatus(0x01);
else
GetDetailWithdrawStatus();
ret = true;
}
else if (b1 == 0xDD && b2 == 0xDD)
{
if (bPermit)
ret = PermitAndProhCommand(0x01, 0x01);
else
ret = PermitAndProhCommand(0x00, 0x00);
}
else if (b1 == 0xEE && b2 == 0xEE)
{
REPEAT:
if (nRepeat < 5)
{
nRepeat++;
if (dllCom.SendResetCommand())
{
byte result = dllCom.ptReceiveData[3];
if (result == 0x11)
{
Thread.Sleep(2000);
StartCommunication();
}
else if (result == 0xDD)
goto REPEAT;
else if (result == 0xEE)
{
nRepeat = 5;
goto REPEAT;
}
}
}
else
GetErrorStatus(0x07, 1);
nRepeat = 0;
}
return ret;
}
private void GetDetailDepositStatus(byte b)
{
byte byteStatus;
byte[] tt = new byte[5];
byteStatus = dllCom.GetDetailStatusData(b);
LogResult("SEND : ", dllCom.tempS);
LogResult("RECV : ", dllCom.GetbalanceByteData());
if (byteStatus == 0x22 || byteStatus == 0x11)
{
if (byteStatus == 0x22)
{
bPermit = false;
LogResult("Deposit Amount : ", dllCom.moneyAmount.ToString());
}
if (byteStatus == 0x11) bPermit = true;
}
else if (byteStatus == 0x33 || byteStatus == 0x44)
{
if (byteStatus == 0x44)
{
LogResult("Deposit Amount : ", dllCom.moneyAmount.ToString());
bWithdraw = false;
}
else bWithdraw = true;
bPermit = false;
}
else if (byteStatus == 0xDD)
{
Thread.Sleep(2000);
GetDetailDepositStatus(b);
}
else if (byteStatus == 0xEE)
GetErrorStatus(0x07, 2);
}
int withdrawAmount = 0;
int[] withdrawArr = new int[8];
private bool GetDetailWithdrawStatus()
{
bool ret = false;
byte byteStatus;
LogResult("SEND : ", "03-FC-01-02-03");
byteStatus = dllCom.GetDetailStatusData(0x02);
LogResult("RECV : ", dllCom.GetbalanceByteData());
LogResult("Withdraw Amount: ", dllCom.moneyAmount.ToString());
withdrawAmount = dllCom.moneyAmount;
withdrawArr = dllCom.balanceData;
if (byteStatus == 0x11 || byteStatus == 0x22)
{
ret = true;
if (byteStatus == 0x11) bPermit = true;
if (byteStatus == 0x22) bPermit = false;
}
else if (byteStatus == 0x33 || byteStatus == 0x44)
{
ret = true;
if (byteStatus == 0x33) bWithdraw = true;
if (byteStatus == 0x44) bWithdraw = false;
}
else if (byteStatus == 0xDD)
{
Thread.Sleep(1000);
ret = GetDetailWithdrawStatus();
}
else if (byteStatus == 0xEE)
{
GetErrorStatus(0x07, 3);
}
return ret;
}
private void WithdrawRefund(int amount)
{
int nWan = amount / 10000;
int nChon = (amount - 10000 * nWan) / 1000;
int nBak = (amount - 10000 * nWan - 1000 * nChon) / 100;
int nSib = (amount - 10000 * nWan - 1000 * nChon - 100 * nBak) / 10;
byte b1 = GetByteTwoInteger(dllCom.balanceData[0] + 5 * dllCom.balanceData[1], 1);
byte b2 = GetByteTwoInteger(2 * dllCom.balanceData[5] + 5 * dllCom.balanceData[6], dllCom.balanceData[2] + 5 * dllCom.balanceData[3]);
byte b3 = GetByteTwoInteger(0, dllCom.balanceData[7]);
byte bCnt = Convert.ToByte(dllCom.balanceData[4]);
GetCoinMeshBalanceData(0x02);
if (paperBLdata[1] == 0 || paperBLdata[2] == 0 || paperBLdata[3] == 0 || paperBLdata[4] == 0)
{
MessageBox.Show("Withdraw possible count is less.");
return;
}
bool bret = dllCom.SendReceiveWithdrawal(b1, b2, b3, bCnt);
LogResult("SEND: ", dllCom.tempS);
if (bret)
{
LogResult("RECV: ", dllCom.GetbalanceByteData());
bret = false;
bret = ReceivedDataAnalProc();
if (bret)
{
GetDetailWithdrawStatus();
if (!bWithdraw)
{
PermitAndProhCommand(0x01, 0x01);
GetDetailDepositStatus(0x01);
}
}
}
}
private void WithdrawChangeAmount(int amount)
{
int nWan = amount / 10000;
int nChon = (amount - 10000 * nWan) / 1000;
int nBak = (amount - 10000 * nWan - 1000 * nChon) / 100;
int nSib = (amount - 10000 * nWan - 1000 * nChon - 100 * nBak) / 10;
byte b1 = GetByteTwoInteger(nSib, 0);
byte b2 = GetByteTwoInteger(0, nBak);
byte b3 = GetByteTwoInteger(0, nWan);
byte bCnt = Convert.ToByte(nChon);
GetCoinMeshBalanceData(0x02);
if (paperBLdata[1] == 0 || paperBLdata[2] == 0 || paperBLdata[3] == 0 || paperBLdata[4] == 0)
{
MessageBox.Show("Withdraw possible count is less.");
return;
}
bool bret = dllCom.SendReceiveWithdrawal(b1, b2, b3, bCnt);
LogResult("SEND: ", dllCom.tempS);
if (bret)
{
LogResult("RECV: ", dllCom.GetbalanceByteData());
bret = false;
bret = ReceivedDataAnalProc();
if (bret)
{
GetDetailWithdrawStatus();
if (!bWithdraw)
{
PermitAndProhCommand(0x01, 0x01);
GetDetailDepositStatus(0x01);
}
}
}
}
private bool WithdrawalDataAnal(byte b)
{
bool ret = false;
if (b == 0x11) ret = true;
else if (b == 0x55)
ret = GetDetailWithdrawStatus();
else if (b == 0xDD)
MessageBox.Show("Please tap the button 発券 again.");
else
GetErrorStatus(0x07, 3);
return ret;
}
private byte GetByteTwoInteger(int val1, int val2)
{
byte ret = 0;
string s1 = Convert.ToString(val1, 2);
string s2 = Convert.ToString(val2, 2);
int[] bits1 = s1.PadLeft(4, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
int[] bits2 = s2.PadLeft(4, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
int[] newbit = new int[8];
Array.Copy(bits1, newbit, 4);
Array.Copy(bits2, 0, newbit, 4, 4);
string s = "";
for (int i = 0; i < 8; i++)
s += newbit[i].ToString();
byte[] bytes = new byte[1];
bytes[0] = Convert.ToByte(s, 2);
ret = bytes[0];
return ret;
}
private void LogResult(string str1, string str2)
{
strLog += Environment.NewLine;
strLog += str1 + str2;
SaveLogData();
}
private void LogErrorData(int nCase)
{
string strError = "";
if (nCase == 0)
{
strError = dllCom.GetErrorMessage();
LogResult("Init Reset Error: ", strError);
}
if (nCase == 1)
{
strError = dllCom.GetErrorMessage();
LogResult("Deposit Permission and Prohibition Error: ", strError);
}
if (nCase == 2)
{
strError = dllCom.GetErrorMessage();
LogResult("Withdrawal Error: ", strError);
}
if (nCase == 3)
{
strError = dllCom.GetErrorMessage();
LogResult("Balance state: ", strError);
}
}
private void GetPaperBalanceData(byte b)
{
for (int i = 0; i < 5; i++)
paperBLdata[i] = 0;
LogResult("SEND : ", "04-FB-01-01-00");
bool bret = dllCom.SendReceiveBalance(b);
if (bret)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
byte[] recv = dllCom.ptReceiveData;
if (recv[0] == 0x04)
{
if (recv[3] == 0x00)
for (int i = 0; i < 5; i++)
paperBLdata[i] = dllCom.HtoD(recv[i + 4]);
else if (recv[3] == 0xDD)
GetPaperBalanceData(b);
else if (recv[3] == 0xEE)
{
LogErrorData(3);
dllCom.GetErrorState(0x02);
LogResult(dllCom.GetBDErrorAnalResult(), "");
}
}
}
else
MessageBox.Show(dllCom.GetErrorMessage());
}
private void GetCoinMeshBalanceData(byte b)
{
for (int i = 0; i < 5; i++)
paperBLdata[i] = 0;
LogResult("SEND : ", "04-FB-01-02-03");
bool bret = dllCom.SendReceiveBalance(b);
if (bret)
{
LogResult("RECV : ", dllCom.GetbalanceByteData());
byte[] recv = dllCom.ptReceiveData;
if (recv[0] == 0x04)
{
if (recv[3] == 0x00)
for (int i = 0; i < 5; i++)
paperBLdata[i] = dllCom.HtoD(recv[i + 4]);
else if (recv[3] == 0xDD)
GetCoinMeshBalanceData(b);
else if (recv[3] == 0xEE)
{
LogErrorData(3);
dllCom.GetErrorState(0x04);
LogResult(dllCom.GetBDErrorAnalResult(), "");
}
}
}
else
MessageBox.Show(dllCom.GetErrorMessage());
}
private void GetErrorStatus(byte b, int obj)
{
LogErrorData(0);
dllCom.GetErrorState(b);
LogResult(dllCom.GetBVErrorAnalResult(), "");
LogResult(dllCom.GetBDErrorAnalResult(), "");
LogResult(dllCom.GetCMErrorAnalResult(), "");
if(obj == 0)
{
string errorMsg = constants.bankNoteErrorMsg;
}
if(obj == 1)
{
string errorMsg = constants.bankNoteErrorMsg;
}
if (obj == 2)
{
string errorMsg = constants.bankNoteDepositeErrorMsg + "\n購入金額 = " + orderTotalPrice.ToString() + "円\n入金金額 = " + depositAmount.ToString() + "円\n釣銭金額 = 0円 \n払出済み = 0円";
}
if (obj == 3)
{
int restPrice = depositAmount - orderTotalPrice;
string errorMsg = constants.bankNoteWithdrawErrorMsg + "\n購入金額 = " + orderTotalPrice.ToString() + "円\n入金金額 = " + depositAmount.ToString() + "円\n釣銭金額 = " + restPrice.ToString() + "円 \n払出済み = " + withdrawAmount + "円";
}
messageDialog.ShowErrorMessage(constants.systemErrorMsg, constants.systemSubErrorMsg);
//MessageBox.Show("Device Error. Please check error log data.");
}
private bool ReceivedDataAnalProc()
{
bool ret = false;
recvData = dllCom.ptReceiveData;
byte btManage = recvData[0];
switch (btManage)
{
case 0x00:
ret = InitDataAnal(recvData[3]);
break;
case 0x01:
ret = PermitAndProhDataAnal(recvData[3], recvData[4]);
break;
case 0x02:
ret = WithdrawalDataAnal(recvData[3]);
break;
case 0x03:
break;
case 0x04:
break;
case 0x05:
break;
}
return ret;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KPI.Model.EF;
namespace KPI.Model
{
public class KPIDbContext : DbContext
{
const String DefaultConnectionName = "KPIDbContext";
public KPIDbContext() : this(DefaultConnectionName)
{
}
public KPIDbContext(String sqlConnectionName) : base(String.Format("Name={0}", sqlConnectionName))
{
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<EF.KPI> KPIs { get; set; }
public DbSet<EF.KPILevel> KPILevels { get; set; }
public DbSet<Data> Datas { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Level> Levels { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Favourite> Favourites { get; set; }
public DbSet<SeenComment> SeenComments { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet <Resource> Resources { get; set; }
public DbSet <Permission> Permissions { get; set; }
public DbSet<Menu> Menus { get; set; }
public DbSet<Unit> Units { get; set; }
public DbSet<Revise> Revises { get; set; }
public DbSet<ActionPlan> ActionPlans { get; set; }
public DbSet <Notification> Notifications { get; set; }
public DbSet<ActionPlanDetail> ActionPlanDetails { get; set; }
public DbSet<NotificationDetail> NotificationDetails { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<ErrorMessage> ErrorMessages { get; set; }
public DbSet<Owner> Owners { get; set; }
public DbSet<Uploader> Uploaders { get; set; }
public DbSet<Manager> Managers { get; set; }
public DbSet<CategoryKPILevel> CategoryKPILevels { get; set; }
public DbSet<Sponsor> Sponsors { get; set; }
public DbSet<OCCategory> OCCategories { get; set; }
public DbSet<Participant> Participants { get; set; }
public DbSet<StateSendMail> StateSendMails { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<MenuLang> MenuLangs { get; set; }
public DbSet<LateOnUpLoad> LateOnUpLoads { get; set; }
protected override void OnModelCreating(DbModelBuilder builder)
{
//builder.Entity<IdentityUserRole>().HasKey(i => new { i.UserId, i.RoleId });
//builder.Entity<IdentityUserLogin>().HasKey(i => i.UserId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace problema_13
{
class Program
{
static void Main(string[] args)
{
//Sortare prin insertie. Implementati algoritmul de sortare <Insertion Sort>.
int n, i, k, j, aux;
Console.WriteLine(" Cate elemente va avea vectorul? ");
Console.Write(" n = ");
n = int.Parse(Console.ReadLine());
int[] v = new int[n];
for (i = 0; i < v.Length; i++)
{
Console.Write($" v [{i}] = ");
v[i] = int.Parse(Console.ReadLine());
}
for (i = 1; i < v.Length; i++)
{
for (k = i; k > 0 && v[k] < v[k - 1]; k--)
{
aux = v[k];
v[k] = v[k - 1];
v[k - 1] = aux;
}
}
Console.WriteLine(" Vectorul sortat este: ");
for (i = 0; i < v.Length; i++)
{
Console.Write($" {v[i]} ");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace Core
{
public class errorHelper
{
/// <summary>
/// 路径
/// </summary>
public static string url = "/errorHelper";
/// <summary>
/// 月数,可以不用注册码
/// </summary>
public static int month = 3;
/// <summary>
/// 从error.txt读取
/// </summary>
/// <returns>若返回1则永久,否则返回年月日字符串</returns>
public static string GetErrorDate()
{
string result = "";
string path = HttpContext.Current.Server.MapPath(url + "/error.txt");
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
result = sr.ReadToEnd();
}
return result == "38564" ? "1" : GetDate(result);
}
/// <summary>
/// 往error.txt写入
/// </summary>
/// <param name="inputString"></param>
public static void SetErrorText(string inputString)
{
string path = HttpContext.Current.Server.MapPath(url + "/error.txt");
using (StreamWriter sr = new StreamWriter(path, false, Encoding.Default))
{
sr.Write(inputString);
}
}
/// <summary>
/// 将乱序字符串转为年月日字符串
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static string GetDate(string number)
{
string year = number[3].ToString() + number[7].ToString() + number[11].ToString() + number[6].ToString();
string month = number[8].ToString() + number[9].ToString();
string day = number[4].ToString() + number[14].ToString();
string strdate = year + "-" + month + "-" + day;
return strdate;
}
/// <summary>
/// 获得机器硬件信息
/// </summary>
/// <returns></returns>
public static string getCPUCode_MAC()
{
string cpuInfo = "";//cpu序列号
string mac = ""; //获取网卡硬件地址
string HDid = ""; //获取硬盘ID
try
{
ManagementClass cimobject = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach (ManagementBaseObject managebaseobj in moc)
{
cpuInfo = managebaseobj.Properties["ProcessorId"].Value.ToString();
if (!cpuInfo.Equals(""))
{
break;
}
}
ManagementClass moc2 = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc3 = moc2.GetInstances();
foreach (ManagementObject mo in moc3)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString();
break;
}
}
ManagementClass mclass = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection mocole = mclass.GetInstances();
foreach (ManagementObject mo in mocole)
{
HDid = (string)mo.Properties["Model"].Value;
}
//cpuInfo += "+" + System.Guid.NewGuid().ToString();
//Method.AddnewSetting(Application.ExecutablePath, userid + "guidcode", userid + "#" + cpuInfo + "," + mac + "+" + HDid + "$");
}
catch
{
}
return (cpuInfo + mac + HDid).Replace(" ", "");
}
/// <summary>
/// 对硬件信息加密
/// </summary>
/// <param name="TextToHash"></param>
/// <returns></returns>
private static string HashTextMD5_ComputeHash(string TextToHash)
{
MD5CryptoServiceProvider md5;
byte[] bytValue;
byte[] bytHash;
md5 = new MD5CryptoServiceProvider();
bytValue = System.Text.Encoding.UTF8.GetBytes(TextToHash);
bytHash = md5.ComputeHash(bytValue);
md5.Clear();
return Convert.ToBase64String(bytHash);
}
/// <summary>
/// 判断是否注册
/// </summary>
/// <returns></returns>
public static bool ZhuCe()
{
string txtInfo = "";
string path = HttpContext.Current.Server.MapPath(url + "/info.txt");
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
txtInfo = sr.ReadToEnd();
}
string computerInfo = HashTextMD5_ComputeHash(getCPUCode_MAC());
if (txtInfo == computerInfo)
{
return true;
}
return false;
}
/// <summary>
/// 写入info.txt 注册码
/// </summary>
public static void SetInfo(string inputString)
{
string path = HttpContext.Current.Server.MapPath(url + "/info.txt");
using (StreamWriter sr = new StreamWriter(path, false, Encoding.Default))
{
sr.Write(inputString);
}
}
/// <summary>
/// 测试是否可以登录使用
/// </summary>
/// <returns></returns>
public static KeyValuePair<int, string> CanUse()
{
int status = 0;
string msg = "登陆失败,请重新尝试!错误代码:";
try
{
string strDate = GetErrorDate();
if (strDate != "1")
{
DateTime dtlimit = DateTime.Parse(strDate);
DateTime dtNow = DateTime.Now;
if (dtlimit < dtNow)
status = 3;
else
{
if (dtlimit > dtNow.AddMonths(month))
//判断注册码
if (!ZhuCe())
status = 2;
else
status = 1;
else
status = 1;
}
}
else
{
//判断注册码
if (!ZhuCe())
status = 2;
else
status = 1;
}
}
catch
{
status = 4;
}
return new KeyValuePair<int, string>(status, msg + status.ToString());
}
}
} |
using UnityEngine;
using System.Collections;
public enum characterType{none, player, enemy, npc};
[System.Serializable]
public class Defence{
public float weaponDefence = 1f;
public float magicDefence = 0f;
}
[System.Serializable]
public class Maxs {
public float maxHealth = 100f;
public float maxMana = 100f;
}
public class Character : MonoBehaviour {
public float health = 100f;
public float mana = 100f;
public float damage = 0f;
public Defence defence;
public characterType type;
public GameObject character;
public Maxs maxs;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using Model;
using Game.Network;
using Google.Protobuf;
using System.Net.Sockets;
namespace TestServer
{
class Program
{
static void Main(string[] args)
{
GameListener listener = new GameListener(10);
listener.AcceptCompleted += AcceptCompleted;
listener.ReceiveCompleted += ReceiveCompleted;
listener.DisconnectCompleted += DisconnectCompleted;
listener.Start(6650);
Console.ReadKey();
}
private static void DisconnectCompleted(object sender, SocketAsyncEventArgs e)
{
Console.WriteLine("客户端断开:" + e.SocketError);
}
private static void ReceiveCompleted(object sender, byte[] message)
{
Message msg = new Message();
msg.MergeFrom(message);
Console.WriteLine("receive:" + msg.ToString());
token.SendAsync(msg.ToByteArray());
}
private static UserToken token;
private static void AcceptCompleted(object sender, SocketAsyncEventArgs e)
{
Console.WriteLine("客户端连接");
token = e.UserToken as UserToken;
}
}
}
|
namespace _03.CorrectBrackets
{
using System;
using System.Linq;
using System.Collections.Generic;
/*
Write a program to check if in a given expression the brackets are put correctly.
Example of correct expression: ((a+b)/5-d). Example of incorrect expression: )(a+b))*/
class CorrectBrackets
{
static void Main()
{
string expression = "((a+b)/5-d)";
Console.WriteLine(BrecketsCheck(expression));
}
static bool BrecketsCheck(string expression)
{
var leftBrecketsPositions = new Queue<int>();
var rightBracketsPositions = new Queue<int>();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '(')
{
leftBrecketsPositions.Enqueue(i);
}
if (expression[i] == ')')
{
rightBracketsPositions.Enqueue(i);
}
}
if (leftBrecketsPositions.Count != rightBracketsPositions.Count)
{
return false;
}
while (leftBrecketsPositions.Count != 0)
{
if (leftBrecketsPositions.Dequeue() < rightBracketsPositions.Dequeue())
{
continue;
}
else
{
return false;
}
}
return true;
}
}
}
|
namespace E16_Groups
{
using System;
using System.Linq;
using E09_StudentGroups;
public class Groups
{
public static void Main(string[] args)
{
// Create a class Group with properties GroupNumber and DepartmentName.
// Introduce a property GroupNumber in the Student class.
// Extract all students from "Mathematics" department.
// Use the Join operator.
Console.WriteLine("Homework 16:");
Console.WriteLine();
var GroupMathematics =
from student in StudentsList.students
join grp in StudentsList.groups on student.GroupNumber equals grp.GroupNumber
where grp.DepartmentName == "Mathematics"
select student;
StudentsList.PrintList(GroupMathematics);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Model
{
public class Partido
{
public int Id { get; set; }
public int EquipoLocalId { get; set; }
public int EquipoVisitanteId { get; set; }
public int? ResultadoEquipoLocal { get; set; }
public int? ResultadoEquipoVisitante { get; set; }
public bool MostrarResultados { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using TLF.Framework.Config;
using TLF.Framework.BaseFrame;
using DevExpress.Utils;
namespace TLF.Framework.ControlLibrary
{
public partial class PChkSpn : DevExpress.XtraEditors.XtraUserControl
{
public PChkSpn()
{
InitializeComponent();
}
#region :: 전역변수 ::
private bool _enableClear = false;
private bool _checkModify = false;
private bool _enterKeySelectEvent = false;
private bool _IsPeriod = true;
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Properties
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: EnableClear :: 일괄 초기화 여부를 설정합니다.
/// <summary>
/// 일괄 초기화 여부를 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("일괄 초기화 여부를 설정합니다."), Browsable(true)]
public bool EnableClear
{
get { return _enableClear; }
set
{
_enableClear = value;
Tag = _enableClear ? AppConfig.CLEARTAG : null;
}
}
#endregion
#region :: CheckModify :: EditValue의 변경 Check 여부를 설정합니다.
/// <summary>
/// EditValue의 변경 Check 여부를 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("EditValue의 변경 Check 여부를 설정합니다."), Browsable(true)]
public bool CheckModify
{
get { return _checkModify; }
set { _checkModify = value; }
}
#endregion
#region :: EditValue :: 시작 EditValue값을 설정 및 가져옵니다.
/// <summary>
/// 시작 EditValue값을 설정 및 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("시작 EditValue값을 설정 및 가져옵니다."), Browsable(true)]
public object EditValue
{
get { return chk.Checked ? SpnFrom.EditValue : null; }
set { SpnFrom.EditValue = value; }
}
#endregion
#region :: EditValue :: 시작 EditValue값을 설정 및 가져옵니다.
/// <summary>
/// 시작 EditValue값을 설정 및 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("시작 EditValue값을 설정 및 가져옵니다."), Browsable(true)]
public object EditValueFrom
{
get { return chk.Checked ? SpnFrom.EditValue : null; }
set { SpnFrom.EditValue = value; }
}
#endregion
#region :: EditValueTo :: 만료 EditValue값을 설정 및 가져옵니다.
/// <summary>
/// 만료 EditValue값을 설정 및 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("만료 EditValue값을 설정 및 가져옵니다."), Browsable(true)]
public object EditValueTo
{
get { return chk.Checked ? SpnTo.EditValue : null; }
set { SpnTo.EditValue = value; }
}
#endregion
#region :: Checked :: EditValue의 사용 여부를 설정합니다.
/// <summary>
/// EditValue의 사용 여부를 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("EditValue의 사용 여부를 설정합니다."), Browsable(true)]
public bool Checked
{
get { return chk.Checked; }
set { chk.Checked = value; }
}
#endregion
#region :: Label :: Label을 설정 또는 가져옵니다.
/// <summary>
/// Label을 설정 또는 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("Label을 설정 또는 가져옵니다."), Browsable(true)]
public string Label
{
get { return chk.Text; }
set { chk.Text = value; }
}
#endregion
#region :: Label :: Label 넓이를 설정 또는 가져옵니다.
/// <summary>
/// Label 넓이를 설정 또는 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("Label 넓이를 설정 또는 가져옵니다."), Browsable(true)]
public int LabelWidth
{
get { return chk.Width; }
set { chk.Width = value; }
}
#endregion
#region :: IsPeriod :: 기간 입력유무를 설정 또는 가져옵니다.
/// <summary>
/// 기간 입력유무를 설정 또는 가져옵니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("기간 입력유무를 설정 또는 가져옵니다."), Browsable(true)]
public bool IsPeriod
{
get { return _IsPeriod; }
set
{
_IsPeriod = value;
if (_IsPeriod)
{
tableLayoutPanel1.ColumnStyles[1].SizeType = System.Windows.Forms.SizeType.Percent;
tableLayoutPanel1.ColumnStyles[1].Width = 50F;
tableLayoutPanel1.ColumnStyles[2].Width = 10F;
tableLayoutPanel1.ColumnStyles[3].SizeType = System.Windows.Forms.SizeType.Percent;
tableLayoutPanel1.ColumnStyles[3].Width = 50F;
}
else
{
tableLayoutPanel1.ColumnStyles[1].SizeType = System.Windows.Forms.SizeType.Percent;
tableLayoutPanel1.ColumnStyles[1].Width = 100F;
tableLayoutPanel1.ColumnStyles[2].Width = 0F;
tableLayoutPanel1.ColumnStyles[3].Width = 0F;
}
}
}
#endregion
#region :: EnterKeySelectEvent :: Enter Key를 누르면 조회 이벤트를 발생시킬지 여부를 설정합니다.
/// <summary>
/// Enter Key를 누르면 조회 이벤트를 발생시킬지 여부를 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("Enter Key를 누르면 조회 이벤트를 발생시킬지 여부를 설정합니다."), Browsable(true)]
public bool EnterKeySelectEvent
{
get { return _enterKeySelectEvent; }
set
{
_enterKeySelectEvent = value;
}
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Method(Public)
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: SetSuperToolTip :: ToolTip을 설정합니다.
/// <summary>
/// ToolTip을 설정합니다.
/// </summary>
/// <param name="title"></param>
/// <param name="contents"></param>
public void SetSuperToolTip(string title, string contents)
{
SuperToolTip sTip = new SuperToolTip();
ToolTipTitleItem tTitle = new ToolTipTitleItem();
ToolTipItem tContents = new ToolTipItem();
tTitle.Text = title;
tContents.Text = contents;
tContents.LeftIndent = 6;
sTip.Items.Add(tTitle);
sTip.Items.Add(tContents); SpnFrom.SuperTip = sTip;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Override(Event, Properties, Method...)
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: OnKeyDown :: Enter Key를 입력하면 조회 이벤트를 실행합니다.
/// <summary>
/// Enter Key를 입력하면 조회 이벤트를 실행합니다.
/// </summary>
/// <param name="e"></param>
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
{
base.OnKeyDown(e);
if (!_enterKeySelectEvent || e.KeyCode != System.Windows.Forms.Keys.Enter) return;
(FindForm() as UIFrame).OnSelectionEvent();
}
#endregion
#region :: OnLostFocus :: Focus를 잃을 때 현재값과 이전값을 비교한다.
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
if (_checkModify)
{
if (SpnFrom.IsModified)
{
(FindForm() as UIFrame).IsModified = true;
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
namespace OCP.Comments
{
/**
* Interface IComment
*
* This class represents a comment
*
* @package OCP\Comments
* @since 9.0.0
*/
public interface IComment {
// const int MAX_MESSAGE_LENGTH = 1000;
/**
* returns the ID of the comment
*
* It may return an empty string, if the comment was not stored.
* It is expected that the concrete Comment implementation gives an ID
* by itself (e.g. after saving).
*
* @return string
* @since 9.0.0
*/
string getId();
/**
* sets the ID of the comment and returns itself
*
* It is only allowed to set the ID only, if the current id is an empty
* string (which means it is not stored in a database, storage or whatever
* the concrete implementation does), or vice versa. Changing a given ID is
* not permitted and must result in an IllegalIDChangeException.
*
* @param string id
* @return IComment
* @throws IllegalIDChangeException
* @since 9.0.0
*/
IComment setId(string id);
/**
* returns the parent ID of the comment
*
* @return string
* @since 9.0.0
*/
string getParentId();
/**
* sets the parent ID and returns itself
* @param string parentId
* @return IComment
* @since 9.0.0
*/
IComment setParentId(string parentId);
/**
* returns the topmost parent ID of the comment
*
* @return string
* @since 9.0.0
*/
string getTopmostParentId();
/**
* sets the topmost parent ID and returns itself
*
* @param string id
* @return IComment
* @since 9.0.0
*/
IComment setTopmostParentId(string id);
/**
* returns the number of children
*
* @return int
* @since 9.0.0
*/
int getChildrenCount();
/**
* sets the number of children
*
* @param int count
* @return IComment
* @since 9.0.0
*/
IComment setChildrenCount(int count);
/**
* returns the message of the comment
*
* @return string
* @since 9.0.0
*/
string getMessage();
/**
* sets the message of the comment and returns itself
*
* When the given message length exceeds MAX_MESSAGE_LENGTH an
* MessageTooLongException shall be thrown.
*
* @param string message
* @return IComment
* @throws MessageTooLongException
* @since 9.0.0
*/
IComment setMessage(string message);
/**
* returns an array containing mentions that are included in the comment
*
* @return array each mention provides a 'type' and an 'id', see example below
* @since 11.0.0
*
* The return array looks like:
* [
* [
* 'type' => 'user',
* 'id' => 'citizen4'
* ],
* [
* 'type' => 'group',
* 'id' => 'media'
* ],
* …
* ]
*
*/
IList<string> getMentions();
/**
* returns the verb of the comment
*
* @return string
* @since 9.0.0
*/
string getVerb();
/**
* sets the verb of the comment, e.g. 'comment' or 'like'
*
* @param string verb
* @return IComment
* @since 9.0.0
*/
IComment setVerb(string verb);
/**
* returns the actor type
*
* @return string
* @since 9.0.0
*/
string getActorType();
/**
* returns the actor ID
*
* @return string
* @since 9.0.0
*/
string getActorId();
/**
* sets (overwrites) the actor type and id
*
* @param string actorType e.g. 'users'
* @param string actorId e.g. 'zombie234'
* @return IComment
* @since 9.0.0
*/
IComment setActor(string actorType, string actorId);
/**
* returns the creation date of the comment.
*
* If not explicitly set, it shall default to the time of initialization.
*
* @return \DateTime
* @since 9.0.0
*/
DateTime getCreationDateTime();
/**
* sets the creation date of the comment and returns itself
*
* @param \DateTime dateTime
* @return IComment
* @since 9.0.0
*/
IComment setCreationDateTime(DateTime dateTime);
/**
* returns the date of the most recent child
*
* @return \DateTime
* @since 9.0.0
*/
DateTime getLatestChildDateTime();
/**
* sets the date of the most recent child
*
* @param \DateTime dateTime
* @return IComment
* @since 9.0.0
*/
IComment setLatestChildDateTime(DateTime dateTime);
/**
* returns the object type the comment is attached to
*
* @return string
* @since 9.0.0
*/
string getObjectType();
/**
* returns the object id the comment is attached to
*
* @return string
* @since 9.0.0
*/
string getObjectId();
/**
* sets (overwrites) the object of the comment
*
* @param string objectType e.g. 'files'
* @param string objectId e.g. '16435'
* @return IComment
* @since 9.0.0
*/
IComment setObject(string objectType, string objectId);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SMSEntities.SMSDBEntities
{
public class Passes
{
//`PassId``PassName``PassStatus``VisitortypeId`
public int PassId { get; set; }
public string PassName { get; set; }
public string PassStatus { get; set; }
public int VisitortypeId { get; set; }
public int DeploymentId { get; set; }
}
}
|
/*
This file is part of SharpPcap.
SharpPcap is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SharpPcap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2005 Tamir Gal <tamir@tamirgal.com>
* Copyright 2008-2009 Chris Morgan <chmorgan@gmail.com>
* Copyright 2008-2009 Phillip Lemon <lucidcomms@gmail.com>
*/
using System;
using System.IO;
using System.Text;
namespace SharpPcap
{
/// <summary>
/// Capture packets from an offline pcap file
/// </summary>
public class PcapOfflineDevice : PcapDevice
{
private string m_pcapFile;
/// <summary>
/// The description of this device
/// </summary>
private const string PCAP_OFFLINE_DESCRIPTION
= "Offline pcap file";
/// <summary>
/// Constructs a new offline device for reading
/// pcap files
/// </summary>
/// <param name="pcapFile"></param>
public PcapOfflineDevice(string pcapFile)
{
m_pcapFile = pcapFile;
}
public override string Name
{
get
{
return m_pcapFile;
}
}
public override string Description
{
get
{
return PCAP_OFFLINE_DESCRIPTION;
}
}
public long FileSize
{
get
{
return new FileInfo(Name).Length;
}
}
/// <summary>
/// The underlying pcap file name
/// </summary>
public string FileName
{
get { return System.IO.Path.GetFileName(this.Name); }
}
/// <summary>
/// Opens the device for capture
/// </summary>
public override void Open()
{
//holds errors
StringBuilder errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
//opens offline pcap file
IntPtr adapterHandle = SafeNativeMethods.pcap_open_offline(this.Name, errbuf);
//handle error
if (adapterHandle == IntPtr.Zero)
{
string err = "Unable to open offline adapter: " + errbuf.ToString();
throw new Exception(err);
}
//set the local handle
this.PcapHandle = adapterHandle;
}
/// <summary>
/// Opens the device for capture
/// </summary>
/// <param name="promiscuous_mode">This parameter
/// has no affect on this method since it's an
/// offline device</param>
public override void Open(bool promiscuous_mode)
{
this.Open();
}
/// <summary>
/// Opens the device for capture
/// </summary>
/// <param name="promiscuous_mode">This parameter
/// has no affect on this method since it's an
/// offline device</param>
/// <param name="read_timeout">This parameter
/// has no affect on this method since it's an
/// offline device</param>
public override void Open(bool promiscuous_mode, int read_timeout)
{
this.Open();
}
/// <summary>
/// Setting a capture filter on this offline device is not supported
/// </summary>
public override void SetFilter(string filter)
{
throw new PcapException("It is not possible to set a capture filter on an offline device");
}
/// <summary>
/// Statistics are not supported for savefiles
/// </summary>
/// <returns>
/// A <see cref="PcapStatistics"/>
/// </returns>
public override PcapStatistics Statistics()
{
throw new PcapException("No statistics are stored in savefiles");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace TicketSellingServer
{
/// <summary>
/// Adapts the service with the logic
/// </summary>
class TicketSellingQueryService: ITicketSellingQueryService
{
public Flights GetFlights(FlightQuery flightQuery)
{
Flights fs;
try
{
fs = TicketSellingQueryLogic.Instance.GetFlights(flightQuery);
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
return fs;
}
public int MakeReservation(FlightSearchReservationRequest request)
{
int resID;
try
{
resID = TicketSellingQueryLogic.Instance.MakeReservation(request);
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
return resID;
}
public void CancelReservation(int reservationID)
{
try
{
TicketSellingQueryLogic.Instance.CancelReservation(reservationID);
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
}
}
}
|
//Write a program that removes from given sequence all negative numbers.
namespace _05.AllNegativeNumberRemove
{
using System;
using System.Collections.Generic;
using System.Linq;
class AllNegativeNumberRemove
{
static void Main()
{
List<int> sequence = new List<int>() {1,-4,22,-13,-11,2,0,88,-192 };
List<int> newSequence = new List<int>();
for (int i = 0; i < sequence.Count; i++)
{
if (sequence[i] >= 0)
{
newSequence.Add(sequence[i]);
}
}
sequence = newSequence;
Console.WriteLine(string.Join(", ",sequence));
}
}
}
|
using System;
namespace CompressionStocking
{
public class StockingCtrl : IStockingCtrl
{
private ICompressionCtrl _compression_device;
private bool _relaxed = true;
public StockingCtrl(ICompressionCtrl compression_device)
{
_compression_device = compression_device;
}
public void start_compressing()
{
if (_relaxed)
{
_compression_device.compress();
}
}
public void start_decompressing()
{
if (!_relaxed)
{
_compression_device.decompress();
}
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Web.UI;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
namespace DotNetNuke.Web.Razor
{
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public class RazorModuleControlFactory : BaseModuleControlFactory
{
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc)
{
return new RazorHostControl("~/" + controlSrc);
}
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
{
return CreateControl(containerControl, String.Empty, moduleConfiguration.ModuleControl.ControlSrc);
}
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc)
{
return CreateControl(containerControl, String.Empty, controlSrc);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeJam.Google.Milkshakes
{
public class Milkshakes : ICodeJamStrategy
{
//private static bool isSatisfied = false;
private static string fileName = "B-small-practice";
private static int caseDataLength = 2;
private static string caseDependentDataLines = "2";
static void Main(string[] args)
{
new Skeleton(new Milkshakes(), fileName + ".in", fileName + ".out", caseDataLength, caseDependentDataLines).Execute().DisplayUnMatchedResult();
Console.ReadKey(true);
}
public string Solve(List<string> caseData)
{
var numberOfShakes = int.Parse(caseData[0]);
caseData.RemoveAt(0);
var customersCount = int.Parse(caseData[0]);
caseData.RemoveAt(0);
if (numberOfShakes < customersCount)
{
return "IMPOSSIBLE";
}
var customerShakesLikingDict = GetCustomerLiking(caseData);
var shakeList = MakeShakes(customerShakesLikingDict, numberOfShakes, customersCount);
return GetResultString(shakeList, numberOfShakes);
}
private string GetResultString(List<KeyValuePair<int, int>> shakeList, int numberOfShakes)
{
string result = "IMPOSSIBLE";
if (shakeList.Count != numberOfShakes)
{
return result;
}
result = string.Empty;
for (int i = 1; i <= numberOfShakes; i++)
{
result += shakeList.First(rs => rs.Key == i).Value + " ";
}
return result.Trim();
}
private List<KeyValuePair<int, int>> MakeShakes(Dictionary<int, List<KeyValuePair<int, int>>> customerShakesLikingDict, int numberOfShakes, int customersCount)
{
List<KeyValuePair<int, int>> resultSet = new List<KeyValuePair<int, int>>();
//isSatisfied = false;
int firstCustomer = 0;
foreach (var shakeLiked in customerShakesLikingDict[firstCustomer])
{
resultSet.Add(new KeyValuePair<int, int>(shakeLiked.Key, shakeLiked.Value));
if (TryMakeShake(resultSet, customerShakesLikingDict, firstCustomer + 1))
{
//isSatisfied = true;
return MakeRemainingShakesUnmalted(resultSet, numberOfShakes);
}
resultSet = new List<KeyValuePair<int, int>>();
}
return resultSet;
}
private List<KeyValuePair<int, int>> MakeRemainingShakesUnmalted(List<KeyValuePair<int, int>> resultSet, int numberOfShakes)
{
for (int i = 1; i <= numberOfShakes; i++)
{
if (resultSet.Any(sl => sl.Key == i))
{
continue;
}
resultSet.Add(new KeyValuePair<int, int>(i, 0));
}
return resultSet;
}
private bool TryMakeShake(List<KeyValuePair<int, int>> resultSet, Dictionary<int, List<KeyValuePair<int, int>>> customerShakesLikingDict, int customerIndex)
{
if (customerIndex == customerShakesLikingDict.Count)
{
return true;
}
List<KeyValuePair<int, int>> myResultSet = new List<KeyValuePair<int, int>>(resultSet);
foreach (var shakeLiked in customerShakesLikingDict[customerIndex])
{
if (myResultSet.Any(rs => rs.Key == shakeLiked.Key) || (shakeLiked.Value == 1 && myResultSet.Any(rs => rs.Value == 1)))
{
continue;
}
myResultSet.Add(new KeyValuePair<int, int>(shakeLiked.Key, shakeLiked.Value));
if (TryMakeShake(myResultSet, customerShakesLikingDict, customerIndex + 1))
{
Console.WriteLine("Customer : " + customerIndex + " gets Shake : " + shakeLiked.Key);
resultSet.Add(new KeyValuePair<int, int>(shakeLiked.Key, shakeLiked.Value));
return true;
}
myResultSet = new List<KeyValuePair<int, int>>(resultSet);
}
return false;
}
private Dictionary<int, List<KeyValuePair<int, int>>> GetCustomerLiking(List<string> caseData)
{
var dict = new Dictionary<int, List<KeyValuePair<int, int>>>();
var customerRph = 0;
caseData.Sort((d1, d2) => d1.Length.CompareTo(d2.Length));
foreach (var data in caseData)
{
var customerData = data.Split(' ').ToList();
var shakesLikedCount = int.Parse(customerData[0]);
var shakesLikedList = new List<KeyValuePair<int, int>>();
for (int i = 1; i <= shakesLikedCount; i++)
{
shakesLikedList.Add(new KeyValuePair<int, int>(int.Parse(customerData[2 * i - 1]), int.Parse(customerData[2 * i])));
}
shakesLikedList.Sort((pair, valuePair) => pair.Value.CompareTo(valuePair.Value));
dict.Add(customerRph, shakesLikedList);
customerRph++;
}
return dict;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GroundChecker : MonoBehaviour
{
[Header("Results")]
public float groundSlopeAngle = 0f; // Angle of the slope in degrees
public Vector3 groundSlopeDir = Vector3.zero; // The calculated slope as a vector
[Header("Settings")]
public LayerMask castingMask; // Layer mask for casts. You'll want to ignore the player.
public bool showDebug;
public float startDistanceFromBottom = 0.2f; // Should probably be higher than skin width
public float sphereCastRadius = 0.25f;
public float sphereCastDistance = 0.75f; // How far spherecast moves down from origin point
public float raycastLength = 0.75f;
public Vector3 rayOriginOffset1 = new Vector3(-0.2f, 0f, 0.16f);
public Vector3 rayOriginOffset2 = new Vector3(0.2f, 0f, -0.16f);
/// <summary>
/// Checks for ground underneath, to determine some info about it, including the slope angle.
/// </summary>
/// <param name="origin">Point to start checking downwards from</param>
public void CheckGround(Vector3 origin)
{
// Out hit point from our cast(s)
RaycastHit hit;
// SPHERECAST
// "Casts a sphere along a ray and returns detailed information on what was hit."
if (Physics.SphereCast(origin, sphereCastRadius, Vector3.down, out hit, sphereCastDistance, castingMask))
{
// Angle of our slope (between these two vectors).
// A hit normal is at a 90 degree angle from the surface that is collided with (at the point of collision).
// e.g. On a flat surface, both vectors are facing straight up, so the angle is 0.
groundSlopeAngle = Vector3.Angle(hit.normal, Vector3.up);
// Find the vector that represents our slope as well.
// temp: basically, finds vector moving across hit surface
Vector3 temp = Vector3.Cross(hit.normal, Vector3.down);
// Now use this vector and the hit normal, to find the other vector moving up and down the hit surface
groundSlopeDir = Vector3.Cross(temp, hit.normal);
}
// Now that's all fine and dandy, but on edges, corners, etc, we get angle values that we don't want.
// To correct for this, let's do some raycasts. You could do more raycasts, and check for more
// edge cases here. There are lots of situations that could pop up, so test and see what gives you trouble.
RaycastHit slopeHit1;
RaycastHit slopeHit2;
// FIRST RAYCAST
if (Physics.Raycast(origin + rayOriginOffset1, Vector3.down, out slopeHit1, raycastLength))
{
if (showDebug) { Debug.DrawLine(origin + rayOriginOffset1, slopeHit1.point, Color.red); }
// Get angle of slope on hit normal
float angleOne = Vector3.Angle(slopeHit1.normal, Vector3.up);
// 2ND RAYCAST
if (Physics.Raycast(origin + rayOriginOffset2, Vector3.down, out slopeHit2, raycastLength))
{
// Debug line to second hit point
Debug.DrawLine(origin + rayOriginOffset2, slopeHit2.point, Color.red);
// Get angle of slope of these two hit points.
float angleTwo = Vector3.Angle(slopeHit2.normal, Vector3.up);
// 3 collision points: Take the MEDIAN by sorting array and grabbing middle.
float[] tempArray = new float[] { groundSlopeAngle, angleOne, angleTwo };
Array.Sort(tempArray);
groundSlopeAngle = tempArray[1];
}
else
{
// 2 collision points (sphere and first raycast): AVERAGE the two
float average = (groundSlopeAngle + angleOne) / 2;
groundSlopeAngle = average;
}
}
if(groundSlopeAngle == 0){
groundSlopeDir = Vector3.zero;
}
}
void OnDrawGizmos()
{
if (showDebug)
{
// Visualize SphereCast with two spheres and a line
Vector3 startPoint = new Vector3(transform.position.x, transform.position.y - (2 / 2) + startDistanceFromBottom, transform.position.z);
Vector3 endPoint = new Vector3(transform.position.x, transform.position.y - (2 / 2) + startDistanceFromBottom - sphereCastDistance, transform.position.z);
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(startPoint, sphereCastRadius);
Gizmos.color = Color.gray;
Gizmos.DrawWireSphere(endPoint, sphereCastRadius);
Gizmos.DrawLine(startPoint, endPoint);
}
}
}
|
using DEMO_DDD.DOMAIN.Entidades;
using DEMO_DDD.DOMAIN.Interfaces.Repositories;
using DEMO_DDD.INFRA.DATA.Contexto;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DEMO_DDD.INFRA.DATA.Repositories
{
public class ClienteRepository : RepositoryBase<Cliente>, IClienteRepository
{
public ClienteRepository(DemoDDDContext context) : base(context)
{
}
public async Task<IEnumerable<Cliente>> ObterClientesProdutos()
{
return await _context.Clientes.AsNoTracking().Include(c => c.Produtos).ToListAsync();
}
public async Task<Produto> ObterProdutosPorCliente(int id)
{
return await _context.Produtos.AsNoTracking().Include(c => c.Cliente).FirstOrDefaultAsync(c => c.Id == id);
}
}
}
|
using CheckMySymptoms.Forms.View;
using System;
using System.Collections.Generic;
using System.Text;
namespace CheckMySymptoms.Flow.Cache
{
public class ViewFieldsListPair
{
public ViewBase View { get; set; }
public object Fields { get; set; }
}
}
|
namespace Service
{
/// <summary>
/// Represents the response to a query.
/// </summary>
public interface IQueryResponse
{
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Autofac;
using Caliburn.Micro;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.Impl.DbImpl;
namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels
{
public class Tmp
{
public Tmp(String str)
{
tmpName = str;
}
public String tmpName { get; private set; }
}
public class MainViewModel : PropertyChangedBase
{
private IWindowManager _vm;
private IContainer _container;
public BindableCollection<Tmp> tmp { get; private set; }
public MainViewModel(ICrudService<WorkerJobCategory> wCrudServiceBase, IWindowManager vm, IContainer container)
{
_vm = vm;
_container = container;
tmp = new BindableCollection<Tmp>();
tmp.Add(new Tmp("koksidgsdfg"));
tmp.Add(new Tmp("koksi2342dgsdfg"));
tmp.Add(new Tmp("koksidgSSDFSDFsdfg"));
tmp.Add(new Tmp("kok22sidgsdfg"));
tmp.Add(new Tmp("ksidgsdfg"));
tmp.Add(new Tmp("ksidsdsgsdfg"));
//IQueryable<WorkerJobCategory> collection = wCrudServiceBase.All;
//T = new BuildingAttributeViewModel(_container.Resolve<ICrudService<BuildingAttribute>>().GetById(1));
}
public void Run()
{
_vm.ShowWindow(new SiteControlViewModel(_container));
}
}
}
|
using FluentValidation;
namespace Application.Users.Commands.RegisterUserCommands {
public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand> {
public RegisterUserCommandValidator () {
RuleFor (e => e.Name)
.NotEmpty ().WithMessage ("Name is Required")
.NotNull ().WithMessage ("Name is Required");
RuleFor (e => e.Email)
.NotEmpty ().WithMessage ("User Email is Required")
.NotNull ().WithMessage ("User Email is Required");
RuleFor (e => e.Password)
.NotEmpty ().WithMessage ("User Password is Required")
.NotNull ().WithMessage ("User Password is Required");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Runtime.Serialization;
using Sunny.Lib.Extension;
namespace Sunny.Lib
{
/// <summary>
/// Provides some helper functionality for working with test case data serialized to XML
/// </summary>
public static class XMLSerializerHelper
{
public static string SerializeToMemory<T>(T instance, XmlSerializerNamespaces ns = null, bool omitXmlDeclaration = true)
{
if (instance == null)
throw new ArgumentException("Serize object is null");
if (null == ns)
{
ns = new XmlSerializerNamespaces();
ns.Add("", "");
}
StringBuilder sb = new StringBuilder();
XmlWriterSettings writerSetting = new XmlWriterSettings();
writerSetting.OmitXmlDeclaration = omitXmlDeclaration;
writerSetting.Indent = true;
using (XmlWriter xmlWriter = XmlWriter.Create(sb, writerSetting))
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, instance, ns);
}
return sb.ToString();
}
/// <summary>
/// Serializes the Type to XML
/// </summary>
/// <param name="objectToBeSerialized">object to be serialized</param>
/// <param name="type">type of object to be serialized</param>
/// <returns>Serialized XML</returns>
public static string SerializeToMemory(object objectToBeSerialized, Type type)
{
UTF8Encoding encoding = new UTF8Encoding();
MemoryStream memorystream = new MemoryStream();
try
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(memorystream, objectToBeSerialized);
}
catch (Exception)
{
// XmlSerializer can't handle things like dictionaries, so as a backup, use the
// DataContractSerializer that WCF uses, which should handle everything
DataContractSerializer serializer = new DataContractSerializer(type);
serializer.WriteObject(memorystream, objectToBeSerialized);
}
StringBuilder buffer = new StringBuilder();
byte[] bytes = memorystream.ToArray();
buffer.Append(encoding.GetString(bytes));
return buffer.ToString();
}
/// <summary>
/// Serializes the type to xml file
/// Overwrites file if exists
/// </summary>
/// <typeparam name="T">The type of object we're serializing</typeparam>
/// <param name="objectToBeSerialized">typed data to save</param>
/// <param name="filePath">full path to the file</param>
public static void SerializeToFile<T>(T objectToBeSerialized, string filePath)
{
System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(fileStream, objectToBeSerialized);
fileStream.Close();
}
/// <summary>
/// Converts the serialized XML to its Type
/// </summary>
/// <param name="serializedXml">serialized XML of the Type</param>
/// <returns>the object deserialized from the XML</returns>
/// <typeparam name="T">The type of object that is serialized in the string</typeparam>
public static T DeserializeFromMemory<T>(string serializedXml)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] buffer = encoding.GetBytes(serializedXml);
MemoryStream memorystream = new MemoryStream(buffer);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(memorystream);
}
catch (InvalidOperationException)
{
// If XmlSerializer failed, it's probably because the string
// was serialized with the backup serializer, so try that.
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(memorystream);
}
}
/// <summary>
/// Converts the serialized XML to its type
/// </summary>
/// <param name="serializedXml">serialized XML of the type</param>
/// <param name="type">given type </param>
/// <returns>the object deserialized from the XML</returns>
public static object DeserializeFromMemory(string serializedXml, Type type)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] buffer = encoding.GetBytes(serializedXml);
MemoryStream memorystream = new MemoryStream(buffer);
try
{
XmlSerializer serializer = new XmlSerializer(type);
return serializer.Deserialize(memorystream);
}
catch (InvalidOperationException)
{
// If XmlSerializer failed, it's probably because the string
// was serialized with the backup serializer, so try that.
DataContractSerializer serializer = new DataContractSerializer(type);
return serializer.ReadObject(memorystream);
}
}
/// <summary>
/// Deserializes in the data from the given file to passed in Type
/// </summary>
/// <param name="filePath">full path to the file</param>
/// <returns>Deserialized Type</returns>
/// <typeparam name="T">The type of object to deserialize from the file</typeparam>
public static T DeserializeFromFile<T>(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
T deserializedObject = (T)serializer.Deserialize(fileStream);
fileStream.Close();
return deserializedObject;
}
/// <summary>
/// Deserializes a subset of XML into the given object type. This is useful for files that contian
/// multiple objects, where you want to only deserialize one of those objects into memory
/// </summary>
/// <typeparam name="T">The type of object that is encoded in the xml</typeparam>
/// <param name="filePath">Path to the XML file to deserialize</param>
/// <param name="xpath">The XPath to the particular object you want deserialized</param>
/// <returns>a fully instantiated object, deserialized from the file.</returns>
public static T DeserializeByXPath<T>(string xpath, string filePath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlNode userNode = xmlDoc.SelectSingleNode(xpath);
if (userNode != null)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(userNode.OuterXml));
}
else
{
return default(T);
}
}
/// <summary>
/// Deserializes a subset of XML into the given object type list.
/// </summary>
/// <typeparam name="T">The type of object that is encoded in the xml</typeparam>
/// <param name="filePath">Path to the XML file to deserialize</param>
/// <param name="xpath">The XPath to the particular object you want deserialized</param>
/// <returns>a fully instantiated object, deserialized from the file.</returns>
public static List<T> DeserializeListByXPath<T>(string xpath, string filePath)
{
List<T> list = new List<T> ();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlNodeList nodeList = xmlDoc.SelectNodes(xpath);
XmlSerializer serializer = new XmlSerializer(typeof(T));
foreach (XmlNode node in nodeList)
{
T t = (T)serializer.Deserialize(new StringReader(node.OuterXml));
if(null!=t)
{
list.Add (t);
}
}
return list;
}
/// <summary>
/// Update the value for give xml element
/// </summary>
/// <typeparam name="T">The type of object we're serializing</typeparam>
/// <param name="xpath">xpath to the xml node</param>
/// <param name="value">new value to set</param>
/// <param name="filePath">full path to the file</param>
/// <returns>a fully instantiated object, deserialized from the file.</returns>
public static T DeserializeFromUpdatedFile<T>(string xpath, string value, string filePath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlNode userNode = xmlDoc.SelectSingleNode(xpath);
userNode.InnerText = value;
XmlSerializer serializer = new XmlSerializer(typeof(T));
T deserializedObject = (T)serializer.Deserialize(new StringReader(xmlDoc.OuterXml));
return deserializedObject;
}
}
/// <summary>
/// XML serializable Dictionary
/// </summary>
/// <typeparam name="TKey">key type, needs to xml serialisable</typeparam>
/// <typeparam name="TValue">value type, needs to xml serialisable</typeparam>
public class XmlSerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
/// <summary>
/// used for accessing item nodes
/// </summary>
private const string ItemNodeName = "item";
/// <summary>
/// used fpr accessomg key nodes
/// </summary>
private const string KeyNodeName = "key";
/// <summary>
/// used for accessing value nodes.
/// </summary>
private const string ValueNodeName = "key";
/// <summary>
/// Initializes a new instance of the XmlSerializableDictionary class. uses Dictionary {TKey, TValue}'s version.
/// </summary>
/// <param name="source">source dictionary</param>
public XmlSerializableDictionary(IDictionary<TKey, TValue> source)
: base(source)
{
}
/// <summary>
/// Initializes a new instance of the XmlSerializableDictionary class. uses Dictionary {TKey, TValue}'s version.
/// </summary>
public XmlSerializableDictionary()
: base()
{
}
/// <summary>
/// from IXmlSerializable. I don't care about the schema, so returns null
/// </summary>
/// <returns>always null</returns>
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// from IXmlSerializable. Reads in the object in xml, called when deserialising.
/// </summary>
/// <param name="reader">xml reader</param>
public void ReadXml(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool isEmpty = reader.IsEmptyElement;
reader.Read();
if (isEmpty)
{
return;
}
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement(ItemNodeName);
reader.ReadStartElement(KeyNodeName);
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement(ValueNodeName);
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// from IXmlSerializable. writes out the item to xml, called when serialising.
/// </summary>
/// <param name="writer">xml writer</param>
public void WriteXml(XmlWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement(ItemNodeName);
writer.WriteStartElement(KeyNodeName);
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement(ValueNodeName);
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENTITY;
using OpenMiracle.DAL;
using System.Windows.Forms;
using System.Data;
namespace OpenMiracle.BLL
{
public class ExchangeRateBll
{
ExchangeRateSP SPExchangeRate = new ExchangeRateSP();
public void ExchangeRateAdd(ExchangeRateInfo exchangerateinfo)
{
try
{
SPExchangeRate.ExchangeRateAdd(exchangerateinfo);
}
catch (Exception ex)
{
MessageBox.Show("ERBll1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// Function to Update values in ExchangeRate Table
/// </summary>
/// <param name="exchangerateinfo"></param>
public void ExchangeRateEdit(ExchangeRateInfo exchangerateinfo)
{
try
{
SPExchangeRate.ExchangeRateEdit(exchangerateinfo);
}
catch (Exception ex)
{
MessageBox.Show("ERBll2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// Function to get all the values from ExchangeRate Table
/// </summary>
/// <returns></returns>
public List<DataTable> ExchangeRateViewAll()
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SPExchangeRate.ExchangeRateViewAll();
}
catch (Exception ex)
{
MessageBox.Show("ERBll3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
/// <summary>
/// Function to get particular values from ExchangeRate Table based on the parameter
/// </summary>
/// <param name="exchangeRateId"></param>
/// <returns></returns>
public ExchangeRateInfo ExchangeRateView(decimal exchangeRateId)
{
ExchangeRateInfo exchangerateinfo = new ExchangeRateInfo();
try
{
exchangerateinfo = SPExchangeRate.ExchangeRateView(exchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return exchangerateinfo;
}
/// <summary>
/// Function to delete particular details based on the parameter
/// </summary>
/// <param name="ExchangeRateId"></param>
public void ExchangeRateDelete(decimal ExchangeRateId)
{
try
{
SPExchangeRate.ExchangeRateDelete(ExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// Function to get the next id for ExchangeRate table
/// </summary>
/// <returns></returns>
public int ExchangeRateGetMax()
{
int max = 0;
try
{
max= SPExchangeRate.ExchangeRateGetMax();
}
catch (Exception ex)
{
MessageBox.Show("ERBll6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return max;
}
/// <summary>
/// Function to insert particular values to ExchangeRate Table
/// </summary>
/// <param name="exchangerateinfo"></param>
public void ExchangeRateAddParticularFields(ExchangeRateInfo exchangerateinfo)
{
try
{
SPExchangeRate.ExchangeRateAddParticularFields(exchangerateinfo);
}
catch (Exception ex)
{
MessageBox.Show("ERBll7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// Function to get values for search based on parameters
/// </summary>
/// <param name="strCurrencyname"></param>
/// <param name="dtDateFrom"></param>
/// <param name="dtDateTo"></param>
/// <returns></returns>
public List<DataTable> ExchangeRateSearch(String strCurrencyname, DateTime dtDateFrom, DateTime dtDateTo)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SPExchangeRate.ExchangeRateSearch(strCurrencyname, dtDateFrom, dtDateTo);
}
catch (Exception ex)
{
MessageBox.Show("ERBll8:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
/// <summary>
/// Function to check existence based on parameters and return status
/// </summary>
/// <param name="dtDate"></param>
/// <param name="decCurrencyId"></param>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public bool ExchangeRateCheckExistence(DateTime dtDate, decimal decCurrencyId, decimal decExchangeRateId)
{
bool isResult = false;
try
{
isResult = SPExchangeRate.ExchangeRateCheckExistence(dtDate, decCurrencyId, decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll9:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isResult;
}
/// <summary>
/// Function to get id based on parameter
/// </summary>
/// <param name="decCurrencyId"></param>
/// <param name="dtDate"></param>
/// <returns></returns>
public decimal GetExchangeRateId(decimal decCurrencyId, DateTime dtDate)
{
decimal decCount = 0;
try
{
decCount = SPExchangeRate.GetExchangeRateId(decCurrencyId, dtDate);
}
catch (Exception ex)
{
MessageBox.Show("ERBll10:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCount;
}
/// <summary>
/// Function to check refernce bassed on parameter
/// </summary>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public decimal ExchangeRateCheckReferences(decimal decExchangeRateId)
{
decimal decReturnValue = 0;
try
{
decReturnValue = SPExchangeRate.ExchangeRateCheckReferences(decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll11:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decReturnValue;
}
/// <summary>
/// Function to get rate based on parameter
/// </summary>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public decimal GetExchangeRateByExchangeRateId(decimal decExchangeRateId)
{
decimal decReturnValue = 0;
try
{
decReturnValue = SPExchangeRate.GetExchangeRateByExchangeRateId(decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll12:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decReturnValue;
}
/// <summary>
/// Function to view rate based on parameter
/// </summary>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public decimal ExchangeRateViewByExchangeRateId(decimal decExchangeRateId)
{
decimal exchangeRate = 0;
try
{
exchangeRate = SPExchangeRate.ExchangeRateViewByExchangeRateId(decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll13:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return exchangeRate;
}
/// <summary>
/// Function to get decimal places based on parameter
/// </summary>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public int NoOfDecimalNumberViewByExchangeRateId(decimal decExchangeRateId)
{
int NoOfDecimalNumber = 0;
try
{
NoOfDecimalNumber = SPExchangeRate.NoOfDecimalNumberViewByExchangeRateId(decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll14:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return NoOfDecimalNumber;
}
/// <summary>
/// Function to get decimal places based on parameter
/// </summary>
/// <param name="decCurrencyId"></param>
/// <returns></returns>
public int NoOfDecimalNumberViewByCurrencyId(decimal decCurrencyId)
{
int NoOfDecimalNumber = 0;
try
{
NoOfDecimalNumber = SPExchangeRate.NoOfDecimalNumberViewByCurrencyId(decCurrencyId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll15:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return NoOfDecimalNumber;
}
/// <summary>
/// Function to get value based on parameter
/// </summary>
/// <param name="decCurrencyId"></param>
/// <returns></returns>
public decimal ExchangerateViewByCurrencyId(decimal decCurrencyId)
{
decimal decExchangerateId = 0;
try
{
decExchangerateId = SPExchangeRate.ExchangerateViewByCurrencyId(decCurrencyId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll16:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decExchangerateId;
}
/// <summary>
/// Function to check existence based on parameters and return status
/// </summary>
/// <param name="dtDate"></param>
/// <param name="decCurrencyId"></param>
/// <param name="decExchangeRateId"></param>
/// <returns></returns>
public bool ExchangeRateCheckExistanceForUpdationAndDelete(DateTime dtDate, decimal decExchangeRateId)
{
bool isResult = false;
try
{
isResult = SPExchangeRate.ExchangeRateCheckExistanceForUpdationAndDelete(dtDate, decExchangeRateId);
}
catch (Exception ex)
{
MessageBox.Show("ERBll17:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isResult;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountdownAudio : MonoBehaviour {
public AudioClip CountdownStart;
public AudioSource CountdownSource;
// Use this for initialization
void Start () {
CountdownSource.clip = CountdownStart;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.F1))
{
if (Time.timeScale > 0)
{
Time.timeScale = 0;
CountdownSource.Pause();
}
else
{
Time.timeScale = 1;
CountdownSource.Play();
}
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using BakerWebApp.Models;
using Microsoft.AspNet.Identity;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
namespace BakerWebApp.Controllers
{
[Authorize]
public class ClientesController : Controller
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public ClientesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: Clientes
public async Task<IActionResult> Index()
{
var usuario = _userManager.FindByNameAsync(User.Identity.Name).Result;
return View(await _context.Clientes.Where(item => item.Usuario.Id == usuario.Id).ToListAsync());
}
// GET: Clientes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Cliente cliente = await _context.Clientes.SingleAsync(m => m.ClienteId == id);
if (cliente == null)
{
return HttpNotFound();
}
return View(cliente);
}
// GET: Clientes/Create
public IActionResult Create()
{
return View();
}
// POST: Clientes/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Cliente cliente)
{
cliente.Usuario = _userManager.FindByNameAsync(User.Identity.Name).Result;
cliente.UsuarioId = cliente.Usuario.Id;
if (ModelState.IsValid)
{
_context.Clientes.Add(cliente);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(cliente);
}
// GET: Clientes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Cliente cliente = await _context.Clientes.Include(u => u.Usuario).SingleAsync(m => m.ClienteId == id);
if (cliente == null)
{
return HttpNotFound();
}
return View(cliente);
}
// POST: Clientes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Cliente cliente)
{
if (ModelState.IsValid)
{
_context.Update(cliente);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(cliente);
}
// GET: Clientes/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Cliente cliente = await _context.Clientes.SingleAsync(m => m.ClienteId == id);
if (cliente == null)
{
return HttpNotFound();
}
return View(cliente);
}
// POST: Clientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
Cliente cliente = await _context.Clientes.SingleAsync(m => m.ClienteId == id);
_context.Clientes.Remove(cliente);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}
|
using Faux.Banque.Domain.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Faux.Banque.Domain.ValueObjects
{
public class Debit : LedgerTransaction
{
public Debit(DateTime transactionDate, decimal amount) : base(transactionDate, amount *-1) { }
}
public class Credit: LedgerTransaction
{
public Credit(DateTime transactionDate, decimal amount) : base(transactionDate, amount) { }
}
}
|
using System;
using WarMachines.Interfaces;
namespace WarMachines.Machines
{
public class Fighter : Machine, IFighter
{
private const double InitialHealthPoints = 200;
public Fighter(string fighterName, double fighterAttackPoints, double figtherDefensePoints, bool stealthMode)
:base(fighterName, InitialHealthPoints, fighterAttackPoints, figtherDefensePoints)
{
this.StealthMode = false;
if (stealthMode == true)
{
this.ToggleStealthMode();
}
}
public Fighter(string fighterName, double fighterAttackPoints, double figtherDefensePoints, bool stealthMode, IPilot fighterPilot)
:this(fighterName, fighterAttackPoints, figtherDefensePoints, stealthMode)
{
this.Pilot = fighterPilot;
}
public bool StealthMode { get; private set; }
public void ToggleStealthMode()
{
this.StealthMode = !this.StealthMode;
}
public override string ToString()
{
string result = base.ToString();
result += "Stealth: ";
if (this.StealthMode == true)
{
result += "ON";
}
else
{
result += "OFF";
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recording.Application.IServices
{
public interface ITransientDependency
{
}
public interface ISingletonDependency
{
}
public interface IScopedDependency
{
}
public interface IBaseServiceForDI
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CIS420Redux.Models
{
public class Document
{
public int Id { get; set; }
public int StudentId { get; set; }
public DateTime ExpirationDate { get; set; }
public string Type { get; set; }
public bool ComplianceStatus { get; set; }
public int StudentNumber { get; set; }
public byte[] FileBytes { get; set; }
public int ContentLength { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
public string UploadedBy{ get; set; }
public virtual Student Students { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HintUI : MonoBehaviour
{
public GameObject hintInteractionUI;
public Text taskHintUI;
#region SINGLETON PATTERN
private static HintUI userInterface;
public static HintUI GetInstance()
{
return userInterface;
}
private void Awake()
{
userInterface = this;
}
#endregion
public void InteractionHintUIState(bool state)
{
hintInteractionUI.SetActive(state);
}
public void ShowTaskHint(string description)
{
taskHintUI.text = description;
taskHintUI.gameObject.SetActive(true);
}
public void HideTaskHint()
{
taskHintUI.gameObject.SetActive(false);
}
}
|
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 Yelemani
{
public partial class Home : Form
{
int tmp;
Login login;
public Home()
{
InitializeComponent();
login = new Login(this);
tmp = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
panel2.Width += 5;
if (panel2.Width >= panel1.Width)
{
login.Show();
this.Hide();
timer1.Stop();
}
}
private void Home_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void Home_FormClosed(object sender, FormClosedEventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
//Database.Bill bill = new Database.Bill();
//bill.setNum(1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Asset.Models.Library.EntityModels.AssetsModels.AssetEntrys;
using AssetSqlDatabase.Library.DatabaseContext;
namespace AssetTrackingSystem.MVC.Controllers.AssetModels.AssetEntries
{
public class ServiceOrRepairingsController : Controller
{
private AssetDbContext db = new AssetDbContext();
// GET: ServiceOrRepairings
public ActionResult Index()
{
var serviceOrRepairings = db.ServiceOrRepairings.Include(s => s.AssetEntry);
return View(serviceOrRepairings.ToList());
}
// GET: ServiceOrRepairings/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ServiceOrRepairing serviceOrRepairing = db.ServiceOrRepairings.Find(id);
if (serviceOrRepairing == null)
{
return HttpNotFound();
}
return View(serviceOrRepairing);
}
// GET: ServiceOrRepairings/Create
public ActionResult Create()
{
ViewBag.AssetEntryId = new SelectList(db.AssetEntries, "Id", "AssetId");
return View();
}
// POST: ServiceOrRepairings/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,AssetEntryId,Description,ServiceDate,ServiceingCostDecimal,PartsCostDecimal,TaxDecimal,ServiceBy")] ServiceOrRepairing serviceOrRepairing)
{
if (ModelState.IsValid)
{
db.ServiceOrRepairings.Add(serviceOrRepairing);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetEntryId = new SelectList(db.AssetEntries, "Id", "AssetId", serviceOrRepairing.AssetEntryId);
return View(serviceOrRepairing);
}
// GET: ServiceOrRepairings/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ServiceOrRepairing serviceOrRepairing = db.ServiceOrRepairings.Find(id);
if (serviceOrRepairing == null)
{
return HttpNotFound();
}
ViewBag.AssetEntryId = new SelectList(db.AssetEntries, "Id", "AssetId", serviceOrRepairing.AssetEntryId);
return View(serviceOrRepairing);
}
// POST: ServiceOrRepairings/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,AssetEntryId,Description,ServiceDate,ServiceingCostDecimal,PartsCostDecimal,TaxDecimal,ServiceBy")] ServiceOrRepairing serviceOrRepairing)
{
if (ModelState.IsValid)
{
db.Entry(serviceOrRepairing).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetEntryId = new SelectList(db.AssetEntries, "Id", "AssetId", serviceOrRepairing.AssetEntryId);
return View(serviceOrRepairing);
}
// GET: ServiceOrRepairings/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ServiceOrRepairing serviceOrRepairing = db.ServiceOrRepairings.Find(id);
if (serviceOrRepairing == null)
{
return HttpNotFound();
}
return View(serviceOrRepairing);
}
// POST: ServiceOrRepairings/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ServiceOrRepairing serviceOrRepairing = db.ServiceOrRepairings.Find(id);
db.ServiceOrRepairings.Remove(serviceOrRepairing);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FastSQL.Sync.Core.Enums
{
public enum MessageStatus
{
None = 0,
Delievered = 1
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using productsapi.DTO;
using productsapi.Models;
using productsapi.Repositories;
namespace productsapi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CategoryController : ControllerBase
{
private readonly ICategory _repo;
private readonly IMapper _mapper;
public CategoryController(ICategory repo , IMapper mapper)
{
_mapper = mapper;
_repo = repo;
}
[HttpGet]
public IActionResult Get()
{
IEnumerable<Category> categories = _repo.GetAll();
IEnumerable<CategoryReadDTO> readCat = _mapper.Map<IEnumerable<CategoryReadDTO>>(categories);
return Ok(readCat);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
public IActionResult AddNew(CategoryWriteDTO category)
{
if( category != null)
{
if (category.parentId != null)
category.parent = _repo.GetOneById(category.parentId);
Category cat = _mapper.Map<Category>(category);
_repo.Add(cat);
if (_repo.SaveChanges() > 0)
return Ok("created");
}
return BadRequest();
}
[HttpGet]
[Route("{id}")]
public IActionResult GetOneById(Guid id)
{
Category category = _repo.GetOneById(id);
if(category != null)
{
CategoryReadDTO readCat = _mapper.Map<CategoryReadDTO>(category);
return Ok(readCat);
}
return NotFound();
}
[HttpPut]
[Route("{id}")]
[ProducesResponseType(StatusCodes.Status201Created)]
public IActionResult Edit(Guid id , CategoryWriteDTO category)
{
if (category != null)
{
//Category parent;
if (category.parentId != null)
category.parent = _repo.GetOneById(category.parentId);
Category cat = _mapper.Map<Category>(category);
_repo.Edit(cat);
if (_repo.SaveChanges() > 0)
return Ok("updated");
}
return BadRequest();
}
[HttpDelete]
[Route("{id}")]
public IActionResult Delete(Guid id)
{
if (id != null)
{
_repo.Delete(id);
if (_repo.SaveChanges() > 0)
return Ok("deleted");
}
return NotFound();
}
[HttpGet]
[Route("{id}/parent")]
public IActionResult GetParent(Guid id)
{
if(id != null)
{
Category cat = _repo.getParent(id);
if(cat != null)
return Ok(cat);
}
return NotFound();
}
}
}
|
using System.Windows.Data;
namespace Tai_Shi_Xuan_Ji_Yi.Converters
{
class CConverterDoubleToTemperature : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double temper = (double)value;
return temper.ToString("F2") + " ℃";
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FacebookWrapper;
using FacebookWrapper.ObjectModel;
namespace BasicFacebookFeatures.Logic
{
public interface IBestFriendFilterStrategy
{
void updateFriendsCounter(Dictionary<string, FacebookUserWrapper> i_FbFriendsCollection);
}
}
|
using System.Collections.Generic;
namespace Micro.Net.Abstractions
{
public interface ITerminable
{
bool IsTerminated { get; }
bool TryGetTerminate(out string reason, out IDictionary<string, string> auxData);
void SetTerminate(string reason, IDictionary<string, string> auxData = null);
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
namespace api_cms.common
{
public class UtilClass
{
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public static int GetRandomNumber(int min, int max)
{
lock (syncLock)
{
return getrandom.Next(min, max);
}
}
public static bool ValidateDatetime(string dateString)
{
try
{
string formatString = "dd/MM/yyyy HH:mm";
DateTime dateValue;
CultureInfo enUS = new CultureInfo("en-US"); // is up to you
if (DateTime.TryParseExact(dateString, formatString, enUS,
DateTimeStyles.None, out dateValue))
return true;
else
return false;
}
catch (Exception)
{
return false;
}
}
public static string GetWebAppRoot()
{
string host = (HttpContext.Current.Request.Url.IsDefaultPort) ?
HttpContext.Current.Request.Url.Host :
HttpContext.Current.Request.Url.Authority;
host = String.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, host);
if (HttpContext.Current.Request.ApplicationPath == "/")
return host;
else
return host + HttpContext.Current.Request.ApplicationPath;
}
public static string SendPost(string postData, string url, string contentType = "application/x-www-form-urlencoded;charset=utf-8")
{
bool success = false;
string resp;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
CookieContainer cookie = new CookieContainer();
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentLength = data.Length;
myRequest.ContentType = contentType;
myRequest.KeepAlive = false;
myRequest.CookieContainer = cookie;
myRequest.AllowAutoRedirect = false;
using (Stream requestStream = myRequest.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
string responseXml = string.Empty;
try
{
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
if (myResponse.StatusCode != HttpStatusCode.OK)
success = false;
else
success = true;
using (Stream respStream = myResponse.GetResponseStream())
{
using (StreamReader respReader = new StreamReader(respStream))
{
responseXml = respReader.ReadToEnd();
}
}
}
}
catch (WebException webEx)
{
if (webEx.Response != null)
{
using (HttpWebResponse exResponse = (HttpWebResponse)webEx.Response)
{
using (StreamReader sr = new StreamReader(exResponse.GetResponseStream()))
{
responseXml = sr.ReadToEnd();
}
}
}
}
if (success)
{
resp = responseXml;
}
else
{
resp = responseXml;
}
return resp;
}
public static string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
public static void AddCookie(HttpContext context, string name, string value, int expire_date = 90)
{
try
{
HttpCookie cookie = new HttpCookie(name);
cookie.Value = value;
cookie.Expires = DateTime.Now.AddDays(expire_date);
context.Response.SetCookie(cookie);
}
catch (Exception ex)
{
LogClass.SaveError("ERROR Add cookie", ex, true);
throw new Exception(ex.Message);
}
}
public static void RemoveCookie(HttpContext context, string name)
{
try
{
var myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-1d);
context.Response.Cookies.Add(myCookie);
}
catch (Exception ex)
{
LogClass.SaveError("ERROR Remove cookie", ex, true);
throw new Exception(ex.Message);
}
}
public static void AddCookie(System.Web.UI.Page page, string name, string value, int expire_date = 90)
{
try
{
HttpCookie cookie = new HttpCookie(name);
cookie.Value = value;
cookie.Expires = DateTime.Now.AddDays(expire_date);
page.Response.SetCookie(cookie);
}
catch (Exception ex)
{
LogClass.SaveError("ERROR Add cookie", ex, true);
}
}
public static void IncludeCSSFile(System.Web.UI.Page page, string cssfile)
{
HtmlGenericControl child = new HtmlGenericControl("link");
child.Attributes.Add("rel", "stylesheet");
child.Attributes.Add("href", cssfile);
child.Attributes.Add("type", "text/css");
page.Header.Controls.AddAt(0, child);
}
public static void IncludeCSS(System.Web.UI.Page page, string css)
{
HtmlGenericControl child = new HtmlGenericControl("style");
child.Attributes.Add("type", "text/css");
child.InnerHtml = css;
page.Header.Controls.AddAt(0, child);
}
public static void IncludeScript(System.Web.UI.Page page, string script)
{
HtmlGenericControl child = new HtmlGenericControl("script");
child.Attributes.Add("type", "text/javascript");
child.InnerHtml = script;
page.Header.Controls.Add(child);
}
public static void IncludeFileJS(System.Web.UI.Page page, string script)
{
HtmlGenericControl child = new HtmlGenericControl("script");
child.Attributes.Add("type", "text/javascript");
child.Attributes.Add("src", script);
page.Header.Controls.Add(child);
}
public static void IncludeSourceJS(System.Web.UI.Page page, string script)
{
HtmlGenericControl child = new HtmlGenericControl();
child.InnerHtml = script;
page.Header.Controls.Add(child);
}
private static readonly string[] VietnameseSigns = new string[]
{
"aAeEoOuUiIdDyY",
"áàạảãâấầậẩẫăắằặẳẵ",
"ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
"éèẹẻẽêếềệểễ",
"ÉÈẸẺẼÊẾỀỆỂỄ",
"óòọỏõôốồộổỗơớờợởỡ",
"ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
"úùụủũưứừựửữ",
"ÚÙỤỦŨƯỨỪỰỬỮ",
"íìịỉĩ",
"ÍÌỊỈĨ",
"đ",
"Đ",
"ýỳỵỷỹ",
"ÝỲỴỶỸ"
};
public static string RemoveSign4VietnameseString(string s)
{
string str = convertToUnSign3(s);
//Tiến hành thay thế , lọc bỏ dấu cho chuỗi
for (int i = 1; i < VietnameseSigns.Length; i++)
{
for (int j = 0; j < VietnameseSigns[i].Length; j++)
str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
}
return str;
}
public static string General_publisher(string publisherId)
{
string s = "P_";
for (int i = 0; i < 5 - publisherId.Length; i++)
{
s += "0";
}
s += publisherId;
return s;
}
public static bool IsUnicode(string input)
{
var asciiBytesCount = Encoding.ASCII.GetByteCount(input);
var unicodBytesCount = Encoding.UTF8.GetByteCount(input);
return asciiBytesCount != unicodBytesCount;
}
public static bool IsPhoneNumber(string number)
{
return Regex.Match(number, @"^[0-9]{10,11}$").Success;
}
public static string EncryptEmail(string email)
{
if (IsValidEmail(email))
{
string e = email.Split('@')[0];
string p = "";
if (e.Length >= 6)
{
return "******" + e.Substring(6, e.Length - 6) + "@" + email.Split('@')[1];
}
else
{
for (int i = 0; i < e.Length; i++)
{
p += "*";
}
return p + "@" + email.Split('@')[1];
}
}
else
{
return email;
}
}
public static string EncryptPhone(string phone)
{
if (IsPhoneNumber(phone))
{
string p = "";
string s = phone.Substring(2, phone.Length - 2);
for (int i = 0; i < s.Length; i++)
{
p += "*";
}
return phone.Substring(0, 2) + p + phone.Substring(phone.Length - 2, 2);
}
else
{
return phone;
}
}
public static bool IsValidEmail(string emailaddress)
{
try
{
Regex rx = new Regex(
@"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
return rx.IsMatch(emailaddress);
}
catch (FormatException)
{
return false;
}
}
public static string Get_Html(string uri)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Timeout = 5000;
//Console.WriteLine("Response stream received.");
//Console.WriteLine(readStream.ReadToEnd());
//response.Close();
//readStream.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
//using (StreamReader reader = new StreamReader(stream))
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return "";
}
}
public static string formatMoney(int money)
{
return String.Format("{0:#,###}", money).Replace(",", ".");
}
public static string convertToUnSign3(string s)
{
Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
string temp = s.Normalize(NormalizationForm.FormD);
return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
}
public static long UnixTime(DateTime d)
{
var timeSpan = (d - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified));
return (long)timeSpan.TotalSeconds;
}
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
}
public class Web
{
public enum Method { GET, POST };
public static string WebRequest(Method method, string contentType, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
try
{
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "";
webRequest.Timeout = 60000;//1min
if (method == Method.POST)
{
webRequest.ContentType = contentType;
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return responseData;
}
public static string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "";
webRequest.Timeout = 60000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
public static string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
}
} |
using UnityEngine;
using System.Collections;
public class ElevatorStatus : MonoBehaviour {
public int currentFloor = 1;//set current floor to the lobby floor (1st floor)
void Start () {
}
// Update is called once per frame
void Update () {
}
public void setCurrentFloor(int floor){
currentFloor = floor;
}
}
|
using Payroll.Common;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Payroll.Models
{
public class WorkHourItem
{
public Guid WorkHourItemId { get; set; }
[Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")]
[Display(ResourceType = typeof(Resource), Name = "DayOfWeek")]
public Common.DayOfWeek DayOfWeek { get; set; }
[Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")]
[Display(ResourceType = typeof(Resource), Name = "Start")]
public TimeSpan Start { get; set; }
[Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")]
[Display(ResourceType = typeof(Resource), Name = "End")]
public TimeSpan End { get; set; }
public Guid WorkHoursId { get; set; }
[ForeignKey("WorkHoursId")]
public virtual WorkHours WorkHours { get; set; }
public string DayOfWeekDescription { get { return this.DayOfWeek.GetDescription(); } }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace JJApi.Controllers
{
[Authorize(Roles = "level1,level2")]
public class UserManagerController : Controller
{
[HttpPost]
[Route("/usermanagement/getData")]
public string getDataUsermanager([FromForm] IFormFile file, Dictionary<string, string> datos)
{
BL.queries.blUsermanager bUsermanager = new BL.queries.blUsermanager(Request.Headers["Authorization"].ToString());
string result = bUsermanager.getDataUsermanager(null, datos);
return result;
}
[HttpPost]
[Route("/usermanagement/getProfilesForNewUser")]
public string getProfilesList([FromForm] IFormFile file, Dictionary<string, string> datos)
{
BL.queries.blUsermanager bUsermanager = new BL.queries.blUsermanager(Request.Headers["Authorization"].ToString());
string result = bUsermanager.getProfilesListForNewUser(null, datos);
return result;
}
[HttpPost]
[Route("/usermanagement/getDataUserInfo")]
public string setDataCompanyprofile([FromForm] IFormFile file, Dictionary<string, string> datos)
{
BL.queries.blUsermanager bUsermanager = new BL.queries.blUsermanager(Request.Headers["Authorization"].ToString());
string result = bUsermanager.getDataUserInfo(null, datos);
return result;
}
[HttpPost]
[Route("/usermanagement/setDataUserInfo")]
public string setDataUserInfo([FromForm] IFormFile file, Dictionary<string, string> datos)
{
BL.queries.blUsermanager bUsermanager = new BL.queries.blUsermanager(Request.Headers["Authorization"].ToString());
string result = bUsermanager.setDataUserInfo(null, datos);
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.DataContracts.DomesticTicket
{
public class PIDInfo
{
/// <summary>
/// IP地址
/// </summary>
public string IP { get; set; }
/// <summary>
/// 端口号
/// </summary>
public int Port { get; set; }
/// <summary>
/// Office号
/// </summary>
public string Office { get; set; }
/// <summary>
/// 运营Code
/// </summary>
public string CarrierCode { get; set; }
/// <summary>
/// 供应Code
/// </summary>
public string SupplierCode { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UberFrba.Abm_Cliente
{
public partial class ModificarCliente : Form
{
private Cliente clienteAModificar;
public ModificarCliente(Cliente cliente)
{
InitializeComponent();
this.clienteAModificar = cliente;
}
private void ModificarCliente_Load(object sender, EventArgs e)
{
try
{
//Cargo en pantalla los datos del cliente elegido
txtNombre.Text = clienteAModificar.Nombre;
txtApellido.Text = clienteAModificar.Apellido;
txtCodpostal.Text = clienteAModificar.CodigoPostal.ToString();
txtDireccion.Text = clienteAModificar.Direccion;
txtTelefono.Text = clienteAModificar.Telefono.ToString();
txtFechaNac.Text = clienteAModificar.FechaNacimiento.ToShortDateString();
txtDni.Text = clienteAModificar.Dni.ToString();
txtEmail.Text = clienteAModificar.Mail;
chkHabilitado.Checked = (clienteAModificar.Activo == 1) ? true : false;
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error inesperado " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
private void btnGuardar_Click(object sender, EventArgs e)
{
try
{
int contadorErrores = 0;
if (txtFechaNac.Text == "")
{
errorFechaNac.Text = "El campo no puede ser vacio";
contadorErrores++;
}
else
{
errorFechaNac.Text = Cliente.validarFechaNac(DateTime.Parse(txtFechaNac.Text));
if (errorFechaNac.Text != "") contadorErrores++;
}
errorNombre.Text = Cliente.validarNombre(txtNombre.Text);
if (errorNombre.Text != "") contadorErrores++;
errorApellido.Text = Cliente.validarApellido(txtApellido.Text);
if (errorApellido.Text != "") contadorErrores++;
errorDni.Text = Cliente.validarDni(txtDni.Text);
if (errorDni.Text != "") contadorErrores++;
//Valido que el campo Telefono sea correcto y no esté repetido si es que se modificó
if (txtTelefono.Text != clienteAModificar.Telefono.ToString())
{
errorTelefono.Text = Cliente.validarTelefono(txtTelefono.Text);
if (errorTelefono.Text != "") contadorErrores++;
}
errorEmail.Text = Cliente.validarEmail(txtEmail.Text);
if (errorEmail.Text != "") contadorErrores++;
errorDireccion.Text = Cliente.validarDireccion(txtDireccion.Text);
if (errorDireccion.Text != "") contadorErrores++;
errorCodPostal.Text = Cliente.validarCodPostal(txtCodpostal.Text);
if (errorCodPostal.Text != "") contadorErrores++;
//Si no hay errores, se intenta modificar el nuevo cliente
if (contadorErrores == 0)
{
Cliente clienteAModificarEnBD = new Cliente();
clienteAModificarEnBD.Nombre = txtNombre.Text;
clienteAModificarEnBD.Apellido = txtApellido.Text;
clienteAModificarEnBD.Dni = Decimal.Parse(txtDni.Text);
clienteAModificarEnBD.Telefono = Decimal.Parse(txtTelefono.Text);
clienteAModificarEnBD.Direccion = txtDireccion.Text;
clienteAModificarEnBD.CodigoPostal = Decimal.Parse(txtCodpostal.Text);
clienteAModificarEnBD.FechaNacimiento = DateTime.Parse(txtFechaNac.Text);
clienteAModificarEnBD.Activo = (chkHabilitado.Checked) ? (Byte)1 : (Byte)0;
clienteAModificarEnBD.Mail = (txtEmail.Text == "") ? null : txtEmail.Text;
String[] respuesta = Cliente.modificarCliente(clienteAModificarEnBD, clienteAModificar.Telefono);
if (respuesta[0] == "Error")
{
lblErrorBaseDatos.Text = respuesta[1];
grpErrorBaseDatos.Visible = true;
}
else
{
MessageBox.Show(respuesta[1], "Operación exitosa", MessageBoxButtons.OK);
this.Hide();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
private void btnCalendario_Click(object sender, EventArgs e)
{
calendarioFechaNac.Visible = true;
btnCalendario.Visible = false;
calendarioFechaNac.BringToFront();
}
private void calendarioFechaNac_DateSelected(object sender, DateRangeEventArgs e)
{
txtFechaNac.Text = e.Start.ToShortDateString();
calendarioFechaNac.Visible = false;
btnCalendario.Visible = true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PSDestroyer : MonoBehaviour
{
ParticleSystem system;
SoundController sound;
private void Awake()
{
system = GetComponent<ParticleSystem>();
sound = GetComponentInChildren<SoundController>();
}
private void Start()
{
sound.PlayStart();
}
// Update is called once per frame
void Update()
{
if (!system.isPlaying && !sound.isPlaying)
{
Destroy(gameObject);
}
}
}
|
namespace KRF.Core.Entities.MISC
{
public class CityAndState
{
public int CityId { get; set; }
public string StateName { get; set; }
}
}
|
using EsMo.Sina.SDK.Resource;
using EsMo.Sina.SDK.Service;
using MvvmCross.Platform;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
namespace EsMo.Sina.SDK
{
public static class ResourceExtension
{
public static string GetResourceString(this string key)
{
return AppResources.ResourceManager.GetString(key);
}
public static string GetResourceString(this Enum enumValue)
{
return GetResourceString(enumValue.ToString());
}
static Stream imageLoading;
public static Stream ImageLoading
{
get
{
if (imageLoading == null)
{
imageLoading = AssetsHelper.timeline_loading.ToAssetsImage().ToStream();
}
return imageLoading;
}
}
static Stream ToStream(this string localPath)
{
return Mvx.Resolve<IApplicationService>().ResourceCache.Get(localPath);
}
}
}
|
using Microsoft.AspNet.Identity;
using MooshakPP.DAL;
using MooshakPP.Models;
using System.Web.Mvc;
namespace MooshakPP.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private static IdentityManager manager = new IdentityManager();
/// <summary>
/// This function will use the IdentityManager class to initilize the database with a few test cases.
/// The acions in this fucntion should only run once because of the "singleton pattern" used.
/// </summary>
private static void IdentityInitilizer()
{
if(!manager.RoleExists("admin"))
{
manager.CreateRole("admin");
}
if (!manager.RoleExists("student"))
{
manager.CreateRole("student");
}
if (!manager.RoleExists("teacher"))
{
manager.CreateRole("teacher");
}
if (!manager.UserExists("admin@admin.com"))
{
ApplicationUser newAdmin = new ApplicationUser();
newAdmin.UserName = "admin@admin.com";
newAdmin.Email = "admin@admin.com";
manager.CreateUser(newAdmin, "Admin-123");
}
if (!manager.UserExists("teacher@teacher.com"))
{
ApplicationUser newUser = new ApplicationUser();
newUser.UserName = "teacher@teacher.com";
newUser.Email = "teacher@teacher.com";
manager.CreateUser(newUser, "123456");
}
var admin = manager.GetUser("admin@admin.com");
if (!manager.UserIsInRole(admin.Id, "admin"))
{
manager.AddUserToRole(admin.Id, "admin");
}
var teacher = manager.GetUser("teacher@teacher.com");
if (!manager.UserIsInRole(teacher.Id, "teacher"))
{
manager.AddUserToRole(teacher.Id, "teacher");
}
}
[Authorize]
public ActionResult Index()
{
IdentityInitilizer();
var userId = User.Identity.GetUserId();
if (manager.UserIsInRole(userId, "admin"))
{
return RedirectToAction("index", "admin");
}
else if (manager.UserIsInRole(userId, "teacher"))
{
return RedirectToAction("index", "teacher");
}
else if (manager.UserIsInRole(userId, "student"))
{
return RedirectToAction("index", "student");
}
else
{
//ToDo throw exception, should not go into this view under normal circumstances
return View();
}
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FastSQL.Core.UI.Interfaces
{
public interface IControlDefinition
{
string Id { get; set; }
string ControlName { get; set; }
string ControlHeader { get; set; }
string Description { get; set; }
string ActivatedById { get; set; }
int DefaultState { get; }
object Control { get; }
}
}
|
namespace Triton.Bot.Profiles
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml.Serialization;
[ProfileElementName("Switch"), XmlRoot("Switch")]
public class SwitchTag : ProfileGroupElement
{
private bool bool_0;
private Func<string> func_0;
[CompilerGenerated]
private List<SwitchArgument> list_1;
private string string_0;
private SwitchArgument switchArgument_0;
private void method_0()
{
string condition = this.Condition;
using (List<SwitchArgument>.Enumerator enumerator = this.Arguments.GetEnumerator())
{
SwitchArgument current;
while (enumerator.MoveNext())
{
current = enumerator.Current;
if (current.Value == condition)
{
goto Label_0037;
}
}
goto Label_004E;
Label_0037:
this.switchArgument_0 = current;
}
Label_004E:
if (this.switchArgument_0 == null)
{
throw new Exception("Switch argument does not contain a matching value! Current condition: " + this.ConditionString + " => " + condition);
}
}
[AsyncStateMachine(typeof(ref G>\.Y7^@i4W=XoH(\[)dV-d_Xx\))]
public override Task ProfileTagLogic()
{
Struct41 struct2;
struct2.switchTag_0 = this;
struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create();
struct2.int_0 = -1;
struct2.asyncTaskMethodBuilder_0.Start<Struct41>(ref struct2);
return struct2.asyncTaskMethodBuilder_0.Task;
}
public override void Reset()
{
base.Reset();
this.bool_0 = false;
}
[XmlElement("Arg")]
public List<SwitchArgument> Arguments
{
[CompilerGenerated]
get
{
return this.list_1;
}
[CompilerGenerated]
set
{
this.list_1 = value;
}
}
public override string Author
{
get
{
return "Bossland GmbH";
}
}
[XmlIgnore]
public string Condition
{
get
{
return this.func_0();
}
}
[XmlAttribute("Condition")]
public string ConditionString
{
get
{
return this.string_0;
}
set
{
if (value != this.string_0)
{
this.string_0 = value;
this.func_0 = ProfileScripting.GetCondition<string>("str(" + value + ")");
}
}
}
public override string Description
{
get
{
return "";
}
}
public override bool IsFinished
{
get
{
return this.bool_0;
}
}
public override string Name
{
get
{
return "Switch";
}
}
public override string Version
{
get
{
return "1.0.0.0";
}
}
[CompilerGenerated]
private struct Struct41 : IAsyncStateMachine
{
public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0;
private List<ProfileElement>.Enumerator enumerator_0;
public int int_0;
public SwitchTag switchTag_0;
private TaskAwaiter taskAwaiter_0;
private void MoveNext()
{
int num = this.int_0;
try
{
if (num != 0)
{
this.switchTag_0.method_0();
this.enumerator_0 = this.switchTag_0.switchArgument_0.Children.GetEnumerator();
}
try
{
TaskAwaiter awaiter;
if (num == 0)
{
awaiter = this.taskAwaiter_0;
this.taskAwaiter_0 = new TaskAwaiter();
num = -1;
this.int_0 = -1;
goto Label_0084;
}
Label_0052:
if (!this.enumerator_0.MoveNext())
{
goto Label_00CD;
}
ProfileElement current = this.enumerator_0.Current;
current.Reset();
awaiter = current.ProfileTagLogic().GetAwaiter();
if (!awaiter.IsCompleted)
{
goto Label_0097;
}
Label_0084:
awaiter.GetResult();
awaiter = new TaskAwaiter();
goto Label_0052;
Label_0097:
num = 0;
this.int_0 = 0;
this.taskAwaiter_0 = awaiter;
this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, SwitchTag.Struct41>(ref awaiter, ref this);
return;
}
finally
{
if (num < 0)
{
this.enumerator_0.Dispose();
}
}
Label_00CD:
this.enumerator_0 = new List<ProfileElement>.Enumerator();
this.switchTag_0.bool_0 = true;
}
catch (Exception exception)
{
this.int_0 = -2;
this.asyncTaskMethodBuilder_0.SetException(exception);
return;
}
this.int_0 = -2;
this.asyncTaskMethodBuilder_0.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine);
}
}
public class SwitchArgument
{
[CompilerGenerated]
private List<ProfileElement> list_0;
[CompilerGenerated]
private string string_0;
public List<ProfileElement> Children
{
[CompilerGenerated]
get
{
return this.list_0;
}
[CompilerGenerated]
set
{
this.list_0 = value;
}
}
[XmlAttribute("Value")]
public string Value
{
[CompilerGenerated]
get
{
return this.string_0;
}
[CompilerGenerated]
set
{
this.string_0 = value;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tasks.Services.Domain.Models
{
public class TaskModel
{
public Guid Id { get; set; }
public string TaskName { get; set; }
public string TaskStatus { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
public bool IsLoginUserTask { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KursusGuru.Data_Layer
{
static class DataController
{
/*
* Liste med brugere.
* I et dictionary indekseres brugeren vha. studienummer (user id).
*/
private static Dictionary<int, User> userList = new Dictionary<int, User>();
/*
* Henter bruger ud fra deres studienummer.
*/
public static User LoadUserData(int id)
{
User user = userList[id];
return user;
}
/*
* Gemmer en bruger.
*/
public static void SaveUserData(User user)
{
userList.Add(user.id, user);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Frostbyte.Entities.Enums;
using Frostbyte.Entities.Results;
using Frostbyte.Handlers;
namespace Frostbyte.Sources
{
public sealed class BandCampSource : ISourceProvider
{
private readonly Regex
_trackUrlRegex = new Regex("^https?://(?:[^.]+\\.|)bandcamp\\.com/track/([a-zA-Z0-9-_]+)/?(?:\\?.*|)$", RegexOptions.Compiled | RegexOptions.IgnoreCase),
_albumUrlRegex = new Regex("^https?://(?:[^.]+\\.|)bandcamp\\.com/album/([a-zA-Z0-9-_]+)/?(?:\\?.*|)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public async ValueTask<SearchResult> SearchAsync(string query)
{
var result = new SearchResult();
query = query switch
{
var trackUrl when _trackUrlRegex.IsMatch(query) => trackUrl,
var albumUrl when _albumUrlRegex.IsMatch(query) => albumUrl,
var _ when !Uri.IsWellFormedUriString(query, UriKind.RelativeOrAbsolute) => $"https://bandcamp.com/search?q={WebUtility.UrlEncode(query)}"
};
var json = await ScrapeJSONAsync(query).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(json))
{
result.LoadType = LoadType.LoadFailed;
return result;
}
var bcResult = JsonSerializer.Parse<BandCampResult>(json);
result.LoadType = bcResult.ItemType == "album" ? LoadType.PlaylistLoaded :
bcResult.ItemType == "track" ? LoadType.TrackLoaded : LoadType.NoMatches;
if (result.LoadType is LoadType.LoadFailed)
return result;
result.Playlist = bcResult.ToAudioPlaylist;
result.Tracks = bcResult.Tracks;
return result;
}
public async ValueTask<Stream> GetStreamAsync(string query)
{
if (!_trackUrlRegex.IsMatch(query))
return default;
var json = await ScrapeJSONAsync(query).ConfigureAwait(false);
var bcResult = JsonSerializer.Parse<BandCampResult>(json);
var track = bcResult.Trackinfo.FirstOrDefault();
if (track is null)
return default;
var stream = await Singleton.Of<HttpHandler>()
.GetStreamAsync(track.File.Mp3Url).ConfigureAwait(false);
return stream;
}
private async ValueTask<string> ScrapeJSONAsync(string url)
{
var rawHtml = await Singleton.Of<HttpHandler>()
.GetStringAsync(url).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(rawHtml))
return string.Empty;
const string startStr = "var TralbumData = {",
endStr = "};";
if (rawHtml.IndexOf(startStr) == -1)
return string.Empty;
var tempData = rawHtml.Substring(rawHtml.IndexOf(startStr) + startStr.Length - 1);
tempData = tempData.Substring(0, tempData.IndexOf(endStr) + 1);
var jsonReg = new Regex(@"([a-zA-Z0-9_]*:\s)(?!\s)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var commentReg = new Regex(@"\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
tempData = commentReg.Replace(tempData, "");
var matches = jsonReg.Matches(tempData);
foreach (Match match in matches)
{
var val = string.Format("\"{0}\":", match.Value.Replace(": ", ""));
var regex = new Regex(Regex.Escape(match.Value), RegexOptions.Compiled | RegexOptions.IgnoreCase);
tempData = regex.Replace(tempData, val, 1);
}
tempData = tempData.Replace("\" + \"", "");
return tempData;
}
}
} |
using CefSharp;
using CefSharp.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Telegram.Bot;
namespace ParserNowgoal
{
/// <summary>
/// Interaction logic for BrowserWindow.xaml
/// </summary>
public partial class BrowserWindow : Window
{
MainWindow _mw;
public BrowserWindow(MainWindow mw)
{
InitializeComponent();
_mw = mw;
Cef.EnableHighDPISupport();
}
public async void Algorithm(object param)
{
var instanceAndCts = (List<object>)param;
var instance = (MainWindow)instanceAndCts[0];
var cts = (CancellationToken)instanceAndCts[1];
string mainScript, api = "959846286:AAFvG7s6rS8zTUgMdWn6IA4NCE5-uVL6q8w";
var ids = new List<string>();
using (StreamReader r = new StreamReader(@"MainScript.js"))
{
mainScript = await r.ReadToEndAsync();
}
using (StreamReader sr = new StreamReader(@"IDs.txt"))
{
var temp = await sr.ReadToEndAsync();
ids = temp.Split('\n').ToList();
}
TelegramBotClient botClient = new TelegramBotClient(api);
while (!cts.IsCancellationRequested)
{
try
{
instance.UpdateStatus("Поиск матчей...");
Thread.Sleep(500);
var json = await EvaluateScript(mainScript);
var content = JsonConvert.DeserializeObject<List<Match>>(json);
instance.UpdateName(await EvaluateScript("var e = document.getElementById(\"CompanySel\");e.options[e.selectedIndex].innerText"));
for (int i = 0; i < content.Count; i++)
{
if (instance.AddRow(content[i]))
{
var temp = content[i];
/*foreach (var id in ids.Where(n => n.Length > 1))
{
await botClient.SendTextMessageAsync(chatId: id,
$"Команды: {temp.Team}\n" +
$"Параметры:\nHT = {temp.HT}\nX = {temp.X}\nJ = {temp.J}" +
$"\nY = {temp.Y}\nZ = {temp.Z}\nW = {temp.W}\n" +
$"Ссылка на событие: {temp.URL}");
}*/
}
}
instance.UpdateStatus("Ожидание...");
Thread.Sleep(1500);
}
catch
{
Thread.Sleep(3000);
}
}
}
async Task<string> EvaluateScript(string script)
{
string toReturn = null;
//We need to bu sure that V8 was fully loaded
while (true)
{
if (ChromiumWebBrowser.CanExecuteJavascriptInMainFrame)
{
await ChromiumWebBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
toReturn = response.Result.ToString();
}
});
break;
}
else Thread.Sleep(500);
}
if (toReturn == null)
{
toReturn = "fuck";
}
return toReturn;
}
private Task LoadPageAsync(string address = null)
{
var tcs = new TaskCompletionSource<bool>();
EventHandler<LoadingStateChangedEventArgs> handler = null;
handler += (sender, args) =>
{
//Wait for while page to finish loading not just the first frame
if (!args.IsLoading)
{
ChromiumWebBrowser.LoadingStateChanged -= handler;
tcs.TrySetResult(true);
}
};
ChromiumWebBrowser.LoadingStateChanged += handler;
if (!string.IsNullOrEmpty(address))
{
ChromiumWebBrowser.Load(address);
}
return tcs.Task;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (_mw.IsVisible)
{
e.Cancel = true;
}
}
}
}
|
using NuGet.Protocol.Core.Types;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using NuGet.Protocol.Core.v3;
namespace Client.V3Test
{
public class RegistrationResourceTests : TestBase
{
[Fact]
public async Task RegistrationResource_NotFound()
{
var repo = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
var resource = repo.GetResource<RegistrationResourceV3>();
var package = await resource.GetPackageMetadata(new PackageIdentity("notfound23lk4j23lk432j4l", new NuGetVersion(1, 0, 99)), CancellationToken.None);
Assert.Null(package);
}
[Fact]
public async Task RegistrationResource_Tree()
{
var repo = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
var resource = repo.GetResource<RegistrationResourceV3>();
var packages = await resource.GetPackageMetadata("ravendb.client", true, false, CancellationToken.None);
var results = packages.ToArray();
Assert.True(results.Length > 500);
}
[Fact]
public async Task RegistrationResource_TreeFilterOnPre()
{
var repo = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
var resource = repo.GetResource<RegistrationResourceV3>();
var packages = await resource.GetPackageMetadata("ravendb.client", false, false, CancellationToken.None);
var results = packages.ToArray();
Assert.True(results.Length < 500);
}
[Fact]
public async Task RegistrationResource_NonTree()
{
var repo = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
var resource = repo.GetResource<RegistrationResourceV3>();
var packagesPre = await resource.GetPackageMetadata("newtonsoft.json", true, false, CancellationToken.None);
var packages = await resource.GetPackageMetadata("newtonsoft.json", false, false, CancellationToken.None);
var results = packages.ToArray();
var resultsPre = packagesPre.ToArray();
Assert.True(results.Length > 10);
Assert.True(results.Length < resultsPre.Length);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
namespace Party_Reservation_Filter_Module
{
class Program
{
static void Main(string[] args)
{
List<string> filters = new List<string>();
List<string> peoples = new List<string>();
peoples = Console.ReadLine().Split(" ").ToList();
string input;
while ((input=Console.ReadLine())!="Print")
{
string[] comand = input.Split(";");
if (comand[0]=="Add filter")
{
filters.Add(comand[1] + ";" + comand[2]);
}
else
{
filters.Remove(comand[1] + ";" + comand[2]);
}
}
for (int i = 0; i < filters.Count; i++)
{
string[] currentFilter = filters[i].Split(";");
peoples = Filter(peoples, currentFilter);
}
Console.WriteLine(string.Join(" ", peoples));
}
static Func<string, string, bool> Comand(string[] comand)
{
if (comand[0] == "Starts with")
{
return (x, y) => x.Substring(0, y.Length) == y;
}
else if (comand[0] == "Ends with")
{
return (x, y) => x.Substring(x.Length - y.Length, y.Length) == y;
}
else if(comand[0]=="Lenght")
{
return (x, y) => x.Length == int.Parse(y);
}
else
{
return (x, y) => x.Contains(y);
}
}
static List<string> Filter(List<string> peoples, string[] comand)
{
Func<string, string, bool> func = Comand(comand);
for (int i = 0; i < peoples.Count; i++)
{
if (func(peoples[i],comand[1]))
{
peoples.RemoveAt(i);
i--;
}
}
return peoples;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.