text
stringlengths
13
6.01M
using DropNet; using Krystalware.UploadHelper; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GameMusicRecord { public partial class Form1 : Form { public Form1() { InitializeComponent(); Upload(); } void Upload() { } } }
using System; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sesi.WebsiteDaSaude.WebApi.Interfaces; using Sesi.WebsiteDaSaude.WebApi.Models; using Sesi.WebsiteDaSaude.WebApi.Repositories; namespace Sesi.WebsiteDaSaude.WebApi.Controllers { [ApiController] [Route("api/[controller]")] [Produces("application/json")] public class ServicosController : ControllerBase { private IServicoRepository ServicoRepository { get; set; } public ServicosController() { ServicoRepository = new ServicoRepository(); } [HttpGet] public IActionResult Listar() { try { return Ok(ServicoRepository.Listar()); }catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } [HttpGet("{id}")] public IActionResult BuscarPorId(int id) { try { var servico = ServicoRepository.BuscarPorId(id); if (servico == null) { return NotFound(new { Erro = true, Mensagem = "Serviço não encontrado." }); } return Ok(servico); } catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } [HttpGet("buscar/{nomeServico}")] public IActionResult BuscarPorNome(string nomeServico) { try { var lista = ServicoRepository.BuscarPorNome(nomeServico); return Ok(lista); }catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } [HttpPost] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Cadastrar(Servicos servico) { try { ServicoRepository.Cadastrar(servico); return Ok(new {Mensagem = "Serviço cadastrado com sucesso!"}); }catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } [HttpPut("{id}")] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Editar(int id, Servicos servicoPassado) { try { servicoPassado.IdServico = id; ServicoRepository.Editar(servicoPassado); return Ok(new { Mensagem = "Serviço alterado com sucesso!" }); }catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } [HttpDelete("{id}")] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Excluir(int id) { try { ServicoRepository.Excluir(id); return Ok(new { Mensagem = "Serviço excluído com sucesso!" }); }catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Projekt53262 { public class Kiosk : KontrolaPrasy { private string adres; public List<Przeglad> listaKategorii = new List<Przeglad>(); public List<Pracownik> listaPracownikow = new List<Pracownik>(); public Kiosk() { } public Kiosk(string adres) { this.adres = adres; } public void DodajPracownika(Pracownik pracownik) { if (listaPracownikow == null) { listaPracownikow[0] = pracownik; } else { listaPracownikow.Add(pracownik); } } public void WypiszPracownikow() { Console.WriteLine($"\nZatrudnieni w kiosku o adresie:{this.adres}"); foreach (Pracownik pracownik in listaPracownikow) { pracownik.WypiszInfo(); } } public void DodajKategorie(Przeglad nazwaKategorii) { if (listaKategorii == null) { listaKategorii[0] = nazwaKategorii; } else { if (listaKategorii.Find(x => x.Rodzaj == nazwaKategorii.Rodzaj) == null) { listaKategorii.Add(nazwaKategorii); } } } public void DodajPrase(Prasa prasa, string Rodzaj) { var i = listaKategorii.FindIndex(x => x.Rodzaj == Rodzaj); if (i == -1) { Przeglad przeglad = new Przeglad(Rodzaj); DodajKategorie(przeglad); listaKategorii.Last().DodajPrase(prasa); } else { listaKategorii[i].DodajPrase(prasa); } } public void WypiszWszystkiePrasy() { Console.WriteLine($"\nWszystkie gazety dostępne w kiosku pod adresem: {this.adres}"); foreach (Przeglad przeglad in listaKategorii) { przeglad.WypiszWszystkiePrasy(); } } public void ZnajdzPrasePoNr(int i) { foreach (Przeglad przeglad in listaKategorii) { przeglad.ZnajdzPrasePoNr(i); } } public void ZnajdzPrasePoTytule(string tytul) { foreach (Przeglad przeglad in listaKategorii) { przeglad.ZnajdzPrasePoTytule(tytul); } } } }
using Resource; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; namespace Common.Wpf.Validation { public class PasswordRule : ValidationRuleBase { private PasswordRule() { } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string password = value as string; if (password.Length < 6 || password.Length > 10) { return new ValidationResult(false, string.Empty); } bool hasCapital = false; char[] charArray = password.ToCharArray(); foreach (char c in charArray) { if (Char.IsUpper(c)) { hasCapital = true; break; } } if (!hasCapital) return new ValidationResult(false, Messages.PasswordRequireCapital); return new ValidationResult(true, null); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Entities.Urls { public enum PageUsage { NoTabs = -1, ThisTab = 0, //AnotherTab = 1, //AllTabs = 2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; /// <summary> /// Task timeout helper based on https://devblogs.microsoft.com/pfxteam/crafting-a-task-timeoutafter-method/ /// </summary> namespace System.Threading.Tasks { public static class TaskTimeoutExtensions { public static async Task WithCancellation(this Task task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s!).TrySetResult(true), tcs)) { if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false)) { throw new OperationCanceledException(cancellationToken); } await task; // already completed; propagate any exception } } public static Task TimeoutAfter(this Task task, int millisecondsTimeout) => task.TimeoutAfter(TimeSpan.FromMilliseconds(millisecondsTimeout)); public static async Task TimeoutAfter(this Task task, TimeSpan timeout) { var cts = new CancellationTokenSource(); if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)).ConfigureAwait(false)) { cts.Cancel(); await task.ConfigureAwait(false); } else { throw new TimeoutException($"Task timed out after {timeout}"); } } public static Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, int millisecondsTimeout) => task.TimeoutAfter(TimeSpan.FromMilliseconds(millisecondsTimeout)); public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) { var cts = new CancellationTokenSource(); if (task == await Task<TResult>.WhenAny(task, Task<TResult>.Delay(timeout, cts.Token)).ConfigureAwait(false)) { cts.Cancel(); return await task.ConfigureAwait(false); } else { throw new TimeoutException($"Task timed out after {timeout}"); } } #if !NETFRAMEWORK public static Task TimeoutAfter(this ValueTask task, int millisecondsTimeout) => task.AsTask().TimeoutAfter(TimeSpan.FromMilliseconds(millisecondsTimeout)); public static Task TimeoutAfter(this ValueTask task, TimeSpan timeout) => task.AsTask().TimeoutAfter(timeout); public static Task<TResult> TimeoutAfter<TResult>(this ValueTask<TResult> task, int millisecondsTimeout) => task.AsTask().TimeoutAfter(TimeSpan.FromMilliseconds(millisecondsTimeout)); public static Task<TResult> TimeoutAfter<TResult>(this ValueTask<TResult> task, TimeSpan timeout) => task.AsTask().TimeoutAfter(timeout); #endif public static async Task WhenAllOrAnyFailed(this Task[] tasks, int millisecondsTimeout) { var cts = new CancellationTokenSource(); Task task = tasks.WhenAllOrAnyFailed(); if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)).ConfigureAwait(false)) { cts.Cancel(); await task.ConfigureAwait(false); } else { throw new TimeoutException($"{nameof(WhenAllOrAnyFailed)} timed out after {millisecondsTimeout}ms"); } } public static async Task WhenAllOrAnyFailed(this Task[] tasks) { try { await WhenAllOrAnyFailedCore(tasks).ConfigureAwait(false); } catch { // Wait a bit to allow other tasks to complete so we can include their exceptions // in the error we throw. using (var cts = new CancellationTokenSource()) { await Task.WhenAny( Task.WhenAll(tasks), Task.Delay(3_000, cts.Token)).ConfigureAwait(false); // arbitrary delay; can be dialed up or down in the future } var exceptions = new List<Exception>(); foreach (Task t in tasks) { switch (t.Status) { case TaskStatus.Faulted: exceptions.Add(t.Exception!); break; case TaskStatus.Canceled: exceptions.Add(new TaskCanceledException(t)); break; } } Debug.Assert(exceptions.Count > 0); if (exceptions.Count > 1) { throw new AggregateException(exceptions); } throw; } } private static Task WhenAllOrAnyFailedCore(this Task[] tasks) { int remaining = tasks.Length; var tcs = new TaskCompletionSource<bool>(); foreach (Task t in tasks) { t.ContinueWith(a => { if (a.IsFaulted) { tcs.TrySetException(a.Exception!.InnerExceptions); Interlocked.Decrement(ref remaining); } else if (a.IsCanceled) { tcs.TrySetCanceled(); Interlocked.Decrement(ref remaining); } else if (Interlocked.Decrement(ref remaining) == 0) { tcs.TrySetResult(true); } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } return tcs.Task; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DocumentManagementLogger { public interface ILogger { void AddErrorLog(string msg); void AddErrorLog(string msg, Exception ex); void AddErrorLog(Exception ex); void AddInformationLog(string msg); void AddWarningLog(string msg); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FormDesigner { public class DocumentRepositoryConfiguration { public DocumentRepositoryConfiguration (string endpoint, string key, string databaseId, string collectionId) { Endpoint = endpoint; Key = key; DatabaseId = databaseId; CollectionId = collectionId; } public string Endpoint { get; set; } public string Key { get; set; } public string DatabaseId { get; set; } public string CollectionId { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace PickUp.Dal.Models { public class Event { public int RestoId { get; set; } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Logo { get; set; } public decimal Rating { get; set; } public Event(int id, int restoId, string name, string description, string logo, decimal rating) { Id = id; RestoId = restoId; Name = name; Description = description; Logo = logo; Rating = rating; } public Event(int id, string name, string description) { Id = id; Name = name; Description = description; } } }
namespace Tests { class RomanNumeralsCalculatorTests { } }
using System.IO; using GameLib; using GameLib.Audio; using GameLib.Input; using JumpAndRun.ClientBase; using ManagedBass; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace JumpAndRun.Client { /// <summary> /// This is the main type for your game. /// </summary> public class JumpAndRunWindowsGame : Game { private readonly BaseGame _baseGame; private readonly GraphicsDeviceManager _manager; public JumpAndRunWindowsGame() { _manager = new GraphicsDeviceManager(this); _manager.GraphicsProfile = GraphicsProfile.HiDef; _baseGame = new BaseGame(this); Content.RootDirectory = "Content"; _manager.PreferredBackBufferWidth = 1920; _manager.PreferredBackBufferHeight = 1080; GameContext.Instance.Set(Platform.WindowsForms, null); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Bass.Init(); ContentManager.Instance.LoadContent(); ContentManager.Instance.Effect = Content.Load<Effect>("LightsBump"); ContentManager.Instance.Font = Content.Load<SpriteFont>("Font1"); ContentManager.Instance.Effects.Add("JumpAndRun.DrunkEffect", Content.Load<Effect>("DrunkEffect")); //SoundEffect.MasterVolume = 1; _baseGame.Initialize(_manager); ContentManager.Instance.RegisterContent(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unloa /// game-specific content. /// </summary> protected override void UnloadContent() { _baseGame.UnloadContent(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="realGameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime realGameTime) { _baseGame.Update(realGameTime); base.Update(realGameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="realGameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime realGameTime) { _baseGame.Draw(realGameTime); base.Draw(realGameTime); } } }
using System; using System.IO; using System.Windows; using System.Windows.Forms; using hybridEncryptor; using System.Windows.Media; using Microsoft.VisualBasic; using System.Diagnostics; namespace Encryption { /// <summary> /// Interaction logic for Encrypteer.xaml /// </summary> public partial class KeySelect : Window { private HybridEncryptor encryptor; string privateA = null; string publicB = null; bool next; public KeySelect(HybridEncryptor encryptor,bool type) { this.encryptor = encryptor; InitializeComponent(); btn_volgende.IsEnabled = false; next = type; } private string browseFile() { //file path ophalen OpenFileDialog fd = new OpenFileDialog(); string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string output = null; string file = null; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) // Test result. { file = fd.FileName; try { if (Directory.Exists(path)) { fd.InitialDirectory = path; } else { fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } output = File.ReadAllText(file); } catch (IOException ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } return output; } private void btn_genereerKey_Click(object sender, RoutedEventArgs e) { //nieuwe key gennen en ophalen encryptor.GenerateRsaKey(); privateA = encryptor.GetRsaKey(true); //naam vragen voor keys string filename = Interaction.InputBox("geef een naam voor de keys", "key naam", "myKey"); //map aanmaken als die er niet is Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\encrypted\\keys"); //private key opslaan using (StreamWriter file = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\encrypted\\keys\\private_"+filename)) { file.WriteLine(privateA); file.Close(); } //public key opslaan using (StreamWriter file = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\encrypted\\keys\\public_"+filename)) { file.WriteLine(encryptor.GetRsaKey(false)); file.Close(); } //melding weergeven en explorer openen op locatie van de files System.Windows.MessageBox.Show("de files zijn gesaved onder:" + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\encrypted\\keys"); Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\encrypted\\keys"); lblUw.Background = Brushes.Green; Unlock(); } private void btn_getPrivateA_Click(object sender, RoutedEventArgs e) { privateA = browseFile(); lblUw.Background = Brushes.Green; Unlock(); } private void btn_getPublicB_Click(object sender, RoutedEventArgs e) { publicB = browseFile(); lblHun.Background = Brushes.Green; Unlock(); } private void Unlock() { if (privateA != null && publicB != null) { btn_volgende.IsEnabled = true; } } private void btn_vorige_Click(object sender, RoutedEventArgs e) { MainWindow window = new MainWindow(); Close(); window.Show(); } private void btn_volgende_Click(object sender, RoutedEventArgs e) { //checken welke optie er in de startmenu gekozen is en dan die starten if (next) { new Encrypteer(encryptor, privateA, publicB).Show(); } else { new Decrypteer(encryptor, privateA, publicB).Show(); } Close(); } } }
using EatDrinkApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EatDrinkApplication.Contracts { public interface ICocktailByIngredientRequest { Task<Cocktails> GetCocktailsByIngredients(string ingredient); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test11._1andtest11._2 { class Program { static void Main(string[] args) { ///////////////////// 试题11.1 ///////////////////// /// try { checked //内存溢出 { int iNum1, iNum2, Num; iNum1 = iNum2 = 60000000; Num = iNum1 * iNum2; Console.WriteLine("{0}*{1}={2}", iNum1, iNum2, Num); } } catch (OverflowException ex) { Console.WriteLine("当前程序引发OverflowException异常:" + ex.Message); } finally { Console.WriteLine("程序结束"); } ///////////////////// 试题11.2 ///////////////////// Console.ReadKey(); } } }
using System.Windows.Controls; namespace EcobitStage.View { /// <summary> /// Interaction logic for UserView.xaml /// </summary> public partial class PrivilegeEditView : Page { public PrivilegeEditView() { InitializeComponent(); } } }
using System.Diagnostics; using Windows.UI; using TheLivingRoom.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237 namespace TheLivingRoom { /// <summary> /// A basic page that provides characteristics common to most applications. /// </summary> public sealed partial class MainPage : Page { private NavigationHelper navigationHelper; private ObservableDictionary defaultViewModel = new ObservableDictionary(); // Used in assigning Sounds to TriggerPoints TriggerPoint toBeAssignedTriggerPoint; Grid toBeAssignedTriggerTile; List<Grid> triggerTiles; /// <summary> /// This can be changed to a strongly typed view model. /// </summary> public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } /// <summary> /// NavigationHelper is used on each page to aid in navigation and /// process lifetime management /// </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } public MainPage() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += navigationHelper_LoadState; this.navigationHelper.SaveState += navigationHelper_SaveState; // Set to-be-assigned helpers to null toBeAssignedTriggerPoint = null; toBeAssignedTriggerTile = null; triggerTiles = new List<Grid>(); // Listen to global KeyDown events Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown; // Get all of the sounds available RenderSounds(); // Get all of the furniture available RenderFurniture(); } private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args) { FurnitureEngine.GetInstance().HandleTrigger(args.VirtualKey); } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { Debug.WriteLine("LoadState Called."); // Check if any of the triggers are assigned and restore the tile foreach (Grid triggerTile in triggerTiles) { // Look up if this trigger should be set with a Sound String triggerID = triggerTile.Tag.ToString(); if (e.PageState != null && e.PageState.ContainsKey(triggerID)) { // Set the TriggerPoint and change its tile Icon TriggerPoint triggerPoint = FurnitureEngine.GetInstance().GetTriggerPointByID(triggerID); Sound sound = FurnitureEngine.GetInstance().GetSoundByName(e.PageState[triggerID].ToString()); if (triggerPoint != null && sound != null) { // Set trigger point triggerPoint.Set(sound); // Set TriggerTile thumbnail to Sound icon Image triggerTileThumbnail = triggerTile.Children[0] as Image; string uriString = "ms-appx:///Assets/SoundPacks/Garage/Icons/" + sound.Name.ToLower() + ".png"; triggerTileThumbnail.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(uriString)); // Reset TriggerTile label to triggernumber int triggerNumber = (int)triggerTile.GetValue(Grid.ColumnProperty); Grid triggerTileLabelGrid = triggerTile.Children[1] as Grid; TextBlock triggerTileLabel = triggerTileLabelGrid.Children[0] as TextBlock; triggerTileLabel.Text = triggerNumber.ToString(); // Change background color of TriggerTile to normal color (white) triggerTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 255, 255, 255) }; } } } } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void navigationHelper_SaveState(object sender, SaveStateEventArgs e) { Debug.WriteLine("SaveState Called."); // Save state of each trigger List<KeyValuePair<String, String>> stateOfTriggers = FurnitureEngine.GetInstance().GetStateOfTriggers(); foreach (KeyValuePair<String, String> statePair in stateOfTriggers) { Debug.WriteLine("Saving mapping " + statePair.Key + " to " + statePair.Value + "."); e.PageState[statePair.Key] = statePair.Value; } } #region NavigationHelper registration /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// /// Page specific logic should be placed in event handlers for the /// <see cref="GridCS.Common.NavigationHelper.LoadState"/> /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. protected override void OnNavigatedTo(NavigationEventArgs e) { navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { navigationHelper.OnNavigatedFrom(e); } #endregion /************************************** Click Event Handlers **************************************/ // Handle transition to Settings page private void settingsButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(SettingsPage)); FurnitureEngine.GetInstance().ClearTriggers(); } // Play preview of Sound corresponding to this SoundTile private void SoundTile_PointerPressed(object sender, RoutedEventArgs e) { Grid clickedTile = (Grid)sender; int row = (int)clickedTile.GetValue(Grid.RowProperty); int col = (int)clickedTile.GetValue(Grid.ColumnProperty); int soundId = row * 3 + col; // Get Sound that corresponds with this cell Sound theSound = FurnitureEngine.GetInstance().GetCurrentSoundPack().Sounds[soundId]; // Check if a TriggerPoint is in the process of being assigned. // If so, assign the TriggerPoint. if (toBeAssignedTriggerPoint != null) { // Set trigger point toBeAssignedTriggerPoint.Set(theSound); // Set TriggerTile thumbnail to Sound icon Image triggerTileThumbnail = toBeAssignedTriggerTile.Children[0] as Image; Image soundTileThumbnail = clickedTile.Children[0] as Image; triggerTileThumbnail.Source = soundTileThumbnail.Source; // Reset TriggerTile label to triggernumber int triggerNumber = (int)toBeAssignedTriggerTile.GetValue(Grid.ColumnProperty); Grid triggerTileLabelGrid = toBeAssignedTriggerTile.Children[1] as Grid; TextBlock triggerTileLabel = triggerTileLabelGrid.Children[0] as TextBlock; triggerTileLabel.Text = triggerNumber.ToString(); // Change background color of TriggerTile to normal color (white) toBeAssignedTriggerTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 255, 255, 255) }; // Clear to-be-assigned helpers toBeAssignedTriggerPoint = null; toBeAssignedTriggerTile = null; } // Play preview of Sound PlaybackEngine.GetInstance().PlaySoundPreview(theSound); } private void TriggerTile_PointerPressed(object sender, PointerRoutedEventArgs e) { Grid clickedTile = (Grid)sender; // Trigger number equal to column number of tile int triggerNumber = (int)clickedTile.GetValue(Grid.ColumnProperty); // Furniture number equal to row number of parent Grid object int furnitureNumber = (int)clickedTile.Parent.GetValue(Grid.RowProperty); // The only use case for pressing a TriggerTile is when setting its Sound // Therefore, we always clear the the previous sound if applicable // and wait for the user to press a SoundTile // Check if another Trigger was pending and change it back to a "Not Set" tile if (toBeAssignedTriggerTile != null) { // Reset thumbnail Image prevTileThumbnail = toBeAssignedTriggerTile.Children[0] as Image; prevTileThumbnail.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/not_set2.png")); // Reset label to trigger number int prevTriggerNumber = (int)toBeAssignedTriggerTile.GetValue(Grid.ColumnProperty); Grid prevTileLabelGrid = toBeAssignedTriggerTile.Children[1] as Grid; TextBlock prevTileLabel = prevTileLabelGrid.Children[0] as TextBlock; prevTileLabel.Text = prevTriggerNumber.ToString(); // Reset background color (to white) toBeAssignedTriggerTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 255, 255, 255) }; } // Set to-be-assigned helper members toBeAssignedTriggerTile = clickedTile; toBeAssignedTriggerPoint = FurnitureEngine.GetInstance().GetFurnitureAtIndex(furnitureNumber).GetTriggerPointAtIndex(triggerNumber - 1); // Reset TriggerPoint, if applicable if (toBeAssignedTriggerPoint.IsSet()) { // Unassign Sound from this Trigger toBeAssignedTriggerPoint.Clear(); } // Set thumbnail to pending "hourglass" icon Image tileThumbnail = toBeAssignedTriggerTile.Children[0] as Image; tileThumbnail.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/hourglass.png")); // Set label to "Pending" Grid tileLabelGrid = toBeAssignedTriggerTile.Children[1] as Grid; TextBlock tileLabel = tileLabelGrid.Children[0] as TextBlock; tileLabel.Text = "Pending"; // Set Tile background to pending assignment color (light orange) toBeAssignedTriggerTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 247, 231, 178) }; } /*private void TriggerTile_CancelAssignment(object sender, PointerRoutedEventArgs e) { if (toBeAssignedTriggerPoint != null) { // Reset thumbnail Image tileThumbnail = toBeAssignedTriggerTile.Children[0] as Image; tileThumbnail.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/not_set.png")); // Reset background (white) toBeAssignedTriggerTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 255, 255, 255) }; } }*/ /************************************** Dynamic UI initialization methods **************************************/ // Populate the soundGrid according to the current SoundPack private void RenderSounds() { List<Sound> sounds = FurnitureEngine.GetInstance().GetCurrentSoundPack().Sounds; // Grid holds maximum of 9 Sounds int numSoundButtons = Math.Min(sounds.Count, 9); for (int i = 0; i < numSoundButtons; ++i) { Grid soundTile = GridUtility.CreateEmptyTile(); soundTile.Background = new SolidColorBrush { Color = Color.FromArgb(255, 204, 248, 255) }; // Set tile image to instrument icon Image soundTileImage = soundTile.Children[0] as Image; string uriString = "ms-appx:///Assets/SoundPacks/Garage/Icons/" + sounds[i].Name.ToLower() + ".png"; soundTileImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(uriString)); // Set the tile label to the instrument name Grid tileLabelGrid = soundTile.Children[1] as Grid; TextBlock tileLabel = tileLabelGrid.Children[0] as TextBlock; tileLabel.Text = sounds[i].Name; // Add the tile in the appropriate row/column soundTile.SetValue(Grid.ColumnProperty, 0); soundTile.SetValue(Grid.RowProperty, i / 3); soundTile.SetValue(Grid.ColumnProperty, i % 3); // Handle PointerPressed event (similar to Click, but for Grids) soundTile.PointerPressed += SoundTile_PointerPressed; soundGrid.Children.Add(soundTile); } } // Populate the furnitureGrid according to FurnitureEngine private void RenderFurniture() { List<Furniture> furniture = FurnitureEngine.GetInstance().GetFurnitureItems(); // At most 3 pieces of Furniture are displayed in furnitureGrid int numFurnitureGrids = Math.Min(furniture.Count, 3); // Render each piece of Furniture in a row with 4 columns as follows: // Col0: Furniture Layout Tile, Col1-3: Trigger Point(s) for (int i = 0; i < numFurnitureGrids; ++i) { Grid curFurnitureRow = GridUtility.CreateFurnitureRow(i); // Create Furniture layout tile in column 0 Grid layoutTile = GridUtility.CreateFurnitureLayoutTile(furniture[i].Name); layoutTile.SetValue(Grid.ColumnProperty, 0); curFurnitureRow.Children.Add(layoutTile); // Add up to three Furniture TriggerPoints in curFurnitureRow columns 1-3 for (int j = 0; j < furniture[i].NumTriggerPoints(); ++j) { // Create tile grid in column j + 1 Grid triggerTile = GridUtility.CreateEmptyTile(); // Give extra right margin to final column if (j == 2) { triggerTile.Margin = new Thickness(10, 10, 20, 10); } // Second child is labelGrid. First child of labelGrid is label. Image tileTriggerImage = triggerTile.Children[0] as Image; tileTriggerImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/not_set2.png")); Grid tileTriggerLabelGrid = triggerTile.Children[1] as Grid; TextBlock tileTriggerLabel = tileTriggerLabelGrid.Children[0] as TextBlock; tileTriggerLabel.Text = (j + 1).ToString(); // Handle PointerPressed events from all TriggerTiles (assignment) triggerTile.PointerPressed += TriggerTile_PointerPressed; triggerTile.SetValue(Grid.ColumnProperty, (j + 1)); curFurnitureRow.Children.Add(triggerTile); // Set tag of this tile to corresponding TriggerPoint's ID TriggerPoint triggerPoint = FurnitureEngine.GetInstance().GetFurnitureAtIndex(i).GetTriggerPointAtIndex(j); triggerTile.Tag = triggerPoint.ID; triggerTiles.Add(triggerTile); } // Add curFurnitureRow to furnitureGrid curFurnitureRow.SetValue(Grid.RowProperty, i); furnitureGrid.Children.Add(curFurnitureRow); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TileDisappearing : MonoBehaviour { public float cycleOffset; public GameObject target; // Start is called before the first frame update void Start() { StartCoroutine(Cycle()); } IEnumerator Cycle() { while (true) { yield return new WaitForSeconds(cycleOffset); target.SetActive(!target.activeSelf); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Rectangle { private double side1, side2; public Rectangle() { side1 = 0; side2 = 0; } public Rectangle(double side1, double side2) { this.side1 = side1; this.side2 = side2; } double AreaCalculator() { return side1 * side2; } double Area { get { if (side1 <= 0 | side2 <= 0) { return 1; } else return this.AreaCalculator(); } } double PerimeterCalculator() { return 2 * (side1 + side2); } double Perimeter { get { if (side1 <= 0 | side2 <= 0) { return 1; } else return this.PerimeterCalculator(); } } class Program { static void Main(string[] args) { Console.WriteLine("Enter side 1 and side 2 :"); double side1 = Convert.ToDouble(Console.ReadLine()); double side2 = Convert.ToDouble(Console.ReadLine()); Rectangle rectangle = new Rectangle(side1, side2); if (rectangle.Perimeter!=1 | rectangle.Area!=1) { Console.WriteLine("Perimeter = {0}, Area= {1}", rectangle.Perimeter, rectangle.Area); } else Console.WriteLine("Bad parametres =("); Console.ReadKey(); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class DesignTimeModel : IDesignTimeModel { private readonly IDbContextServices _contextServices; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public DesignTimeModel(IDbContextServices contextServices) { _contextServices = contextServices; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IModel Model => _contextServices.DesignTimeModel; } }
using GistManager.GistService; using GistManager.GistService.Model; using GistManager.Mvvm; using GistManager.Mvvm.Commands.Async; using GistManager.Mvvm.Commands.Async.AsyncCommand; using GistManager.Mvvm.Commands.Async.AsyncRelayCommand; using GistManager.Mvvm.Commands.RelayCommand; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace GistManager.ViewModels { public class GistFileViewModel : BindableBase, IViewModelWithHistory { private readonly IAsyncOperationStatusManager asyncOperationStatusManager; protected IGistClientService GistClientService { get; } public GistFileModel GistFile { get; } public GistViewModel ParentGist { get; } public bool Refreshing { get; set; } #region constructors public GistFileViewModel(IGistClientService gistClientService, IAsyncOperationStatusManager asyncOperationStatusManager, IErrorHandler errorHandler) { GistClientService = gistClientService ?? throw new ArgumentNullException(nameof(gistClientService)); this.asyncOperationStatusManager = asyncOperationStatusManager ?? throw new ArgumentNullException(nameof(asyncOperationStatusManager)); FileNameChangedCommand = new AsyncCommand<string>(RenameGistFileAsync, asyncOperationStatusManager, errorHandler) { ExecutionInfo = "Renaming gist file" }; CheckoutCommand = new AsyncCommand<GistHistoryEntryModel>(RefreshGistFileAsync, asyncOperationStatusManager, errorHandler) { ExecutionInfo = "Checking out file", SuppressCompletionCommand = true }; } public GistFileViewModel(GistViewModel parent, IGistClientService gistClientService, IAsyncOperationStatusManager commandStatusManager, IErrorHandler errorHandler) : this(gistClientService, commandStatusManager,errorHandler) { ParentGist = parent; } public GistFileViewModel(GistFileModel file, GistViewModel parent, IGistClientService gistClientService, IAsyncOperationStatusManager commandStatusManager, IErrorHandler errorHandler) : this(parent, gistClientService, commandStatusManager,errorHandler) { this.GistFile = file; fileName = file.Name; History = new ObservableRangeCollection<GistHistoryEntryViewModel>(); Url = file.Url; DeleteGistFileCommand = new AsyncRelayCommand(DeleteGistFileAsync, commandStatusManager, errorHandler) { ExecutionInfo = "Deleting file from gist" }; CopyGistFileUrlCommand = new RelayCommand(CopyGistFileUrl, errorHandler); } #endregion #region bound properties private string fileName; public string FileName { get { return fileName; } set { var originalFileName = fileName; SetProperty(ref fileName, value); if (!Refreshing && !string.IsNullOrWhiteSpace(originalFileName)) { OnFileNameChangedAsync(originalFileName, fileName); } } } private string content; public string Content { get => content; set { SetProperty(ref content, value); RaisePropertyChanged(nameof(IsEnabled)); } } private bool isSelected; public bool IsSelected { get => isSelected; set => SetProperty(ref isSelected, value); } public string Url { get; } private bool isEnabled = true; public bool IsEnabled { get => isEnabled; set => SetProperty(ref isEnabled, value); } private bool isInEditMode; public bool IsInEditMode { get => isInEditMode; set => SetProperty(ref isInEditMode, value); } public ObservableRangeCollection<GistHistoryEntryViewModel> History { get; set; } #endregion public string Id { get { var data = Url.Split('/'); return data[data.Length - 1]; } } #region commands public ICommand DeleteGistFileCommand { get; } public ICommand CopyGistFileUrlCommand { get; } private AsyncCommand<GistHistoryEntryModel> CheckoutCommand { get; } // HACK: Command should be readonly protected AsyncCommand<string> FileNameChangedCommand { get; set; } #endregion #region command implementation private void CopyGistFileUrl() => Clipboard.SetText(Url); protected async virtual Task OnFileNameChangedAsync(string originalName, string newName) { if (!string.IsNullOrEmpty(originalName) && newName != originalName) await FileNameChangedCommand.ExecuteAsync(newName); } private async Task RenameGistFileAsync(string newName) => await GistClientService.RenameGistFileAsync(ParentGist.Gist.Id, GistFile.Name, newName, Content); private async Task DeleteGistFileAsync() => await GistClientService.DeleteGistFileAsync(ParentGist.Gist.Id, FileName); private async Task RefreshGistFileAsync(GistHistoryEntryModel historyEntry) { var gistVersion = await GistClientService.GetGistVersionAsync(historyEntry.Url); var gistFile = gistVersion.GetFileById(Id); if (gistFile != null) { Content = await GistClientService.GetGistFileContentAsync(gistFile.Url); IsEnabled = true; Refreshing = true; FileName = gistFile.Name; Refreshing = false; } else { IsEnabled = false; } } #endregion public async Task OnHistoryCheckoutAsync(GistHistoryEntryViewModel version) { foreach (var historyEntry in History) { if (historyEntry.Version != version.Version) { historyEntry.IsCheckedOut = false; } } await CheckoutCommand.ExecuteAsync(version.HistoryEntry); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiaxeirisiPoiotitas { class Odigos : Ergazomenos { private string amka; private string name; private string surname; private string oxima; public Odigos(String amka, String name, String surname) : base(amka, name, surname) { this.amka = amka; this.name = name; this.surname = surname; this.Type = "Worker"; } public string Amka { get { return amka; } set { amka = value; } } public string Oxima { get { return oxima; } set { oxima = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Utility; using System.IO; using Model.Properties; using Model.Helper; namespace Model.InvoiceManagement { public class GovPlatformFactory { private static int __InvoiceBusyCount = 0; public static EventHandler SendNotification { get; set; } public static int ResetBusyCount() { Interlocked.Exchange(ref __InvoiceBusyCount, 0); return __InvoiceBusyCount; } private static void notifyToProcess(object stateInfo) { try { InvoiceNotification.ProcessMessage(); } catch (Exception ex) { Logger.Error(ex); } try { using (GovPlatformManager mgr = new GovPlatformManager()) { mgr.TransmitInvoice(); mgr.ExecuteCommand(@" INSERT INTO DocumentDispatch (DocID, TypeID) SELECT DocID, DocType FROM CDS_Document AS c WHERE (CurrentStep IS NULL) AND (DocDate >= {0}) AND (NOT EXISTS (SELECT NULL FROM DocumentDispatch WHERE (DocID = c.DocID) AND (TypeID = c.DocType)))",DateTime.Today.AddDays(-1)); } } catch (Exception ex) { Logger.Error(ex); } } private static void checkResponse(object stateInfo) { try { using (GovPlatformManager mgr = new GovPlatformManager()) { mgr.CheckResponse(); } } catch (Exception ex) { Logger.Error(ex); } } } }
using System; using System.Collections.Generic; using Templates.Framework; namespace Templates { public class TemplateFunction : IFunction { protected ICodeBlock codeBlock; protected IList<IConstructor> constructors; protected string indent; protected bool isCommentedOut; protected bool isNew; protected string name; protected Overridability overridability; protected IList<IVariable> parameters; protected Privacy privacy; protected IVariableType returnType; protected string signature; protected string sortBy; protected string summary; protected IList<ITag> tags; public ICodeBlock CodeBlock { get { return this.codeBlock; } } public IList<IConstructor> Constructors { get { return this.constructors; } set { this.constructors = value; } } public string Indent { get { return this.indent; } set { this.indent = value; } } public bool IsCommentedOut { get { return this.isCommentedOut; } set { this.isCommentedOut = value; } } public bool IsNew { get { return this.isNew; } set { this.isNew = value; } } public string Name { get { return this.name; } } public Overridability Overridability { get { return this.overridability; } } public IList<IVariable> Parameters { get { return this.parameters; } } public Privacy Privacy { get { return this.privacy; } } public IVariableType ReturnType { get { return this.returnType; } } public string Summary { get { return this.summary; } set { this.summary = value; } } public IList<ITag> Tags { get { return this.tags; } } public string Signature { get { if (string.IsNullOrWhiteSpace(this.signature)) { this.signature = this.returnType + " " + this.name + "("; for (int i = 0; i < this.parameters.Count; i++) { if (i > 0) this.signature += ", "; this.signature += this.parameters[i].VariableType + " " + this.parameters[i].InstanceName; } this.signature += ")"; } return this.signature; } } public string SortBy { get { if (string.IsNullOrWhiteSpace(this.sortBy)) { this.sortBy = this.name + ": "; for (int i = 0; i < this.parameters.Count; i++) { if (i > 0) this.sortBy += ", "; this.sortBy += this.parameters[i].VariableType.Name + " " + this.parameters[i].InstanceName; } } return this.sortBy; } } public TemplateFunction(Privacy privacy, string returnType, string name) : this(privacy, Overridability.None, new TemplateVariableType(returnType), name, new List<IVariable>()) { } public TemplateFunction(Privacy privacy, IVariableType returnType, string name) : this(privacy, Overridability.None, returnType, name, new List<IVariable>()) { } public TemplateFunction(Privacy privacy, string returnType, string name, IList<IVariable> parameters) : this(privacy, Overridability.None, new TemplateVariableType(returnType), name, parameters) { } public TemplateFunction(Privacy privacy, IVariableType returnType, string name, IList<IVariable> parameters) : this(privacy, Overridability.None, returnType, name, parameters) { } public TemplateFunction(Privacy privacy, Overridability overridability, string returnType, string name) : this(privacy, overridability, new TemplateVariableType(returnType), name, new List<IVariable>()) { } public TemplateFunction(Privacy privacy, Overridability overridability, IVariableType returnType, string name) : this(privacy, overridability, returnType, name, new List<IVariable>()) { } public TemplateFunction(Privacy privacy, Overridability overridability, string returnType, string name, IList<IVariable> parameters) : this(privacy, overridability, new TemplateVariableType(returnType), name, parameters) { } public TemplateFunction(Privacy privacy, Overridability overridability, IVariableType returnType, string name, IList<IVariable> parameters) { this.overridability = overridability; this.name = name; this.parameters = parameters; this.privacy = privacy; this.returnType = returnType; this.codeBlock = new TemplateCodeBlock(); this.indent = "\t"; this.tags = new List<ITag>(); } public void Add() { this.codeBlock.Add(string.Empty); } public void Add(string code) { this.codeBlock.Add(code); } public void Tag(string tag) { this.tags.Add(new TemplateTag(tag)); } public virtual IList<ILine> ToLines() { IList<ILine> functionLines = new List<ILine>(); foreach (ITag tag in this.tags) functionLines.Add(new TemplateLine(tag)); string temp = string.Empty; if (this.privacy == Privacy.Public) temp += "public"; else if (this.privacy == Privacy.Protected) temp += "protected"; else if (this.privacy == Privacy.Private) temp += "private"; if (this.isNew) temp += " new"; if (this.overridability != Overridability.None) { temp += " "; if (this.overridability == Overridability.Overridable) temp += "virtual"; else if (this.overridability == Overridability.Overriding) temp += "override"; else temp += "static"; } temp += " " + Signature; string prefix = this.isCommentedOut ? "//" : string.Empty; functionLines.Add(new TemplateLine(prefix + temp)); functionLines.Add(new TemplateLine(prefix + "{")); foreach (ILine line in this.codeBlock.Lines) functionLines.Add(new TemplateLine(prefix + this.indent + line.Code)); functionLines.Add(new TemplateLine(prefix + "}")); return functionLines; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using BookStore.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BookStore.Model; namespace BookStore.DAL.Tests { [TestClass()] public class UserDALTests { UserDAL userDAL = new UserDAL(); [TestMethod()] public void AddUserTest() { User user = new User(0, Name: "赵六", Password: "123", Email: "zl@qq.com", No: "100200", Birthday: new DateTime(), IsDel: false, Type: 1); Assert.AreEqual(1, userDAL.AddUser(user)); } [TestMethod()] public void UpdateUserTest() { //Assert.Fail(); //李员工 123456 li_sir@qq.com 100002 1996-12-13 0 1 User user = new User(2, Name: "李员工", Password: "12345", Email: "li_sir@qq.com", No: "100002", Birthday: new DateTime(), IsDel: false, Type: 1); //(0, Name: "赵六", Password: "123", //Email: "zl@qq.com", No: "100200", //Birthday: new DateTime(), IsDel: false, Type: 1); Assert.AreEqual(1, userDAL.UpdateUser(user)); } [TestMethod()] public void SoftDeleteTest() { int flag = userDAL.SoftDelete("1100001"); Assert.AreEqual(0, flag); // Assert.Fail(); } [TestMethod()] public void RealDeleteTest() { int flag = userDAL.SoftDelete("1100001"); Assert.AreEqual(0, flag); } [TestMethod()] public void DeletesTest() { //Assert.Fail(); int flag = userDAL.Deletes("1"); Assert.AreEqual(0, flag); } [TestMethod()] public void GetAllUsersTest() { List<User> users = userDAL.GetAllUsers(); Assert.AreEqual(10, users.Count); } [TestMethod()] public void UpdatePwdTest() { int flag = userDAL.UpdatePwd("王五", "111"); Assert.AreEqual(1, flag); //Assert.Fail(); } [TestMethod()] public void GetUserByLoginNameTest() { //Assert.Fail(); User user = userDAL.GetUserByLoginName("李欣", 1); Assert.IsNotNull(user); } [TestMethod()] public void GetUserByLoginNameAndPasswordTest() { User user = userDAL.GetUserByLoginNameAndPassword("李欣", "111"); Assert.IsNotNull(user); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; ////////////////////////////////////////////////////////////////// //Created by: Daniel McCluskey //Project: CT6024 - AI //Repo: https://github.com/danielmccluskey/CT6024-AI //Script Purpose: Script to turn on Radio to distract enemies near intel ////////////////////////////////////////////////////////////////// public class CS_SpyTurnOnRadioIntelAction : CS_GOAPAction { private bool m_bRequiresInRange = true; private bool m_bGuardDistracted = false; public CS_SpyTurnOnRadioIntelAction() { AddEffect("intelClearOfEnemies", true); // m_fCost = 1.0f; } public override void ResetGA() { //m_bGuardDistracted = false; m_goTarget = null; } public override bool IsActionFinished() { return m_bGuardDistracted; } public override bool NeedsToBeInRange() { return m_bRequiresInRange; } public override bool CheckPreCondition(GameObject agent) { CS_RadioComponent[] goDistractingObjects = (CS_RadioComponent[])UnityEngine.GameObject.FindObjectsOfType(typeof(CS_RadioComponent)); CS_RadioComponent goClosestDistraction = null; CS_IntelComponent cIntel = GameObject.FindObjectOfType<CS_IntelComponent>(); if (cIntel == null) { return false; } float fDistanceToDistraction = 0; foreach (CS_RadioComponent distraction in goDistractingObjects) { if (goClosestDistraction == null) { // first one, so choose it for now goClosestDistraction = distraction; fDistanceToDistraction = (distraction.gameObject.transform.position - cIntel.transform.position).magnitude; } else { // is this one closer than the last? float dist = (distraction.gameObject.transform.position - cIntel.transform.position).magnitude; if (dist < fDistanceToDistraction) { // we found a closer one, use it goClosestDistraction = distraction; fDistanceToDistraction = dist; } } } if (goClosestDistraction == null) { return false; } m_goTarget = goClosestDistraction.gameObject; if (m_goTarget != null) { return true; } return false; } public override bool PerformAction(GameObject agent) { m_bGuardDistracted = true; m_goTarget.GetComponent<CS_Radio>().SetRadioStatus(true); GameObject.FindObjectOfType<CS_Spy>().SetHide(true); return false; } }
// <copyright file="Query.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace Library.Models { /// <summary> /// /// </summary> public class Query { /// <summary> /// /// </summary> public int Page { get; protected set; } /// <summary> /// /// </summary> public int ItemsPerPage { get; protected set; } /// <summary> /// /// </summary> /// <param name="page"></param> /// <param name="itemsPerPage"></param> public Query(int page, int itemsPerPage) { Page = page; ItemsPerPage = itemsPerPage; if (Page <= 0) { Page = 1; } if (ItemsPerPage <= 0) { ItemsPerPage = 10; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConfigControlBuilderFactory.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.GUI.Configuration { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Soloplan.WhatsON.Configuration; public sealed class ConfigControlBuilderFactory { /// <summary> /// Singleton instance. /// </summary> private static volatile ConfigControlBuilderFactory instance; /// <summary> /// Caches control builders that should be used by a given type. /// </summary> private readonly IList<KeyValuePair<Type, IConfigControlBuilder>> controlBuilderByType = new List<KeyValuePair<Type, IConfigControlBuilder>>(); /// <summary> /// Indicates whether this control builder factory is already configured or not. /// </summary> private bool isConfigured; /// <summary> /// Gets the singleton instance. /// </summary> /// <remarks> /// Getter of this property is thread-safe. /// </remarks> public static ConfigControlBuilderFactory Instance { [MethodImpl(MethodImplOptions.Synchronized)] get => instance ?? (instance = new ConfigControlBuilderFactory()); } /// <summary> /// Registers the specified <paramref name="controlBuilder"/>for the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for which to use the specified controlBuilder.</param> /// <param name="controlBuilder">The control builder to use with <paramref name="type"/>.</param> public void RegisterControlBuilder(Type type, IConfigControlBuilder controlBuilder) { this.controlBuilderByType.Add(new KeyValuePair<Type, IConfigControlBuilder>(type, controlBuilder)); } /// <summary> /// Gets the control builder for the specified <paramref name="type" />. /// </summary> /// <param name="type">The type to get the control builder.</param> /// <param name="configurationItemKey">The configuration item key.</param> /// <returns> /// The control builder for this type or null if not found. /// </returns> internal IConfigControlBuilder GetControlBuilder(Type type, string configurationItemKey) { this.CheckConfiguration(); var builder = this.controlBuilderByType.FirstOrDefault(b => b.Key == type && b.Value.SupportedConfigurationItemsKey == configurationItemKey); if (builder.Key == null) { builder = this.controlBuilderByType.FirstOrDefault(b => b.Key == type); } return builder.Key != null ? builder.Value : null; } /// <summary> /// Registers control builders for specific types. /// </summary> private void RegisterBuiltInTypeSpecificControlBuilders() { this.RegisterControlBuilder(typeof(string), new TextConfigControlBuilder()); this.RegisterControlBuilder(typeof(int), new NumericConfigControlBuilder()); this.RegisterControlBuilder(typeof(string), new CategoryComboBoxConfigControlBuilder()); this.RegisterControlBuilder(typeof(bool), new CheckBoxConfigControlBuilder()); this.RegisterControlBuilder(typeof(ConnectorNotificationConfiguration), new NotificationSettingsControlBuilder()); } /// <summary> /// Checks whether this control builder factory is already configured. /// </summary> private void CheckConfiguration() { if (!this.isConfigured) { this.RegisterBuiltInTypeSpecificControlBuilders(); this.isConfigured = true; } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PSA; using System.Net.Http; using System.Threading.Tasks; namespace PageSpeedInsight.Tests { [TestClass] public class UnitTest1 { PageSpeedCore ps = new PageSpeedCore(); string inputUrl1 = "http://www.carchat24.com"; [TestMethod] public void FetURL_NotValid() { //var response = ps.FetchURL(""); var res = ps.FetchURL("URL is not valid."); Assert.AreEqual("URL is not valid.", res); } [TestMethod] public void FetURL() { var response = ps.FetchURL(inputUrl1); Assert.AreEqual("Lots of string", response.ToString()); } [TestMethod] public void ValidURL() { bool isValidURL = ps.IsValidURL(inputUrl1); Assert.AreEqual(true, isValidURL); } [TestMethod] public void ValidURL_WithWrongStringInput() { bool isValidURL = ps.IsValidURL(inputUrl1); Assert.AreNotEqual(false, isValidURL); } [TestMethod] public void Test_ExtractDomainName() { string rawURL = "http://www.carchat24.com/about"; string expectedURL = "http://www.carchat24.com"; string result = ps.ExtractDomainFromURL(rawURL); Assert.AreEqual(expectedURL, result); } [TestMethod] public void Test_ExtractDomainName_WithPathAndQuery() { string rawURL = "http://www.carchat24.com"; string expectedURL = "http://www.carchat24.com"; string result = ps.ExtractDomainFromURL(rawURL); Assert.AreEqual(expectedURL, result); } } }
using System; using System.Collections.Generic; using System.Text; namespace RFID_Inventarization { internal class Level3 { public string id; public string parent; public string title; public Level3(string title, string id, string parent) { this.title = title; this.id = id; this.parent = parent; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KPI.Model.ViewModel { public class ToDoList { public int ID { get; set; } public int UserID { get; set; } public int DataID { get; set; } public int CommentID { get; set; } public string Title { get; set; } public string KPILevelCodeAndPeriod { get; set; } public string Description { get; set; } public string Content { get; set; } public int ApprovedBy { get; set; } private DateTime? createTime = null; public DateTime CreateTime { get { return this.createTime.HasValue ? this.createTime.Value : DateTime.Now; } set { this.createTime = value; } } public DateTime Deadline { get; set; } public DateTime SubmitDate { get; set; } public bool Status { get; set; } public bool ApprovedStatus { get; set; } public int ActionPlanCategoryID { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AchievementPanel : MonoBehaviour { public GameObject openButton; public GameObject closeButton; public GameObject achievementPrefab; public Transform achievementContainer; private AchievementDatabase databaseScript; private List<Achievement> database; private List<GameObject> achievementUI = new List<GameObject>(); private PlayerController playerController; private void Start() { databaseScript = FindObjectOfType<AchievementDatabase>(); database = databaseScript.achievementDatabase; playerController = FindObjectOfType<PlayerController>(); gameObject.SetActive(false); closeButton.SetActive(false); openButton.SetActive(true); CreateList(); UpdateList(); } public void OpenPanel() { gameObject.SetActive(true); openButton.SetActive(false); closeButton.SetActive(true); if (playerController) { playerController.ControlSwitch(true); } } public void ClosePanel() { gameObject.SetActive(false); closeButton.SetActive(false); openButton.SetActive(true); if (playerController) { playerController.ControlSwitch(false); } } private void CreateList() { Vector2 containerSize = achievementContainer.GetComponent<RectTransform>().sizeDelta; float padding = -Screen.height * 0.05f; for (int i = 0; i < database.Count; i++) { GameObject go = Instantiate(achievementPrefab); go.transform.SetParent(achievementContainer, false); go.GetComponent<RectTransform>().position = new Vector3(achievementContainer.position.x, achievementContainer.position.y + padding, 0); go.transform.GetChild(0).GetComponent<Image>().sprite = database[i].Sprite; achievementUI.Add(go); padding -= Screen.height * 0.25f; } } public void UpdateList() { for (int i = 0; i < achievementUI.Count; i++) { if(database[i].isUnlocked == true) { achievementUI[i].transform.GetChild(0).gameObject.SetActive(true); achievementUI[i].transform.GetChild(1).gameObject.SetActive(false); } else if (database[i].isUnlocked == false) { achievementUI[i].transform.GetChild(0).gameObject.SetActive(false); achievementUI[i].transform.GetChild(1).gameObject.SetActive(true); } } } }
using System; using System.Collections.Generic; using System.Text; namespace ConsultingManager.Dto { public class StartCustomerProcessDto { public Guid modelProcessId { get; set; } public string modelProcessDescription { get; set; } public Guid customerId { get; set; } public Guid consultantId { get; set; } public Guid customerUserId { get; set; } public DateTime startDate { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; namespace NuGet.Frameworks { /// <summary> /// Sorts NuGet Frameworks in a consistent way for package readers. /// The order is not particularly useful here beyond making things deterministic /// since it compares completely different frameworks. /// </summary> public class NuGetFrameworkSorter : IComparer<NuGetFramework> { public NuGetFrameworkSorter() { } public int Compare(NuGetFramework x, NuGetFramework y) { if (ReferenceEquals(x, y)) { return 0; } if (ReferenceEquals(x, null)) { return -1; } if (ReferenceEquals(y, null)) { return 1; } // Any goes first if (x.IsAny && !y.IsAny) { return -1; } if (!x.IsAny && y.IsAny) { return 1; } // Unsupported goes last if (x.IsUnsupported && !y.IsUnsupported) { return 1; } if (!x.IsUnsupported && y.IsUnsupported) { return -1; } // Compare on Framework, Version, Profile, Platform, and PlatformVersion var result = StringComparer.OrdinalIgnoreCase.Compare(x.Framework, y.Framework); if (result != 0) { return result; } result = x.Version.CompareTo(y.Version); if (result != 0) { return result; } result = StringComparer.OrdinalIgnoreCase.Compare(x.Profile, y.Profile); if (result != 0) { return result; } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLayer.Facturacion { public class FacturacionData : DataBase { #region Constructores public FacturacionData(Conexion.DAOFactory factory) : base(factory) { } #endregion public void BuscarCliente() { ConsultarGenerico(Constantes.sp_Fac_Buscar_Cliente); } public void ConsultarCatalogo() { ConsultarGenerico(Constantes.sp_Fac_Consultar_Catalogo); } public void ConsultarSucursal() { ConsultarGenerico(Constantes.sp_Fac_Consultar_Sucursal); } public void ConsultarTicket() { ConsultarGenerico(Constantes.sp_Fac_Consultar_Ticket); } public void ValidaTicketComprobante() { ConsultarGenerico(Constantes.sp_Fac_Valida_Ticket_Comprobante); } /// <summary> /// Consulta la información necesaria para generar el comprobante y mandarlo a timbrar. /// </summary> public void GeneraDatosParaTimbrar() { CrearParametroExito(); ConsultarGenerico(Constantes.sp_Fac_CalculaImpuestosArticulo); } /// <summary> /// Guarda un nuevo comprobante. /// </summary> public void GuardarComprobante() { CrearParametroExito(); EjecutarGenerico(Constantes.sp_Fac_GuardaComprobante); } public void DesActivarCliente() { ConsultarGenerico(Constantes.sp_Fac_DesActivar_Cliente); } public void GuardaCliente() { ConsultarGenerico(Constantes.sp_Fac_Guarda_Cliente); } public void BuscarComprobante() { ConsultarGenerico(Constantes.sp_Fac_Buscar_Comprobante); } /// <summary> /// Guarda o actualiza los binarios correspondientes al comprobante. /// </summary> public void GuardaActualizaBinariosComprobante() { CrearParametroExito(); EjecutarGenerico(Constantes.sp_Fac_GuardaBinariosComprobante); } /// <summary> /// Verifica que el usuario y la contraseña proporcioados en el login, existan en la BD, de existir y estar correcto, devuelve los accesos del usuario correspondiente. /// </summary> public void IntentoLoguear() { CrearParametroExito(); CrearParametroExiste(); ConsultarGenerico(Constantes.sp_Seg_VerificaUsuario); } /// <summary> /// Cancela un comprobante /// </summary> public void CancelarComprobante() { CrearParametroExito(); EjecutarGenerico(Constantes.sp_Fac_CancelaComprobante); } /// <summary> /// Guarda en bitácora de la BD /// </summary> public void GuardaBitacora() { //CrearParametroExito(); EjecutarGenerico(Constantes.sp_Uti_RegistraBitacora); } } }
using System; using System.Web; using System.Xml; using umbraco; using umbraco.BasePages; using umbraco.BusinessLogic; using spa = umbraco.cms.businesslogic.packager.standardPackageActions; using umbraco.interfaces; namespace PackageActionsContrib { /// <summary> /// This Package action will Add a new Mime Type to the web.config file /// </summary> /// <remarks> /// This package action is part of the PackageActionsContrib Project /// </remarks> public class AddMimeType : IPackageAction { //Set the web.config full path const string FULL_PATH = "/web.config"; #region IPackageAction Members /// <summary> /// This Alias must be unique and is used as an identifier that must match /// the alias in the package action XML /// </summary> /// <returns>The Alias in string format</returns> public string Alias() { return "AddMimeType"; } /// <summary> /// Append the xmlData node to the web.config file /// </summary> /// <param name="packageName">Name of the package that we install</param> /// <param name="xmlData">The data that must be appended to the web.config file</param> /// <returns>True when succeeded</returns> public bool Execute(string packageName, XmlNode xmlData) { //Set result default to false bool result = false; //Get attribute values of xmlData string position, extension, mimetype; position = getAttributeDefault(xmlData, "position", null); if (!getAttribute(xmlData, "extension", out extension)) return result; if (!getAttribute(xmlData, "mimetype", out mimetype)) return result; //Create a new xml document XmlDocument document = new XmlDocument(); //Keep current indentions format document.PreserveWhitespace = true; //Load the web.config file into the xml document document.Load(HttpContext.Current.Server.MapPath(FULL_PATH)); //Select root node in the web.config file for insert new nodes XmlNode rootNode = document.SelectSingleNode("//configuration/system.webServer"); //Check for rootNode exists if (rootNode == null) return result; //Set modified document default to false bool modified = false; //Set insert node default true bool insertNode = true; //Check for staticContent node if (rootNode.SelectSingleNode("staticContent") != null) { //Replace root node rootNode = rootNode.SelectSingleNode("staticContent"); //Look for existing nodes with same path like the new node if (rootNode.HasChildNodes) { //Look for existing nodeType nodes XmlNode node = rootNode.SelectSingleNode( String.Format("//mimeMap[@fileExtension = '{0}' and @mimeType = '{1}']", extension, mimetype)); //If path already exists if (node != null) { //Cancel insert node operation insertNode = false; } } } else { //Create staticContent node var staticContentNode = document.CreateElement("staticContent"); rootNode.AppendChild(staticContentNode); //Replace root node rootNode = staticContentNode; //Mark document modified modified = true; } //Check for insert flag if (insertNode) { //Create new node with attributes XmlNode newNode = document.CreateElement("mimeMap"); newNode.Attributes.Append( xmlHelper.addAttribute(document, "fileExtension", extension)); newNode.Attributes.Append( xmlHelper.addAttribute(document, "mimeType", mimetype)); //Select for new node insert position if (position == null || position == "end") { //Append new node at the end of root node rootNode.AppendChild(newNode); //Mark document modified modified = true; } else if (position == "beginning") { //Prepend new node at the beginnig of root node rootNode.PrependChild(newNode); //Mark document modified modified = true; } } //Check for modified document if (modified) { try { //Save the Rewrite config file with the new rewerite rule document.Save(HttpContext.Current.Server.MapPath(FULL_PATH)); //No errors so the result is true result = true; } catch (Exception e) { //Log error message string message = "Error at execute AddMimeType package action: " + e.Message; Log.Add(LogTypes.Error, getUser(), -1, message); } } return result; } /// <summary> /// Removes the xmlData node from the web.config file /// </summary> /// <param name="packageName">Name of the package that we install</param> /// <param name="xmlData">The data that must be appended to the web.config file</param> /// <returns>True when succeeded</returns> public bool Undo(string packageName, System.Xml.XmlNode xmlData) { //Set result default to false bool result = false; //Get attribute values of xmlData string extension, mimetype; if (!getAttribute(xmlData, "extension", out extension)) return result; if (!getAttribute(xmlData, "mimetype", out mimetype)) return result; //Create a new xml document XmlDocument document = new XmlDocument(); //Keep current indentions format document.PreserveWhitespace = true; //Load the web.config file into the xml document document.Load(HttpContext.Current.Server.MapPath(FULL_PATH)); //Select root node in the web.config file for insert new nodes XmlNode rootNode = document.SelectSingleNode("//configuration/system.webServer/staticContent"); //Check for rootNode exists if (rootNode == null) return result; //Set modified document default to false bool modified = false; //Look for existing nodes with same path of undo attribute if (rootNode.HasChildNodes) { //Look for existing add nodes with attribute path foreach (XmlNode existingNode in rootNode.SelectNodes( String.Format("//mimeMap[@fileExtension = '{0}' and @mimeType = '{1}']", extension, mimetype))) { //Remove existing node from root node rootNode.RemoveChild(existingNode); modified = true; } } if (modified) { try { //Save the Rewrite config file with the new rewerite rule document.Save(HttpContext.Current.Server.MapPath(FULL_PATH)); //No errors so the result is true result = true; } catch (Exception e) { //Log error message string message = "Error at undo AddMimeType package action: " + e.Message; Log.Add(LogTypes.Error, getUser(), -1, message); } } return result; } /// <summary> /// Get the current user, or when unavailable admin user /// </summary> /// <returns>The current user</returns> private User getUser() { int id = BasePage.GetUserId(BasePage.umbracoUserContextID); id = (id < 0) ? 0 : id; return User.GetUser(id); } /// <summary> /// Get a named attribute from xmlData root node /// </summary> /// <param name="xmlData">The data that must be appended to the web.config file</param> /// <param name="attribute">The name of the attribute</param> /// <param name="value">returns the attribute value from xmlData</param> /// <returns>True, when attribute value available</returns> private bool getAttribute(XmlNode xmlData, string attribute, out string value) { //Set result default to false bool result = false; //Out params must be assigned value = String.Empty; //Search xml attribute XmlAttribute xmlAttribute = xmlData.Attributes[attribute]; //When xml attribute exists if (xmlAttribute != null) { //Get xml attribute value value = xmlAttribute.Value; //Set result successful to true result = true; } else { //Log error message string message = "Error at AddMimeType package action: " + "Attribute \"" + attribute + "\" not found."; Log.Add(LogTypes.Error, getUser(), -1, message); } return result; } /// <summary> /// Get an optional named attribute from xmlData root node /// when attribute is unavailable, return the default value /// </summary> /// <param name="xmlData">The data that must be appended to the web.config file</param> /// <param name="attribute">The name of the attribute</param> /// <param name="defaultValue">The default value</param> /// <returns>The attribute value or the default value</returns> private string getAttributeDefault(XmlNode xmlData, string attribute, string defaultValue) { //Set result default value string result = defaultValue; //Search xml attribute XmlAttribute xmlAttribute = xmlData.Attributes[attribute]; //When xml attribute exists if (xmlAttribute != null) { //Get available xml attribute value result = xmlAttribute.Value; } return result; } /// <summary> /// Returns a Sample XML Node /// In this case the Sample HTTP Module TimingModule /// </summary> /// <returns>The sample xml as node</returns> public XmlNode SampleXml() { return spa.helper.parseStringToXmlNode( "<Action runat=\"install\" undo=\"true/false\" alias=\"AddMimeType\" " + "position=\"beginning/end\" " + "extension=\".txt\" " + "mimetype=\"text/plain\" />" ); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.ExploringCards.Collection { public class ExploringCard_TheresSomethingInTheAir : ICard, IExploringCard { private int eventNumber = 0; public void ExecuteEvent() { if (eventNumber == 0) { ExecuteActiveThreat(); eventNumber++; } else { ExecuteFutureThreat(); } } private void ExecuteFutureThreat() { ExploringCard_Deck.GlobalSetQuestionMarkOnDeck(); } private void ExecuteActiveThreat() { ExploringCard_Deck.GlobalSetQuestionMarkOnDeck(); } public string GetCardDescription() { if (eventNumber == 0) { return "Ein grünes Fragezeichen wird zusätzlich platziert."; } else { return "Ein grünes Fragezeichen wird zusätzlich platziert.\r\n Eine neue Karte wird gezogen."; } } public int GetMaterialNumber() { return 19; } public bool HasDiscardOption() { return false; } public override string ToString() { return "There's something in the Air"; } } }
using mTransport.Methodes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mTransport.Models { public partial class Materiel : ICRUD { public void Delete() { //using (DB db = new DB()) //{ // var d = db.Materiels.SingleOrDefault(i => i.Id == Id); // if (d != null) // { // db.Materiels.Remove(d); // db.SaveChanges(); // } //} } public void Insert() { using (DB db = new DB()) { db.Materiels.Add(this); db.SaveChanges(); } } public void Update() { using (DB db = new DB()) { db.Entry(this).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } } //Méthode ne necessitant pas la création d'un objet est a déclarée static public static List<Materiel> getAll() { using (DB db = new DB()) { var l = db.Materiels.Where(i => i.Supprime == false).ToList(); return l; } } public static Materiel getMateriel(int Id) { using (DB db = new DB()) { Materiel c = new Materiel(); c = db.Materiels.SingleOrDefault(i => i.Id == Id); return c; } } } }
using System.Web.UI; namespace OdeToFood.Account { public partial class ResetPasswordConfirmation : Page { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Scriptables/CarLogic")] public class SOCarLogic : ScriptableObject { public SOCarLogic Ref { get; private set; } public CarTurn CarTurnRef { get; private set; } public CarLateralMovement CarMoveRef { get; private set; } public void CreateRunTimeObject(CarTurn val1, CarLateralMovement val2) { Ref = ScriptableObject.CreateInstance<SOCarLogic>(); Ref.SetValue(val1 , val2); } public void SetValue(CarTurn val1, CarLateralMovement val2) { CarTurnRef = val1; CarMoveRef = val2; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIManager : MonoBehaviour { [SerializeField] private Sprite[] livesImages; [SerializeField] private Image playerLivesImage; [SerializeField] private Text playerScore; public int score = 0; public void updateLives(int currentLives) { playerLivesImage.sprite = livesImages[currentLives]; } public void updateScore() { score = score + 10; playerScore.text = "Score:" + score; } public void resetScore() { score = 0; playerScore.text = "Score:" + score; } }
/// <summary> /// Scribble.rs Pad namespace /// </summary> namespace ScribblersPad { /// <summary> /// Main menu UI layout enumerator /// </summary> public enum EMainMenuUILayoutState { /// <summary> /// Nothing /// </summary> Nothing, /// <summary> /// Main menu UI layout state /// </summary> Main, /// <summary> /// Play menu UI layout state /// </summary> Play, /// <summary> /// Lobby settings menu UI layout state /// </summary> LobbySettings, /// <summary> /// Lobby list menu UI layout state /// </summary> LobbyList } }
 namespace Medit1.Models { public class CruiseCommodite { public int CruiseId { get; set; } public Cruise Cruise { get; set; } public int CommoditeId { get; set; } public Commodite Commodite { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.Shape { public struct Size { public Size(float width, float height) : this() { this.Width = width; this.Height = height; } public float Width { get; set; } public float Height { get; set; } public override string ToString() { return this.Width + " / " + this.Height; } public override bool Equals(object obj) { if (obj == null || !(obj is Size)) { return false; } var size = ((Size)obj); return size.Width == Width && size.Height == Height; } public override int GetHashCode() { return this.Width.GetHashCode() ^ this.Height.GetHashCode(); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Project.Domain.AggregatesModel; namespace Project.Infrastructure.EntityConfigurations { public class ProjectViewerConfig : IEntityTypeConfiguration<ProjectViewer> { public void Configure(EntityTypeBuilder<ProjectViewer> builder) { builder.ToTable("ProjectViewers").HasKey(x => x.Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace treatment.Models { public class TreatmentHistory { public string ClinicName { get; set; } public string DeseaseName { get; set; } public string Observation { set; get; } public string Date { set; get; } public string VoterNumber { set; get; } } }
using System; using System.Data; using MySql.Data.MySqlClient; namespace Nou { public partial class Register : System.Web.UI.Page { MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=web;User Id=root;password=''"); private Boolean existsUser(String username) { MySqlCommand cmd = new MySqlCommand("Select Count(*) from users where username ='" + username + "'", con); MySqlDataReader sReader = null; Int32 numberOfRows = 0; try { con.Open(); sReader = cmd.ExecuteReader(); while (sReader.Read()) { if (!(sReader.IsDBNull(0))) { numberOfRows = Convert.ToInt32(sReader[0]); if (numberOfRows > 0) { return true; } } } } catch (Exception ex) { throw ex; } finally { con.Close(); } return false; } protected void registerBtn(object sneder, EventArgs e) { String nameV = text1.Text; String passV = text2.Text; if (existsUser(nameV)) { Label2.Text = "This username already exist!"; //Response.Redirect("Register.aspx"); text1.Text = string.Empty; text2.Text = string.Empty; return; } con.Open(); MySqlCommand cmd2 = con.CreateCommand(); cmd2.CommandType = CommandType.Text; cmd2.Parameters.AddWithValue("@name", nameV); cmd2.Parameters.AddWithValue("@pass", passV); String sql = "insert into users (username, password) values(@name, @pass)"; cmd2.CommandText = sql; cmd2.ExecuteNonQuery(); text1.Text = string.Empty; text2.Text = string.Empty; con.Close(); Label2.Text = "Registered succesfuly!"; //Response.Redirect("Default.aspx"); } } }
using HCL.Academy.DAL; using HCL.Academy.Model; using HCLAcademy.Util; using System; using System.Collections.Generic; using System.Web.Http; using Microsoft.ApplicationInsights; using System.Diagnostics; namespace HCL.Academy.Service.Controllers { /// <summary> /// This service exposes all the methods related to Skill Competency Levels. /// </summary> //[EnableCors(origins: "https://hclacademyhubnew.azurewebsites.net", headers: "*", methods: "*")] public class SkillCompetencyLevelController : ApiController { /// <summary> /// This method gets all the Skill Competency Levels /// </summary> /// <param name="request"></param> /// <returns></returns> [Authorize] [HttpPost] [ActionName("GetSkillCompetencyLevels")] public List<SkillCompetencyLevel> GetSkillCompetencyLevels(RequestBase request) { List<SkillCompetencyLevel> response = new List<SkillCompetencyLevel>(); try { SqlSvrDAL dal = new SqlSvrDAL(request.ClientInfo); response = dal.GetSkillCompetencyLevels(); } catch (Exception ex) { //LogHelper.AddLog("SkillCompetencyLevelController,GetSkillCompetencyLevels", ex.Message, ex.StackTrace, "HCL.Academy.Service", request.ClientInfo.emailId); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } return response; } /// <summary> /// This method adds a skill competency level. /// </summary> /// <param name="skillCompetencyLevel"></param> /// <returns></returns> [Authorize] [HttpPost] [ActionName("AddSkillCompetencyLevel")] public bool AddSkillCompetencyLevel(SkillCompetencyLevelRequest skillCompetencyLevel) { bool response = false; try { SqlSvrDAL dal = new SqlSvrDAL(skillCompetencyLevel.ClientInfo); response = dal.AddSkillCompetencyLevel(skillCompetencyLevel.SkillID, skillCompetencyLevel.CompetencyID, skillCompetencyLevel.Description, skillCompetencyLevel.ProfessionalSkills, skillCompetencyLevel.SoftSkills, skillCompetencyLevel.CompetencyLevelOrder, skillCompetencyLevel.TrainingCompletionPoints, skillCompetencyLevel.AssessmentCompletionPoints); } catch (Exception ex) { // LogHelper.AddLog("SkillCompetencyLevelController,AddSkillCompetencyLevel", ex.Message, ex.StackTrace, "HCL.Academy.Service", skillCompetencyLevel.ClientInfo.emailId); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } return response; } /// <summary> /// Updates the desired skill competency level. /// </summary> /// <param name="skillCompetencyLevel"></param> /// <returns></returns> [Authorize] [HttpPost] [ActionName("UpdateSkillCompetencyLevel")] public bool UpdateSkillCompetencyLevel(SkillCompetencyLevelRequest skillCompetencyLevel) { bool response = false; try { SqlSvrDAL dal = new SqlSvrDAL(skillCompetencyLevel.ClientInfo); response = dal.UpdateSkillCompetencyLevel(skillCompetencyLevel.ItemID,skillCompetencyLevel.SkillID, skillCompetencyLevel.CompetencyID, skillCompetencyLevel.Description, skillCompetencyLevel.ProfessionalSkills, skillCompetencyLevel.SoftSkills, skillCompetencyLevel.CompetencyLevelOrder, skillCompetencyLevel.TrainingCompletionPoints, skillCompetencyLevel.AssessmentCompletionPoints); } catch (Exception ex) { //LogHelper.AddLog("SkillCompetencyLevelController,UpdateSkillCompetencyLevel", ex.Message, ex.StackTrace, "HCL.Academy.Service", skillCompetencyLevel.ClientInfo.emailId); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } return response; } /// <summary> /// This method removes the selected skill competency level /// </summary> /// <param name="req"></param> /// <param name="itemId"></param> /// <returns></returns> [Authorize] [HttpPost] [ActionName("RemoveSkillCompetencyLevel")] public bool RemoveSkillCompetencyLevel(RequestBase req,int itemId) { bool response = false; try { SqlSvrDAL dal = new SqlSvrDAL(req.ClientInfo); response = dal.RemoveSkillCompetencyLevel(itemId); } catch (Exception ex) { //LogHelper.AddLog("SkillCompetencyLevelController,RemoveSkillCompetencyLevel", ex.Message, ex.StackTrace, "HCL.Academy.Service", req.ClientInfo.emailId); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } return response; } } }
using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; using System.Collections; using System.Linq; namespace Cauldron.Anathema { public class CarapaceHelmetCardController : CardController { public CarapaceHelmetCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController) { } public override void AddTriggers() { //Reduce damage dealt to this card by 1. base.AddReduceDamageTrigger((Card c) => c == base.Card, 1); //Villain targets are immune to damage dealt by environment cards. base.AddImmuneToDamageTrigger((DealDamageAction dd) => dd.DamageSource.IsEnvironmentCard && base.IsVillainTarget(dd.Target), false); } public override IEnumerator Play() { //When this card enters play, destroy all other head cards. if (GetNumberOfHeadInPlay() > 1) { IEnumerator coroutine = base.GameController.DestroyCards(this.DecisionMaker, new LinqCardCriteria((Card c) => this.IsHead(c) && c != base.Card, "head", true, false, null, null, false), false, null, null, null, SelectionType.DestroyCard, base.GetCardSource(null)); if (base.UseUnityCoroutines) { yield return base.GameController.StartCoroutine(coroutine); } else { base.GameController.ExhaustCoroutine(coroutine); } } yield break; } private bool IsHead(Card card) { return card != null && base.GameController.DoesCardContainKeyword(card, "head", false, false); } private int GetNumberOfHeadInPlay() { return base.FindCardsWhere((Card c) => c.IsInPlayAndHasGameText && this.IsHead(c), false, null, false).Count<Card>(); } } }
using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using System.Threading.Tasks; namespace Marvolo.Data.Sync { /// <summary> /// </summary> public sealed class DbSync { private readonly HashSet<DbSyncEntry> _added = new HashSet<DbSyncEntry>(); private readonly ObjectContext _context; private readonly HashSet<DbSyncEntry> _deleted = new HashSet<DbSyncEntry>(); private readonly HashSet<DbSyncEntry> _modified = new HashSet<DbSyncEntry>(); private readonly HashSet<DbSyncEntry> _unchanged = new HashSet<DbSyncEntry>(); /// <summary> /// </summary> /// <param name="context"></param> /// <param name="entries"></param> internal DbSync(IObjectContextAdapter context, IEnumerable<DbSyncEntry> entries) { _context = context.ObjectContext; foreach (var entry in entries) { switch (entry.SourceState) { case EntityState.Added: _added.Add(entry); break; case EntityState.Deleted: _deleted.Add(entry); break; case EntityState.Modified: _modified.Add(entry); break; case EntityState.Unchanged: _unchanged.Add(entry); break; } } } /// <summary> /// </summary> /// <param name="state"></param> /// <returns></returns> public IEnumerable<DbSyncEntry> GetEntries(EntityState state = EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged) { var entries = Enumerable.Empty<DbSyncEntry>(); if (state.HasFlag(EntityState.Added)) { entries = entries.Concat(_added); } if (state.HasFlag(EntityState.Deleted)) { entries = entries.Concat(_deleted); } if (state.HasFlag(EntityState.Modified)) { entries = entries.Concat(_modified); } if (state.HasFlag(EntityState.Unchanged)) { entries = entries.Concat(_unchanged); } return entries; } /// <summary> /// </summary> public void Sync() { var entries = GetEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Where(entry => entry.TargetState == EntityState.Detached); // attach those target entity that are marked as detached foreach (var entry in entries) _context.AttachTo(entry.TargetEntityKey.EntitySetName, entry.TargetEntity); } /// <summary> /// </summary> /// <param name="state"></param> public void Refresh(EntityState state = EntityState.Added | EntityState.Deleted | EntityState.Modified) { _context.Refresh(RefreshMode.StoreWins, GetEntries(state).Where(CanRefresh).Select(entry => entry.TargetEntity)); } /// <summary> /// </summary> /// <param name="state"></param> /// <returns></returns> public Task RefreshAsync(EntityState state = EntityState.Added | EntityState.Deleted | EntityState.Modified) { return _context.RefreshAsync(RefreshMode.StoreWins, GetEntries(state).Where(CanRefresh).Select(entry => entry.TargetEntity)); } /// <summary> /// </summary> public void Flush() { foreach (var entry in GetEntries()) { entry.TargetState = _context.ObjectStateManager.TryGetObjectStateEntry(entry.TargetEntityKey, out var current) ? current.State : EntityState.Detached; } } private static bool CanRefresh(DbSyncEntry entry) { switch (entry.TargetState) { case EntityState.Detached: return entry.SourceState == EntityState.Added; default: return true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Monetization; public class AdvertsInitialiser : MonoBehaviour { [SerializeField] string _gameId = "2983149"; [SerializeField] bool _testMode = false; void Start() { //Debug.LogError("Ads now don't initialize."); Monetization.Initialize(_gameId, _testMode); } public void ShowPrivacyPolicy() { Application.OpenURL("https://www.freeprivacypolicy.com/privacy/view/7a7f49c0a52590d8a462cee4fd057ae1"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace No8.Solution.Printers.Factories { public class EpsonFactory : AbstractPrinterFactory { public override Printer CreateNew(string model) => new EpsonPrinter(model); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Evpro.Data.Infrastructure; using Evpro.Domain.Entities; using Evpro.Service.Pattern; namespace Evpro.Service { public class EventownerService : MyServiceGeneric<eventowner>, IEventownerService { private static IDataBaseFactory dbfac = new DataBaseFactory(); private static IUnitOfWork utw = new UnitOfWork(dbfac); public EventownerService():base(utw) { } } }
using Ornithology.Entity; using Ornithology.Services; using Ornithology.WebApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Mvc; using X.PagedList; namespace Ornithology.WebApi.Controllers { public class AveController : ApiController { private IAveServices _aveServices = null; private const int pageSize = 5; public AveController(IAveServices aveServices) { _aveServices = aveServices; } public async Task<ActionResult> Listar(int? page = 1) { var client = new HttpClient(); var response = await client.GetAsync("http://yourapi.com/api/ave"); var lista2 = await _aveServices.ListarAsync(); var lista = await response.Content.ReadAsAsync<IEnumerable<Ave>>(); IPagedList<Ave> paginasConAves = lista.ToPagedList(page ?? 1, pageSize); //if (Request.IsAjaxRequest()) //{ // return PartialView("_QuestoesPartialView", vm); //} return View(paginasConAves); } // GET: api/Ave public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Ave/5 public string Get(int id) { return "value"; } // POST: api/Ave public void Post([FromBody]string value) { } // PUT: api/Ave/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Ave/5 public void Delete(int id) { } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Data; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities; using DotNetNuke.Entities.Modules; #endregion namespace DotNetNuke.Services.Social.Messaging { /// <summary> /// Archived Status of a Message /// </summary> public enum MessageArchivedStatus { /// <summary> /// Archived Message Status /// </summary> Archived = 1, /// <summary> /// UnArchived Message Status /// </summary> UnArchived = 0, /// <summary> /// Any Message Status - Both Archived and UnArchived /// </summary> Any = -1 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CTCT.Util; using System.Runtime.Serialization; namespace CTCT.Components.EventSpot { /// <summary> /// Promocode class /// </summary> [DataContract] [Serializable] public class Promocode : Component { /// <summary> /// Constructor /// </summary> public Promocode() { this.FeeIds = new List<string>(); } /// <summary> /// Name of the promotional code visible to registrants, between 4 - 12 characters, cannot contain spaces or special character (_ is OK); each code_name must be unique /// </summary> [DataMember(Name = "code_name", EmitDefaultValue = false)] public string CodeName { get; set; } /// <summary> /// Type of promocode: /// ACCESS - applies to a specific fee with has_restricted_access = true, fee_list must include only a single fee_id. See Event Fees /// DISCOUNT - when set to DISCOUNT, you must specify either a discount_percent or a discount_amount /// </summary> [DataMember(Name = "code_type", EmitDefaultValue = false)] private string CodeTypeString { get; set; } /// <summary> /// Type of promocode: /// ACCESS - applies to a specific fee with has_restricted_access = true, fee_list must include only a single fee_id. See Event Fees /// DISCOUNT - when set to DISCOUNT, you must specify either a discount_percent or a discount_amount /// </summary> public CodeType CodeType { get { return this.CodeTypeString.ToEnum<CodeType>(); } set { this.CodeTypeString = value.ToString(); } } /// <summary> /// Specifies a fixed discount amount, minimum of 0.01, is required when code_type = DISCOUNT, but not using discount_percent /// </summary> [DataMember(Name = "discount_amount", EmitDefaultValue = true)] public double DiscountAmount { get; set; } /// <summary> /// Specifies a discount percentage, from 1% - 100%, is required when code_type = DISCOUNT, but not using discount_amount /// </summary> [DataMember(Name = "discount_percent", EmitDefaultValue = true)] public int DiscountPercent { get; set; } /// <summary> /// Required when code_type = DISCOUNT; /// FEE_LIST - discount is applied only to those fees listed in the fee_ids array ORDER_TOTAL - discount is applied to the order total /// </summary> [DataMember(Name = "discount_scope", EmitDefaultValue = false)] private string DiscountScopeString { get; set; } /// <summary> /// Required when code_type = DISCOUNT; /// FEE_LIST - discount is applied only to those fees listed in the fee_ids array ORDER_TOTAL - discount is applied to the order total /// </summary> public DiscountScope DiscountScope { get { return this.DiscountScopeString.ToEnum<DiscountScope>(); } set { this.DiscountScopeString = value.ToString(); } } /// <summary> /// Discount types /// </summary> [DataMember(Name = "discount_type", EmitDefaultValue = false)] private string DiscountTypeString { get; set; } /// <summary> /// Discount types /// </summary> public DiscountType DiscountType { get { return this.DiscountTypeString.ToEnum<DiscountType>(); } set { this.DiscountTypeString = value.ToString(); } } /// <summary> /// Identifies the fees to which the promocode applies; /// </summary> [DataMember(Name = "fee_ids", EmitDefaultValue = false)] public IList<string> FeeIds { get; set; } /// <summary> /// Unique ID for the event promotional code /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// When set to true, promocode cannot be redeemed; when false, promocode can be redeemed; default = false /// </summary> [DataMember(Name = "is_paused", EmitDefaultValue = true)] public bool IsPaused { get; set; } /// <summary> /// Number of promocodes available for redemption; -1 = unlimited /// </summary> [DataMember(Name = "quantity_available", EmitDefaultValue = true)] public int QuantityAvailable { get; set; } /// <summary> /// Total number of promocodes available for redemption; -1 = unlimited /// </summary> [DataMember(Name = "quantity_total", EmitDefaultValue = true)] public int QuantityTotal { get; set; } /// <summary> /// Number of promocodes that have been redeemed; starts at 0 /// </summary> [DataMember(Name = "quantity_used", EmitDefaultValue = true)] public int QuantityUsed { get; set; } /// <summary> /// Status of the promocode /// </summary> [DataMember(Name = "status", EmitDefaultValue = false)] private string StatusString { get; set; } /// <summary> /// Status of the promocode /// </summary> public PromocodeStatus Status { get { return this.StatusString.ToEnum<PromocodeStatus>(); } set { this.StatusString = value.ToString(); } } } /// <summary> /// Type of promocode /// </summary> [Serializable] public enum CodeType { /// <summary> /// applies to a specific fee with has_restricted_access = true, fee_list must include only a single fee_id. See Event Fees /// </summary> ACCESS, /// <summary> /// when set to DISCOUNT, you must specify either a discount_percent or a discount_amount /// </summary> DISCOUNT } /// <summary> /// Discount Scope /// </summary> [Serializable] public enum DiscountScope { /// <summary> /// discount is applied only to those fees listed in the fee_ids array /// </summary> FEE_LIST, /// <summary> /// discount is applied to the order total /// </summary> ORDER_TOTAL } /// <summary> /// Discount Type /// </summary> [Serializable] public enum DiscountType { /// <summary> /// discount is a percentage specified by discount_percent /// </summary> PERCENT, /// <summary> /// discount is a fixed amount, specified by discount_amount /// </summary> AMOUNT } /// <summary> /// Promocode Status /// </summary> [Serializable] public enum PromocodeStatus { /// <summary> /// promocode is available to be redeemed /// </summary> LIVE, /// <summary> /// promocode is not available for redemption /// </summary> PAUSED, /// <summary> /// no more promocodes remain, /// </summary> DEPLETED } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; using Pidgin; using ODataQuery.Parsers; namespace ODataQuery.Tests { public class LogicalTests { [Theory] [InlineData("rate lt 100", "Lt[Ident[rate],Const[100]]")] [InlineData("rate lt 100 and vip eq 1 or booked ne 1", "Or[And[Lt[Ident[rate],Const[100]],Eq[Ident[vip],Const[1]]],Ne[Ident[booked],Const[1]]]")] [InlineData("((rate lt 100) and (vip eq 1 or booked ne 1))", "And[Lt[Ident[rate],Const[100]],Or[Eq[Ident[vip],Const[1]],Ne[Ident[booked],Const[1]]]]")] [InlineData("today gt 2000-01-01", "Gt[Ident[today],Const[2000-01-01T00:00:00]]")] [InlineData("not contains(name, 'abc') or name eq 'abc'", "Or[Not[Func[Contains,Ident[name],Const[abc]]],Eq[Ident[name],Const[abc]]]")] public void LogicalExpression(string input, string expected) { var result = Logical.LogicalExpr .Before(Parser<char>.End) .ParseOrThrow(input) .ToString(); Assert.Equal(expected, result); } } }
using System; using System.Data; using System.Data.SqlClient; using Tools; using System.Configuration; using Accounting.Utility; using Accounting.DataAccess; using System.Collections.Generic; using System.Web.SessionState; using System.Linq; namespace AccSys.Web.WebControls { public class DalResourceAuthorization { public static List<ResourceAuthorization> GetAuthorizationResources(int userId) { var access = new List<ResourceAuthorization>(); var user = new DaLogIn().GetUser(ConnectionHelper.getConnection(), userId); DataTable dt = new DataTable(); if (user != null && user.RoleId > 0) { string qstr = @"SELECT Resources.ResourceId,GroupName,ResourceName,ResourceType,ResourcePath,ResourcesInRole.RoleId, RoleName,CanView,CanAdd,CanEdit,CanDelete FROM Resources LEFT JOIN ResourcesInRole ON Resources.ResourceID = ResourcesInRole.ResourceID AND RoleId=@RoleId LEFT JOIN Roles ON Roles.RoleId = ResourcesInRole.RoleId ORDER BY GroupName,ResourceName"; using (SqlDataAdapter da = new SqlDataAdapter(qstr, ConnectionHelper.DefaultConnectionString)) { da.SelectCommand.Parameters.Add("@RoleId", SqlDbType.Int).Value = user.RoleId; da.Fill(dt); da.Dispose(); } foreach (DataRow dr in dt.Rows) { access.Add(Map(dr, user.UserID, user.UserName)); } } return access; } public static ResourceAuthorization GetAuthorization(HttpSessionState Session, string ResourcePath) { if (Session.IsSuperAdmin()) { return new ResourceAuthorization { CanAdd = true, CanDelete = true, CanEdit = true, CanView = true, ResourcePath = ResourcePath, UserName = Session.UserName() }; } var userRoleAccess = Session.UserRoleAccess(); var access = userRoleAccess.FirstOrDefault(x => x.ResourcePath.ToLower().Contains(ResourcePath.ToLower())); if (access != null) { return access; } else { return new ResourceAuthorization() { ResourcePath = ResourcePath, UserName = Session.UserName(), CanAdd = false, CanEdit = false, CanDelete = false, CanView = false }; } } public static ResourceAuthorization Map(DataRow dataRow) { ResourceAuthorization obj = new ResourceAuthorization(); try { obj.CanAdd = Utility.IsNull<bool>(dataRow["CanAdd"], false); obj.CanDelete = Utility.IsNull<bool>(dataRow["CanDelete"], false); obj.CanEdit = Utility.IsNull<bool>(dataRow["CanEdit"], false); obj.CanView = Utility.IsNull<bool>(dataRow["CanView"], false); obj.GroupName = Utility.IsNull<string>(dataRow["GroupName"], ""); obj.ResourceID = Utility.IsNull<int>(dataRow["ResourceID"], 0); obj.ResourceName = Utility.IsNull<string>(dataRow["ResourceName"], ""); obj.ResourcePath = Utility.IsNull<string>(dataRow["ResourcePath"], ""); obj.ResourceType = Utility.IsNull<string>(dataRow["ResourceType"], ""); obj.RoleId = Utility.IsNull<int>(dataRow["RoleId"], 0); obj.RoleName = Utility.IsNull<string>(dataRow["RoleName"], ""); obj.UserID = Utility.IsNull<int>(dataRow["UserID"], 0); obj.UserName = Utility.IsNull<string>(dataRow["UserName"], ""); } catch (Exception ex) { throw ex; } return obj; } public static ResourceAuthorization Map(DataRow dataRow, int userId, string userName) { ResourceAuthorization obj = new ResourceAuthorization(); try { obj.CanAdd = Utility.IsNull<bool>(dataRow["CanAdd"], false); obj.CanDelete = Utility.IsNull<bool>(dataRow["CanDelete"], false); obj.CanEdit = Utility.IsNull<bool>(dataRow["CanEdit"], false); obj.CanView = Utility.IsNull<bool>(dataRow["CanView"], false); obj.GroupName = Utility.IsNull<string>(dataRow["GroupName"], ""); obj.ResourceID = Utility.IsNull<int>(dataRow["ResourceID"], 0); obj.ResourceName = Utility.IsNull<string>(dataRow["ResourceName"], ""); obj.ResourcePath = Utility.IsNull<string>(dataRow["ResourcePath"], ""); obj.ResourceType = Utility.IsNull<string>(dataRow["ResourceType"], ""); obj.RoleId = Utility.IsNull<int>(dataRow["RoleId"], 0); obj.RoleName = Utility.IsNull<string>(dataRow["RoleName"], ""); obj.UserID = userId; obj.UserName = userName; } catch (Exception ex) { throw ex; } return obj; } public static DataTable GetResources(string ResourceType) { DataTable dtResources = new DataTable(); try { using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Resources WHERE ResourceType=@ResourceType ORDER BY GroupName,ResourceName", ConnectionHelper.DefaultConnectionString)) { da.SelectCommand.Parameters.Add("@ResourceType", SqlDbType.VarChar, 50).Value = ResourceType; da.Fill(dtResources); da.Dispose(); } } catch (Exception ex) { throw ex; } return dtResources; } public static DataTable GetResourceGroupNames() { DataTable dtGroups = new DataTable(); using (SqlDataAdapter da = new SqlDataAdapter("SELECT DISTINCT GroupName FROM Resources", ConnectionHelper.DefaultConnectionString)) { da.Fill(dtGroups); da.Dispose(); } return dtGroups; } public static void SaveResource(int resourceId, string resourceName, string resourcePath, string resourceType, string groupName) { try { string qstr = ""; if (resourceId > 0) qstr = @"UPDATE Resources SET ResourceName=@ResourceName,ResourcePath=@ResourcePath,ResourceType=@ResourceType,GroupName=@GroupName WHERE ResourceID=@ResourceID"; else qstr = @"INSERT INTO Resources(ResourceName, ResourcePath, ResourceType, GroupName) VALUES (@ResourceName,@ResourcePath,@ResourceType,@GroupName)"; using (SqlConnection conn = new SqlConnection(ConnectionHelper.DefaultConnectionString)) { using (SqlCommand cmd = new SqlCommand(qstr, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@ResourceName", SqlDbType.NVarChar, 50).Value = resourceName; cmd.Parameters.Add("@ResourcePath", SqlDbType.NVarChar, 100).Value = resourcePath; cmd.Parameters.Add("@ResourceType", SqlDbType.VarChar, 50).Value = resourceType; cmd.Parameters.Add("@GroupName", SqlDbType.NVarChar, 100).Value = groupName; if (resourceId > 0) cmd.Parameters.Add("@ResourceID", SqlDbType.Int).Value = resourceId; if (conn.State != ConnectionState.Open) conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } catch (Exception ex) { throw ex; } } public static void DeleteResource(int resourceId) { try { if (resourceId <= 0) return; string qstr = @"DELETE FROM Resources WHERE ResourceID=@ResourceID"; using (SqlConnection conn = new SqlConnection(ConnectionHelper.DefaultConnectionString)) { using (SqlCommand cmd = new SqlCommand(qstr, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@ResourceID", SqlDbType.Int).Value = resourceId; if (conn.State != ConnectionState.Open) conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } catch (Exception ex) { throw ex; } } public static void ResolveResource(string resourceName, string resourcePath, string resourceType, string groupName, Guid applicationID, string applicationName) { try { string qstr = @"IF NOT EXISTS(SELECT * FROM Resources WHERE ResourcePath=@ResourcePath) INSERT INTO Resources(ResourceName, ResourcePath, ResourceType, GroupName) VALUES(@ResourceName,@ResourcePath,@ResourceType,@GroupName) ELSE UPDATE Resources SET ResourceName=@ResourceName,ResourceType=@ResourceType,GroupName=@GroupName WHERE ResourcePath=@ResourcePath"; using (SqlConnection conn = new SqlConnection(ConnectionHelper.DefaultConnectionString)) { using (SqlCommand cmd = new SqlCommand(qstr, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@ResourceName", SqlDbType.NVarChar, 50).Value = resourceName; cmd.Parameters.Add("@ResourcePath", SqlDbType.NVarChar, 100).Value = resourcePath; cmd.Parameters.Add("@ResourceType", SqlDbType.VarChar, 50).Value = resourceType; cmd.Parameters.Add("@GroupName", SqlDbType.NVarChar, 100).Value = groupName; if (conn.State != ConnectionState.Open) conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } catch (Exception ex) { throw ex; } } public static DataTable GetResourcesOfRole(int roleId, string groupName) { DataTable dtResources = new DataTable(); try { string qstr = @"SELECT Resources.ResourceID, Resources.ResourceName, Resources.ResourcePath, Resources.ResourceType, Resources.GroupName, ISNULL(ResourcesInRole.RoleId,@RoleId) AS RoleId, ISNULL(CanView, 0) AS CanView, ISNULL(CanAdd, 0) AS CanAdd, ISNULL(CanEdit,0) AS CanEdit, ISNULL(CanDelete,0) AS CanDelete FROM Resources LEFT OUTER JOIN ResourcesInRole ON (Resources.ResourceID = ResourcesInRole.ResourceID AND RoleId=@RoleId)"; if (groupName.ToLower() != "all") qstr += string.Format(" WHERE ISNULL(GroupName,'')='{0}'", groupName); qstr += " ORDER BY GroupName,ResourceName"; using (SqlDataAdapter da = new SqlDataAdapter(qstr, ConnectionHelper.DefaultConnectionString)) { da.SelectCommand.Parameters.Add("@RoleId", SqlDbType.Int).Value = roleId; da.SelectCommand.Parameters.Add("@GroupName", SqlDbType.NVarChar, 100).Value = groupName; da.Fill(dtResources); da.Dispose(); } } catch (Exception ex) { throw ex; } return dtResources; } public static void SaveResourcesOfRole(int resourceId, int roleId, bool canView, bool canAdd, bool canEdit, bool canDelete) { try { string qstr = @"IF EXISTS(SELECT * FROM ResourcesInRole WHERE ResourceID = @ResourceID AND RoleId = @RoleId) UPDATE ResourcesInRole SET CanView = @CanView, CanAdd = @CanAdd, CanEdit = @CanEdit, CanDelete = @CanDelete WHERE ResourceID = @ResourceID AND RoleId = @RoleId ELSE INSERT INTO ResourcesInRole(ResourceID, RoleId, CanView, CanAdd, CanEdit, CanDelete) VALUES (@ResourceID,@RoleId,@CanView,@CanAdd,@CanEdit,@CanDelete)"; using (SqlConnection conn = new SqlConnection(ConnectionHelper.DefaultConnectionString)) { using (SqlCommand cmd = new SqlCommand(qstr, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@ResourceID", SqlDbType.Int).Value = resourceId; cmd.Parameters.Add("@RoleId", SqlDbType.Int).Value = roleId; cmd.Parameters.Add("@CanView", SqlDbType.Bit).Value = canView; cmd.Parameters.Add("@CanAdd", SqlDbType.Bit).Value = canAdd; cmd.Parameters.Add("@CanEdit", SqlDbType.Bit).Value = canEdit; cmd.Parameters.Add("@CanDelete", SqlDbType.Bit).Value = canDelete; if (conn.State != ConnectionState.Open) conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } catch (Exception ex) { throw ex; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpecialAudioTrigger : AudioTrigger { [SerializeField] string EventName = null; private void Start() { if(PlayerPrefs.GetInt(EventName) == 1) { triggered = true; } } public override void OnTriggerEnter2D(Collider2D collision) { PlayerPrefs.SetInt(EventName, 1); base.OnTriggerEnter2D(collision); } }
using System; using System.Collections; using System.Diagnostics; using UnityEngine; public class WWWUploader : MonoSingleton<WWWUploader> { public class CR_Loader { public enum E_State { None, Ing, End, Err } public enum E_Error { None, FileNoExist, WWWErr } private const int UNION_LENGTH = 1048576; private static int m_count; private int m_id; public string m_url; public string m_fileName; public string m_path; public Action<float> m_actionOnProgress; public Action<int, string> m_actionOnComplete; public WWWUploader.CR_Loader.E_State m_state; public float m_progress; public WWWUploader.CR_Loader.E_Error m_err; public string m_errMessage; public WWW m_www; public IEnumerator m_iEnumerator; public static int Count { get { return WWWUploader.CR_Loader.m_count; } } public int ID { get { return this.m_id; } } public CR_Loader(string path, string url, Action<float> action_on_progress, Action<int, string> action_on_complete) { this.m_id = ++WWWUploader.CR_Loader.m_count; this.m_path = Application.get_dataPath() + "/" + path; this.m_url = url; string[] array = this.m_path.Split(new char[] { '/' }); if (array != null && array.Length > 0) { this.m_fileName = array[array.Length - 1]; } this.m_actionOnProgress = action_on_progress; this.m_actionOnComplete = action_on_complete; this.m_state = WWWUploader.CR_Loader.E_State.None; this.m_progress = 0f; this.m_err = WWWUploader.CR_Loader.E_Error.None; this.m_errMessage = string.Empty; this.m_iEnumerator = this.IE_Load(); } [DebuggerHidden] public IEnumerator IE_Load() { WWWUploader.CR_Loader.<IE_Load>c__Iterator1E <IE_Load>c__Iterator1E = new WWWUploader.CR_Loader.<IE_Load>c__Iterator1E(); <IE_Load>c__Iterator1E.<>f__this = this; return <IE_Load>c__Iterator1E; } public void FireOnComplete() { if (this.m_actionOnComplete != null) { this.m_actionOnComplete.Invoke((int)this.m_err, this.m_errMessage); } } public void FireOnProgress() { if (this.m_actionOnProgress != null) { this.m_actionOnProgress.Invoke(this.m_progress); } } public void Dispose() { if (this.m_www != null) { this.m_www.Dispose(); } } } public class LoaderInfo { public int id; public string url; public string fileName; public string path; public float progress; } private ListQueue<WWWUploader.CR_Loader> m_loaderQueue; public void Open() { this.m_loaderQueue = new ListQueue<WWWUploader.CR_Loader>(); } public int Load(string path, string url, Action<float> action_on_progress, Action<int, string> action_on_complete) { WWWUploader.CR_Loader cR_Loader = new WWWUploader.CR_Loader(path, url, action_on_progress, action_on_complete); base.StartCoroutine(cR_Loader.m_iEnumerator); return cR_Loader.ID; } public void Stop(int id) { WWWUploader.CR_Loader loaderFromID = this.GetLoaderFromID(id); if (loaderFromID != null && loaderFromID.m_state == WWWUploader.CR_Loader.E_State.Ing) { base.StopCoroutine(loaderFromID.m_iEnumerator); loaderFromID.Dispose(); this.m_loaderQueue.Remove(loaderFromID); } } private void LateUpdate() { } public WWWUploader.CR_Loader GetLoaderFromID(int id) { WWWUploader.CR_Loader result = null; for (int i = 0; i < this.m_loaderQueue.get_Count(); i++) { WWWUploader.CR_Loader cR_Loader = this.m_loaderQueue.get_Item(i); if (cR_Loader.ID == id) { result = cR_Loader; break; } } return result; } public WWWUploader.LoaderInfo GetLoaderInfoFromID(int id) { WWWUploader.CR_Loader loaderFromID = this.GetLoaderFromID(id); if (loaderFromID == null) { return null; } return new WWWUploader.LoaderInfo { id = loaderFromID.ID, url = loaderFromID.m_url, fileName = loaderFromID.m_fileName, path = loaderFromID.m_path, progress = loaderFromID.m_progress }; } }
using Assets.Scripts.Enemies.Interfaces; using UnityEngine; namespace Assets.Scripts.Weapons.SeekerBeam.Beams { public class RangeBeam { Vector3 defaultScale; public GameObject RangeBeamInstance { get; set; } public ITargetable Target { get; set; } public Vector2 CurrentPosition { get; set; } public bool CanRemove { get; set; } public RangeBeam(GameObject RangeBeamInstance, ITargetable Target) { this.RangeBeamInstance = RangeBeamInstance; this.Target = Target; defaultScale = RangeBeamInstance.transform.localScale; } public void UpdateBeam(Vector2 currentPosition) { CurrentPosition = currentPosition; RangeBeamInstance.transform.position = currentPosition; RotateAndScaleBeamToTarget(); } void RotateAndScaleBeamToTarget() { var beamCrop = 0.5f; var currentPositionToTarget = Target.Position - CurrentPosition; var beamSegmentScaler = currentPositionToTarget.magnitude - beamCrop; RangeBeamInstance.transform.localScale = defaultScale * new Vector2(beamSegmentScaler, 1); RangeBeamInstance.transform.rotation = Quaternion.FromToRotation(Vector2.right, currentPositionToTarget); } } }
using System; using System.Collections.Generic; using System.Text; namespace HW2 { public class BettingPlatformEmulator { public static readonly List<Player> Players = new List<Player>(10); private Player ActivePlayer; public readonly Account Account; private BetService BetService; private PaymentService paymentService; private static List<PaymentService> AllPaymentServices = new List<PaymentService>(10); private float CurrentOdds; public BettingPlatformEmulator() { Account = new Account("USD"); BetService = new BetService(); CurrentOdds = 0; } public void Start() { while (true) { Console.Clear(); if (ActivePlayer == null) { Console.WriteLine("======================================"); Console.WriteLine("Welcome to our Betting Platform!\n======================================\n\tMENU"); Console.WriteLine("1. Register"); Console.WriteLine("2. Login"); Console.WriteLine("3. Stop"); Console.Write("Enter option's number: "); bool inputIsCorrect = int.TryParse(Console.ReadLine().Trim(),out int answer); if (!inputIsCorrect) { Console.WriteLine("Wrong input!"); continue; } switch (answer) { case 1: Register(); break; case 2: Login(); break; case 3: Exit(); break; default: break; } } else { Console.WriteLine("============================================"); Console.WriteLine("Welcome to our Betting Platform {0}!\n\tMENU", ActivePlayer.FirstName); Console.WriteLine("============================================"); Console.WriteLine("1. Deposit"); Console.WriteLine("2. Withdraw"); Console.WriteLine("3. Get Odds"); Console.WriteLine("4. Bet"); Console.WriteLine("5. Get balance"); Console.WriteLine("6. Logout"); Console.Write("Enter option's number: "); bool inputIsCorrect = int.TryParse(Console.ReadLine().Trim(), out int answer); if (!inputIsCorrect) { Console.WriteLine("Wrong input!"); continue; } Console.WriteLine("--------------------------"); switch (answer) { case 1: Deposit(); break; case 2: Withdraw(); break; case 3: GetOdds(); break; case 4: Bet(); break; case 5: GetBalance(); break; case 6: Logout(); break; default: break; } } } } private void Bet() { string Currency = GetCurrency(); decimal amount; Console.Write("Please, enter amount you want to bet: "); while (true) { if (!Decimal.TryParse(Console.ReadLine().Trim(), out amount)) { Console.WriteLine("Incorrect input! Try again!"); continue; } break; } try { ActivePlayer.Withdraw(amount, Currency); } catch (NotSupportedException) { Console.WriteLine("Withdraw failure!"); Console.WriteLine("Insufficient funds!"); Console.ReadKey(); return; } Console.WriteLine("\nBet accepted!"); Console.Write("Obtaining results"); for (int i = 0; i < 3; i++) { System.Threading.Thread.Sleep(1000); Console.Write("."); } System.Threading.Thread.Sleep(1000); Console.WriteLine("\n"); decimal result = BetService.Bet(amount); if(result == 0) { Console.WriteLine("Ah! It was a bit unlucky. That could happen to anyone."); Console.WriteLine("How about you try again and proove that that was just a small misfortune?"); } else { Console.WriteLine("Woah! Someone is definitely lucky today!\n"); Console.WriteLine($"You bet {amount} {Currency} with odds {CurrentOdds} and won {result} {Currency}!"); Console.WriteLine($"Your net profit is: {result - amount}\n"); Console.WriteLine("Then don't waste your fortune! Bet again!"); } ActivePlayer.Deposit(result, Currency); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void GetOdds() { CurrentOdds = BetService.GetOdds(); Console.WriteLine($"Here are Odds: {CurrentOdds}"); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Exit() { System.Environment.Exit(1); } private void GetBalance() { string Currency = GetCurrency(); Console.WriteLine(); ActivePlayer.GetBalance(Currency); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Deposit() { string Currency = GetCurrency(); decimal Amount; while (true) { Console.Write("Enter deposit amount: "); if(!decimal.TryParse(Console.ReadLine().Trim(), out Amount) || Amount < 0) { Console.WriteLine("Wrong input!"); continue; } break; } bool fail = false; try { paymentService.StartDeposit(Amount, Currency); } catch (LimitExceedExeption) { Console.WriteLine("Please, try to make a transaction with lower amount"); fail = true; } catch (InsufficientFundsExeption) { Console.WriteLine("Please, try to make a transaction with lower amount or change payment method"); fail = true; } catch (PaymentServiceExeption) { Console.WriteLine("You exceeded this bank transactions limit!\nPlease, try to make a transaction with lower amount or change payment method"); fail = true; } catch (Exception) { Console.WriteLine("Something went wrong. Try again later..."); fail = true; } if (fail) { Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); return; } Console.WriteLine("Deposit success!"); ActivePlayer.Deposit(Amount, Currency); Account.Deposit(Amount, Currency); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Withdraw() { string Currency = GetCurrency(); decimal Amount; while (true) { Console.Write("Enter amount you want to withdraw: "); if (!decimal.TryParse(Console.ReadLine().Trim(), out Amount) || Amount < 0) { Console.WriteLine("Wrong input!"); continue; } break; } if (Account.GetBalance("USD") < ActivePlayer.GetBalance("USD")) { try { Account.Withdraw(Amount, Currency); } catch (NotSupportedException) { Console.WriteLine("Withdraw failure!"); Console.WriteLine("There is some problem on the program side. Please, try later."); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); return; } } bool fail = false; string result = ""; try { result = paymentService.StartWithdrawal(Amount, Currency); } catch (LimitExceedExeption) { Console.WriteLine("Please, try to make a transaction with lower amount"); fail = true; } catch (InsufficientFundsExeption) { Console.WriteLine("Please, try to make a transaction with lower amount or change payment method"); fail = true; } catch (PaymentServiceExeption) { Console.WriteLine("You exceeded this bank transactions limit!\nPlease, try to make a transaction with lower amount or change payment method"); fail = true; } catch (Exception) { Console.WriteLine("Something went wrong. Try again later..."); fail = true; } if (fail) { Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); return; } try { ActivePlayer.Withdraw(Amount, Currency); } catch (NotSupportedException) { Console.WriteLine("Withdraw failure!"); Console.WriteLine("Insufficient funds!"); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); return; } Console.WriteLine("Withdrawall success!"); Console.WriteLine(result); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Register() { Console.WriteLine("-------------------"); Console.WriteLine("Registering new player."); Console.Write("Enter your name, please: "); string name = Console.ReadLine(); Console.Write("Enter your Last name, please: "); string Lastname = Console.ReadLine(); Console.Write("Enter your Email, please: "); string email = Console.ReadLine(); string password; while (true) { Console.Write("Enter your Password, please: "); password = Console.ReadLine().Trim(); Console.Write("Repeat your Password, please: "); string repeatPassword = Console.ReadLine().Trim(); if(password != repeatPassword) { Console.WriteLine("Passwords are not equal!"); continue; } break; } string Currency = GetCurrency(); Players.Add(new Player(Currency, name, Lastname, email, password)); paymentService = new PaymentService(); AllPaymentServices.Add(paymentService); Console.WriteLine("Registration success!"); Console.WriteLine("-------------------"); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Login() { if(Players.Count == 0) { Console.WriteLine("Players list is empty!"); Console.ReadKey(); return; } Console.WriteLine("-------------------"); Console.WriteLine("Logging in."); Console.Write("Enter First name: "); string firstName = Console.ReadLine(); Console.Write("Enter Last name: "); string lastName = Console.ReadLine(); Console.Write("Enter password: "); string password = Console.ReadLine().Trim(); Player currPlayer = Players[0]; bool isFound = false; foreach (var player in Players) { if(player.FirstName == firstName && player.LastName == lastName) { currPlayer = player; isFound = true; break; } } if (isFound && currPlayer.IsPasswordValid(password)) { ActivePlayer = currPlayer; Console.WriteLine("Login success!"); paymentService = AllPaymentServices[Players.IndexOf(currPlayer)]; } else Console.WriteLine("No user with such parameters found!"); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } private void Logout() { CurrentOdds = 0; ActivePlayer.Dispose(); ActivePlayer = null; } private string GetCurrency() { string Currency; while (true) { Console.Write("Enter your account currency, please: "); Currency = Console.ReadLine().Trim().ToUpper(); if (!(Currency == "USD" || Currency == "EUR" || Currency == "UAH")) { Console.WriteLine("Unsupported currency!"); Console.WriteLine("We support : UAH, USD, EUR"); continue; } break; } return Currency; } } }
using System; using Foundation; using UIKit; namespace Practical_Assignment { public class ProjectDetailsSource : UITableViewSource { protected string cellIdentifier = "ProjectDetailsCell"; ProjectsCell layoutTableCell; objTask Task; public ProjectDetailsSource(ProjectDetailsController projectDetailsController, objTask task) { Task = task; projectDetailsController.NavigationItem.SetRightBarButtonItem(new UIBarButtonItem(UIBarButtonSystemItem.Save, (sender, args) => { //get updated task object Task = AppDelegate.task; //save updated children to database Repository.SaveTaskSet(Task.TaskSet); Repository.SaveProjectData(Task.ProjectData); Console.WriteLine("Updated information"); projectDetailsController.NavigationController.PushViewController(new ProjectsController(), true); }), true); AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; layoutTableCell = new ProjectsCell(); layoutTableCell.LayoutSubviews(); } public override nint RowsInSection(UITableView tableview, nint section) { return 8; } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { return 50; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { ProjectDetailsCell cell = (ProjectDetailsCell)tableView.DequeueReusableCell(ProjectDetailsCell.Key); switch (indexPath.Row) { case 0: cell.UpdateCell("Title", Task, indexPath.Row+1); return cell; case 1: cell.UpdateCell("Description", Task, indexPath.Row + 1); return cell; case 2: cell.UpdateCell("Estimated Hours", Task, indexPath.Row + 1); return cell; case 3: cell.UpdateCell("Start Date", Task, indexPath.Row + 1); return cell; case 4: cell.UpdateCell("End Date", Task, indexPath.Row + 1); return cell; case 5: cell.UpdateCell("Due Date", Task, indexPath.Row + 1); return cell; case 6: cell.UpdateCell("Active", Task, indexPath.Row + 1); return cell; case 7: cell.UpdateCell("Billable", Task, indexPath.Row + 1); return cell; default: return cell; } } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow(indexPath, true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Midterm { class Program { static void Main(string[] args) { /* #2. Loops,If-statements and switch. * Loops will repeat until the desired end sequence. If-statements performs the condition if it is met and switches * will replace if-statements */ /* #3. int i = 4; Boolean keepLooping = true; while (keepLooping) { if (i <= 3) keepLooping = false; i++; Console.WriteLine(i); */ /* #4. int i = 2; while (i <= 128) { { if ((i % 2) == 0) { Console.WriteLine("[{0}]", i); } else if ((i % 2) != 0) { Console.Write(""); } i *= 2; */ /* #5. string a = ","; int b; for (b = 49; b >= 1; --b) { Console.Write(b); if (b >= 2) { Console.Write(a); */ /* #6. int a = 1; while (a <= 21) { { if ((a %2 ) == 0) { Console.Write(" "); } else if ((a % 2) != 0) { Console.Write(a); } a++; */ /* #7. The output for the following code is ' * '. This code replicated with while statements is nothing since the do-while checks after executing while the while checks before. /* 8. You can combine Boolean values by using boolean operators. bool icyRain = false ; bool tornadoWarning = false; if ((!icyRain) && (!tornadoWarning)) { Console.WriteLine("Let's go outside!"); } */ } } }
using SudokuSolver.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SudokuSolver.Models { public class SudokuField : IField<int>, IUpdatable<int> { public SudokuField(int value, SudokuBlock row, SudokuBlock column, SudokuBlock square, bool solved) { Value = value; Row = row; Column = column; Square = square; Solved = solved; } public int Value { get; set; } public SudokuBlock Row { get; set; } public SudokuBlock Column { get; set; } public SudokuBlock Square { get; set; } public List<int> PossibleNumbers { get; set; } public bool Solved { get; set; } public void Update(int value) { Value = value; PossibleNumbers = new List<int> { value }; RemovePossibleNumbersFromFieldBlocks(value); Solved = true; } // Removes a number from all fields, except the current field, in it private void RemovePossibleNumbersFromFieldBlocks(int number) { RemovePossibleNumbers(Row, number); RemovePossibleNumbers(Square, number); RemovePossibleNumbers(Column, number); } private void RemovePossibleNumbers(SudokuBlock block, int number) { foreach (var _field in block.Fields) { if (_field != this) { ((SudokuField)_field).PossibleNumbers.Remove(number); } } } } }
// ========================================================== // Clase para reproducir archivos de mp3, utilizando las API´s // Multimedia de Windows. // Gonzalo Antonio Sosa M. Julio 2003 // ========================================================== // importamos los espacios de nombres que necesitaremos. using System; using System.IO; using System.Text; using System.Runtime.InteropServices; namespace ReproductorMp3 { /// <summary> /// Clase para la reproducción de archivos de audio. /// </summary> public class Reproductor { #region Declaración de API´s // declaramos las funciones Api´s requeridas para la reproducción. // Envía cadenas de comando a un dispositivo MCI. [DllImport("winmm.dll")] public static extern int mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLengh, int hwndCallback); // Obtiene el número de dispositivos de salida, audio en este caso. [DllImport("winmm.dll")] public static extern int waveOutGetNumDevs(); // Obtiene la cadena de mensaje de error, del valor de retorno de la función // mciSendString. [DllImport("winmm.dll")] public static extern int mciGetErrorString(int fwdError, StringBuilder lpszErrorText, int cchErrorText); // Obtiene el nombre corto del archivo especificado en el parámetro // lpszLongPath. [DllImport("kernel32.dll")] public static extern int GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer); // Obtiene el nombre largo del archivo especificado en el parámetro // lpszShortName [DllImport("kernel32.dll")] public static extern int GetLongPathName(string lpszShortPath, StringBuilder lpszLongPath, int cchBuffer); #endregion #region Variables y constantes const int MAX_PATH = 260; // Constante con la longitud máxima de un nombre de archivo. const string Tipo = "MPEGVIDEO"; // Constante con el formato de archivo a reproducir. const string sAlias = "ArchivoDeSonido"; // Alias asiganado al archivo especificado. private string fileName; //Nombre de archivo a reproducir #endregion #region Declaración del Evento //Especificamos el delegado al que se vá a asociar el evento. public delegate void ReproductorMessage(string Msg); //Declaramos nuestro evento. public event ReproductorMessage ReproductorEstado; #endregion #region Contructor // Constructor de clase por defecto. public Reproductor() { } #endregion #region Propiedad de para leer o establecer el archivo a reproducir /// <summary> /// Propiedad que obtiene o establece el nombre y ruta del archivo /// de audio a reproducir /// </summary> public string NombreDeArchivo { get { return fileName; } set { fileName = value; } } #endregion #region Métodos que efectuan las operaciones básicas /// <summary> /// Método para convertir un nombre de archivo largo en uno corto, /// necesario para usarlo como parámetro de la función MciSendString. /// </summary> /// <param name="nombreLargo">Nombre y ruta del archivo a convertir.</param> /// <returns>Nombre corto del archivo especificado.</returns> private string NombreCorto(string NombreLargo) { // Creamos un buffer usando un constructor de la clase StringBuider. StringBuilder sBuffer = new StringBuilder(MAX_PATH); // intentamos la conversión del archivo. if (GetShortPathName(NombreLargo, sBuffer, MAX_PATH) > 0) // si la función ha tenido éxito devolvemos el buffer formateado // a tipo string. return sBuffer.ToString(); else // en caso contrario, devolvemos una cadena vacía. return ""; } /// <summary> /// Método que convierte un nombre de archivo corto, en uno largo. /// </summary> /// <param name="NombreCorto">Nombre del archivo a convertir.</param> /// <returns>Cadena con el nombre de archivo resultante.</returns> public string NombreLargo(string NombreCorto) { StringBuilder sbBuffer = new StringBuilder(MAX_PATH); if (GetLongPathName(NombreCorto, sbBuffer, MAX_PATH) > 0) return sbBuffer.ToString(); else return ""; } /// <summary> /// Método para convertir los mensajes de error numéricos, generados por la /// función mciSendString, en su correspondiente cadena de caracteres. /// </summary> /// <param name="ErrorCode">Código de error devuelto por la función mciSendString</param> /// <returns>Cadena de tipo string, con el mensaje de error</returns> private string MciMensajesDeError(int ErrorCode) { // Creamos un buffer, con suficiente espacio, para almacenar el mensaje // devuelto por la función. StringBuilder sbBuffer = new StringBuilder(MAX_PATH); // Obtenemos la cadena de mensaje. if (mciGetErrorString(ErrorCode, sbBuffer, MAX_PATH) != 0) // Sí la función ha tenido éxito, valor devuelto diferente de 0, // devolvemos el valor del buffer, formateado a string. return sbBuffer.ToString(); else // si no, devolvemos una cadena vacía. return ""; } /// <summary> /// Devuelve el número de dispositivos de salida, /// instalados en nuestro sistema. /// </summary> /// <returns>Número de dispositivos.</returns> public int DispositivosDeSonido() { return waveOutGetNumDevs(); } /// <summary> /// Abre el archivo específicado. /// </summary> /// <returns>Verdadero si se tuvo éxito al abrir el archivo /// falso en caso contrario.</returns> private bool Abrir() { // verificamos que el archivo existe; si no, regresamos falso. if (!File.Exists(fileName)) return false; // obtenemos el nombre corto del archivo. string nombreCorto = NombreCorto(fileName); // intentamos abrir el archivo, utilizando su nombre corto // y asignándole un alias para trabajar con él. if (mciSendString("open " + nombreCorto + " type " + Tipo + " alias " + sAlias, null, 0, 0) == 0) // si el resultado es igual a 0, la función tuvo éxito, // devolvemos verdadero. return true; else // en caso contrario, falso. return false; } /// <summary> /// Inicia la reproducción del archivo específicado. /// </summary> public void Reproducir() { // Nos cersioramos que hay un archivo que reproducir. if (fileName != "") { // intentamos iniciar la reproducción. if (Abrir()) { int mciResul = mciSendString("play " + sAlias, null, 0, 0); if (mciResul == 0) // si se ha tenido éxito, devolvemos el mensaje adecuado, ReproductorEstado("Ok"); else // en caso contrario, la cadena de mensaje de error. ReproductorEstado(MciMensajesDeError(mciResul)); } else // sí el archivo no ha sido abierto, indicamos el mensaje de error. ReproductorEstado("No se ha logrado abrir el archivo especificado"); } else // si no hay archivo especificado, devolvemos la cadena indicando // el evento. ReproductorEstado("No se ha especificado ningún nombre de archivo"); } /// <summary> /// Inicia la reproducción desde una posición específica. /// </summary> /// <param name="Desde">Nuevo valor de la posición a iniciar</param> public void ReproducirDesde(long Desde) { int mciResul = mciSendString("play " + sAlias + " from " + (Desde * 1000).ToString(), null, 0, 0); if (mciResul == 0) ReproductorEstado("Nueva Posición: " + Desde.ToString()); else ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Modifica la velocidad actual de reproducción. /// </summary> /// <param name="Tramas">Nuevo valor de la velocidad.</param> public void Velocidad(int Tramas) { // Establecemos la nueva velocidad pasando como parámetro, // la cadena adecuada, incluyendo el nuevo valor de la velocidad, // medido en tramas por segundo. int mciResul = mciSendString("set " + sAlias + " tempo " + Tramas.ToString(), null, 0, 0); if (mciResul == 0) // informamos el evento de la modificación éxitosa, ReproductorEstado("Velocidad modificada."); else // de lo contrario, enviamos el mensaje de error correspondiente. ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Mueve el apuntador del archivo a la posición especificada. /// </summary> /// <param name="NuevaPosicion">Nueva posición</param> public void Reposicionar(int NuevaPosicion) { // Enviamos la cadena de comando adecuada a la función mciSendString, // pasando como parte del mismo, la cantidad a mover el apuntador de // archivo. int mciResul = mciSendString("seek " + sAlias + " to " + (NuevaPosicion * 1000).ToString(), null, 0, 0); if (mciResul == 0) ReproductorEstado("Nueva Posición: " + NuevaPosicion.ToString()); else ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Mueve el apuntador de archivo al inicio del mismo. /// </summary> public void Principio() { // Establecemos la cadena de comando para mover el apuntador del archivo, // al inicio de este. int mciResul = mciSendString("seek " + sAlias + " to start", null, 0, 0); if (mciResul == 0) ReproductorEstado("Inicio de " + Path.GetFileNameWithoutExtension(fileName)); else ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Mueve el apuntador de archivo al final del mismo. /// </summary> public void Final() { // Establecemos la cadena de comando para mover el apuntador del archivo, // al final de este. int mciResul = mciSendString("seek " + sAlias + " to end", null, 0, 0); if (mciResul == 0) ReproductorEstado("Final de " + Path.GetFileNameWithoutExtension(fileName)); else ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Pausa la reproducción en proceso. /// </summary> public void Pausar() { // Enviamos el comando de pausa mediante la función mciSendString, int mciResul = mciSendString("pause " + sAlias, null, 0, 0); if (mciResul == 0) ReproductorEstado("Pausada"); else ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Continúa con la reproducción actual. /// </summary> public void Continuar() { // Enviamos el comando de pausa mediante la función mciSendString, int mciResul = mciSendString("resume " + sAlias, null, 0, 0); if (mciResul == 0) // informamos del evento, ReproductorEstado("Continuar"); else // si no, comunicamos el error. ReproductorEstado(MciMensajesDeError(mciResul)); } /// <summary> /// Detiene la reproducción actual y cierra el archivo de audio. /// </summary> public void Cerrar() { // Establecemos los comando detener reproducción y cerrar archivo. mciSendString("stop " + sAlias, null, 0, 0); mciSendString("close " + sAlias, null, 0, 0); } /// <summary> /// Detiene la reproducción del archivo de audio. /// </summary> public void Detener() { // Detenemos la reproducción, mediante el comando adecuado. mciSendString("stop " + sAlias, null, 0, 0); } /// <summary> /// Obtiene el estado de la reproducción en proceso. /// </summary> /// <returns>Cadena con la información requerida.</returns> public string Estado() { StringBuilder sbBuffer = new StringBuilder(MAX_PATH); // Obtenemos la información mediante el comando adecuado. mciSendString("status " + sAlias + " mode", sbBuffer, MAX_PATH, 0); // Devolvemos la información. return sbBuffer.ToString(); } /// <summary> /// Obtiene un valor que indica si la reproducción está en marcha. /// </summary> /// <returns>Verdadero si se encuentra en marcha, falso si no.</returns> public bool EstadoReproduciendo() { return Estado() == "playing" ? true : false; } /// <summary> /// Obtiene un valor que indica si la reproducción está pausada. /// </summary> /// <returns>Verdadero si se encuentra en marcha, falso si no.</returns> public bool EstadoPausado() { return Estado() == "paused" ? true : false; } /// <summary> /// Obtiene un valor que indica si la reproducción está detenida. /// </summary> /// <returns>Verdadero si se encuentra en marcha, falso si no.</returns> public bool EstadoDetenido() { return Estado() == "stopped" ? true : false; } /// <summary> /// Obtiene un valor que indica si el archivo se encuentra abierto. /// </summary> /// <returns>Verdadero si se encuentra en marcha, falso si no.</returns> public bool EstadoAbierto() { return Estado() == "open" ? true : false; } /// <summary> /// Calcula la posición actual del apuntador del archivo. /// </summary> /// <returns>Posición actual</returns> public long CalcularPosicion() { StringBuilder sbBuffer = new StringBuilder(MAX_PATH); // Establecemos el formato de tiempo. mciSendString("set " + sAlias + " time format milliseconds", null, 0, 0); // Enviamos el comando para conocer la posición del apuntador. mciSendString("status " + sAlias + " position", sbBuffer, MAX_PATH, 0); // Sí hay información en el buffer, if (sbBuffer.ToString() != "") // la devolvemos, eliminando el formato de milisegundos // y formateando la salida a entero largo; return long.Parse(sbBuffer.ToString()) / 1000; else // si no, devolvemos cero. return 0L; } /// <summary> /// Devuelve una cadena con la información de posición del apuntador del archivo. /// </summary> /// <returns>Cadena con la información.</returns> public string Posicion() { // obtenemos los segundos. long sec = CalcularPosicion(); long mins; // Si la cantidad de segundos es menor que 60 (1 minuto), if (sec < 60) // devolvemos la cadena formateada a 0:Segundos. return "0:" + String.Format("{0:D2}", sec); // Si los segundos son mayores que 59 (60 o más), else if (sec > 59) { // calculamos la cantidad de minutos, mins = (int)(sec / 60); // restamos los segundos de la cantida de minutos obtenida, sec = sec - (mins * 60); // devolvemos la cadena formateada a Minustos:Segundos. return String.Format("{0:D2}", mins) + ":" + String.Format("{0:D2}", sec); } else // en caso de obtener un valor menos a 0, devolvemos una cadena vacía. return ""; } /// <summary> /// Cálcula el tamaño del archivo abierto para reproducción. /// </summary> /// <returns>Tamaño en segundos del archivo.</returns> public long CalcularTamaño() { StringBuilder sbBuffer = new StringBuilder(MAX_PATH); mciSendString("set " + sAlias + " time format milliseconds", null, 0, 0); // Obtenemos el largo del archivo, en millisegundos. mciSendString("status " + sAlias + " length", sbBuffer, MAX_PATH, 0); // Sí el buffer contiene información, if (sbBuffer.ToString() != "") // la devolvemos, formateando la salida a entero largo; return long.Parse(sbBuffer.ToString()) / 1000; else // si no, devolvemos cero. return 0L; } /// <summary> /// Obtiene una cadena con la información sobre el tamaño (largo) del archivo. /// </summary> /// <returns>Largo del archivo de audio.</returns> public string Tamaño() { long sec = CalcularTamaño(); long mins; // Si la cantidad de segundos es menor que 60 (1 minuto), if (sec < 60) // devolvemos la cadena formateada a 0:Segundos. return "0:" + String.Format("{0:D2}", sec); // Si los segundos son mayores que 59 (60 o más), else if (sec > 59) { mins = (int)(sec / 60); sec = sec - (mins * 60); // devolvemos la cadena formateada a Minustos:Segundos. return String.Format("{0:D2}", mins) + ":" + String.Format("{0:D2}", sec); } else return ""; } #endregion } }
using System; using System.IO; using System.Linq; using System.Globalization; namespace Marina_Berth { class MarinaTools { public static void goBackMainMenu() { string pressEnter = Console.ReadLine(); if (pressEnter != null) { Home.mainMenu(); } } public static RecordList readList() // Read a list from a file or create a new one { string path = "Marina Berth Records.bin"; try { using (Stream stream = File.Open(path, FileMode.Open)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); RecordList recordsList = (RecordList)bformatter.Deserialize(stream); return recordsList; } } catch { RecordList recordsList = new RecordList(); return recordsList; } } public static void writeList(RecordList list) // Write a list in the file { string path = "Marina Berth Records.bin"; using (Stream stream = File.Open(path, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); list.reorderList(); //reorder the list, in case a record has been deleted bformatter.Serialize(stream, list); } } public static void writeEmptyList() //clear all the text in the file. It is used when the last record on the list is deleted. { string path = "Marina Berth Records.bin"; File.WriteAllText(path, String.Empty); } public static bool checkInput(string input) // check if the input is empty { if (string.IsNullOrEmpty(input)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Empty input, please try again." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } else { bool repeat = false; return repeat; } } public static bool checkDoubleInput(string input) // Validate double inputs { string trimInput = input.Trim(); if (!checkInput(trimInput)) { try { double number = double.Parse(trimInput); if (number != 0)// the user can't insert 0 { bool repeat = false; return repeat; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("A value of 0 is not accepted." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You can insert only numbers." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } else { bool repeat = true; return repeat; } } public static bool checkIntInput(string input) // Validate int inputs { string trimInput = input.Trim(); if (!checkInput(trimInput)) { try { int number = int.Parse(trimInput); if (number != 0) // the user can't insert 0 { bool repeat = false; return repeat; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("A value of 0 is not accepted." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You can insert only numbers." + Environment.NewLine); bool repeat = true; return repeat; } } else { bool repeat = true; return repeat; } } public static bool checkStringInput(string input) //validate string inputs { string trimInput = input.Trim(); if (!checkInput(trimInput)) { if (trimInput.All(Char.IsLetter)) { bool repeat = false; return repeat; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You can insert only letters." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } else { bool repeat = true; return repeat; } } public static double spaceAvailable() // returns the space available in the marina berth { int maxSpace = 150; var recordList = readList(); double sum = 0; foreach (var item in recordList) { sum = sum + item.getLength(); } double spaceAvailable = maxSpace - sum; return spaceAvailable; } public static void checkBoatLength(double lenght) //check the lenght of the boat and if it is too big go back to the main menu { int maxLength = 15; if (lenght > maxLength) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("We are sorry but the boat is too long. Press enter to go back to the main menu"); MarinaTools.goBackMainMenu(); } } public static void checkBoatDraft(double draft) //check the draft of the boat and if it is over tha max go back to the main menu { int maxDraft = 5; if (draft > maxDraft) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("We are sorry but the boat is too deep. Press enter to go back to the main menu"); MarinaTools.goBackMainMenu(); } } public static bool checkBoatType(string input) // method to validate boat type entered by the user { string trimInput = input.Trim(); if (!checkInput(trimInput)) { if (trimInput.All(Char.IsLetter)) { string lowInputBoatType = input.ToLower(new CultureInfo("en-US", false)); char boatTypeLetter = lowInputBoatType[0]; if (boatTypeLetter == 'n' || boatTypeLetter == 's' || boatTypeLetter == 'm') // the user input has to be on of these char { bool repeat = false; return repeat; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Insert a valid boat type. Try again." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You can insert only letters." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.White; bool repeat = true; return repeat; } } else { bool repeat = true; return repeat; } } } }
// <copyright file="EdgeFactory.cs">Copyright ? 2018</copyright> using System; using Microsoft.Pex.Framework; using QuickGraph; namespace QuickGraphTest.Factories { /// <summary>A factory for QuickGraph.Edge`1[System.String] instances</summary> public static partial class EdgeFactory { /// <summary>A factory for QuickGraph.Edge`1[System.Int32] instances</summary> [PexFactoryMethod(typeof(Edge<int>))] public static Edge<int> Create(int source_i, int target_i1) { PexAssume.IsTrue(source_i != target_i1); Edge<int> edge = new Edge<int>(source_i, target_i1); return edge; // TODO: Edit factory method of Edge`1<Int32> // This method should be able to configure the object in all possible ways. // Add as many parameters as needed, // and assign their values to each field by using the API. } } }
namespace CarWash.Bot.States { /// <summary> /// User Profile state type. /// </summary> public class UserProfile { /// <summary> /// Gets or sets user display friendly name. /// </summary> /// <value> /// User display friendly name. /// </value> public string NickName { get; set; } /// <summary> /// Gets or sets the user's ID within the CarWash API. /// </summary> /// <value> /// The <see cref="ClassLibrary.Models.User"/>'s ID within the CarWash API. /// </value> public string CarwashUserId { get; set; } /// <summary> /// Gets or sets a value indicating whether a welcome message was already sent to the chat. /// </summary> /// <value> /// True if a welcome message was already sent to the chat. /// </value> public bool IsWelcomeMessageSent { get; set; } = false; } }
using System; namespace DipDemo.Cataloguer.Infrastructure.Presentation { public interface IView { void ShowView(); void ShowModalView(); void CloseView(); event EventHandler Closed; } }
//Problem 21. Letters count //Write a program that reads a string from the console and prints all different letters in the string along with information how many times each letter is found. using System; namespace Problem21LettersCount { class LettersCount { static void Main() { int size = ('z' - 'a') + 1; Console.WriteLine("Enter text: "); string input = Console.ReadLine(); int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = 0; } input = input.ToLower(); foreach (char ch in input) { if (Char.IsLetter(ch)) { arr[ch - 'a']++; } } for (int i = 0; i < size; i++) { if (arr[i] != 0) { Console.WriteLine("Letter '{0}' -> {1} time(s)", (char)(i + 'a'), arr[i]); } } } } }
using FluentAssertions; using FluentAssertions.Execution; using NUnit.Framework; using System.Linq; namespace AppSettingsGenerator.Tests { class ConfigGeneratorNLogTests { private ConfigGenerator _configGenerator; [SetUp] public void SetUp() { _configGenerator = new ConfigGenerator(); } [Test] public void Generate_() { using var assertionScope = new AssertionScope(); var (generated, _) = _configGenerator.Generate("NLog.json"); generated.Select(x => x.fileName).Should().ContainSingle(x => x == "extensions.cs"); var appsettings = generated.FirstOrDefault(x => x.fileName == "AppSettings.cs"); appsettings.generatedClass.Should().Contain("public NLog NLog { get; set; }"); var (compilationResult, reason) = new TestCodeCompiler().Compile(generated.Select(x => x.generatedClass)); compilationResult.Should().BeTrue(); reason.Should().BeEmpty(); } } }
namespace PDV.DAO.Entidades.Estoque.InventarioEstoque { public class ItemInventario { public decimal IDItemInventario { get; set; } public decimal IDInventario { get; set; } public decimal IDAlmoxarifado { get; set; } public decimal IDProduto { get; set; } public decimal Quantidade { get; set; } public ItemInventario() { } } }
namespace Contoso.Bsl.Business.Responses { public class ErrorResponse : BaseResponse { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TourApi.Models; namespace TourApi.Repos { public interface IClientsRepository { Task<Client> Get(Guid id); Task<List<Client>> GetAll(); Task<Client> Create(Client client); void Delete(Guid id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Events { class Program { static void Main(string[] args) { /*Eventy - jak plakaty na słupie informacyjnym Odbiorcy dostają informację, że coś się wydarzyło i reagują na to zdarzenie (event). Tworzymy niezależne aplikacje blokowe, gdzie jeden blok nie zależy od drugiego. Komunikują się pomiędzy sobą zdarzeniami. Zmieniając coś w jednym bloku, nie zmieniamy w drugim, dlatego że event w jednym bloku tylko się podnosi, a drugi tylko na niego reaguje. Mamy luźne połączenie pomiędzy blokami kodu. Tu: symulujemy to AgendaManagerem i SMSSenderem. */ AgendaManager amgr = new AgendaManager(); SMSSender sms = new SMSSender(); //sms oczekuje, że jak się coś pojawi, to on coś zrobi amgr.AddedAgenda += sms.OnAddedAgenda; amgr.AddAgenda(new Agenda() { AgendaDate = DateTime.Now.AddDays(2), AgendaName = "Kubuś Puchatek i złote gatki" }); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EventsEntityFrmVs.Models { public class CommentModel { public int Id { get; set; } public string Text { get; set; } public DateTime? Date { get; set; } public virtual EventModel Event { get; set; } public int EventId { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using Ego.PDF.Data; using Ego.PDF.PHP; namespace Ego.PDF { public static class FPdfExtensions { public static string Output(this FPdf document, string name, OutputDevice destination) { // Output PDF to some destination if (document.State < 3) { document.Close(); } if (destination == OutputDevice.Default) { if (string.IsNullOrEmpty(name)) { name = "doc.pdf"; destination = OutputDevice.StandardOutput; } else { destination = OutputDevice.SaveToFile; } } switch (destination) { case OutputDevice.StandardOutput: HttpContext.Current.Response.AppendHeader("Content-Type: application/pdf", ""); HttpContext.Current.Response.AppendHeader("Content-Disposition: inline; filename=\"" + name + "\"", ""); HttpContext.Current.Response.AppendHeader("Cache-Control: private, max-age=0, must-revalidate", ""); HttpContext.Current.Response.AppendHeader("Pragma: public", ""); HttpContext.Current.Response.Write(document.Buffer); break; case OutputDevice.Download: // Download file HttpContext.Current.Response.AppendHeader("Content-Type: application/x-download", ""); HttpContext.Current.Response.AppendHeader( "Content-Disposition: attachment; filename=\"" + name + "\"", ""); HttpContext.Current.Response.AppendHeader("Cache-Control: private, max-age=0, must-revalidate", ""); HttpContext.Current.Response.AppendHeader("Pragma: public", ""); HttpContext.Current.Response.Write(document.Buffer); break; case OutputDevice.SaveToFile: // Save to local file FileStream f = FileSystemSupport.FileOpen(name, "wb"); if (!TypeSupport.ToBoolean(f)) { throw new InvalidOperationException( "Unable to create output file: " + name); } var writer = new StreamWriter(f, FPdf.PrivateEncoding); writer.Write(document.Buffer); writer.Close(); break; case OutputDevice.ReturnAsString: return document.Buffer; default: throw new InvalidOperationException("Incorrect output destination: " + destination); break; } return string.Empty; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ReGame : MonoBehaviour { [SerializeField] private AudioSource ButtonSE; void Start() { FadeManager.FadeIn(); } bool isCalledOnce = false; public void OnClickStartButton() { if (!isCalledOnce) { ButtonSE.PlayOneShot(ButtonSE.clip); isCalledOnce = true; FadeManager.FadeOut(4); Debug.Log("GameSceneへ"); } } }
using CapstoneTravelApp.DatabaseTables; using SQLite; using System; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CapstoneTravelApp.LodgingFolder { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LodgingNotesPage : ContentPage { private SQLiteConnection conn; private Lodging_Table lodging; public LodgingNotesPage(Lodging_Table _currentLodging) { InitializeComponent(); lodging = _currentLodging; conn = DependencyService.Get<ITravelApp_db>().GetConnection(); Title = $"{lodging.LodgeName}" + " Notes"; courseNotesEditor.Text = $"{lodging.LodgeNotes}"; } private async void MenuButton_Clicked(object sender, EventArgs e) { var action = await DisplayActionSheet("Options", "Cancel", null, "Save Notes", "Share Notes"); if (action == "Save Notes") { lodging.LodgeNotes = courseNotesEditor.Text; conn.Update(lodging); await DisplayAlert("Notice", "Lodging Notes Saved", "Ok"); await Navigation.PopModalAsync(); } else if (action == "Share Notes") { await Share.RequestAsync(new ShareTextRequest { Text = courseNotesEditor.Text + "\n" + "Record updated at: " + DateTime.Now.ToString("MM/dd/yy HH:mm tt") }); } } } }
using Microsoft.Azure.Management.Resources.Models; using System; using System.Threading.Tasks; namespace Microsoft.CortanaAnalytics.SolutionAccelerators.Shared { interface IProvision { /// <summary> /// Submits a deployment request for the ARM Template /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="resourceGroup">The resource group name.</param> /// <param name="json">Json object that contains the Template and Parameters</param> /// <param name="token">The token for authorization</param> /// <returns>DeploymentResult</returns> DeploymentResult DeployTemplate(string subscriptionId, string resourceGroup, Json json, string token); /// <summary> /// Monitor the progress of the deplyment operations for submitted ARM template /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="resourceGroup">The resource group name.</param> /// <param name="correlationId">The guid that was generated calling DeployTemplate</param> /// <param name="token">The token for authorization</param> /// <returns>DeploymentResult</returns> Task<DeploymentOperationsGetResult[]> DeploymentStatusAsync(string subscriptionId, string resourceGroup, Guid correlationId, string token); } }
using System; namespace Aut.Lab.lab10 { public class Circle { private Point point1 = null; private Point point2 = null; public Circle(Point p1,Point p2) { point1 = p1; point2 = p2; } public double Radius() { double pow = Math.Pow(point1.X - point2.X,2) + Math.Pow(point1.Y - point2.Y,2); double sumra = Math.Sqrt(pow); return(sumra); } public double Area(double ra) { double pow = Math.Pow(ra,2); double area = 3.14 * pow; return(area); } public double CircleLength(double ra) { double length = 2 * 3.14 * ra; return(length); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WeaponBullet : MonoBehaviour { public float speed = 20f; public Rigidbody2D rb; public GameObject bullet; public int damage = 30; // Use this for initialization void Start () { rb.velocity = transform.right * speed; } private void OnTriggerEnter2D(Collider2D hitInfo) { PlayerHealth playerHealth = hitInfo.GetComponent<PlayerHealth>(); Debug.Log("We hit " + hitInfo.name); if (hitInfo.tag == "player") { playerHealth.takendamage(damage); } DestroyObject(gameObject); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using Newtonsoft.Json; #endregion namespace Dnn.PersonaBar.SiteSettings.Services.Dto { public class UpdateBasicSearchSettingsRequest { public int MinWordLength { get; set; } public int MaxWordLength { get; set; } public bool AllowLeadingWildcard { get; set; } public string SearchCustomAnalyzer { get; set; } public int TitleBoost { get; set; } public int TagBoost { get; set; } public int ContentBoost { get; set; } public int DescriptionBoost { get; set; } public int AuthorBoost { get; set; } } }
using System; public class EpochTools { /// <summary> /// Return a convenient string representation for folder/file name, /// Format : yyyy_MM_dd-HH_mm_ss /// </summary> /// <param name="epoch">epoch date (number milliseconds since 1.1.1970)</param> /// <returns>a sortable representation of the date, to be used for a folder/file name</returns> public static string ConvertEpochToSortableDateTimeString(long epoch) { var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(epoch); return String.Format("{0:yyyy_MM_dd-HH_mm_ss}", dateTime); } /// <summary> /// Return a convenient string representation for displaying a date to users, /// Format : dddd dd.MM.yyyy /// </summary> /// <param name="epoch">epoch date (number milliseconds since 1.1.1970)</param> /// <returns>a human readable representation of the date (not the time)</returns> public static string ConvertEpochToHumanReadableDate(long epoch) { var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(epoch); return String.Format(new System.Globalization.CultureInfo("fr-FR"), "{0:dddd dd.MM.yyyy}", dateTime); } /// <summary> /// Return a convenient string representation for displaying a time to users, /// Format : HH:mm /// </summary> /// <param name="epoch">epoch date (number milliseconds since 1.1.1970)</param> /// <returns>a human readable representation of the time</returns> public static string ConvertEpochToHumanReadableTime(long epoch, bool localTime = false) { var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(epoch); if (localTime) dateTime = TimeZone.CurrentTimeZone.ToLocalTime(dateTime); return String.Format("{0:HH:mm}", dateTime); } /// <summary> /// Return a convenient string representation for displaying a duration to users, /// Format : xh xm /// </summary> /// <param name="ms">duration in milliseconds</param> /// <returns>a human readable representation of a duration</returns> public static string ConvertDurationToHumanReadableString(long ms) { TimeSpan t = TimeSpan.FromMilliseconds(ms); return string.Format("{0:D2}h {1:D2}m", t.Hours, t.Minutes); } }
using System; using System.Collections.Generic; namespace Matrizes { class Program { static void Main(string[] args) { int[,] matriz = LerDados(); ImprimeMatriz(matriz); ImprimeDiagonal(matriz); ContaNegativos(matriz); } public static int[,] LerDados() { Console.Write("Informe um número de ordem para a matriz: "); int n = int.Parse(Console.ReadLine()); Console.WriteLine(); int[,] matriz = new int[n, n]; for (int i = 0; i < n; i++) { Console.WriteLine($"{i + 1}° LINHA:"); for (int j = 0; j < n; j++) { Console.Write($"{i + 1}° coluna: "); matriz[i, j] = int.Parse(Console.ReadLine()); } Console.Clear(); } return matriz; } public static void ImprimeMatriz(int[,] matriz) { int n = matriz.GetLength(0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(matriz[i, j] + " "); } Console.WriteLine(); } Console.WriteLine(); } public static void ImprimeDiagonal(int[,] matriz) { int n = matriz.GetLength(0); int[] diagonal = new int[3]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { diagonal[i] = matriz[i, j]; } } } Console.Write("Diagonal principal: "); for (int i = 0; i < diagonal.Length; i++) { Console.Write(diagonal[i] + " "); } Console.WriteLine(); } public static void ContaNegativos(int[,] matriz) { int n = matriz.GetLength(0); List<int> negativos = new List<int>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matriz[i, j] < 0) { negativos.Add(matriz[i, j]); } } } Console.Write($"Números negativos: {negativos.Count}"); Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace prjSellor.Models { public class Schedule { [Key, Column(Order = 0)] public string userName { get; set; } [Key, Column(Order = 1)] public DateTime startDate { get; set; } public DateTime endDate { get; set; } } }
using System; namespace Game.Difficult { public class BotDifficult { public float DamageMultiplier { get; } public float BlasterReloadDelay { get; } public float MissileReloadDelay { get; } public float ScoreMultiplier { get; } public static DifficultRate DifficultRate; public BotDifficult(DifficultRate difficultRate) { DifficultRate = difficultRate; switch (difficultRate) { case DifficultRate.Easy: DamageMultiplier = 1.0f; BlasterReloadDelay = 1.0f; MissileReloadDelay = 2f; ScoreMultiplier = 1.0f; break; case DifficultRate.Medium: DamageMultiplier = 0.9f; BlasterReloadDelay = 1.2f; MissileReloadDelay = 2.5f; ScoreMultiplier = 1.2f; break; case DifficultRate.Hard: DamageMultiplier = 0.8f; BlasterReloadDelay = 1.5f; MissileReloadDelay = 3f; ScoreMultiplier = 1.5f; break; default: throw new ArgumentOutOfRangeException(nameof(difficultRate), difficultRate, null); } } } public enum DifficultRate { Easy, Medium, Hard } }
using System.Collections.Generic; public class Garage { public Garage() { this.ParkedCars = new List<int>(); } public List<int> ParkedCars { get; set; } }
using System; using NUnit.Framework; namespace Tasks.Tests { [TestFixture()] public class TestUQueue { [Test] public void TestEmpty() { var q = new UQueue(); Assert.Throws( typeof(InvalidOperationException), delegate { q.Peek(); } ); Assert.Throws( typeof(InvalidOperationException), delegate { q.Dequeue(); } ); } [TestCase()] public void TestEnqueueDequeue(params object[] args) { var q = new UQueue(); for (int i = 0; i < args.Length; ++i) { q.Enqueue(args[i]); Assert.AreEqual(q.Count, i + 1); } for (int i = 0; i < args.Length; ++i) { Assert.AreEqual(args[i], q.Dequeue()); Assert.AreEqual(q.Count, args.Length - i - 1); } } } }
using OmniSharp.Extensions.JsonRpc.Testing; namespace Lsp.Integration.Tests.Fixtures { public interface IConfigureLanguageProtocolFixture { JsonRpcTestOptions Configure(JsonRpcTestOptions options); } }
using AuthAutho.Areas.Identity.Data; using AuthAutho.Data; using AuthAutho.Extensions; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AuthAutho.ConfigureStartup { public static class IdentityConfig { public static IServiceCollection AddAuthorizationConfigIdentity(this IServiceCollection services) { //Adicionando configuração para utilização de clains padrão que a microsift recomenda services.AddAuthorization(options => { options.AddPolicy("PodeExcluir", policy => policy.RequireClaim("PodeExcluir")); options.AddPolicy("PodeLer", policy => policy.Requirements.Add(new PermissaoNecessaria("PodeLer"))); options.AddPolicy("PodeEscrever", policy => policy.Requirements.Add(new PermissaoNecessaria("PodeEscrever"))); }); return services; } public static IServiceCollection AddIdentityConfig(this IServiceCollection services, IConfiguration configuration) { //Configurando o identity services.AddDbContext<AuthDbContext>(options => options.UseSqlServer( configuration.GetConnectionString("AuthDbContextConnection"))); services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>()//Necessario adicionar para trabalhar com roles .AddEntityFrameworkStores<AuthDbContext>(); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.DataContracts.Cashbag { public class ReadyAccountDto { /// <summary> /// 现金账户余额 /// </summary> public decimal ReadyBalance { get; set; } /// <summary> /// 冻结金额 /// </summary> public decimal FreezeAmount { get; set; } /// <summary> /// 账户总额 /// </summary> public decimal TotalBalance { get { return ReadyBalance + FreezeAmount; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PasswordPolicy.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace CGI.Reflex.Core.Utilities { public static class PasswordPolicy { private static readonly Regex ReValidate = new Regex(@"((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})", RegexOptions.CultureInvariant | RegexOptions.Compiled); public static bool Validate(string clearPassword) { if (string.IsNullOrEmpty(clearPassword)) return false; return ReValidate.IsMatch(clearPassword); } } }
using MrHai.Application; using MrHai.Application.Models; using MrHai.BMS.Controllers.Base; using MrHai.BMS.Controllers.Common.Funtion; using MrHai.BMS.Models.Work; using MrHai.Core.Models; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Web; using System.Web.Mvc; using TwinkleStar.Common; namespace MrHai.BMS.Controllers { [Export] public class MainArticleController : BaseController { [Import] public IMrHaiApplication MrHaiApplication { get; set; } // GET: Article // GET: MainArticle public ActionResult Index() { string workName = Request.Form["txtWorkName"] == null ? "" : Request.Form["txtWorkName"].Trim(); var list = MrHaiApplication.GetInfoByPid("3").AppendData as List<Infomation> ?? new List<Infomation>(); List<WorkViewModel> modelList = new List<WorkViewModel>(); foreach (var item in list) { WorkViewModel entity = new WorkViewModel(); entity.name = item.Title; entity.content = item.Content; entity.infoID = item.Id; modelList.Add(entity); } ViewBag.modelList = modelList; return View(); } public ActionResult New(string id) { viewAddModel model = new viewAddModel(); if (!string.IsNullOrEmpty(id)) { var dbModel = MrHaiApplication.GetInfo(id).AppendData as Infomation; var caModel = MrHaiApplication.GetCategory(dbModel.CategoryId)?.AppendData as Category ?? new Category(); model.content = dbModel.Content; model.title = dbModel.Title; model.workId = dbModel.CategoryId; model.workName = caModel.Name; model.cdID = caModel.ParentId; model.infoID = dbModel.Id; } ViewBag.model = model; return View(); } [HttpPost] public ActionResult Add() { var data = Request.GetPostBody<viewAddModel>(); if (string.IsNullOrEmpty(data.infoID))//新增 { data.infoType = InfomationType.MainArtistCV; data.userID = UserID; data.workId = "3"; data.userID = UserID; AddEWC tool = new AddEWC(MrHaiApplication); return Json(tool.CommonAdd(data)); } else//更新 { data.infoType = InfomationType.MainArtistCV; data.userID = UserID; data.workId = "3"; data.userID = UserID; AddEWC tool = new AddEWC(MrHaiApplication); return Json(tool.CommonUpdate(data)); } } public ActionResult Delete(string id) { AddEWC tool = new AddEWC(MrHaiApplication); return JsonBase(tool.CommonDelete(id)); } } }
using CMS_Database.Entities; using CMS_Database.Interfaces; using CMS_Database.Repositories; using CMS_ShopOnline.Areas.Administration.Models; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using WebMatrix.WebData; namespace CMS_ShopOnline.Areas.Administration.Controllers { public class UserController : Controller { private readonly INhanVien _NhanVien = new NhanVienRepository(); private readonly IPhanQuyen _PhanQuyen = new PhanQuyenRepository(); private readonly IListController _ListController = new ListControllerRepository(); private readonly ILoaiNV _LoaiNV = new LoaiNVRepository(); // GET: CMS_Sale/NhanVien public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(LoginViewModel login) { if (ModelState.IsValid) { //int Id = WebSecurity.GetUserId(login.Username); //để update tạo tài khoản bool IsAu = WebSecurity.Login(login.Username, login.Password,false); if (IsAu) { var user = _NhanVien.GetByUserName(login.Username); if(user.SLDNSai >= 5 || user.IsDelete == true) { ModelState.AddModelError("", "Tài khoản bị khóa.Vui lòng liên hệ quản lí!!!"); return View(login); } else { HttpContext.Application["TaiKhoanLogin"] = user.TenTaiKhoan.ToLower(); return RedirectToAction("Index", "Home",new { area ="CMS_Sale"}); } } else { var user = _NhanVien.GetByUserName(login.Username); if(user == null) { ModelState.AddModelError("", "User name hoặc password không chính xác."); return View(login); } else { ModelState.AddModelError("", "Mật khẩu không chính xác."); user.SLDNSai = user.SLDNSai+1; _NhanVien.Update(user); _NhanVien.Save(); return View(login); } } } return View(); } public ActionResult LogOff() { Helpers.Helper.CurrentUser = null; WebSecurity.Logout(); HttpContext.Application.Contents.Remove("TaiKhoanLogin"); HttpContext.Application.Contents.Remove("ListRequest"); return RedirectToAction("Login", "User", new { @area = "Administration" }); } [Authorize] public ActionResult NotPage() { return View(); } } }
using HardwareInventoryManager.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Diagnostics; using System.Linq; using System.Web; namespace HardwareInventoryManager { public class CustomApplicationDbContext : ApplicationDbContext { public CustomApplicationDbContext() : base() { } public override int SaveChanges() { SetCreatedModifiedDates(); return base.SaveChanges(); } private void SetCreatedModifiedDates() { var entries = this.ChangeTracker.Entries().Where(t => t.State == EntityState.Modified || t.State == EntityState.Added); var currentTime = DateTime.Now; foreach (var entry in entries) { var entityBase = entry.Entity as ModelEntity; if (entityBase != null) { if (entry.State == EntityState.Added && (entityBase.CreatedDate == DateTime.MinValue || entityBase.CreatedDate == null)) { entityBase.CreatedDate = currentTime; } entityBase.UpdatedDate = currentTime; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace GetSetGo.Models { public class VehicleType { [Required] [Range(1,int.MaxValue, ErrorMessage = "Id should be greater than or equal to 1" )] [VehicleTypeIdIdentity] public byte Id { get; set; } [Required] public string Name { get; set; } public static readonly byte Bicycle = 1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ISKlinike { public class Validator { public const string povratnaPoruka = "Obavezno polje!"; public const string poruka = "Unos mora biti u metrima!"; public static bool ValidirajUnos(TextBox txt,ErrorProvider err, string poruka) { if(string.IsNullOrEmpty(txt.Text)) { err.SetError(txt, poruka); return false; } err.Clear(); return true; } } }
using System.Drawing; using System.Windows.Forms; namespace PDV.UTIL.Components.Custom { public class DataGridViewCheckBoxColumnHeaderCell : DataGridViewColumnHeaderCell { private Rectangle CheckBoxRegion; private bool checkAll = false; protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); graphics.FillRectangle(new SolidBrush(Color.Transparent), cellBounds); CheckBoxRegion = new Rectangle((cellBounds.Width / 2) - 5, cellBounds.Location.Y + 2, 14, cellBounds.Size.Height); if (checkAll) ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked); else ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal); //Rectangle normalRegion = new Rectangle(cellBounds.Location.X + 1 + 25, cellBounds.Location.Y, cellBounds.Size.Width - 26, cellBounds.Size.Height); //graphics.DrawString(value.ToString(), cellStyle.Font, new SolidBrush(cellStyle.ForeColor), normalRegion); } protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { Rectangle rec = new Rectangle(new Point(0, 0), CheckBoxRegion.Size); checkAll = !checkAll; if (rec.Contains(e.Location)) DataGridView.Invalidate(); base.OnMouseClick(e); } public bool CheckAll { get { return checkAll; } set { checkAll = value; } } } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace NtApiDotNet { /// <summary> /// Implements a UnicodeString which contains raw bytes. /// </summary> public class UnicodeStringBytesSafeBuffer : SafeStructureInOutBuffer<UnicodeStringOut> { private UnicodeStringBytesSafeBuffer() : base(IntPtr.Zero, 0, false) { } /// <summary> /// Constructor. /// </summary> /// <param name="ba">The bytes for the name.</param> public UnicodeStringBytesSafeBuffer(byte[] ba) : base(ba.Length, true) { Data.WriteBytes(ba); Result = new UnicodeStringOut { Length = (ushort)ba.Length, MaximumLength = (ushort)ba.Length, Buffer = Data.DangerousGetHandle() }; } /// <summary> /// Get a null safe buffer. /// </summary> public static new UnicodeStringBytesSafeBuffer Null => new UnicodeStringBytesSafeBuffer(); } }