text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MenuToGame : MonoBehaviour { [SerializeField] GameObject loadingSet; [SerializeField] RectTransform slider; [SerializeField] GameObject thisGuy; [SerializeField] ParticleSystem manyParticles; // Start is called before the first frame update public void Tran_SITION(int index) { iTween.PunchScale(thisGuy, iTween.Hash("z", 10f, "amount", thisGuy.transform.localScale)); loadingSet.SetActive(true); StartCoroutine(Transicao(index)); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) { FindObjectOfType<AudioManager>().Play("re"); Tran_SITION(1); } } IEnumerator Transicao(int buildNumber) { //var em = manyParticles.emission; //em.rateOverTime = 90; manyParticles.gameObject.SetActive(false); //slider.offsetMax += new Vector2(-10f * Time.deltaTime, slider.offsetMax.y); //print("Ema"); yield return new WaitForSeconds(5f); AsyncOperation operacao = SceneManager.LoadSceneAsync(buildNumber); while (!operacao.isDone) { float progresso = Mathf.Clamp01(operacao.progress / 0.9f); slider.offsetMax -= new Vector2(progresso * -1500f * Time.deltaTime, slider.offsetMax.y); //xRect.x = Mathf.Clamp(xRect.x, 0f, 1366f); yield return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace ReaderMockUp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private bool _cancelled; private TcpListener _listener; public MainWindow() { InitializeComponent(); var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); cmbIps.ItemsSource = ipHostInfo.AddressList.Where(i => !i.IsIPv6LinkLocal).Select(i => i.ToString()).ToList(); } private void Button_Click(object sender, RoutedEventArgs e) { if (cmbIps.SelectedItem == null || string.IsNullOrEmpty(tbPort.Text)) return; btnStart.IsEnabled = false; btnStop.IsEnabled = true; var tag = Convert.ToString(new Random().Next(1, 15), 16); _listener = new TcpListener(IPAddress.Parse(cmbIps.SelectedItem.ToString()), int.Parse(tbPort.Text)); _listener.Start(); var seconds = int.Parse(tbMps.Text); Task.Factory.StartNew(() => { var client = _listener.AcceptTcpClient(); while (!_cancelled) { try { for (var i = 1; i < seconds; i++) { var stream = client.GetStream(); //var ut = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; ; //string response = "\xA0"+tag+"," + ut * 1000 + ",-52\r\n"; var data = new List<byte> { 160, 19, 1, 137, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) i, 8 }; data.Add(CheckSum(data.ToArray(), 0, data.Count)); stream.Write(data.ToArray(), 0, data.Count); //client.Close(); } Thread.Sleep(1000); } catch (Exception) { break; } } _listener.Stop(); }); } private void Button_Click_1(object sender, RoutedEventArgs e) { btnStart.IsEnabled = true; btnStop.IsEnabled = false; _cancelled = true; } public byte CheckSum(byte[] btAryBuffer, int nStartPos, int nLen) { byte btSum = 0x00; for (var nloop = nStartPos; nloop < nStartPos + nLen; nloop++) { btSum += btAryBuffer[nloop]; } return Convert.ToByte((~btSum + 1) & 0xFF); } } }
using System; using System.Linq; using TheSlum.Interfaces; namespace TheSlum.Characters { public class Healer : Character, IHeal { private const int HealthPp = 75; private const int DefPoints = 50; private const int HPoints = 60; private const int RanPoints = 6; public Healer(string id, int x, int y, Team team) : base(id, x, y, HealthPp, DefPoints, team, RanPoints) { this.HealingPoints = HPoints; } public override Character GetTarget(System.Collections.Generic.IEnumerable<Character> targetsList) { var target = targetsList.OrderBy(t => t.HealthPoints).LastOrDefault(tar => (tar.Team == this.Team && tar.IsAlive && tar !=this)); return target; } public override void AddToInventory(Item item) { this.Inventory.Add(item); ApplyItemEffects(item); } protected override void ApplyItemEffects(Item item) { base.ApplyItemEffects(item); this.HealingPoints += item.HealthEffect; } protected override void RemoveItemEffects(Item item) { base.RemoveItemEffects(item); this.HealingPoints -= item.HealthEffect; } public override void RemoveFromInventory(Item item) { this.Inventory.Remove(item); RemoveItemEffects(item); } public override string ToString() { string retStr = base.ToString(); retStr += String.Format(", Healing: {0}", this.HealingPoints); return retStr; } public int HealingPoints { get; set; } } }
namespace WebApplication1.Models { public class Item { #region public properties public int RecordId { get; set; } public string ItemID { get; set; } public string Misc1 { get; set; } public string Misc2 { get; set; } public string Misc3 { get; set; } public string Misc4 { get; set; } public string Misc5 { get; set; } public int TaxCode { get; set; } public string Description { get; set; } public int Qty { get; set; } public double Price { get; set; } public string TransCode { get; set; } public double Cost { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MOTHER3; using Extensions; namespace MOTHER3Funland { public partial class frmBattleBgLayerEditor : M3Form { bool loading = false; bool expanded = false; public frmBattleBgLayerEditor() { InitializeComponent(); // Load the layer entries loading = true; for (int i = 0; i < GfxBattleBg.Entries; i++) { cboEntry.Items.Add(i.ToString("X2")); } loading = false; cboEntry.SelectedIndex = 0; } private void mnuGraphicsSave_Click(object sender, EventArgs e) { Helpers.GraphicsSave(sender, dlgSaveImage); } private void mnuGraphicsCopy_Click(object sender, EventArgs e) { Helpers.GraphicsCopy(sender); } private void cboEntry_SelectedIndexChanged(object sender, EventArgs e) { if (loading) return; int index = cboEntry.SelectedIndex; var bg = GfxBattleBg.Bgs[index]; //pLayer.Image = GfxBattleBg.GetLayer(index); txtGfxEntry.Text = bg.GfxEntry.ToString(); txtArrEntry.Text = bg.ArrEntry.ToString(); txtPalDir.Text = bg.PalDir.ToString(); txtPalStart.Text = bg.PalStart.ToString(); txtPalEnd.Text = bg.PalEnd.ToString(); txtPalDelay.Text = bg.PalDelay.ToString(); txtDriftH.Text = bg.DriftH.ToString(); txtDriftV.Text = bg.DriftV.ToString(); txtAmplH.Text = bg.AmplH.ToString(); txtAmplV.Text = bg.AmplV.ToString(); txtFreqH.Text = bg.FreqH.ToString(); txtFreqV.Text = bg.FreqV.ToString(); txtWavenumH.Text = bg.WavenumH.ToString(); txtWavenumV.Text = bg.WavenumV.ToString(); // Arrangement stuff arrEditor.Clear(); int[] gfxEntry = GfxBattleBgTable.GetEntry(bg.GfxEntry); arrEditor.SetTileset(M3Rom.Rom, gfxEntry[0], gfxEntry[1] >> 5); arrEditor.SetArrangement(GfxBattleBgTable.GetArr(bg.ArrEntry), 32, 32); arrEditor.SetPalette(bg.Palette); arrEditor.RenderArr(); arrEditor.RenderTileset(); arrEditor.CurrentTile = 0; arrEditor.RefreshArr(); } public override void SelectIndex(int[] index) { // 0: Layer index // 1: Expanded // 2: Palette index // 3: Tile index // 4: splitMain position // 5: splitLeft position // 6: Arrangement grid // 7: Arrangement zoom // 8: Tileset grid // 9: Tileset zoom // 10: Tile grid // 11: Tile zoom cboEntry.SelectedIndex = index[0]; if (index.Length == 1) return; if (index[1] == 1) lblAnim_Click(null, null); arrEditor.CurrentPalette = index[2]; arrEditor.CurrentTile = index[3]; arrEditor.SplitMainPosition = index[4]; arrEditor.SplitLeftPosition = index[5]; arrEditor.GridArr = index[6] != 0; arrEditor.ZoomArr = index[7]; arrEditor.GridTileset = index[8] != 0; arrEditor.ZoomTileset = index[9]; arrEditor.GridTile = index[10] != 0; arrEditor.ZoomTile = index[11]; } public override int[] GetIndex() { return new int[] { cboEntry.SelectedIndex, (expanded ? 1 : 0), arrEditor.CurrentPalette, arrEditor.CurrentTile, arrEditor.SplitMainPosition, arrEditor.SplitLeftPosition, arrEditor.GridArr ? 1 : 0, arrEditor.ZoomArr, arrEditor.GridTileset ? 1 : 0, arrEditor.ZoomTileset, arrEditor.GridTile ? 1 : 0, arrEditor.ZoomTile }; } private void btnApply_Click(object sender, EventArgs e) { int index = cboEntry.SelectedIndex; var bg = GfxBattleBg.Bgs[index]; // Gfx entry /*try { bg.GfxEntry = ushort.Parse(txtGfxEntry.Text); } catch { txtGfxEntry.SelectAll(); return; } // Arr entry try { bg.ArrEntry = ushort.Parse(txtArrEntry.Text); } catch { txtArrEntry.SelectAll(); return; }*/ // Pal dir try { bg.PalDir = ushort.Parse(txtPalDir.Text); } catch { txtPalDir.SelectAll(); return; } // Pal start try { bg.PalStart = ushort.Parse(txtPalStart.Text); } catch { txtPalStart.SelectAll(); return; } // Pal end try { bg.PalEnd = ushort.Parse(txtPalEnd.Text); } catch { txtPalEnd.SelectAll(); return; } // Pal delay try { bg.PalDelay = ushort.Parse(txtPalDelay.Text); } catch { txtPalDelay.SelectAll(); return; } // Drift H try { bg.DriftH = short.Parse(txtDriftH.Text); } catch { txtDriftH.SelectAll(); return; } // Drift V try { bg.DriftV = short.Parse(txtDriftV.Text); } catch { txtDriftV.SelectAll(); return; } // Ampl H try { bg.AmplH = short.Parse(txtAmplH.Text); } catch { txtAmplH.SelectAll(); return; } // Ampl V try { bg.AmplV = short.Parse(txtAmplV.Text); } catch { txtAmplV.SelectAll(); return; } // Freq H try { bg.FreqH = short.Parse(txtFreqH.Text); } catch { txtFreqH.SelectAll(); return; } // Freq V try { bg.FreqV = short.Parse(txtFreqV.Text); } catch { txtFreqV.SelectAll(); return; } // Wavenum H try { bg.WavenumH = short.Parse(txtWavenumH.Text); } catch { txtWavenumH.SelectAll(); return; } // Wavenum V try { bg.WavenumV = short.Parse(txtWavenumV.Text); } catch { txtWavenumV.SelectAll(); return; } if (index > 0) { // Arrangement GfxBattleBgTable.SetArr(bg.ArrEntry, arrEditor.GetArrangement()); // Graphics int gfxPointer = GfxBattleBgTable.GetEntry(bg.GfxEntry)[0]; arrEditor.GetTileset(M3Rom.Rom, gfxPointer); // Palette bg.Palette = arrEditor.GetPalette(); } bg.Save(); int currentpal = arrEditor.CurrentPalette; int currenttile = arrEditor.CurrentTile; int primarycol = arrEditor.PrimaryColorIndex; int secondarycol = arrEditor.SecondaryColorIndex; cboEntry_SelectedIndexChanged(null, null); arrEditor.CurrentPalette = currentpal; arrEditor.PrimaryColorIndex = primarycol; arrEditor.SecondaryColorIndex = secondarycol; arrEditor.CurrentTile = currenttile; } private void lblAnim_Click(object sender, EventArgs e) { if (expanded) { // Let's collapse it lblAnim.Text = "[ + ] Animation parameters"; grpAnim.Height = 18; } else { // Let's expand it lblAnim.Text = "[ - ] Animation parameters"; grpAnim.Height = 180; } arrEditor.Top = grpAnim.Top + grpAnim.Height + 6; arrEditor.Height = btnApply.Top - arrEditor.Top - 6; expanded = !expanded; } } }
using System.Collections.Generic; using EPI.BinaryTree; namespace EPI.Recursion { /// <summary> /// Write a function that takes a positive integer n and returns all distinct binary trees with n nodes /// </summary> public static class EnumerateBinaryTree<T> { public static List<BinaryTreeNode<T>> FindAllBinaryTrees(int n) { if (n <= 0) { return null; } List<BinaryTreeNode<T>> result = ListAllBinaryTreeHelper(1, n); return result; } private static List<BinaryTreeNode<T>> ListAllBinaryTreeHelper(int start, int end) { List<BinaryTreeNode<T>> result = new List<BinaryTreeNode<T>>(); // base case: add tree by iterating current node;'s parent to result if (start > end) { result.Add(null); return result; } else { for (int i = start; i <= end; i++) { var leftTreeResults = ListAllBinaryTreeHelper(start, i - 1); var rightTreeResults = ListAllBinaryTreeHelper(i + 1, end); foreach (var left in leftTreeResults) { foreach (var right in rightTreeResults) { result.Add(new BinaryTreeNode<T>(default(T)) { Left = left, Right = right }); } } } return result; } } } }
using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; using Prism.Navigation; namespace HW04.ViewModels { public class NewPageViewModel : BindableBase, INavigationAware { #region DateTimeNow private string _DateTimeNow; /// <summary> /// DateTimeNow /// </summary> public string DateTimeNow { get { return this._DateTimeNow; } set { this.SetProperty(ref this._DateTimeNow, value); } } #endregion public NewPageViewModel() { } public void OnNavigatedFrom(NavigationParameters parameters) { throw new NotImplementedException(); } public void OnNavigatedTo(NavigationParameters parameters) { if (parameters.ContainsKey("Now")) { var t = parameters["Now"] as DateTime?; DateTimeNow = $"現在時間 {t}"; } else { DateTimeNow = "沒參數"; } } } }
using DatVentas; using EntVenta; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusVenta { public class BusEmpresa { public void Agregar_Empresa(Empresa e) { int filasAfectadas = new DatEmpresa().Agregar_Empresa(e); if (filasAfectadas != 1) { throw new ApplicationException("Ocurrio un error al insertar"); } } public void Actualizar_Empresa(Empresa e) { int filasAfectadas = new DatEmpresa().EditarEmpresa(e); if (filasAfectadas != 1) { throw new ApplicationException("Ocurrio un error al insertar"); } } public Empresa ObtenerEmpresa() { DataRow dtEmpresa = new DatEmpresa().MostraEmpresa(); Empresa e = new Empresa(); e.Id = Convert.ToInt32( dtEmpresa["Id_Empresa"] ); e.Nombre = dtEmpresa["Empresa"].ToString(); e.Logo = (byte[])(dtEmpresa["Logo"]); e.Impuesto = dtEmpresa["Impuesto"].ToString(); e.Porcentaje = Convert.ToDecimal( dtEmpresa["Porcentaje_Impuesto"] ); e.Moneda = dtEmpresa["Moneda"].ToString(); e.Usa_Impuestos = dtEmpresa["Maneja_Impuesto"].ToString(); e.Busqueda = dtEmpresa["Modo_Busqueda"].ToString(); e.RutaBackup = dtEmpresa["Ruta_CopiaSeguridad"].ToString(); e.Pais = dtEmpresa["Pais"].ToString(); e.FrecuenciaBackup = Convert.ToInt32(dtEmpresa["Frecuencia_Respaldo"]); e.CorreoEnvio = dtEmpresa["Correo_EnvioReporte"].ToString(); return e; } } }
using System.Collections; using System.Collections.Generic; using BP12.Events; using DChild.Gameplay.Combat; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class GemCrawler : Minion { [SerializeField] [MinValue(0f)] [TabGroup("Attack")] private float m_attackFinishRest; [SerializeField] [TabGroup("Attack")] private GameObject m_crystalAttack; [SerializeField] private float m_scoutDuration; [SerializeField] private DamageFXType m_damageType; [SerializeField] private AttackDamage m_damage; private GemCrawlerAnimation m_animation; private ITurnHandler m_turn; private ICharacterTime m_characteraTime; private PhysicsMovementHandler2D m_movement; private EnemyBehaviourHandler m_behaviourHandler; protected override CharacterAnimation animation => m_animation; public bool isAttacking => m_animation.isAttackAnimationPlaying; public void LookAt(Vector2 target) { m_behaviourHandler.SetActiveBehaviour(StartCoroutine(TurnRoutine(target))); } public void Patrol(Vector2 position, float speed) { m_movement.MoveTo(position, speed); } public void Attack(IDamageable target) { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(CrystalAttackRoutine(target))); } public void Scout() { m_movement.Stop(); if (!isAttacking) { Debug.Log("Near"); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(ScoutRoutine())); } } private void Flinch() { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(Wait())); } private IEnumerator Wait() { m_waitForBehaviourEnd = true; yield return new WaitForSeconds(1f); m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } private IEnumerator CrystalAttackRoutine(IDamageable target) { m_waitForBehaviourEnd = true; m_movement.Stop(); //yield return new WaitForAnimationEvent yield return null; m_turn.LookAt(target.position); m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } private IEnumerator ScoutRoutine() { m_waitForBehaviourEnd = true; m_movement.Stop(); //Do idle yield return new WaitForSeconds(m_scoutDuration); m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } private IEnumerator DeathRoutine() { m_waitForBehaviourEnd = true; m_movement.Stop(); //Do animation death yield return null; m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } private IEnumerator TurnRoutine(Vector2 destination) { yield return new WaitForSeconds(m_scoutDuration); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_waitForBehaviourEnd = true; m_turn.LookAt(destination); yield return null; m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } protected override void OnTakeExternalDamage(DamageSource source) { Flinch(); base.OnTakeExternalDamage(source); } protected override void GetAttackInfo(out AttackInfo attackInfo, out DamageFXType fxType) { fxType = m_damageType; attackInfo = new AttackInfo(m_damage, 0, null, null); } protected override EventActionArgs OnDeath(object sender, EventActionArgs eventArgs) { base.OnDeath(sender, eventArgs); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(DeathRoutine())); return eventArgs; } protected override void InitializeMinion() { m_health.InitializeHealth(); } protected override void Awake() { base.Awake(); m_movement = new PhysicsMovementHandler2D(GetComponent<ObjectPhysics2D>(), transform); m_behaviourHandler = new EnemyBehaviourHandler(this); m_turn = new SimpleTurnHandler(this); m_characteraTime = GetComponent<ICharacterTime>(); m_animation = GetComponent<GemCrawlerAnimation>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; namespace StarlightRiver.Tiles.Vitric { class AncientSandstone : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = true; Main.tileBlockLight[Type] = true; minPick = int.MaxValue; Main.tileMerge[Type][ModContent.TileType<VitricSand>()] = true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using CapaDatos; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Tulpep.NotificationWindow; namespace CapaUsuario.Compras.Orden_de_Compra { public partial class FrmOrdenDeCompra : Form { DOrdenCompra ordenCompra = new DOrdenCompra(); private DSolicitudCompra solicitud; private DPedidoReaprov pedido; private bool isPedido; private DCotizacionSC cotSC; private DCotizacionPR cotPR; public FrmOrdenDeCompra() { InitializeComponent(); } private void FrmOrdenDeCompra_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; CargarListados(); FrmOrdenDeCompra_SizeChanged(sender, e); //PersonalizarGrids(); } private void PersonalizarGridDetalle() { if (isPedido) { DgvDetalleCompra.Columns["CodStock"].HeaderText = "Código de producto"; } else { DgvDetalleCompra.Columns["CodBienUso"].HeaderText = "Código de bien de uso"; } } private void PersonalizarGridCotizacion() { Dgv2.Columns["CodCotizacion"].HeaderText = "Código de cotización"; } private void CargarListados() { CargarOrdenes(); CargarSolicitudes(); CargarPedidos(); } private void CargarSolicitudes() { solicitud = new DSolicitudCompra(); DgvSolicitudes.DataSource = solicitud.SelectSCSinOrdenCompra(); DgvSolicitudes.Refresh(); } private void CargarOrdenes() { DgvOrdenesCompra.DataSource = ordenCompra.SelectOrdenesCompra(); DgvOrdenesCompra.Refresh(); } private void CargarPedidos() { pedido = new DPedidoReaprov(); DgvPedidos.DataSource = pedido.SelectPRSinOrdenCompra(); DgvPedidos.Refresh(); } private void FrmOrdenDeCompra_SizeChanged(object sender, EventArgs e) { DgvOrdenesCompra.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DgvSolicitudes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DgvPedidos.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DgvDetalleCompra.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; Dgv2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } private void PedidoRadioButton_CheckedChanged(object sender, EventArgs e) { if (PedidoRadioButton.Checked) { DgvOrdenesCompra.DataSource = ordenCompra.SelectOrdenesCompraByTipo("PR"); DgvOrdenesCompra.Refresh(); } else if (SolicitudRadioButton.Checked) { DgvOrdenesCompra.DataSource = ordenCompra.SelectOrdenesCompraByTipo("SC"); DgvOrdenesCompra.Refresh(); } else { CargarOrdenes(); } } private void SolicitudRadioButton_CheckedChanged(object sender, EventArgs e) { if (SolicitudRadioButton.Checked) { DgvOrdenesCompra.DataSource = ordenCompra.SelectOrdenesCompraByTipo("SC"); DgvOrdenesCompra.Refresh(); } else if (PedidoRadioButton.Checked) { DgvOrdenesCompra.DataSource = ordenCompra.SelectOrdenesCompraByTipo("PR"); DgvOrdenesCompra.Refresh(); } else { CargarOrdenes(); } } private void CrearOrdenPedidoButton_Click(object sender, EventArgs e) { if (DgvPedidos.RowCount == 0) { MessageBox.Show("No hay pedidos", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } isPedido = true; DeshabilitarBotones(); materialTabControl1.SelectedTab = TabNueva; var stock = new DStockPedidoReaprov(); DgvDetalleCompra.DataSource = stock.GetStockEnPedidoReaprov((int)DgvPedidos.SelectedRows[0].Cells[0].Value); DgvDetalleCompra.Refresh(); PersonalizarGridDetalle(); } private void CrearOrdenSolicitudButton_Click(object sender, EventArgs e) { if (DgvSolicitudes.RowCount == 0) { MessageBox.Show("No hay solicitudes", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } isPedido = false; DeshabilitarBotones(); materialTabControl1.SelectedTab = TabNueva; var bienUso = new DSolicitudBienUso(); DgvDetalleCompra.DataSource = bienUso.GetBienesUsoEnSolicitudCompra((int)DgvSolicitudes.SelectedRows[0].Cells[0].Value); DgvDetalleCompra.Refresh(); } private void DgvDetalleCompra_SelectionChanged(object sender, EventArgs e) { try { if (isPedido) { cotPR = new DCotizacionPR(); Dgv2.DataSource = cotPR.SelectCotizacionesPRByCodStockAndCodPR((int)DgvDetalleCompra.SelectedRows[0].Cells[0].Value , (int)DgvPedidos.SelectedRows[0].Cells[0].Value); Dgv2.Refresh(); PersonalizarGridCotizacion(); } else { cotSC = new DCotizacionSC(); Dgv2.DataSource = cotSC.SelectCotizacionesSCByCodBienUsoAndCodSC((int)DgvDetalleCompra.SelectedRows[0].Cells[0].Value, (int)DgvSolicitudes.SelectedRows[0].Cells[0].Value); Dgv2.Refresh(); } } catch (Exception ex) { //MessageBox.Show($"Error: {ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void DeshabilitarBotones() { CrearOrdenPedidoButton.Enabled = false; CrearOrdenSolicitudButton.Enabled = false; EmitirButton.Enabled = false; BorrarOrdenButton.Enabled = false; ConfirmarOrdenButton.Enabled = true; CancelarButton.Enabled = true; } private void HabilitarBotones() { CrearOrdenPedidoButton.Enabled = true; CrearOrdenSolicitudButton.Enabled = true; EmitirButton.Enabled = true; BorrarOrdenButton.Enabled = true; ConfirmarOrdenButton.Enabled = false; CancelarButton.Enabled = false; } private void CancelarButton_Click(object sender, EventArgs e) { LimpiarGridsDetalles(); HabilitarBotones(); } private void LimpiarGridsDetalles() { DgvDetalleCompra.DataSource = null; Dgv2.DataSource = null; DgvDetalleCompra.Refresh(); Dgv2.Refresh(); } private void ConfirmarOrdenButton_Click(object sender, EventArgs e) { for (int i = 0; i < DgvDetalleCompra.RowCount; i++) { DataTable dtDetalle = (DataTable)DgvDetalleCompra.DataSource; var codProducto = 0; var codCotizacion = 0; decimal precioCot; // Comprobamos que todos los productos de la orden de compra tengan una cotización if (isPedido) { codProducto = (int)dtDetalle.Rows[i]["CodStock"]; cotPR = new DCotizacionPR(); var dtCot = cotPR.SelectCotizacionesPRByCodStockAndCodPR(codProducto , (int)DgvPedidos.SelectedRows[0].Cells[0].Value); codCotizacion = (int)dtCot.Rows[0]["CodCotizacion"]; precioCot = cotPR.GetPrecioCotizadoByCodCotizacionPR(codProducto, codCotizacion); if (precioCot <= 0) { MessageBox.Show("Alguno de los productos del detalle de orden de compra no tiene una cotización." + Environment.NewLine + "Revise las cotizaciones.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); CancelarButton_Click(sender, e); return; } } else { codProducto = (int)dtDetalle.Rows[i]["CodBienUso"]; cotSC = new DCotizacionSC(); var dtCot = cotPR.SelectCotizacionesPRByCodStockAndCodPR(codProducto , (int)DgvSolicitudes.SelectedRows[0].Cells[0].Value); codCotizacion = (int)dtCot.Rows[0]["CodCotizacion"]; precioCot = cotSC.GetPrecioCotizadoByCodBienUsoSC(codProducto, codCotizacion); if (precioCot <= 0) { MessageBox.Show("Alguno de los productos del detalle de orden de compra no tiene una cotización." + Environment.NewLine + "Revise las cotizaciones.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); CancelarButton_Click(sender, e); return; } } } var rta = MessageBox.Show("¿Realizar orden de compra?", "Confirmación", MessageBoxButtons.YesNo , MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; string msg; try { int codOrdenCompra = ordenCompra.InsertOrdenCompra(false, isPedido ? "PR" : "SC"); if (isPedido) { cotPR.UpdateCotizacionPR((int)DgvPedidos.SelectedRows[0].Cells[0].Value, codOrdenCompra); } else { cotSC.UpdateCotizacionSC((int)DgvSolicitudes.SelectedRows[0].Cells[0].Value, codOrdenCompra); } msg = "Se ingresó la orden de compra correctamente"; } catch (Exception ex) { msg = "Error al ingresar la orden de compra"; MessageBox.Show($"ERROR: {ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } var popup1 = new PopupNotifier() { Image = msg == "Se ingresó la orden de compra correctamente" ? Properties.Resources.sql_success1 : Properties.Resources.sql_error, TitleText = "Mensaje", ContentText = msg, ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(10) }; popup1.Popup(); HabilitarBotones(); LimpiarGridsDetalles(); CargarListados(); } private void BorrarOrdenButton_Click(object sender, EventArgs e) { if (DgvOrdenesCompra.RowCount == 0) { MessageBox.Show("No hay órdenes de compra a borrar", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((bool)DgvOrdenesCompra.SelectedRows[0].Cells[1].Value) { MessageBox.Show("No se puede borrar la orden de compra, se encuentra emitida", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var rta = MessageBox.Show("¿Borrar orden de compra?", "Confirmación", MessageBoxButtons.YesNo , MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; try { ordenCompra.DeleteOrdenCompra((int)DgvOrdenesCompra.SelectedRows[0].Cells[0].Value); var popup1 = new PopupNotifier() { Image = Properties.Resources.info100, TitleText = "Mensaje", ContentText = "Se eliminó la orden de compra correctamente", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), }; popup1.Popup(); } catch (Exception ex) { MessageBox.Show($"ERROR: {ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } CargarListados(); } private void EmitirButton_Click(object sender, EventArgs e) { if (DgvOrdenesCompra.RowCount == 0) { MessageBox.Show("No hay órdenes de compra a emitir", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var rta = MessageBox.Show("¿Emitir orden de compra?", "Confirmación", MessageBoxButtons.YesNo , MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; string msg = ordenCompra.EmitirOrdenCompra((int)DgvOrdenesCompra.SelectedRows[0].Cells[0].Value, DateTime.Now); var popup1 = new PopupNotifier() { Image = msg == "Se emitió la orden de compra correctamente" ? Properties.Resources.info100 : Properties.Resources.sql_error, TitleText = "Mensaje", ContentText = msg, ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), }; popup1.Popup(); CargarOrdenes(); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace KubeTest { public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { var configuration = context.RequestServices.GetRequiredService<IConfiguration>(); var secretKey = configuration.GetValue<string>("SecretKey"); if (context.Request.Path == "/up") { if (DateTime.UtcNow.Minute % 2 == 0) { await context.Response.WriteAsync("up"); } else { context.Response.StatusCode = StatusCodes.Status404NotFound; await context.Response.WriteAsync("down"); } } else { await context.Response.WriteAsync($"Hello World from {Environment.MachineName}. Secret Key: {secretKey}"); } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TimeClock.Data.Models { public class TimeClockSpan { public readonly DateTime _start; public readonly DateTime _end; public TimeClockSpan(DateTime start, DateTime end) { _start = start; _end = end; } public TimeSpan Span() { return (_start - _end); } } }
using MediaBrowser.Model.Dlna; namespace MediaBrowser.Model.MediaInfo { public class LiveStreamRequest { public string OpenToken { get; set; } public string UserId { get; set; } public string PlaySessionId { get; set; } public long? MaxStreamingBitrate { get; set; } public long? StartTimeTicks { get; set; } public int? AudioStreamIndex { get; set; } public int? SubtitleStreamIndex { get; set; } public int? MaxAudioChannels { get; set; } public string ItemId { get; set; } public DeviceProfile DeviceProfile { get; set; } public bool EnableDirectPlay { get; set; } public bool EnableDirectStream { get; set; } public MediaProtocol[] DirectPlayProtocols { get; set; } public LiveStreamRequest() { EnableDirectPlay = true; EnableDirectStream = true; DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; } public LiveStreamRequest(AudioOptions options) { MaxStreamingBitrate = options.MaxBitrate; ItemId = options.ItemId; DeviceProfile = options.Profile; MaxAudioChannels = options.MaxAudioChannels; DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; VideoOptions videoOptions = options as VideoOptions; if (videoOptions != null) { AudioStreamIndex = videoOptions.AudioStreamIndex; SubtitleStreamIndex = videoOptions.SubtitleStreamIndex; } } } }
namespace MovieRating.Data.Configurations { using Entities; public class UserRoleConfiguration:EntityBaseConfiguration<UserRole> { public UserRoleConfiguration() { Property(ur => ur.UserId).IsRequired(); Property(ur => ur.RoleId).IsRequired(); } } }
using System.Collections; using System.Collections.Generic; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Arithmetic { internal sealed partial class Lexer : IEnumerable<Token<RMathToken>> { private readonly StringeReader _reader; public Lexer(Stringe input) { _reader = new StringeReader(input); } public IEnumerator<Token<RMathToken>> GetEnumerator() { while (!_reader.EndOfStringe) { _reader.SkipWhiteSpace(); yield return _reader.ReadToken(Rules); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MinecraftToolsBoxSDK { public class ColorSlider : Slider { #region Public Methods static ColorSlider() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorSlider), new FrameworkPropertyMetadata(typeof(ColorSlider))); } #endregion #region Dependency Properties public Color LeftColor { get { return (Color)GetValue(LeftColorProperty); } set { SetValue(LeftColorProperty, value); } } public static readonly DependencyProperty LeftColorProperty = DependencyProperty.Register("LeftColor", typeof(Color), typeof(ColorSlider), new UIPropertyMetadata(Colors.Black)); public Color RightColor { get { return (Color)GetValue(RightColorProperty); } set { SetValue(RightColorProperty, value); } } public static readonly DependencyProperty RightColorProperty = DependencyProperty.Register("RightColor", typeof(Color), typeof(ColorSlider), new UIPropertyMetadata(Colors.White)); // TESTING // //public System.String Text //{ // get { return (System.String)GetValue(TextProperty); } // set { SetValue(TextProperty, value); } //} //// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc... //public static readonly DependencyProperty TextProperty = // DependencyProperty.Register("Text", typeof(System.String), typeof(ColorSlider), new UIPropertyMetadata("")); #endregion } }
using System; namespace NumberGame { class Program { static void Main(string[] args) { GetAppInfo(); GreedUser(); while (true) { // Generate Random Number Random random = new Random(); int correctNumber = random.Next(1, 10); // Initializing the Guessing number variable int guess = 0; // Ask user for number Console.WriteLine("Guess a number between 1 and 10"); while (guess != correctNumber) { // Get user Number string input = Console.ReadLine(); // Check the User input is only Number if (!int.TryParse(input, out guess)) { // call print color msg function PrintColorMsg(ConsoleColor.Red, "Please enter actual number"); continue; } // Convert input string into int guess = Int32.Parse(input); // Match guess to correct number if (guess != correctNumber) { // Tell USer its Wrong number PrintColorMsg(ConsoleColor.DarkRed, "Wrong Number!! Please Try Again"); } } // Success Msg // Changing the text color PrintColorMsg(ConsoleColor.Yellow, "Coorect Number"); // Ask if Play Again Console.WriteLine("Play Again? [ Y / N ]"); // Getting the user Input string answer = Console.ReadLine().ToUpper(); if(answer == "Y") { continue; } else if(answer == "N") { return; } else { return; } } } static void GetAppInfo() { // Setting up the application variables string appName = " Guess The Number "; string appVersion = "1.0.0"; string appAuthor = "Harjinder Gill"; // Changing the text color Console.ForegroundColor = ConsoleColor.Green; // Writintg the Info Console.WriteLine("{0}: Version {1} by {2}", appName, appVersion, appAuthor); // Getting text color Console.ResetColor(); } static void PrintColorMsg(ConsoleColor color, string message) { // Changing the text color Console.ForegroundColor = color; // Tell USer its Wrong User Input Console.WriteLine(message); // Getting text color Console.ResetColor(); } static void GreedUser() { // Ask Users name Console.WriteLine("What is Your name? "); // Getting the user Input string userInput = Console.ReadLine(); Console.WriteLine("Hello {0} Let's Play a game ...", userInput); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using gMediaTools.Services; using gMediaTools.Services.CurveFitting; namespace gMediaTools.Factories { public enum CurveFittingType { Logarithmic, Linear, PowerLaw } public class CurveFittingFactory { public ICurveFittingService GetCurveFittingService(CurveFittingType curveFittingType) { switch (curveFittingType) { case CurveFittingType.Logarithmic: return ServiceFactory.GetService<LogarithmicCurveFittingService>(); case CurveFittingType.Linear: break; case CurveFittingType.PowerLaw: return ServiceFactory.GetService<PowerLawCurveFittingService>(); default: break; } throw new ArgumentException($"Unsupported curveFittingType: {curveFittingType}", nameof(curveFittingType)); } } }
using CoreLib.Models; using DatabaseDAL.DataAccess; using HRM.Authentication; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HRM.Controllers { public class InsuranceController : Controller { // GET: Insurance [RequiredLogin] public ActionResult Index() { return View(); } [HttpGet] public ActionResult GetInsurance(InsuranceSocial insuranceSocial) { return Json(DatabaseInsurance.SearchInsurance(insuranceSocial), JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult InsertInsurance(InsuranceSocial insuranceSocial) { return Json(DatabaseInsurance.InsertInsurance(insuranceSocial)); } [HttpDelete] public ActionResult DeleteInsurance(int id) { return Json(DatabaseInsurance.DeleteInsurance(id)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; namespace PilerStationServices { [DataContract] public class CropConsultantsJSON { #region Properties [DataMember] public List<CropConsultant> cropConsultants { get; set; } /* [DataMember] public int employeeNum { get; set; } [DataMember] public string firstName { get; set; } [DataMember] public string lastName { get; set; } [DataMember] public string email { get; set; } [DataMember] public int district { get; set; } */ #endregion } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; public class LookAtCharacters : MonoBehaviour { private Transform target; public float maxAngle = 35.0f; private Quaternion baseRotation; private Quaternion targetRotation; void Start() { if (GameManager.level == 3) { maxAngle = maxAngle / 2f; } baseRotation = transform.rotation; target = GameObject.FindGameObjectWithTag("HeadCollider").GetComponent<Transform>(); } void Update() { Vector3 look = target.transform.position - transform.position; look.y = 0; Quaternion q = Quaternion.LookRotation(look); if (Quaternion.Angle(q, baseRotation) <= maxAngle) { targetRotation = q; } transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime); } }
using Aps.Models.api; using Aps.Repositories; using Aps.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace Aps.Controllers { [Route("api/[controller]")] [ApiController] public class UsuariosController : Controller { private readonly UsuariosRepo _repo; private readonly JwtService _jwtService; public UsuariosController(UsuariosRepo repo, JwtService jwtService) { _repo = repo; _jwtService = jwtService; } //Rota de login e geração do token [HttpPost("login")] public async Task<ActionResult<dynamic>> LogIn([FromBody] LogIn model) { try { var user = await _repo.ValidateLogIn(model.Email, model.Password); if (user == null) { return NotFound(new { message = "Usuário ou senha inválidos." }); } var token = _jwtService.GenerateToken(user); return new { token = token }; } catch (Exception e) { return BadRequest(e.Message); } } //Rota de criação de usuários [HttpPost("signup")] public async Task<ActionResult<dynamic>> SignUp([FromBody] UsuarioForm user) { try { var resp = await _repo.Create(user); return Ok(resp); } catch (Exception e) { return BadRequest(e.Message); } } [HttpDelete("{usuarioId}")] [Authorize] public async Task<ActionResult<dynamic>> Delete(int usuarioId) { var resp = await _repo.DeleteUsuario(usuarioId); return Ok(resp); } } }
using System; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Documentation { public class DocumentationFile : Entity { public virtual string FileName { get; set; } public virtual byte[] FileData { get; set; } public virtual string Title { get; set; } public virtual string Description { get; set; } public virtual DateTime LastModifiedDate { get; set; } public virtual DateTime UploadedDate { get; set; } public virtual AdminUser UploadedBy { get; set; } public virtual DocumentationFileTag DocumentationFileTag { get; set; } public virtual bool Archive { get; set; } } }
//----------------------------------------------------------------------- // <copyright file="ExtendDocumentWriter.cs" company="4Deep Technologies LLC"> // Copyright (c) 4Deep Technologies LLC. All rights reserved. // <author>Darren Ford</author> // <date>Thursday, April 30, 2015 3:00:44 PM</date> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dizzle.Cqrs.Core.Storage { public static class ExtendDocumentWriter { /// <summary> /// Given a <paramref name="key"/> either adds a new <typeparamref name="TEntity"/> OR updates an existing one. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="addFactory">The add factory (used to create a new entity, if it is not found).</param> /// <param name="update">The update method (called to update an existing entity, if it exists).</param> /// <param name="hint">The hint.</param> /// <returns></returns> public static TEntity AddOrUpdate<TKey, TEntity>(this IDocumentWriter<TKey, TEntity> self, TKey key, Func<TEntity> addFactory, Action<TEntity> update, AddOrUpdateHint hint = AddOrUpdateHint.ProbablyExists) { return self.AddOrUpdate(key, addFactory, entity => { update(entity); return entity; }, hint); } /// <summary> /// Given a <paramref name="key"/> either adds a new <typeparamref name="TEntity"/> OR updates an existing one. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="newView">The new view that will be saved, if entity does not already exist</param> /// <param name="updateViewFactory">The update method (called to update an existing entity, if it exists).</param> /// <param name="hint">The hint.</param> /// <returns></returns> public static TEntity AddOrUpdate<TKey, TEntity>(this IDocumentWriter<TKey, TEntity> self, TKey key, TEntity newView, Action<TEntity> updateViewFactory, AddOrUpdateHint hint = AddOrUpdateHint.ProbablyExists) { return self.AddOrUpdate(key, () => newView, view => { updateViewFactory(view); return view; }, hint); } /// <summary> /// Saves new entity, using the provided <param name="key"></param> and throws /// <exception cref="InvalidOperationException"></exception> if the entity actually already exists /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="newEntity">The new entity.</param> /// <returns></returns> public static TEntity Add<TKey, TEntity>(this IDocumentWriter<TKey, TEntity> self, TKey key, TEntity newEntity) { return self.AddOrUpdate(key, newEntity, e => { var txt = String.Format("Entity '{0}' with key '{1}' should not exist.", typeof(TEntity).Name, key); throw new InvalidOperationException(txt); }, AddOrUpdateHint.ProbablyDoesNotExist); } /// <summary> /// Updates already existing entity, throwing exception, if it does not already exist. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="change">The change.</param> /// <returns></returns> public static TEntity UpdateOrThrow<TKey, TEntity>(this IDocumentWriter<TKey, TEntity> self, TKey key, Func<TEntity, TEntity> change) { return self.AddOrUpdate(key, () => { var txt = String.Format("Failed to load '{0}' with key '{1}'.", typeof(TEntity).Name, key); throw new InvalidOperationException(txt); }, change, AddOrUpdateHint.ProbablyExists); } /// <summary> /// Updates already existing entity, throwing exception, if it does not already exist. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="change">The change.</param> /// <returns></returns> public static TEntity UpdateOrThrow<TKey, TEntity>(this IDocumentWriter<TKey, TEntity> self, TKey key, Action<TEntity> change) { return self.AddOrUpdate(key, () => { var txt = String.Format("Failed to load '{0}' with key '{1}'.", typeof(TEntity).Name, key); throw new InvalidOperationException(txt); }, change, AddOrUpdateHint.ProbablyExists); } /// <summary> /// Updates an entity, creating a new instance before that, if needed. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TView">The type of the view.</typeparam> /// <param name="self">The self.</param> /// <param name="key">The key.</param> /// <param name="update">The update.</param> /// <param name="hint">The hint.</param> /// <returns></returns> public static TView UpdateEnforcingNew<TKey, TView>(this IDocumentWriter<TKey, TView> self, TKey key, Action<TView> update, AddOrUpdateHint hint = AddOrUpdateHint.ProbablyExists) where TView : new() { return self.AddOrUpdate(key, () => { var view = new TView(); update(view); return view; }, v => { update(v); return v; }, hint); } public static TView UpdateEnforcingNew<TView>(this IDocumentWriter<unit, TView> self, Action<TView> update, AddOrUpdateHint hint = AddOrUpdateHint.ProbablyExists) where TView : new() { return self.UpdateEnforcingNew(unit.it, update, hint); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FrozenTimeCanvas : MonoBehaviour { public float startTime; //public Text timeText; public Image bg; public Slider slider; public int duration; // Start is called before the first frame update void Start() { startTime = Time.time; } // Update is called once per frame void Update() { float timeLeft = (duration - (Time.time - startTime)); Color fullBgColor = bg.color; fullBgColor.a = (timeLeft / duration)/2; bg.color = fullBgColor; slider.value = timeLeft / duration; //timeText.text = (int)(timeLeft+1) + "s"; } }
namespace Galaxy.Extensions { /// <summary> /// extensions for bool /// </summary> public static class BoolExtensions { /// <summary> /// returns 0 if false otherwise 1 /// </summary> /// <returns>1 or 0</returns> public static int ToOneZero(this bool value) { return value ? 1 : 0; } /// <summary> /// returns 0 if false otherwise 1 as a string /// </summary> /// <returns>"1" or "0"</returns> public static string ToOneZeroStr(this bool value) { return value ? "1" : "0"; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Communicator.Core.Domain; using Communicator.Infrastructure.IRepositories; using Communicator.Infrastructure.IServices; using Communicator.Infrastructure.Services; using Moq; using Xunit; namespace Communicator.Tests.Services { public class UserServiceTests { [Fact] public async Task given_valids_register_variables_should_register_new_user() { var userRepository = new Mock<IUserRepository>(); var mapper = new Mock<IMapper>(); var encypter = new Mock<IEncrypter>(); var userService = new UserService(userRepository.Object,mapper.Object, encypter.Object); await userService.Register("login", "password", "fname", "lname"); userRepository.Verify(x=>x.Add(It.IsAny<User>()),Times.Once); } [Fact] public async Task given_valid_user_login_should_retrun_user() { var userRepository = new Mock<IUserRepository>(); userRepository.Setup(e => e.Get("adam")).ReturnsAsync(new User("adam", "adam","salt", "adam", "adam")); var mapper = new Mock<IMapper>(); var encypter = new Mock<IEncrypter>(); var userService = new UserService(userRepository.Object, mapper.Object, encypter.Object); var user = await userService.Get("adam"); userRepository.Verify(x => x.Get(It.IsAny<string>()), Times.Once); } [Fact] public async Task given_valid_user_login_should_not_retrun_user() { var userRepository = new Mock<IUserRepository>(); userRepository.Setup(e => e.Get("adam")).ReturnsAsync(()=>null); var mapper = new Mock<IMapper>(); var encypter = new Mock<IEncrypter>(); var userService = new UserService(userRepository.Object, mapper.Object, encypter.Object); var user = await userService.Get("adam"); userRepository.Verify(x => x.Get(It.IsAny<string>()), Times.Once); } [Fact] public async Task getall_method_should_invoke_get_method_im_repository() { var userRepository = new Mock<IUserRepository>(); userRepository.Setup(e => e.Get()).ReturnsAsync(new List<User>{new User("adam", "adam","salt", "adam", "adam"),new User("adam1","adam","salt", "adam","adam")}.AsEnumerable()); var mapper = new Mock<IMapper>(); var encypter = new Mock<IEncrypter>(); var userService = new UserService(userRepository.Object, mapper.Object, encypter.Object); await userService.GetAll(); userRepository.Verify(x => x.Get(), Times.Once); } } }
using System; namespace _20_Lesson { class Program { static void Main(string[] args) { string nameConcat = string.Concat("My ", "name ", "is ", "Andrey!"); Console.WriteLine(nameConcat); nameConcat = string.Join(" ", "My", "name", "is", "Andrey!"); Console.WriteLine(nameConcat); nameConcat = nameConcat.Insert(0, "By the way, "); Console.WriteLine(nameConcat); nameConcat = nameConcat.Remove(0, 12); Console.WriteLine(nameConcat); string replace = nameConcat.Replace('n', 'N'); Console.WriteLine(replace); string lower = nameConcat.ToLower(); Console.WriteLine(lower); string upper = nameConcat.ToUpper(); Console.WriteLine(upper); //string a = "My name is Andrey"; пример сравнения символов строк без регистрозависимости //string b = "MY NAME is Andrey"; //a = a.ToUpper(); //b = b.ToUpper(); //bool result = a == b; //Console.WriteLine(result); string str = " my name is Andrey "; Console.WriteLine(str.Trim()); } } }
using SnowDAL.DBModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SnowDAL.Repositories.Interfaces { public interface IApiLogRepository { void Add(APILogEntity entity); } }
using AppNotas.Modelo; using CarritoCompras.Modelo; using CarritoCompras.Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CarritoCompras.View { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PageRegistro : ContentPage { public PageRegistro () { InitializeComponent (); } private async void BtnRegistrar_Clicked(object sender, EventArgs e) { Usuario oUsuario = new Usuario() { Nombres = txtNombre.Text, Apellidos = txtApellido.Text, Documento = txtDocumento.Text, Email = txtEmail.Text, Clave = txtContrasena.Text }; bool respuesta = await ApiServiceAuthentication.RegistrarUsuario(oUsuario); if (respuesta) { await DisplayAlert("Correcto", "Usuario registrado", "Aceptar"); await Navigation.PopModalAsync(); } else { await DisplayAlert("Oops", "No se pudo registrar", "Aceptar"); } //var actionSheet = await DisplayActionSheet("Title", "Cancel", "Destruction", "Button1", "Button2", "Button3"); //switch (actionSheet) //{ // case "Cancel": // // Do Something when 'Cancel' Button is pressed // break; // case "Destruction": // // Do Something when 'Destruction' Button is pressed // break; // case "Button1": // // Do Something when 'Button1' Button is pressed // break; // case "Button2": // // Do Something when 'Button2' Button is pressed // break; // case "Button3": // // Do Something when 'Button3' Button is pressed // break; //} } private void TapBackArrow_Tapped(object sender, EventArgs e) { Navigation.PopModalAsync(); } private void TapLabelTerminosCondiciones_Tapped(object sender, EventArgs e) { popupTerminosCondiciones.IsVisible = true; //await Navigation.PushModalAsync(new PagePopup()); } private void BtnCerrarModal_Clicked(object sender, EventArgs e) { popupTerminosCondiciones.IsVisible = false; } } }
using BHLD.Data.Infrastructure; using BHLD.Data.Repositories; using BHLD.Model.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BHLD.Services { public interface Ihu_districtServices { hu_district Add(hu_district hu_District); void Update(hu_district hu_District); hu_district Delete(int id); IEnumerable<hu_district> GetAll(); IEnumerable<hu_district> GetAllByPaging(int tag, int page, int pageSize, out int totalRow); hu_district GetById(int id); IEnumerable<hu_district> GetAllPaging(int page, int pageSize, out int totalRow); void SaveChanges(); } public class hu_districtServices : Ihu_districtServices { hu_districtRepository _hu_districtRepository; IUnitOfWork _unitOfWork; public hu_districtServices(hu_districtRepository hu_districtRepository, IUnitOfWork unitOfWork) { this._hu_districtRepository = hu_districtRepository; this._unitOfWork = unitOfWork; } public hu_district Add(hu_district hu_Title) { return _hu_districtRepository.Add(hu_Title); } public hu_district Delete(int id) { return _hu_districtRepository.Delete(id); } public IEnumerable<hu_district> GetAll() { return _hu_districtRepository.GetAll(new string[] { "District" }); } public IEnumerable<hu_district> GetAllByPaging(int tag, int page, int pageSize, out int totalRow) { return _hu_districtRepository.GetAllByDistrict(tag, page, pageSize, out totalRow); } public IEnumerable<hu_district> GetAllPaging(int page, int pageSize, out int totalRow) { return _hu_districtRepository.GetMultiPaging(x => x.status, out totalRow, page, pageSize); } public hu_district GetById(int id) { return _hu_districtRepository.GetSingleById(id); } public void SaveChanges() { _unitOfWork.Commit(); } public void Update(hu_district hu_District) { _hu_districtRepository.Update(hu_District); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using PluginDevelopment.DAL; namespace PluginDevelopment.Controllers { public class MenuController : ApiController { public string GetMenuData() { var menuData = MenuOperation.GetMenuDocument(); return menuData; } } }
using System; namespace Ntech.Saga.Contracts { public interface IBookingCreatedEvent { Guid CorrelationId { get; } string CustomerId { get; } string BookingId { get; } string BlobUri { get; } DateTime CreationTime { get; } } }
// RayProfiler // https://github.com/Bugfire using UnityEngine; namespace RayStorm { /* See RayProfilerFirstComponent.cs about DefaultExecutionOrder. */ #if UNITY_5_5_OR_NEWER [DefaultExecutionOrder (int.MaxValue)] #endif sealed public class RayProfilerLastComponent : RayProfilerMarker { RayProfilerLastComponent () : base (RayProfiler.Order.Last) { } } }
using MikeGrayCodes.BuildingBlocks.Application.Behaviors; using MikeGrayCodes.Ordering.Application.Application.Commands; using MikeGrayCodes.Ordering.Domain.Entities.Orders; using System; using System.Threading; using System.Threading.Tasks; namespace MikeGrayCodes.Ordering.Application.Commands.SetStockConfirmedOrderStatus { public class SetStockConfirmedOrderStatusExistsHandler : IExistsHandler<SetStockConfirmedOrderStatusCommand> { public IOrderRepository orderRepository; public SetStockConfirmedOrderStatusExistsHandler(IOrderRepository orderRepository) { this.orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); } public async Task<bool> Evaluate(SetStockConfirmedOrderStatusCommand request, CancellationToken cancellationToken = default) { return await orderRepository.GetAsync(request.OrderNumber) != null; } } }
using JhinBot.Enums; using JhinBot.GlobalConst; using System.Collections.Generic; namespace JhinBot.Translator { public class ConvoSubTypeTranslator { private Dictionary<string, ConversationSubType> translationDict = new Dictionary<string, ConversationSubType>() { { Global.Params.CONVO_CRTE_TEXT, ConversationSubType.Create}, { Global.Params.CONVO_UPDT_TEXT, ConversationSubType.Update}, { Global.Params.CONVO_DELE_TEXT, ConversationSubType.Delete}, }; public ConversationSubType Translate(string str) { if (!translationDict.TryGetValue(str, out var subType)) return ConversationSubType.None; else return subType; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WinForms = System.Windows.Forms; namespace FillBarcodeVolume { /// <summary> /// Interaction logic for SelectFolder.xaml /// </summary> public partial class FillBarcodeVolume : Window { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public FillBarcodeVolume() { InitializeComponent(); } internal void GetFilesInfo(List<string> barcodeFiles, List<string> volumeFiles, ref string excelFile) { throw new NotImplementedException(); } private void btnMerge_Click(object sender, RoutedEventArgs e) { try { MergeFiles(); } catch(Exception ex) { SetInfo(ex.Message); log.Info(ex.Message + ex.StackTrace); } } private void MergeFiles() { log.Info("Merge Files"); string errMsg = ""; bool readyForMerge = CheckReady(ref errMsg); if (!readyForMerge) { SetInfo(errMsg); return; } int nBarcodeFileCnt = BarcodeFiles.Count; List<string> allBarcodes = new List<string>(); List<string> allVolumes = new List<string>(); BarcodesFileReader barcodesFileReader = new BarcodesFileReader(); VolumeFileReader volumeFileReader = new VolumeFileReader(); int slices = 0; for (int i = 0; i < nBarcodeFileCnt; i++) { string barcodeFilePath = BarcodeFiles[i]; string volumeFilePath = VolumeFiles[i]; var barcodes = barcodesFileReader.Read(barcodeFilePath, ref slices); var volumes = volumeFileReader.Read(volumeFilePath, slices); if(barcodes.Count() != volumes.Count()) { string tmpError = string.Format("barcode count:{2} != volume count:{3} at file:{0} & {1}", barcodeFilePath, volumeFilePath, barcodes.Count(), volumes.Count()); SetInfo(tmpError); log.InfoFormat(tmpError); return; } allBarcodes.AddRange(barcodes); allVolumes.AddRange(volumes); } List<SampleInfo> sampleInfos = GetSampleInfos(allBarcodes, allVolumes); ExcelHelper.WriteResult(sampleInfos, DstFile); } private List<SampleInfo> GetSampleInfos(List<string> allBarcodes, List<string> allVolumes) { List<SampleInfo> samplesInfo = new List<SampleInfo>(); int cnt = allBarcodes.Count; for(int i = 0; i< cnt; i++) { string barcode = allBarcodes[i]; string volume = allVolumes[i]; string orgBarcode = GetOrgBarcode(barcode); samplesInfo.Add(new SampleInfo(barcode, orgBarcode, volume)); } return samplesInfo; } private string GetOrgBarcode(string barcode) { int index = barcode.IndexOf('-'); return barcode.Substring(0, index); } public List<string> BarcodeFiles { get; set; } public List<string> VolumeFiles { get; set; } public string DstFile { get; set; } private void btnBrowse_Click(object sender, RoutedEventArgs e) { btnMerge.IsEnabled = false; var dialog = new WinForms.FolderBrowserDialog(); var result = dialog.ShowDialog(); if (result != WinForms.DialogResult.OK) return; string folder = dialog.SelectedPath; DirectoryInfo dirInfo = new DirectoryInfo(folder); var files = dirInfo.EnumerateFiles("*.csv").Select(x=>x.FullName); SeparateFilesByType(files); DstFile = dirInfo.EnumerateFiles(".xlsx").First().FullName; BarcodeFiles.Sort(); VolumeFiles.Sort(); lstBarcodes.ItemsSource = BarcodeFiles; lstVolumes.ItemsSource = VolumeFiles; //检查 string errMsg = ""; bool readyForMerge = CheckReady(ref errMsg); if(!readyForMerge) { SetInfo(errMsg); } btnMerge.IsEnabled = readyForMerge; } private bool CheckReady(ref string errMsg) { if (BarcodeFiles.Count == 0) { errMsg = "未找到条码文件!"; return false; } if (BarcodeFiles.Count != VolumeFiles.Count) { errMsg = "条码文件数与体积文件数不相等!"; return false; } if (DstFile == "") { errMsg = "未找到目标文件!"; return false; } return true; } private void SetInfo(string txt, bool bRed = true) { txtInfo.Text = txt; txtInfo.Foreground = new SolidColorBrush(bRed ? Colors.Red : Colors.Black); } private void SeparateFilesByType(IEnumerable<string> files) { BarcodeFiles.Clear(); VolumeFiles.Clear(); foreach(string file in files) { bool isBarcode = File.ReadLines(file).First().Contains("条"); if(isBarcode) { BarcodeFiles.Add(file); } else { VolumeFiles.Add(file); } } } } }
using System; using System.Collections.Generic; using System.Text; using GhostscriptSharp; using System.Runtime.InteropServices; namespace Examples { /// <summary> /// Similar to command line gs /// </summary> /// <remarks>Port of Ghostscript Example code at http://pages.cs.wisc.edu/~ghost/doc/cvs/API.htm</remarks> class Example2 { public const String KernelDllName = "kernel32.dll"; public const String GhostscriptDllDirectory = @"C:\Program Files\gs\gs8.71\bin"; public static String start_string = "systemdict /start get exec" + System.Environment.NewLine; [DllImport(KernelDllName, SetLastError = true)] static extern int SetDllDirectory(string lpPathName); [DllImport(KernelDllName, EntryPoint = "RtlMoveMemory", SetLastError = true)] static extern int CopyMemory(IntPtr dest, IntPtr source, Int64 count); static void Main(string[] args) { #region StdIn Handler StringBuilder sbInput = new StringBuilder(); // This is very slow, especially because Ghostscript asks for input 1 character at a time API.StdinCallback stdin = (caller_handle, str, n) => { if (n == 0) { str = IntPtr.Zero; return 0; } if (sbInput.Length == 0) { sbInput.AppendLine(Console.ReadLine()); } if (sbInput.Length > 0) { int len = (sbInput.Length < n) ? sbInput.Length : n; byte[] b = ASCIIEncoding.ASCII.GetBytes(sbInput.ToString(0, len)); GCHandle cHandle = GCHandle.Alloc(b, GCHandleType.Pinned); IntPtr cPtr = cHandle.AddrOfPinnedObject(); Int64 copyLen = (long)len; CopyMemory(str, cPtr, copyLen); cPtr = IntPtr.Zero; cHandle.Free(); sbInput.Remove(0, len); return len; } return 0; }; #endregion #region StdOut Handler API.StdoutCallback stdout = (caller_handle, buf, len) => { Console.Write(buf.Substring(0, len)); return len; }; #endregion #region StdErr Handler API.StdoutCallback stderr = (caller_handle, buf, len) => { Console.Error.Write(buf.Substring(0, len)); return len; }; #endregion string[] gsargv = new string[args.Length + 1]; gsargv[0] = "GhostscriptSharp"; /* actual value doesn't matter */ Array.Copy(args, 0, gsargv, 1, args.Length); IntPtr minst; int code, code1; int exit_code; SetDllDirectory(GhostscriptDllDirectory); code = API.CreateAPIInstance(out minst, IntPtr.Zero); if (code < 0) { System.Environment.Exit(1); } API.Set_Stdio(minst, stdin, stdout, stderr); code = API.InitAPI(minst, gsargv.Length, gsargv); if (code == 0) { API.RunString(minst, start_string, 0, out exit_code); } code1 = API.ExitAPI(minst); if ((code == 0) || (code == (int)API.GhostscriptErrorCode.e_Quit)) { code = code1; } API.DeleteAPIInstance(minst); if ((code == 0) || (code == (int)API.GhostscriptErrorCode.e_Quit)) { System.Environment.Exit(0); } System.Environment.Exit(1); } } }
using UnityEngine; using UnityEngine.SceneManagement; public class ColoringUI : MonoBehaviour { public void GoToMenu() { SceneManager.LoadScene("MainMenu"); } public void Reload() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } public void ScreenShot() { //ScreenCapture.TakeScreenshot_Static(Camera.main.pixelWidth, Camera.main.pixelHeight); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerUpsManager : MonoBehaviour { public static PowerUpsManager Instance { get; private set; } private void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); } else { Instance = this; } } private List<PowerUps> PowerUpsList; private void Start() { PowerUpsList = new List<PowerUps>(); } public void AddPowerUps(PowerUps PowerUpsPrefab) { foreach (PowerUps m in PowerUpsList) { if (m.GetType() == PowerUpsPrefab.GetType()) { return; } } PowerUps PowerUpsCreated = Instantiate(PowerUpsPrefab, transform); PowerUpsList.Add(PowerUpsCreated); PowerUpsCreated.Activate(); } public void RemovePowerUps(PowerUps PowerUps) { PowerUpsList.Remove(PowerUps); Destroy(PowerUps.gameObject); } }
using AutoMapper; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MoviesAPI.DTOs; using MoviesAPI.Entities; using MoviesAPI.Helpers; using MoviesAPI.Services; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq.Dynamic.Core; using Microsoft.Extensions.Logging; namespace MoviesAPI.Controllers { [ApiController] [Route("api/movies")] public class MoviesController : ControllerBase { private readonly MoviesDbContext _context; private readonly IMapper _mapper; private readonly IFileStorageService _fileStorageService; private readonly ILogger<MoviesController> _logger; private readonly string containerName = "movies"; public MoviesController(MoviesDbContext context, IMapper mapper, IFileStorageService fileStorageService, ILogger<MoviesController> logger) { _context = context; _mapper = mapper; _fileStorageService = fileStorageService; _logger = logger; } [HttpGet] public async Task<ActionResult<IndexMoviePageDTO>> Get() { var top = 6; var today = DateTime.Today; var upcomingReleases = await _context.Movies .Where(x => x.ReleaseDate > today) .OrderBy(x => x.ReleaseDate) .Take(top) .ToListAsync(); var inTheathers = await _context.Movies .Where(x => x.InTheatre) .Take(top) .ToListAsync(); var result = new IndexMoviePageDTO(); result.InTheaters = _mapper.Map<List<MovieDTO>>(inTheathers); result.UpcomingReleases = _mapper.Map<List<MovieDTO>>(upcomingReleases); return result; } [HttpGet("filter")] public async Task<ActionResult<List<MovieDTO>>> Filter([FromQuery] FilterMoviesDTO filterMoviesDTO) { var moviesQueryable = _context.Movies.AsQueryable(); if(!string.IsNullOrWhiteSpace(filterMoviesDTO.Title)) { moviesQueryable = moviesQueryable.Where(x => x.Title.Contains(filterMoviesDTO.Title)); } if(filterMoviesDTO.InTheaters) { moviesQueryable = moviesQueryable.Where(x => x.InTheatre); } if(filterMoviesDTO.UpcomingReleses) { var today = DateTime.Today; moviesQueryable = moviesQueryable.Where(x => x.ReleaseDate > today); } if(filterMoviesDTO.GenreId != 0) { moviesQueryable = moviesQueryable .Where(x => x.MoviesGenres.Select(y => y.GenreId).Contains(filterMoviesDTO.GenreId)); } //if(!string.IsNullOrWhiteSpace(filterMoviesDTO.OrderingField)) //{ // if(filterMoviesDTO.OrderingField == "title") // { // if (filterMoviesDTO.AscendingOrder) // { // moviesQueryable = moviesQueryable.OrderBy(x => x.Title); // } // else // { // moviesQueryable = moviesQueryable.OrderByDescending(x => x.Title); // } // } //} if(!string.IsNullOrWhiteSpace(filterMoviesDTO.OrderingField)) { try { moviesQueryable = moviesQueryable .OrderBy($"{filterMoviesDTO.OrderingField} {(filterMoviesDTO.AscendingOrder ? "ascending" : "descending")}"); } catch (Exception) { // error _logger.LogWarning("Couldn't order by firle: " + filterMoviesDTO.OrderingField); } } await HttpContext.InsertPaginationParametersInResponse(moviesQueryable, filterMoviesDTO.RecordsPerPage); var movies = await moviesQueryable.Paginate(filterMoviesDTO.Pagination).ToListAsync(); return _mapper.Map<List<MovieDTO>>(movies); } [HttpGet("{id}", Name = "getMovie")] public async Task<ActionResult<MovieDetailsDTO>> Get(int id) { var movie = await _context.Movies .Include(x => x.MoviesActors).ThenInclude(x => x.Person) .Include(x=>x.MoviesGenres).ThenInclude(x=>x.Genre) .FirstOrDefaultAsync(x => x.Id == id); if (movie == null) { return NotFound(); } return _mapper.Map<MovieDetailsDTO>(movie); } [HttpPost] public async Task<ActionResult> Post([FromForm] MovieCreationDTO movieCreationDTO) { var movie = _mapper.Map<Movie>(movieCreationDTO); if (movieCreationDTO.Poster != null) { using (var memoryStream = new MemoryStream()) { await movieCreationDTO.Poster.CopyToAsync(memoryStream); var content = memoryStream.ToArray(); var extension = Path.GetExtension(movieCreationDTO.Poster.FileName); movie.Poster = await _fileStorageService.SaveFile(content, extension, containerName, movieCreationDTO.Poster.ContentType); } } AnnotateActorsOrder(movie); _context.Add(movie); await _context.SaveChangesAsync(); var movieDTO = _mapper.Map<MovieDTO>(movie); return new CreatedAtRouteResult("getMovie", new { id = movie.Id }, movieDTO); } private static void AnnotateActorsOrder(Movie movie) { if(movie.MoviesActors !=null) { for(int i=0;i<movie.MoviesActors.Count; i++) { movie.MoviesActors[i].Order = i; } } } [HttpPut("{id}")] public async Task<ActionResult> Put(int id, [FromForm] MovieCreationDTO movieCreationDTO) { var movieDB = await _context.Movies.FirstOrDefaultAsync(x => x.Id == id); if (movieDB == null) { return NotFound(); } movieDB = _mapper.Map(movieCreationDTO, movieDB); if (movieCreationDTO.Poster != null) { using (var memoryStream = new MemoryStream()) { await movieCreationDTO.Poster.CopyToAsync(memoryStream); var content = memoryStream.ToArray(); var extension = Path.GetExtension(movieCreationDTO.Poster.FileName); movieDB.Poster = await _fileStorageService.EditFile(content, extension, containerName, movieDB.Poster, movieCreationDTO.Poster.ContentType); } } _context.Database.ExecuteSqlRaw($"DELETE FROM MoviesActors WHERE MovieId = ${movieDB.Id}; DELETE FROM MoviesGenres WHERE MovieId = ${movieDB.Id};"); AnnotateActorsOrder(movieDB); await _context.SaveChangesAsync(); return NoContent(); } [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { var exists = await _context.Movies.AnyAsync(x => x.Id == id); if (!exists) { return NotFound(); } _context.Remove(new Movie() { Id = id }); await _context.SaveChangesAsync(); return NoContent(); } [HttpPatch("{id}")] public async Task<ActionResult> Patch(int id, [FromBody] JsonPatchDocument<MoviePatchDTO> patchDocument) { if (patchDocument == null) { return BadRequest(); } var entityFromDB = await _context.Movies.FirstOrDefaultAsync(x => x.Id == id); if(entityFromDB==null) { return NotFound(); } var entityDTO = _mapper.Map<MoviePatchDTO>(entityFromDB); patchDocument.ApplyTo(entityDTO, ModelState); var isValid = TryValidateModel(entityDTO); if(!isValid) { return BadRequest(ModelState); } _mapper.Map(entityDTO, entityFromDB); await _context.SaveChangesAsync(); return NoContent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Compent.Shared.Search.Contract; using UBaseline.Search.Core; using Uintra.Core.Member.Entities; using Uintra.Core.Member.Services; using Uintra.Core.Search.Entities; using Uintra.Core.Search.Entities.Mappers; using Uintra.Core.Search.Repository; namespace Uintra.Core.Search.Indexers { public class MemberIndexer : ISearchDocumentIndexer { public Type Type { get; } = typeof(SearchableMember); private readonly IIntranetMemberService<IntranetMember> _intranetMemberService; private readonly ISearchableMemberMapper<SearchableMember> _searchableMemberMapper; private readonly IIndexContext<SearchableMember> _indexContext; private readonly IUintraSearchRepository<SearchableMember> _searchRepository; public MemberIndexer( IIndexContext<SearchableMember> indexContext, IUintraSearchRepository<SearchableMember> searchRepository, ISearchableMemberMapper<SearchableMember> searchableMemberMapper, IIntranetMemberService<IntranetMember> intranetMemberService) { _indexContext = indexContext; _searchRepository = searchRepository; _searchableMemberMapper = searchableMemberMapper; _intranetMemberService = intranetMemberService; } public async Task<bool> RebuildIndex() { try { var actualUsers = _intranetMemberService.GetAll().Where(u => !u.Inactive); var searchableUsers = actualUsers.Select(_searchableMemberMapper.Map).ToList(); var rc = await _indexContext.RecreateIndex(); var i =await _searchRepository.IndexAsync(searchableUsers); return true; //return _indexerDiagnosticService.GetSuccessResult(typeof(MembersIndexer<T>).Name, searchableUsers); } catch (Exception e) { return false; //return _indexerDiagnosticService.GetFailedResult(e.Message + e.StackTrace, typeof(MembersIndexer<T>).Name); } } public Task<bool> Delete(IEnumerable<string> nodeIds) { return Task.FromResult(true); } } }
using Pe.Stracon.Politicas.Infraestructura.CommandModel.Base; using Pe.Stracon.Politicas.Infraestructura.CommandModel.General; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.Politicas.Infraestructura.CommandModel.Mapping.General { /// <summary> /// Implementación del mapeo de la entidad unidad operativa staff /// </summary> /// <remarks> /// Creación: GMD 20161121 <br /> /// Modificación: <br /> /// </remarks> public class UnidadOperativaUsuarioConsultaMapping : BaseEntityMapping<UnidadOperativaUsuarioConsultaEntity> { /// <summary> /// Constuctor del Mapping de Unidad Operativa Responsable /// </summary> public UnidadOperativaUsuarioConsultaMapping() : base() { HasKey(x => x.CodigoUnidadUsuarioConsulta).ToTable("UNIDAD_OPERATIVA_USUARIO_CONSULTA", "GRL"); Property(u => u.CodigoUnidadUsuarioConsulta).HasColumnName("CODIGO_UNIDAD_OPERATIVA_USUARIO_CONSULTA"); Property(u => u.CodigoUnidadOperativa).HasColumnName("CODIGO_UNIDAD_OPERATIVA"); Property(u => u.CodigoTrabajador).HasColumnName("CODIGO_TRABAJADOR"); Property(u => u.EstadoRegistro).HasColumnName("ESTADO_REGISTRO"); Property(u => u.UsuarioCreacion).HasColumnName("USUARIO_CREACION"); Property(u => u.FechaCreacion).HasColumnName("FECHA_CREACION"); Property(u => u.TerminalCreacion).HasColumnName("TERMINAL_CREACION"); Property(u => u.UsuarioModificacion).HasColumnName("USUARIO_MODIFICACION"); Property(u => u.FechaModificacion).HasColumnName("FECHA_MODIFICACION"); Property(u => u.TerminalModificacion).HasColumnName("TERMINAL_MODIFICACION"); } } }
using System; namespace iPadPos { public class NotificationCenter { static NotificationCenter shared; public static NotificationCenter Shared { get { return shared ?? (shared = new NotificationCenter()); } } public NotificationCenter () { } public event Action CouponsChanged; public void ProcCouponsChanged() { if (CouponsChanged != null) CouponsChanged (); } public event Action NewProductChanged; public void ProcNewProductChanged() { if (NewProductChanged != null) NewProductChanged (); } } }
using AutoMapper; using EasyWebApp.API.Extensions; using EasyWebApp.API.Services.UserSrv; using EasyWebApp.Data.Entities.AuthenticationEnties; using EasyWebApp.Data.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EasyWebApp.API.Controllers { [Route("api/[controller]")] [Authorize] [ApiController] public class UserController : ControllerBase { private readonly IUserSrv _userService; private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<UserController> _logger; private readonly IMapper _mapper; public UserController(IUserSrv userSrv, UserManager<ApplicationUser> userManager, ILogger<UserController> logger, IMapper mapper) { this._userService = userSrv; this._userManager = userManager; this._logger = logger; this._mapper = mapper; } [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<UserInfoViewModel>> GetUserInfo() { var userId = User.GetId(); var loggedUser = await _userService.GetUserInfo(userId); var result = _mapper.Map<UserInfoViewModel>(loggedUser); return Ok(result); } } }
using System.Collections.Generic; using Assets.Scripts.Models.ResourceObjects.CraftingResources; using Assets.Scripts.Models.ResourceObjects; namespace Assets.Scripts.Models.Constructions.Stone { public class StoneWall : Construction { public StoneWall() { ConstructionType = ConstructionType.Wall; LocalizationName = "stone_wall"; Description = "stone_wall_descr"; IconName = "stone_wall_icon"; PrefabPath = "Prefabs/Constructions/Stone/Wall/StoneWall"; PrefabTemplatePath = "Prefabs/Constructions/Stone/Wall/StoneWallTemplate"; CraftRecipe = new List<HolderObject>(); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(WoodResource), 10)); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(StoneResource), 30)); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiCoin.Models; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace FiiiCoin.Wallet.Win.Converters { public enum ModelType { AccountInfo, PageUnspent } public static class Extensions { public static string GetTag(this PageUnspent unspentUtxo) { var amount = StaticConverters.LongToDoubleConverter.Convert(unspentUtxo.Amount, typeof(object), null, StaticConverters.CultureInfo); var amountStr = amount == null ? "Null" : amount.ToString(); var result = string.Format("{0}({1})", unspentUtxo.Address, amountStr); return result; } public static string GetTag(this AccountInfo accountInfo) { if (string.IsNullOrEmpty(accountInfo.Tag)) return string.Format("{0}", accountInfo.Address); else return string.Format("{0}({1})", accountInfo.Address, accountInfo.Tag); } } public class ModelToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter == null || !(parameter is ModelType)) return null; var result = ""; var model = (ModelType)parameter; switch (model) { case ModelType.AccountInfo: if (value is AccountInfo) { result = ((AccountInfo)value).GetTag(); } break; case ModelType.PageUnspent: if (value is PageUnspent) { result = ((PageUnspent)value).GetTag(); } break; default: break; } return result; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; namespace DataAccessLayer.Repository { public class WorkRepository : BaseRepository<Work> { public WorkRepository(TaskManagementContext context) : base(context) { } } }
using ND.FluentTaskScheduling.Command.asyncrequest; using ND.FluentTaskScheduling.Core; using ND.FluentTaskScheduling.Model; using ND.FluentTaskScheduling.Model.enums; using ND.FluentTaskScheduling.Model.request; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):BaseMonitor.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-04-06 16:06:48 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-04-06 16:06:48 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Command.Monitor { public abstract class AbsMonitor { protected Task _task; CancellationTokenSource importCts = new CancellationTokenSource();//是否取消监控 /// <summary> /// 监控间隔时间 (毫秒) /// </summary> public virtual int Interval { get; set; } /// <summary> /// 监控名称 /// </summary> public virtual string Name { get; set; } /// <summary> /// 监控描述 /// </summary> public virtual string Discription{get;set;} public AbsMonitor() { _task=Task.Factory.StartNew(TryRun,importCts.Token); //_thread = new System.Threading.Thread(TryRun); //_thread.IsBackground = true; // _thread.Start(); } private void TryRun() { var r = NodeProxy.PostToServer<EmptyResponse, AddNodeMonitorRequest>(ProxyUrl.AddNodeMonitorRequest_Url, new AddNodeMonitorRequest() { NodeId = GlobalNodeConfig.NodeID,Name=Name,Discription=Discription,Internal=this.Interval, ClassName=this.GetType().Name,ClassNameSpace=this.GetType().FullName,MonitorStatus=(int)MonitorStatus.Monitoring, Source = Source.Node }); if (r.Status != ResponesStatus.Success) { //记录日志,并抛出异常 LogProxy.AddNodeErrorLog("请求" + ProxyUrl.AddNodeMonitorRequest_Url + "上报节点信息失败,服务端返回信息:" + JsonConvert.SerializeObject(r)); } while (true) { try { if(importCts.Token.IsCancellationRequested)//如果要是已取消则break { //LogProxy.AddNodeLog(this.GetType().Name + "监控组件收到取消请求,已取消监控!"); var r2 = NodeProxy.PostToServer<EmptyResponse, UpdateNodeMonitorRequest>(ProxyUrl.UpdateNodeMonitorRequest_Url, new UpdateNodeMonitorRequest() { NodeId = GlobalNodeConfig.NodeID, MonitorClassName = this.GetType().Name, MonitorStatus = (int)MonitorStatus.NoMonitor, Source = Source.Node }); if (r2.Status != ResponesStatus.Success) { //记录日志,并抛出异常 LogProxy.AddNodeErrorLog("请求" + ProxyUrl.UpdateNodeMonitorRequest_Url + "上报节点监控(停止监控)信息失败,服务端返回信息:" + JsonConvert.SerializeObject(r)); } break; } Run(); System.Threading.Thread.Sleep(Interval); } catch (Exception exp) { LogProxy.AddNodeErrorLog(this.GetType().Name + "监控严重错误,异常信息:"+JsonConvert.SerializeObject(exp)); } } } /// <summary> /// 监控执行方法约定 /// </summary> protected abstract void Run(); /// <summary> /// 取消执行 /// </summary> public virtual void CancelRun() { try { importCts.Cancel(); //LogProxy.AddNodeLog(this.GetType().Name + "监控组件取消监控!"); //var r = NodeProxy.PostToServer<EmptyResponse, UpdateNodeMonitorRequest>(ProxyUrl.UpdateNodeMonitorRequest_Url, new UpdateNodeMonitorRequest() { NodeId = GlobalNodeConfig.NodeID, MonitorClassName = Name, MonitorStatus = (int)MonitorStatus.NoMonitor, Source = Source.Node }); //if (r.Status != ResponesStatus.Success) //{ // //记录日志,并抛出异常 // LogProxy.AddNodeErrorLog("请求" + ProxyUrl.UpdateNodeMonitorRequest_Url + "上报节点监控(停止监控)信息失败,服务端返回信息:" + JsonConvert.SerializeObject(r)); //} } catch(Exception ex) { LogProxy.AddNodeErrorLog(this.GetType().Name + "取消监控异常,异常信息:" + JsonConvert.SerializeObject(ex)); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using ToilluminateModel; namespace ToilluminateModel.Controllers { public class PlayerPlayListLinkTablesController : BaseApiController { private ToilluminateEntities db = new ToilluminateEntities(); // GET: api/PlayerPlayListLinkTables public IQueryable<PlayerPlayListLinkTable> GetPlayerPlayListLinkTable() { return db.PlayerPlayListLinkTable; } // GET: api/PlayerPlayListLinkTables/5 [ResponseType(typeof(PlayerPlayListLinkTable))] public async Task<IHttpActionResult> GetPlayerPlayListLinkTable(int id) { PlayerPlayListLinkTable playerPlayListLinkTable = await db.PlayerPlayListLinkTable.FindAsync(id); if (playerPlayListLinkTable == null) { return NotFound(); } return Ok(playerPlayListLinkTable); } // PUT: api/PlayerPlayListLinkTables/5 [ResponseType(typeof(void))] public async Task<IHttpActionResult> PutPlayerPlayListLinkTable(int id, PlayerPlayListLinkTable playerPlayListLinkTable) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != playerPlayListLinkTable.ID) { return BadRequest(); } playerPlayListLinkTable.UpdateDate = DateTime.Now; db.Entry(playerPlayListLinkTable).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PlayerPlayListLinkTableExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/PlayerPlayListLinkTables [ResponseType(typeof(PlayerPlayListLinkTable))] public async Task<IHttpActionResult> PostPlayerPlayListLinkTable(PlayerPlayListLinkTable playerPlayListLinkTable) { if (!ModelState.IsValid) { return BadRequest(ModelState); } playerPlayListLinkTable.UpdateDate = DateTime.Now; playerPlayListLinkTable.InsertDate = DateTime.Now; db.PlayerPlayListLinkTable.Add(playerPlayListLinkTable); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = playerPlayListLinkTable.ID }, playerPlayListLinkTable); } // DELETE: api/PlayerPlayListLinkTables/5 [ResponseType(typeof(PlayerPlayListLinkTable))] public async Task<IHttpActionResult> DeletePlayerPlayListLinkTable(int id) { PlayerPlayListLinkTable playerPlayListLinkTable = await db.PlayerPlayListLinkTable.FindAsync(id); if (playerPlayListLinkTable == null) { return NotFound(); } db.PlayerPlayListLinkTable.Remove(playerPlayListLinkTable); await db.SaveChangesAsync(); return Ok(playerPlayListLinkTable); } [HttpPost, Route("api/PlayerPlayListLinkTables/DeletePlayerPlayListLinkTableByPlayerID/{PlayerID}")] public async Task<IHttpActionResult> DeletePlayerPlayListLinkTableByGroupID(int PlayerID) { List<PlayerPlayListLinkTable> ppltList = db.PlayerPlayListLinkTable.Where(a => a.PlayerID == PlayerID).ToList(); foreach (PlayerPlayListLinkTable pplt in ppltList) { if (pplt == null) { return NotFound(); } db.PlayerPlayListLinkTable.Remove(pplt); await db.SaveChangesAsync(); } return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool PlayerPlayListLinkTableExists(int id) { return db.PlayerPlayListLinkTable.Count(e => e.ID == id) > 0; } } }
using AutoMapper; using vega3.Models; using vega3.Controllers.Resources; using System.Linq; namespace vega3.Mapping { public class MappingProfile : Profile { public MappingProfile() { // Domain to Api Resource CreateMap<Make, MakeResource>(); CreateMap<Model, ModelResource>(); CreateMap<Feature,FeatureResource>(); //Api Resource to Domain CreateMap<VehicleResource, Vehicle>() .ForMember(v => v.ContactName, opt=> opt.MapFrom(vr => vr.Contact.Name)) .ForMember(v => v.ContactPhone, opt=> opt.MapFrom(vr => vr.Contact.Phone)) .ForMember(v => v.ContactEmail, opt=> opt.MapFrom(vr => vr.Contact.Email)) .ForMember(v => v.Features, opt=> opt.MapFrom(vr => vr.Features.Select(id => new VehicleFeature{FeatureId = id}))); } } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `CollisionPair`. Inherits from `AtomEventReference&lt;CollisionPair, CollisionVariable, CollisionPairEvent, CollisionVariableInstancer, CollisionPairEventInstancer&gt;`. /// </summary> [Serializable] public sealed class CollisionPairEventReference : AtomEventReference< CollisionPair, CollisionVariable, CollisionPairEvent, CollisionVariableInstancer, CollisionPairEventInstancer>, IGetEvent { } }
using ProgFrog.Interface.TaskRunning.Runners; using System.Diagnostics; using System.IO; namespace ProgFrog.Core.TaskRunning.Runners { public class ProcessProxy : IProcess { private Process _process; public ProcessProxy(Process process) { this._process = process; } public int ExitCode { get { return _process.ExitCode; } } public bool RedirectStandardInput { get { return _process.StartInfo.RedirectStandardInput; } } public bool UseShellExecute { get { return _process.StartInfo.UseShellExecute; } } public bool RedirectStandardOutput { get { return _process.StartInfo.RedirectStandardOutput; } } public StreamWriter StandardInput { get { return _process.StandardInput; } } public StreamReader StandardOutput { get { return _process.StandardOutput; } } public void WaitForExit() { _process.WaitForExit(); } } }
using System; using System.Collections.Generic; using System.Text; namespace WindowsFA { public class FAModel { public FAModel() { } public double eff(double r) { return (Math.Pow(Math.E, r) - 1.0); } public double eff(double r, double p) { return (Math.Pow(1.0 + r / p, p) - 1.0); } public double nom(double r) { return (Math.Log(r + 1.0)); } public double nom(double r, double p) { return (p * ((Math.Pow(r + 1.0, 1.0 / p) - 1.0))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Web_Api.Controllers { public class BookController : ApiController { public string GetBook(string Title, int NumberOfPages, [FromBody] string Author) { return string.Format("le livre{0}; Nombre de page{1}; Author{2}", Title, NumberOfPages, Author); } public string PostBook(string Title, int NumberOfPages, string Author) { return string.Format("le livre{0}; Nombre de page{1}; Author{2}", Title, NumberOfPages, Author); } public string GetBook(Book b) { return string.Format("le livre{0}; Nombre de page{1}; Author{2}", b.Title, b.NumberOfPages, b.Author); } public string PostBook(Book b) { return string.Format("le livre{0}; Nombre de page{1}; Author{2}", b.Title, b.NumberOfPages, b.Author); } public string PostBook(Book b, string Author) { return string.Format("le livre{0}; Nombre de page{1}; Author{2}", b.Title, b.NumberOfPages, Author); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Direct; using Fanout; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using producer.Controllers; using Queue; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace producer { public class Program { public static void Main(string[] args) { if (args.Length == 0) { System.Console.WriteLine("choose: queue"); return; } int consumerLength = int.Parse(args[1]); switch (args[0]) { case "queue": var queue = new QueueExample(); for (int i = 0; i < consumerLength; i++) queue.RunConsumer(); break; case "fanout": var fanout = new FanoutExample(); for (int i = 0; i < consumerLength; i++) fanout.RunConsumer(); break; case "direct": var direct = new DirectExample(); direct.RunConsumerInfo(); direct.RunConsumerWarning(); direct.RunConsumerError(); direct.RunConsumerAll(); break; case "topic": var topic = new Topic.TopicExample(); topic.RunConsumerSum(); topic.RunConsumerSumAll(); topic.RunConsumerSub(); topic.RunConsumerSubAll(); topic.RunConsumerAll(); break; } CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
using System; using System.Collections.Generic; using System.Linq; namespace _11_Palindromes { public class _11_Palindromes { public static void Main() { var separator = new[] { '.', '!', '?', ',', ' ' }; var text = Console.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries).ToArray(); var result = new SortedSet<string>(); foreach (var word in text) { var length = word.Length / 2; var reminder = word.Length % 2; var firstPart = word.Substring(0, length); var second = word.Substring(length+reminder).ToCharArray(); Array.Reverse(second); var secondPart = string.Join("", second); if (firstPart.Equals(secondPart)) { result.Add(word); } } Console.WriteLine("[" + string.Join(", ", result) + "]"); } } }
using System; using System.Collections.Generic; using System.Text; namespace PizzaBox.Domain.DataAccess { class CrustMapper { public static PizzaLib.Crust Map(Client.Models.Crust crust) { return new PizzaLib.Crust() { Id = crust.Id, name = crust.Crust1, price = crust.Price }; } } }
using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Interoperability.GeoServices.Rest; using gView.Interoperability.GeoServices.Rest.Json; using System; using System.Text; using System.Threading.Tasks; namespace gView.Interoperability.GeoServices.Dataset { public class GeoServicesFeatureClass : FeatureClass, IWebFeatureClass { private GeoServicesDataset _dataaset; private GeoServicesFeatureClass() { } async static internal Task<GeoServicesFeatureClass> CreateAsync(GeoServicesDataset dataset, JsonLayer jsonLayer) { var featureClass = new GeoServicesFeatureClass(); featureClass._dataaset = dataset; featureClass.ID = jsonLayer.Id.ToString(); featureClass.Name = jsonLayer.Name; var fields = featureClass.Fields as FieldCollection; if (fields != null && jsonLayer.Fields != null) { foreach (var jsonField in jsonLayer.Fields) { var fieldType = RestHelper.FType(jsonField.Type); if (fieldType == FieldType.String) { fields.Add(new Field(jsonField.Name, fieldType, 1024) { aliasname = jsonField.Alias ?? jsonField.Name }); } else { fields.Add(new Field(jsonField.Name, fieldType) { aliasname = jsonField.Alias ?? jsonField.Name }); } if (fieldType == FieldType.ID) { featureClass.IDFieldName = jsonField.Name; } } } featureClass.GeometryType = jsonLayer.GetGeometryType(); if (jsonLayer.Extent != null) { featureClass.Envelope = new Envelope(jsonLayer.Extent.Xmin, jsonLayer.Extent.Ymin, jsonLayer.Extent.Xmax, jsonLayer.Extent.Ymax); } featureClass.SpatialReference = await dataset.GetSpatialReference(); return featureClass; } #region IWebFeatureClass public string ID { get; private set; } #endregion public override Task<IFeatureCursor> GetFeatures(IQueryFilter filter) { string queryUrl = $"{_dataaset.ServiceUrl()}/{this.ID}/query?f=json"; string geometryType = String.Empty, geometry = String.Empty; int outSrefId = (filter.FeatureSpatialReference != null) ? filter.FeatureSpatialReference.EpsgCode : 0, inSrefId = 0; // Bitte nicht ändern -> Verursacht Pagination Error vom AGS und Performance Problem wenn daten im SQL Spatial liegen string featureLimit = String.Empty; //(filter.FeatureLimit <= 0 ? "" : filter.FeatureLimit.ToString()); string separatedSubFieldsString = String.IsNullOrWhiteSpace(filter.SubFields) ? "*" : filter.SubFields.Replace(" ", ","); if (filter is SpatialFilter) { var sFilter = (SpatialFilter)filter; inSrefId = sFilter.FilterSpatialReference != null ? sFilter.FilterSpatialReference.EpsgCode : 0; if (sFilter.Geometry is IPoint) { geometry = RestHelper.ConvertGeometryToJson(((Point)sFilter.Geometry), inSrefId); geometryType = RestHelper.GetGeometryTypeString(((Point)sFilter.Geometry)); } else if (sFilter.Geometry is IMultiPoint) { geometry = RestHelper.ConvertGeometryToJson(((MultiPoint)sFilter.Geometry), inSrefId); geometryType = RestHelper.GetGeometryTypeString(((MultiPoint)sFilter.Geometry)); } // TODO - if needed else if (sFilter.Geometry is IPolyline) { geometry = RestHelper.ConvertGeometryToJson(((Polyline)sFilter.Geometry), inSrefId); geometryType = RestHelper.GetGeometryTypeString(((Polyline)sFilter.Geometry)); } else if (sFilter.Geometry is IPolygon) { geometry = RestHelper.ConvertGeometryToJson(((Polygon)sFilter.Geometry), inSrefId); geometryType = RestHelper.GetGeometryTypeString(((Polygon)sFilter.Geometry)); } else if (sFilter.Geometry is IEnvelope) { geometry = RestHelper.ConvertGeometryToJson(((Envelope)sFilter.Geometry), inSrefId); geometryType = RestHelper.GetGeometryTypeString(((Envelope)sFilter.Geometry)); } else { } } string where = filter.WhereClause; // is always set in featurecursor //string orderBy = this.IDFieldName; var postBodyData = new StringBuilder(); postBodyData.Append($"&geometry={geometry}&geometryType={geometryType}&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds="); postBodyData.Append($"&time=&maxAllowableOffset=&outFields={separatedSubFieldsString}&resultRecordCount={featureLimit}&f=pjson"); postBodyData.Append($"&returnCountOnly=false&returnIdsOnly=false&returnGeometry={true}"); return Task.FromResult<IFeatureCursor>( new GeoServicesFeatureCursor(_dataaset, this, queryUrl, postBodyData.ToString(), where)); } async public override Task<ICursor> Search(IQueryFilter filter) { var cursor = (await GetFeatures(filter)) as ICursor; return cursor; } } }
using UnityEngine; using System.Collections; public class BoardController : MonoBehaviour { private void Start(){ for(int i =0; i <this.transform.childCount; i++){ this.transform.GetChild(i).gameObject.AddComponent<DropZoneController>(); this.transform.GetChild(i).GetComponent<DropZoneController>().fieldID =new Vector2(i/3, i%3); } } }
using System.ComponentModel.DataAnnotations; namespace Foundry.Website.Models.Account { public class LoginViewModel : ViewModel { [Required(ErrorMessage = "Username is required to login.")] public string Username { get; set; } [Required(ErrorMessage = "Password is required to login.")] public string Password { get; set; } public bool RememberMe { get; set; } } }
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 WebAppAdvocacia.Models; using PagedList; using Rotativa; namespace Areas.Administracao.Controllers { public class TribunalController : Controller { private ContextoEF db = new ContextoEF(); public ActionResult GerarPDF(int? pagina) { int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; var modelo = db.Tribunais.OrderBy(e => e.Descricao).ToPagedList(numeroPagina, tamanhoPagina); var pdf = new ViewAsPdf { ViewName = "IndexParaImpressao", Model = modelo }; return pdf; } public ActionResult GerarPDFEmDetalhes(int? id) { var modelo = db.Tribunais.Find(id); var pdf = new ViewAsPdf { ViewName = "IndexParaImpressaoEmDetalhes", Model = modelo }; return pdf; } public ActionResult ConsultarTribunal(int? pagina, string DescricaoTribunal = null) { int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; var Tribunal = new object(); if (!string.IsNullOrEmpty(DescricaoTribunal)) { Tribunal = db.Tribunais .Where(e => e.Descricao.ToUpper().Contains(DescricaoTribunal.ToUpper())) .OrderBy(e => e.Descricao).ToPagedList(numeroPagina, tamanhoPagina); } else { Tribunal = db.Tribunais.OrderBy(e => e.Descricao).ToPagedList(numeroPagina, tamanhoPagina); } return View("Index", Tribunal); } // GET: Tribunal public ActionResult Index(string ordenacao, int? pagina) { var tribunais = db.Tribunais.AsQueryable(); ViewBag.OrdenacaoAtual = ordenacao; ViewBag.DescricaoTribunalParam = string.IsNullOrEmpty(ordenacao) ? "DescricaoTribunal_Desc" : ""; ViewBag.EnderecoTribunalParam = ordenacao == "EnderecoTribunal" ? "EnderecoTribunal_Desc" : "EnderecoTribunal"; int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; switch (ordenacao) { case "DescricaoTribunal_Desc": tribunais = db.Tribunais.OrderByDescending(s => s.Descricao); break; case "EnderecoTribunal": tribunais = db.Tribunais.OrderBy(s => s.Endereco); break; case "EnderecoTribunal_Desc": tribunais = db.Tribunais.OrderByDescending(s => s.Endereco); break; default: tribunais = db.Tribunais.OrderBy(s => s.Descricao); break; } return View(tribunais.ToPagedList(numeroPagina, tamanhoPagina)); } // GET: Tribunal/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Tribunal tribunal = db.Tribunais.Find(id); if (tribunal == null) { return HttpNotFound(); } return View(tribunal); } // GET: Tribunal/Create public ActionResult Create() { return View(); } // POST: Tribunal/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 = "TribunalID,Descricao,Endereco")] Tribunal tribunal) { if (ModelState.IsValid) { db.Tribunais.Add(tribunal); db.SaveChanges(); TempData["Mensagem"] = "Tribunal Cadastrado Com Sucesso!"; return RedirectToAction("Index"); } return View(tribunal); } // GET: Tribunal/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Tribunal tribunal = db.Tribunais.Find(id); if (tribunal == null) { return HttpNotFound(); } return View(tribunal); } // POST: Tribunal/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 = "TribunalID,Descricao,Endereco")] Tribunal tribunal) { if (ModelState.IsValid) { db.Entry(tribunal).State = EntityState.Modified; db.SaveChanges(); TempData["Mensagem"] = "Tribunal Atualizado Com Sucesso!"; return RedirectToAction("Index"); } return View(tribunal); } // GET: Tribunal/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Tribunal tribunal = db.Tribunais.Find(id); if (tribunal == null) { return HttpNotFound(); } return View(tribunal); } // POST: Tribunal/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Tribunal tribunal = db.Tribunais.Find(id); db.Tribunais.Remove(tribunal); db.SaveChanges(); TempData["Mensagem"] = "Tribunal Excluido Com Sucesso!"; return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Windows.Forms; using DelftTools.Controls.Swf; using NUnit.Framework; namespace DelftTools.Tests.Controls.Swf { /// <summary> /// These test are to show some 'problems' with contextmenus and combininbg them /// In order to support rich context menus we typeically want the following scenario: /// baseMenu = new Menu /// baseMenu.Extend(ContextMenu.Items) /// /// The problem is that a menuItem has an owner and there can only be 1 owner /// This could be easily solved if menuItems implemented IClonable. /// Unfortunately this is not the case. DelftTools.Shell.Gui.Swf.Controls offers /// a ClonableToolStripMenuItem class inherited from ToolStripMenuItem that can be used /// to clone objects. /// Other solutions using extension methods (no support protected members (event handlers)) /// or reflection (too complex for event handlers) have been taken into account. /// </summary> [TestFixture] public class MenuItemContextMenuStripAdapterTest { [Test] public void SimpleOwnerTest() { ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem("Test"); ContextMenuStrip contextMenuStripFirst = new ContextMenuStrip(); contextMenuStripFirst.Items.Add(toolStripMenuItem); // contextMenuStripFirst has 1 item as expected Assert.AreEqual(1, contextMenuStripFirst.Items.Count); ContextMenuStrip contextMenuStripSecond = new ContextMenuStrip(); contextMenuStripSecond.Items.Add(toolStripMenuItem); // Add same item to second menu; this will have 1 item as expected Assert.AreEqual(1, contextMenuStripSecond.Items.Count); // The first menu will have 0 items Assert.AreEqual(0, contextMenuStripFirst.Items.Count); // NB Setting toolStripMenuItem.Owner to null would have had the same effect } [Test] public void CombineMenusWithoutAdapterMenuItem() { ContextMenuStrip contextMenuStripFirst = new ContextMenuStrip(); contextMenuStripFirst.Items.Add("item1"); contextMenuStripFirst.Items.Add("item2"); contextMenuStripFirst.Items.Add("item3"); ContextMenuStrip contextMenuStripSecond = new ContextMenuStrip(); contextMenuStripSecond.Items.Add("item4"); contextMenuStripSecond.Items.Add("item5"); Assert.AreEqual(3, contextMenuStripFirst.Items.Count); Assert.AreEqual(2, contextMenuStripSecond.Items.Count); // AddRange doesn't work! // contextMenuStripFirst.Items.AddRange(contextMenuStripSecond.Items); ToolStripItem[] toolStripItems = new ToolStripItem[contextMenuStripSecond.Items.Count]; contextMenuStripSecond.Items.CopyTo(toolStripItems, 0); contextMenuStripFirst.Items.AddRange(toolStripItems); Assert.AreEqual(5, contextMenuStripFirst.Items.Count); // NB 0 is not what I want; a menuitem can only be part of 1 menu Assert.AreEqual(0, contextMenuStripSecond.Items.Count); } [Test] public void CombineMenusWithoutAdapterClonableToolStripMenuItem() { ContextMenuStrip contextMenuStripFirst = new ContextMenuStrip(); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item1" }); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item2" }); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item3" }); ContextMenuStrip contextMenuStripSecond = new ContextMenuStrip(); contextMenuStripSecond.Items.Add(new ClonableToolStripMenuItem { Text = "item4" }); contextMenuStripSecond.Items.Add(new ClonableToolStripMenuItem { Text = "item5" }); Assert.AreEqual(3, contextMenuStripFirst.Items.Count); Assert.AreEqual(2, contextMenuStripSecond.Items.Count); for (int i = 0; i < contextMenuStripSecond.Items.Count; i++) { contextMenuStripFirst.Items.Add(((ClonableToolStripMenuItem) contextMenuStripSecond.Items[i]).Clone()); } Assert.AreEqual(5, contextMenuStripFirst.Items.Count); Assert.AreEqual(2, contextMenuStripSecond.Items.Count); } [Test] public void CombineMenusWithAdapter() { ContextMenuStrip contextMenuStripFirst = new ContextMenuStrip(); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item1" }); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item2" }); contextMenuStripFirst.Items.Add(new ClonableToolStripMenuItem { Text = "item3" }); ContextMenuStrip contextMenuStripSecond = new ContextMenuStrip(); contextMenuStripSecond.Items.Add(new ClonableToolStripMenuItem { Text = "item4" }); contextMenuStripSecond.Items.Add(new ClonableToolStripMenuItem { Text = "item5" }); Assert.AreEqual(3, contextMenuStripFirst.Items.Count); Assert.AreEqual(2, contextMenuStripSecond.Items.Count); MenuItemContextMenuStripAdapter menuItemContextMenuStripAdapter = new MenuItemContextMenuStripAdapter(contextMenuStripFirst); menuItemContextMenuStripAdapter.Add(new MenuItemContextMenuStripAdapter(contextMenuStripSecond)); Assert.AreEqual(5, contextMenuStripFirst.Items.Count); Assert.AreEqual(2, contextMenuStripSecond.Items.Count); } [Test] public void TestAdapterCloningForEventHandling() { ContextMenuStrip contextMenuStripFirst = new ContextMenuStrip(); ContextMenuStrip contextMenuStripSecond = new ContextMenuStrip(); ClonableToolStripMenuItem clonableToolStripMenuItem = new ClonableToolStripMenuItem { Text = "item1" }; contextMenuStripSecond.Items.Add(clonableToolStripMenuItem); int counter = 0; clonableToolStripMenuItem.CheckedChanged += (o, e) => { counter++; }; MenuItemContextMenuStripAdapter menuItemContextMenuStripAdapter = new MenuItemContextMenuStripAdapter(contextMenuStripFirst); // Add items from second menu to first menu menuItemContextMenuStripAdapter.Add(new MenuItemContextMenuStripAdapter(contextMenuStripSecond)); Assert.AreEqual(1, contextMenuStripFirst.Items.Count); Assert.AreEqual(1, contextMenuStripSecond.Items.Count); // Both event should call the same eventhandler and thus increment the same counter var. ((ToolStripMenuItem)contextMenuStripFirst.Items[0]).Checked = !(((ToolStripMenuItem)contextMenuStripFirst.Items[0]).Checked); Assert.AreEqual(1, counter); ((ToolStripMenuItem)contextMenuStripSecond.Items[0]).Checked = !(((ToolStripMenuItem)contextMenuStripSecond.Items[0]).Checked); Assert.AreEqual(2, counter); } [Test] public void TestInsertAtOfMultiItems() { var contextMenuStripFirst = new ContextMenuStrip(); var contextMenuStripSecond = new ContextMenuStrip(); var clonableToolStripMenuItem1 = new ClonableToolStripMenuItem { Text = "item1" }; var clonableToolStripMenuItem2 = new ClonableToolStripMenuItem { Text = "item2" }; var clonableToolStripMenuItem3 = new ClonableToolStripMenuItem { Text = "item3" }; contextMenuStripFirst.Items.Add(clonableToolStripMenuItem1); contextMenuStripFirst.Items.Add(clonableToolStripMenuItem2); contextMenuStripSecond.Items.Add(clonableToolStripMenuItem3); var menuItemContextMenuStripAdapter1 = new MenuItemContextMenuStripAdapter(contextMenuStripFirst); var menuItemContextMenuStripAdapter2 = new MenuItemContextMenuStripAdapter(contextMenuStripSecond); menuItemContextMenuStripAdapter2.Insert(0, menuItemContextMenuStripAdapter1); var contextMenuStripMerged = menuItemContextMenuStripAdapter2.ContextMenuStrip; Assert.AreEqual(3, contextMenuStripMerged.Items.Count); Assert.AreEqual("item1", contextMenuStripMerged.Items[0].Text); Assert.AreEqual("item2", contextMenuStripMerged.Items[1].Text); Assert.AreEqual("item3", contextMenuStripMerged.Items[2].Text); } [Test] public void TestIndexOf() { var contextMenuStrip = new ContextMenuStrip(); var toolStripMenuItem = new ToolStripMenuItem() { Text = "item1", Name = "item1"}; var clonableToolStripMenuItem1 = new ClonableToolStripMenuItem { Text = "item2" }; var clonableToolStripMenuItem2 = new ClonableToolStripMenuItem { Text = "item3", Name = "item3" }; contextMenuStrip.Items.Add(toolStripMenuItem); contextMenuStrip.Items.Add(clonableToolStripMenuItem1); contextMenuStrip.Items.Add(clonableToolStripMenuItem2); var menuItemContextMenuStripAdapter = new MenuItemContextMenuStripAdapter(contextMenuStrip); Assert.AreEqual(0, menuItemContextMenuStripAdapter.IndexOf("item1")); Assert.AreEqual(2, menuItemContextMenuStripAdapter.IndexOf("item3")); Assert.AreEqual(-1, menuItemContextMenuStripAdapter.IndexOf("haha")); } [Test] public void ContextMenuStripIndexByName() { var contextMenuStrip = new ContextMenuStrip(); var toolStripMenuItemNotNamed = new ToolStripMenuItem() { Text = "NotNamed" }; var toolStripMenuItemNamed = new ToolStripMenuItem() { Name = "Named" }; contextMenuStrip.Items.Add(toolStripMenuItemNotNamed); contextMenuStrip.Items.Add(toolStripMenuItemNamed); Assert.IsNull(contextMenuStrip.Items["NotNamed"]); Assert.IsNotNull(contextMenuStrip.Items["Named"]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PROYECTOFINAL.Models { [Serializable] public class usuariomodel { public int IdUsuario { get; set; } public string Usuario { get; set; } public string constraseña { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; /// <summary> /// Serana Wilger /// 06/26/2020 /// Entity.cs /// /// The abstract class for Database Entities /// </summary> namespace sbwilger.DAL { public abstract class Entity { [Key] public int Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Estacionamento.Map; using Welic.Dominio.Models.Estacionamento.Services; using Welic.Dominio.Patterns.Repository.Pattern.Repositories; using Welic.Dominio.Patterns.Service.Pattern; namespace Services.Estacionamento { public class ServiceEstacionamentoVagas : Service<EstacionamentoVagasMap>, IServiceEstacionamentoVagas { public ServiceEstacionamentoVagas(IRepositoryAsync<EstacionamentoVagasMap> repository) : base(repository) { } } }
using C1.Win.C1FlexGrid; using Common; using Common.Presentation; using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace MPD.Modals { public partial class SortByColor : SkinnableModalBase { #region Private Fields private Point mCancelPt = new Point(12, 318); private Point mOKPt = new Point(559, 318); #endregion #region Constructors public SortByColor(ParameterStruct parameters, SkinnableFormBase owner, ColumnCollection cols) : base(parameters, owner) { InitializeComponent(); ApplySkin(parameters); SetCaption("Sort Status by Color"); owner.AddOwnedForm(this); LoadSortCombos(cols); } #endregion #region Public Properties /// <summary> /// Gets the list of items to sort by. /// </summary> public List<string> SortItems { get { return sorting.SortItems; } } #endregion #region Public Methods /// <summary> /// Clears the Ascending/Descending options. /// </summary> public void ClearSortOrder() { sorting.ClearSortOrder(); } #endregion #region Protected Methods protected override void DoCancel() { base.DoCancel(); } protected override void DoOK() { mResultText = (sortColor.Checked ? "1" : "0"); if (sortColor.Checked) mResultText += "-" + GetColorSortOrder(); if (mResultText.EndsWith(";")) mResultText = mResultText.Remove(mResultText.LastIndexOf(";")); mResultText += "|" + sorting.SortBy1.SelectedIndex.ToString() + "-" + (sorting.Ascending1.Checked ? "1" : "0"); if (sorting.SortBy2.SelectedIndex > -1) mResultText += "|" + sorting.SortBy2.SelectedIndex.ToString() + "-" + (sorting.Ascending2.Checked ? "1" : "0"); if (sorting.SortBy3.SelectedIndex > -1) mResultText += "|" + sorting.SortBy3.SelectedIndex.ToString() + "-" + (sorting.Ascending3.Checked ? "1" : "0"); if (sorting.SortBy4.SelectedIndex > -1) mResultText += "|" + sorting.SortBy4.SelectedIndex.ToString() + "-" + (sorting.Ascending4.Checked ? "1" : "0"); //Format: sortcolor[1|0]-color1;color2;...;colorN|sortby1-[1|0]|sortby2-[1|0]|sortby3-[1|0]|sortby4-[1|0] base.DoOK(); } private string GetColorSortOrder() { StringBuilder result = new StringBuilder(); for(int i=0; i<colorGrid.Rows.Count;i++) { CellStyle cs = colorGrid.GetCellStyle(i, 1); result.Append(cs.BackColor.ToArgb().ToString() + ";"); } return result.ToString(); } #endregion #region Private Methods private void Cancel_Click(object sender, EventArgs e) { DoCancel(); } private void LoadGrid() { for (int i = 0; i < colorGrid.Rows.Count; i++) { colorGrid.SetData(i, 0, "Drag me up or down"); } CellStyle cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["Yellow"]; colorGrid.SetCellStyle(0, 0, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["Red"]; colorGrid.SetCellStyle(0, 1, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["Orange"]; colorGrid.SetCellStyle(0, 2, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["Pink"]; colorGrid.SetCellStyle(0, 3, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["Blue"]; colorGrid.SetCellStyle(0, 4, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["LightGreen"]; colorGrid.SetCellStyle(0, 5, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = ClientPresentation.GridColors[5]; //Magenta. colorGrid.SetCellStyle(0, 6, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["DarkGray"]; colorGrid.SetCellStyle(0, 7, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["LightGray"]; colorGrid.SetCellStyle(0, 8, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["DarkYellow"]; colorGrid.SetCellStyle(0, 9, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["DarkGreen"]; colorGrid.SetCellStyle(0, 10, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["DarkBlue"]; colorGrid.SetCellStyle(0, 11, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Legend.LegendColors["LightBlue"]; colorGrid.SetCellStyle(0, 12, cs); cs = colorGrid.Styles.Add(null); cs.BackColor = Color.FromArgb(120, 20, 60); colorGrid.SetCellStyle(0, 13, cs); } private void LoadSortCombos(ColumnCollection cols) { sorting.SortBy1.Items.Clear(); sorting.SortBy2.Items.Clear(); sorting.SortBy3.Items.Clear(); sorting.SortBy4.Items.Clear(); sorting.SortBy1.Items.Add(""); sorting.SortBy2.Items.Add(""); sorting.SortBy3.Items.Add(""); sorting.SortBy4.Items.Add(""); foreach(Column col in cols) { sorting.SortBy1.Items.Add(col.Name); sorting.SortBy2.Items.Add(col.Name); sorting.SortBy3.Items.Add(col.Name); sorting.SortBy4.Items.Add(col.Name); } sorting.SortBy1.SelectedIndex = sorting.SortBy2.SelectedIndex = 0; sorting.SortBy3.SelectedIndex = sorting.SortBy4.SelectedIndex = 0; } private void OK_Click(object sender, EventArgs e) { DoOK(); } private void SortByColor_Shown(object sender, EventArgs e) { ok.Location = mOKPt; cancel.Location = mCancelPt; titleBar.HelpVisible = false; } private void SortByColor_Load(object sender, EventArgs e) { LoadGrid(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace LineOperator2.Services { public interface IExternalStoragePath { List<string> GetExternalStoragePath(); } }
using System; namespace GraphicalEditorServer.DTO.EventSourcingDTO { public class BuildingSelectionEventDTO { public String Username { get; set; } public int BuildingNumber { get; set; } public BuildingSelectionEventDTO() { } public BuildingSelectionEventDTO(string username, int buildingNumber) { Username = username; BuildingNumber = buildingNumber; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; //using IronOcr; using IronOcr.Languages; using System.Windows.Shell; using System.Diagnostics; using IronOcr; namespace Narcyzo_pomagacz { public partial class MainForm : Form { private OpenFileDialog pdfOpenDialog; private FolderBrowserDialog folderDialog; private delegate void PdfProcessCompleted(PdfExtraction pdfExtraction); private PdfExtraction pdfExtResult; public MainForm() { this.StartPosition = FormStartPosition.CenterScreen; this.FormBorderStyle = FormBorderStyle.FixedDialog; InitializeComponent(); pdfOpenDialog = new OpenFileDialog(); folderDialog = new FolderBrowserDialog(); } private void ProcessPDF(string path, PdfProcessCompleted completedCallback) { List<ExtractionRecord> extractionStruct = new List<ExtractionRecord>(); AutoOcr pdfOcr = new AutoOcr(); pdfOcr.Language = IronOcr.Languages.Polish.OcrLanguagePack; pdfOcr.ReadBarCodes = false; OcrResult ocrRes = pdfOcr.ReadPdf(path); //AspriseOCR.SetUp(); //AspriseOCR ocr = new AspriseOCR(); //string lann = AspriseOCR.ListSupportedLangs(); //ocr.StartEngine("eng", AspriseOCR.SPEED_FASTEST); //string ocrResultText = ocr.Recognize(path, -1, -1, -1, -1, -1, AspriseOCR.RECOGNIZE_TYPE_TEXT, AspriseOCR.OUTPUT_FORMAT_PLAINTEXT); //ocr.StopEngine(); string ocrString = ocrRes.Text; string[] pdfLines = ocrString.Split(new char[] { '\r', '\n' }); string date = pdfLines.Where(s => s.Contains("Dnia")).First().Replace("Dnia ", ""); string targetName = pdfLines.Where(s => s.Contains("Korespondent")).First().Replace("Korespondent", "").Trim(); string[] bill = pdfLines.Where(x => x.Contains("BILANS")).ToArray(); foreach (var line in bill) { var splitedLine = line.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries); short id = short.Parse(splitedLine[0]); int krs = Int32.Parse(splitedLine[1]); string name = splitedLine[2].Substring(0, splitedLine[2].IndexOf("BILANS")).Trim(); var years = splitedLine[2].Substring(splitedLine[2].LastIndexOf("BILANS") + "BILANS".Length).Trim().Split(';').Where(year => year.Length > 0).Select(s => Int32.Parse(s)).ToList(); var extraction = new ExtractionRecord(id, name, krs, years); extractionStruct.Add(extraction); } PdfExtraction pdfExtract = new PdfExtraction(extractionStruct, date, targetName); completedCallback.Invoke(pdfExtract); } private void ProcessData(PdfExtraction pdfResult) { pdfExtResult = pdfResult; if (this.dataGridView.InvokeRequired) { this.dataGridView.Invoke(new MethodInvoker(delegate () { pdfResult.extractionList.ForEach(element => dataGridView.Rows.Add(element.id, element.name, element.KRS, element.GetYearsString())); toolStripProgressBar.Style = ProgressBarStyle.Continuous; toolStripProgressBar.MarqueeAnimationSpeed = 0; toolStripProgressBar.Value = toolStripProgressBar.Maximum; toolStripStatusLabel_Date.Text = string.Format("Data: {0}", pdfResult.date); toolStripStatusLabel_Bilanse.Text = string.Format("Bilanse: {0}", pdfResult.extractionList.Count()); toolStripStatusLabel_Name.Text = string.Format("Korespondent: {0}", pdfResult.targetName); })); } else { pdfResult.extractionList.ForEach(element => dataGridView.Rows.Add(element.id, element.name, element.KRS, element.GetYearsString())); toolStripProgressBar.Style = ProgressBarStyle.Continuous; toolStripProgressBar.MarqueeAnimationSpeed = 0; toolStripProgressBar.Value = toolStripProgressBar.Maximum; toolStripStatusLabel_Date.Text = string.Format("Data: {0}", pdfResult.date); toolStripStatusLabel_Bilanse.Text = string.Format("Bilanse: {0}", pdfResult.extractionList.Count()); toolStripStatusLabel_Name.Text = string.Format("Korespondent: {0}", pdfResult.targetName); } Application.UseWaitCursor = false; MessageBox.Show("Process completed", "PDF Process", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void button1_Click(object sender, EventArgs e) { var result = pdfOpenDialog.ShowDialog(); if (result == DialogResult.OK) { string path = pdfOpenDialog.FileName; ThreadStart ts = new ThreadStart(() => ProcessPDF(path, (pdfResult) => ProcessData(pdfResult))); Thread pdfTherad = new Thread(ts); pdfTherad.Priority = ThreadPriority.Highest; pdfTherad.Start(); toolStripProgressBar.Style = ProgressBarStyle.Marquee; toolStripProgressBar.MarqueeAnimationSpeed = 30; Application.UseWaitCursor = true; Console.WriteLine("koniec"); } } string projPath = ""; private void buttonProcess_Click(object sender, EventArgs e) { if(folderDialog.ShowDialog() == DialogResult.OK && pdfExtResult != null) { string folderPath = folderDialog.SelectedPath; string projectPath = Path.Combine(folderPath, pdfExtResult.date); projPath = projectPath; if (!Directory.Exists(projectPath)) { Directory.CreateDirectory(projectPath); foreach (var company in pdfExtResult.extractionList) { string folderName = string.Format("{0}_{1}", company.KRS, company.years.Last()); Directory.CreateDirectory(Path.Combine(projectPath, folderName)); } } string cmd = "explorer.exe"; string arg = "/select, " + projectPath; Process.Start(cmd, arg); } } private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; if (e.RowIndex >= 0) { //TODO - Button Clicked - Execute Code Here var selectedRow = pdfExtResult.extractionList[e.RowIndex]; string folderTarget = string.Format("{0}_{1}", selectedRow.KRS, selectedRow.years.Last()); string folderTargetPath = Path.Combine(projPath, folderTarget); string cmd = "explorer.exe"; string arg = "/open, " + folderTargetPath; Process.Start(cmd, arg); } } private void MainForm_Load(object sender, EventArgs e) { } } }
using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace Port_v2._0 { public class dbConnection { // Строка подключения private static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PortConnectionString"].ConnectionString); // открытие подключения к базе данных, если оно было закрыто или разорвано private static SqlConnection openConnection() { if (conn.State == ConnectionState.Closed) { conn.Open(); } else { MessageBox.Show("Ошибка подключения!"); } return conn; } // получить таблицу из запроса public static DataTable GetDataTable(string Q) { DataTable DT = new DataTable(); SqlCommand myCommand = new SqlCommand(); SqlDataAdapter myAdapter = new SqlDataAdapter(); myCommand.Connection = openConnection(); myCommand.CommandText = Q; myCommand.ExecuteNonQuery(); myAdapter.SelectCommand = myCommand; myAdapter.Fill(DT); myCommand.Connection.Close(); return DT; } // получить таблицу из запроса c параметрами public static DataTable GetDataTablePar(string Q, SqlParameter[] sqlParameter) { DataTable dataTable = new DataTable(); SqlCommand myCommand = new SqlCommand(); SqlDataAdapter myAdapter = new SqlDataAdapter(); dataTable = null; DataSet ds = new DataSet(); try { myCommand.Connection = openConnection(); myCommand.CommandText = Q; myCommand.Parameters.AddRange(sqlParameter); myCommand.ExecuteNonQuery(); myAdapter.SelectCommand = myCommand; myAdapter.Fill(ds); dataTable = ds.Tables[0]; } catch (SqlException e) { MessageBox.Show("Хм..., что-то пошло не так =)", "Упс...", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } finally { myCommand.Connection.Close(); } return dataTable; } // Выполнение транцакций 1 c параметрами public static DataTable GetT1(string query1, string query2, string query3, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); myCommand.Connection = openConnection(); SqlTransaction transaction = conn.BeginTransaction(); myCommand.Transaction = transaction; try { myCommand.CommandText = query2; myCommand.Parameters.AddRange(sqlParameter); myCommand.ExecuteNonQuery(); //выполняем запрос myCommand.CommandText = query1; myCommand.ExecuteNonQuery(); myCommand.CommandText = query3; myCommand.ExecuteNonQuery(); //выполняем запрос transaction.Commit(); //подтверждаем транзакцию MessageBox.Show("Все данные были успешно добавлены"); } catch //если возникла ошибка, выходим из транзакции с откатом { MessageBox.Show("Ошибка транзакции!"); try { transaction.Rollback(); } catch { MessageBox.Show("Ошибка отката транзакции!"); } } finally { myCommand.Connection.Close(); } return null; } // Выполнение транцакций 2 c параметрами public static DataTable GetT2(string query, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); myCommand.Connection = openConnection(); SqlTransaction transaction = conn.BeginTransaction(); myCommand.Transaction = transaction; try { myCommand.CommandText = query; myCommand.Parameters.AddRange(sqlParameter); myCommand.ExecuteNonQuery(); //выполняем запрос transaction.Commit(); //подтверждаем транзакцию MessageBox.Show("Транзакция выполнена успешно"); } catch //если возникла ошибка, выходим из транзакции с откатом { MessageBox.Show("Ошибка транзакции!"); try { transaction.Rollback(); } catch { MessageBox.Show("Ошибка отката транзакции!"); } } finally { myCommand.Connection.Close(); } return null; } } }
namespace InterpreterSample { public abstract class Node { public abstract void Parse(Context context); } }
using System; using System.Linq; using System.Windows.Input; using Xamarin.Forms; using Plugin.Permissions; using Plugin.Permissions.Abstractions; namespace Tianhai.OujiangApp.Schedule.ViewModels{ public class AboutViewModel:BaseViewModel{ public INavigation Navigation{get;set;} public AboutViewModel(Page Page){ Title="更多"; RefreshScheduleCommand=new Command(async ()=>{ this.btnRefreshScheduleIsEnabled=false; try{ var result=await Services.ScheduleService.RefreshCurrentLessons(); if(result!=null){ await Page.DisplayAlert("哇!","课表已经更新当前学期最新版本。","好耶"); } }catch(Exceptions.SessionTimeoutException){ await Navigation.PushAsync(new Views.LoginPage()); }catch(Exception e){ await Page.DisplayAlert("遇到未知错误",e.Message,"好的"); } this.btnRefreshScheduleIsEnabled=true; return; }); CalendarSyncCommand=new Command(async ()=>{ btnCalendarSyncIsEnabled=false; try{ var accountName=Services.CalendarService.GetAccountName(); var status=await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Calendar); if(status!=PermissionStatus.Granted){ if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Calendar)){ await Page.DisplayAlert("权限申请","我们接下来将向系统申请读写日历的权限。","好啊"); } var results=await CrossPermissions.Current.RequestPermissionsAsync(Permission.Calendar); if(results.ContainsKey(Permission.Calendar)){ status=results[Permission.Calendar]; } } if(status==PermissionStatus.Granted){ await Page.Navigation.PushAsync(new Views.CalendarSyncPage()); }else if(status!=PermissionStatus.Unknown){ await Page.DisplayAlert("没有权限","权限申请失败或您拒绝了权限申请,不能继续。","好吧"); } }catch(Exceptions.NotLoggedInException){ await Page.DisplayAlert("压根儿没登入","你还一次都没有登入过,不能同步。请先使用“更新课表”。","好的"); }catch(Exception e){ await Page.DisplayAlert("未知错误",e.Message,"好的"); } btnCalendarSyncIsEnabled=true; }); } public ICommand RefreshScheduleCommand{get;} public ICommand CalendarSyncCommand{get;} private bool _btnCalendarSyncIsEnabled=true; public bool btnCalendarSyncIsEnabled{ get{ return _btnCalendarSyncIsEnabled; } set{ _btnCalendarSyncIsEnabled=value; OnPropertyChanged(); } } private bool _btnRefreshScheduleIsEnabled=true; public bool btnRefreshScheduleIsEnabled{ get{ return _btnRefreshScheduleIsEnabled; } set{ _btnRefreshScheduleIsEnabled=value; OnPropertyChanged(); } } } }
using System; using System.Collections; using System.Collections.Generic; using CQRS.MediatR.Query; namespace Scheduler.FileService.Queries { public class ReadCsv : IQuery<ICollection> { public Type Type { get; } public string FilePath { get; set; } public int Take { get; set; } public int Skip { get; set; } public ReadCsv(Type type,string filePath) { Type = type; FilePath = filePath; } } }
using System; using System.Text; using System.Collections; using System.Xml; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Resources; using System.Reflection; using System.Globalization; using System.Threading; using Telerik.WebControls; using UFSoft.UBF.UI.WebControls; using UFSoft.UBF.UI.Controls; using UFSoft.UBF.Util.Log; using UFSoft.UBF.Util.Globalization; using UFSoft.UBF.UI.IView; using UFSoft.UBF.UI.Engine; using UFSoft.UBF.UI.MD.Runtime; using UFSoft.UBF.UI.ActionProcess; using UFSoft.UBF.UI.WebControls.ClientCallBack; using U9.VOB.Cus.HBHTianRiSheng.Proxy; using System.Collections.Specialized; using UFIDA.U9.UI.PDHelper; using UFSoft.UBF.ExportService; using System.Collections.Generic; /*********************************************************************************************** * Form ID: * UIFactory Auto Generator ***********************************************************************************************/ namespace FollowServiceUIModel { public partial class FollowServiceUIFormWebPart { public string WorkTypeValueSetCode = string.Empty; public string DeliveryTypeValueSetCode = string.Empty; #region Custome eventBind //BtnSave_Click... private void BtnSave_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnSave_Click_DefaultImpl(sender, e); } //BtnCancel_Click... private void BtnCancel_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnCancel_Click_DefaultImpl(sender, e); } //BtnAdd_Click... private void BtnAdd_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnAdd_Click_DefaultImpl(sender, e); } //BtnDelete_Click... private void BtnDelete_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnDelete_Click_DefaultImpl(sender, e); } //BtnCopy_Click... private void BtnCopy_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnCopy_Click_DefaultImpl(sender, e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_AfterCopy(this.Model.FollowService); } //BtnSubmit_Click... private void BtnSubmit_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnSubmit_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approving); } //BtnApprove_Click... private void BtnApprove_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnApprove_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approved); } //BtnRecovery_Click... private void BtnRecovery_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnRecovery_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Opened); } //BtnUndoApprove_Click... private void BtnUndoApprove_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnUndoApprove_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Opened); } //BtnFind_Click... private void BtnFind_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnFind_Click_DefaultImpl(sender, e); } //BtnList_Click... private void BtnList_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnList_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_BtnList_Click(this); } //BtnFirstPage_Click... private void BtnFirstPage_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnFirstPage_Click_DefaultImpl(sender, e); } //BtnPrevPage_Click... private void BtnPrevPage_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnPrevPage_Click_DefaultImpl(sender, e); } //BtnNextPage_Click... private void BtnNextPage_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnNextPage_Click_DefaultImpl(sender, e); } //BtnLastPage_Click... private void BtnLastPage_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnLastPage_Click_DefaultImpl(sender, e); } //BtnAttachment_Click... private void BtnAttachment_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnAttachment_Click_DefaultImpl(sender, e); } //BtnFlow_Click... private void BtnFlow_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnFlow_Click_DefaultImpl(sender, e); } //BtnOutput_Click... private void BtnOutput_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnOutput_Click_DefaultImpl(sender, e); } //BtnPrint_Click... private void BtnPrint_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. BtnPrint_Click_DefaultImpl(sender, e); } //BtnOk_Click... private void BtnOk_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnOk_Click_DefaultImpl(sender,e); this.CloseDialog(true); } //BtnClose_Click... private void BtnClose_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnClose_Click_DefaultImpl(sender,e); this.CloseDialog(false); } //BtnReview_Click... private void BtnReview_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnReview_Click_DefaultImpl(sender,e); FollowServiceRecord focused = this.Model.FollowService.FocusedRecord; if (focused != null && focused.ID > 0 ) { NameValueCollection nv = new NameValueCollection(); nv.Add("SrcDoc", focused.ID.ToString()); // 列表 910f434c-9933-4910-9f03-d4502cae2285 this.ShowModalDialog("d5d270d8-ba8a-4a9d-98c3-c3e7cac03135", "售后回报单结果", "992", "504", string.Empty , nv); } } //BtnToFeeback_Click... private void BtnToFeeback_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnToFeeback_Click_DefaultImpl(sender,e); FollowServiceRecord focused = this.Model.FollowService.FocusedRecord; if (focused != null && focused.ID > 0 ) { Follow2FeedbackSVProxy proxy = new Follow2FeedbackSVProxy(); proxy.FollowIDs = new System.Collections.Generic.List<long>(); proxy.FollowIDs.Add(focused.ID); proxy.Do(); BtnReview_Click_Extend(sender, e); } } //BtnDocClose_Click... private void BtnDocClose_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnDocClose_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Closed); } //BtnDocOpen_Click... private void BtnDocOpen_Click_Extend(object sender, EventArgs e) { //调用模版提供的默认实现.--默认实现可能会调用相应的Action. //BtnDocOpen_Click_DefaultImpl(sender,e); U9.VOB.HBHCommon.HBHCommonUI.HBHUIHelper.UIForm_UpdateStatus(this, this.Model.FollowService, U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Opened); } #endregion #region 自定义数据初始化加载和数据收集 private void OnLoadData_Extend(object sender) { OnLoadData_DefaultImpl(sender); } private void OnDataCollect_Extend(object sender) { OnDataCollect_DefaultImpl(sender); } #endregion #region 自己扩展 Extended Event handler public void AfterOnLoad() { } public void AfterCreateChildControls() { //查找对话框。 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowConfirmDialog(this.Page, "5d9958c0-1a8f-49ca-97cc-8c2e1b30e8d1", "580", "408", Title, wpFindID.ClientID, this.BtnFind, null); // 取得提示信息资源:是否删除当前记录 string message = UFIDA.U9.UI.PDHelper.PDResource.GetDeleteConfirmInfo(); // 绑定注册弹出对话框到按钮 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowDelConfirmDialog(this.Page, message, "", this.BtnDelete); // 启用页面个性化 UFIDA.U9.UI.PDHelper.PersonalizationHelper.SetPersonalizationEnable(this, true); // 启用弹性域 UFIDA.U9.UI.PDHelper.FlexFieldHelper.SetDescFlexField(new UFIDA.U9.UI.PDHelper.DescFlexFieldParameter(this.FlexFieldPicker0, this.Model.FollowService) ); // 绑定注册弹出对话框到按钮 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowDelConfirmDialog(this.Page, "确认审核?", "确认审核", this.BtnApprove); // 绑定注册弹出对话框到按钮 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowDelConfirmDialog(this.Page, "确认转回报单?", "确认转回报单", this.BtnToFeeback); // 绑定注册弹出对话框到按钮 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowDelConfirmDialog(this.Page, "确认关闭?", "确认关闭", this.BtnDocClose); // 绑定注册弹出对话框到按钮 UFIDA.U9.UI.PDHelper.PDFormMessage.ShowDelConfirmDialog(this.Page, "确认打开?", "确认打开", this.BtnDocOpen); if (string.IsNullOrEmpty(DeliveryTypeValueSetCode)) { DeliveryTypeValueSetCode = U9.VOB.HBHCommon.HBHCommonUI.UICommonHelper.GetValueSetCode("TianRiSheng_DeliveryTypeCode_Follow"); } // 发运方式 this.DeliveryType195.AddTypeParams("DefCode" // , U9.VOB.Cus.HBHTianRiSheng.HBHHelper.DescFlexFieldHelper.Const_DeliveryTypeCode , DeliveryTypeValueSetCode ); if (string.IsNullOrEmpty(WorkTypeValueSetCode)) { WorkTypeValueSetCode = U9.VOB.HBHCommon.HBHCommonUI.UICommonHelper.GetValueSetCode("TianRiSheng_WorkTypeCode_Follow"); } WorkType118.CustomInParams = string.Format("DefCode={0}" , WorkTypeValueSetCode ); //UIControlBuilder.SetLabelFormReference(this.lblDocumentType67, "4723b733-117e-424d-a25d-e42f54d720d9", true, 992, 504); //this.lblDeliveryType195.WinTitle = Const_ParamTitle; //this.lblWorkType118.WinTitle = Const_ParamTitle; UFSoft.UBF.UI.Engine.Builder.UIControlBuilder.SetLabelFormReference(this.lblDeliveryType195, U9.VOB.Cus.HBHTianRiSheng.HBHTianRiShengUI.UIHelper.Const_ParamTitle, true, 992, 504); UFSoft.UBF.UI.Engine.Builder.UIControlBuilder.SetLabelFormReference(this.lblWorkType118, U9.VOB.Cus.HBHTianRiSheng.HBHTianRiShengUI.UIHelper.Const_ParamTitle, true, 992, 504); this.PageItem_Operators85.CustomInParams = string.Format("{0}={1}" , MultiOperatorRef.MultiOperatorRefWebPart.Const_RefType , MultiOperatorRef.MultiOperatorRefWebPart.Const_IsSingleReturn ); } public void AfterEventBind() { } public void BeforeUIModelBinding() { } public void AfterUIModelBinding() { FollowServiceRecord focusedHead = this.Model.FollowService.FocusedRecord; if (focusedHead == null) return; //U9.VOB.HBHCommon.HBHCommonUI.UISceneHelper.SetToolBarStatus(this.Toolbar2 // , status, focusedHead.DataRecordState, false, 0, 1, 2, 2); U9.VOB.HBHCommon.HBHCommonUI.UISceneHelper.SetToolBarStatus(this.Toolbar2 , focusedHead.Status ?? (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Empty, focusedHead.DataRecordState, false, (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Opened, (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approving, (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approved, 1 , (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Closed , new List<int>() { (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approved } ); //this.BtnSave.Enabled = true; this.BtnOk.Visible = false; this.BtnClose.Visible = false; this.SrcDoc118.Enabled = false; bool isButtonEnabled = this.IsCurrentPrintable(focusedHead); ButtonManger.SetButtonStatus(this, "BtnPrint", isButtonEnabled); this.DocumentType67.Enabled = true; if (focusedHead.ID > 0) { if (focusedHead.Status == (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approving || focusedHead.Status == (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approved || focusedHead.Status == (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Closed ) { this.DocumentType67.Enabled = false; } } this.RegisterClientPrintScript(); } #endregion #region Customer Method public bool IsCurrentPrintable(FollowServiceRecord record) { return record != null && (record.DocumentType_PrintStyle == 0 || (record.Status == (int)U9.VOB.HBHCommon.U9CommonBE.DocStatusData.Approved && record.DocumentType_PrintStyle == 1)); } private void RegisterClientPrintScript() { string ufDefaultPrintTemplateID = null; if (this.Model.FollowService.FocusedRecord != null) { ufDefaultPrintTemplateID = this.Model.FollowService.FocusedRecord.DocumentType_PrintTemplate_TemplateID; } ExportServiceFactory.RegisterClientExportScript(this, this.BtnOutput, "U9.VOB.Cus.HBHTianRiSheng.FollowService"); FollowServiceRecord focusedRecord = this.Model.FollowService.FocusedRecord; UFPrintStyle printStyle = PDPrintHelper.TransPrintMode(focusedRecord.DocumentType_PrintStyle); ExportServiceFactory.RegisterClientPrintScript(this, this.BtnPrint, "U9.VOB.Cus.HBHTianRiSheng.FollowService", ufDefaultPrintTemplateID, null, false, printStyle); //if (this.Action.IsCanBePrintByStatus(this.Model.FollowService.FocusedRecord)) if (this.Action.IsCanBePrintByStatus(this.Model.FollowService.FocusedRecord)) { PDPrintHelper.SetBtnPrintStatus(this.Model.FollowService, new UFSoft.UBF.UI.ControlModel.IUFButton[] { this.BtnPrint }); //PDPrintHelper.SetBtnPrintStatus(this.Model.FollowService, new UFSoft.UBF.UI.ControlModel.IUFButton[] //{ // this.BtnFastPrint //}); } else { this.BtnPrint.Enabled = false; //this.BtnFastPrint.Enabled = false; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XH.Infrastructure.Query; namespace XH.Queries.Projects.Queries { public class ListProjectsQuery : ListQueryBase { public string Keywords { get; set; } } }
using System; using System.Threading.Tasks; using System.Net.Http; using PCLStorage; using System.IO; namespace CC.Utilities { public class DownloadManager { async public Task DownloadFileAsync(string url, string path){ using (var client = new HttpClient ()) { var request = new HttpRequestMessage (HttpMethod.Get, url); var sendTask = client.SendAsync (request, HttpCompletionOption.ResponseHeadersRead); var response = sendTask.Result.EnsureSuccessStatusCode (); var httpStream = await response.Content.ReadAsStreamAsync (); var storage = FileSystem.Current.LocalStorage; var file = await storage.CreateFileAsync (path, CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenAsync (FileAccess.ReadAndWrite)) { using (var reader = new StreamReader (httpStream)) { await httpStream.CopyToAsync (fileStream); await fileStream.FlushAsync (); } } } } } }
namespace Leprechaun.MetadataGeneration { public interface ITypeNameGenerator { string GetFullTypeName(string fullPath); string ConvertToIdentifier(string name); } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.Command.Example4 { public class ApplicationMakeText { public string CurrentText { get; set; } public string currentCode = "-1"; public const string EXIT_CODE = "0"; CommandHistory history; Func<ApplicationMakeText, TextEditor, BaseCommand> Insert = (ApplicationMakeText app, TextEditor editor) => { return new InsertTextCommand(app, editor); }; Func<ApplicationMakeText, TextEditor, BaseCommand> Remove = (ApplicationMakeText app, TextEditor editor) => { return new RemoveTextCommand(app, editor); }; Func<ApplicationMakeText, TextEditor, BaseCommand> UndoCommand = (ApplicationMakeText app, TextEditor editor) => { return new UndoCommand(app, editor); }; public void ExecuteCommand(BaseCommand command) { if(command.Execute()) history.Push(command); } public void Undo() { var command = history.Pop(); command?.Undo(); } public static void Run() { var app = new ApplicationMakeText(); var editor = new TextEditor(); app.history = new CommandHistory(); Action createMenu = () => { Console.Clear(); Console.WriteLine("Choose a command and type the word/phrase you should put into the system"); Console.WriteLine("e.g. 1|Put this text into the system"); Console.WriteLine("Options:"); Console.WriteLine("1 - Insert text"); Console.WriteLine("2 - Remove text"); Console.WriteLine("3 - Undo"); Console.WriteLine("0 - Exit"); }; Action getUserInput = () => { var input = Console.ReadLine().Split("|"); if(input.Length > 1) app.CurrentText = input[1]; app.currentCode = input[0]; }; Dictionary<string, Func<BaseCommand>> commands = new Dictionary<string, Func<BaseCommand>>(); commands.Add("1", () => app.Insert(app, editor)); commands.Add("2", () => app.Remove(app, editor)); commands.Add("3", () => app.UndoCommand(app, editor)); createMenu(); getUserInput(); while (app.currentCode != EXIT_CODE) { var command = commands[app.currentCode](); app.ExecuteCommand(command); createMenu(); Console.WriteLine("\n\nLast Result:"); Console.WriteLine(editor.Text); getUserInput(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; public class SpawnEnemy : MonoBehaviour { public GameObject playerPrefab; // Start is called before the first frame update void Start() { SpawnEnemyy(); } // Update is called once per frame void SpawnEnemyy() { PhotonNetwork.Instantiate(playerPrefab.name, playerPrefab.transform.position, playerPrefab.transform.rotation); } }
using System; /*Write an expression that checks for given integer if its third digit from right-to-left is 7.*/ class ThirdDigitIs7 { static void Main() { Console.Write("number = "); int number = Convert.ToInt32(Console.ReadLine()); bool isTrue = false; if ((number / 100) % 10 == 7) isTrue = true; Console.WriteLine(isTrue); } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FifthBot.Resources.Database { public class ServerSetting { [Key] public ulong ServerID { get; set; } public string ServerName { get; set; } /* public int purgerInterval { get; set; } public string mutedRole { get; set; } public string intAdminGroups { get; set; } [NotMapped] public string[] adminGroups { get { return intAdminGroups.Split(';'); } set { string[] data = value; this.intAdminGroups = String.Join(";", data); } } public string intModGroups { get; set; } [NotMapped] public string[] modGroups { get { return intModGroups.Split(';'); } set { string[] data = value; this.intModGroups = String.Join(";", data); } } public string intIntroChannels { get; set; } [NotMapped] public string[] introChannels { get { return intIntroChannels.Split(';'); } set { string[] data = value; this.intIntroChannels = String.Join(";", data); } } */ } }
using System.Reflection.Emit; namespace IronAHK.Scripting { internal struct LoopMetadata { public Label Begin; public Label End; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class glucose_control : MonoBehaviour { public GameObject glucose_stick; public void glucose_animation() { glucose_stick.GetComponent<Animator>().Play("glucose_color_change"); } }
using CollaborativeFiltering; using CollaborativeFilteringUI.Core.Utils; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CollaborativeFilteringUI.Utils { public class ResultsPersister { public void SaveResults(List<Pair<string, double>> results, string evaluationMethod, string filePath) { var sb = new StringBuilder(); sb.AppendLine(evaluationMethod); foreach (var result in results) sb.AppendLine(result.Item1.ToString() + "," + result.Item2.ToString(CultureInfo.InvariantCulture)); File.WriteAllText(filePath, sb.ToString()); } public void LoadResults(string filePath, out List<Pair<string, double>> results, out string evaluationMethod) { var lines = File.ReadAllLines(filePath); evaluationMethod = lines[0]; results = new List<Pair<string, double>>(); for(int i = 1; i < lines.Length; ++i) { var split = lines[i].Split(','); var value = double.Parse(split[1], CultureInfo.InvariantCulture); results.Add(new Pair<string, double>(split[0], value)); } } } }
using System; using System.Collections.Generic; using System.Text; namespace _03._Battle_Manager { public class BattleList { public static List<BattlePerson> Battles { get; set; } = new List<BattlePerson>(); public static void DeleteAll(string username) { BattleList.Battles.RemoveRange(0, BattleList.Battles.Count); } public static void Delete(string username) { var user = BattleList.Battles.Find(x => x.Name == username); if (user != null) { BattleList.Battles.Remove(user); } } public static void Attack(string attackerName, string defenderName, int damage) { var attacker = BattleList.Battles.Find(x => x.Name == attackerName); var defender = BattleList.Battles.Find(x => x.Name == defenderName); if ((attacker != null) && (defender != null)) { defender.Health -= damage; attacker.Energy -= 1; if (defender.Health <= 0) { BattleList.Battles.Remove(defender); Console.WriteLine($"{defenderName} was disqualified!"); } if (attacker.Energy == 0) { BattleList.Battles.Remove(attacker); Console.WriteLine($"{attackerName} was disqualified!"); } } } public static void AddPerson(string name, int health, int energy) { var person = BattleList.Battles.Find(x => x.Name == name); if (person != null) { person.Health += health; } else { BattleList.Battles.Add(BattlePerson.CreatePerson(name, health, energy)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IridiumToolsPatch { public class ModConfig { public int length; public int radius; public ModConfig() { length = 5; radius = 2; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using xKnight.Models; namespace xKnight.Attacking { public class EncodedXssAttackAnnounceItem : AttackAnnounceItem { public XAttack XAttack { get; private set; } public EncodedXssAttackStatus AttackStatus { get; private set; } public EncodedXssAttackAnnounceItem(XAttack xAttack, EncodedXssAttackStatus attackStatus, XssAttackingSharedReource attackingSharedResource, string description, DateTime dateTime) :base(attackingSharedResource,description,dateTime) { this.XAttack = xAttack; this.AttackStatus = attackStatus; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using CODE.Framework.Wpf.Utilities; namespace CODE.Framework.Wpf.Mvvm { /// <summary> /// Special menu object that can be bound to a collection of view actions to automatically and dynamically populate the menu. /// </summary> public class ViewActionRibbon : TabControl { /// <summary> /// Initializes a new instance of the <see cref="ViewActionRibbon" /> class. /// </summary> public ViewActionRibbon() { SelectionChanged += (s, e) => { if (!FirstPageIsSpecial) return; if (SelectedIndex == 0) { IsSpecialFirstPageActive = true; if (!IsLoaded && !_mustRaiseSpecialFirstPageActivateEventOnLoad) _mustRaiseSpecialFirstPageActivateEventOnLoad = true; if (!IsLoaded && _mustRaiseSpecialFirstPageDeactivateEventOnLoad) _mustRaiseSpecialFirstPageDeactivateEventOnLoad = false; } else { IsSpecialFirstPageActive = false; if (!IsLoaded && _mustRaiseSpecialFirstPageActivateEventOnLoad) _mustRaiseSpecialFirstPageActivateEventOnLoad = false; if (!IsLoaded && !_mustRaiseSpecialFirstPageDeactivateEventOnLoad) _mustRaiseSpecialFirstPageDeactivateEventOnLoad = true; if (SelectedIndex > -1) LastRegularIndex = SelectedIndex; } Visibility = SelectedIndex == 0 ? Visibility.Hidden : Visibility.Visible; }; Loaded += (s, e) => { if (_mustRaiseSpecialFirstPageDeactivateEventOnLoad) RaiseEvent(new RoutedEventArgs(SpecialFirstPageDeactivateEvent)); if (_mustRaiseSpecialFirstPageActivateEventOnLoad) RaiseEvent(new RoutedEventArgs(SpecialFirstPageActivateEvent)); if (_setSelectedIndexOnLoadComplete > -1) { SelectedIndex = _setSelectedIndexOnLoadComplete; _setSelectedIndexOnLoadComplete = -1; } }; Initialized += (o, e) => { var window = ElementHelper.FindParent<Window>(this) ?? ElementHelper.FindVisualTreeParent<Window>(this); if (window == null) return; window.PreviewKeyDown += (s, a) => { var key = a.Key; var systemKey = a.SystemKey; if (GetKeyboardShortcutsActive(this)) { if (SelectedIndex < 0 || SelectedIndex >= Items.Count) return; var page = Items[SelectedIndex] as RibbonPage; if (page == null) return; var panel = page.Content as RibbonPageLayoutPanel; if (panel == null) return; foreach (var child in panel.Children) { var button = child as RibbonButton; if (button == null || string.IsNullOrEmpty(button.AccessKey) || button.AccessKey != a.Key.ToString() || button.Command == null) continue; var command = button.Command as ViewAction; if (command == null || !command.CanExecute(button.CommandParameter)) continue; command.Execute(button.CommandParameter); SetKeyboardShortcutsActive(window, false); a.Handled = true; return; } } if ((key == Key.LeftAlt || key == Key.RightAlt) || (key == Key.System && (systemKey == Key.LeftAlt || systemKey == Key.RightAlt))) { if (!ReadyForStatusChange) return; var state = !GetKeyboardShortcutsActive(window); SetKeyboardShortcutsActive(window, state); ReadyForStatusChange = !state; a.Handled = true; } else if (key == Key.Escape) { if (!GetKeyboardShortcutsActive(this)) return; SetKeyboardShortcutsActive(window, false); ReadyForStatusChange = true; a.Handled = true; } }; PreviewMouseDown += (s, a) => { if (!GetKeyboardShortcutsActive(this)) return; SetKeyboardShortcutsActive(window, false); ReadyForStatusChange = true; }; window.PreviewMouseDown += (s, a) => { if (!GetKeyboardShortcutsActive(this)) return; SetKeyboardShortcutsActive(window, false); ReadyForStatusChange = true; }; window.PreviewKeyUp += (s, a) => { var key = a.Key; var systemKey = a.SystemKey; if ((key == Key.LeftAlt || key == Key.RightAlt) || (key == Key.System && (systemKey == Key.LeftAlt || systemKey == Key.RightAlt))) ReadyForStatusChange = true; }; }; } /// <summary> /// Background/theme brush used by the ribbon /// </summary> /// <value>The ribbon theme brush.</value> public Brush RibbonThemeBrush { get { return (Brush)GetValue(RibbonThemeBrushProperty); } set { SetValue(RibbonThemeBrushProperty, value); } } /// <summary> /// Background/theme brush used by the ribbon /// </summary> public static readonly DependencyProperty RibbonThemeBrushProperty = DependencyProperty.Register("RibbonThemeBrush", typeof(Brush), typeof(ViewActionRibbon), new PropertyMetadata(null)); /// <summary> /// Background brush for the selected ribbon page /// </summary> /// <value>The ribbon selected page brush.</value> public Brush RibbonSelectedPageBrush { get { return (Brush)GetValue(RibbonSelectedPageBrushProperty); } set { SetValue(RibbonSelectedPageBrushProperty, value); } } /// <summary> /// Background brush for the selected ribbon page /// </summary> public static readonly DependencyProperty RibbonSelectedPageBrushProperty = DependencyProperty.Register("RibbonSelectedPageBrush", typeof(Brush), typeof(ViewActionRibbon), new PropertyMetadata(null)); /// <summary> /// For internal use only /// </summary> protected bool ReadyForStatusChange = true; /// <summary>Indicates whether the user has pressed the ALT key and thus activated display of keyboard shortcuts</summary> public static readonly DependencyProperty KeyboardShortcutsActiveProperty = DependencyProperty.RegisterAttached("KeyboardShortcutsActive", typeof (bool), typeof (ViewActionRibbon), new FrameworkPropertyMetadata(false) {Inherits = true}); /// <summary>Indicates whether the user has pressed the ALT key and thus activated display of keyboard shortcuts</summary> /// <param name="obj">The obj.</param> /// <returns>System.String.</returns> public static bool GetKeyboardShortcutsActive(DependencyObject obj) { return (bool) obj.GetValue(KeyboardShortcutsActiveProperty); } /// <summary>Indicates whether the user has pressed the ALT key and thus activated display of keyboard shortcuts</summary> public static void SetKeyboardShortcutsActive(DependencyObject obj, bool value) { obj.SetValue(KeyboardShortcutsActiveProperty, value); } /// <summary> /// Indicates whether the first ribbon page is to be handled differently as a file menu /// </summary> public bool FirstPageIsSpecial { get { return (bool) GetValue(FirstPageIsSpecialProperty); } set { SetValue(FirstPageIsSpecialProperty, value); } } /// <summary> /// Indicates whether the first ribbon page is to be handled differently as a file menu /// </summary> public static readonly DependencyProperty FirstPageIsSpecialProperty = DependencyProperty.Register("FirstPageIsSpecial", typeof (bool), typeof (ViewActionRibbon), new PropertyMetadata(true)); /// <summary> /// For internal use only /// </summary> protected int LastRegularIndex = -1; /// <summary> /// Title for empty global category titles (default: File) /// </summary> public string EmptyGlobalCategoryTitle { get { return (string) GetValue(EmptyGlobalCategoryTitleProperty); } set { SetValue(EmptyGlobalCategoryTitleProperty, value); } } /// <summary> /// Title for empty global category titles (default: File) /// </summary> public static readonly DependencyProperty EmptyGlobalCategoryTitleProperty = DependencyProperty.Register("EmptyGlobalCategoryTitle", typeof (string), typeof (ViewActionRibbon), new PropertyMetadata("File")); /// <summary> /// Title for empty local category titles (default: File) /// </summary> public string EmptyLocalCategoryTitle { get { return (string) GetValue(EmptyLocalCategoryTitleProperty); } set { SetValue(EmptyLocalCategoryTitleProperty, value); } } /// <summary> /// Title for empty local category titles (default: File) /// </summary> public static readonly DependencyProperty EmptyLocalCategoryTitleProperty = DependencyProperty.Register("EmptyLocalCategoryTitle", typeof (string), typeof (ViewActionRibbon), new PropertyMetadata("File")); /// <summary> /// Indicates whether local categories (ribbon pages populated from local/individual view actions) shall use the special colors /// </summary> public bool HighlightLocalCategories { get { return (bool) GetValue(HighlightLocalCategoriesProperty); } set { SetValue(HighlightLocalCategoriesProperty, value); } } /// <summary> /// Indicates whether local categories (ribbon pages populated from local/individual view actions) shall use the special colors /// </summary> public static readonly DependencyProperty HighlightLocalCategoriesProperty = DependencyProperty.Register("HighlightLocalCategories", typeof (bool), typeof (ViewActionRibbon), new PropertyMetadata(true)); /// <summary> /// Indicates whether the first special ribbon page is active /// </summary> public bool IsSpecialFirstPageActive { get { return (bool) GetValue(IsSpecialFirstPageActiveProperty); } set { SetValue(IsSpecialFirstPageActiveProperty, value); } } /// <summary> /// Indicates whether the first special ribbon page is active /// </summary> public static readonly DependencyProperty IsSpecialFirstPageActiveProperty = DependencyProperty.Register("IsSpecialFirstPageActive", typeof (bool), typeof (ViewActionRibbon), new PropertyMetadata(false, IsSpecialFirstPageActiveChanged)); /// <summary> /// Determines whether [is special first page active changed] [the specified dependency object]. /// </summary> /// <param name="d">The dependency object.</param> /// <param name="args">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> private static void IsSpecialFirstPageActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { var ribbon = d as ViewActionRibbon; if (ribbon == null) return; var active = (bool) args.NewValue; if (!active) { ribbon.SelectedIndex = ribbon.LastRegularIndex; ribbon.Visibility = Visibility.Visible; if (ribbon.IsLoaded) ribbon.RaiseEvent(new RoutedEventArgs(SpecialFirstPageDeactivateEvent)); else ribbon._mustRaiseSpecialFirstPageDeactivateEventOnLoad = true; } else { if (ribbon.IsLoaded) ribbon.RaiseEvent(new RoutedEventArgs(SpecialFirstPageActivateEvent)); else ribbon._mustRaiseSpecialFirstPageActivateEventOnLoad = true; } } private bool _mustRaiseSpecialFirstPageActivateEventOnLoad; private bool _mustRaiseSpecialFirstPageDeactivateEventOnLoad; /// <summary> /// Occurs when the special first page is activated /// </summary> public static readonly RoutedEvent SpecialFirstPageActivateEvent = EventManager.RegisterRoutedEvent("SpecialFirstPageActivate", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (ViewActionRibbon)); /// <summary> /// Occurs when the special first page is activated /// </summary> public event RoutedEventHandler SpecialFirstPageActivate { add { AddHandler(SpecialFirstPageActivateEvent, value); } remove { RemoveHandler(SpecialFirstPageActivateEvent, value); } } /// <summary> /// Occurs when the special first page is deactivated /// </summary> public static readonly RoutedEvent SpecialFirstPageDeactivateEvent = EventManager.RegisterRoutedEvent("SpecialFirstPageDeactivate", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (ViewActionRibbon)); /// <summary> /// Occurs when the special first page is activated /// </summary> public event RoutedEventHandler SpecialFirstPageDeactivate { add { AddHandler(SpecialFirstPageDeactivateEvent, value); } remove { RemoveHandler(SpecialFirstPageDeactivateEvent, value); } } /// <summary> /// Model used as the data context /// </summary> public object Model { get { return GetValue(ModelProperty); } set { SetValue(ModelProperty, value); } } /// <summary> /// Model dependency property /// </summary> public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof (object), typeof (ViewActionRibbon), new UIPropertyMetadata(null, ModelChanged)); /// <summary> /// Change handler for model property /// </summary> /// <param name="d">The dependency object that triggered this change.</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = d as ViewActionRibbon; if (ribbon == null) return; ribbon.RepopulateRibbon(e.NewValue); } private void RepopulateRibbon(object model) { var actionsContainer = model as IHaveActions; if (actionsContainer != null && actionsContainer.Actions != null) { actionsContainer.Actions.CollectionChanged += (s, e2) => PopulateRibbon(actionsContainer); Visibility = Visibility.Visible; PopulateRibbon(actionsContainer); } else Visibility = Visibility.Collapsed; } /// <summary> /// Selected view used as the data context /// </summary> public object SelectedView { get { return GetValue(SelectedViewProperty); } set { SetValue(SelectedViewProperty, value); } } /// <summary> /// Selected view dependency property /// </summary> public static readonly DependencyProperty SelectedViewProperty = DependencyProperty.Register("SelectedView", typeof (object), typeof (ViewActionRibbon), new UIPropertyMetadata(null, SelectedViewChanged)); /// <summary> /// Change handler for selected view property /// </summary> /// <param name="d">The dependency object that triggered this change.</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void SelectedViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d == null) return; var ribbon = d as ViewActionRibbon; if (ribbon == null) return; var viewResult = e.NewValue as ViewResult; if (viewResult == null) { ribbon.PopulateRibbon(ribbon.Model as IHaveActions); return; } var actionsContainer = viewResult.Model as IHaveActions; if (actionsContainer != null) { actionsContainer.Actions.CollectionChanged += (s, e2) => ribbon.PopulateRibbon(ribbon.Model as IHaveActions, actionsContainer); ribbon.PopulateRibbon(ribbon.Model as IHaveActions, actionsContainer, viewResult.ViewTitle); } else ribbon.PopulateRibbon(ribbon.Model as IHaveActions); } /// <summary> /// If set to true, the top level menu items will be forced to be upper case /// </summary> /// <value><c>true</c> if [force top level menu items upper case]; otherwise, <c>false</c>.</value> public bool ForceTopLevelTitlesUpperCase { get { return (bool) GetValue(ForceTopLevelTitlesUpperCaseProperty); } set { SetValue(ForceTopLevelTitlesUpperCaseProperty, value); } } /// <summary> /// If set to true, the top level menu items will be forced to be upper case /// </summary> public static readonly DependencyProperty ForceTopLevelTitlesUpperCaseProperty = DependencyProperty.Register("ForceTopLevelTitlesUpperCase", typeof (bool), typeof (ViewActionRibbon), new PropertyMetadata(true, ForceTopLevelTitlesUpperCaseChanged)); private static void ForceTopLevelTitlesUpperCaseChanged(DependencyObject d, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var ribbon = d as ViewActionRibbon; if (ribbon != null) ribbon.PopulateRibbon(ribbon.Model as IHaveActions); } /// <summary> /// Attached property used to reference the command/action on any custom ribbon item /// </summary> public static readonly DependencyProperty RibbonItemCommandProperty = DependencyProperty.RegisterAttached("RibbonItemCommand", typeof (ICommand), typeof (ViewActionRibbon), new PropertyMetadata(null)); /// <summary> /// Attached property used to reference the command/action on any custom ribbon item /// </summary> /// <param name="d">The dependency object the item is set on</param> /// <returns>ICommand.</returns> public static ICommand GetRibbonItemCommand(DependencyObject d) { return (ICommand) d.GetValue(RibbonItemCommandProperty); } /// <summary> /// Attached property used to reference the command/action on any custom ribbon item /// </summary> /// <param name="d">The dependency object the item is set on</param> /// <param name="value">The value.</param> public static void SetRibbonItemCommand(DependencyObject d, ICommand value) { d.SetValue(RibbonItemCommandProperty, value); } /// <summary> /// Policy that can be applied to view-actions displayed in the ribbon. /// </summary> /// <remarks> /// This kind of policy can be used to change which view-actions are to be displayed, or which order they are displayed in. /// </remarks> /// <value>The view action policy.</value> public IViewActionPolicy ViewActionPolicy { get { return (IViewActionPolicy)GetValue(ViewActionPolicyProperty); } set { SetValue(ViewActionPolicyProperty, value); } } /// <summary> /// Policy that can be applied to view-actions displayed in the ribbon. /// </summary> /// <remarks> /// This kind of policy can be used to change which view-actions are to be displayed, or which order they are displayed in. /// </remarks> /// <value>The view action policy.</value> public static readonly DependencyProperty ViewActionPolicyProperty = DependencyProperty.Register("ViewActionPolicy", typeof(IViewActionPolicy), typeof(ViewActionRibbon), new PropertyMetadata(null)); /// <summary> /// Populates the current ribbon with items based on the actions collection /// </summary> /// <param name="actions">List of primary actions</param> /// <param name="actions2">List of view specific actions</param> /// <param name="selectedViewTitle">The selected view title.</param> protected virtual void PopulateRibbon(IHaveActions actions, IHaveActions actions2 = null, string selectedViewTitle = "") { var oldSelectedPage = SelectedIndex; RemoveAllMenuKeyBindings(); Items.Clear(); if (actions == null) return; var actionList = ViewActionPolicy != null ? ViewActionPolicy.GetConsolidatedActions(actions, actions2, selectedViewTitle, viewModel: Model) : ViewActionHelper.GetConsolidatedActions(actions, actions2, selectedViewTitle); var rootCategories = ViewActionPolicy != null ? ViewActionPolicy.GetTopLevelActionCategories(actionList, EmptyGlobalCategoryTitle, EmptyLocalCategoryTitle, viewModel: Model) : ViewActionHelper.GetTopLevelActionCategories(actionList, EmptyGlobalCategoryTitle, EmptyLocalCategoryTitle); var pageCounter = 0; var selectedIndex = -1; var standardSelectedIndexSet = false; var specialSelectedIndexSet = false; var viewActionCategories = rootCategories as ViewActionCategory[] ?? rootCategories.ToArray(); foreach (var category in viewActionCategories) { RibbonPage tab; var tabVisibilityBinding = new MultiBinding {Converter = new MaximumVisibilityMultiConverter()}; if (category.IsLocalCategory && HighlightLocalCategories) { var caption = category.Caption; if (string.IsNullOrEmpty(caption)) caption = ForceTopLevelTitlesUpperCase ? selectedViewTitle.Trim().ToUpper() : selectedViewTitle.Trim(); tab = new RibbonSpecialPage {Header = caption}; if (!specialSelectedIndexSet) { selectedIndex = pageCounter; specialSelectedIndexSet = true; } } else { if (pageCounter == 0 && FirstPageIsSpecial) tab = new RibbonFirstPage {Header = ForceTopLevelTitlesUpperCase ? category.Caption.Trim().ToUpper() : category.Caption.Trim()}; else { tab = new RibbonPage {Header = ForceTopLevelTitlesUpperCase ? category.Caption.Trim().ToUpper() : category.Caption.Trim()}; if (!standardSelectedIndexSet && !specialSelectedIndexSet) { selectedIndex = pageCounter; standardSelectedIndexSet = true; } } } var items = new RibbonPageLayoutPanel(); tab.Content = items; PopulateSubCategories(items, category, actionList, ribbonPage: tab, visibilityBinding: tabVisibilityBinding); Items.Add(tab); tab.SetBinding(VisibilityProperty, tabVisibilityBinding); if (category.AccessKey != ' ') { var pageIndexToSelect = pageCounter; var pageAccessKey = (Key) Enum.Parse(typeof (Key), category.AccessKey.ToString(CultureInfo.InvariantCulture).ToUpper()); MenuKeyBindings.Add(new ViewActionMenuKeyBinding(new ViewAction(execute: (a, o) => { SelectedIndex = pageIndexToSelect; var window = ElementHelper.FindParent<Window>(this) ?? ElementHelper.FindVisualTreeParent<Window>(this); SetKeyboardShortcutsActive(window, true); ReadyForStatusChange = false; }) { ShortcutKey = pageAccessKey, ShortcutModifiers = ModifierKeys.Alt })); tab.PageAccessKey = category.AccessKey.ToString(CultureInfo.InvariantCulture).Trim().ToUpper(); } pageCounter++; } // We are checking for a selected default page pageCounter = 0; if (actionList.Count(a => a.IsDefaultSelection) > 0) foreach (var category in viewActionCategories) { var matchingActions = ViewActionPolicy != null ? ViewActionPolicy.GetAllActionsForCategory(actionList, category, viewModel: Model) : ViewActionHelper.GetAllActionsForCategory(actionList, category); foreach (var matchingAction in matchingActions) if (matchingAction.IsDefaultSelection) { selectedIndex = pageCounter; break; } pageCounter++; } if (selectedIndex == -1) selectedIndex = oldSelectedPage; if (selectedIndex == -1) selectedIndex = 0; if (selectedIndex >= Items.Count) selectedIndex = Items.Count - 1; LastRegularIndex = selectedIndex; SelectedIndex = selectedIndex; _setSelectedIndexOnLoadComplete = !IsLoaded ? SelectedIndex : -1; CreateAllMenuKeyBindings(); } /// <summary> /// Called after tabs are created. Can be overridden in subclasses. /// </summary> protected virtual void AfterTabCreated() { } /// <summary> /// Adds sub-items for the specified tab item and category /// </summary> /// <param name="parentPanel">Parent item container</param> /// <param name="category">Category we are interested in</param> /// <param name="actions">Actions to consider</param> /// <param name="indentLevel">Current hierarchical indentation level</param> /// <param name="ribbonPage">The ribbon page.</param> /// <param name="visibilityBinding">The visibility binding.</param> protected virtual void PopulateSubCategories(Panel parentPanel, ViewActionCategory category, IEnumerable<IViewAction> actions, int indentLevel = 0, RibbonPage ribbonPage = null, MultiBinding visibilityBinding = null) { var populatedCategories = new List<string>(); if (actions == null) return; var viewActions = actions as IViewAction[] ?? actions.ToArray(); var matchingActions = ViewActionPolicy != null ? ViewActionPolicy.GetAllActionsForCategory(viewActions, category, indentLevel, EmptyGlobalCategoryTitle, false, Model) : ViewActionHelper.GetAllActionsForCategory(viewActions, category, indentLevel, EmptyGlobalCategoryTitle, false); var addedRibbonItems = 0; foreach (var matchingAction in matchingActions) { if (addedRibbonItems > 0 && matchingAction.BeginGroup) parentPanel.Children.Add(new RibbonSeparator()); if (matchingAction.Categories != null && matchingAction.Categories.Count > indentLevel + 1 && !populatedCategories.Contains(matchingAction.Categories[indentLevel].Id)) // This is further down in a sub-category even { // TODO: Add a drop-down menu capable button populatedCategories.Add(matchingAction.Categories[indentLevel].Id); var newRibbonButton = new RibbonButtonLarge {Content = matchingAction.Categories[indentLevel + 1].Caption, Visibility = matchingAction.Visibility}; CreateMenuItemBinding(matchingAction, newRibbonButton); if (visibilityBinding != null) visibilityBinding.Bindings.Add(new Binding("Visibility") {Source = newRibbonButton}); PopulateSubCategories(parentPanel, matchingAction.Categories[indentLevel], viewActions, indentLevel + 1); newRibbonButton.AccessKey = matchingAction.AccessKey.ToString(CultureInfo.CurrentUICulture).Trim().ToUpper(); parentPanel.Children.Add(newRibbonButton); addedRibbonItems++; } else { if (matchingAction.ActionView != null) { if (matchingAction.ActionViewModel != null && matchingAction.ActionView.DataContext == null) matchingAction.ActionView.DataContext = matchingAction.ActionViewModel; var command = GetRibbonItemCommand(matchingAction.ActionView); if (command == null) SetRibbonItemCommand(matchingAction.ActionView, matchingAction); if (visibilityBinding != null) visibilityBinding.Bindings.Add(new Binding("Visibility") {Source = matchingAction.ActionView}); matchingAction.ActionView.IsVisibleChanged += (s, e) => InvalidateAll(); var isInFirstPage = false; if (ribbonPage != null) isInFirstPage = ribbonPage is RibbonFirstPage; if (!isInFirstPage) { ElementHelper.DetachElementFromParent(matchingAction.ActionView); if (matchingAction.ActionView.Style == null) { var resource = TryFindResource("CODE.Framework-Ribbon-CustomControlContainerStyle"); if (resource != null) { var genericStyle = resource as Style; if (genericStyle != null) matchingAction.ActionView.Style = genericStyle; } } parentPanel.Children.Add(matchingAction.ActionView); } } else { RibbonButton newRibbonButton; if (matchingAction.Significance == ViewActionSignificance.AboveNormal || matchingAction.Significance == ViewActionSignificance.Highest) newRibbonButton = new RibbonButtonLarge { Content = matchingAction.Caption, Command = matchingAction, Visibility = matchingAction.Visibility }; else newRibbonButton = new RibbonButtonSmall { Content = matchingAction.Caption, Command = matchingAction, Visibility = matchingAction.Visibility }; newRibbonButton.IsVisibleChanged += (s, e) => InvalidateAll(); newRibbonButton.SetBinding(ContentControl.ContentProperty, new Binding("Caption") {Source = matchingAction, Mode = BindingMode.OneWay}); CreateMenuItemBinding(matchingAction, newRibbonButton); if (visibilityBinding != null) visibilityBinding.Bindings.Add(new Binding("Visibility") {Source = newRibbonButton}); if (matchingAction.ViewActionType == ViewActionTypes.Toggle) newRibbonButton.SetBinding(RibbonButton.IsCheckedProperty, new Binding("IsChecked") {Source = matchingAction}); if (matchingAction.AccessKey != ' ') newRibbonButton.AccessKey = matchingAction.AccessKey.ToString(CultureInfo.CurrentUICulture).Trim().ToUpper(); parentPanel.Children.Add(newRibbonButton); HandleRibbonShortcutKey(newRibbonButton, matchingAction, ribbonPage); } addedRibbonItems++; } } if (addedRibbonItems > 0) parentPanel.Children.Add(new RibbonSeparator()); } private void InvalidateAll() { InvalidateMeasure(); InvalidateArrange(); InvalidateVisual(); foreach (var tab in Items) { var tabItem = tab as TabItem; if (tabItem == null) continue; tabItem.InvalidateMeasure(); tabItem.InvalidateArrange(); tabItem.InvalidateVisual(); if (tabItem.Content == null) continue; var tabContent = tabItem.Content as FrameworkElement; if (tabContent == null) continue; tabContent.InvalidateMeasure(); tabContent.InvalidateArrange(); tabContent.InvalidateVisual(); } } /// <summary> /// Handles the assignment of shortcut keys /// </summary> /// <param name="button">The button.</param> /// <param name="action">The category.</param> /// <param name="ribbonPage">The ribbon page.</param> protected virtual void HandleRibbonShortcutKey(RibbonButton button, IViewAction action, RibbonPage ribbonPage) { if (action.ShortcutKey == Key.None) return; MenuKeyBindings.Add(new ViewActionMenuKeyBinding(action)); } /// <summary> /// For internal use only /// </summary> protected readonly List<ViewActionMenuKeyBinding> MenuKeyBindings = new List<ViewActionMenuKeyBinding>(); /// <summary> /// For internal use only /// </summary> private int _setSelectedIndexOnLoadComplete = -1; /// <summary> /// Removes all key bindings from the current window that were associated with a view category menu /// </summary> protected virtual void CreateAllMenuKeyBindings() { var window = ElementHelper.FindVisualTreeParent<Window>(this); if (window == null) return; foreach (var binding in MenuKeyBindings) window.InputBindings.Add(binding); } /// <summary> /// Removes all key bindings from the current window that were associated with a view category menu /// </summary> protected virtual void RemoveAllMenuKeyBindings() { MenuKeyBindings.Clear(); var window = ElementHelper.FindVisualTreeParent<Window>(this); if (window == null) return; var bindingIndex = 0; while (true) { if (bindingIndex >= window.InputBindings.Count) break; var binding = window.InputBindings[bindingIndex]; if (binding is ViewActionMenuKeyBinding) window.InputBindings.RemoveAt(bindingIndex); // We remove the item from the collection and start over with the remove operation since now all indexes changed else bindingIndex++; } } /// <summary> /// Creates the menu item binding. /// </summary> /// <param name="action">The action.</param> /// <param name="ribbonButton">The ribbon button.</param> private void CreateMenuItemBinding(IViewAction action, FrameworkElement ribbonButton) { var binding = new MultiBinding {Converter = new MinimumVisibilityMultiConverter()}; binding.Bindings.Add(new Binding("Availability") {Source = action, Converter = new AvailabilityToVisibleConverter()}); binding.Bindings.Add(new Binding("Visibility") {Source = action}); ribbonButton.SetBinding(VisibilityProperty, binding); } } /// <summary> /// Ribbon page /// </summary> public class RibbonPage : TabItem { /// <summary>Access key to be displayed for the page</summary> public string PageAccessKey { get { return (string) GetValue(PageAccessKeyProperty); } set { SetValue(PageAccessKeyProperty, value); } } /// <summary>Access key to be displayed for the page</summary> public static readonly DependencyProperty PageAccessKeyProperty = DependencyProperty.Register("PageAccessKey", typeof (string), typeof (RibbonPage), new PropertyMetadata(string.Empty, OnPageAccessKeyChanged)); /// <summary>Fires when the page access key changes</summary> /// <param name="d">The dependency object.</param> /// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void OnPageAccessKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { var page = d as RibbonPage; if (page == null) return; page.PageAccessKeySet = !string.IsNullOrEmpty(args.NewValue.ToString()); } /// <summary>Indicates whether a page access key has been set</summary> /// <value><c>true</c> if [page access key set]; otherwise, <c>false</c>.</value> public bool PageAccessKeySet { get { return (bool) GetValue(PageAccessKeySetProperty); } set { SetValue(PageAccessKeySetProperty, value); } } /// <summary>Indicates whether a page access key has been set</summary> public static readonly DependencyProperty PageAccessKeySetProperty = DependencyProperty.Register("PageAccessKeySet", typeof (bool), typeof (RibbonPage), new PropertyMetadata(false)); } /// <summary> /// Special page class for the first page in a ribbon /// </summary> public class RibbonFirstPage : RibbonPage { } /// <summary> /// Special page class for special pages in a ribbon /// </summary> public class RibbonSpecialPage : RibbonPage { } /// <summary> /// Default ribbon button /// </summary> public class RibbonButton : Button { /// <summary>Access key to be displayed for the button</summary> public string AccessKey { get { return (string) GetValue(AccessKeyProperty); } set { SetValue(AccessKeyProperty, value); } } /// <summary>Access key to be displayed for the button</summary> public static readonly DependencyProperty AccessKeyProperty = DependencyProperty.Register("AccessKey", typeof (string), typeof (RibbonButton), new PropertyMetadata(string.Empty, OnAccessKeyChanged)); /// <summary>Fires when the access key changes</summary> /// <param name="d">The dependency object.</param> /// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void OnAccessKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { var button = d as RibbonButton; if (button == null) return; button.AccessKeySet = !string.IsNullOrEmpty(args.NewValue.ToString()); } /// <summary>Indicates whether a access key has been set</summary> /// <value><c>true</c> if [access key set]; otherwise, <c>false</c>.</value> public bool AccessKeySet { get { return (bool) GetValue(AccessKeySetProperty); } set { SetValue(AccessKeySetProperty, value); } } /// <summary>Indicates whether a page access key has been set</summary> public static readonly DependencyProperty AccessKeySetProperty = DependencyProperty.Register("AccessKeySet", typeof (bool), typeof (RibbonButton), new PropertyMetadata(false)); /// <summary>Indicates whether the button is to be rendered as "checked" (often used in Toggle-style actions)</summary> public bool IsChecked { get { return (bool) GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } /// <summary>Indicates whether the button is to be rendered as "checked" (often used in Toggle-style actions)</summary> public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof (bool), typeof (RibbonButton), new PropertyMetadata(false)); } /// <summary> /// Large button element used in ribbons /// </summary> public class RibbonButtonLarge : RibbonButton { } /// <summary> /// Small button element used in ribbons /// </summary> public class RibbonButtonSmall : RibbonButton { } /// <summary> /// Separator element used in ribbons /// </summary> public class RibbonSeparator : Control { /// <summary> /// Initializes a new instance of the <see cref="RibbonSeparator"/> class. /// </summary> public RibbonSeparator() { Focusable = false; } } /// <summary> /// This panel is used to lay out items within a ribbon page /// </summary> public class RibbonPageLayoutPanel : Panel { /// <summary>Font Size used to render group titles</summary> public double GroupTitleFontSize { get { return (double) GetValue(GroupTitleFontSizeProperty); } set { SetValue(GroupTitleFontSizeProperty, value); } } /// <summary>Font Size used to render group titles</summary> public static readonly DependencyProperty GroupTitleFontSizeProperty = DependencyProperty.Register("GroupTitleFontSize", typeof (double), typeof (RibbonPageLayoutPanel), new PropertyMetadata(10d)); /// <summary>Font family used to render group titles</summary> public FontFamily GroupTitleFontFamily { get { return (FontFamily) GetValue(GroupTitleFontFamilyProperty); } set { SetValue(GroupTitleFontFamilyProperty, value); } } /// <summary>Font family used to render group titles</summary> public static readonly DependencyProperty GroupTitleFontFamilyProperty = DependencyProperty.Register("GroupTitleFontFamily", typeof (FontFamily), typeof (RibbonPageLayoutPanel), new PropertyMetadata(new FontFamily("Segoe UI"))); /// <summary>Font weight used to render group titles</summary> public FontWeight GroupTitleFontWeight { get { return (FontWeight) GetValue(GroupTitleFontWeightProperty); } set { SetValue(GroupTitleFontWeightProperty, value); } } /// <summary>Font weight used to render group titles</summary> public static readonly DependencyProperty GroupTitleFontWeightProperty = DependencyProperty.Register("GroupTitleFontWeight", typeof (FontWeight), typeof (RibbonPageLayoutPanel), new PropertyMetadata(FontWeights.Normal)); /// <summary>Foreground brush used to render group titles</summary> public Brush GroupTitleForegroundBrush { get { return (Brush) GetValue(GroupTitleForegroundBrushProperty); } set { SetValue(GroupTitleForegroundBrushProperty, value); } } /// <summary>Foreground brush used to render group titles</summary> public static readonly DependencyProperty GroupTitleForegroundBrushProperty = DependencyProperty.Register("GroupTitleForegroundBrush", typeof (Brush), typeof (RibbonPageLayoutPanel), new PropertyMetadata(Brushes.Black)); /// <summary>Foreground brush opacity used to render group titles</summary> public double GroupTitleForegroundBrushOpacity { get { return (double) GetValue(GroupTitleForegroundBrushOpacityProperty); } set { SetValue(GroupTitleForegroundBrushOpacityProperty, value); } } /// <summary>Foreground brush opacity used to render group titles</summary> public static readonly DependencyProperty GroupTitleForegroundBrushOpacityProperty = DependencyProperty.Register("GroupTitleForegroundBrushOpacity", typeof (double), typeof (RibbonPageLayoutPanel), new PropertyMetadata(.6d)); /// <summary> /// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param> /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { var availableWitdh = availableSize.Width; var availableHeight = availableSize.Height; if (double.IsInfinity(availableSize.Height)) availableHeight = Height > 0 ? Height : 70; else availableHeight -= 18; var availableSizeForControls = new Size(availableWitdh, availableHeight); foreach (UIElement child in Children) if (child is RibbonSeparator) child.Measure(availableSize); else child.Measure(availableSizeForControls); var left = 0d; var top = 0d; var lastLargestWidth = 0d; var lastElementWasFullHeight = true; foreach (UIElement child in Children) { var largeButton = child as RibbonButtonLarge; var smallButton = child as RibbonButtonSmall; var separator = child as RibbonSeparator; if (largeButton != null) { top = 0d; left += lastLargestWidth; lastElementWasFullHeight = true; lastLargestWidth = largeButton.DesiredSize.Width; } else if (smallButton != null) { if (lastElementWasFullHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } if (top + smallButton.DesiredSize.Height > availableHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } lastElementWasFullHeight = false; lastLargestWidth = Math.Max(lastLargestWidth, smallButton.DesiredSize.Width); top += smallButton.DesiredSize.Height; } else if (separator != null) { top = 0d; left += lastLargestWidth; lastElementWasFullHeight = true; lastLargestWidth = separator.DesiredSize.Width; } else if (child != null) { if (lastElementWasFullHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } var childHeight = child.DesiredSize.Height; if (childHeight >= availableHeight) { childHeight = availableHeight; lastElementWasFullHeight = true; } else lastElementWasFullHeight = false; if (top + childHeight > availableHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } lastLargestWidth = Math.Max(lastLargestWidth, child.DesiredSize.Width); top += childHeight; } } left += lastLargestWidth; var baseSize = base.MeasureOverride(availableSize); var finalHeight = baseSize.Height; if (finalHeight < 1 || double.IsNaN(finalHeight)) finalHeight = Height; if (finalHeight < 1 || double.IsNaN(finalHeight)) finalHeight = 70; return new Size(left, finalHeight); } private readonly List<GroupTitleRenderInfo> _groupTitles = new List<GroupTitleRenderInfo>(); /// <summary> /// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { _groupTitles.Clear(); var left = 0d; var top = 0d; var lastLargestWidth = 0d; var lastElementWasFullHeight = true; var availableHeight = finalSize.Height; if (double.IsInfinity(finalSize.Height)) availableHeight = Height > 0 ? Height : 70; else availableHeight -= 14; var currentGroupLeft = 0d; var isGroupStart = true; GroupTitleRenderInfo currentRenderInfo = null; foreach (UIElement child in Children) { var largeButton = child as RibbonButtonLarge; var smallButton = child as RibbonButtonSmall; var separator = child as RibbonSeparator; if (isGroupStart) { currentGroupLeft = left; currentRenderInfo = new GroupTitleRenderInfo(); if (largeButton != null && largeButton.Command != null) { var action = largeButton.Command as IViewAction; if (action != null) currentRenderInfo.GroupTitle = action.GroupTitle; } else if (smallButton != null && smallButton.Command != null) { var action = smallButton.Command as IViewAction; if (action != null) currentRenderInfo.GroupTitle = action.GroupTitle; } else if (child != null) { var action = ViewActionRibbon.GetRibbonItemCommand(child) as IViewAction; if (action != null) currentRenderInfo.GroupTitle = action.GroupTitle; } _groupTitles.Add(currentRenderInfo); isGroupStart = false; } if (largeButton != null) { top = 0d; left += lastLargestWidth; lastElementWasFullHeight = true; lastLargestWidth = largeButton.IsVisible ? largeButton.DesiredSize.Width : 0d; if (largeButton.IsVisible) largeButton.Arrange(new Rect(left, top, largeButton.DesiredSize.Width, largeButton.DesiredSize.Height)); } else if (smallButton != null) { if (lastElementWasFullHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } if (top + smallButton.DesiredSize.Height > availableHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } lastElementWasFullHeight = false; if (smallButton.IsVisible) smallButton.Arrange(new Rect(left, top, smallButton.DesiredSize.Width, smallButton.DesiredSize.Height)); lastLargestWidth = Math.Max(lastLargestWidth, smallButton.IsVisible ? smallButton.DesiredSize.Width : 0d); top += smallButton.DesiredSize.Height; } else if (separator != null) { top = 0d; left += lastLargestWidth; currentRenderInfo.RenderRect = new Rect(currentGroupLeft, 0d, left - currentGroupLeft, finalSize.Height); if (currentRenderInfo.RenderRect.Width < 2 || string.IsNullOrEmpty(currentRenderInfo.GroupTitle)) _groupTitles.Remove(currentRenderInfo); isGroupStart = true; separator.Arrange(new Rect(left, top, separator.DesiredSize.Width, separator.DesiredSize.Height)); lastElementWasFullHeight = true; lastLargestWidth = separator.DesiredSize.Width; } else if (child != null) { if (lastElementWasFullHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } var childHeight = child.DesiredSize.Height; if (childHeight >= availableHeight) { childHeight = availableHeight; lastElementWasFullHeight = true; } else lastElementWasFullHeight = false; if (top + childHeight > availableHeight) { left += lastLargestWidth; lastLargestWidth = 0d; top = 0d; } if (child.IsVisible) child.Arrange(new Rect(left, top, child.DesiredSize.Width, childHeight)); lastLargestWidth = Math.Max(lastLargestWidth, child.IsVisible ? child.DesiredSize.Width : 0d); top += childHeight; } } if (currentRenderInfo != null) { left += lastLargestWidth; currentRenderInfo.RenderRect = new Rect(currentGroupLeft, 0d, left - currentGroupLeft, finalSize.Height); if (currentRenderInfo.RenderRect.Width < 2 || string.IsNullOrEmpty(currentRenderInfo.GroupTitle)) _groupTitles.Remove(currentRenderInfo); } return base.ArrangeOverride(finalSize); } /// <summary> /// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext" /> object during the render pass of a <see cref="T:System.Windows.Controls.Panel" /> element. /// </summary> /// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext" /> object to draw.</param> protected override void OnRender(DrawingContext dc) { var typeFace = new Typeface(GroupTitleFontFamily, FontStyles.Normal, GroupTitleFontWeight, FontStretches.Normal); var brush = GroupTitleForegroundBrush.Clone(); brush.Opacity = GroupTitleForegroundBrushOpacity; foreach (var title in _groupTitles) { if (string.IsNullOrEmpty(title.GroupTitle)) continue; if (title.RenderRect.Width < 20) continue; var format = new FormattedText(title.GroupTitle, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeFace, GroupTitleFontSize, brush) { TextAlignment = TextAlignment.Center, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis, MaxTextWidth = title.RenderRect.Width - 10, MaxTextHeight = title.RenderRect.Height, }; var yOffset = title.RenderRect.Height - format.Height + 1; dc.PushTransform(new TranslateTransform(title.RenderRect.X, yOffset)); dc.DrawText(format, new Point(10d, 0d)); dc.Pop(); } base.OnRender(dc); } /// <summary> /// Class GroupTitleRenderInfo /// </summary> private class GroupTitleRenderInfo { public string GroupTitle { get; set; } public Rect RenderRect { get; set; } } } /// <summary> /// Special button used to close the special ribbon UI /// </summary> public class CloseSpecialRibbonUiButton : Button { /// <summary> /// Reference to the ribbon control /// </summary> public ViewActionRibbon Ribbon { get { return (ViewActionRibbon) GetValue(RibbonProperty); } set { SetValue(RibbonProperty, value); } } /// <summary> /// Reference to the ribbon control /// </summary> public static readonly DependencyProperty RibbonProperty = DependencyProperty.Register("Ribbon", typeof (ViewActionRibbon), typeof (CloseSpecialRibbonUiButton), new PropertyMetadata(null)); /// <summary> /// Called when a <see cref="T:System.Windows.Controls.Button" /> is clicked. /// </summary> protected override void OnClick() { base.OnClick(); if (Ribbon == null) return; if (Ribbon.Items.Count > 1) { if (!Ribbon.IsSpecialFirstPageActive) Ribbon.IsSpecialFirstPageActive = true; // This can happen in theme switching scenarios. We trigger the change here so everything associated with this property changing actually fires. Ribbon.IsSpecialFirstPageActive = false; } } } /// <summary> /// List of action items for first page controls /// </summary> public class SpecialFirstPageActionList : Panel { private double _widest; /// <summary> /// Policy that can be applied to view-actions displayed in the ribbon. /// </summary> /// <remarks> /// This kind of policy can be used to change which view-actions are to be displayed, or which order they are displayed in. /// </remarks> /// <value>The view action policy.</value> public IViewActionPolicy ViewActionPolicy { get { return (IViewActionPolicy)GetValue(ViewActionPolicyProperty); } set { SetValue(ViewActionPolicyProperty, value); } } /// <summary> /// Policy that can be applied to view-actions displayed in the ribbon. /// </summary> /// <remarks> /// This kind of policy can be used to change which view-actions are to be displayed, or which order they are displayed in. /// </remarks> /// <value>The view action policy.</value> public static readonly DependencyProperty ViewActionPolicyProperty = DependencyProperty.Register("ViewActionPolicy", typeof(IViewActionPolicy), typeof(SpecialFirstPageActionList), new PropertyMetadata(null)); /// <summary> /// Current active view associated with the current action list /// </summary> /// <value>The active view.</value> public FrameworkElement ActiveView { get { return (FrameworkElement)GetValue(ActiveViewProperty); } set { SetValue(ActiveViewProperty, value); } } /// <summary> /// Current active view associated with the current action list /// </summary> /// <value>The active view.</value> public static readonly DependencyProperty ActiveViewProperty = DependencyProperty.Register("ActiveView", typeof(FrameworkElement), typeof(SpecialFirstPageActionList), new PropertyMetadata(null)); /// <summary> /// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { var top = 0d; foreach (UIElement child in Children) { child.Arrange(new Rect(0d, top, _widest, child.DesiredSize.Height)); top += child.DesiredSize.Height; } return base.ArrangeOverride(new Size(_widest, finalSize.Height)); } /// <summary> /// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param> /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { var widest = 0d; var height = 0d; var size = new Size(1000, 1000); foreach (UIElement child in Children) { child.Measure(size); widest = Math.Max(widest, child.DesiredSize.Width); height += child.DesiredSize.Height; } _widest = widest; var newFinalSize = new Size(widest, height); return base.ArrangeOverride(newFinalSize); } /// <summary> /// Model used as the data context /// </summary> public object Model { get { return GetValue(ModelProperty); } set { SetValue(ModelProperty, value); } } /// <summary> /// Model dependency property /// </summary> public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof (object), typeof (SpecialFirstPageActionList), new UIPropertyMetadata(null, ModelChanged)); /// <summary> /// Change handler for model property /// </summary> /// <param name="d">The dependency object that triggered this change.</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var list = d as SpecialFirstPageActionList; if (list == null) return; var actionsContainer = e.NewValue as IHaveActions; if (actionsContainer != null && actionsContainer.Actions != null) { actionsContainer.Actions.CollectionChanged += (s, e2) => list.PopulateList(actionsContainer); list.Visibility = Visibility.Visible; list.PopulateList(actionsContainer); } else list.Visibility = Visibility.Collapsed; } /// <summary> /// Selected view used as the data context /// </summary> public object SelectedView { get { return GetValue(SelectedViewProperty); } set { SetValue(SelectedViewProperty, value); } } /// <summary> /// Selected view dependency property /// </summary> public static readonly DependencyProperty SelectedViewProperty = DependencyProperty.Register("SelectedView", typeof (object), typeof (SpecialFirstPageActionList), new UIPropertyMetadata(null, SelectedViewChanged)); /// <summary> /// For internal use only /// </summary> public bool IsActivating { get { return (bool)GetValue(IsActivatingProperty); } set { SetValue(IsActivatingProperty, value); } } /// <summary> /// Reference to a special button that has most recently been activated /// </summary> /// <value> /// The last selected button. /// </value> public SpecialFirstPageRibbonButton LastSelectedButton { get; set; } /// <summary> /// For internal use only /// </summary> public static readonly DependencyProperty IsActivatingProperty = DependencyProperty.Register("IsActivating", typeof(bool), typeof(SpecialFirstPageActionList), new PropertyMetadata(false, OnIsActivatingChanged)); /// <summary> /// Fires when IsActivating changes /// </summary> /// <param name="d">The list object</param> /// <param name="e">Event args</param> private static void OnIsActivatingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(bool) e.NewValue) return; // Nothing to do var list = d as SpecialFirstPageActionList; if (list == null) return; var selectedItem = list.Children.OfType<SpecialFirstPageRibbonButton>().FirstOrDefault(b => b.IsSelected); if (selectedItem == null || list.ActiveView == null || list.ActiveView != selectedItem.ActionView) { SpecialFirstPageRibbonButton initialButton = null; if (list.LastSelectedButton != null) { // We had a previously selected button. However, the reference to the button may // be outdated, as the list may be repopulated. Therefore, we can't use the button // directly, but instead we look at the actions associated with the button initialButton = list.Children.OfType<SpecialFirstPageRibbonButton>().FirstOrDefault(b => b.Command == list.LastSelectedButton.Command); } if (initialButton == null) initialButton = list.Children.OfType<SpecialFirstPageRibbonButton>().FirstOrDefault(b => { var command = b.Command as OnDemandLoadCustomViewViewAction; if (command == null) return false; return command.IsInitiallySelected; }); if (initialButton != null) { if (list.ActiveView != null) list.ActiveView = null; initialButton.ActivateButton(list); } } } /// <summary> /// Change handler for selected view property /// </summary> /// <param name="d">The dependency object that triggered this change.</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void SelectedViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d == null) return; var list = d as SpecialFirstPageActionList; if (list == null) return; var viewResult = e.NewValue as ViewResult; if (viewResult == null) { list.PopulateList(list.Model as IHaveActions); return; } var actionsContainer = viewResult.Model as IHaveActions; if (actionsContainer != null) { actionsContainer.Actions.CollectionChanged += (s, e2) => list.PopulateList(list.Model as IHaveActions, actionsContainer); list.PopulateList(list.Model as IHaveActions, actionsContainer, viewResult.ViewTitle); } else list.PopulateList(list.Model as IHaveActions); } /// <summary> /// Populates the current list with items based on the actions collection /// </summary> /// <param name="actions">List of primary actions</param> /// <param name="actions2">List of view specific actions</param> /// <param name="selectedViewTitle">The selected view title.</param> private void PopulateList(IHaveActions actions, IHaveActions actions2 = null, string selectedViewTitle = "") { Children.Clear(); if (actions == null) return; var actionList = ViewActionPolicy != null ? ViewActionPolicy.GetConsolidatedActions(actions, actions2, selectedViewTitle, viewModel: this) : ViewActionHelper.GetConsolidatedActions(actions, actions2, selectedViewTitle); var globalCategory = "File"; var ribbon = ElementHelper.FindParent<ViewActionRibbon>(this); if (ribbon != null) globalCategory = ribbon.EmptyGlobalCategoryTitle; var rootCategories = ViewActionPolicy != null ? ViewActionPolicy.GetTopLevelActionCategories(actionList, globalCategory, globalCategory, this) : ViewActionHelper.GetTopLevelActionCategories(actionList, globalCategory, globalCategory); var viewActionCategories = rootCategories as ViewActionCategory[] ?? rootCategories.ToArray(); if (viewActionCategories.Length > 0) { var category = viewActionCategories[0]; var matchingActions = ViewActionPolicy != null ? ViewActionPolicy.GetAllActionsForCategory(actionList, category, orderByGroupTitle: false, viewModel: this) : ViewActionHelper.GetAllActionsForCategory(actionList, category, orderByGroupTitle: false); var matchingActionsArray = matchingActions as IViewAction[] ?? matchingActions.ToArray(); // Prevents multiple enumeration foreach (var action in matchingActionsArray) if (action.ActionView == null && action.ActionViewModel == null && !(action is OnDemandLoadCustomViewViewAction)) { // This is a standard button which triggers the associated action var button = new SpecialFirstPageRibbonButton { Content = action.Caption, Command = action, AccessKey = action.AccessKey.ToString(CultureInfo.CurrentUICulture).Trim().ToUpper() }; CreateMenuItemBinding(action, button); Children.Add(button); } else { // This action has a custom view associated which is displayed when the button is clicked var button = new SpecialFirstPageRibbonButton { Content = action.Caption, Command = action, AccessKey = action.AccessKey.ToString(CultureInfo.CurrentUICulture).Trim().ToUpper(), ActionView = action.ActionView, ActionViewModel = action.ActionViewModel }; CreateMenuItemBinding(action, button); Children.Add(button); } } } /// <summary> /// Creates the menu item binding. /// </summary> /// <param name="action">The action.</param> /// <param name="ribbonButton">The ribbon button.</param> private static void CreateMenuItemBinding(IViewAction action, FrameworkElement ribbonButton) { ribbonButton.SetBinding(VisibilityProperty, new Binding("Availability") {Source = action, Converter = new AvailabilityToVisibleConverter()}); } } /// <summary> /// For internal use only /// </summary> public class AvailabilityToVisibleConverter : IValueConverter { /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is ViewActionAvailabilities)) return Visibility.Collapsed; var availability = (ViewActionAvailabilities) value; return availability == ViewActionAvailabilities.Available ? Visibility.Visible : Visibility.Collapsed; } /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // Not used return null; } } /// <summary> /// Looks at multiple Visibility values and returns the highest visibility level /// </summary> public class MaximumVisibilityMultiConverter : IMultiValueConverter { /// <summary> /// Converts source values to a value for the binding target. The data binding engine calls this method when it propagates the values from source bindings to the binding target. /// </summary> /// <param name="values">The array of values that the source bindings in the <see cref="T:System.Windows.Data.MultiBinding" /> produces. The value <see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the source binding has no value to provide for conversion.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value.If the method returns null, the valid null value is used.A return value of <see cref="T:System.Windows.DependencyProperty" />.<see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the converter did not produce a value, and that the binding will use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> if it is available, or else will use the default value.A return value of <see cref="T:System.Windows.Data.Binding" />.<see cref="F:System.Windows.Data.Binding.DoNothing" /> indicates that the binding does not transfer the value or use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> or the default value.</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var result = Visibility.Collapsed; foreach (var value in values) { var visibility = (Visibility) value; if (result == Visibility.Collapsed && (visibility == Visibility.Hidden || visibility == Visibility.Visible)) result = visibility; else if (result == Visibility.Hidden && visibility == Visibility.Visible) return Visibility.Visible; // It can't be more than visible, so we can simply return this if (result == Visibility.Visible) return Visibility.Visible; } return result; } /// <summary> /// Converts a binding target value to the source binding values. /// </summary> /// <param name="value">The value that the binding target produces.</param> /// <param name="targetTypes">The array of types to convert to. The array length indicates the number and types of values that are suggested for the method to return.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>An array of values that have been converted from the target value back to the source values.</returns> public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { // Not needed return null; } } /// <summary> /// Looks at multiple Visibility values and returns the lowest visibility level /// </summary> public class MinimumVisibilityMultiConverter : IMultiValueConverter { /// <summary> /// Converts source values to a value for the binding target. The data binding engine calls this method when it propagates the values from source bindings to the binding target. /// </summary> /// <param name="values">The array of values that the source bindings in the <see cref="T:System.Windows.Data.MultiBinding" /> produces. The value <see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the source binding has no value to provide for conversion.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value.If the method returns null, the valid null value is used.A return value of <see cref="T:System.Windows.DependencyProperty" />.<see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the converter did not produce a value, and that the binding will use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> if it is available, or else will use the default value.A return value of <see cref="T:System.Windows.Data.Binding" />.<see cref="F:System.Windows.Data.Binding.DoNothing" /> indicates that the binding does not transfer the value or use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> or the default value.</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var result = Visibility.Visible; foreach (var value in values) { var visibility = (Visibility) value; if (visibility == Visibility.Collapsed) return Visibility.Collapsed; if (result == Visibility.Visible && visibility == Visibility.Hidden) result = Visibility.Hidden; } return result; } /// <summary> /// Converts a binding target value to the source binding values. /// </summary> /// <param name="value">The value that the binding target produces.</param> /// <param name="targetTypes">The array of types to convert to. The array length indicates the number and types of values that are suggested for the method to return.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>An array of values that have been converted from the target value back to the source values.</returns> public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { // Not needed return null; } } /// <summary> /// For internal use only /// </summary> public class ChildrenCollectionCountToVisibleConverter : IValueConverter { private readonly UIElementCollection _children; /// <summary> /// Initializes a new instance of the <see cref="ChildrenCollectionCountToVisibleConverter" /> class. /// </summary> /// <param name="children">The children.</param> public ChildrenCollectionCountToVisibleConverter(UIElementCollection children) { _children = children; } /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // We are bound to a property of the items collection, but we do not really care and always go after the items collection itself to determined visibility if (_children == null) return Visibility.Collapsed; foreach (var item in _children) { var uiElement = item as UIElement; if (uiElement != null && !(uiElement is RibbonSeparator) && uiElement.Visibility == Visibility.Visible) return Visibility.Visible; } return Visibility.Collapsed; } /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // Not used return null; } } /// <summary> /// Special button class for the first page in the ribbon /// </summary> public class SpecialFirstPageRibbonButton : Button { /// <summary>Access key to be displayed for the button</summary> public string AccessKey { get { return (string) GetValue(AccessKeyProperty); } set { SetValue(AccessKeyProperty, value); } } /// <summary>Access key to be displayed for the button</summary> public static readonly DependencyProperty AccessKeyProperty = DependencyProperty.Register("AccessKey", typeof (string), typeof (SpecialFirstPageRibbonButton), new PropertyMetadata(string.Empty, OnAccessKeyChanged)); /// <summary>Fires when the access key changes</summary> /// <param name="d">The dependency object.</param> /// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void OnAccessKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs args) { var button = d as SpecialFirstPageRibbonButton; if (button == null) return; button.AccessKeySet = !string.IsNullOrEmpty(args.NewValue.ToString()); } /// <summary>Indicates whether a access key has been set</summary> /// <value><c>true</c> if [access key set]; otherwise, <c>false</c>.</value> public bool AccessKeySet { get { return (bool) GetValue(AccessKeySetProperty); } set { SetValue(AccessKeySetProperty, value); } } /// <summary>Indicates whether a page access key has been set</summary> public static readonly DependencyProperty AccessKeySetProperty = DependencyProperty.Register("AccessKeySet", typeof(bool), typeof(SpecialFirstPageRibbonButton), new PropertyMetadata(false)); /// <summary> /// Indicates whether the current button is considered to be "selected" /// </summary> /// <value><c>true</c> if this instance is selected; otherwise, <c>false</c>.</value> public bool IsSelected { get { return (bool)GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } /// <summary> /// Indicates whether the current button is considered to be "selected" /// </summary> /// <value><c>true</c> if this instance is selected; otherwise, <c>false</c>.</value> public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(SpecialFirstPageRibbonButton), new PropertyMetadata(false)); /// <summary> /// Custom view associated with this button /// </summary> /// <value>The action view.</value> public FrameworkElement ActionView { get; set; } /// <summary> /// Custom view-model associated with this action /// </summary> /// <value>The action view model.</value> public object ActionViewModel { get; set; } /// <summary> /// Called when the button is clicked /// </summary> protected override void OnClick() { if (Command != null) { var onDemandLoadViewAction = Command as OnDemandLoadCustomViewViewAction; if (onDemandLoadViewAction == null) { // We have a standard action.command that handles everything base.OnClick(); return; } } ActivateButton(); } /// <summary> /// Activates the button /// </summary> /// <param name="list">Parent action list</param> public void ActivateButton(SpecialFirstPageActionList list = null) { if (list == null) list = ElementHelper.FindVisualTreeParent<SpecialFirstPageActionList>(this); if (list == null) return; foreach (var button in list.Children.OfType<SpecialFirstPageRibbonButton>().Where(b => b.IsSelected)) button.IsSelected = false; if (ActionView == null && Command != null) { var onDemandLoadViewAction = Command as OnDemandLoadCustomViewViewAction; if (onDemandLoadViewAction != null) { onDemandLoadViewAction.Execute(null); // Makes sure the desired view is loaded on demand ActionView = onDemandLoadViewAction.ActionView; ActionViewModel = onDemandLoadViewAction.ActionViewModel; } } if (list.ActiveView != null && list.ActiveView != ActionView) { //ElementHelper.DetachElementFromParent(list.ActiveView); list.ActiveView = null; } if (ActionView != null && list.ActiveView != ActionView) { if (ActionView.DataContext == null) ActionView.DataContext = ActionViewModel; //ElementHelper.DetachElementFromParent(ActionView); list.ActiveView = ActionView; } IsSelected = true; if (ActionView != null) list.LastSelectedButton = this; } } }
using System; using System.ComponentModel.DataAnnotations; namespace RazorPagesMovie.Models { public class Movie { //public string Title { get; set; } public int ID { get; set; } [StringLength(60, MinimumLength = 3, ErrorMessage = "3文字以上60文字以内で入力してください")] [Required(ErrorMessage = "{0}は、省略することはできません")] [Display(Name = "タイトル")] public string Title { get; set; } [DataType(DataType.Date)] [Required(ErrorMessage = "{0}は、省略することはできません")] [Display(Name = "リリース日")] public DateTime ReleaseDate { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$", ErrorMessage = "ジャンルの指定に誤りがあります")] [Required(ErrorMessage = "{0}は、省略することはできません")] [Display(Name = "ジャンル")] public string Genre { get; set; } [Range(1, 10000, ErrorMessage = "1から10000の間で入力してください")] [Required(ErrorMessage = "{0}は、省略することはできません")] [DisplayFormat(DataFormatString = "{0:#,0}", ApplyFormatInEditMode = true)] [Display(Name = "価格")] public decimal Price { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$", ErrorMessage = "レイティングの指定に誤りがあります")] [StringLength(5)] [Required(ErrorMessage = "{0}は、省略することはできません")] [Display(Name = "レイティング")] public string Rating { get; set; } } }
using JT808.Protocol.Attributes; using JT808.Protocol.Formatters; using JT808.Protocol.MessagePack; namespace JT808.Protocol.MessageBody { public class JT808_0x0200_0x30 : JT808_0x0200_BodyBase, IJT808MessagePackFormatter<JT808_0x0200_0x30> { /// <summary> /// 无线通信网络信号强度 /// </summary> public byte WiFiSignalStrength { get; set; } public override byte AttachInfoId { get; set; } = 0x30; public override byte AttachInfoLength { get; set; } = 1; public JT808_0x0200_0x30 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_0x0200_0x30 jT808LocationAttachImpl0x30 = new JT808_0x0200_0x30(); jT808LocationAttachImpl0x30.AttachInfoId = reader.ReadByte(); jT808LocationAttachImpl0x30.AttachInfoLength = reader.ReadByte(); jT808LocationAttachImpl0x30.WiFiSignalStrength = reader.ReadByte(); return jT808LocationAttachImpl0x30; } public void Serialize(ref JT808MessagePackWriter writer, JT808_0x0200_0x30 value, IJT808Config config) { writer.WriteByte(value.AttachInfoId); writer.WriteByte(value.AttachInfoLength); writer.WriteByte(value.WiFiSignalStrength); } } }
using Lottery.Interfaces.BonusCalculator; using Lottery.Utils; namespace Lottery.Service.BonusCalculator { public class PowerLotteryCalculator : IBonusCalculator { public int CalculateBonus(int shootCount, bool shootSpecial, int selectCount) { var bonus = 0; for (int currentShootCount = 1; currentShootCount <= shootCount; currentShootCount++) { var combination = Calculator.Combination(shootCount, currentShootCount) * Calculator.Combination(selectCount - shootCount, 6 - currentShootCount); bonus += CalculateBonus(currentShootCount, true) * combination; bonus += CalculateBonus(currentShootCount, false) * combination * 7; } return bonus; } private int CalculateBonus(int shootCount, bool shootSpecial) { switch (shootCount) { case 1: return shootSpecial ? 100 : 0; case 2: return shootSpecial ? 200 : 0; case 3: return shootSpecial ? 400 : 100; case 4: return shootSpecial ? 4000 : 800; case 5: return shootSpecial ? 150000 : 20000; case 6: return shootSpecial ? 200000000 : 5000000; } return 0; } } }
using MyShop.Core.Contracts; using MyShop.Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyShop.WebUI.Controllers { public class HomeController : Controller { IRepository<Product> _contextProduct; IRepository<ProductCategory> _contextCategory; public HomeController(IRepository<Product> context, IRepository<ProductCategory> contextCategory) { _contextProduct = context; _contextCategory = contextCategory; } public ActionResult Index() { IEnumerable<Product> products = _contextProduct.GetAll(); return View(products); } public ActionResult Details(string id) { Product product = _contextProduct.Find(id); return View(product); } public ActionResult About() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TournamentBot.BL.Common { public class CommandInvalidArgumentsException : Exception { public CommandInvalidArgumentsException() { } public CommandInvalidArgumentsException(string message) : base(message) { } public CommandInvalidArgumentsException(string message, Exception inner) : base(message, inner) { } } }
using FluentAssertions; using NUnit.Framework; using System.Globalization; using System.Threading; namespace EasyConsoleNG.Tests { [TestFixture] public class EasyConsoleInputTest_Bool { private CultureInfo originalCulture; private TestEasyConsole console; [SetUp] public void SetUp() { console = new TestEasyConsole(); } [Test] public void GivenTrueInput_WhenReadingBool_ShouldReturnTrue() { console.SetupInput("Enabled\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(true); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenFalseInput_WhenReadingBool_ShouldReturnFalse() { console.SetupInput("Disabled\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(false); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenTrueInput_WhenReadingBool_ShouldIgnoreCase() { console.SetupInput("ENABLED\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(true); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenFalseInput_WhenReadingBool_ShouldIgnoreCase() { console.SetupInput("disabled\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(false); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenTrueInput_WhenReadingBool_ShouldAllowBegining() { console.SetupInput("E\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(true); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenFalseInput_WhenReadingBool_ShouldAllowBegining() { console.SetupInput("D\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(false); console.CapturedOutput.Should().Be("Value (default: False): "); } [Test] public void GivenInvalidInput_WhenReadingBool_ShouldRetry() { console.SetupInput("FOO\nE\n"); var value = console.Input.ReadBool("Value"); value.Should().Be(true); console.CapturedOutput.Should().Be("Value (default: False): Please enter a 'True' or 'False'.\nValue (default: False): "); } } }
using Cs_Gerencial.Aplicacao.Interfaces; using Cs_Gerencial.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Cs_Gerencial.Windows { /// <summary> /// Interaction logic for CadastroSenhaMaster.xaml /// </summary> public partial class CadastroSenhaMaster : Window { private readonly IAppServicoParametros _AppServicoParametros = BootStrap.Container.GetInstance<IAppServicoParametros>(); private readonly IAppServicoUsuario _AppServicoUsuario = BootStrap.Container.GetInstance<IAppServicoUsuario>(); private readonly IAppServicoLogSistema _AppServicoLogSistema = BootStrap.Container.GetInstance<IAppServicoLogSistema>(); Usuario _usuario; Parametros parametros; string senhaAtual; LogSistema logSistema; public CadastroSenhaMaster(Usuario usuario) { _usuario = usuario; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { parametros = _AppServicoParametros.GetAll().FirstOrDefault(); senhaAtual = _AppServicoUsuario.DecriptogravarSenha(parametros.SenhaMaster); if (_usuario.NomeUsuario == "Administrador") { gropBoxSenhaAtual.IsEnabled = false; passSenhaNova.IsEnabled = true; } } private void btnSalvar_Click(object sender, RoutedEventArgs e) { parametros.SenhaMaster = _AppServicoUsuario.CriptogravarSenha(passSenhaNova.Password); _AppServicoParametros.Update(parametros); SalvarLogSistema("Alterou a Senha Master"); Close(); } private void passSenhaAtual_PasswordChanged(object sender, RoutedEventArgs e) { VerificarSenhaMasterAtual(); } private void passSenhaNova_PasswordChanged(object sender, RoutedEventArgs e) { VerificarSenhaMasterAtual(); } private void SalvarLogSistema(string descricao) { logSistema = new LogSistema(); logSistema.Data = DateTime.Now.Date; logSistema.Descricao = descricao; logSistema.Hora = DateTime.Now.ToLongTimeString(); logSistema.Tela = "Cadastro Senha Master"; logSistema.IdUsuario = _usuario.UsuarioId; logSistema.Usuario = _usuario.NomeUsuario; logSistema.Maquina = Environment.MachineName.ToString(); _AppServicoLogSistema.Add(logSistema); } private void VerificarSenhaMasterAtual() { if (senhaAtual == passSenhaAtual.Password || _usuario.NomeUsuario == "Administrador") { passSenhaNova.IsEnabled = true; if(passSenhaNova.Password.Length >= 4) btnSalvar.IsEnabled = true; else btnSalvar.IsEnabled = false; } else { passSenhaNova.IsEnabled = false; btnSalvar.IsEnabled = false; } if (_usuario.NomeUsuario == "Administrador") { btnSalvar.IsEnabled = true; passSenhaNova.IsEnabled = true; } } private void PassarDeUmCoponenteParaOutro(object sender, KeyEventArgs e) { var uie = e.OriginalSource as UIElement; if (e.Key == Key.Enter) { e.Handled = true; uie.MoveFocus( new TraversalRequest( FocusNavigationDirection.Next)); } } private void passSenhaAtual_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void passSenhaNova_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } } }
using Game.Entity.Accounts; using Game.Facade; using Game.Kernel; using Game.Utils; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Web; using System.Web.SessionState; using Game.Facade.DataStruct; namespace Game.Web.Card { /// <summary> /// DataHandler 的摘要说明 /// </summary> public class DataHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = GameRequest.GetQueryString("action").ToLower(); switch (action) { case "getnicknamebygameid": GetNickNameByGameID(context); break; case "getpaydiamondlist": GetPayDiamondList(context); break; case "getpresentdiamondlist": GetPresentDiamondList(context); break; case "getcostdiamondlist": GetCostDiamondList(context); break; case "getspreadregisterlist": GetSpreadRegisterList(context); break; case "getexchangediamondlist": GetExchangeDiamondList(context); break; case "getunderlist": GetUnderList(context); break; case "getunderdetail": GetUnderDetail(context); break; default: break; } } /// <summary> /// 获取用户昵称 /// </summary> /// <param name="context"></param> protected void GetNickNameByGameID(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); int gameid = GameRequest.GetFormInt("gameid", 0); AccountsInfo info = FacadeManage.aideAccountsFacade.GetAccountsInfoByGameID(gameid); ajv.SetDataItem("nickname", info != null ? info.NickName : ""); ajv.SetDataItem("compellation", info != null ? info.Compellation : ""); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } /// <summary> /// 获取充值钻石记录 /// </summary> /// <param name="context"></param> protected void GetPayDiamondList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } StringBuilder sb = new StringBuilder(); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); string where = string.Format(" WHERE UserID = {0} AND OrderStatus = 1 ", uti.UserID); PagerSet pagerSet = FacadeManage.aideTreasureFacade.GetPayDiamondRecord(where, page, number); string html = string.Empty; if (pagerSet.PageSet.Tables[0].Rows.Count > 0) { foreach (DataRow item in pagerSet.PageSet.Tables[0].Rows) { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", Fetch.FormatTimeWrap(Convert.ToDateTime(item["PayDate"]))); sb.AppendFormat("<td>{0}</td>", item["BeforeDiamond"]); sb.AppendFormat("<td>{0}</td>", Convert.ToInt32(item["Diamond"]) + Convert.ToInt32(item["OtherPresent"])); sb.AppendFormat("<td>{0}</td>", item["Amount"]); sb.Append("</tr>"); } html = sb.ToString(); } else { html = "<tr><td colspan=\"4\">暂无记录!</td></tr>"; } ajv.SetDataItem("html", html); ajv.SetDataItem("total", pagerSet.RecordCount); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } /// <summary> /// 获取代理赠送钻石记录 /// </summary> /// <param name="context"></param> protected void GetPresentDiamondList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } StringBuilder sb = new StringBuilder(); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); string where = string.Format("WHERE SourceUserID = {0}", uti.UserID); PagerSet pagerSet = FacadeManage.aideRecordFacade.GetAgentPresentDiamondRecord(where, page, number); string html = string.Empty; if (pagerSet.PageSet.Tables[0].Rows.Count > 0) { foreach (DataRow item in pagerSet.PageSet.Tables[0].Rows) { AccountsInfo info = FacadeManage.aideAccountsFacade.GetAccountsInfoByUserID(Convert.ToInt32(item["TargetUserID"])); sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", Fetch.FormatTimeWrap(Convert.ToDateTime(item["CollectDate"]))); sb.AppendFormat("<td>{0}</td>", info != null ? info.GameID.ToString() : ""); sb.AppendFormat("<td>({0}){1}</td>", item["SourceDiamond"], item["PresentDiamond"]); sb.AppendFormat("<td>{0}</td>", item["CollectNote"]); sb.Append("</tr>"); } html = sb.ToString(); } else { html = "<tr><td colspan=\"4\">暂无记录!</td></tr>"; } ajv.SetDataItem("html", html); ajv.SetDataItem("total", pagerSet.RecordCount); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } /// <summary> /// 获取钻石创建房间记录 /// </summary> /// <param name="context"></param> protected void GetCostDiamondList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } StringBuilder sb = new StringBuilder(); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); string where = $"WHERE UserID = {uti.UserID}"; PagerSet pagerSet = FacadeManage.aidePlatformFacade.GetCreateRoomCost(where, page, number); string html; if (pagerSet.PageSet.Tables[0].Rows.Count > 0) { foreach (DataRow item in pagerSet.PageSet.Tables[0].Rows) { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", Fetch.FormatTimeWrap(Convert.ToDateTime(item["CreateDate"]))); sb.AppendFormat("<td>{0}</td>", item["RoomID"]); sb.AppendFormat("<td>{0}</td>", item["CreateTableFee"]); sb.AppendFormat("<td>{0}</td>", !item["DissumeDate"].ToString().Equals("") ? Fetch.FormatTimeWrap(Convert.ToDateTime(item["DissumeDate"])) : ""); sb.Append("</tr>"); } html = sb.ToString(); } else { html = "<tr><td colspan=\"4\">暂无记录!</td></tr>"; } ajv.SetDataItem("html", html); ajv.SetDataItem("total", pagerSet.RecordCount); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } /// <summary> /// 获取代理推广人 /// </summary> /// <param name="context"></param> protected void GetSpreadRegisterList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } StringBuilder sb = new StringBuilder(); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); DataSet ds = FacadeManage.aideAccountsFacade.GetAgentSpreadList(uti.UserID, page, number); string html = string.Empty; if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", Fetch.FormatTimeWrap(Convert.ToDateTime(item["RegisterDate"]))); sb.AppendFormat("<td>{0}</td>", item["GameID"]); sb.AppendFormat("<td>{0}</td>", Fetch.RegisterOrigin(Convert.ToInt32(item["RegisterOrigin"]))); sb.AppendFormat("<td>{0}</td>", Convert.ToInt32(item["AgentID"]) > 0 ? "代理商" : "非代理商"); sb.Append("</tr>"); } html = sb.ToString(); } else { html = "<tr><td colspan=\"4\">暂无记录!</td></tr>"; } ajv.SetDataItem("html", html); ajv.SetDataItem("total", FacadeManage.aideAccountsFacade.GetAgentSpreadCount(uti.UserID)); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } /// <summary> /// 代理兑换游戏币记录 /// </summary> /// <param name="context"></param> protected void GetExchangeDiamondList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } StringBuilder sb = new StringBuilder(); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); PagerSet pagerSet = FacadeManage.aideRecordFacade.GetAgentExchangeDiamondRecord($"WHERE UserID = {uti.UserID} ", page, number); string html = string.Empty; if (pagerSet.PageSet.Tables[0].Rows.Count > 0) { foreach (DataRow item in pagerSet.PageSet.Tables[0].Rows) { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", Fetch.FormatTimeWrap(Convert.ToDateTime(item["CollectDate"]))); sb.AppendFormat("<td>{0}</td>", item["PresentGold"]); sb.AppendFormat("<td>{0}</td>", item["ExchDiamond"]); sb.AppendFormat("<td>{0}</td>", Convert.ToInt64(item["CurDiamond"]) - Convert.ToInt64(item["ExchDiamond"])); sb.Append("</tr>"); } html = sb.ToString(); } else { html = "<tr><td colspan=\"4\">暂无记录!</td></tr>"; } ajv.SetDataItem("html", html); ajv.SetDataItem("total", pagerSet.RecordCount); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } public void GetUnderList(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } string type = GameRequest.GetQueryString("type"); string range = GameRequest.GetQueryString("range"); int number = GameRequest.GetQueryInt("pageSize", 10); int page = GameRequest.GetQueryInt("page", 1); string sqlMonth = " AND CollectDate >= '" + new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd HH:mm:ss") + "'"; string sqlRange = range == "month" ? sqlMonth : ""; number = range == "all" ? 10 : 50; string sqlWhere; long pCount = 0; UnderList list = new UnderList(); PagerSet ps; switch (type) { case "user": sqlWhere = $" WHERE SourceUserID = {uti.UserID} AND TargetUserID NOT IN (SELECT UserID FROM WHJHAccountsDBLink.WHJHAccountsDB.dbo.AccountsAgentInfo) {sqlRange} GROUP BY TargetUserID,SourceUserID "; ps = FacadeManage.aideRecordFacade.GetAgentBelowUserPresentDiamondRecord(sqlWhere, page, number); list.PageCount = ps.PageCount; list.RecordCount = ps.RecordCount; list.PageIndex = ps.PageIndex; list.PageSize = ps.PageSize; if (ps.RecordCount > 0) { foreach (DataRow row in ps.PageSet.Tables[0].Rows) { UnderData data = new UnderData() { UserID = Convert.ToInt32(row["UserID"]), RankID = Convert.ToInt32(row["PageView_RowNo"]) }; data.GameID = FacadeManage.aideAccountsFacade.GetGameIDByUserID(data.UserID); data.NickName = FacadeManage.aideAccountsFacade.GetNickNameByUserID(data.UserID); data.Diamond = FacadeManage.aideTreasureFacade.GetUserCurrency(data.UserID)?.Diamond ?? 0; if (type == "month") { data.MonthDiamond = Convert.ToInt64(row["SumDiamond"]); data.TotalDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID); } else { data.TotalDiamond = Convert.ToInt64(row["SumDiamond"]); data.MonthDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID, sqlMonth); } list.dataList.Add(data); } } pCount = FacadeManage.aideRecordFacade.GetAgentBelowAccountsCount(uti.UserID); break; case "agent": list.Link = true; if (range == "all") { IList<AccountsAgentInfo> belowList = FacadeManage.aideAccountsFacade.GetAgentBelowAgentList(uti.UserID); list.PageCount = 1; list.RecordCount = belowList?.Count ?? 0; list.PageIndex = 1; list.PageSize = belowList?.Count ?? 0; var iCount = 0; if (belowList != null) foreach (AccountsAgentInfo agentInfo in belowList) { iCount++; UnderData data = new UnderData() { UserID = agentInfo.UserID, RankID = iCount }; data.GameID = FacadeManage.aideAccountsFacade.GetGameIDByUserID(data.UserID); data.NickName = FacadeManage.aideAccountsFacade.GetNickNameByUserID(data.UserID); data.Diamond = FacadeManage.aideTreasureFacade.GetUserCurrency(data.UserID)?.Diamond ?? 0; data.TotalDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID, sqlMonth); data.MonthDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID, sqlMonth); list.dataList.Add(data); } } else { sqlWhere = $" WHERE SourceUserID IN ( SELECT UserID FROM WHJHAccountsDBLink.WHJHAccountsDB.dbo.AccountsAgentInfo WHERE ParentAgent = {uti.AgentID} ) {sqlRange} GROUP BY SourceUserID "; ps = FacadeManage.aideRecordFacade .GetAgentBelowAgentPresentDiamondRecord(sqlWhere, page, number); list.PageCount = ps.PageCount; list.RecordCount = ps.RecordCount; list.PageIndex = ps.PageIndex; list.PageSize = ps.PageSize; if (ps.RecordCount > 0) { foreach (DataRow row in ps.PageSet.Tables[0].Rows) { UnderData data = new UnderData() { UserID = Convert.ToInt32(row["UserID"]), RankID = Convert.ToInt32(row["PageView_RowNo"]) }; data.GameID = FacadeManage.aideAccountsFacade.GetGameIDByUserID(data.UserID); data.NickName = FacadeManage.aideAccountsFacade.GetNickNameByUserID(data.UserID); data.Diamond = FacadeManage.aideTreasureFacade.GetUserCurrency(data.UserID)?.Diamond ?? 0; if (type == "month") { data.MonthDiamond = Convert.ToInt64(row["SumDiamond"]); data.TotalDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID); } else { data.TotalDiamond = Convert.ToInt64(row["SumDiamond"]); data.MonthDiamond = FacadeManage.aideRecordFacade.GetTotalPresentCount(uti.UserID, data.UserID, sqlMonth); } list.dataList.Add(data); } } } pCount = FacadeManage.aideAccountsFacade.GetAgentBelowAgentCount(uti.UserID); break; default: ajv.msg = "类型参数丢失!"; context.Response.Write(ajv.SerializeToJson()); return; } ajv.SetDataItem("list", list.dataList); ajv.SetDataItem("total", list.RecordCount); if (list.Link) ajv.SetDataItem("link", true); ajv.SetDataItem("count", pCount); ajv.SetValidDataValue(true); context.Response.Write(ajv.SerializeToJson()); } private static void GetUnderDetail(HttpContext context) { AjaxJsonValid ajv = new AjaxJsonValid(); //判断登录 UserTicketInfo uti = Fetch.GetUserCookie(); if (uti == null || uti.UserID <= 0) { ajv.code = 0; ajv.msg = "登录已失效,请重新打开页面"; context.Response.Write(ajv.SerializeToJson()); return; } int userid = GameRequest.GetQueryInt("userid", 0); AccountsInfo ai = FacadeManage.aideAccountsFacade.GetAccountsInfoByUserID(userid); if (ai.AgentID > 0) { AccountsAgentInfo aai = FacadeManage.aideAccountsFacade.GetAccountsAgentInfoByAgentID(ai.AgentID); UnderDetail underDetail = new UnderDetail() { UserID = ai.UserID, GameID = ai.GameID, NickName = ai.NickName, Compellation = aai.Compellation, QQAccount = aai.QQAccount, ContactAddress = aai.ContactAddress, ContactPhone = aai.ContactPhone, AgentID = ai.AgentID, Diamond = FacadeManage.aideTreasureFacade.GetUserCurrency(ai.UserID)?.Diamond ?? 0 }; ajv.SetDataItem("info",underDetail.ToString()); ajv.SetValidDataValue(true); } context.Response.Write(ajv.SerializeToJson()); } public bool IsReusable => false; } }
using EddiSpeechResponder; using EddiSpeechService; using EddiSpeechService.SpeechPreparation; using EddiVoiceAttackResponder; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; namespace UnitTests { [TestClass] public class SpeechUnitTests : TestBase { [TestInitialize] public void start() { MakeSafe(); } private string CondenseSpaces(string s) { return System.Text.RegularExpressions.Regex.Replace(s, @"\s+", " "); } [DataTestMethod] [DataRow( "Priority 1", "Priority 3", 1, 3, "Priority 1", "Priority 3" )] // Queued in order [DataRow( "Priority 3", "Priority 1", 3, 1, "Priority 1", "Priority 3" )] // Queued out of order public void TestSpeechPriority(string message1, string message2, int priority1, int priority2, string expectedResult1, string expectedResult2 ) { var speechService = new PrivateObject(new SpeechService()); speechService.SetFieldOrProperty("speechQueue", new SpeechQueue()); SpeechQueue speechQueue = (SpeechQueue)speechService.GetFieldOrProperty("speechQueue"); EddiSpeech speech1 = new EddiSpeech(message1, null, priority1); EddiSpeech speech2 = new EddiSpeech(message2, null, priority2); if ( speechQueue is null ) { Assert.Fail(); } speechQueue.Enqueue(speech1); speechQueue.Enqueue(speech2); if ( speechQueue.TryDequeue( out EddiSpeech result1 )) { Assert.IsNotNull( result1 ); } else { Assert.Fail(); } if ( speechQueue.TryDequeue( out EddiSpeech result2 )) { Assert.IsNotNull( result2 ); } else { Assert.Fail(); } Assert.AreEqual( expectedResult1, result1.message); Assert.AreEqual( expectedResult2, result2.message); } [TestMethod] public void TestActiveSpeechPriority() { var speechService = new PrivateObject(new SpeechService()); EddiSpeech priority5speech = new EddiSpeech("Priority 5", null, 5); EddiSpeech priority4speech = new EddiSpeech("Priority 2", null, 4); EddiSpeech priority2speech = new EddiSpeech("Priority 4", null, 2); EddiSpeech priority1speech = new EddiSpeech("Priority 1", null, 1); // Set up priority 5 speech speechService.SetFieldOrProperty("activeSpeechPriority", priority5speech.priority); Assert.AreEqual(5, (int?)speechService.GetFieldOrProperty("activeSpeechPriority")); // Check that priority 5 speech IS interrupted by priority 4 speech. Assert.IsTrue((bool?)speechService.Invoke("checkSpeechInterrupt", new object[] { priority4speech.priority })); // Set up priority 4 speech speechService.SetFieldOrProperty("activeSpeechPriority", priority4speech.priority); Assert.AreEqual(4, (int?)speechService.GetFieldOrProperty("activeSpeechPriority")); // Check that priority 4 speech IS NOT interrupted by priority 2 speech. Assert.IsFalse((bool?)speechService.Invoke("checkSpeechInterrupt", new object[] { priority2speech.priority })); // Check that priority 4 speech IS interrupted by priority 1 speech. Assert.IsTrue((bool?)speechService.Invoke("checkSpeechInterrupt", new object[] { priority1speech.priority })); } [TestMethod] public void TestClearSpeechQueue() { EddiSpeech speech = new EddiSpeech("Priority 3", null, 3); SpeechQueue speechQueue = new SpeechQueue(); Assert.IsTrue(speechQueue.priorityQueues.ElementAtOrDefault(speech.priority) != null); speechQueue.priorityQueues[speech.priority].Enqueue(speech); Assert.AreEqual(1, speechQueue.priorityQueues[speech.priority].Count); speechQueue.DequeueAllSpeech(); Assert.AreEqual(0, speechQueue.priorityQueues[speech.priority].Count); } [TestMethod] public void TestFilterSpeechQueue() { EddiSpeech speech1 = new EddiSpeech("Jumped", null, 3, null, false, "FSD engaged"); EddiSpeech speech2 = new EddiSpeech("Refueled", null, 3, null, false, "Ship refueled"); EddiSpeech speech3 = new EddiSpeech("Scanned", null, 3, null, false, "Body scan"); SpeechQueue speechQueue = new SpeechQueue(); Assert.IsTrue(speechQueue.priorityQueues.ElementAtOrDefault(3) != null); speechQueue.priorityQueues[speech1.priority].Enqueue(speech1); speechQueue.priorityQueues[speech2.priority].Enqueue(speech2); speechQueue.priorityQueues[speech3.priority].Enqueue(speech3); Assert.AreEqual(3, speechQueue.priorityQueues[3].Count); speechQueue.DequeueSpeechOfType("Body scan"); Assert.AreEqual(2, speechQueue.priorityQueues[3].Count); if (speechQueue.priorityQueues[3].TryDequeue(out EddiSpeech result1)) { Assert.AreEqual("FSD engaged", result1.eventType); } if (speechQueue.priorityQueues[3].TryDequeue(out EddiSpeech result2)) { Assert.AreEqual("Ship refueled", result2.eventType); } } [TestMethod] public void TestPathingString1() { string pathingString = @"There are [4;5] lights"; List<string> pathingOptions = new List<string>() { "There are 4 lights" , "There are 5 lights" }; HashSet<string> pathingResults = new HashSet<string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } HashSet<string> expectedHashSet = new HashSet<string>(pathingOptions.Select(CondenseSpaces)); Assert.IsTrue(pathingResults.SetEquals(expectedHashSet)); } [TestMethod] public void TestPathingString2() { string pathingString = @"There are [4;5;] lights"; List<string> pathingOptions = new List<string>() { "There are 4 lights" , "There are 5 lights" , "There are lights" }; HashSet<string> pathingResults = new HashSet<string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } HashSet<string> expectedHashSet = new HashSet<string>(pathingOptions.Select(CondenseSpaces)); Assert.IsTrue(pathingResults.SetEquals(expectedHashSet)); } [TestMethod] public void TestPathingString3() { string pathingString = @"There [are;might be;could be] [4;5;] lights;It's dark in here;"; List<string> pathingOptions = new List<string>() { "There are 4 lights" , "There are 5 lights" , "There are lights" ,"There might be 4 lights" , "There might be 5 lights" , "There might be lights" ,"There could be 4 lights" , "There could be 5 lights" , "There could be lights" , "It's dark in here" , "" }; HashSet<string> pathingResults = new HashSet<string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } HashSet<string> expectedHashSet = new HashSet<string>(pathingOptions.Select(CondenseSpaces)); Assert.IsTrue(pathingResults.SetEquals(expectedHashSet)); } [TestMethod] public void TestPathingString4() { var pathingString = @";;;;;;Seven;;;"; var pathingOptions = new List<string>() { "" , "Seven" }; int sevenCount = 0; var pathingResults = new HashSet<string>(); for ( int i = 0; i < 10000; i++) { var pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add( pathedString ); if ( pathedString == "Seven") { sevenCount++; } } Assert.IsTrue(sevenCount > 750); Assert.IsTrue(sevenCount < 1500); var expectedHashSet = new HashSet<string>(pathingOptions.Select(CondenseSpaces)); Assert.IsTrue( pathingResults.SetEquals( expectedHashSet ) ); } [TestMethod] public void TestPathingString5() { string pathingString = @"You leave me [no choice]."; List<string> pathingOptions = new List<string>() { "You leave me no choice." }; HashSet<string> pathingResults = new HashSet<string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } Assert.IsTrue(pathingResults.SetEquals(new HashSet<string>(pathingOptions))); } [TestMethod] public void TestPathingString6() { string pathingString = @"[There can be only one.]"; List<string> pathingOptions = new List<string>() { "There can be only one." }; HashSet<string> pathingResults = new HashSet<string>(); for (int i = 0; i < 1000; i++) { string pathedString = VoiceAttackPlugin.SpeechFromScript(pathingString); pathingResults.Add(pathedString); } Assert.IsTrue(pathingResults.SetEquals(new HashSet<string>(pathingOptions))); } [TestMethod] public void TestSectorTranslations() { Assert.AreEqual("Swoiwns <say-as interpret-as=\"characters\">N</say-as> <say-as interpret-as=\"characters\">Y</say-as> dash <say-as interpret-as=\"characters\">B</say-as> <say-as interpret-as=\"characters\">a</say-as> 95 dash 0", Translations.GetTranslation("Swoiwns NY-B a95-0")); Assert.AreEqual("<say-as interpret-as=\"characters\">P</say-as> <say-as interpret-as=\"characters\">P</say-as> <say-as interpret-as=\"characters\">M</say-as> 5 2 8 7", Translations.GetTranslation("PPM 5287")); } [TestMethod] public void TestTranslationVesper() { Assert.AreEqual(Translations.GetTranslation("VESPER-M4"), "Vesper M 4"); } [TestMethod] public void TestSpeechQueue_DequeueSpeechOfType() { PrivateObject privateObject = new PrivateObject(new SpeechQueue()); privateObject.Invoke("DequeueAllSpeech", System.Array.Empty<object>()); privateObject.Invoke("Enqueue", new object[] { new EddiSpeech("Test speech 1", null, 3, null, false, null) }); privateObject.Invoke("Enqueue", new object[] { new EddiSpeech("Test speech 2", null, 4, null, false, "Hull damaged") }); privateObject.Invoke("Enqueue", new object[] { new EddiSpeech("Test speech 3", null, 3, null, false, "Body scanned") }); List<ConcurrentQueue<EddiSpeech>> priorityQueues = (List<ConcurrentQueue<EddiSpeech>>)privateObject.GetFieldOrProperty("priorityQueues"); Assert.AreEqual(3, priorityQueues?.SelectMany(q => q).Count()); try { // Only the speech of type "Hull damaged" should be removed, null types and other types should remain in place. privateObject.Invoke("DequeueSpeechOfType", new object[] { "Hull damaged" }); Assert.AreEqual(2, priorityQueues?.SelectMany(q => q).Count()); // Verify that the order of remaining speech of the same priority is unchanged. Assert.AreEqual("Test speech 1", priorityQueues?[3].First().message); Assert.AreEqual("Test speech 3", priorityQueues?[3].Last().message); } catch (System.Exception) { Assert.Fail(); } privateObject.Invoke("DequeueAllSpeech", System.Array.Empty<object>()); } [DataTestMethod] // Test escaping for invalid ssml. [DataRow("<invalid>test</invalid> <invalid withattribute='attribute'>test2</invalid>", "&lt;invalid&gt;test&lt;/invalid&gt; &lt;invalid withattribute='attribute'&gt;test2&lt;/invalid&gt;")] // Test escaping for double quotes, single quotes, and <phoneme> ssml commands. XML characters outside of ssml elements are escaped. [DataRow(@"<phoneme alphabet=""ipa"" ph=""ʃɪnˈrɑːrtə"">Shinrarta</phoneme> <phoneme alphabet='ipa' ph='ˈdezɦrə'>Dezhra</phoneme> & Co's shop", "<phoneme alphabet=\"ipa\" ph=\"ʃɪnˈrɑːrtə\">Shinrarta</phoneme> <phoneme alphabet='ipa' ph='ˈdezɦrə'>Dezhra</phoneme> &amp; Co&apos;s shop")] // Test escaping for <break> elements. XML characters outside of ssml elements are escaped. [DataRow(@"<break time=""100ms""/>He said ""Foo"".", "<break time=\"100ms\"/>He said &quot;Foo&quot;.")] // Test escaping for Cereproc unique <usel> and <spurt> elements. Input and output should be equal. [DataRow(@"<spurt audio='g0001_004'>cough</spurt> This is a <usel variant=""1"">test</usel> sentence.", @"<spurt audio='g0001_004'>cough</spurt> This is a <usel variant=""1"">test</usel> sentence.")] // Test escaping for characters included in the escape sequence ('X' in this case) [DataRow(@"Brazilian armada <say-as interpret-as=""characters"">X</say-as>", @"Brazilian armada <say-as interpret-as=""characters"">X</say-as>")] public void TestSpeechServiceEscaping(string input, string expectedOutput) { var result = SpeechFormatter.EscapeSSML(input); Assert.AreEqual(expectedOutput, result); } [TestMethod] public void TestDisableIPA() { // Test removal of <phoneme> tags (and only phenome tags) when the user has indicated that they would like to disable phonetic speech var line = @"<break time=""100ms""/><phoneme alphabet=""ipa"" ph=""ʃɪnˈrɑːrtə"">Shinrarta</phoneme> <phoneme alphabet='ipa' ph='ˈdezɦrə'>Dezhra</phoneme> & Co's shop"; var result = SpeechFormatter.DisableIPA(line); Assert.AreEqual(@"<break time=""100ms""/>Shinrarta Dezhra & Co's shop", result); } [TestMethod] public void TestPersonalityLocalizedScriptsAreComplete() { // Make sure that all default scripts in our invariant personality also exist in localized default personalities var dirInfo = new DirectoryInfo(AppContext.BaseDirectory); var @default = Personality.FromFile(dirInfo?.FullName + "\\eddi.json", true); Assert.IsNotNull(@default); var missingScripts = new Dictionary<string, List<string>>(); foreach (var fileInfo in dirInfo.GetFiles().Where(f => f.Name.StartsWith("eddi") && f.Name != "eddi.json")) { var localizedDefaultPersonality = Personality.FromFile(fileInfo.FullName); foreach (var script in @default.Scripts) { if (!@localizedDefaultPersonality.Scripts.ContainsKey(script.Key)) { // Missing script found if (!missingScripts.ContainsKey(fileInfo.Name)) { // Make sure we've initialized a list to record it missingScripts[fileInfo.Name] = new List<string>(); } // Record the missing script missingScripts[fileInfo.Name].Add(script.Key); } } } Assert.AreEqual(0, missingScripts.Count); } [DataTestMethod] [DataRow(@" ", "")] [DataRow(@"Test <break time=""3s""/>", "Test")] [DataRow(@"<break time=""3ms""/> Test", @"<break time=""3ms""/> Test")] [DataRow(@"<break time=""3ms""/> <break time=""3ms""/>", "")] [DataRow(@"<break time=""3s""/> Test <break time=""3s""/>", @"<break time=""3s""/> Test")] public void TestSpeechServiceTrimming(string input, string output) { Assert.AreEqual(output, SpeechFormatter.TrimSpeech(input)); } [DataTestMethod] [DataRow( "{body.", "body" ) ] [DataRow( "{set test to body.", "body" ) ] [DataRow( "{set test to body.materials[0].", @"body.materials.<index\>" ) ] [DataRow( "{set test to body.materials[0].Category.", @"body.materials.<index\>.Category" ) ] [DataRow( "{StationDetails().", "StationDetails()" )] public void TestSpeechResponderTextCompletionLookupItem ( string lineTxt, string result ) { Assert.AreEqual(result, EditScriptWindow.GetTextCompletionLookupItem(lineTxt)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nhibernate { class Car { public virtual int Id { get; set; } public virtual string Title { get; set; } public virtual Make Make { get; set; } public virtual Model Model { get; set; } } }