text stringlengths 13 6.01M |
|---|
using iTextSharp.text;
using iTextSharp.text.pdf;
using SVN.Pdf.Enums;
namespace SVN.Pdf.Components
{
public class SvnText : SvnCell
{
private string Text { get; }
private float Size { get; }
private VAlign VerticalAlignment { get; }
private HAlign HorizontalAlignment { get; }
private int ElementAlignmentV
{
get
{
switch (this.VerticalAlignment)
{
case VAlign.Bottom:
return Element.ALIGN_BOTTOM;
case VAlign.Middle:
return Element.ALIGN_MIDDLE;
case VAlign.Top:
default:
return Element.ALIGN_TOP;
}
}
}
private int ElementAlignmentH
{
get
{
switch (this.HorizontalAlignment)
{
case HAlign.Right:
return Element.ALIGN_RIGHT;
case HAlign.Center:
return Element.ALIGN_CENTER;
case HAlign.Left:
default:
return Element.ALIGN_LEFT;
}
}
}
private BaseFont BaseFont
{
get => BaseFont.CreateFont(@"C:\Windows\Fonts\Calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
internal SvnText(SvnCell parent, string text, float size, VAlign vAlign, HAlign hAlign, BaseColor background, BaseColor foreground, SvnBorder border)
{
base.Parent = parent;
base.Background = background;
base.Foreground = foreground;
base.Border = border;
this.Text = text;
this.Size = size;
this.VerticalAlignment = vAlign;
this.HorizontalAlignment = hAlign;
}
public override PdfPTable Build()
{
var table = new PdfPTable(100)
{
WidthPercentage = 100,
};
table.AddCell(new PdfPCell(new Paragraph(this.Text, new Font(this.BaseFont, this.Size, default(int), base.Foreground)))
{
Colspan = 100,
FixedHeight = base.AbsoluteHeight(),
VerticalAlignment = this.ElementAlignmentV,
HorizontalAlignment = this.ElementAlignmentH,
BackgroundColor = base.Background,
BorderWidthTop = base.BorderWidthTop,
BorderWidthRight = base.BorderWidthRight,
BorderWidthBottom = base.BorderWidthBottom,
BorderWidthLeft = base.BorderWidthLeft,
BorderColor = base.BorderColor,
});
return table;
}
}
} |
using System;
using System.Collections.Generic;
using System.Windows.Input;
using MusicPlayer.Core.Models;
using MusicPlayer.Core.Players.Interfaces;
using MusicPlayer.Core.SongFilesManager.Interfaces;
using MusicPlayer.Microsoft;
using MusicPlayer.ViewModels.Interfaces;
namespace MusicPlayer.ViewModels
{
public partial class SongsViewModel : ViewModelBase, ISongsViewModel
{
private readonly ISongFilesManager _songFilesManager;
private readonly IMp3Player _mp3Player;
public SongsViewModel(ISongFilesManager songFilesManager, IMp3Player mp3Player)
{
_songFilesManager = songFilesManager;
_mp3Player = mp3Player;
UpdateAllSongsList();
_mp3Player.OnSongChange += songIndex => { RaisePropertyChanged("SelectedIndex"); };
}
public void UpdateAllSongsList()
{
Songs = _songFilesManager.ReadSongsFromFile();
}
public void UpdatePlaylistSongs(Playlist playlist)
{
Songs = playlist.List;
RaisePropertyChanged("Songs");
}
public void PassSongsToPlayer(Song selectedSong)
{
List<Song> tempList = new List<Song>();
tempList.AddRange(Songs);
tempList.Remove(selectedSong);
tempList.Insert(0, selectedSong);
_mp3Player.SongList = tempList;
}
public void PlaySelectedSong()
{
_mp3Player.Play();
}
public int SelectedIndex
{
get { return _mp3Player.CurrentSongIndex; }
}
}
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using SearchFood.Navigation;
using SearchFood.SearchFoodServiceReference;
using SearchFood.Model;
using Windows.UI.Xaml;
namespace SearchFood.ViewModel
{
public class AccountViewModel : ViewModelBase
{
private Utilisateur _utilisateur;
private Historique _historique;
private Restaurant _restaurant;
private Categorie _categorie;
private Type_Cuisine _typeCuisine;
private string _nomRestaurant;
private string _categorieRestaurant;
private string _typeCuisineRestaurant;
private List<Historique> _historiques;
private Restaurant restaurant;
private List<Restaurant> _historiqueRestaurant;
private INavigationService _navigationService;
private Services _service;
public ObservableCollection<HistoriquesModel> Historiqueslist
{
get { return _historiqueslist; }
set
{
_historiqueslist = value;
RaisePropertyChanged();
}
}
private ObservableCollection<HistoriquesModel> _historiqueslist = new ObservableCollection<HistoriquesModel>();
public ICommand GoBackButton { get; set; }
public AccountViewModel(INavigationService navigation)
{
_navigationService = navigation;
_service = new Services();
Historiques = new List<Historique>();
HistoriqueRestaurant = new List<Restaurant>();
GoBackButton = new RelayCommand(GoBack);
_utilisateur = ((App)(Application.Current)).UserConnected;
InithistoriqueList();
}
private async void InitHistorique()
{
_historiques = await _service._historique.GetHistoriqueByUser(((App)(Application.Current)).UserConnected.Id_Utilisateur);
foreach (Historique histo in _historiques)
{
restaurant = await _service._restaurants.GetRestaurants(histo.Id_Restaurant);
_historiqueRestaurant.Add(restaurant);
Restaurant = restaurant;
Historique = histo;
Categorie = await _service._categories.GetCategorie(restaurant.Id_Categorie);
CategorieRestaurant = Categorie.Nom_Categorie;
Type_Cuisine = await _service._typesCuisines.GetTypeCuisine(restaurant.Id_Type_Cuisine);
Type_CuisineRestaurant = Type_Cuisine.Type_Cuisine1;
}
}
private async void InithistoriqueList()
{
_historiqueslist = new ObservableCollection<HistoriquesModel>();
_historiques = new List<Historique>();
_historiques = await _service._historique.GetHistoriqueByUser(((App)(Application.Current)).UserConnected.Id_Utilisateur);
foreach (Historique histo in _historiques)
{
restaurant = await _service._restaurants.GetRestaurants(histo.Id_Restaurant);
_historiqueRestaurant.Add(restaurant);
Restaurant = restaurant;
Historique = histo;
Categorie = await _service._categories.GetCategorie(restaurant.Id_Categorie);
CategorieRestaurant = Categorie.Nom_Categorie;
Type_Cuisine = await _service._typesCuisines.GetTypeCuisine(restaurant.Id_Type_Cuisine);
Type_CuisineRestaurant = Type_Cuisine.Type_Cuisine1;
HistoriquesModel historiqueModel = new HistoriquesModel{Date = histo.Date.ToString().Substring(0, 10), NomRestaurant = restaurant.Nom, TypeCuisine = Type_CuisineRestaurant, Categorie = CategorieRestaurant};
_historiqueslist.Add(historiqueModel);
}
}
#region Getter / Setter MVVM
public Utilisateur Utilisateur
{
get { return _utilisateur; }
set { _utilisateur = value; RaisePropertyChanged(); }
}
public Restaurant Restaurant
{
get { return _restaurant; }
set { _restaurant = value; RaisePropertyChanged(); }
}
public Historique Historique
{
get { return _historique; }
set { _historique = value; RaisePropertyChanged(); }
}
public Categorie Categorie
{
get { return _categorie; }
set { _categorie = value; RaisePropertyChanged(); }
}
public Type_Cuisine Type_Cuisine
{
get { return _typeCuisine; }
set { _typeCuisine = value; RaisePropertyChanged(); }
}
public string NomRestaurant
{
get { return _nomRestaurant; }
set { _nomRestaurant = value; RaisePropertyChanged(); }
}
public string CategorieRestaurant
{
get { return _categorieRestaurant; }
set { _categorieRestaurant = value; RaisePropertyChanged(); }
}
public string Type_CuisineRestaurant
{
get { return _typeCuisineRestaurant; }
set { _typeCuisineRestaurant = value; RaisePropertyChanged(); }
}
public List<Historique> Historiques
{
get { return _historiques; }
set { _historiques = value; RaisePropertyChanged(); }
}
public List<Restaurant> HistoriqueRestaurant
{
get { return _historiqueRestaurant; }
set { _historiqueRestaurant = value; RaisePropertyChanged(); }
}
#endregion
public void GoBack()
{
_navigationService.GoBack();
}
}
}
|
using System;
using Mono.VisualC.Interop;
using Mono.VisualC.Interop.ABI;
namespace Qt.Gui {
public class QPaintDevice : ICppObject {
#region Sync with qpaintdevice.h
// C++ interface
public interface IQPaintDevice : ICppClassOverridable<QPaintDevice> {
[Virtual] int devType (CppInstancePtr @this);
[Virtual] /*QPaintEngine */ IntPtr paintEngine (CppInstancePtr @this); // abstract
//...
void QPaintDevice (CppInstancePtr @this);
[Virtual] int metric (CppInstancePtr @this, /*PaintDeviceMetric*/ IntPtr metric);
}
// C++ fields
private struct _QPaintDevice {
public ushort painters;
}
#endregion
private static IQPaintDevice impl = Qt.Libs.QtGui.GetClass<IQPaintDevice,_QPaintDevice,QPaintDevice> ("QPaintDevice");
public CppInstancePtr Native { get; protected set; }
public QPaintDevice (IntPtr native)
{
Native = native;
}
internal QPaintDevice (CppTypeInfo subClass)
{
subClass.AddBase (impl.TypeInfo);
}
public void Dispose ()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootingController : MonoBehaviour {
public List<Transform> cannonTips;
public Transform cannon;
public Animator cannonAnimator;
public Transform cannonMount;
public float cannonMovementSpeed = 0.1f;
public GameObject target;
public SpriteRenderer crosshair;
private Transform lastUsedTip;
public void Update(){
updateRotation ();
crosshair.transform.position = Vector2.Lerp (crosshair.transform.position, target.transform.position, 30.0f * Time.deltaTime);
}
public Transform getNextTip() {
if (!lastUsedTip) {
lastUsedTip = cannonTips [0];
return lastUsedTip;
}
int next = (cannonTips.IndexOf (lastUsedTip) + 1) % cannonTips.Count;
lastUsedTip = cannonTips [next];
Debug.Log (next);
return lastUsedTip;
}
private void updateRotation(){
if (target) {
Vector3 enemyPosition = target.transform.position;
Vector3 stationPosition = cannonMount.position;
//crosshair.transform.position = enemyPosition;
Vector3 direction = enemyPosition - stationPosition;
Vector3 upVector = Vector3.up;
//check if on the right, then rotate in the other direction
float inverseDirection = 1.0f;
if (direction.x > 0) {
inverseDirection = -1.0f;
}
float angle = Vector3.Angle (upVector, direction);
//the pivot point is set when importing the sprite
Quaternion rotation = Quaternion.AngleAxis (angle * inverseDirection, new Vector3 (0, 0, 1));
cannon.rotation = Quaternion.Lerp(cannon.rotation, rotation, cannonMovementSpeed * Time.deltaTime);
}
}
public bool isRecharging(){
return cannonAnimator.GetBool ("recharging");
}
public void shoot(){
cannonAnimator.SetBool ("recharging", true);
}
public void didRecharge(){
cannonAnimator.SetBool ("recharging", false);
}
}
|
using Hosting = Microsoft.Extensions.Hosting;
namespace PasswordCheck.Tests
{
public class TestFixture
{
public readonly Hosting.IHost Host;
public TestFixture()
{
Host = Hosting.Host.CreateDefaultBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddBreachedPasswordService();
services.AddForbiddenPasswordService(hostContext.Configuration);
})
.Build();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biblioteca.Model
{
public abstract class Pessoa
{
public string Nome { set; get; }
public DateTime DataNascimento { set; get; }
public string Telefone { set; get; }
public string CPF { set; get; }
public string RG { set; get; }
public int CEP { set; get; }
public string Cidade { set; get; }
public string Estado { set; get; }
public string Endereço { set; get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickCollab.Session
{
public interface ISessionInstanceRepository
{
IEnumerable<SessionInstance> ListAllSessions();
SessionInstance GetSession(string sessionName);
void AddSession(SessionInstance instance);
void DeleteSession(string sessionName);
bool SessionExists(string sessionName);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicNoteController : MonoBehaviour
{
private float startPosY;
private float endPosY;
private float removePosY;
private float noteBeat;
//private bool paused;
// Start is called before the first frame update
public void Initialize(float startPosX, float startPosY, float endPosY, float removePosY, float startPosZ, float noteBeat)
{
this.startPosY = startPosY;
this.endPosY = endPosY;
this.removePosY = removePosY;
this.noteBeat = noteBeat;
//paused = false;
// set position of the note
transform.position = new Vector3(startPosX, startPosY, startPosZ);
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(transform.position.x, startPosY + (endPosY - startPosY) * (1f - (noteBeat - SongManager.songPosInBeats) / SongManager.beatsShownOnScreen), transform.position.z);
// remove itself when out of screen aka completely miss
if (transform.position.y < removePosY)
{
gameObject.SetActive(false);
}
}
public void Perfect()
{
gameObject.SetActive(false);
}
public void Good()
{
gameObject.SetActive(false);
}
public void Okay()
{
gameObject.SetActive(false);
}
}
|
using System;
using System.Collections.Generic;
using SubSonic.BaseClasses;
using SubSonic.Extensions;
using SubSonic.SqlGeneration.Schema;
namespace Pes.Core
{
[SubSonicTableNameOverride("StatusUpdates")]
public partial class StatusUpdate : EntityBase<StatusUpdate>
{
#region Properties
public override object Id
{
get { return StatusUpdateID; }
set { StatusUpdateID = (long)value; }
}
[SubSonicPrimaryKey]
public long StatusUpdateID { get; set; }
public DateTime CreateDate { get; set; }
public string Status { get; set; }
public int? AccountID { get; set; }
public System.Data.Linq.Binary Timestamp { get; set; }
#endregion
public StatusUpdate()
{
}
public StatusUpdate(object id)
{
if (id != null)
{
StatusUpdate entity = Single(id);
if (entity != null)
entity.CopyTo<StatusUpdate>(this);
else
this.StatusUpdateID = 0;
}
}
public bool Save()
{
bool rs = false;
if (StatusUpdateID > 0)
rs = Update(this) > 0;
else
rs = Add(this) != null;
return rs;
}
}
} |
namespace Delegates
{
using System;
internal class Program
{
private static void Main(string[] args)
{
var grades = new Grade[5];
grades[0] = new Grade { Name = "Joe", Score = 12.45f };
grades[0].NameChanged += OnNameChanged;
grades[1] = new Grade { Name = "John", Score = 14.45f };
grades[1].NameChanged += OnNameChanged;
grades[2] = new Grade { Name = "Lucy", Score = 15.45f };
grades[2].NameChanged += OnNameChanged;
grades[3] = new Grade { Name = "Mary", Score = 13.45f };
grades[3].NameChanged += OnNameChanged;
grades[4] = new Grade { Name = "Frank", Score = 16.45f };
grades[4].NameChanged += OnNameChanged;
var gradeBook = new GradeBook(grades);
PrintGrades(gradeBook);
ChangeGrades(gradeBook);
PrintGrades(gradeBook);
Console.Read();
}
private static void OnNameChanged(object sender, NameChangedEventArgs args)
{
Console.WriteLine($"Name changed from: {args.ExistingName} To: {args.NewName}");
}
private static void ChangeGrades(GradeBook gradeBook)
{
gradeBook.Grades[0].Name = "Joe2";
gradeBook.Grades[1].Name = "John22";
gradeBook.Grades[2].Name = "Lucy2";
gradeBook.Grades[3].Name = "Mary2";
gradeBook.Grades[4].Name = "Frank2";
}
private static void PrintGrades(GradeBook gradeBook)
{
Console.WriteLine("--------------------------------------");
foreach (var grade in gradeBook.Grades)
{
Console.WriteLine($"{grade.Name}'s grade is: {grade.Score}");
}
Console.WriteLine("--------------------------------------");
}
}
} |
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Cauldron.TheWanderingIsle
{
public class IslandquakeCardController : CardController
{
public IslandquakeCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController)
{
}
public override void AddTriggers()
{
// At the start of the environment turn, this card deals each target other than Teryx 4 sonic damage. Hero targets which caused Teryx to regain HP since the end of the last environment turn are immune to this damage.
base.AddStartOfTurnTrigger((TurnTaker tt) => tt == base.TurnTaker, new Func<PhaseChangeAction, IEnumerator>(this.DealDamageResponse), TriggerType.DealDamage, null);
}
private IEnumerator DealDamageResponse(PhaseChangeAction pca)
{
//make hero targets who caused Teryx to gain HP last round to become immune to the next damage
IEnumerator makeImmune;
foreach (Card c in this.GetHeroesWhoCausedTeryxToGainHpLastRound())
{
CannotDealDamageStatusEffect cannotDealDamageStatusEffect = new CannotDealDamageStatusEffect();
cannotDealDamageStatusEffect.TargetCriteria.IsSpecificCard = c;
cannotDealDamageStatusEffect.NumberOfUses = new int?(1);
cannotDealDamageStatusEffect.UntilTargetLeavesPlay(c);
cannotDealDamageStatusEffect.IsPreventEffect = true;
makeImmune = base.AddStatusEffect(cannotDealDamageStatusEffect, true);
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(makeImmune);
}
else
{
base.GameController.ExhaustCoroutine(makeImmune);
}
}
//this card deals each target other than Teryx 4 sonic damage
IEnumerator dealDamage = base.DealDamage(base.Card, (Card c) => c.Identifier != "Teryx", 4, DamageType.Sonic);
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(dealDamage);
}
else
{
base.GameController.ExhaustCoroutine(dealDamage);
}
//Then, this card is destroyed.
IEnumerator destroy = base.GameController.DestroyCard(this.DecisionMaker, base.Card, false, null, null, null, null, null, null, null, null, base.GetCardSource(null));
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(destroy);
}
else
{
base.GameController.ExhaustCoroutine(destroy);
}
yield break;
}
private IEnumerable<GainHPJournalEntry> GainHPEntriesThisRound()
{
IEnumerable<GainHPJournalEntry> gainHPJournalEntriesThisRound = from e in base.GameController.Game.Journal.GainHPEntries()
where e.Round == this.Game.Round
select e;
return gainHPJournalEntriesThisRound;
}
private List<Card> GetHeroesWhoCausedTeryxToGainHpLastRound()
{
IEnumerable<GainHPJournalEntry> teryxGainHp = from e in this.GainHPEntriesThisRound()
where e.TargetCard != null && e.TargetCard.Identifier == "Teryx" && e.SourceCard != null && e.SourceCard.IsHero && e.SourceCard.IsTarget
select e;
List<Card> heroes = new List<Card>();
foreach (GainHPJournalEntry ghp in teryxGainHp)
{
Card c = ghp.SourceCard;
if (c.IsTarget && c.IsHero)
{
heroes.Add(c);
}
}
return heroes;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SinavSistemi.BusinessLogicLayer;
using SinavSistemi.Entity;
namespace SinavSistemi.Test
{
public class Test
{
[Test]
public void GirisTesti()
{
OgrenciBLL ogrenci = new OgrenciBLL();
Assert.AreEqual(2, ogrenci.GirisKontrolu("cihancifci", "13579"));
}
[Test]
public void SoruGetirmeTesti()
{
SoruBLL soru = new SoruBLL();
List<SoruEntity> sorular = soru.SorularıGetir(2);
Assert.IsNotNull(sorular);
}
[Test]
public void SoruEklemeTesti()
{
SoruBLL soruBll = new SoruBLL();
SoruEntity soru = new SoruEntity();
soru.soruA = "1245";
soru.soruB = "1246";
soru.soruC = "1247";
soru.soruD = "1248";
soru.soruDogruCevap = "C";
soru.soruIcerik = "işelminin sonucu kaçtır ?";
soru.soruOnBilgi = "893 + 354";
soru.soruKonuID = 1;
soru.resimYolu = "";
soruBll.SoruEkle(soru);
Assert.Pass();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace EFC.Framework.Common.Dtos
{
[Serializable]
public class ErrorDto
{
public string Message { get; set; }
public HttpStatusCode StatusCode { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2_Strategy
{
class Program
{
static void Main(string[] args)
{
StrategyA sa=new StrategyA();
;
Context context=new Context();
context.SetStrategy(sa);
context.HandleStragy();
}
}
public class Context
{
private Strategy _strategy;
public void SetStrategy(Strategy strategy)
{
_strategy = strategy;
}
public void HandleStragy()
{
_strategy.AlgorithmInterface();
}
}
public abstract class Strategy
{
public abstract void AlgorithmInterface();
}
class StrategyA:Strategy
{
/// <inheritdoc />
public StrategyA()
{
}
/// <inheritdoc />
public override void AlgorithmInterface()
{
Console.WriteLine("a+b");
}
}
class StrategyB:Strategy
{
/// <inheritdoc />
public override void AlgorithmInterface()
{
Console.WriteLine("a-b");
}
}
class StrategyC:Strategy
{
/// <inheritdoc />
public override void AlgorithmInterface()
{
Console.WriteLine("a*b");
}
}
}
|
using System;
using System.Collections.Generic;
namespace _7._Traffic_Jam
{
class TrafficJam
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Queue<string> cars = new Queue<string>();
int passedCars = 0;
while (true)
{
string input = Console.ReadLine();
if (input == "end")
{
break;
}
else if (input == "green")
{
int carsToPass = Math.Min(n, cars.Count);
for (int i = 1; i <= carsToPass; i++)
{
Console.WriteLine($"{cars.Dequeue()} passed!");
passedCars++;
}
}
else
{
cars.Enqueue(input);
}
}
Console.WriteLine($"{passedCars} cars passed the crossroads.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace SO.Urba.Models.ValueObjects
{
[Table("Member", Schema = "data" )]
[Serializable]
public class MemberVo
{
[DisplayName("member Id")]
[Required]
[Key]
public int memberId { get; set; }
[DisplayName("contact Info Id")]
public Nullable<int> contactInfoId { get; set; }
[Required]
[DisplayName("username")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Please enter minimum 3 characters!") ]
[RegularExpression(@"^[a-zA-Z\s?]+$", ErrorMessage = "[username] Please enter valid characters!")]
public string username { get; set; }
[Required]
[DisplayName("password")]
[StringLength(64)]
public string password { get; set; }
[NotMapped]
public string passwordReset { get; set; }
[DisplayName("force Password Reset")]
public Nullable<bool> forcePasswordReset { get; set; }
[DisplayName("created")]
[Required]
public DateTime created { get; set; }
[DisplayName("modified")]
[Required]
public DateTime modified { get; set; }
[DisplayName("created By")]
public Nullable<int> createdBy { get; set; }
[DisplayName("modified By")]
public Nullable<int> modifiedBy { get; set; }
[DisplayName("is Active")]
[Required]
public bool isActive { get; set; }
[ForeignKey("contactInfoId")]
public ContactInfoVo contactInfo { get; set; }
[Association("Member_MemberRoleLookup", "memberId", "memberId")]
public List<MemberRoleLookupVo> memberRoleLookupses { get; set; }
[NotMapped]
public List<int> memberRoleTypes { get; set; }
public MemberVo()
{
this.isActive = true;
memberRoleTypes = new List<int>();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PretrageOsnovno
{
class BreadthFirstSearch
{
public State Search(string startNodeName, string endNodeName)
{
// TODO 4: implementirati algoritam prvi u dubinu širinu
return null;
}
}
}
|
namespace HCL.Academy.Model
{
public class OnboardingReportRequest:RequestBase
{
public string Status { get; set; }
public bool IsExcelDownload { get; set; }
public int RoleId { get; set; }
public int GEOId { get; set; }
public int ProjectId { get; set; }
public string option { get; set; }
public string search { get; set; }
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Dnn.PersonaBar.Library.Prompt.Common;
using DotNetNuke.Services.Scheduling;
namespace Dnn.PersonaBar.TaskScheduler.Components.Prompt.Models
{
public class TaskModelBase
{
public int ScheduleId { get; set; }
public string FriendlyName { get; set; }
public string NextStart { get; set; }
public bool Enabled { get; set; }
#region Constructors
public TaskModelBase()
{
}
public TaskModelBase(ScheduleItem item)
{
Enabled = item.Enabled;
FriendlyName = item.FriendlyName;
NextStart = item.NextStart.ToPromptShortDateAndTimeString();
ScheduleId = item.ScheduleID;
}
#endregion
#region CommandLinks
#endregion
}
}
|
using Contoso.Contexts;
using Contoso.Data.Entities;
using Microsoft.EntityFrameworkCore;
namespace MigrationTool
{
public class MigrationContext : DbContext
{
public MigrationContext()
{
this.EntityConfigurationHandler = new EntityConfigurationHandler(this);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{//Can't use DI to create MigrationContext for dotnet ef migrations add
optionsBuilder.UseSqlServer(@"Server=.\SQL2016;Database=Contoso;Trusted_Connection=True;trustServerCertificate=true;");
//Alternatively use DI and at runtime use
//myDbContext.Database.Migrate(); Then context.Database.EnsureCreated();
//Instead of "dotnet ef database update -v" at the command line.
}
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Instructor> Instructors { get; set; }
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
public DbSet<CourseAssignment> CourseAssignments { get; set; }
public DbSet<LookUps> LookUps { get; set; }
protected virtual EntityConfigurationHandler EntityConfigurationHandler { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
this.EntityConfigurationHandler.Configure(modelBuilder);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.ViewModel;
using Torshify.Radio.Framework;
using Torshify.Radio.Framework.Commands;
namespace Torshify.Radio.Core.Views.NowPlaying
{
[Export(typeof(NowPlayingViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
[RegionMemberLifetime(KeepAlive = false)]
public class NowPlayingViewModel : NotificationObject, INavigationAware
{
#region Fields
private readonly Dispatcher _dispatcher;
private readonly ITrackPlayer _player;
private readonly IRadio _radio;
private ImageSource _backgroundImage;
private bool _hasTrack;
private bool _initializeÌmageMap;
private IRegionNavigationService _navigationService;
private Random _random;
private TaskScheduler _taskScheduler;
#endregion Fields
#region Constructors
[ImportingConstructor]
public NowPlayingViewModel(IRadio radio, [Import("CorePlayer")] ITrackPlayer player, Dispatcher dispatcher)
{
_radio = radio;
_player = player;
_dispatcher = dispatcher;
_random = new Random();
_taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
NavigateBackCommand = new AutomaticCommand(ExecuteNavigateBack, CanExecuteNavigateBack);
NextTrackCommand = new ManualCommand(ExecuteNextTrack, CanExecuteNextTrack);
TogglePlayPauseCommand = new ManualCommand(ExecuteTogglePlayPause, CanExecuteTogglePlayPause);
ShareTrackCommand = new ManualCommand<Track>(ExecuteShareTrack, CanExecuteShareTrack);
}
#endregion Constructors
#region Properties
public ManualCommand<Track> ShareTrackCommand
{
get;
private set;
}
public ManualCommand TogglePlayPauseCommand
{
get;
private set;
}
public ManualCommand NextTrackCommand
{
get;
private set;
}
public ICommand NavigateBackCommand
{
get; private set;
}
public IRadio Radio
{
get { return _radio; }
}
public ITrackPlayer Player
{
get
{
return _player;
}
}
[Import]
public IBackdropService BackdropService
{
get;
set;
}
[Import]
public ILoggerFacade Logger
{
get;
set;
}
public ImageSource BackgroundImage
{
get { return _backgroundImage; }
set
{
if (_backgroundImage != value)
{
_backgroundImage = value;
RaisePropertyChanged("BackgroundImage");
}
}
}
public bool InitializeÌmageMap
{
get { return _initializeÌmageMap; }
set
{
if (_initializeÌmageMap != value)
{
_initializeÌmageMap = value;
RaisePropertyChanged("InitializeÌmageMap");
}
}
}
public bool HasTrack
{
get { return _hasTrack; }
set
{
if (_hasTrack != value)
{
_hasTrack = value;
RaisePropertyChanged("HasTrack");
}
}
}
#endregion Properties
#region Methods
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
_radio.CurrentTrackChanged -= RadioOnCurrentTrackChanged;
_radio.UpcomingTrackChanged -= RadioOnUpcomingTrackChanged;
_radio.TrackStreamQueued -= RadioOnTrackStreamQueued;
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
_navigationService = navigationContext.NavigationService;
_radio.CurrentTrackChanged += RadioOnCurrentTrackChanged;
_radio.UpcomingTrackChanged += RadioOnUpcomingTrackChanged;
_radio.TrackStreamQueued += RadioOnTrackStreamQueued;
if (_radio.CurrentTrack != null)
{
HasTrack = true;
QueryForBackdrop(_radio.CurrentTrack.Artist);
}
RefreshCommands();
}
private BitmapImage GetImageSource(string imageUrl)
{
var imageSource = new BitmapImage();
try
{
imageSource.BeginInit();
imageSource.CacheOption = BitmapCacheOption.None;
imageSource.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
imageSource.UriSource = new Uri(imageUrl, UriKind.Absolute);
imageSource.EndInit();
if (imageSource.CanFreeze)
{
imageSource.Freeze();
}
}
catch (Exception e)
{
Logger.Log(e.ToString(), Category.Exception, Priority.Low);
}
return imageSource;
}
private void RadioOnTrackStreamQueued(object sender, EventArgs eventArgs)
{
RefreshCommands();
}
private void RadioOnUpcomingTrackChanged(object sender, EventArgs eventArgs)
{
RefreshCommands();
}
private void RadioOnCurrentTrackChanged(object sender, TrackChangedEventArgs e)
{
if (e.CurrentTrack == null)
{
HasTrack = false;
}
if (e.CurrentTrack != null && e.PreviousTrack != null && e.CurrentTrack.Artist == e.PreviousTrack.Artist)
{
return;
}
if (e.CurrentTrack != null)
{
HasTrack = true;
QueryForBackdrop(e.CurrentTrack.Artist);
}
RefreshCommands();
}
private void QueryForBackdrop(string artist)
{
BackdropService
.Query(artist)
.ContinueWith(task =>
{
if (task.Exception != null)
{
Logger.Log(task.Exception.ToString(), Category.Exception, Priority.Medium);
}
else
{
if (_random.Next(100) > 50)
{
InitializeÌmageMap = false;
var imageUrl = task.Result.OrderBy(k => Guid.NewGuid()).FirstOrDefault();
if (imageUrl != null)
{
BackgroundImage = GetImageSource(imageUrl);
}
else
{
string[] randoms;
if (BackdropService.TryGetAny(out randoms))
{
BackgroundImage = GetImageSource(randoms[0]);
}
else
{
BackgroundImage = null;
}
}
}
else
{
InitializeÌmageMap = true;
}
}
}, _taskScheduler)
.ContinueWith(task =>
{
if (task.IsFaulted && task.Exception != null)
{
task.Exception.Handle(e => true);
}
});
}
private bool CanExecuteNavigateBack()
{
return _navigationService != null && _navigationService.Journal.CanGoBack;
}
private void ExecuteNavigateBack()
{
_navigationService.Journal.GoBack();
}
private bool CanExecuteShareTrack(Track track)
{
return true;
}
private void ExecuteShareTrack(Track track)
{
}
private void ExecuteTogglePlayPause()
{
if (_player.IsPlaying)
{
_player.Pause();
}
else
{
_player.Play();
}
}
private bool CanExecuteTogglePlayPause()
{
return _radio.CurrentTrack != null;
}
private bool CanExecuteNextTrack()
{
return _radio.CanGoToNextTrack || _radio.CanGoToNextTrackStream;
}
private void ExecuteNextTrack()
{
if (_radio.CanGoToNextTrack)
{
_radio.NextTrack();
}
else if (_radio.CanGoToNextTrackStream)
{
_radio.NextTrackStream();
}
}
private void RefreshCommands()
{
if (_dispatcher.CheckAccess())
{
TogglePlayPauseCommand.NotifyCanExecuteChanged();
NextTrackCommand.NotifyCanExecuteChanged();
}
else
{
_dispatcher.BeginInvoke(new Action(RefreshCommands));
}
}
#endregion Methods
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace GP3_Coursework
{
struct fastEnemy
{
// position
public Vector3 fastEnemyposition;
// direction
public Vector3 fastEnemydirection;
// speed
public float fastEnemyspeed;
// active
public bool isActive;
// health
public int health;
public void Update(float delta)
{
// update position
fastEnemyposition += fastEnemydirection * fastEnemyspeed * GameConstants.fastEnemySpeedAdjustment * delta;
// if leaves play field size
if (fastEnemyposition.X < -GameConstants.PlayfieldSizeX ||
fastEnemyposition.Z > GameConstants.PlayfieldSizeZ ||
fastEnemyposition.Z < -GameConstants.PlayfieldSizeZ)
isActive = false;
// health = 0
if (health == 0)
{
isActive = false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
namespace Sunny.DB
{
public class SqlServerEFDataProvider:BaseEFDataProvider
{
/// <summary>
/// Get connection factory
/// </summary>
/// <returns>Connection factory</returns>
public override IDbConnectionFactory GetConnectionFactory()
{
return new SqlConnectionFactory();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.DataEntity;
using Model.Locale;
using Utility;
using eIVOGo.Module.UI;
using eIVOGo.Module.Base;
namespace eIVOGo.Module.Inquiry
{
public partial class QueryCALogList : InquireEntity
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override UserControl _itemList
{
get { return itemList; }
}
protected override void buildQueryItem()
{
Expression<Func<CALog, bool>> queryExpr = c => true;
if (!String.IsNullOrEmpty(OwnerID.SelectedValue))
{
int ownerID = int.Parse(OwnerID.SelectedValue);
queryExpr = queryExpr.And(w => w.CDS_Document.DocumentOwner.OwnerID == ownerID);
}
if (DateFrom.HasValue)
queryExpr = queryExpr.And(w => w.LogDate.HasValue && w.LogDate.Value >= DateFrom.DateTimeValue);
if (DateTo.HasValue)
queryExpr = queryExpr.And(w => w.LogDate.HasValue && w.LogDate.Value < DateTo.DateTimeValue.AddDays(1));
if (!String.IsNullOrEmpty(CACatalog.SelectedValue))
{
queryExpr = queryExpr.And(w => w.Catalog == int.Parse(CACatalog.SelectedValue));
}
itemList.BuildQuery = table =>
{
return table.Where(queryExpr).OrderByDescending(c => c.LogID);
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Alpaca.Markets
{
public sealed partial class AlpacaTradingClient
{
/// <summary>
/// Gets list of available orders from Alpaca REST API endpoint.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only list of order information objects.</returns>
[Obsolete("This method will be removed in the next major release.", false)]
public Task<IReadOnlyList<IOrder>> ListAllOrdersAsync(
CancellationToken cancellationToken = default) =>
ListOrdersAsync(new ListOrdersRequest(), cancellationToken);
/// <summary>
/// Gets list of available orders from Alpaca REST API endpoint.
/// </summary>
/// <param name="request">List orders request parameters.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only list of order information objects.</returns>
public Task<IReadOnlyList<IOrder>> ListOrdersAsync(
ListOrdersRequest request,
CancellationToken cancellationToken = default) =>
_httpClient.GetAsync<IReadOnlyList<IOrder>, List<JsonOrder>>(
request.EnsureNotNull(nameof(request)).GetUriBuilder(_httpClient),
cancellationToken, _alpacaRestApiThrottler);
/// <summary>
/// Creates new order for execution using Alpaca REST API endpoint.
/// </summary>
/// <param name="request">New order placement request parameters.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only order information object for newly created order.</returns>
public Task<IOrder> PostOrderAsync(
NewOrderRequest request,
CancellationToken cancellationToken = default) =>
postOrderAsync(request.EnsureNotNull(nameof(request)).Validate().GetJsonRequest(), cancellationToken);
/// <summary>
/// Creates new order for execution using Alpaca REST API endpoint.
/// </summary>
/// <param name="orderBase">New order placement request parameters.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only order information object for newly created order.</returns>
public Task<IOrder> PostOrderAsync(
OrderBase orderBase,
CancellationToken cancellationToken = default) =>
postOrderAsync(orderBase.EnsureNotNull(nameof(orderBase)).Validate().GetJsonRequest(), cancellationToken);
private Task<IOrder> postOrderAsync(
JsonNewOrder jsonNewOrder,
CancellationToken cancellationToken = default) =>
_httpClient.PostAsync<IOrder, JsonOrder, JsonNewOrder>(
"v2/orders", jsonNewOrder, cancellationToken, _alpacaRestApiThrottler);
/// <summary>
/// Updates existing order using Alpaca REST API endpoint.
/// </summary>
/// <param name="request">Patch order request parameters.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only order information object for updated order.</returns>
public Task<IOrder> PatchOrderAsync(
ChangeOrderRequest request,
CancellationToken cancellationToken = default) =>
_httpClient.PatchAsync<IOrder, JsonOrder, ChangeOrderRequest>(
request.EnsureNotNull(nameof(request)).Validate().GetEndpointUri(),
request, _alpacaRestApiThrottler, cancellationToken);
/// <summary>
/// Get single order information by client order ID from Alpaca REST API endpoint.
/// </summary>
/// <param name="clientOrderId">Client order ID for searching.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only order information object.</returns>
public Task<IOrder> GetOrderAsync(
String clientOrderId,
CancellationToken cancellationToken = default) =>
_httpClient.GetAsync<IOrder, JsonOrder>(
new UriBuilder(_httpClient.BaseAddress)
{
Path = "v2/orders:by_client_order_id",
Query = new QueryBuilder()
.AddParameter("client_order_id", clientOrderId)
},
cancellationToken, _alpacaRestApiThrottler);
/// <summary>
/// Get single order information by server order ID from Alpaca REST API endpoint.
/// </summary>
/// <param name="orderId">Server order ID for searching.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Read-only order information object.</returns>
public Task<IOrder> GetOrderAsync(
Guid orderId,
CancellationToken cancellationToken = default) =>
_httpClient.GetAsync<IOrder, JsonOrder>(
$"v2/orders/{orderId:D}", cancellationToken, _alpacaRestApiThrottler);
/// <summary>
/// Deletes/cancel order on server by server order ID using Alpaca REST API endpoint.
/// </summary>
/// <param name="orderId">Server order ID for cancelling.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns><c>True</c> if order cancellation was accepted.</returns>
public Task<Boolean> DeleteOrderAsync(
Guid orderId,
CancellationToken cancellationToken = default) =>
_httpClient.DeleteAsync(
$"v2/orders/{orderId:D}", cancellationToken, _alpacaRestApiThrottler);
/// <summary>
/// Deletes/cancel all open orders using Alpaca REST API endpoint.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>List of order cancellation status objects.</returns>
public Task<IReadOnlyList<IOrderActionStatus>> DeleteAllOrdersAsync(
CancellationToken cancellationToken = default) =>
_httpClient.DeleteAsync<IReadOnlyList<IOrderActionStatus>, List<JsonOrderActionStatus>>(
"v2/orders", cancellationToken, _alpacaRestApiThrottler);
}
}
|
using System.Drawing;
namespace MH_Database.Ressources.Pictures.Rarities.Gen3_4
{
internal class WeaponsIcons
{
readonly internal Bitmap[] Bow = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Bow_Rarity_1,
Weapons.Bow_Rarity_2,
Weapons.Bow_Rarity_3,
Weapons.Bow_Rarity_4,
Weapons.Bow_Rarity_5,
Weapons.Bow_Rarity_6,
Weapons.Bow_Rarity_7,
Weapons.Bow_Rarity_8,
Weapons.Bow_Rarity_9,
Weapons.Bow_Rarity_X
};
readonly internal Bitmap[] Charge_Blade = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Charge_Blade_Rarity_1,
Weapons.Charge_Blade_Rarity_2,
Weapons.Charge_Blade_Rarity_3,
Weapons.Charge_Blade_Rarity_4,
Weapons.Charge_Blade_Rarity_5,
Weapons.Charge_Blade_Rarity_6,
Weapons.Charge_Blade_Rarity_7,
Weapons.Charge_Blade_Rarity_8,
Weapons.Charge_Blade_Rarity_9,
Weapons.Charge_Blade_Rarity_X
};
readonly internal Bitmap[] Dual_Blades = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Dual_Blades_Rarity_1,
Weapons.Dual_Blades_Rarity_2,
Weapons.Dual_Blades_Rarity_3,
Weapons.Dual_Blades_Rarity_4,
Weapons.Dual_Blades_Rarity_5,
Weapons.Dual_Blades_Rarity_6,
Weapons.Dual_Blades_Rarity_7,
Weapons.Dual_Blades_Rarity_8,
Weapons.Dual_Blades_Rarity_9,
Weapons.Dual_Blades_Rarity_X
};
readonly internal Bitmap[] Great_Sword = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Great_Sword_Rarity_1,
Weapons.Great_Sword_Rarity_2,
Weapons.Great_Sword_Rarity_3,
Weapons.Great_Sword_Rarity_4,
Weapons.Great_Sword_Rarity_5,
Weapons.Great_Sword_Rarity_6,
Weapons.Great_Sword_Rarity_7,
Weapons.Great_Sword_Rarity_8,
Weapons.Great_Sword_Rarity_9,
Weapons.Great_Sword_Rarity_X
};
readonly internal Bitmap[] Gunlance = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Gunlance_Rarity_1,
Weapons.Gunlance_Rarity_2,
Weapons.Gunlance_Rarity_3,
Weapons.Gunlance_Rarity_4,
Weapons.Gunlance_Rarity_5,
Weapons.Gunlance_Rarity_6,
Weapons.Gunlance_Rarity_7,
Weapons.Gunlance_Rarity_8,
Weapons.Gunlance_Rarity_9,
Weapons.Gunlance_Rarity_X
};
readonly internal Bitmap[] Hammer = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Hammer_Rarity_1,
Weapons.Hammer_Rarity_2,
Weapons.Hammer_Rarity_3,
Weapons.Hammer_Rarity_4,
Weapons.Hammer_Rarity_5,
Weapons.Hammer_Rarity_6,
Weapons.Hammer_Rarity_7,
Weapons.Hammer_Rarity_8,
Weapons.Hammer_Rarity_9,
Weapons.Hammer_Rarity_X
};
readonly internal Bitmap[] Heavy_Bowgun = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Heavy_Bowgun_Rarity_1,
Weapons.Heavy_Bowgun_Rarity_2,
Weapons.Heavy_Bowgun_Rarity_3,
Weapons.Heavy_Bowgun_Rarity_4,
Weapons.Heavy_Bowgun_Rarity_5,
Weapons.Heavy_Bowgun_Rarity_6,
Weapons.Heavy_Bowgun_Rarity_7,
Weapons.Heavy_Bowgun_Rarity_8,
Weapons.Heavy_Bowgun_Rarity_9,
Weapons.Heavy_Bowgun_Rarity_X
};
readonly internal Bitmap[] Hunting_Horn = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Hunting_Horn_Rarity_1,
Weapons.Hunting_Horn_Rarity_2,
Weapons.Hunting_Horn_Rarity_3,
Weapons.Hunting_Horn_Rarity_4,
Weapons.Hunting_Horn_Rarity_5,
Weapons.Hunting_Horn_Rarity_6,
Weapons.Hunting_Horn_Rarity_7,
Weapons.Hunting_Horn_Rarity_8,
Weapons.Hunting_Horn_Rarity_9,
Weapons.Hunting_Horn_Rarity_X
};
readonly internal Bitmap[] Insect_Glaive = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Insect_Glaive_Rarity_1,
Weapons.Insect_Glaive_Rarity_2,
Weapons.Insect_Glaive_Rarity_3,
Weapons.Insect_Glaive_Rarity_4,
Weapons.Insect_Glaive_Rarity_5,
Weapons.Insect_Glaive_Rarity_6,
Weapons.Insect_Glaive_Rarity_7,
Weapons.Insect_Glaive_Rarity_8,
Weapons.Insect_Glaive_Rarity_9,
Weapons.Insect_Glaive_Rarity_X
};
readonly internal Bitmap[] Lance = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Lance_Rarity_1,
Weapons.Lance_Rarity_2,
Weapons.Lance_Rarity_3,
Weapons.Lance_Rarity_4,
Weapons.Lance_Rarity_5,
Weapons.Lance_Rarity_6,
Weapons.Lance_Rarity_7,
Weapons.Lance_Rarity_8,
Weapons.Lance_Rarity_9,
Weapons.Lance_Rarity_X
};
readonly internal Bitmap[] Light_Bowgun = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Light_Bowgun_Rarity_1,
Weapons.Light_Bowgun_Rarity_2,
Weapons.Light_Bowgun_Rarity_3,
Weapons.Light_Bowgun_Rarity_4,
Weapons.Light_Bowgun_Rarity_5,
Weapons.Light_Bowgun_Rarity_6,
Weapons.Light_Bowgun_Rarity_7,
Weapons.Light_Bowgun_Rarity_8,
Weapons.Light_Bowgun_Rarity_9,
Weapons.Light_Bowgun_Rarity_X
};
readonly internal Bitmap[] Long_Sword = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Long_Sword_Rarity_1,
Weapons.Long_Sword_Rarity_2,
Weapons.Long_Sword_Rarity_3,
Weapons.Long_Sword_Rarity_4,
Weapons.Long_Sword_Rarity_5,
Weapons.Long_Sword_Rarity_6,
Weapons.Long_Sword_Rarity_7,
Weapons.Long_Sword_Rarity_8,
Weapons.Long_Sword_Rarity_9,
Weapons.Long_Sword_Rarity_X
};
readonly internal Bitmap[] Switch_Axe = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Switch_Axe_Rarity_1,
Weapons.Switch_Axe_Rarity_2,
Weapons.Switch_Axe_Rarity_3,
Weapons.Switch_Axe_Rarity_4,
Weapons.Switch_Axe_Rarity_5,
Weapons.Switch_Axe_Rarity_6,
Weapons.Switch_Axe_Rarity_7,
Weapons.Switch_Axe_Rarity_8,
Weapons.Switch_Axe_Rarity_9,
Weapons.Switch_Axe_Rarity_X
};
readonly internal Bitmap[] Sword_and_Shield = new Bitmap[11]
{
null, //We keep 'null' so that [1] return the rarity 1 icon
Weapons.Sword_and_Shield_Rarity_1,
Weapons.Sword_and_Shield_Rarity_2,
Weapons.Sword_and_Shield_Rarity_3,
Weapons.Sword_and_Shield_Rarity_4,
Weapons.Sword_and_Shield_Rarity_5,
Weapons.Sword_and_Shield_Rarity_6,
Weapons.Sword_and_Shield_Rarity_7,
Weapons.Sword_and_Shield_Rarity_8,
Weapons.Sword_and_Shield_Rarity_9,
Weapons.Sword_and_Shield_Rarity_X
};
internal class KinsectClass
{
readonly internal Bitmap Blunt = new Bitmap(Weapons.Kinsect_Blunt);
readonly internal Bitmap Cutting = new Bitmap(Weapons.Kinsect_Cutting);
}
internal KinsectClass Kinsect = new KinsectClass();
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGTool.Arquivo
{
public class Cip
{
public async Task<int> ProcurarGim(string dirSndDat)
{
int header = 0x2E47494D;
List<string> sndInfo = new List<string>();
string dirSnd = dirSndDat.Replace(".cip", "");
Directory.CreateDirectory(dirSnd);
int tamanhoArq = (int)new FileInfo(dirSndDat).Length;
int contador = 0;
await Task.Run(() =>
{
using (BinaryReader br = new BinaryReader(File.Open(dirSndDat, FileMode.Open)))
{
while (br.BaseStream.Position < tamanhoArq)
{
int valor = br.ReadInt32();
if (valor == header)
{
int indexInt = (int)br.BaseStream.Position - 4;
br.BaseStream.Position += 0x10;
int tamanhoDoGim = (br.ReadInt32() + 0x10) - 0x80;
br.BaseStream.Position = indexInt;
byte[] ehpEmbyte = br.ReadBytes(tamanhoDoGim);
string index = indexInt + "";
string nomeAt3 = contador.ToString().PadLeft(5, '0');
contador++;
File.WriteAllBytes(dirSnd + "\\" + nomeAt3 + ".gim", ehpEmbyte);
sndInfo.Add(index + "," + dirSnd + "\\" + nomeAt3 + ".gim");
}
}
File.WriteAllLines(dirSndDat.Replace(".cip", ".txt"), sndInfo);
}
});
return contador;
}
public void InsiraNoCip(string dirSndDat)
{
string[] arquivos = File.ReadAllLines(dirSndDat);
using (BinaryWriter writer = new BinaryWriter(File.Open(dirSndDat.Replace(".txt",".cip"), FileMode.Open)))
{
for (int i = 0; i < arquivos.Length; i++)
{
string info = arquivos[i];
if (info != "")
{
string[] fileInfo = info.Split(',');
int posicaoArquivo = int.Parse(fileInfo[0]);
string diretorio = fileInfo[1];
byte[] arquivo = File.ReadAllBytes(diretorio);
writer.BaseStream.Seek(posicaoArquivo,SeekOrigin.Begin);
writer.Write(arquivo);
}
}
}
}
}
}
|
namespace Bodoconsult.Core.Web.Mail.Model
{
/// <summary>
/// Contains config data for Excel import
/// </summary>
public class ExcelFileConfig
{
public ExcelFileConfig()
{
EmailAddressColumn = 0;
SalutationAddressColumn = 1;
}
/// <summary>
/// Path to the data file with addresses to send the file to
/// </summary>
public string PhysicalPathOfDataSourceFile { get; set; }
/// <summary>
/// Sheetname in the Excel file
/// </summary>
public string SheetName { get; set; }
/// <summary>
/// Column number of the email address column (default: 0 [first column])
/// </summary>
public int EmailAddressColumn { get; set; }
/// <summary>
/// Column number of the salutation address column (default: 1 [second column])
/// </summary>
public int SalutationAddressColumn { get; set; }
}
}
|
using CakeShop.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace CakeShop.Data
{
public class CakeShopDAO
{
private OurCakeShopEntities Database;
/// <summary>
/// Hàm khởi tạo kết nối cơ sở dữ liệu
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public CakeShopDAO()
{
Database = new OurCakeShopEntities();
}
/// <summary>
/// Hàm lấy dánh sách tất cả bánh của cửa hàng theo Category name
/// Hàm cập nhật cơ sở dữ liệu
/// </summary>
public void UpdateDatabase()
{
Database.SaveChanges();
}
#region Cake
/// <summary>
/// Hàm lấy dánh sách bánh theo tên loại và lượng tồn
/// </summary>
/// <param name="catName">Tên loại (Category Name)</param>
/// <param name="inventoryNum">Số lượng tồn (Iventory Number)</param>
/// <returns></returns>
public List<CAKE> CakeList(
long[] catIDs = null,
int arrangeMode = -1,
long inventoryNum = -1,
DateTime dateAdded = default(DateTime),
string searchText = ""
)
{
List<CAKE> result = new List<CAKE>();
var cakes = Database.CAKEs;
IQueryable<CAKE> tmp;
// Lọc theo loại
if (catIDs != null)
{
var catList = catIDs.AsQueryable()
.Join(Database.CATEGORies,
c1 => c1,
c2 => c2.ID,
(c1, c2) => new { ID = c2.ID, Name = c2.Name });
var cakebycat = cakes
.Join(catList,
cake => cake.CatID,
cat => cat.ID,
(cake, cat) => cake);
tmp = cakebycat;
}
else
{
tmp = cakes;
}
// Lọc theo số lượng
if (inventoryNum > -1)
{
var cakebynum = tmp.Where(t => t.InventoryNum >= inventoryNum);
tmp = cakebynum;
}
else { }
// Lọc theo ngày thêm
if (dateAdded != default(DateTime))
{
}
else { }
var ordered = tmp;
// Không sắp xếp
if (arrangeMode == -1)
{ }
// Theo Alphabet tăng
else if (arrangeMode == 0)
{
ordered = tmp.OrderBy(t => t.Name);
}
// Theo Alphabet giảm
else if (arrangeMode == 1)
{
ordered = tmp.OrderByDescending(t => t.Name);
}
// Theo giá tăng
else if (arrangeMode == 2)
{
ordered = tmp.OrderBy(t => t.SellPrice);
}
// Theo giá giảm
else if (arrangeMode == 3)
{
ordered = tmp.OrderByDescending(t => t.SellPrice);
}
else if (arrangeMode == 4)
{
ordered = tmp.OrderBy(t => t.InventoryNum);
}
else if (arrangeMode == 5)
{
ordered = tmp.OrderByDescending(t => t.InventoryNum);
}
var searched = ordered.Where(x => x.Name.Contains(searchText));
if (searched != null)
{
result = searched.Cast<CAKE>().ToList();
}
else if (tmp != null)
{
result = ordered.Cast<CAKE>().ToList();
}
else
{
result = cakes.ToList();
}
return result;
}
/// <summary>
/// Tìm kiếm Cake theo tên
/// </summary>
/// <param name="text">name cần tìm kiếm</param>
/// <returns></returns>
public List<CAKE> SearchCakeByName(string text)
{
List<CAKE> result = new List<CAKE>();
var query = Database.CAKEs.Where(x => x.Name.Contains(text));
result = query.ToList();
return result;
}
/// <summary>
/// Update Cake theo ID
/// </summary>
/// <param name="CakeID">ID (CakeID</param>
/// <param name="Cake">Cake (Cake)</param>
public bool UpdateCake(CAKE updateCake, long CakeID)
{
bool check = true;
var cur = (from c in Database.CAKEs
where c.ID == CakeID
select c).SingleOrDefault();
try
{
cur.AvatarImage = updateCake.AvatarImage.ToArray();
cur.Name = updateCake.Name;
cur.BasePrice = updateCake.BasePrice;
cur.SellPrice = updateCake.SellPrice;
cur.Introduction = updateCake.Introduction;
cur.DateAdded = updateCake.DateAdded;
cur.CatID = updateCake.CatID;
}
catch (Exception ex)
{
check = false;
}
Database.SaveChanges();
return check;
}
/// <summary>
/// Hàm thêm một loại bánh mới vào cơ sở dữ liệu
/// </summary>
/// <param name="tempCake"></param>
public void AddCake(CAKE tempCake)
{
var cakes = CakeList();
cakes.Add(tempCake);
Database.SaveChanges();
}
/// <summary>
/// Hàm lấy tên bánh theo Id
/// </summary>
/// <param name="ID">ID (CatID)</param>
/// <returns></returns>
public string CakeName(long ID)
{
var cake = Database.CAKEs;
var query = from c in cake
where c.ID == ID
select c.Name;
var name = query.ToList()[0].ToString();
return name;
}
/// <summary>
/// Hàm lấy dánh sách tất cả bánh của cửa hàng theo Category Id
/// </summary>
/// <param name="CatID">ID (CatID)</param>
/// <returns></returns>
public List<CAKE> CakeList(long CatID)
{
var categories = Database.CATEGORies;
var query = from c in categories
where c.ID == CatID
select c;
var cat = query.ToList()[0];
var cakes = cat.CAKEs.ToList();
return cakes;
}
/// <summary>
/// Hàm lấy cake theo ID
/// </summary>
/// <param name="CakeID">ID (CakeID)</param>
/// <returns></returns>
public CAKE GetCAKEs(long CakeID)
{
var cakes = Database.CAKEs;
var query = (from c in cakes
where c.ID == CakeID
select c).SingleOrDefault();
CAKE result = (CAKE)query;
return result;
}
/// <summary>
/// Hàm cập nhật lượng bánh tồn kho
/// </summary>
/// <param name="CatID">ID (CatID)</param>
/// <returns></returns>
public bool UpdateInvetoryCake(long CakeId, long NewInventoryNumber)
{
bool check = true;
try
{
var cake = (from c in Database.CAKEs
where c.ID == CakeId
select c).SingleOrDefault();
cake.InventoryNum = NewInventoryNumber;
Database.SaveChanges();
}
catch (Exception ex)
{
check = false;
}
return check;
}
/// <summary>
/// Hàm lấy số lượng bánh theo loại category
/// </summary>
/// <param name="CatID">ID (CatID)</param>
/// <returns></returns>
public long CountCakesByCategory(long CatID)
{
var query = (from c in Database.CAKEs
where c.CatID == CatID
select c.ID);
var count = query.ToList().Count();
return count;
}
/// <summary>
/// Hàm lấy tổng số lương bánh
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public long CountAllCakes()
{
var query = (from c in Database.CAKEs
select c.ID);
var count = query.ToList().Count();
return count;
}
#endregion Cake
#region Order
/// <summary>
/// Hàm lấy dánh sách tất cả Order
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public List<ORDER> OrderList()
{
var oRDERs = Database.ORDERs;
var query = oRDERs.OrderByDescending(x => x.DateCompleted);
var result = query.ToList();
return result;
}
/// <summary>
/// Hàm lấy danh sách tất cả
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public bool UpdateOrderStatus(long OrderID, string Status)
{
bool check = true;
try
{
var order = (from o in Database.ORDERs
where o.ID == OrderID
select o).SingleOrDefault();
order.Status = Status;
Database.SaveChanges();
}
catch (Exception ex)
{
check = false;
}
return check;
}
/// <summary>
/// Hàm lấy số lượng order hiện tại
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public long OrderCount()
{
long count = (long)Database.ORDERs.Count();
return count;
}
#endregion Order
#region Category
/// <summary>
/// Hàm lấy dánh sách tất cả Category
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public List<CATEGORY> CategoryList()
{
var categories = Database.CATEGORies.OrderBy(c => c.ID).ToList();
return categories;
}
public long CategoryCount()
{
var count = Database.CATEGORies.Count();
return count;
}
public string CategoryNameByID(long CatID)
{
var query = (from c in Database.CATEGORies
where c.ID == CatID
select c).SingleOrDefault();
string name = query.Name;
return name;
}
#endregion
#region Receive
/// <summary>
/// Ham lay danh sach don nhap hang
/// </summary>
/// <returns></returns>
public List<ReceiveModel> ReceiveList()
{
var result = new List<ReceiveModel>();
var receives = Database.RECEIVEs
.Join(Database.CAKEs,
r => r.CakeID,
c => c.ID,
(r, c) => new { r.ID, r.DateAdded, r.CakeID, c.Name, c.AvatarImage, r.CakeNum, r.Price, r.TotalBill })
.GroupBy(e => new { e.ID, e.DateAdded, e.TotalBill })
.Select(g =>
new
{
ID = g.Select(r => r.ID).FirstOrDefault(),
Date = g.Select(r => r.DateAdded).FirstOrDefault(),
CountCake = g.Select(r => new { r.CakeID, r.Name, r.AvatarImage, r.CakeNum, r.Price })
.GroupBy(r => r.CakeID)
.Select(r => new
{
CakeID = r.Select(e => e.CakeID).FirstOrDefault(),
Name = r.Select(e => e.Name).FirstOrDefault(),
AvatarImage = r.Select(e => e.Name).FirstOrDefault(),
Num = r.Sum(e => e.CakeNum),
Price = r.Sum(e => e.Price)
}).Count(),
SumCake = g.Sum(s => s.CakeNum),
Total = g.Select(r => r.TotalBill).FirstOrDefault(),
CakeList = g.Select(r => new { r.CakeID, r.Name, r.AvatarImage, r.CakeNum, r.Price })
.GroupBy(r => new { r.CakeID, r.Price })
.Select(r => new
{
CakeID = r.Select(e => e.CakeID).FirstOrDefault(),
Name = r.Select(e => e.Name).FirstOrDefault(),
AvatarImage = r.Select(e => e.AvatarImage).FirstOrDefault(),
Num = r.Sum(e => e.CakeNum),
Price = r.Sum(e => e.Price)
}).
OrderBy(r => r.CakeID).ToList()
});
foreach (var r in receives.ToList())
{
var tempCakeList = new List<CakeModel_ReceiveModel>();
foreach (var cake in r.CakeList)
{
tempCakeList.Add(new CakeModel_ReceiveModel()
{
ID = cake.CakeID,
AvatarImage = cake.AvatarImage,
Name = cake.Name,
Num = cake.Num,
Price = cake.Price
});
}
var tempReceive = new ReceiveModel
{
ID = r.ID,
Date = r.Date,
CountCake = r.CountCake,
SumCake = r.SumCake,
Total = r.Total,
CakeList = tempCakeList
};
result.Add(tempReceive);
}
return result;
}
public long ReceiveCount()
{
long result = Database.RECEIVEs
.GroupBy(r => r.ID)
.Select(r => r.Key).Count();
return result;
}
#endregion Receive
#region Order_Detail
/// <summary>
/// Hàm lấy dánh sách tất cả bánh của đơn hàng theo OrderId
/// </summary>
/// <param name="OrderId">ID (OrderId)</param>
/// <returns></returns>
public List<ORDER_DETAIL> OrderDetailList(long OrderId)
{
var order_details = Database.ORDER_DETAIL;
var query = from o in order_details
where o.OrderID == OrderId
select o;
var list = query.ToList();
return list;
}
#endregion
#region Status
/// <summary>
/// Hàm lấy dánh sách tất cả hình thức thanh toán
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public List<STATUS> StatusList()
{
var sTATUs = Database.STATUS.ToList();
return sTATUs;
}
public string GetSTATUSsName(string ID)
{
var status = Database.STATUS;
var query = from s in status
where s.ID == ID
select s.Name;
string name = query.ToList()[0].ToString();
return name;
}
public STATUS GetStatusByID(string ID)
{
var status = Database.STATUS;
var query = from s in status
where s.ID == ID
select s;
STATUS result = query.ToList()[0];
return result;
}
#endregion
#region Statistics
public long TotalOrders(int week, int month, int year)
{
long result = 0;
int start = 1;
int end = 7;
switch (week)
{
case 0: break;
case 1: start = 8; end = 14; break;
case 2: start = 15; end = 21; break;
case 3:
start = 8; end = DateTime.DaysInMonth(year, month); break;
}
var orders = Database.ORDERs
.Where(o => o.DateCompleted.Month == month
&& o.DateCompleted.Year == year
&& o.DateCompleted.Day > start
&& o.DateCompleted.Day < end
)
.GroupBy(o => o.ID)
.Select(o => new
{
SUM = o.Sum(or => or.TotalBill)
}).FirstOrDefault();
if (orders != null)
{
result = orders.SUM;
}
else
{
}
return result;
}
public List<(long, string, long)> TotalOrders_CakeCat(int week, int month, int year)
{
var result = new List<(long, string, long)>();
long deFault = 0;
int start = 1;
int end = 7;
switch (week)
{
case 0: break;
case 1: start = 8; end = 14; break;
case 2: start = 15; end = 21; break;
case 3:
start = 8; end = DateTime.DaysInMonth(year, month); break;
}
var orders = Database.ORDERs
.Where(o => o.DateCompleted.Month == month
&& o.DateCompleted.Year == year
&& o.DateCompleted.Day > start
&& o.DateCompleted.Day < end
)
.Join(Database.ORDER_DETAIL, o => o.ID, od => od.OrderID, (o, od) => new
{
od.OrderID,
od.ProductID,
od.ProductNum,
od.Price
});
var order_cake = Database.CAKEs
.Join(orders,
c => c.ID,
o => o.ProductID,
(c, o) => new
{
o.OrderID,
c.CatID,
o.ProductID,
Money = o.ProductNum * o.Price
}).DefaultIfEmpty();
var temp = Database.CATEGORies
.GroupJoin(order_cake,
cat => cat.ID,
od_c => od_c.CatID,
(cat, od_c) => new
{
cat.ID,
CatName = cat.Name,
Total = (od_c.ToList().Count != 0) ? od_c.Select(o => o.Money).Sum() : deFault
}).DefaultIfEmpty();
foreach (var item in temp)
{
result.Add((item.ID, item.CatName, item.Total));
}
return result;
}
public long TotalReceives(int week, int month, int year)
{
long result = 0;
int start = 1;
int end = 7;
switch (week)
{
case 0: break;
case 1: start = 8; end = 14; break;
case 2: start = 15; end = 21; break;
case 3:
start = 8; end = DateTime.DaysInMonth(year, month); break;
}
var receives = Database.RECEIVEs
.Where(o => o.DateAdded.Month == month
&& o.DateAdded.Year == year
&& o.DateAdded.Day > start
&& o.DateAdded.Day < end
)
.GroupBy(o => o.ID)
.Select(o => new
{
SUM = o.Sum(or => or.TotalBill)
}).FirstOrDefault();
if (receives != null)
{
result = receives.SUM;
}
else { }
return result;
}
public List<(long, string, long)> TotalReceives_CakeCat(int week, int month, int year)
{
var result = new List<(long, string, long)>();
long deFault = 0;
int start = 1;
int end = 7;
switch (week)
{
case 0: break;
case 1: start = 8; end = 14; break;
case 2: start = 15; end = 21; break;
case 3:
start = 8; end = DateTime.DaysInMonth(year, month); break;
}
var receives = Database.RECEIVEs
.Where(o => o.DateAdded.Month == month
&& o.DateAdded.Year == year
&& o.DateAdded.Day > start
&& o.DateAdded.Day < end
)
.Join(Database.ORDER_DETAIL, o => o.ID, od => od.OrderID, (o, od) => new
{
od.OrderID,
od.ProductID,
od.ProductNum,
od.Price
});
var order_cake = Database.CAKEs
.Join(receives,
c => c.ID,
o => o.ProductID,
(c, o) => new
{
o.OrderID,
c.CatID,
o.ProductID,
Money = o.ProductNum * o.Price
}).DefaultIfEmpty();
var temp = Database.CATEGORies
.GroupJoin(order_cake,
cat => cat.ID,
od_c => od_c.CatID,
(cat, od_c) => new
{
cat.ID,
CatName = cat.Name,
Total = (od_c.ToList().Count != 0) ? od_c.Select(o => o.Money).Sum() : deFault
}).DefaultIfEmpty();
foreach (var item in temp)
{
result.Add((item.ID, item.CatName, item.Total));
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
///
public void Statistics(DateTime start, DateTime end = default(DateTime))
{
var newEnd = (end == default(DateTime)) ? DateTime.Now : end;
var orderlist = Database.ORDERs
.Select(o => o.DateCompleted >= start && o.DateCompleted <= newEnd)
;
var orderlist2 = Database.ORDERs
//.GroupBy(o=> o.DateCompleted.Month == 1)
.Select(o => o.DateCompleted >= start && o.DateCompleted <= newEnd)
;
var receivelist = Database.RECEIVEs
.Select(r => r.DateAdded >= start && r.DateAdded <= newEnd);
}
#endregion Statistics
}
}
|
using REQFINFO.Repository.DataEntity;
using REQFINFO.Repository.Infrastructure;
using REQFINFO.Repository.Infrastructure.Contract;
using REQFINFO.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace REQFINFO.Repository
{
public class WorkFlowUserGroupRepository: BaseRepository<WorkFlowUserGroup>
{
GIGEntities entities;
public WorkFlowUserGroupRepository(IUnitOfWork unit)
: base(unit)
{
entities = (GIGEntities)this.UnitOfWork.Db;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace OCP.AppFramework.Http
{
/**
* Class ContentSecurityPolicy is a simple helper which allows applications to
* modify the Content-Security-Policy sent by Nextcloud. Per default only JavaScript,
* stylesheets, images, fonts, media and connections from the same domain
* ('self') are allowed.
*
* Even if a value gets modified above defaults will still get appended. Please
* notice that Nextcloud ships already with sensible defaults and those policies
* should require no modification at all for most use-cases.
*
* This class allows unsafe-eval of javascript and unsafe-inline of CSS.
*
* @package OCP\AppFramework\Http
* @since 8.1.0
*/
public class ContentSecurityPolicy : EmptyContentSecurityPolicy
{
/** @var bool Whether inline JS snippets are allowed */
protected bool inlineScriptAllowed = false;
/** @var bool Whether eval in JS scripts is allowed */
protected bool evalScriptAllowed = false;
/** @var array Domains from which scripts can get loaded */
protected IList<string> allowedScriptDomains = new List<string>
{
"\"self\""
};
/**
* @var bool Whether inline CSS is allowed
* TODO: Disallow per default
* @link https://github.com/owncloud/core/issues/13458
*/
protected bool inlineStyleAllowed = true;
/** @var array Domains from which CSS can get loaded */
protected IList<string> allowedStyleDomains = new List<string>
{
"\"self\""
};
/** @var array Domains from which images can get loaded */
protected IList<string> allowedImageDomains = new List<string>
{
"\"self\"",
"data:",
"blob:",
};
/** @var array Domains to which connections can be done */
protected IList<string> allowedConnectDomains = new List<string>
{
"\"self\""
};
/** @var array Domains from which media elements can be loaded */
protected IList<string> allowedMediaDomains = new List<string>
{
"\"self\""
};
/** @var array Domains from which object elements can be loaded */
protected IList<string> allowedObjectDomains = new List<string>();
/** @var array Domains from which iframes can be loaded */
protected IList<string> allowedFrameDomains = new List<string>();
/** @var array Domains from which fonts can be loaded */
protected IList<string> allowedFontDomains = new List<string>
{
"\"self\"",
"data:"
};
/** @var array Domains from which web-workers and nested browsing content can load elements */
protected IList<string> allowedChildSrcDomains = new List<string>();
/** @var array Domains which can embed this Nextcloud instance */
protected IList<string> allowedFrameAncestors = new List<string>
{
"\"self\""
};
/** @var array Domains from which web-workers can be loaded */
protected IList<string> allowedWorkerSrcDomains = new List<string>();
/** @var array Locations to report violations to */
protected IList<string> reportTo = new List<string>();
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace JJApi.Controllers
{
public class RegisterController : Controller
{
[HttpPost]
[Route("/Register/setData")]
public string setDataCompanyprofile([FromForm] IFormFile file, Dictionary<string, string> collection)
{
BL.queries.blRegister bRegister = new BL.queries.blRegister();
string result = bRegister.setDataCompanyprofile(null,collection);
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SKT.MES.Web.AjaxServices.Report;
namespace SKT.MES.Web.Report
{
public partial class ReportTemplateEdit : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxServiceReport));
if (!IsPostBack)
{
this.ddlReport.Items.Insert(0, new ListItem("", ""));
int tmplId = Convert.ToInt32(Request.QueryString["ID"]);
if (tmplId != -1)
{
SKT.MES.Report.Model.ReportInfo model = (new SKT.MES.Report.BLL.Report()).GetInfo(tmplId);
this.txtTmplName.Enabled = false;
this.txtTmplName.Text = model.RTName;
this.hdnValue.Value = (String.IsNullOrEmpty(model.RTContent)) ? "" : model.RTContent;
this.txtTmplDesc.Text = model.RTDescription;
this.ddlReport.SelectedValue = model.Report;
}
}
}
}
} |
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.SfGauge.XForms;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace SampleBrowser
{
public partial class CircularGauge : SamplePage
{
SfCircularGauge circularGauge;
Scale scale;
NeedlePointer needlePointer;
RangePointer rangePointer;
TickSettings major;
public CircularGauge()
{
InitializeComponent();
StackLayout _layout = new StackLayout();
_layout.Orientation = StackOrientation.Vertical;
_layout.SizeChanged += _layout_SizeChanged;
_layout.VerticalOptions = LayoutOptions.FillAndExpand;
_layout.Children.Add(getCircularGauge());
this.ContentView = _layout;
this.ContentView.BackgroundColor = Color.White;
PropertyLayout();
}
void _layout_SizeChanged(object sender, EventArgs e)
{
circularGauge.WidthRequest = 330;
circularGauge.HeightRequest = 330;
}
SfCircularGauge getCircularGauge()
{
if (this.ContentView == null)
{
circularGauge = new SfCircularGauge();
ObservableCollection<Scale> scales = new ObservableCollection<Scale>();
circularGauge.VerticalOptions = LayoutOptions.CenterAndExpand;
//Scales
scale = new Scale();
scale.StartValue = 0;
scale.EndValue = 100;
scale.Interval = 10;
scale.StartAngle = 135;
scale.SweepAngle = 270;
scale.RimThickness = 20;
scale.RimColor = Color.FromHex("#d14646");
scale.LabelColor = Color.Gray;
scale.LabelOffset = 0.1;
scale.MinorTicksPerInterval = 0;
List<Pointer> pointers = new List<Pointer>();
needlePointer = new NeedlePointer();
needlePointer.Value = 60;
needlePointer.Color = Color.Gray;
needlePointer.KnobRadius = 20;
needlePointer.KnobColor = Color.FromHex("#2bbfb8");
needlePointer.Thickness = 5;
needlePointer.LengthFactor = 0.8;
needlePointer.Type = PointerType.Bar;
rangePointer = new RangePointer();
rangePointer.Value = 60;
rangePointer.Color = Color.FromHex("#2bbfb8");
rangePointer.Thickness = 20;
pointers.Add(needlePointer);
pointers.Add(rangePointer);
TickSettings minor = new TickSettings();
minor.Length = 4;
minor.Color = Color.FromHex("#444444");
minor.Thickness = 3;
scale.MinorTickSettings = minor;
major = new TickSettings();
major.Length = 12;
major.Color = Color.FromHex("#444444");
major.Thickness = 3;
major.Offset = Device.OnPlatform(0.05, 0.1,0.3);
scale.MajorTickSettings = major;
scale.Pointers = pointers;
scales.Add(scale);
circularGauge.Scales = scales;
Header header = new Header();
header.Text = "Speedmeter";
header.TextSize = 20;
header.Position = Device.OnPlatform(iOS: new Point(.3, .7), Android: new Point(0.38, 0.7), WinPhone: new Point(0.38, 0.7));
header.ForegroundColor = Color.Gray;
circularGauge.Headers.Add(header);
}
return circularGauge;
}
void PropertyLayout()
{
StackLayout stack = new StackLayout();
stack.BackgroundColor = Color.White;
stack.Padding = 10;
Label pointer = new Label();
pointer.Text = "Pointer Value";
if (Device.OS == TargetPlatform.iOS)
{
pointer.FontSize = 15;
}
else if (Device.OS == TargetPlatform.Android)
{
pointer.FontSize = 15;
}
else
{
pointer.FontSize = 20;
}
pointer.TextColor = Color.Black;
pointer.FontAttributes = FontAttributes.Bold;
Xamarin.Forms.Slider pointerSlider = new Xamarin.Forms.Slider();
pointerSlider.Maximum = 100;
if (Device.OS == TargetPlatform.WinPhone)
{
pointerSlider.BackgroundColor = Color.Gray;
}
pointerSlider.Value = 60;
pointerSlider.ValueChanged += pointerSlider_ValueChanged;
stack.Children.Add(pointer);
stack.Children.Add(pointerSlider);
this.PropertyView = stack;
}
void tickSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
major.Offset = ((double)e.NewValue);
}
void labelSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
scale.LabelOffset = ((double)e.NewValue);
}
void pointerSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
needlePointer.Value = e.NewValue;
rangePointer.Value = e.NewValue;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Species : MonoBehaviour
{
public enum Type
{
Flower,
Bush,
Grass,
Sheep,
}
public static T GetClassByName<T>(Species.Type type)
{
switch (type)
{
case Type.Flower:
return (T)(object)new Flower().GetType();
/*
case Type.Bush:
return (T)(object)new Bush().GetType();
case Type.Grass:
return (T)(object)new Grass().GetType();
*/
case Type.Sheep:
return (T)(object)new Sheep().GetType();
default:
return default(T);
}
}
public static Component GetScriptComponent(GameObject target)
{
Component component = null;
foreach (string name in Enum.GetNames(typeof(Species.Type)))
{
if (target.GetComponent(name) != null)
{
component = target.GetComponent(name);
}
}
return component;
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using InventoryTrackingSystem.Models;
using InventoryTrackingSystem.ViewModels;
namespace InventoryTrackingSystem.Controllers
{
public class ProductController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
protected UserManager<ApplicationUser> UserManager { get; set; }
private Repo_Product repo_product = new Repo_Product();
private Repo_UserProfile repo_userprofile = new Repo_UserProfile();
public ProductController()
{
db = new ApplicationDbContext();
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
}
// GET: /Product/
public ActionResult Index()
{
if (User.IsInRole("Admin") || User.IsInRole("User"))
{
return View(repo_product.getProductList());
}
// Anonymous - must log in as User or Admin
else
{
return RedirectToAction("Login", "Account");
}
}
// GET: /Product/Details/5
public ActionResult Details(int? id)
{
RedirectToAction("Index", "Product");
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
return View(repo_product.getProductDetails(id));
}
}
// GET: /Product/Create
[Authorize(Roles = "Admin")]
public ActionResult Create()
{
return View();
}
// POST: /Product/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "productId,productName,description,price,quantity")] Product product)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Details view for Admin
else if (User.IsInRole("Admin"))
{
return View(repo_product.getProductForEdit(id));
}
else
{
return RedirectToAction("Index", "Home");
}
}
// POST: /Product/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "productId,productName,description,price")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.Entry(product).Property(x => x.quantity).IsModified = false;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: /Product/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Turnamentor.Core.RoundSelecting
{
class RoundSelectorConfig
{
public int NumberOfContestantsInRound { get; set; }
public List<Type> Contestants { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ApiCatalogoCarro.InputModel
{
public class CarroInputModel
{
[Required]
[StringLength(100, MinimumLength = 3, ErrorMessage = "O nome do carro deve conter entre 3 e 100 caracteres")]
public string Nome { get; set; }
[Required]
[StringLength(100, MinimumLength = 1, ErrorMessage = "O nome do fabricante deve conter entre 3 e 100 caracteres")]
public string Fabricante { get; set; }
[Required]
[Range(1, 1000, ErrorMessage = "O preço deve ser de no mínimo 1 Metical e no máximo 1000 Meticais")]
public double Preco { get; set; }
}
}
|
using System;
namespace Promelectro.Api.Models
{
public class File
{
public int Id { get; set; }
public string Description { get; set; }
public int UserId { get; set; }
public int? PostId { get; set; }
public DateTime DateLoad { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
namespace Shooter
{
class Program
{
public static void Main(string[] args)
{
IScreen screen = new Main();
while ((screen = screen.Start()) != null) ;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GamingLogic
{
public class StaffCoding
{
public IEnumerable<string> RepeatString5Times(string repeat)
{
if (repeat == null)
{
throw new ArgumentNullException(nameof(repeat));
}
for (int i = 0; i < 5; i++)
{
if (i == 3)
{
throw new ArgumentNullException("We just testing code");
}
yield return $"The number {repeat} and {i}";
}
}
}
}
|
using Cloudies.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Cloudies.Web.Controllers.Labs
{
public class NewLabsController : Controller
{
//
// GET: /NewLabs/
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ViewModelNewLab newLab)
{
Lab lab = new Lab();
lab.Start_Time = newLab.Start_Time;
lab.End_Time = newLab.End_Time;
lab.Name = newLab.Name.Trim();
lab.Time_Zone = "Asia/Calcutta";
lab.Status = "Scheduled";
lab.User_ID = 5;
LabConfiguration labConfig = new LabConfiguration();
labConfig.OS = newLab.OS.Trim();
labConfig.VM_Count = newLab.VM_Count;
labConfig.Hard_Disk = newLab.Hard_Disk.Trim();
labConfig.VM_Type = newLab.VM_Type.Trim();
labConfig.Networked = newLab.VMNetwork.Trim();
IjepaiEntities db = new IjepaiEntities();
db.LabConfigurations.Add(labConfig);
try
{
db.SaveChanges();
lab.Config_ID = labConfig.ID;
db.Labs.Add(lab);
db.SaveChanges();
StoreParticipants(newLab.Participants, lab.ID);
}
catch (Exception ex)
{
string message = ex.ToString();
}
return View("~/Views/MyLabs/Index.cshtml");
}
public int StoreParticipants(ICollection<Participant> Participants, int Participants_Of_Lab)
{
IjepaiEntities db = new IjepaiEntities();
db.LabParticipants.Where(p => p.Lab_Id == Participants_Of_Lab).ToList().ForEach(p => db.LabParticipants.Remove(p));
if (Participants != null)
{
foreach (Participant participant in Participants)
{
if (participant.Username != null)
{
LabParticipant labParticipant = new LabParticipant();
labParticipant.Email_Address = participant.Username.Trim();
if(participant.First_Name != null) labParticipant.First_Name = participant.First_Name.Trim();
if(participant.Last_Name != null) labParticipant.Last_Name = participant.Last_Name.Trim();
labParticipant.Role = participant.Role.Trim();
labParticipant.Lab_Id = Participants_Of_Lab;
db.LabParticipants.Add(labParticipant);
db.SaveChanges();
}
}
}
return 0;
}
[HttpPost]
public JsonResult EditLab(ViewModelEditLab labProp)
{
IjepaiEntities db = new IjepaiEntities();
Lab lab = db.Labs.Find(labProp.Lab_ID_For_Edit);
lab.Name = labProp.Name.Trim();
lab.Start_Time = labProp.Start_Time;
lab.End_Time = labProp.End_Time;
lab.LabConfiguration.Networked = labProp.VMNetwork.Trim();
lab.LabConfiguration.OS = labProp.OS.Trim();
lab.LabConfiguration.VM_Type = labProp.VM_Type.Trim();
lab.LabConfiguration.VM_Count = labProp.VM_Count;
db.Entry(lab).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(new { Status = 0, Message = "Lab updated succesfully." });
}
[HttpPost]
public JsonResult ExtendLab(ViewModelExtendLab labProp)
{
IjepaiEntities db = new IjepaiEntities();
Lab lab = db.Labs.Find(labProp.Lab_ID_For_Extend);
lab.End_Time = labProp.End_Time;
db.SaveChanges();
return Json(new { Status = 0, Message = "Lab extended successfully." });
}
[HttpPost]
public JsonResult DeleteLab(int Lab_ID_For_Deletion)
{
IjepaiEntities db = new IjepaiEntities();
db.Billings.Where(bill => bill.Lab_Id == Lab_ID_For_Deletion).ToList().ForEach(b => db.Billings.Remove(b));
db.LabParticipants.Where(p => p.Lab_Id == Lab_ID_For_Deletion).ToList().ForEach(p => db.LabParticipants.Remove(p));
Lab lab = db.Labs.Find(Lab_ID_For_Deletion);
db.LabSoftwares.Where(s => s.Config_Id == lab.Config_ID).ToList().ForEach(s => db.LabSoftwares.Remove(s));
db.LabConfigurations.Where(c => c.ID == lab.Config_ID).ToList().ForEach(c => db.LabConfigurations.Remove(c));
db.Labs.Remove(lab);
db.SaveChanges();
return Json(new { Status = 0, Message = "Lab deleted successfully." });
}
public ActionResult BlankParticipantRow(int Count)
{
ViewBag.ParticipantNum = Count;
return View("NewParticipantRow", new Participant());
}
}
} |
using System;
namespace Revature_Project1.Models
{
public class BusinessCheckingAccount : Checking
{
LoanAccount businessLoan;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Mentors.Models
{
public class Mentor : Person, IComparable<Mentor>
{
[Required]
public int ExperienceInYear { get; set; }
[Required]
public int MaxStudentCount { get; set; }
public int CurrentStudentCount { get; set; }
public int FreeStudentCount => MaxStudentCount - CurrentStudentCount;
public string PlaceOfWork { get; set; }
public ICollection<MentorStudent> MentorStudent { get; set; }
public ICollection<MentorTecnology> MentorTecnology { get; set; }
public Mentor()
{
MentorStudent = new List<MentorStudent>();
MentorTecnology = new List<MentorTecnology>();
}
public int CompareTo(Mentor other)
{
if (Id > other.Id)
{
return 1;
}
if (Id < other.Id)
{
return -1;
}
return 0;
}
}
}
|
using System.Threading.Tasks;
namespace t4ccer.Noisy
{
public static class NoiseExtensions
{
public static Plane AtPlane(this INoise noise, double startX, double startY, int width, int height, double increment)
=> noise.AtPlane(startX, startY, 0, width, height, increment);
public static Plane AtPlane(this INoise noise, double startX, double startY, double z, int width, int height, double increment)
{
var values = new double[width, height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
var val = noise.At(startX + x * increment, startY + y * increment, z);
values[x, y] = val;
}
}
return values;
}
public static Plane AtPlaneParallel(this INoise noise, double startX, double startY, int width, int height, double increment)
=> noise.AtPlaneParallel(startX, startY, 0, width, height, increment);
public static Plane AtPlaneParallel(this INoise noise, double startX, double startY, double z, int width, int height, double increment)
{
var values = new double[width, height];
Parallel.For(0, width * height, i =>
{
int x = i / height;
int y = i % height;
var val = noise.At(startX + x * increment, startY + y * increment, z);
values[x, y] = val;
});
return values;
}
public static Line AtLine(this INoise noise, double startX, int width, double increment)
=> AtLine(noise, startX, 0, 0, width, increment);
public static Line AtLine(this INoise noise, double startX, double y, double z, int width, double increment)
{
var values = new double[width];
for (int x = 0; x < width; x++)
{
var val = noise.At(startX + x * increment, y, z);
values[x] = val;
}
return values;
}
}
}
|
using System;
using Ganaderia.App.Dominio;
using Ganaderia.App.Persistencia;
namespace Ganaderia.App.Consola
{
class Program
{
private static IRepositorioGanadero _repoGanadero = new RepositorioGanadero(new Persistencia.AppContext());
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//AddGanadero();
//GetAllGanaderos();
//UpdateGanadero();
DeleteGanadero(1003);
//GetGanadero(1);
}
private static void AddGanadero()
{
var ganadero = new Ganadero
{
Nombres = "Mario",
Apellidos = "Herrera",
NumeroTelefono = "3148596563",
Direccion = "Kra 4 #45-12",
Correo = "sergio.mintic@ucaldas.edu.co",
Contrasena = "123456",
Latitude = 7455,
Longitud = 5333
};
_repoGanadero.AddGanadero(ganadero);
}
private static void GetAllGanaderos()
{
var ganaderos = _repoGanadero.GetAllGanaderos();
foreach(Ganadero item in ganaderos)
{
Console.WriteLine(item.Nombres);
}
}
private static void UpdateGanadero()
{
var ganadero = new Ganadero
{
Id = 2,
Nombres = "Pedro",
Apellidos = "Sanchez",
NumeroTelefono = "3148596563",
Direccion = "Kra 4 #45-12",
Correo = "sergio.mintic@ucaldas.edu.co",
Contrasena = "123456",
Latitude = 7455,
Longitud = 5333
};
_repoGanadero.UpdateGanadero(ganadero);
}
private static void DeleteGanadero(int idGanadero)
{
//var response = _repoGanadero.DeleteGanadero(idGanadero);
string message = _repoGanadero.DeleteGanadero(idGanadero) ? "El ganadero se ha eliminado correctamemte" : "El ganadero no ha sido encontrado";
Console.WriteLine(message);
// if (response)
// {
// Console.WriteLine("El ganadero se ha eliminado correctamemte");
// } else
// {
// Console.WriteLine("El ganadero no ha sido encontrado");
// }
}
private static void GetGanadero(int idGanadero)
{
var ganadero = _repoGanadero.GetGanadero(idGanadero);
Console.WriteLine("El nombre del ganadero es: " + ganadero.Nombres);
}
}
}
|
namespace Logs.Models
{
public class Subscription
{
public Subscription()
{
}
public Subscription(int logId, string userId)
{
this.UserId = userId;
this.TrainingLogId = logId;
}
public int SubscriptionId { get; set; }
public string UserId { get; set; }
public int TrainingLogId { get; set; }
public virtual User User { get; set; }
public virtual TrainingLog TrainingLog { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace app
{
public interface IGetDataService
{
// Task<IDictionary<int, Book>> GetBooksAsync(IEnumerable<int> authorIds, CancellationToken cancellationToken);
Task<ILookup<int, Book>> GetBooksAsync(IEnumerable<int> authorIds);
Task<ILookup<int, SalesInvoice>> GetSalesInvoicesAsync(IEnumerable<int> bookIds);
Task<IDictionary<int, Author>> GetAuthorsByIdAsync(IEnumerable<int> authorIds, CancellationToken cancellationToken);
Task<IDictionary<int, String>> GetAuthorsNameAsync(IEnumerable<int> authorIds, CancellationToken cancellationToken);
}
public class GetDataService : IGetDataService
{
public readonly ApplicationDbContext db;
public GetDataService(ApplicationDbContext _db)
{
db = _db;
}
public async Task<ILookup<int, Book>> GetBooksAsync(IEnumerable<int> authorIds)
{
var books = await db.Books.Where(b => authorIds.Contains(b.AuthorId)).ToListAsync();
return books.ToLookup(b => b.AuthorId);
}
public async Task<ILookup<int, SalesInvoice>> GetSalesInvoicesAsync(IEnumerable<int> bookIds)
{
var salesInvoices = await db.SalesInvoices.Where(b => bookIds.Contains(b.BookId)).ToListAsync();
return salesInvoices.ToLookup(b => b.BookId);
}
public async Task<IDictionary<int, Author>> GetAuthorsByIdAsync(IEnumerable<int> authorIds, CancellationToken cancellationToken){
return await db.Authors.Where(a => authorIds.Contains(a.Id)).ToDictionaryAsync(a => a.Id, a => a);
}
public async Task<IDictionary<int, String>> GetAuthorsNameAsync(IEnumerable<int> authorIds, CancellationToken cancellationToken){
return await db.Authors.Where(a => authorIds.Contains(a.Id)).ToDictionaryAsync(a => a.Id, a => a.Name);
}
}
} |
using DutchTreat.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication4.Data
{
public class DutchRepository : IDutchRepository
{
private readonly DutchContext _ctx;
private readonly ILogger<DutchRepository> _logger;
public DutchRepository(DutchContext ctx, ILogger<DutchRepository> logger)
{
_ctx = ctx;
_logger = logger;
}
public IEnumerable<Product> GetAllProducts()
{
try
{
_logger.LogInformation("GetAllProducts() was called");
return _ctx.Products.OrderBy(p => p.Title).ToList();
}
catch(Exception exp)
{
_logger.LogError("Failed to get All producctsion : " + exp.ToString());
}
return null;
}
public IEnumerable<Order> GetAllOrders()
{
_logger.LogInformation("GetAllOrders() was called");
return _ctx.Orders.Include(o => o.Items)
.ThenInclude(i => i.Product)
.ToList();
}
public IEnumerable<Product> GetProductByCategory(string Category)
{
return _ctx.Products.Where(p => p.Category == Category).ToList();
}
public bool SaveAll()
{
return _ctx.SaveChanges() > 0;
}
public Order GetOrderById(int id)
{
return _ctx.Orders.Include(o => o.Items)
.ThenInclude(i => i.Product)
.Where (o => o.Id == id)
.FirstOrDefault();
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Aspit.StudentReg.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspit.StudentReg.Entities;
namespace Aspit.StudentReg.Tests
{
[TestClass]
public class StudentsTests
{
readonly int id = 1;
readonly string name = " per Bosen ";
readonly string expectedName = "Per Bosen";
readonly string uniLogin = "perx234k";
/// <summary>
/// Creates a basic student object using the readonly fields: id,name,expectedName,uniLogin
/// </summary>
/// <returns>A basic student</returns>
public Student GetBasicStudent()
{
return new Student(id, name, uniLogin);
}
[TestMethod]
public void Initialization()
{
Assert.AreNotEqual(null, GetBasicStudent());
}
[TestMethod]
public void StudentValueTest()
{
Student student = GetBasicStudent();
Assert.AreEqual(id, student.Id);
Assert.AreEqual(expectedName, student.Name);
Assert.AreEqual(uniLogin, student.UniLogin);
}
[TestMethod]
public void StudentAttendanceRegistrationsAssignment()
{
AttendanceRegistration registration = new AttendanceRegistration
{
Id = 1,
LeavingTime = new DateTime(2018, 6, 11, 23, 59, 59),
MeetingTime = new DateTime(2018, 6, 11, 9, 0, 0)
};
Student student = GetBasicStudent();
student.AttendanceRegistrations = registration;
Assert.AreEqual(registration, student.AttendanceRegistrations);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Unilogin is invalid")]
public void StudentUniLoginError()
{
Student student = new Student(id, name, "PerBo");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Name is invalid")]
public void StudentNameError()
{
Student student = new Student(id, "!Per 0Bo", uniLogin);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException),
"Id cannot be less than 0")]
public void StudentIdError()
{
Student student = new Student(-1, name, uniLogin);
}
[TestMethod()]
public void Compare()
{
//Test if names are sorted alphabeticly
Student student1 = new Student(0, "Morten", uniLogin);
Student student2 = new Student(1, "Magnus", uniLogin);
Assert.AreEqual(1, Student.Compare(student1, student2));
//Test if students with an attendanceRegistration sorts
student1.AttendanceRegistrations = new AttendanceRegistration
{
MeetingTime = DateTime.Now
};
Assert.AreEqual(-1, Student.Compare(student1, student2));
}
}
} |
namespace Standard
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal delegate IntPtr MessageHandler(Standard.WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
}
|
using System;
using System.Collections.Generic;
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;
using Newtonsoft.Json.Linq;
namespace protótipos
{
public partial class EstoqueForm : Form
{
string url = "http://localhost/Projeto-Estoque-master/";
public EstoqueForm()
{
InitializeComponent();
carregaTabela();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void atualizar_Click(object sender, EventArgs e)
{
carregaTabela();
}
private void carregaTabela()
{
tabela.Columns.Clear();
tabela.Items.Clear();
ColumnHeader ch = new ColumnHeader();
ch.Text = "Produto";
tabela.Columns.Add(ch);
ch = new ColumnHeader();
ch.Text = "peso";
tabela.Columns.Add(ch);
ch = new ColumnHeader();
ch.Text = "quantidade";
tabela.Columns.Add(ch);
ch = new ColumnHeader();
ch.Text = "Data de vencimento";
tabela.Columns.Add(ch);
ch = new ColumnHeader();
ch.Text = "Data de Chegada";
tabela.Columns.Add(ch);
ch = new ColumnHeader();
ch.Text = "Cpf do Usuário";
tabela.Columns.Add(ch);
//view = details
try
{
var requisicaoWeb = WebRequest.CreateHttp(url + "estoque/listar.php");
requisicaoWeb.Method = "GET";
requisicaoWeb.UserAgent = "RequisicaoWebDemo";
using (var resposta = requisicaoWeb.GetResponse())
{
var streamDados = resposta.GetResponseStream();
StreamReader reader = new StreamReader(streamDados);
object objResponse = reader.ReadToEnd();
MessageBox.Show(objResponse.ToString());
var jo = JObject.Parse(objResponse.ToString());
var games = jo["estoques"].ToObject<Estoque[]>();
foreach (var game in games)
{
ListViewItem item = new ListViewItem();
item.Text = game.produto;
item.SubItems.Add(game.peso.ToString());
item.SubItems.Add(game.quantidade.ToString());
item.SubItems.Add(game.data_de_vencimento);
item.SubItems.Add(game.data_de_chegada);
item.SubItems.Add(game.cpf_funcionario);
tabela.Items.Add(item);
tabela.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
streamDados.Close();
resposta.Close();
}
}
catch
{
MessageBox.Show("Tente novamente, erro de conexão!");
}
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
/** 版本信息模板在安装目录下,可自行修改。
* PaperCardexercise.cs
*
* 功 能: N/A
* 类 名: PaperCardexercise
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014/11/28 16:20:51 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace IES.Resource.Model
{
/// <summary>
/// 答题卡习题
/// </summary>
[Serializable]
public partial class PaperCardexercise
{
public PaperCardexercise()
{}
#region Model
private int _cardexerciseid;
private int _paperid;
private int _exercisetype;
private int _choicenum;
private string _answer;
private decimal _score;
private int _orde;
/// <summary>
/// 主键
/// </summary>
public int CardExerciseID
{
set{ _cardexerciseid=value;}
get{return _cardexerciseid;}
}
/// <summary>
/// 试卷编号
/// </summary>
public int PaperID
{
set{ _paperid=value;}
get{return _paperid;}
}
/// <summary>
/// 1.判断;2单选;3多选;4填空;5简答题
/// </summary>
public int ExerciseType
{
set{ _exercisetype=value;}
get{return _exercisetype;}
}
/// <summary>
/// 选项的数量
/// </summary>
public int ChoiceNum
{
set{ _choicenum=value;}
get{return _choicenum;}
}
/// <summary>
/// 答案.
///单选题答案 : 3 表示第三个选项是正确答案
///多选题答案 : 2able2004acc20053 表示第2,3是正确答案,答案分隔符号able2004acc2005
///填空题答案:北京able2004acc2005上海 表示第一个填空答案是北京 第二题的填空是上海 分隔符号able2004acc2005
/// </summary>
public string Answer
{
set{ _answer=value;}
get{return _answer;}
}
/// <summary>
/// 分值
/// </summary>
public decimal Score
{
set{ _score=value;}
get{return _score;}
}
/// <summary>
/// 习题的顺序
/// </summary>
public int Orde
{
set{ _orde=value;}
get{return _orde;}
}
#endregion Model
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Perpustakaan.Data;
using Microsoft.AspNetCore.Http;
namespace Perpustakaan.Controllers
{
public class LoginController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Authorize(Perpustakaan.Models.Users userModel)
{
using(ApplicationDbContext db = new ApplicationDbContext()){
var userDetails = db.Users.Where(x => x.Email == userModel.Email && x.Password == userModel.Password).FirstOrDefault();
if(userDetails == null)
{
return View("Index");
}
else{
HttpContext.Session.SetString("UserId", userDetails.Email);
return RedirectToAction("Index", "Peminjaman");
}
}
}
public IActionResult Logout()
{
HttpContext.Session.Remove("UserId");
return RedirectToAction("Index", "Login");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.PluginInterfaces.V2;
using VVVV.PluginInterfaces.V1;
using VVVV.Utils.VMath;
using System.Runtime.InteropServices;
using VVVV.MSKinect.Lib;
using System.ComponentModel.Composition;
using SlimDX.Direct3D9;
using SlimDX;
using Microsoft.Kinect;
using VVVV.Nodes.OpenCV;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.Drawing;
namespace VVVV.MSKinect.Nodes
{
[PluginInfo(Name = "FindBoard", Category = "Kinect", Version = "Microsoft", Author = "elliotwoods", Credits = "vux", Tags = "directx,texture")]
public class FindBoardNode : IPluginEvaluate, IPluginConnections
{
#region pins and fields
[Input("Kinect Runtime")]
private Pin<KinectRuntime> FInRuntime;
[Input("Board Size X", DefaultValue=10, MinValue=1)]
private IDiffSpread<int> FInBoardX;
[Input("Board Size Y", DefaultValue = 7, MinValue = 1)]
private IDiffSpread<int> FInBoardY;
[Input("Do", IsBang = true)]
private ISpread<bool> FInDo;
[Input("Enabled", IsSingle=true)]
private IDiffSpread<bool> FInEnabled;
[Output("Corners RGB Map")]
private ISpread<Vector2D> FOutCornersRGBMap;
[Output("Corners Depth Map")]
private ISpread<Vector2D> FOutCornersDepthMap;
[Output("Corners Depth")]
private ISpread<Double> FOutCornersDepth;
[Output("Corners World")]
private ISpread<Vector3D> FOutCornersXYZ;
[Output("Status")]
private ISpread<string> FOutStatus;
private bool FInvalidateConnect = false;
private bool FInvalidate = true;
private KinectRuntime FRuntime;
private byte[] FDataRGB = null;
private short[] FDataDepth = null;
private int[] FMappingColorToDepth = null;
private CVImage FImageRGB = new CVImage();
private CVImage FImageLuminance = new CVImage();
private ColorImagePoint[] FMappingDepthToColor = null;
private DepthImageFormat FDepthFormat;
private ColorImageFormat FColorFormat;
private Size FColorSize;
private Size FDepthSize;
private Object FLockRGB = new Object();
private Object FLockDepth = new Object();
#endregion
[ImportingConstructor()]
public FindBoardNode(IPluginHost host)
{
}
public void Evaluate(int SpreadMax)
{
if (this.FInvalidateConnect)
{
if (FRuntime != null)
{
//remove any listeners
FRuntime.ColorFrameReady -= FRuntime_ColorFrameReady;
FRuntime.DepthFrameReady -= FRuntime_DepthFrameReady;
}
if (this.FInRuntime.PluginIO.IsConnected)
{
//Cache runtime node
this.FRuntime = this.FInRuntime[0];
if (FRuntime != null)
{
//add any listeners
FRuntime.ColorFrameReady += new EventHandler<ColorImageFrameReadyEventArgs>(FRuntime_ColorFrameReady);
FRuntime.DepthFrameReady += new EventHandler<DepthImageFrameReadyEventArgs>(FRuntime_DepthFrameReady);
}
}
this.FInvalidateConnect = false;
}
try
{
if (FInDo[0])
{
FindBoards();
FOutStatus[0] = "OK";
}
}
catch (Exception e)
{
FOutStatus[0] = e.Message;
}
}
void FRuntime_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
var frame = e.OpenDepthImageFrame();
if (frame != null && FInEnabled[0])
{
lock (FLockDepth)
{
FDepthFormat = frame.Format;
if (FDataDepth == null || FDataDepth.Length != frame.PixelDataLength)
{
FDataDepth = new short[frame.PixelDataLength];
FDepthSize = new Size(frame.Width, frame.Height);
FMappingDepthToColor = new ColorImagePoint[frame.Width * frame.Height];
}
frame.CopyPixelDataTo(FDataDepth);
if (FColorFormat != ColorImageFormat.Undefined)
{
FRuntime.Runtime.MapDepthFrameToColorFrame(frame.Format, FDataDepth, FColorFormat, FMappingDepthToColor);
}
}
frame.Dispose();
}
}
void FRuntime_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
{
var frame = e.OpenColorImageFrame();
if (frame != null && FInEnabled[0])
{
lock (FLockRGB)
{
FColorFormat = frame.Format;
if (FDataRGB == null || FDataRGB.Length != frame.PixelDataLength)
{
FDataRGB = new byte[frame.PixelDataLength];
FColorSize = new Size(frame.Width, frame.Height);
}
frame.CopyPixelDataTo(FDataRGB);
}
frame.Dispose();
}
}
public void ConnectPin(IPluginIO pin)
{
if (pin == this.FInRuntime.PluginIO)
{
this.FInvalidateConnect = true;
}
}
public void DisconnectPin(IPluginIO pin)
{
if (pin == this.FInRuntime.PluginIO)
{
this.FInvalidateConnect = true;
}
}
private void FindBoards()
{
if (FDataRGB == null)
throw (new Exception("Couldn't read RGB frame"));
if (FDataDepth == null)
throw (new Exception("Couldn't read depth frame"));
lock (FLockDepth)
{
lock (FLockRGB)
{
var kinect = FRuntime.Runtime;
//allocate our version of the color image
if (FImageRGB.Width != FColorSize.Width || FImageRGB.Height != FColorSize.Height)
{
var size = new Size(FColorSize.Width, FColorSize.Height);
FImageRGB.Initialise(size, TColorFormat.RGBA8);
FImageLuminance.Initialise(size, TColorFormat.L8);
}
//invert lookup table
invertLookup();
//convert rgb to luminance
FImageRGB.SetPixels(FDataRGB);
FImageRGB.GetImage(TColorFormat.L8, FImageLuminance);
//find chessboard corners
var pointsInRGB = CameraCalibration.FindChessboardCorners(FImageLuminance.GetImage() as Image<Gray, byte>, new Size(FInBoardX[0], FInBoardY[0]), CALIB_CB_TYPE.ADAPTIVE_THRESH);
//if we didn't find anything, then complain and quit
if (pointsInRGB == null)
throw(new Exception("No chessboard found."));
FOutCornersRGBMap.SliceCount = pointsInRGB.Length;
FOutCornersDepthMap.SliceCount = pointsInRGB.Length;
FOutCornersDepth.SliceCount = pointsInRGB.Length;
FOutCornersXYZ.SliceCount = pointsInRGB.Length;
for(int i=0; i<pointsInRGB.Length; i++)
{
FOutCornersRGBMap[i] = new Vector2D((double)pointsInRGB[i].X, (double)pointsInRGB[i].Y);
var xRGB = (int) pointsInRGB[i].X;
var yRGB = (int) pointsInRGB[i].Y;
var colorIndex = xRGB + yRGB * kinect.ColorStream.FrameWidth;
var depthIndex = FMappingColorToDepth[colorIndex];
var xDepth = depthIndex % kinect.DepthStream.FrameWidth;
var yDepth = depthIndex / kinect.DepthStream.FrameWidth;
FOutCornersDepthMap[i] = new Vector2D((double) xDepth, (double) yDepth);
FOutCornersDepth[i] = (Double)FDataDepth[xDepth + yDepth * FDepthSize.Width];
var world = kinect.MapDepthToSkeletonPoint(FDepthFormat, xRGB, yRGB, FDataDepth[depthIndex]);
FOutCornersXYZ[i] = new Vector3D((double)world.X, (double)world.Y, (double)world.Z);
}
}
}
#region oldcode
////if we've got matching depth and rgb frames then let's find some chessboards!
////if (true || this.rgbFrameAvailable == this.depthFrameAvailable)
//{
// //find points in rgb
// PointF[] pointsRGB;
// lock (FLockRGB)
// {
// var image = FImageLuminance.GetImage() as Emgu.CV.Image<Gray, byte>;
// pointsRGB = CameraCalibration.FindChessboardCorners(image, FBoardSize, CALIB_CB_TYPE.ADAPTIVE_THRESH);
// }
// if (pointsRGB == null)
// return;
// var frameDepth = FRuntime.Runtime.DepthStream.OpenNextFrame()
// //allocate output data
// PointF[] pointsDepthMap = new PointF[pointsRGB.Length];
// Vector3D[] pointsWorld = new Vector3D[pointsRGB.Length];
// ushort[] pointsDepthValue = new ushort[pointsRGB.Length];
// //build rgb->depth lookup table
// invertLookup();
// //lookup world xyz
// lock (FLockDepth)
// {
// int idxRGB, idxDepth;
// ushort depth;
// var widthRGB = this.FRuntime.Runtime.ColorStream.FrameWidth;
// var heightRGB = this.FRuntime.Runtime.ColorStream.FrameHeight;
// var widthDepth = this.FRuntime.Runtime.DepthStream.FrameWidth;
// var formatDepth = this.FRuntime.Runtime.DepthStream.Format;
// for (int i = 0; i < pointsRGB.Length; i++)
// {
// var xInRGB = pointsRGB[i].X;
// var yInRGB = pointsRGB[i].Y;
// if (xInRGB < 0 || xInRGB >= widthRGB || yInRGB < 0 || yInRGB >= heightRGB)
// {
// //this corner appears to be outside rgb map, skip it
// continue;
// }
// idxRGB = (int) xInRGB + (int)( (int) yInRGB * widthRGB);
// idxDepth = FMappingColorToDepth[idxRGB];
// pointsDepthMap[i] = new PointF(idxDepth % widthDepth, idxDepth / widthDepth);
// depth = (ushort) FDataDepth[idxDepth];
// var world = FRuntime.Runtime.MapDepthToSkeletonPoint(formatDepth, (int) pointsDepthMap[i].X, (int) pointsDepthMap[i].Y, FDataDepth[idxDepth]);
// pointsWorld[i] = new Vector3D((double) world.X, (double) world.Y, (double) world.Z);
// }
// }
// lock (FLockPoints)
// {
// FPointsRGBMap.SliceCount = pointsRGB.Length;
// FPointsDepthMap.SliceCount = pointsRGB.Length;
// FPointsWorld.SliceCount = pointsRGB.Length;
// for (int i = 0; i < pointsRGB.Length; i++)
// {
// FPointsRGBMap[i] = new Vector2D((double) pointsRGB[i].X, (double) pointsRGB[i].Y);
// FPointsDepthMap[i] = new Vector2D((double)pointsDepthMap[i].X, (double)pointsDepthMap[i].Y);
// FPointsWorld[i] = pointsWorld[i];
// }
// }
// }
#endregion
}
private void invertLookup()
{
if (FMappingColorToDepth == null || FMappingColorToDepth.Length != FRuntime.Runtime.ColorStream.FramePixelDataLength)
FMappingColorToDepth = new int[FRuntime.Runtime.ColorStream.FramePixelDataLength];
int stride = FRuntime.Runtime.ColorStream.FrameWidth;
for (int i = 0; i < FMappingDepthToColor.Length; i++)
{
var depthToColor = FMappingDepthToColor[i];
FMappingColorToDepth[depthToColor.X + stride * depthToColor.Y] = i;
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.DataPipeline.Deployment.WorkflowRunnerLib.Services")]
[assembly: AssemblyDescription("Workflow library for Services ADF deployments")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MyCore
{
public abstract class UIView : UIBase
{
public abstract void Show();
public abstract void Hide();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExitScreen : MonoBehaviour {
[SerializeField] private MenuInputController m_input;
[SerializeField] private MenuCity MenuAnimator;
[Header("Screen references")]
[SerializeField] private GameObject MainMenuScreen;
void Awake(){
m_input = transform.parent.GetComponent<MenuInputController>();
}
void Update () {
if(m_input.GetSubmit()){
MenuActions.instance.ExitGame();
}
if(m_input.GetPrevious()){
MenuAnimator.goBack();
MenuActions.instance.ChangePanel(MainMenuScreen);
}
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Xna.Framework.Audio;
using System.Windows.Resources;
using Tff.Panzer.Models.Army;
namespace Tff.Panzer.Factories
{
public class SoundFactory
{
SoundEffect trackedSound = null;
SoundEffect wheeledSound = null;
SoundEffect walkSound = null;
SoundEffect jetAirplaneSound = null;
SoundEffect propAirplaneSound = null;
SoundEffect navalSound = null;
SoundEffect battleSound = null;
public SoundFactory()
{
Uri soundUri = new Uri(Constants.TrackedSoundPath, UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(soundUri);
trackedSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.WheeledSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
wheeledSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.WalkSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
walkSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.JetAirplaneSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
jetAirplaneSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.PropAirplaneSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
propAirplaneSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.NavalSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
navalSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
soundUri = new Uri(Constants.BattleSoundPath, UriKind.Relative);
info = Application.GetResourceStream(soundUri);
battleSound = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
}
public SoundEffect TrackedSound
{
get
{
return trackedSound;
}
}
public SoundEffect WheeledSound
{
get
{
return wheeledSound;
}
}
public SoundEffect WalkSound
{
get
{
return walkSound;
}
}
public SoundEffect JetAirplaneSound
{
get
{
return jetAirplaneSound;
}
}
public SoundEffect PropAirplaneSound
{
get
{
return propAirplaneSound;
}
}
public SoundEffect NavalSound
{
get
{
return navalSound;
}
}
public SoundEffect BattleSound
{
get
{
return battleSound;
}
}
public void PlayEquipmentSound(Equipment equipment)
{
switch (equipment.MovementTypeEnum)
{
case MovementTypeEnum.Tracked:
this.TrackedSound.Play();
break;
case MovementTypeEnum.HalfTracked:
this.TrackedSound.Play();
break;
case MovementTypeEnum.Wheeled:
this.WheeledSound.Play();
break;
case MovementTypeEnum.Walk:
this.WalkSound.Play();
break;
case MovementTypeEnum.None:
this.WalkSound.Play();
break;
case MovementTypeEnum.Air:
if (equipment.JetIndicator == true)
{
JetAirplaneSound.Play();
}
else
{
PropAirplaneSound.Play();
}
break;
case MovementTypeEnum.Water:
NavalSound.Play();
break;
case MovementTypeEnum.AllTerrain:
WheeledSound.Play();
break;
}
}
public void PlayBattleSound()
{
this.BattleSound.Play();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccess;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
namespace ControlD
{
/// <summary>
/// Esta clase contien unacamente las variables que se van a usar para guardar los datos en la BD
/// utiliza unacamente metodos GET y SET de cada variable
/// </summary>
public class Class1
{
//Variables para la tabla de imagenes
private int _ID;
private String _OrderID;
private String _ImageReference;
private Byte _Imagen;
private String _Comment;
private DateTime _CreateDate;
private String _Usuario;
//Variable para el control de errores
public int ID
{
get { return _ID; }
set { _ID = value; }
}
public String OrderID
{
get { return _OrderID; }
set { _OrderID = value; }
}
public String ImageReference
{
get { return _ImageReference; }
set { _ImageReference = value; }
}
public Byte Image
{
get { return _Imagen; }
set { _Imagen = value; }
}
public String comment
{
get { return _Comment; }
set { _Comment = value; }
}
public DateTime CreateData
{
get { return _CreateDate; }
set { _CreateDate = value; }
}
public String Usuario
{
get { return _Usuario; }
set { _Usuario = value; }
}
}// Fin de la primer clase
/// <summary>
/// En esta clase se piden los datos para la conexion y los datos que se van a insertar
/// se utiliza el metodo image_save para poder ejecutar el procedimiento para insertar
/// los archivos en la BD
/// </summary>
public class ImagesMethod
{
//variable para mostrar mensaje en caso de cualquier error en la hora de guardar los datos
private String _ClassError;
//GET y SET de la variable error
public String ClassError
{
get { return _ClassError; }
set { _ClassError = value; }
}
//variables para conectarce y leer la BD, contiene password, usuario, contraseña, servidor y nombre de la BD
public SqlDataReader DR;
public String Database;
public String Pass;
public String Server;
public String User;
//variable para dar acceso a la BD
public DataAccess.DataAccess DA;// = new DataAccess.DataAccess("AgioNet v1.3", "Agiotech01", "192.168.1.1", "aguser");
//Constructor de la clase que pide los datos necesarios para la coneccion con la BD
public ImagesMethod(String Pass, String Server, String User, String Database)
{
this.Pass = Pass;
this.Server = Server;
this.User = User;
this.Database = Database;
DA = new DataAccess.DataAccess(Server, Database, User, Pass);
}
//Metodo image_save que pide los datos para insertar en la tabla de la BD
public void image_save(String OrderID, String References, byte[] Image, String Comment, String User, String Typ)
{
try
{
//Se ejecuta el Procedimiento Almacenado para insertar Datos
DR = DA.ExecuteSP("sp_image_image_insert", OrderID, References, Image, Comment, User, Typ);
if (DA.LastErrorMessage != "")
{
throw new Exception(DA.LastErrorMessage);
}
}
catch (Exception e)
{
_ClassError = e.Message;
}
}
}// fin segunda clase
/// <summary>
/// Clase ImageBinar que funsiona para convertir los archivos que se quieren guardar en un tipo byte
/// utiliza la el metodo downloadDataToByteArray que recibe la direccion del archivo(puede ser como
/// ...Documentos/minuta.docx), toma el archivo y lo combierte en un arreglo binario.
/// </summary>
public class ImageBinar
{
public byte[] downloadDataToByteArray(string url)
{
//Variable de Arreglo byte que contendra el archivo subido
byte[] Convertir = new byte[0];
try
{
//se crean variables para tomar el archivo con Webrequest y WebResponse
//y se combierte el archivo a una variable de tipo Stream
WebRequest req = WebRequest.Create(url);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
// variables parte del codigo que se usa para los byte del archivo
byte[] buffer = new byte[1024];
int dataLength = (int)response.ContentLength;
MemoryStream memStream = new MemoryStream();
int bytesRead;
//siclo para igualar el archivo en una variable de tipo MemoryStream
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
//se iguala el resultado a la primer variable de arreglo byte
Convertir = memStream.ToArray();
stream.Close();
memStream.Close();
}
catch (Exception) { throw; }
//Se retorna el resultado en tipo byte
return Convertir;
}
}//Fin del methodo para guardar archivo
/// <summary>
/// La Clase Extenciones funsiona para poder tomar la estencion de los archivos que se pretenden guardar
/// Dentro de la clase se utiiza el metodo GetExtension que recibe un dato String(la direccion del archivo)
/// y retorna otro dato String(la extencion del archivo que se va a guardar)
///
/// ejemplo:
/// string Resultado = Path.GetExtension(Direccion URL del archivo); // la direccion puede ser como .../imagenes/imagen.jpg
/// return resultado //retorna la pura extension del archivo en un caracter de texto
/// </summary>
public class Extenciones
{
public string GetExtension(string Extensiones)
{
string Result = Path.GetExtension(Extensiones); // returns .exe
return Result;
}
}//Fin del metodo para tomar la extencion de archivo
public class ShowFile
{
public SqlDataReader DR;
public String Database;
public String Pass;
public String Server;
public String User;
public static SqlConnection conn = new SqlConnection("Server=192.168.1.1; Database= AgioNet v1.3; User Id=aguser; Password=Agiotech01");
private String _ClassError;
//GET y SET de la variable error
public String ClassError
{
get { return _ClassError; }
set { _ClassError = value; }
}
//variable para dar acceso a la BD
public DataAccess.DataAccess DA;
public string GetExtension(string link)
{
string Resultado = link;
return link;
}
public ShowFile(String Pass, String Server, String User, String Database)
{
this.Pass = Pass;
this.Server = Server;
this.User = User;
this.Database = Database;
DA = new DataAccess.DataAccess(Server, Database, User, Pass);
}
public MemoryStream[] GetFile(String OrderID, String References)
{
String dat = "no pasa valor";
MemoryStream[] mst = new MemoryStream[100];
int suma = 0;
try
{
byte[] Convertir = new byte[suma];
//Se ejecuta el Procedimiento Almacenado para insertar Datos
DR = DA.ExecuteSP("sp_image_image_getByRef", OrderID, References);
if (DA._LastErrorMessage != "")
{
throw new Exception(DA._LastErrorMessage);
}
if (DR.HasRows)
{
while (DR.Read())
{
for (int i = 0; i < DR.VisibleFieldCount; i++)
{
mst[i] = new MemoryStream((byte[])DR[3]);
i++;
}
}
}
}
catch (Exception e)
{
//dat = "fallaste";
_ClassError = e.Message;
}
return mst;
//return dat; ----------Para enviar texto
}
}// Fin de la clase ShowFile
} |
using Entities.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorApp.Services
{
public class Bina:IEntity
{
public int BinaId { get; set; }
public string BinaAdi { get; set; }
public string Adres { get; set; }
public int KatSayisi { get; set; }
public int Yasi { get; set; }
}
}
|
using PNPUCore.Controle;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using PNPUTools;
using PNPUTools.DataManager;
using System.Xml;
using PNPUCore.Rapport;
using System.Linq;
namespace PNPUCore.Process
{
/// <summary>
/// Cette classe correspond au process de contrôle des mdb.
/// </summary>
class ProcessControlePacks : ProcessCore, IProcess
{
public List<string> listMDB { get; set; }
public string MDBCourant { get; set; }
/// <summary>
/// Constructeur de la classe.
/// </summary>
/// <param name="rapportProcess">Objet permettant de générer le rapport au format JSON sur le résultat du déroulement des contrôles.</param>
public ProcessControlePacks(int wORKFLOW_ID, string cLIENT_ID) : base(wORKFLOW_ID, cLIENT_ID)
{
this.PROCESS_ID = ParamAppli.ProcessControlePacks;
this.LibProcess = "Pré contrôle des .mdb";
}
/// <summary>
/// Méthode principale du process qui appelle les différents contrôles.
/// </summary>
public new void ExecuteMainProcess()
{
List<IControle> listControl = new List<IControle>();
string GlobalResult = ParamAppli.StatutOk;
string SourceResult = ParamAppli.StatutOk;
string statutControle;
listMDB = new List<string>();
sRapport = string.Empty;
string[] tMDB = null;
RControle RapportControle;
Rapport.Source RapportSource;
string[] listClientId = CLIENT_ID.Split(',');
//POUR TEST
/*this.CLIENT_ID = "101";*/
this.STANDARD = true;
//this.TYPOLOGY = ParamAppli.ListeInfoClient[listClientId.First()].TYPOLOGY;
Logger.Log(this, ParamAppli.StatutInfo, " Debut du process " + this.ToString());
RapportProcess.Name = this.LibProcess;
RapportProcess.Debut = DateTime.Now;
RapportProcess.IdClient = CLIENT_ID;
RapportProcess.Source = new List<Rapport.Source>();
PNPUTools.GereMDBDansBDD gereMDBDansBDD = new PNPUTools.GereMDBDansBDD();
gereMDBDansBDD.ExtraitFichiersMDBBDD(ref tMDB, WORKFLOW_ID, ParamAppli.DossierTemporaire, ParamAppli.ConnectionStringBaseAppli);
foreach (String sFichier in tMDB)
{
listMDB.Add(sFichier);
}
GetListControle(ref listControl);
foreach (string sMDB in listMDB)
{
MDBCourant = sMDB;
RapportSource = new Rapport.Source();
RapportSource.Name = System.IO.Path.GetFileName(sMDB);
RapportSource.Controle = new List<RControle>();
SourceResult = ParamAppli.StatutOk;
foreach (IControle controle in listControl)
{
RapportControle = new RControle();
RapportControle.Name = controle.GetLibControle();
RapportControle.Tooltip = controle.GetTooltipControle();
RapportControle.Message = new List<string>();
RapportControleCourant = RapportControle;
Logger.Log(this, controle, ParamAppli.StatutInfo, "Début du contrôle " + controle.ToString());
statutControle = controle.MakeControl();
Logger.Log(this, controle, statutControle, "Fin du contrôle " + controle.ToString());
//ERROR > WARNING > OK
if (GlobalResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutError)
{
GlobalResult = statutControle;
}
else if (GlobalResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutWarning)
{
GlobalResult = statutControle;
}
if (SourceResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutError)
{
SourceResult = statutControle;
}
else if (SourceResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutWarning)
{
SourceResult = statutControle;
}
RapportControle.Result = ParamAppli.TranscoSatut[statutControle];
RapportSource.Controle.Add(RapportControle);
}
RapportSource.Result = ParamAppli.TranscoSatut[SourceResult];
RapportProcess.Source.Add(RapportSource);
}
// Le controle des dépendance est à part puisqu'il traite tous les mdb en une fois
ControleDependancesMDB cdmControleDependancesMDB = new ControleDependancesMDB(this);
RapportSource = new Rapport.Source();
RapportSource.Name = "Contrôle des dépendances inter packages";
RapportSource.Controle = new List<RControle>();
RapportControle = new RControle();
RapportControle.Name = cdmControleDependancesMDB.ToString();
RapportControle.Message = new List<string>();
RapportControleCourant = RapportControle;
Logger.Log(this, cdmControleDependancesMDB, ParamAppli.StatutInfo, "Début du contrôle " + cdmControleDependancesMDB.ToString());
statutControle = cdmControleDependancesMDB.MakeControl();
Logger.Log(this, cdmControleDependancesMDB, statutControle, "Fin du contrôle " + cdmControleDependancesMDB.ToString());
RapportControle.Result = ParamAppli.TranscoSatut[statutControle];
//RapportSource2.Controle.Add(RapportControle2);
RapportProcess.Source.Add(RapportSource);
// Génération du fichier CSV des dépendances
StreamWriter swFichierDep = new StreamWriter(Path.Combine(ParamAppli.DossierTemporaire, this.WORKFLOW_ID.ToString("000000") + "_DEPENDANCES.csv"));
foreach (string sLig in RapportControle.Message)
swFichierDep.WriteLine(sLig);
swFichierDep.Close();
// Je supprime les messages pour qu'ils ne sortent pas dans le report JSON
RapportControle.Message.Clear();
RapportSource.Result = RapportControle.Result;
// Recherche des dépendances avec les tâches CCT sur la base de référence
ControleRechercheDependancesRef crdrControleRechercheDependancesRef = new ControleRechercheDependancesRef(this);
RapportSource = new Rapport.Source();
RapportSource.Name = "Recherche des dépendances avec les tâches CCT sur la base de référence";
RapportSource.Controle = new List<RControle>();
RapportControle = new RControle();
RapportControle.Name = cdmControleDependancesMDB.ToString();
RapportControle.Message = new List<string>();
RapportControleCourant = RapportControle;
Logger.Log(this, crdrControleRechercheDependancesRef, ParamAppli.StatutInfo, "Début du contrôle " + crdrControleRechercheDependancesRef.ToString());
statutControle = crdrControleRechercheDependancesRef.MakeControl();
Logger.Log(this, crdrControleRechercheDependancesRef, statutControle, "Fin du contrôle " + crdrControleRechercheDependancesRef.ToString());
RapportControle.Result = ParamAppli.TranscoSatut[statutControle];
//RapportSource2.Controle.Add(RapportControle2);
RapportProcess.Source.Add(RapportSource);
// Je supprime les messages pour qu'ils ne sortent pas dans le report JSON
RapportControle.Message.Clear();
RapportSource.Result = RapportControle.Result;
RapportProcess.Fin = DateTime.Now;
RapportProcess.Result = ParamAppli.TranscoSatut[GlobalResult];
Logger.Log(this, GlobalResult, "Fin du process " + this.ToString());
//Si le contrôle est ok on génère les lignes d'historique pour signifier que le workflow est lancé
//string[] listClientId = new string[] { "DASSAULT SYSTEME", "SANEF", "DRT", "GALILEO", "IQERA", "ICL", "CAMAIEU", "DANONE", "HOLDER", "OCP", "UNICANCER", "VEOLIA" };
//string[] listClientId = new string[] { "111" };//{ "DASSAULT SYSTEME", "SANEF", "DRT", "GALILEO", "IQERA", "ICL", "CAMAIEU", "DANONE", "HOLDER", "OCP", "UNICANCER", "VEOLIA" };
PNPU_H_WORKFLOW historicWorkflow = new PNPU_H_WORKFLOW();
historicWorkflow.CLIENT_ID = this.CLIENT_ID;
historicWorkflow.LAUNCHING_DATE = RapportProcess.Debut;
historicWorkflow.ENDING_DATE = new DateTime(1800, 1, 1);
historicWorkflow.STATUT_GLOBAL = "IN PROGRESS";
historicWorkflow.WORKFLOW_ID = this.WORKFLOW_ID;
RequestTool.CreateUpdateWorkflowHistoric(historicWorkflow);
foreach (string clientId in listClientId) {
InfoClient client = RequestTool.getClientsById(clientId);
PNPU_H_STEP historicStep = new PNPU_H_STEP();
historicStep.ID_PROCESS = this.PROCESS_ID;
historicStep.ITERATION = 1;
historicStep.WORKFLOW_ID = this.WORKFLOW_ID;
historicStep.CLIENT_ID = clientId;
historicStep.CLIENT_NAME = client.CLIENT_NAME;
historicStep.USER_ID = "PNPUADM";
historicStep.LAUNCHING_DATE = RapportProcess.Debut;
historicStep.ENDING_DATE = RapportProcess.Fin;
historicStep.TYPOLOGY = "SAAS DEDIE";
historicStep.ID_STATUT = GlobalResult;
RequestTool.CreateUpdateStepHistoric(historicStep);
}
// TEST ajout MDB
//gereMDBDansBDD.AjouteFichiersMDBBDD(new string[] { "D:\\PNPU\\Tests_RAMDL\\test.mdb" }, WORKFLOW_ID, ParamAppli.DossierTemporaire, ParamAppli.ConnectionStringBaseAppli, CLIENT_ID,1);
int NextProcess = RequestTool.GetNextProcess(WORKFLOW_ID, ParamAppli.ProcessControlePacks);
foreach(string clienId in listClientId)
{
LauncherViaDIspatcher.LaunchProcess(NextProcess, decimal.ToInt32(this.WORKFLOW_ID), clienId);
}
}
internal static new IProcess CreateProcess(int WORKFLOW_ID, string CLIENT_ID)
{
return new ProcessControlePacks(WORKFLOW_ID, CLIENT_ID);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Data.OleDb;
using HSoft.SQL;
using HSoft.ClientManager.Web;
using SisoDb.Sql2012;
using SisoDb.Configurations;
using CTCT;
using CTCT.Components;
using CTCT.Components.Contacts;
using CTCT.Components.AccountService;
using CTCT.Components.EmailCampaigns;
using CTCT.Exceptions;
using Obout.Interface;
public partial class CCMail_Menu : System.Web.UI.Page
{
public static string sDB = "ClientManagerSP";
protected void Page_Load(object sender, EventArgs e)
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
LastDateContacts.Text = _sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateContacts' AND isdeleted = 0").ToString();
try { RecordCountContacts.Text = _sql.ExecuteScalar("SELECT count(*) FROM [dbo].[ContactStructure]").ToString(); } catch { RecordCountContacts.Text = "-"; }
LastDateContactLists.Text = _sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateContactLists' AND isdeleted = 0").ToString();
try { RecordCountContactLists.Text = _sql.ExecuteScalar("SELECT count(*) FROM [dbo].[ContactListStructure]").ToString(); } catch { RecordCountContactLists.Text = "-"; }
LastDateEmailCampaigns.Text = _sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateEmailCampaigns' AND isdeleted = 0").ToString();
try { RecordCountEmailCampaigns.Text = _sql.ExecuteScalar("SELECT count(*) FROM [dbo].[EmailCampaignStructure]").ToString(); } catch { RecordCountEmailCampaigns.Text = "-"; }
LastDateOpenActivities.Text = _sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateOpenActivities' AND isdeleted = 0").ToString();
try { RecordCountOpenActivities.Text = _sql.ExecuteScalar("SELECT count(*) FROM [dbo].[ContactListStructure]").ToString(); } catch { RecordCountOpenActivities.Text = "-"; }
_sql.Close();
}
protected void Btn_Command(object sender, CommandEventArgs e)
{
CC_Command(e.CommandName);
Response.Redirect("/CCMail/Menu.aspx");
}
protected void CC_Command(string scmd)
{
switch (scmd)
{
case "ResetLoadDate":
{
}
break;
case "ResetDatabase":
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings[sDB].ConnectionString.CreateSql2012Db();
_siso.CreateIfNotExists();
using (var session = _siso.BeginSession())
{
session.DeleteByQuery<CTCT.Components.Contacts.Contact>(o => o.Id != "");
session.DeleteByQuery<CTCT.Components.Contacts.ContactList>(o => o.Id != "");
session.DeleteByQuery<CTCT.Components.EmailCampaigns.EmailCampaign>(o => o.Id != "");
// session.DeleteByQuery<CTCT.Components.Tracking.OpenActivity>(o => o.CampaignId != "");
}
_sql.Execute("UPDATE CC_TimeStamps SET [TimeStamp] = '1901-01-01' WHERE [Name] = 'LastDateContacts' AND isdeleted = 0");
_sql.Execute("UPDATE CC_TimeStamps SET [TimeStamp] = '1901-01-01' WHERE [Name] = 'LastDateContactLists' AND isdeleted = 0");
_sql.Execute("UPDATE CC_TimeStamps SET [TimeStamp] = '1901-01-01' WHERE [Name] = 'LastDateEmailCampaigns' AND isdeleted = 0");
_sql.Execute("UPDATE CC_TimeStamps SET [TimeStamp] = '1901-01-01' WHERE [Name] = 'LastDateOpenActivities' AND isdeleted = 0");
_sql.Close();
}
break;
case "UpdateDatabase":
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
DateTime _lastmod;
// _lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateEmailCampaigns' AND isdeleted = 0").ToString());
// UpdateEmailCampaigns(_lastmod);
// _lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateOpenActivities' AND isdeleted = 0").ToString());
// UpdateEmailCampaignOpens(_lastmod);
_lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateContacts' AND isdeleted = 0").ToString());
UpdateContacts(_lastmod);
_lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT [TimeStamp] FROM CC_TimeStamps WHERE [Name] = 'LastDateContactLists' AND isdeleted = 0").ToString());
UpdateContactLists(_lastmod);
_sql.Close();
}
break;
}
}
public void UpdateEmailCampaignOpens(DateTime lastupdate)
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings[sDB].ConnectionString.CreateSql2012Db();
ConstantContact _constantContact = null;
string _apiKey = string.Empty;
string _accessToken = string.Empty;
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
Pagination _page = null;
DateTime _last = lastupdate;
int? _limit = 500;
while (1 == 1)
{
ResultSet<CTCT.Components.Tracking.OpenActivity> _openactivities = null;
try
{
_openactivities = _constantContact.GetCampaignTrackingOpens(_limit, lastupdate, _page);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetCampaignTrackingOpens {0}", ex.Message));
throw ex;
}
if (_openactivities.Meta.Pagination.Next == null) { break; }
if (_page == null) { _page = new Pagination(); }
_page.Next = _openactivities.Meta.Pagination.Next;
}
_sql.Execute(String.Format("UPDATE CC_TimeStamps SET [TimeStamp] = '{0}' WHERE [Name] = 'LastDateOpenActivities' AND isdeleted = 0", _last));
}
public void UpdateEmailCampaigns(DateTime lastupdate)
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings[sDB].ConnectionString.CreateSql2012Db();
ConstantContact _constantContact = null;
string _apiKey = string.Empty;
string _accessToken = string.Empty;
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
Pagination _page = null;
DateTime _last = lastupdate;
int? _limit = 50;
while (1 == 1)
{
ResultSet<CTCT.Components.EmailCampaigns.EmailCampaign> _emailcampaigns = null;
try
{
_emailcampaigns = _constantContact.GetCampaigns(CampaignStatus.SENT, _limit, lastupdate, _page);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetCampaigns {0}", ex.Message));
throw ex;
}
using (var session = _siso.BeginSession())
{
foreach (CTCT.Components.EmailCampaigns.EmailCampaign _emailcampaign in _emailcampaigns.Results)
{
if (session.Query<CTCT.Components.EmailCampaigns.EmailCampaign>().Count(o => o.Id == _emailcampaign.Id) != 0)
{
session.Update(_emailcampaign);
}
else
{
session.Insert(_emailcampaign);
if (_emailcampaign.ModifiedDate > _last) { _last = (DateTime)_emailcampaign.ModifiedDate; }
}
}
}
if (_emailcampaigns.Meta.Pagination.Next == null) { break; }
if (_page == null) { _page = new Pagination(); }
_page.Next = _emailcampaigns.Meta.Pagination.Next;
}
_sql.Execute(String.Format("UPDATE CC_TimeStamps SET [TimeStamp] = '{0}' WHERE [Name] = 'LastDateEmailCampaigns' AND isdeleted = 0", _last));
_sql.Close();
}
public void UpdateContactLists(DateTime lastupdate)
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings[sDB].ConnectionString.CreateSql2012Db();
ConstantContact _constantContact = null;
string _apiKey = string.Empty;
string _accessToken = string.Empty;
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
DateTime _last = lastupdate;
IList<ContactList> _contactlists = null;
try
{
_contactlists = _constantContact.GetLists(lastupdate);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetContactLists {0}", ex.Message));
throw ex;
}
using (var session = _siso.BeginSession())
{
foreach (ContactList _contactlist in _contactlists)
{
if (session.Query<CTCT.Components.Contacts.ContactList>().Count(o => o.Id == _contactlist.Id) != 0)
{
session.Update(_contactlist);
}
else
{
session.Insert(_contactlist);
if (DateTime.Parse(_contactlist.DateModified) > _last) { _last = DateTime.Parse(_contactlist.DateModified); }
}
}
}
_sql.Execute(String.Format("UPDATE CC_TimeStamps SET [TimeStamp] = '{0}' WHERE [Name] = 'LastDateContactLists' AND isdeleted = 0", _last));
_sql.Close();
}
public void UpdateContacts(DateTime lastupdate)
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[sDB].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings[sDB].ConnectionString.CreateSql2012Db();
ConstantContact _constantContact = null;
string _apiKey = string.Empty;
string _accessToken = string.Empty;
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
Pagination _page = null;
DateTime _last = lastupdate;
int? _limit = 500;
while (1 == 1)
{
ResultSet<CTCT.Components.Contacts.Contact> _contacts = null;
try
{
_contacts = _constantContact.GetContacts(lastupdate,_limit, _page);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetContacts {0}", ex.Message));
throw ex;
}
if (_contacts == null)
{
Exception ex = new Exception("No results returned, possible connection failure.");
throw ex;
}
using (var session = _siso.BeginSession())
{
foreach (CTCT.Components.Contacts.Contact _contact in _contacts.Results)
{
if (session.Query<CTCT.Components.Contacts.Contact>().Count(o => o.Id == _contact.Id) != 0)
{
session.Update(_contact);
}
else
{
session.Insert(_contact);
if (DateTime.Parse(_contact.DateModified) > _last) { _last = DateTime.Parse(_contact.DateModified); }
}
}
}
if (_contacts.Meta.Pagination.Next == null) { break; }
if (_page == null) { _page = new Pagination(); }
_page.Next = _contacts.Meta.Pagination.Next;
}
_sql.Execute(String.Format("UPDATE CC_TimeStamps SET [TimeStamp] = '{0}' WHERE [Name] = 'LastDateContacts' AND isdeleted = 0", _last));
_sql.Close();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using PrimeNumberPrinter.Program;
namespace UnitTests.Tests
{
[TestFixture]
public class OutputPrinterTests
{
private OutputPrinter outputPrinter;
[OneTimeSetUp]
public void Init()
{
outputPrinter = new OutputPrinter();
}
// Not much to do here with these requirements, but could be useful in the future
[Test]
public void TestOutput()
{
outputPrinter.PrintLines("Testing");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Acid : MonoBehaviour
{
[SerializeField] AudioManager SFX = null;
[SerializeField] ParticleSystem Bubbles = null;
private void Start()
{
Bubbles.Play();
SFX.Play("AP_Bubbles");
}
private void OnTriggerEnter2D(Collider2D _player)
{
if (_player.gameObject.tag == "Player")
{
SFX.Play("AP_Damage");
_player.gameObject.GetComponent<PlayerController2D>().GameOver();
}
else if(_player.gameObject.CompareTag("Enemy"))
{
SFX.Play("AP_Damage");
_player.gameObject.GetComponent<EnemyHandle>().TakeDamage(50);
}
}
}
|
#if TEST
using UnityEngine;
namespace Action
{
public class TestLow : State
{
public TestLow(Animator animator, UInput.InputComponet input, Rigidbody2D rigid)
: base(animator, input, rigid)
{
}
public override void Start()
{
Debug.Log("Start TestLow");
}
public override void Update()
{}
public override void End()
{}
public override bool ShouldStart()
{
return true;
}
public override bool ShouldEnd()
{
return false;
}
}
} // namespace Action
#endif // TEST |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPI.Model.EF
{
public class CategoryKPILevel
{
public int ID { get; set; }
public int KPILevelID { get; set; }
public int CategoryID { get; set; }
public bool Status { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simon.Pattern.MethodTemplate
{
/// <summary>
/// Method Template Pattern
/// 在抽象类中定义算法的骨架,将具体的步骤实现延迟要子类中
/// 优点:在不改变算法结构的情况下,重新定义算法的具体步骤
/// 也可以理解为在父类中通过非抽象方法调用抽象方法
/// </summary>
public class MethodTemplateDemo
{
public static void Run()
{
//SqlBuilderBase sqlBuilder = new SqlBuilderForAccess();
//Console.WriteLine(sqlBuilder.BuildSqlString("AllDocs", "LastModified", "2012-12-12"));
Number num = new Number();
float[] f = { 1,2,3,4};
CompareMehod com = new CompareMehod();
num.DoCompare += com.C1;
num.DoCompare += com.C2;
Console.WriteLine(num.CompareTo(f));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace SendMail
{
public class Settings
{
private static Settings instance = null;
public string Host { get; set; } //ホスト名
public int Port { get; set; } //ポート番号
public string PassWord { get; set; } //パスワード
public bool SSL { get; set; } //SSL有無
public string MailAddress { get; set; } //メールアドレス
public string UserName { get; set; } //ユーザー名
//XMLファイル
public string FileName { get; set; } = "mail.xml";
bool ans = true;
//コンストラクタ
private Settings() { }
public static Settings getInstance()
{
if (instance == null)
{
instance = new Settings();
}
return instance;
}
public bool FileCheck()
{
if (File.Exists(this.FileName))
{
reSelializer();
if (ans != false)
{
return true;
}
return false;
}
return false;
}
//シリアル化
public void Serializer()
{
var xws = new XmlWriterSettings
{
Encoding = new System.Text.UTF8Encoding(false),
Indent = true,
IndentChars = "",
};
using (var writer = XmlWriter.Create(this.FileName, xws))
{
var serializer = new DataContractSerializer(this.GetType());
serializer.WriteObject(writer, this);
}
}
//逆シリアライズ
public void reSelializer()
{
using (var reader = XmlReader.Create(this.FileName))
{
try
{
var serializer = new DataContractSerializer(typeof(Settings));
var mail = serializer.ReadObject(reader) as Settings;
instance = mail;
//settingsへの登録
this.Port = mail.Port;
this.Host = mail.Host;
this.PassWord = mail.PassWord;
this.SSL = mail.SSL;
this.MailAddress = mail.MailAddress;
this.UserName = mail.UserName;
}
catch (Exception e)
{
ans = false;
}
}
}
//初期値設定
public string sHost()
{
return "smtp.gmail.com";
}
public string sPort()
{
return 587.ToString();
}
public string sPassWord()
{
return "Infosys2021";
}
public string sMailAddress()
{
return "ojsinfosys01@gmail.com";
}
public bool bSSL()
{
return true;
}
}
} |
//
// 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.Web.UI;
using DotNetNuke.Web.UI;
using Telerik.Web.UI;
#endregion
namespace DotNetNuke.Web.UI.WebControls
{
public class DnnToolTip : RadToolTip, ILocalizable
{
private bool _localize = true;
protected override void Render(HtmlTextWriter writer)
{
LocalizeStrings();
base.Render(writer);
}
public string ResourceKey { get; set; }
#region ILocalizable Implementation
public bool Localize
{
get
{
if (base.DesignMode)
{
return false;
}
return _localize;
}
set
{
_localize = value;
}
}
public string LocalResourceFile { get; set; }
public virtual void LocalizeStrings()
{
if ((this.Localize) && (!(String.IsNullOrEmpty(this.ResourceKey))))
{
if (!(String.IsNullOrEmpty(base.ManualCloseButtonText)))
{
base.ManualCloseButtonText = Utilities.GetLocalizedStringFromParent(String.Format("{0}.ManualCloseButtonText", this.ResourceKey), this);
}
if (!(String.IsNullOrEmpty(base.Text)))
{
base.Text = Utilities.GetLocalizedStringFromParent(String.Format("{0}.Text", this.ResourceKey), this);
}
if (!(String.IsNullOrEmpty(base.ToolTip)))
{
base.ToolTip = Utilities.GetLocalizedStringFromParent(String.Format("{0}.ToolTip", this.ResourceKey), this);
}
}
}
#endregion
}
}
|
using System;
using System.Linq;
using AdonisUI.Controls;
using MessageBox = AdonisUI.Controls.MessageBox;
using MessageBoxImage = AdonisUI.Controls.MessageBoxImage;
using MessageBoxResult = AdonisUI.Controls.MessageBoxResult;
namespace Athena.MessageBoxes {
public class RemoveDatabaseWithBooksMessageBox {
public bool Show() {
var messageBox = new MessageBoxModel {
Text = "Baza danych zawiera już książki. Czy jesteś absosmerfnie pewien, że chcesz ją usunąć?",
Caption = "Info",
Icon = MessageBoxImage.Warning,
Buttons = new[] {
MessageBoxButtons.Yes("Tak"),
MessageBoxButtons.No("Nie")
},
IsSoundEnabled = false
};
var buttons = messageBox.Buttons.ToArray();
buttons[0].IsDefault = false;
buttons[1].IsDefault = true;
MessageBox.Show(messageBox);
switch (messageBox.Result) {
case MessageBoxResult.No:
return false;
case MessageBoxResult.Yes:
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
}
} |
using LocalResourceDataContracts;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace LocalResourceManager
{
/// <summary>
///
/// </summary>
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
ConfigurationName = "LargeNetNamedPipeBinding")]
public class CacheManagerService : ICacheManagerService
{
public void CacheManagerService()
{
// check binding
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string[] GetPatientIds()
{
var patientIds = (from idc in _cacheImages.Values
select idc.PatientId).Distinct();
return patientIds.ToArray();
}
#region Image Operations
/// <summary>
///
/// </summary>
/// <returns></returns>
public Guid[] GetImageResourceIds(string patientId)
{
return (from idc in _cacheImages.Values
where idc.PatientId.CompareTo(patientId) == 0
select idc.Id).ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="seriesInstanceUID"></param>
/// <returns></returns>
public Guid[] GetImageIdsBySeries(string seriesInstanceUID)
{
return (from idc in _cacheImages.Values
where idc.SeriesInstanceUID.CompareTo(seriesInstanceUID) == 0
select idc.Id).ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ImageDataContract GetImage(Guid id)
{
return _cacheImages[id];
}
/// <summary>
///
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="pixelType"></param>
/// <param name="label"></param>
/// <returns></returns>
public ImageDataContract AddImage(ImageDataContract idc)
{
// assert that GUID was not already assigned
System.Diagnostics.Trace.Assert(idc.Id.CompareTo(Guid.Empty) == 0);
idc.Id = Guid.NewGuid();
idc.PixelBuffer =
BufferRepository.CreateBuffer(idc.Id, typeof(ushort), idc.Width * idc.Height);
_cacheImages.TryAdd(idc.Id, idc);
return idc;
}
/// <summary>
///
/// </summary>
/// <param name="guid"></param>
public void RemoveImage(Guid guid)
{
ImageDataContract idc;
_cacheImages.TryRemove(guid, out idc);
BufferRepository.FreeBuffer(idc.PixelBuffer.Id);
//if (_cacheImages.Count == 0)
//{
// System.Diagnostics.Trace.Assert(BufferRepository.GetCount() == 0);
//}
}
// the image cache
static ConcurrentDictionary<Guid, ImageDataContract> _cacheImages =
new ConcurrentDictionary<Guid, ImageDataContract>();
#endregion
#region ImageVolume Operations
/// <summary>
///
/// </summary>
/// <returns></returns>
public Guid[] GetImageVolumeResourceIds(string patientId)
{
return (from ivdc in _cacheImageVolumes.Values
where ivdc.PatientId.CompareTo(patientId) == 0
select ivdc.Id).ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="seriesInstanceUID"></param>
/// <returns></returns>
public ImageVolumeDataContract GetImageVolumeBySeriesInstanceUID(string seriesInstanceUID)
{
var ivdcs = from ivdc in _cacheImageVolumes.Values
where ivdc.SeriesInstanceUID.CompareTo(seriesInstanceUID) == 0
select ivdc;
// System.Diagnostics.Trace.Assert(ivdcs.Count() <= 1);
return ivdcs.FirstOrDefault();
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ImageVolumeDataContract GetImageVolume(Guid id)
{
return _cacheImageVolumes[id];
}
/// <summary>
///
/// </summary>
/// <param name="ivdc"></param>
/// <returns></returns>
public ImageVolumeDataContract AddImageVolume(ImageVolumeDataContract ivdc)
{
// assert that GUID was not already assigned
System.Diagnostics.Trace.Assert(ivdc.Id.CompareTo(Guid.Empty) == 0);
ivdc.Id = Guid.NewGuid();
ivdc.PixelBuffer =
BufferRepository.CreateBuffer(ivdc.Id, typeof(ushort),
ivdc.Width * ivdc.Height * ivdc.Depth);
_cacheImageVolumes.TryAdd(ivdc.Id, ivdc);
return ivdc;
}
/// <summary>
///
/// </summary>
/// <param name="guid"></param>
public void RemoveImageVolume(Guid guid)
{
ImageVolumeDataContract ivdc;
_cacheImageVolumes.TryRemove(guid, out ivdc);
BufferRepository.FreeBuffer(ivdc.PixelBuffer.Id);
}
// the image cache
static ConcurrentDictionary<Guid, ImageVolumeDataContract> _cacheImageVolumes =
new ConcurrentDictionary<Guid, ImageVolumeDataContract>();
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
public Guid[] GetStructureResourceIds(string patientId)
{
return (from sdc in _cacheStructures.Values
where sdc.PatientId.CompareTo(patientId) == 0
select sdc.Id).ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="forUid"></param>
/// <returns></returns>
public Guid[] GetStructuresInFrameOfReferenceUid(string forUid)
{
var ids = from sdc in _cacheStructures.Values
where sdc.FrameOfReferenceUID.CompareTo(forUid) == 0
select sdc.Id;
return ids.ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public StructureDataContract GetStructure(Guid id)
{
return _cacheStructures[id];
}
/// <summary>
///
/// </summary>
/// <param name="sdc"></param>
/// <returns></returns>
public StructureDataContract AddStructure(StructureDataContract sdc)
{
System.Diagnostics.Trace.Assert(sdc.Id.CompareTo(Guid.Empty) == 0);
sdc.Id = Guid.NewGuid();
_cacheStructures.TryAdd(sdc.Id, sdc);
return sdc;
}
/// <summary>
///
/// </summary>
/// <param name="guid"></param>
public void RemoveStructure(Guid guid)
{
StructureDataContract sdc;
_cacheStructures.TryRemove(guid, out sdc);
foreach (var pdcGuid in sdc.Contours)
{
PolygonDataContract pdc;
_cachePolygons.TryRemove(pdcGuid, out pdc);
BufferRepository.FreeBuffer(pdc.VertexBuffer.Id);
}
}
//
static ConcurrentDictionary<Guid, StructureDataContract> _cacheStructures =
new ConcurrentDictionary<Guid, StructureDataContract>();
public PolygonDataContract GetPolygon(Guid guid)
{
if (_cachePolygons.ContainsKey(guid))
return _cachePolygons[guid];
return null;
}
public PolygonDataContract AddPolygon(PolygonDataContract pdc)
{
System.Diagnostics.Trace.Assert(pdc.Id.CompareTo(Guid.Empty) == 0);
pdc.Id = Guid.NewGuid();
_cachePolygons.TryAdd(pdc.Id, pdc);
// assert that GUID was not already assigned
pdc.VertexBuffer =
BufferRepository.CreateBuffer(pdc.Id, typeof(System.Windows.Media.Media3D.Vector3D),
pdc.VertexCount);
return pdc;
}
static ConcurrentDictionary<Guid, PolygonDataContract> _cachePolygons =
new ConcurrentDictionary<Guid, PolygonDataContract>();
/// <summary>
///
/// </summary>
/// <param name="relatedId"></param>
/// <returns></returns>
public SurfaceMeshDataContract GetSurfaceMeshByRelatedStructureId(Guid relatedId)
{
var smdcs = from smdc in _cacheMeshes.Values
where smdc.RelatedStructureId.CompareTo(relatedId) == 0
select smdc;
System.Diagnostics.Trace.Assert(smdcs.Count() <= 1);
return smdcs.FirstOrDefault();
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public SurfaceMeshDataContract GetSurfaceMesh(Guid id)
{
return _cacheMeshes[id];
}
/// <summary>
///
/// </summary>
/// <param name="smdc"></param>
/// <returns></returns>
public SurfaceMeshDataContract AddSurfaceMesh(SurfaceMeshDataContract smdc)
{
OperationContext oc = OperationContext.Current;
oc.
// assert that GUID was not already assigned
System.Diagnostics.Trace.Assert(smdc.Id.CompareTo(Guid.Empty) == 0);
smdc.Id = Guid.NewGuid();
_cacheMeshes.TryAdd(smdc.Id, smdc);
smdc.VertexBuffer =
BufferRepository.CreateBuffer(Guid.NewGuid(), typeof(System.Windows.Media.Media3D.Vector3D),
smdc.VertexCount);
smdc.NormalBuffer =
BufferRepository.CreateBuffer(Guid.NewGuid(), typeof(System.Windows.Media.Media3D.Vector3D),
smdc.VertexCount);
smdc.TriangleIndexBuffer =
BufferRepository.CreateBuffer(Guid.NewGuid(), typeof(TriangleIndex),
smdc.TriangleCount);
return smdc;
}
/// <summary>
///
/// </summary>
/// <param name="guid"></param>
public void RemoveSurfaceMesh(Guid guid)
{
SurfaceMeshDataContract smdc;
_cacheMeshes.TryRemove(guid, out smdc);
BufferRepository.FreeBuffer(smdc.VertexBuffer.Id);
BufferRepository.FreeBuffer(smdc.NormalBuffer.Id);
BufferRepository.FreeBuffer(smdc.TriangleIndexBuffer.Id);
}
static ConcurrentDictionary<Guid, SurfaceMeshDataContract> _cacheMeshes =
new ConcurrentDictionary<Guid, SurfaceMeshDataContract>();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Application.Data;
using System.Data;
namespace Application.Service.Services
{
public class MessageService : IMessageService
{
private MessageEntity db = new MessageEntity();
public List<Message> GetMessage()
{
return db.Message.ToList();
}
public Message GetMessageById(Guid id)
{
// return db.Message.Where(x=>x.guid==id);
return null;
}
public Guid SaveMessage(Message mess)
{
var x= EmailService.SendEmail(mess);
mess.IsSent =x;
db.Message.Add(mess);
db.SaveChanges();
return mess.guid;
}
}
} |
using AutoMapper;
using CandidateTesting.RicardoCastroMartin.Domain.Interfaces;
using System;
using System.Text;
namespace CandidateTesting.RicardoCastroMartin.Domain
{
public class AgoraLog
{
private string _separator = "\t";
private static ILog _log;
public AgoraLog(ILog log)
{
_log = log;
}
public static string GetHeader() {
StringBuilder sb = new StringBuilder();
sb.Append("#Version: 1.0\n");
sb.Append($"#Date: {DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")}\n");
sb.Append("#Fields: provider http-method status-code uri-path time-taken response-size cache-status\n");
return sb.ToString();
}
public override string ToString()
{
return $"{_log.Provider}{_separator}{_log.HttpMethod}{_separator}{_log.StatusCode}{_separator}{_log.UriPath}{_separator}{_log.TimeTaken}{_separator}{_log.ResponseSize}{_separator}{_log.CacheStatus}\n";
}
}
}
|
using UnityEngine;
public class Health : MonoBehaviour
{
public int NumberOfLives { get { return numberOfLives; } }
public int MaxNumberOfLives { get { return maxNumberOfLives; } }
[SerializeField]
private int maxNumberOfLives = 10;
[SerializeField]
private int numberOfLives = 3;
private void Update()
{
if (numberOfLives == 0)
{
GameOver();
}
}
public void DecreaseLife(int lives)
{
numberOfLives = Mathf.Max(numberOfLives - lives, 0);
}
public void IncreaseLife(int lives)
{
numberOfLives = Mathf.Min(numberOfLives + lives, maxNumberOfLives);
}
public void GameOver()
{
//Caricare scena nuova o resettare il livello
this.enabled = false;
}
}
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Kers.Models.Repositories;
using Kers.Models.Entities.KERScore;
using Kers.Models.Abstract;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Kers.Models.Entities;
using Kers.Models.Contexts;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System.Text.RegularExpressions;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
using Microsoft.Extensions.Configuration;
namespace Kers.Controllers
{
[Route("api/[controller]")]
public class EmailController : BaseController
{
KERScoreContext _context;
IConfiguration _configuration;
public EmailController(
KERSmainContext mainContext,
IKersUserRepository userRepo,
KERScoreContext _context,
IConfiguration _configuration
):base(mainContext, _context, userRepo)
{
this._context = _context;
this._configuration = _configuration;
}
[HttpPost("")]
[Authorize]
public IActionResult Send([FromBody] Email Email){
try{
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Kers System", Email.From));
message.To.Add (new MailboxAddress ("Kers Recipient", Email.To));
message.Subject = Email.Subject;
message.Body = new TextPart ("plain") {
Text = Email.Body
};
// https://github.com/jstedfast/MailKit
using (var client = new SmtpClient ()) {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
/*
Pressets:
1: Ivelin's email
2: IIS config (maybe not possible to be used, skipped for now)
3: appsettings.json
4: custom
*/
if(Email.Pressets == 1){
client.Connect ("outlook.office365.com", 587, false);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate (_configuration["Email:UserId"], _configuration["Email:UserPassword"]);
}else if( Email.Pressets == 3){
client.Connect (_configuration["Email:MailServerAddress"], Convert.ToInt32(_configuration["Email:MailServerPort"]), false);
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate (_configuration["Email:UserId"], _configuration["Email:UserPassword"]);
}else if(Email.Pressets == 4){
client.Connect (Email.Server, Email.Port, false);
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate (Email.Username, Email.Password);
}else if(Email.Pressets == 5){
client.Connect (Email.Server, Email.Port, false);
client.AuthenticationMechanisms.Remove ("XOAUTH2");
//client.Authenticate (Email.Username, Email.Password);
}
//https://github.com/jstedfast/MailKit/issues/126
client.MessageSent += OnMessageSent;
client.Send (message);
client.Disconnect (true);
}
return new OkObjectResult("Email sent successfully!");
} catch (Exception ex) {
return new OkObjectResult(ex.Message);
}
}
//https://github.com/jstedfast/MailKit/issues/126
void OnMessageSent (object sender, MessageSentEventArgs e)
{
//Console.WriteLine ("The message was sent!");
}
/******************************** */
// Email Templates CRUD Operations
/******************************** */
[HttpPost("addtemplate")]
[Authorize]
public IActionResult AddTemplate( [FromBody] MessageTemplate template){
if(template != null){
var user = this.CurrentUser();
template.CreatedBy = user;
template.UpdatedBy = user;
template.Updated = template.Created = DateTimeOffset.Now;
context.Add(template);
context.SaveChanges();
this.Log(template,"MessageTemplate", "Message Template Added.");
return new OkObjectResult(template);
}else{
this.Log( template ,"MessageTemplate", "Error in adding Message Template attempt.", "MessageTemplate", "Error");
return new StatusCodeResult(500);
}
}
[HttpPut("updatetemplate/{id}")]
[Authorize]
public IActionResult UpdateTemplate( int id, [FromBody] MessageTemplate template){
var entity = context.MessageTemplate.Find(id);
if(template != null && entity != null){
var user = this.CurrentUser();
entity.Code = template.Code;
entity.Subject = template.Subject;
entity.BodyHtml = template.BodyHtml;
entity.BodyText = template.BodyText;
entity.UpdatedBy = user;
entity.Updated = DateTimeOffset.Now;
context.SaveChanges();
this.Log(entity,"MessageTemplate", "Message Template Updated.");
return new OkObjectResult(entity);
}else{
this.Log( entity ,"MessageTemplate", "Not Found MessageTemplate in an update attempt.", "MessageTemplate", "Error");
return new StatusCodeResult(500);
}
}
[HttpDelete("deletetemplate/{id}")]
[Authorize]
public IActionResult DeleteTemplate( int id ){
var entity = context.MessageTemplate.Find(id);
if(entity != null){
context.MessageTemplate.Remove(entity);
context.SaveChanges();
this.Log(entity,"MessageTemplate", "MessageTemplate Removed.");
return new OkResult();
}else{
this.Log( id ,"MessageTemplate", "Not Found MessageTemplate in a delete attempt.", "MessageTemplate", "Error");
return new StatusCodeResult(500);
}
}
[HttpGet("gettemplates")]
[Authorize]
public async Task<IActionResult> GetTemplates(){
return new OkObjectResult(await _context.MessageTemplate.ToListAsync());
}
public IActionResult Error()
{
return View();
}
}
public class Email{
public int Pressets;
public string Server;
public int Port;
public string Username;
public string Password;
public string From;
public string To;
public string Subject;
public string Body;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MMSdb.dbo.Tables
{
[Table("tbl_WorkHistory")]
public class tbl_WorkHistory
{
[Key]
public long wh_ID { get; set; }
public long dmg_ID { get; set; }
public Boolean? wh_Employed { get; set; }
public Double? wh_Unemployment { get; set; }
public DateTime? wh_UnemploymentStartDate { get; set; }
public DateTime? wh_UnemploymentEndDate { get; set; }
public DateTime? wh_DateLastworked { get; set; }
public Double? wh_TotalEarningsLastYear { get; set; }
public Double? wh_TotalEarningsthisYear { get; set; }
public int? wh_Type { get; set; }
public Boolean? wh_SelfEmployed { get; set; }
public Double? wh_SelfEmployedAmount { get; set; }
public String? wh_Notes { get; set; }
public Boolean? deleted { get; set; }
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// The list of perks to display in an item tooltip - and whether or not they have been activated. Perks apply a variety of effects to a character, and are generally either intrinsic to the item or provided in activated talent nodes or sockets.
/// </summary>
[DataContract]
public partial class DestinyPerksDestinyPerkReference : IEquatable<DestinyPerksDestinyPerkReference>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyPerksDestinyPerkReference" /> class.
/// </summary>
/// <param name="PerkHash">The hash identifier for the perk, which can be used to look up DestinySandboxPerkDefinition if it exists. Be warned, perks frequently do not have user-viewable information. You should examine whether you actually found a name/description in the perk's definition before you show it to the user..</param>
/// <param name="IconPath">The icon for the perk..</param>
/// <param name="IsActive">Whether this perk is currently active. (We may return perks that you have not actually activated yet: these represent perks that you should show in the item's tooltip, but that the user has not yet activated.).</param>
/// <param name="Visible">Some perks provide benefits, but aren't visible in the UI. This value will let you know if this is perk should be shown in your UI..</param>
public DestinyPerksDestinyPerkReference(uint? PerkHash = default(uint?), string IconPath = default(string), bool? IsActive = default(bool?), bool? Visible = default(bool?))
{
this.PerkHash = PerkHash;
this.IconPath = IconPath;
this.IsActive = IsActive;
this.Visible = Visible;
}
/// <summary>
/// The hash identifier for the perk, which can be used to look up DestinySandboxPerkDefinition if it exists. Be warned, perks frequently do not have user-viewable information. You should examine whether you actually found a name/description in the perk's definition before you show it to the user.
/// </summary>
/// <value>The hash identifier for the perk, which can be used to look up DestinySandboxPerkDefinition if it exists. Be warned, perks frequently do not have user-viewable information. You should examine whether you actually found a name/description in the perk's definition before you show it to the user.</value>
[DataMember(Name="perkHash", EmitDefaultValue=false)]
public uint? PerkHash { get; set; }
/// <summary>
/// The icon for the perk.
/// </summary>
/// <value>The icon for the perk.</value>
[DataMember(Name="iconPath", EmitDefaultValue=false)]
public string IconPath { get; set; }
/// <summary>
/// Whether this perk is currently active. (We may return perks that you have not actually activated yet: these represent perks that you should show in the item's tooltip, but that the user has not yet activated.)
/// </summary>
/// <value>Whether this perk is currently active. (We may return perks that you have not actually activated yet: these represent perks that you should show in the item's tooltip, but that the user has not yet activated.)</value>
[DataMember(Name="isActive", EmitDefaultValue=false)]
public bool? IsActive { get; set; }
/// <summary>
/// Some perks provide benefits, but aren't visible in the UI. This value will let you know if this is perk should be shown in your UI.
/// </summary>
/// <value>Some perks provide benefits, but aren't visible in the UI. This value will let you know if this is perk should be shown in your UI.</value>
[DataMember(Name="visible", EmitDefaultValue=false)]
public bool? Visible { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyPerksDestinyPerkReference {\n");
sb.Append(" PerkHash: ").Append(PerkHash).Append("\n");
sb.Append(" IconPath: ").Append(IconPath).Append("\n");
sb.Append(" IsActive: ").Append(IsActive).Append("\n");
sb.Append(" Visible: ").Append(Visible).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyPerksDestinyPerkReference);
}
/// <summary>
/// Returns true if DestinyPerksDestinyPerkReference instances are equal
/// </summary>
/// <param name="input">Instance of DestinyPerksDestinyPerkReference to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyPerksDestinyPerkReference input)
{
if (input == null)
return false;
return
(
this.PerkHash == input.PerkHash ||
(this.PerkHash != null &&
this.PerkHash.Equals(input.PerkHash))
) &&
(
this.IconPath == input.IconPath ||
(this.IconPath != null &&
this.IconPath.Equals(input.IconPath))
) &&
(
this.IsActive == input.IsActive ||
(this.IsActive != null &&
this.IsActive.Equals(input.IsActive))
) &&
(
this.Visible == input.Visible ||
(this.Visible != null &&
this.Visible.Equals(input.Visible))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.PerkHash != null)
hashCode = hashCode * 59 + this.PerkHash.GetHashCode();
if (this.IconPath != null)
hashCode = hashCode * 59 + this.IconPath.GetHashCode();
if (this.IsActive != null)
hashCode = hashCode * 59 + this.IsActive.GetHashCode();
if (this.Visible != null)
hashCode = hashCode * 59 + this.Visible.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using System;
using System.Globalization;
using System.IO;
namespace FileCabinetApp
{
/// <summary>
/// Main class of FileCabinetApp.
/// </summary>
public static class Program
{
private const string DeveloperName = "Dmitry Bolbat";
private const string HintMessage = "Enter your command, or enter 'help' to get help.";
private const int CommandHelpIndex = 0;
private const int DescriptionHelpIndex = 1;
private const int ExplanationHelpIndex = 2;
private static readonly Tuple<string, Action<string>>[] Commands = new Tuple<string, Action<string>>[]
{
new Tuple<string, Action<string>>("help", PrintHelp),
new Tuple<string, Action<string>>("exit", Exit),
new Tuple<string, Action<string>>("stat", Stat),
new Tuple<string, Action<string>>("create", Create),
new Tuple<string, Action<string>>("list", List),
new Tuple<string, Action<string>>("edit", Edit),
new Tuple<string, Action<string>>("find", Find),
new Tuple<string, Action<string>>("export", Export),
};
private static readonly string[][] HelpMessages = new string[][]
{
new string[] { "help", "prints the help screen", "The 'help' command prints the help screen." },
new string[] { "exit", "exits the application", "The 'exit' command exits the application." },
new string[] { "stat", "shows the number of records that the service stores", "The 'stat' command shows the number of records that the service stores." },
new string[] { "create", "creates new record", "The 'create' command creates new record." },
new string[] { "list", "shows list of records", "The 'list' command shows list of records." },
new string[] { "edit", "edits created record by id", "The 'edit' command allows to edit created record by id." },
new string[] { "find", "finds and shows created records by inputed property", "The 'find' command finds and shows created records by inputed property." },
new string[] { "export", "exports current records to csv or xml file", "The 'export' command exports current records to csv or xml file." },
};
private static string typeOfValidation;
private static FileCabinetRecord defaultValidationRecord = new FileCabinetRecord
{
Id = 0,
FirstName = "Sam",
LastName = "Dif",
DateOfBirth = new DateTime(1950, 5, 5),
WorkExperience = 1,
Weight = 10,
LuckySymbol = '7',
};
private static FileCabinetRecord customValidationRecord = new FileCabinetRecord
{
Id = 0,
FirstName = "FirstName",
LastName = "LastName",
DateOfBirth = new DateTime(2000, 1, 1),
WorkExperience = 15,
Weight = 70,
LuckySymbol = 'S',
};
private static IFileCabinetService fileCabinetServiceInterface;
private static bool isRunning = true;
/// <summary>
/// Starting point of console application.
/// </summary>
/// <param name="args">Command line arguments.</param>
public static void Main(string[] args)
{
if (args is null)
{
throw new ArgumentNullException(nameof(args));
}
Console.WriteLine($"File Cabinet Application, developed by {Program.DeveloperName}");
UsingValidationRules(args);
Console.WriteLine(Program.HintMessage);
Console.WriteLine();
do
{
Console.Write("> ");
var inputs = Console.ReadLine().Split(' ', 2);
const int commandIndex = 0;
var command = inputs[commandIndex];
if (string.IsNullOrEmpty(command))
{
Console.WriteLine(Program.HintMessage);
continue;
}
var index = Array.FindIndex(Commands, 0, Commands.Length, i => i.Item1.Equals(command, StringComparison.InvariantCultureIgnoreCase));
if (index >= 0)
{
const int parametersIndex = 1;
var parameters = inputs.Length > 1 ? inputs[parametersIndex] : string.Empty;
Commands[index].Item2(parameters);
}
else
{
PrintMissedCommandInfo(command);
}
}
while (isRunning);
}
/// <summary>
/// Specifying the type of validation rules.
/// </summary>
/// <param name="args">Command line arguments.</param>
private static void UsingValidationRules(string[] args)
{
if (args.Length == 0)
{
fileCabinetServiceInterface = new FileCabinetService(new DefaultValidator());
Console.WriteLine("Using default validation rules.");
typeOfValidation = "default";
return;
}
if (args[0].ToLower() == "--validation-rules=default")
{
fileCabinetServiceInterface = new FileCabinetService(new DefaultValidator());
Console.WriteLine("Using default validation rules.");
typeOfValidation = "default";
return;
}
if (args[0].ToLower() == "--validation-rules=custom")
{
fileCabinetServiceInterface = new FileCabinetService(new CustomValidator());
Console.WriteLine("Using custom validation rules.");
typeOfValidation = "custom";
return;
}
if (args[0] == "-v")
{
if (args[1].ToLower() == "default")
{
fileCabinetServiceInterface = new FileCabinetService(new DefaultValidator());
Console.WriteLine("Using default validation rules.");
typeOfValidation = "default";
return;
}
if (args[1].ToLower() == "custom")
{
fileCabinetServiceInterface = new FileCabinetService(new CustomValidator());
Console.WriteLine("Using custom validation rules.");
typeOfValidation = "custom";
return;
}
}
}
/// <summary>
/// Prints information about not existing command writed by user.
/// </summary>
/// <param name="command">String representation of writed command.</param>
private static void PrintMissedCommandInfo(string command)
{
Console.WriteLine($"There is no '{command}' command.");
Console.WriteLine();
}
/// <summary>
/// Prints information about all commands that application support.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void PrintHelp(string parameters)
{
if (!string.IsNullOrEmpty(parameters))
{
var index = Array.FindIndex(HelpMessages, 0, HelpMessages.Length, i => string.Equals(i[Program.CommandHelpIndex], parameters, StringComparison.InvariantCultureIgnoreCase));
if (index >= 0)
{
Console.WriteLine(HelpMessages[index][Program.ExplanationHelpIndex]);
}
else
{
Console.WriteLine($"There is no explanation for '{parameters}' command.");
}
}
else
{
Console.WriteLine("Available commands:");
foreach (var helpMessage in HelpMessages)
{
Console.WriteLine("\t{0}\t- {1}", helpMessage[Program.CommandHelpIndex], helpMessage[Program.DescriptionHelpIndex]);
}
}
Console.WriteLine();
}
/// <summary>
/// Exits the application.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Exit(string parameters)
{
Console.WriteLine("Exiting an application...");
isRunning = false;
}
/// <summary>
/// Prints the number of records that the service stores.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Stat(string parameters)
{
Console.WriteLine($"{Program.fileCabinetServiceInterface.GetStat()} record(s).");
}
/// <summary>
/// Reads input and validate it.
/// </summary>
/// <param name="converter">Function for converter.</param>
/// <param name="validator">Function for validator.</param>
/// <returns>Input in nessecary type.</returns>
private static T ReadInput<T>(Func<string, Tuple<bool, string, T>> converter, Func<T, Tuple<bool, string>> validator)
{
do
{
T value;
var input = Console.ReadLine();
var conversionResult = converter(input);
if (!conversionResult.Item1)
{
Console.WriteLine($"Conversion failed: {conversionResult.Item2}. Please, correct your input.");
continue;
}
value = conversionResult.Item3;
var validationResult = validator(value);
if (!validationResult.Item1)
{
Console.WriteLine($"Validation failed: {validationResult.Item2}. Please, correct your input.");
continue;
}
return value;
}
while (true);
}
/// <summary>
/// Convert string.
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>Tuple that represent convert status and converted result.</returns>
private static Tuple<bool, string, string> StringConverter(string str)
{
return new Tuple<bool, string, string>(true, str, str);
}
/// <summary>
/// Convert DateTime.
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>Tuple that represent convert status and converted result.</returns>
private static Tuple<bool, string, DateTime> DateConverter(string str)
{
string datePattern = "MM/dd/yyyy";
var parsed = DateTime.TryParseExact(str, datePattern, null, 0, out DateTime dateOfBirth);
return new Tuple<bool, string, DateTime>(parsed, str, dateOfBirth);
}
/// <summary>
/// Convert short.
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>Tuple that represent convert status and converted result.</returns>
private static Tuple<bool, string, short> ShortConverter(string str)
{
var parsed = short.TryParse(str, out short sh);
return new Tuple<bool, string, short>(parsed, str, sh);
}
/// <summary>
/// Convert decimal.
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>Tuple that represent convert status and converted result.</returns>
private static Tuple<bool, string, decimal> DecimalConverter(string str)
{
var parsed = decimal.TryParse(str, out decimal dcm);
return new Tuple<bool, string, decimal>(parsed, str, dcm);
}
/// <summary>
/// Convert char.
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>Tuple that represent convert status and converted result.</returns>
private static Tuple<bool, string, char> CharConverter(string str)
{
var parsed = char.TryParse(str, out char ch);
return new Tuple<bool, string, char>(parsed, str, ch);
}
/// <summary>
/// First name validation.
/// </summary>
/// <param name="firstName">String to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> FirstNameValidator(string firstName)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.FirstName = firstName;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Last name validation.
/// </summary>
/// <param name="lastName">String to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> LastNameValidator(string lastName)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.LastName = lastName;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Date of birth validation.
/// </summary>
/// <param name="dateOfBirth">DateTime object to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> DateOfBirthValidator(DateTime dateOfBirth)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.DateOfBirth = dateOfBirth;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Work experience validation.
/// </summary>
/// <param name="workExperience">Short object to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> WorkExperienceValidator(short workExperience)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.WorkExperience = workExperience;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Weightvalidation.
/// </summary>
/// <param name="weight">Decimal object to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> WeightValidator(decimal weight)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.Weight = weight;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Lucky symbol validation.
/// </summary>
/// <param name="luckySymbol">Char object to validate.</param>
/// <returns>Tuple with bool that represent validation status and string if exception catched.</returns>
private static Tuple<bool, string> LuckySymbolValidator(char luckySymbol)
{
FileCabinetRecord record = defaultValidationRecord;
if (typeOfValidation.Equals("custom"))
{
record = customValidationRecord;
}
record.LuckySymbol = luckySymbol;
return fileCabinetServiceInterface.StartValidation(record);
}
/// <summary>
/// Creates new record and save it as FileCabinetRecord object.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Create(string parameters)
{
FileCabinetRecord newRecord = new ();
Console.Write("First name: ");
newRecord.FirstName = ReadInput(StringConverter, FirstNameValidator);
Console.Write("Last name: ");
newRecord.LastName = ReadInput(StringConverter, LastNameValidator);
Console.Write("Date of birth: ");
newRecord.DateOfBirth = ReadInput(DateConverter, DateOfBirthValidator);
Console.Write("Work experience: ");
newRecord.WorkExperience = ReadInput(ShortConverter, WorkExperienceValidator);
Console.Write("Weight: ");
newRecord.Weight = ReadInput(DecimalConverter, WeightValidator);
Console.Write("Lucky symbol: ");
newRecord.LuckySymbol = ReadInput(CharConverter, LuckySymbolValidator);
try
{
int id = fileCabinetServiceInterface.CreateRecord(newRecord);
Console.WriteLine($"Record #{id} is created");
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Edits existing record and save it as FileCabinetRecord object.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Edit(string parameters)
{
var isIdParsed = int.TryParse(parameters, out int id);
if (!isIdParsed)
{
Console.WriteLine("Record id must be a number");
return;
}
var records = fileCabinetServiceInterface.GetRecords();
bool isRecordExist = false;
for (int i = 0; i < records.Count; i++)
{
if (records[i].Id == id)
{
isRecordExist = true;
}
}
if (isRecordExist)
{
FileCabinetRecord updatedRecord = new ();
updatedRecord.Id = id;
Console.Write("First name: ");
updatedRecord.FirstName = ReadInput(StringConverter, FirstNameValidator);
Console.Write("Last name: ");
updatedRecord.LastName = ReadInput(StringConverter, LastNameValidator);
Console.Write("Date of birth: ");
updatedRecord.DateOfBirth = ReadInput(DateConverter, DateOfBirthValidator);
Console.Write("Work experience: ");
updatedRecord.WorkExperience = ReadInput(ShortConverter, WorkExperienceValidator);
Console.Write("Weight: ");
updatedRecord.Weight = ReadInput(DecimalConverter, WeightValidator);
Console.Write("Lucky symbol: ");
updatedRecord.LuckySymbol = ReadInput(CharConverter, LuckySymbolValidator);
try
{
fileCabinetServiceInterface.EditRecord(updatedRecord);
Console.WriteLine($"Record #{id} is updated");
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine($"#{id} record is not found");
}
}
/// <summary>
/// Finds and prints records according to some property.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Find(string parameters)
{
CultureInfo ci = new ("en-US");
var inputs = parameters.Split(' ', 2);
if (inputs.Length != 2)
{
Console.WriteLine("Please input property of search and text for search like \" find firstname \"Ivan\" \" ");
return;
}
string property = inputs[0];
string text = inputs[1].Replace("\"", string.Empty);
if (property.ToLower().Equals("firstname"))
{
var list = fileCabinetServiceInterface.FindByFirstName(text);
if (list is null)
{
Console.WriteLine("There aren't such records");
}
else
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($"#{list[i].Id}, {list[i].FirstName}, {list[i].LastName}, {list[i].DateOfBirth.ToString("yyyy'-'MMM'-'dd", ci)}, Work experience: {list[i].WorkExperience}, Weight: {list[i].Weight}, Lucky symbol: {list[i].LuckySymbol}");
}
}
}
else if (property.ToLower().Equals("lastname"))
{
var list = fileCabinetServiceInterface.FindByLastName(text);
if (list is null)
{
Console.WriteLine("There aren't such records");
}
else
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($"#{list[i].Id}, {list[i].FirstName}, {list[i].LastName}, {list[i].DateOfBirth.ToString("yyyy'-'MMM'-'dd", ci)}, Work experience: {list[i].WorkExperience}, Weight: {list[i].Weight}, Lucky symbol: {list[i].LuckySymbol}");
}
}
}
else if (property.ToLower().Equals("dateofbirth"))
{
string pattern = "yyyy-MMM-dd";
var parsed = DateTime.TryParseExact(text, pattern, ci, 0, out DateTime dateOfBirth);
if (!parsed)
{
Console.WriteLine("Invalid date type, please, use yyyy-MMM-dd (2001-Dec-01) pattern");
return;
}
var list = fileCabinetServiceInterface.FindByDateOfBirth(dateOfBirth);
if (list is null)
{
Console.WriteLine("There aren't such records");
}
else
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($"#{list[i].Id}, {list[i].FirstName}, {list[i].LastName}, {list[i].DateOfBirth.ToString("yyyy'-'MMM'-'dd", ci)}, Work experience: {list[i].WorkExperience}, Weight: {list[i].Weight}, Lucky symbol: {list[i].LuckySymbol}");
}
}
}
else
{
Console.WriteLine("There isn't such property for search");
}
}
/// <summary>
/// Prints all existing records.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void List(string parameters)
{
var list = fileCabinetServiceInterface.GetRecords();
CultureInfo ci = new ("en-US");
if (list.Count == 0)
{
Console.WriteLine("List of records is empty, please use 'create' command to add record");
}
else
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($"#{list[i].Id}, {list[i].FirstName}, {list[i].LastName}, {list[i].DateOfBirth.ToString("yyyy'-'MMM'-'dd", ci)}, Work experience: {list[i].WorkExperience}, Weight: {list[i].Weight}, Lucky symbol: {list[i].LuckySymbol}");
}
}
}
/// <summary>
/// Export all existing records.
/// </summary>
/// <param name="parameters">String representation of writed command parameters.</param>
private static void Export(string parameters)
{
if (fileCabinetServiceInterface.GetRecords().Count == 0)
{
Console.WriteLine("List of records is empty, please use 'create' command to create record");
}
var inputs = parameters.Split(' ', 2);
if (inputs.Length != 2)
{
Console.WriteLine("Please input property of export like \"export csv filename.csv \" ");
return;
}
string exportType = inputs[0];
string fileName = inputs[1];
try
{
FileStream fileStream = new (fileName, FileMode.Open);
fileStream.Close();
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"Export failed: can't open file {fileName}");
return;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Export failed: can't access to the file {fileName}");
return;
}
catch (FileNotFoundException)
{
FileStream fileStream = new (fileName, FileMode.Create);
fileStream.Close();
StreamWriter writer = new (fileName);
writer.AutoFlush = true;
FileCabinetServiceSnapshot snapshot = fileCabinetServiceInterface.MakeSnapshot();
if (exportType == "csv")
{
snapshot.SaveToCsv(writer);
Console.WriteLine($"All records are exported to file {fileName}");
}
if (exportType.Equals("xml"))
{
snapshot.SaveToXml(writer);
Console.WriteLine($"All records are exported to file {fileName}");
}
writer.Close();
return;
}
Console.Write($"File is exist - rewrite {fileName}? [Y/n] ");
var input = Console.ReadLine();
if (input.ToLower().Equals("y"))
{
StreamWriter writer = new (fileName);
writer.AutoFlush = true;
FileCabinetServiceSnapshot snapshot = fileCabinetServiceInterface.MakeSnapshot();
if (exportType == "csv")
{
snapshot.SaveToCsv(writer);
Console.WriteLine($"All records are exported to file {fileName}");
}
if (exportType.Equals("xml"))
{
snapshot.SaveToXml(writer);
Console.WriteLine($"All records are exported to file {fileName}");
}
writer.Close();
}
if (input.ToLower().Equals("n"))
{
return;
}
}
}
} |
using System;
using System.Collections.Generic;
namespace Webshop.Data
{
public class Order
{
/// <summary>
/// A rendelést létrehozó felhasználó azonosítója
/// </summary>
public string UserId { get; set; }
/// <summary>
/// A rendeléshez tartozó fizetési mód neve
/// </summary>
public string PaymentMetod { get; set; }
/// <summary>
/// A rendeléshez tartozó kiszállítási opció neve
/// </summary>
public string ShippingMethod { get; set; }
/// <summary>
/// A rendelés létrehozásának időpontja
/// </summary>
public DateTime orderTime { get; set; }
/// <summary>
/// A rendelés státuszának egyéni azonosítója
/// </summary>
public int StatusId { get; set; }
/// <summary>
/// A rendelés státuszának objektuma
/// </summary>
public Status Status { get; set; }
/// <summary>
/// A megrendelés egyéni azonosítója
/// </summary>
public int OrderId { get; set; }
/// <summary>
/// A rendelés több terméket is tartalmazhat
/// </summary>
public List<OrderItem> orderItems { get; set; }
}
}
|
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="TcpConnectionListenerSettings.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the TcpConnectionListenerSettings class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
namespace IndiePortable.Communication.UniversalWindows
{
using System;
using System.Collections.Generic;
using System.Linq;
using Tcp;
/// <summary>
/// Provides information necessary for starting a <see cref="TcpConnectionListener" />.
/// </summary>
public sealed class TcpConnectionListenerSettings
{
/// <summary>
/// The backing field for the <see cref="ListenerNetworkAdapters" /> property.
/// </summary>
private readonly IEnumerable<IPPortAddressInfo> listenerNetworkAdaptersBacking;
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnectionListenerSettings" /> class.
/// </summary>
/// <param name="listenerPort">
/// The TCP port that shall be listened on for incoming connections.
/// </param>
public TcpConnectionListenerSettings(ushort listenerPort)
{
this.listenerNetworkAdaptersBacking = new[] { new IPPortAddressInfo(new byte[4], listenerPort) };
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnectionListenerSettings" /> class.
/// </summary>
/// <param name="listenerNetworkAdapters">
/// The network adapters' addresses to listen on.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="listenerNetworkAdapters" /> is <c>null</c>.</para>
/// </exception>
public TcpConnectionListenerSettings(params IPPortAddressInfo[] listenerNetworkAdapters)
: this((IEnumerable<IPPortAddressInfo>)listenerNetworkAdapters)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnectionListenerSettings" /> class.
/// </summary>
/// <param name="listenerNetworkAdapters">
/// The network adapters' addresses to listen on.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="listenerNetworkAdapters" /> is <c>null</c>.</para>
/// </exception>
public TcpConnectionListenerSettings(IEnumerable<IPPortAddressInfo> listenerNetworkAdapters)
{
if (object.ReferenceEquals(listenerNetworkAdapters, null))
{
throw new ArgumentNullException(nameof(listenerNetworkAdapters));
}
this.listenerNetworkAdaptersBacking = listenerNetworkAdapters.ToArray();
}
/// <summary>
/// Gets the network adapters' addresses to listen on.
/// </summary>
/// <value>
/// Contains the network adapters' addresses to listen on.
/// </value>
public IEnumerable<IPPortAddressInfo> ListenerNetworkAdapters => this.listenerNetworkAdaptersBacking;
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace RichJoslin
{
namespace BubbleShooterVR
{
public class GridBallSensorNode : MonoBehaviour
{
public Vector3 gridPosition { get; set; }
public const float POP_DELAY = 0.01f;
// for debugging
void OnDrawGizmos()
{
// Gizmos.color = Color.yellow;
// Gizmos.DrawSphere(transform.position, transform.localScale.x / 2);
}
public void OnTriggerEnter(Collider other)
{
GridBall parentGridBall = this.transform.parent.GetComponent<GridBall>();
if (parentGridBall != null)
{
BallShot ballShotThatHitMe = other.GetComponent<BallShot>();
if (ballShotThatHitMe != null)
{
// only sense flying balls
if (ballShotThatHitMe.state == BallShot.State.Flying)
{
// before processing anything else, snap a new GridBall into place
GridBall newGridBall = ballShotThatHitMe.SnapTo(parentGridBall.ballGrid, this);
// TODO: everything below this belongs in a different class - maybe use command pattern
// then start processing what happens after the ball exists
switch (ballShotThatHitMe.ballType)
{
case BallType.PaintSplash:
// turn all touched balls the same color
foreach (GridBall neighborBall in newGridBall.neighbors)
{
neighborBall.ballColor = newGridBall.ballColor;
}
break;
case BallType.Bomb:
// TODO: pop all balls in a radius
break;
default:
// basic match-3 popping
GameMgr.I.StartCoroutine(this.PopChainLoop(newGridBall));
break;
}
}
}
else
{
Debug.LogWarning("grid ball sensor hit with something other than a ball shot", this);
}
}
else
{
Debug.LogWarning("orphaned grid ball sensor", this);
}
}
public IEnumerator PopChainLoop(GridBall newGridBall)
{
// set this before we lose a reference to it when the new grid ball pops
BallGrid currentBallGrid = newGridBall.ballGrid;
currentBallGrid.SetState(BallGrid.State.Popping);
List<GridBall> ballCluster = new List<GridBall>() { newGridBall };
List<GridBall> searched = new List<GridBall>(ballCluster);
Queue<GridBall> searchQueue = new Queue<GridBall>(ballCluster);
List<GridBall> adjacentBallsThatSurvived = new List<GridBall>();
while (searchQueue.Count > 0)
{
GridBall curBall = searchQueue.Dequeue();
if (curBall.ballColor == newGridBall.ballColor)
{
if (!ballCluster.Contains(curBall)) ballCluster.Add(curBall);
foreach (GridBall gb in curBall.neighbors)
{
if (!searched.Contains(gb))
{
searched.Add(gb);
searchQueue.Enqueue(gb);
}
}
}
else
{
if (!adjacentBallsThatSurvived.Contains(curBall)) adjacentBallsThatSurvived.Add(curBall);
}
}
if (ballCluster.Count >= 3)
{
foreach (GridBall gb in ballCluster)
{
gb.RemoveFromWall();
yield return new WaitForSeconds(POP_DELAY);
}
}
int loopSafety = 0;
List<GridBall> searched2 = new List<GridBall>();
while (adjacentBallsThatSurvived.Count > 0)
{
GridBall survivorBall = adjacentBallsThatSurvived[0];
searched2.Add(survivorBall);
adjacentBallsThatSurvived.RemoveAt(0);
survivorBall.CheckIfConnectedToWall();
if (!survivorBall.isConnectedToWall)
{
foreach (GridBall gb in survivorBall.neighbors)
{
if (!searched2.Contains(gb) && !adjacentBallsThatSurvived.Contains(gb))
{
adjacentBallsThatSurvived.Add(gb);
}
}
survivorBall.RemoveFromWall();
yield return new WaitForSeconds(POP_DELAY);
}
loopSafety++;
if (loopSafety > 10000)
{
Debug.LogError("loop safety!");
break;
}
}
currentBallGrid.SetState(BallGrid.State.Default);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Numero
{
private double numero;
/// <summary>
/// Cambia el valor del Numero luego de validar el valor recibido por parametro.
/// </summary>
/// <param name="numero"></param>
public void SetNumero(string numero)
{
this.numero = ValidarNumero(numero);
}
/// <summary>
/// Intenta parsear el string recibido, devuelve 0 si el valor no es valido.
/// </summary>
/// <param name="numero"></param>
/// <returns></returns>
private double ValidarNumero(string numero)
{
double parseo;
double.TryParse(numero, out parseo);
return parseo;
}
/// <summary>
/// Crea una instancia de numero con valor 0.
/// </summary>
public Numero()
{
this.numero = 0;
}
/// <summary>
/// Crea una instacia de numero con el valor recibido por parametro.
/// </summary>
/// <param name="numero"></param>
public Numero(double numero)
{
this.numero = numero;
}
/// <summary>
/// Crea una instacia de numero con el valor recibido por parametro luego de que este sea validado.
/// </summary>
/// <param name="strNumero"></param>
public Numero(string strNumero)
{
this.SetNumero(strNumero);
}
/// <summary>
/// Checkea si el string recibido corresponde a un numero binario.
/// </summary>
/// <param name="binario"></param>
/// <returns></returns>
private static bool EsBinario(string binario)
{
foreach(char c in binario)
{
if (!(c.Equals('0') || c.Equals('1') || c.Equals('\n')))
{
return false;
}
}
return true;
}
/// <summary>
/// Convierte un numero binario recibido como string a su valor decimal si es posible.
/// </summary>
/// <param name="binario"></param>
/// <returns></returns>
static public string BinarioDecimal(string binario)
{
int devolucion = 0;
int contador = (binario.Length - 2);
int digito;
if(EsBinario(binario))
{
foreach (char c in binario)
{
int.TryParse(c.ToString(), out digito);
if (contador == 0)
{
devolucion += digito;
break;//Se sale del ciclo para no tomar errores con los demas char del string. Ej. \n.
}
else
{
devolucion += (int)Math.Pow(digito * 2, contador);
}
contador--;
}
return devolucion.ToString();
}
else
{
return "Valor invalido";
}
}
/// <summary>
/// Retorna un string con un numero binario equivalente a la parte entera positiva del double recibido.
/// </summary>
/// <param name="numero"></param>
/// <returns></returns>
static public string DecimalBinario(double numero)
{
string devolucion = "\n";
numero = (int) Math.Abs(numero);
while (numero > 1)
{
devolucion = devolucion.Insert(0, (numero % 2).ToString());
numero = (numero - (numero % 2)) / 2;
}
devolucion = devolucion.Insert(0, (numero % 2).ToString());
return devolucion;
}
/// <summary>
/// Convierte un numero decimal recibido como string a binario si es possible, sino retorna valor invalido.
/// </summary>
/// <param name="numero"></param>
/// <returns></returns>
static public string DecimalBinario(string numero)
{
double x;
double.TryParse(numero, out x);
if(x == 0.0 && numero != "0")
{
return "Valor invalido";
}
return DecimalBinario(x);
}
/// <summary>
/// Operador de resta entre dos numeros.
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static double operator -(Numero n1, Numero n2)
{
return (n1.numero - n2.numero);
}
/// <summary>
/// Operador de suma entre dos numeros.
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static double operator +(Numero n1, Numero n2)
{
return (n1.numero + n2.numero);
}
/// <summary>
/// Operador de division entre dos num. En caso de que el divisor sea 0 retorna MinValue.
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static double operator /(Numero n1, Numero n2)
{
if(n2.numero == 0)
{
return double.MinValue;
}
else
{
return (n1.numero / n2.numero);
}
}
/// <summary>
/// Operador de multiplicacion entre dos numeros.
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static double operator *(Numero n1, Numero n2)
{
return (n1.numero * n2.numero);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Worker : MonoBehaviour
{
public TaskList task;
public ResourceManager RM;
private ActionList AL;
private InputManager IM;
public GameObject targetNode;
public GameObject unitMesh;
public Material[] unitMaterials;
public Material[] highlightedMaterials;
public NodeManager.ResourceTypes heldResourceType;
public bool isGathering = false;
public bool isGatherer = false;
private NavMeshAgent agent;
private NavMeshObstacle obstacle;
private Animator anim;
private ObjectInfo objInfo;
private SkinnedMeshRenderer unitRenderer;
public int heldResource;
public int maxHeldResource;
public float distToTarget;
// Start is called before the first frame update
void Start()
{
StartCoroutine(GatherTick());
agent = GetComponent<NavMeshAgent>();
obstacle = GetComponent<NavMeshObstacle>();
anim = GetComponent<Animator>();
objInfo = GetComponent<ObjectInfo>();
AL = FindObjectOfType<ActionList>();
RM = FindObjectOfType<ResourceManager>();
IM = FindObjectOfType<InputManager>();
unitRenderer = unitMesh.GetComponent<SkinnedMeshRenderer>();
agent.autoBraking = false;
agent.stoppingDistance = 1.5f;
}
// Update is called once per frame
void Update()
{
//animation control
if (task == TaskList.Moving || task == TaskList.Gathering || task == TaskList.Delivering)
{
anim.SetBool("isWalking", true);
if (isGathering)
{
anim.SetBool("isWalking", false);
anim.SetBool("isCollecting", true);
}
else
{
anim.SetBool("isCollecting", false);
anim.SetBool("isWalking", true);
}
}
if(task == TaskList.Idle)
{
anim.SetBool("isCollecting", false);
anim.SetBool("isWalking", false);
}
if (!agent.pathPending && anim.GetBool("isWalking") == true)
{
if (targetNode == null)
{
obstacle.enabled = false;
agent.enabled = true;
if (agent.remainingDistance <= agent.stoppingDistance + 2.6)
{
if (agent.velocity.sqrMagnitude <= 0.5f)
{
anim.SetBool("isWalking", false);
task = TaskList.Idle;
agent.destination = transform.position;
}
}
}
}
if (task == TaskList.Gathering)
{
if (targetNode != null)
{
distToTarget = Vector3.Distance(targetNode.transform.position, transform.position);
var targetRotation = Quaternion.LookRotation(targetNode.transform.position - transform.position);
// Smoothly rotate towards the target point.
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
if (distToTarget <= 8f)
{
Gather();
}
}
}
if(task == TaskList.Delivering)
{
if (distToTarget <= 15.5f)
{
if (heldResourceType == NodeManager.ResourceTypes.Stone)
{
if (RM.stone >= RM.maxStone)
{
task = TaskList.Idle;
isGatherer = false;
}
else if (RM.stone + heldResource >= RM.maxStone)
{
int resourceOverflow = (int)RM.maxStone - (int)RM.stone;
heldResource -= resourceOverflow;
RM.stone = RM.maxStone;
RM.collectedStone += heldResource;
if (targetNode != null)
{
task = TaskList.Gathering;
agent.destination = targetNode.transform.position;
}
else
{
task = TaskList.Idle;
}
isGatherer = false;
}
else
{
RM.stone += heldResource;
RM.collectedStone += heldResource;
heldResource = 0;
if (targetNode != null)
{
task = TaskList.Gathering;
agent.destination = targetNode.transform.position;
}
else
{
task = TaskList.Idle;
}
isGatherer = false;
}
}
else if (heldResourceType == NodeManager.ResourceTypes.Iron)
{
if (RM.iron >= RM.maxIron) //Is the stored amount of Iron greater than or equal to the max amount of Iron?
{
task = TaskList.Idle; //Set the colonist to be idle
isGatherer = false; //Set the colonist to not be a gatherer
}
else if (RM.iron + heldResource >= RM.maxIron) //Is the stored amount of Iron going to exceed the max when the colonist delivers?
{
int resourceOverflow = (int)RM.maxIron - (int)RM.iron; //How much Iron can be stored before hitting capacity
heldResource -= resourceOverflow; //Remove the Iron that can be stored from the colonist
RM.iron = RM.maxIron; //Set the stored Iron to equal the maximum
RM.collectedIron += heldResource;
if (targetNode != null)
{
task = TaskList.Gathering; //Set the worker to go back to gathering
agent.destination = targetNode.transform.position; //Set the worker's destination
}
else
{
task = TaskList.Idle;
}
isGatherer = false; //Set the worker to not be a gatherer
}
else
{
RM.iron += heldResource; //Add the worker's Iron to the stored Iron
RM.collectedIron += heldResource;
heldResource = 0; //Empty the worker's Iron storage
if (targetNode != null)
{
task = TaskList.Gathering; //Set the worker to go back to gathering
agent.destination = targetNode.transform.position; //Set the worker's destination
}
else
{
task = TaskList.Idle;
}
isGatherer = false; //Set the worker to not be a gatherer
}
}
else if(heldResourceType == NodeManager.ResourceTypes.Gold)
{
if(RM.gold >= RM.maxGold)
{
task = TaskList.Idle;
isGatherer = false;
}
else if(RM.gold + heldResource >= RM.maxGold)
{
int resourceOverflow = (int)RM.maxGold - (int)RM.gold;
heldResource -= resourceOverflow;
RM.gold = RM.maxGold;
RM.collectedGold += heldResource;
if (targetNode != null)
{
task = TaskList.Gathering;
agent.destination = targetNode.transform.position;
}
else
{
task = TaskList.Idle;
}
isGatherer = false;
}
else
{
RM.gold += heldResource;
RM.collectedGold += heldResource;
heldResource = 0;
if (targetNode != null)
{
task = TaskList.Gathering;
agent.destination = targetNode.transform.position;
}
else
{
task = TaskList.Idle;
}
isGatherer = false;
}
}
}
}
if(targetNode == null && objInfo.target == null && task == TaskList.Gathering)
{
isGatherer = false;
if(heldResource != 0)
{
obstacle.enabled = false; //Disable the NavMeshObstacle component
agent.enabled = true; //Enables the NavMeshAgent component
isGathering = false;
if (GetClosestDropOff(IM.playerBuildings) != null)
{
agent.destination = GetClosestDropOff(IM.playerBuildings).transform.position;
distToTarget = Vector3.Distance(GetClosestDropOff(IM.playerBuildings).transform.position, transform.position);
task = TaskList.Delivering;
}
else
{
task = TaskList.Idle;
}
}
else
{
task = TaskList.Idle;
}
}
if(heldResource >= maxHeldResource)
{
if (isGathering && targetNode != null)
{
targetNode.GetComponent<NodeManager>().gatherers--;
}
isGathering = false;
obstacle.enabled = false;
agent.enabled = true;
if (GetClosestDropOff(IM.playerBuildings) != null)
{
agent.destination = GetClosestDropOff(IM.playerBuildings).transform.position;
distToTarget = Vector3.Distance(GetClosestDropOff(IM.playerBuildings).transform.position, transform.position);
task = TaskList.Delivering;
}
else
{
task = TaskList.Idle;
}
}
if(Input.GetMouseButtonDown(1) && objInfo.isSelected)
{
if (!BuildingPlacement.buildingProcess)
{
RightClick();
}
}
if(objInfo.isSelected)
{
OnMouseExit();
}
}
public void RightClick()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 500))
{
if(hit.collider.tag == "Ground")
{
heldResource = 0;
if(isGathering && targetNode != null)
{
targetNode.GetComponent<NodeManager>().gatherers--;
isGathering = false;
isGatherer = false;
}
if(targetNode != null)
{
targetNode = null;
}
if (!agent.enabled)
{
obstacle.enabled = false;
agent.enabled = true;
}
AL.Move(agent, hit, true);
task = TaskList.Moving;
obstacle.enabled = false;
agent.enabled = true;
}
else if(hit.collider.tag == "Resource")
{
heldResource = 0;
if (isGathering && targetNode != null)
{
targetNode.GetComponent<NodeManager>().gatherers--;
isGathering = false;
isGatherer = false;
}
if(!agent.enabled)
{
obstacle.enabled = false;
agent.enabled = true;
}
//AL.Move(agent, hit, false);
targetNode = hit.collider.gameObject;
agent.destination = targetNode.transform.position;
task = TaskList.Gathering;
AudioManager.Instance.PlayMessageSound("WorkerGather");
}
}
}
GameObject GetClosestDropOff(List<GameObject> dropOffs)
{
GameObject closestDrop = null;
float closestDistance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject targetDrop in dropOffs)
{
ObjectInfo buildingInfo = targetDrop.GetComponent<ObjectInfo>();
if (!buildingInfo.isUnit && buildingInfo.isPlayerObject)
{
PlaceableBuilding placeableBuilding = targetDrop.GetComponent<PlaceableBuilding>();
if (placeableBuilding.isDropOff && placeableBuilding.isPlaced && heldResourceType == placeableBuilding.resourceType)
{
Vector3 direction = targetDrop.transform.position - position;
float distance = direction.sqrMagnitude;
if (distance < closestDistance)
{
closestDistance = distance;
closestDrop = targetDrop;
}
}
}
}
return closestDrop;
}
public void Gather()
{
isGathering = true;
if(!isGatherer)
{
targetNode.GetComponent<NodeManager>().gatherers++;
isGatherer = true;
}
heldResourceType = targetNode.GetComponent<NodeManager>().resourceType;
obstacle.enabled = true;
agent.enabled = false;
}
IEnumerator GatherTick()
{
while(true)
{
yield return new WaitForSeconds(1);
if(isGathering)
{
heldResource++;
}
}
}
public void PlayGatheringSound()
{
AudioManager.Instance.PlayRandomWorkerSound(transform.position);
}
void OnMouseOver()
{
if (!objInfo.isSelected)
{
unitRenderer.materials = highlightedMaterials;
}
}
void OnMouseExit()
{
unitRenderer.materials = unitMaterials;
}
}
|
namespace AdventCalendar.Day7
{
public abstract class BinaryGate : ICircuitElement
{
protected ICircuitElement Input1 { get; private set; }
protected ICircuitElement Input2 { get; private set; }
protected BinaryGate(ICircuitElement input1, ICircuitElement input2)
{
Input1 = input1;
Input2 = input2;
}
public abstract ushort GetSignalValue();
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FeelingGoodApp.Services.Models
{
public class Location
{
public int Id { get; set; }
[JsonProperty(PropertyName = "lat")]
public float Latitude { get; set; }
[JsonProperty(PropertyName = "lng")]
public float Longitude { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UDPDepthTest
{
class Program
{
static DepthClient dc;
static void Main(string[] args)
{
getdepth gd = new getdepth();
gd.DataReceived += Gd_DataReceived;
dc = new DepthClient(424, 512);
dc.InitCLients();
while (true)
{
Console.WriteLine(dc.Recieve().Length);
}
}
private static void Gd_DataReceived(object sender, ushort[] e)
{
dc.Send("127.0.0.1", e);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Manager
{
/// <summary>
/// 사운드 관련 스크립트입니다.
///
/// 0 : 문 여는 소리
/// 1 : 문 닫는 소리
/// 2 : 귀신 소리
/// 3 : 캐비넷 소리
/// 4 : keypad누르는 소리
/// </summary>
public class soundManager : MonoBehaviour
{
private AudioSource asource;
[SerializeField] private AudioClip[] aclip;
// Start is called before the first frame update
private static soundManager manager;
public static soundManager soundsystem
{
get { return manager; }
}
private void Awake()
{
manager = GetComponent<soundManager>();
}
void Start()
{
asource = GetComponent<AudioSource>();
}
public void open_door()
{
asource.clip = aclip[0];
asource.Play();
}
public void close_door()
{
asource.clip = aclip[1];
asource.Play();
}
public void ghost()
{
asource.clip = aclip[2];
asource.Play();
}
public void cabinet()
{
asource.clip = aclip[3];
asource.loop = false;
asource.volume = 0.2f;
asource.Play();
}
public void keypad_btn()
{
asource.clip = aclip[4];
asource.Play();
}
public void Quizdoing()
{
asource.clip = aclip[5];
asource.Play();
}
public void Quizending()
{
asource.clip = aclip[6];
asource.Play();
}
public void gun()
{
asource.clip = aclip[7];
asource.Play();
}
public void last()
{
asource.clip = aclip[8];
asource.Play();
}
}
}
|
using PhotoShare.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhotoShare.Client.Core.Commands
{
public class LogoutCommand
{
public string Execute(string[] data)
{
if(!AuthenticationManager.IsAuthenticated())
{
throw new InvalidOperationException("You shold log in first in order to logout!");
}
User user = AuthenticationManager.GetCurentUser();
AuthenticationManager.Logout();
return $"User {user.Username} successfully logged out!";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SecondWebAppHomework.Models;
namespace SecondWebAppHomework.Controllers
{
public class CatsController : Controller
{
public IActionResult Index(Color? color, Gender? gender)
{
var cats = PopulateList();
if (color.HasValue)
{
cats = cats.Where(x => x.AnimalColor == color.Value).ToList();
}
if (gender.HasValue)
{
cats = cats.Where(x => x.AnimalGender == gender.Value).ToList();
}
return View(cats);
}
private List<Cat> PopulateList()
{
List<Cat> cats = new List<Cat>
{
new Cat()
{
AnimalName = "Cathy",
AnimalGender = Gender.Male,
AnimalColor = Color.Black
},
new Cat()
{
AnimalName = "Kitty",
AnimalGender = Gender.Female,
AnimalColor = Color.White
},
new Cat()
{
AnimalName = "Micky",
AnimalGender = Gender.Male,
AnimalColor = Color.Yellow
}
};
return cats;
}
}
} |
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BlobHostedInWeb.BlobHandler
{
public class BlobProcesser
{
CloudStorageAccount myStorageAccount = null;
CloudBlobContainer myContainer = null;
CloudBlobClient blobClient = null;
string _generalStorageConString = "";
string _premiumStorageConString = "";
string _storageConString = "";
bool _isPremium = false;
public BlobProcesser(bool isPremium = false)
{
_isPremium = isPremium;
_storageConString = !_isPremium ? _generalStorageConString : _premiumStorageConString;
}
public async Task WriteDocToBlobAsync(byte[] docBytes, int count)
{
if (CloudStorageAccount.TryParse(_storageConString, out myStorageAccount))
{
try
{
CloudBlobClient blobClient = myStorageAccount.CreateCloudBlobClient();
myContainer = blobClient.GetContainerReference("nileshdemoblobs");
await myContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Blob, new BlobRequestOptions(), new OperationContext());
CloudBlockBlob blockBlob = myContainer.GetBlockBlobReference("fileFromService");
await blockBlob.UploadFromByteArrayAsync(docBytes, 0, count);
//blockBlob.u
}
catch (StorageException stex)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
}
}
}
public async Task<DummyModel> ReadDocFromBlobAsync()
{
DummyModel outputModel = new DummyModel();
if (CloudStorageAccount.TryParse(_storageConString, out myStorageAccount))
{
try
{
CloudBlobClient blobClient = myStorageAccount.CreateCloudBlobClient();
myContainer = blobClient.GetContainerReference("nileshdemoblobs");
CloudBlockBlob blockBlob = myContainer.GetBlockBlobReference("fileFromService");
Stream fileContent = await blockBlob.OpenReadAsync();
using (MemoryStream ms = new MemoryStream())
{
fileContent.CopyTo(ms);
outputModel.Data = ms.ToArray();
}
outputModel.FileName = "fileFromService";
}
catch (StorageException stex)
{
throw;
}
catch (Exception ex)
{
}
finally
{
}
}
return outputModel;
}
}
}
|
using System.Collections.Generic;
namespace DisposableFixer.Configuration {
internal class DefaultConfiguration : IConfiguration {
public DefaultConfiguration() {
TrackingTypes = new HashSet<string> {
"System.IO.StreamReader",
"System.IO.StreamWriter",
"System.IO.BinaryReader",
"System.IO.BinaryWriter",
"System.IO.BufferedStream",
"System.Security.Cryptography.CryptoStream",
"System.Resources.ResourceReader",
"System.Resources.ResourceSet",
"System.Resources.ResourceWriter",
"Newtonsoft.Json.JsonTextWriter",
"Newtonsoft.Json.Bson.BsonWriter",
"Newtonsoft.Json.Bson.BsonWriter"
};
IgnoredInterfaces = new HashSet<string> {
"System.Collections.Generic.IEnumerator",
"Microsoft.Extensions.Logging.ILoggerFactory"
};
IgnoredTypes = new HashSet<string> {
"System.Threading.Tasks.Task",
};
IgnoredTrackingTypeCtorCalls = new Dictionary<string, IReadOnlyCollection<CtorCall>> {
["System.IO.BinaryReader"] = new [] {
new CtorCall(new [] {"Stream","Encoding","Boolean"}, 2, true)
},
["System.IO.BinaryWriter"] = new[] {
new CtorCall(new [] {"Stream","Encoding","Boolean"}, 2, true)
},
["System.IO.StreamReader"] = new[] {
new CtorCall(new [] {"Stream", "Encoding", "Boolean", "Int32", "Boolean"},4, true)
},
["System.IO.StreamWriter"] = new[] {
new CtorCall(new [] {"Stream","Encoding", "Int32","Boolean"},3, true)
}
};
}
public HashSet<string> IgnoredTypes { get; }
public HashSet<string> IgnoredInterfaces { get; }
public HashSet<string> TrackingTypes { get; }
public Dictionary<string,IReadOnlyCollection<CtorCall>> IgnoredTrackingTypeCtorCalls { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace TxHumor.Common
{
public class com_UrlHelper
{
private com_UrlHelper() { ;}
public static string GetRelUrl(object o, string separator)
{
string[] array = combine(o);
return string.Join(separator, array);
}
public static string GetAbsUrl(string hostName, object o, string separator, string anchor)
{
string relUrl = GetRelUrl(o, separator);
return string.Concat(hostName, "/", relUrl, "/", anchor ?? string.Empty);
}
private static string[] combine(object o)
{
if (o == null) return null;
PropertyInfo[] pis = o.GetType().GetProperties();
if (pis == null || pis.Length == 0) return null;
List<string> list = new List<string>();
foreach (PropertyInfo item in pis)
{
var value = item.GetValue(o, null);
if (value == null) continue;
string s = value.ToString();
list.Add(s);
}
return list.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Problem1
{
static void Answer1()
{
int summ = 0;
for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
summ += i;
}
}
Console.Out.WriteLine("Summ = {0}", summ);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Palindrome
{
class Program
{
static void Main(string[] args)
{
for (int i = 10000; i > 0; i--) {
string iString = i.ToString();
string reverse = new string(iString.Reverse().ToArray());
if (iString == reverse)
{
Console.WriteLine("Palindrom: {0} ", i);
break;
}
}
Console.ReadLine();
}
}
}
|
using Cinema.Data.Models;
using Cinema.Data.Repositories;
using Cinema.Data.Services.Contracts;
using Moq;
using NUnit.Framework;
using System;
namespace Cinema.Tests.Data.Services.Tests.SeatService
{
[TestFixture]
public class ConstructorShould
{
[Test]
public void InitiateNewSeatServiceInstanceWhenProperDependncyIsPassed()
{
var mockedFilmScreeningRepo = new Mock<IRepository<FilmScreening>>();
var actualSeatService =
new Cinema.Data.Services.SeatService(mockedFilmScreeningRepo.Object);
Assert.IsInstanceOf(typeof(ISeatService), actualSeatService);
Assert.IsInstanceOf(typeof(Cinema.Data.Services.SeatService), actualSeatService);
}
[Test]
public void ThrowWhenParameterFilmScreeningRepositoryHasNullValue()
{
IRepository<FilmScreening> nullFilmScreeningRepo = null;
Assert.That(() =>
new Cinema.Data.Services.SeatService(nullFilmScreeningRepo),
Throws.InstanceOf<ArgumentNullException>());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Content_Manegement.Entities
{
public class Menu
{
public virtual int MenuId { get; set; }
public virtual string Title { get; set; }
public virtual string MenuType { get; set; }
public virtual string Description { get; set; }
public virtual string TitMenuPermision { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace ProductsSrvc
{
public class ProductsRepository : IProductsRepository
{
public async Task<IEnumerable<Product>> GetProducts()
{
using (var context = new ProductsDbContext())
{
var results = await context.Products.AsNoTracking().OrderBy(p => p.Name).ToListAsync();
return results;
}
}
public async Task<Product> GetProduct(int Id)
{
using (var context = new ProductsDbContext())
{
var results = await context.Products.FindAsync(Id);
return results;
}
}
public async Task<int> AddProduct(Product product)
{
using (var context = new ProductsDbContext())
{
if (product == null)
{
throw new ArgumentNullException("product is null");
}
context.Products.Add(product);
await context.SaveChangesAsync();
return product.Id;
}
}
public async Task UpdateProduct(int Id, Product product)
{
using (var context = new ProductsDbContext())
{
context.Entry(product).State = EntityState.Modified;
await context.SaveChangesAsync();
}
}
public async Task DeleteProduct(int Id)
{
using (var context = new ProductsDbContext())
{
var product = context.Products.Find(Id);
if (product == null)
{
throw new ArgumentNullException("Product Doesn't exist");
}
context.Entry(product).State = EntityState.Deleted;
await context.SaveChangesAsync();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Resources;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
namespace DCL.Phone.Xna
{
/// <summary>
/// Provides an extending "wrapper" over the default Microsoft.Xna.Framework.Game
/// with pivot functionality (pivot is a UI based on switching between tabs).
/// XNA games that require the tab interface should derive from this class.
/// </summary>
public class PivotGame: Game
{
#region Fields
int delta = 0; //Indicates the scrolling "distance"
Vector2 deltaVector = Vector2.Zero; //For drawing texts
int selInd = 0; //Selected tab index
float cameraWidth=8, zoom=1; //Projection paramenters
bool SelectedIndexSetFirstTime = true; //Selection changed event in not fired when loading the pivot
bool SwitchingTabsNow = false; //We are changing the selection right now
ContentManager FontLoader; //For providing default fonts from the resource file
List<int> CallStack = new List<int>(); //Is needed for handling the "Back" button
ProjectionType proj; //Projection for BasicEffect
/// <summary>
/// The standard font for drawing page headers that can be changed.
/// </summary>
protected internal SpriteFont HeaderFont;
/// <summary>
/// The font that is used to draw text on the page and can be changed.
/// </summary>
protected internal SpriteFont ContentFont;
/// <summary>
/// The font that is used to draw the application title and can be changed
/// (the recommended font size is 16-20)
/// </summary>
protected internal SpriteFont TitleFont;
#endregion
#region Events
/// <summary>
/// The devegate for the SelectionChanged event handler.
/// </summary>
/// <param name="sender">object that fires the event.</param>
/// <param name="e">Event arguments that contain the previous selected page index.</param>
public delegate void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);
/// <summary>
/// Is fired when used changes the current pivot page by scrolling or tapping at the header.
/// </summary>
public event SelectionChangedEventHandler SelectionChanged;
#endregion
#region Properties
#region Appearance
/// <summary>
/// Gets or sets the title of the application.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the background color of all the pivot pages.
/// </summary>
public Color BackgroundColor
{
get { return this[SelectedIndex].BackgroundColor; }
set
{
foreach (PivotGameItem pgi in Items)
pgi.BackgroundColor = value;
}
}
/// <summary>
/// Gets or sets the foreground (text) color of all the pivot pages.
/// </summary>
public Color ForegroundColor
{
get { return this[SelectedIndex].ForegroundColor; }
set
{
foreach (PivotGameItem pgi in Items)
pgi.ForegroundColor = value;
}
}
/// <summary>
/// Gets or sets the background color of scenes on all the pivot pages.
/// </summary>
public Color SceneBackgroundColor
{
get { return this[SelectedIndex].DrawingArea.BackgroundColor; }
set
{
foreach (PivotGameItem pgi in Items)
pgi.DrawingArea.BackgroundColor = value;
}
}
/// <summary>
/// Gets or sets the background texture of scenes on all the pivot pages.
/// </summary>
public Texture2D SceneBackgroundTexture
{
get { return this[SelectedIndex].DrawingArea.BackgroundTexture; }
set
{
foreach (PivotGameItem pgi in Items)
pgi.DrawingArea.BackgroundTexture = value;
}
}
/// <summary>
/// Gets or sets the rectangle for the scenes on all the pivot pages.
/// </summary>
public Rectangle DrawingArea
{
get
{
return new Rectangle(this[SelectedIndex].DrawingArea.X,
this[SelectedIndex].DrawingArea.Y,
this[SelectedIndex].DrawingArea.Width,
this[SelectedIndex].DrawingArea.Height);
}
set
{
foreach (PivotGameItem pgi in Items)
{
pgi.DrawingArea.X = value.X;
pgi.DrawingArea.Y = value.Y;
pgi.DrawingArea.Width = value.Width;
pgi.DrawingArea.Height = value.Height;
pgi.Update();
}
}
}
/// <summary>
/// Gets or sets the image that is shown while loading the application.
/// The property should be set in the LoadContent() method before calling base.LoadContent().
/// </summary>
public Texture2D SplashScreenImage { get; set; }
#endregion
#region Graphics
/// <summary>
/// Gets or sets the default GraphicsDeviceManager object of the game.
/// </summary>
protected internal GraphicsDeviceManager GraphicsDeviceManager { get; set; }
/// <summary>
/// Gets or sets the default SpriteBatch object that is used by the game to draw textures.
/// </summary>
protected internal SpriteBatch SpriteBatch { get; set; }
/// <summary>
/// Gets or sets the default BasicEffect object that is used by the game to draw 3D scenes.
/// </summary>
protected BasicEffect BasicEffect { get; set; }
/// <summary>
/// The projection type for BasicEffect.
/// </summary>
protected ProjectionType Projection
{
get { return proj; }
set
{
proj = value;
if (value == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, CameraScale / Zoom), new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / Zoom);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-CameraScale / Zoom / 2 + SceneCenterTranslation.X,
CameraScale / Zoom / 2 + SceneCenterTranslation.X,
-CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
-CameraScale, CameraScale);
}
}
}
/// <summary>
/// Gets or sets the coefficient that is used to calculate the camera's width, height and depth.
/// </summary>
public float CameraScale
{
get { return cameraWidth; }
set
{
cameraWidth = value;
if (Projection == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, value / Zoom), new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * value / Zoom);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-value / Zoom / 2 + SceneCenterTranslation.X,
value / Zoom / 2 + SceneCenterTranslation.X,
-value * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
value * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
-value, value);
}
}
}
/// <summary>
/// Gets or sets the camera's zoom.
/// </summary>
public float Zoom
{
get { return zoom; }
set
{
zoom = value;
if (Projection == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, CameraScale / value), new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / value);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-CameraScale / value / 2 + SceneCenterTranslation.X,
CameraScale / value / 2 + SceneCenterTranslation.X,
-CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / value / 2 + SceneCenterTranslation.Y,
CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / value / 2 + SceneCenterTranslation.Y,
-CameraScale, CameraScale);
}
}
}
/// <summary>
/// Gets or sets the vector by that the 3D scene's center is translated.
/// </summary>
protected Vector2 SceneCenterTranslation { set; get; }
internal int Delta
{
get { return delta; }
set { delta = value; deltaVector = new Vector2(delta, 0); }
}
#endregion
#region Pages
//The pages
private List<PivotGameItem> Items { get; set; }
/// <summary>
/// Gets or sets the current page index. If the index changes, then the SelectionChanged event is fired.
/// </summary>
public int SelectedIndex
{
get { return selInd; }
set
{
int prev = selInd;
selInd = value;
if (!SelectedIndexSetFirstTime)
{
CallStack.Add(prev);
this[value].headerPosition = new Vector2(10, 40);
if (SelectionChanged != null && value != prev)
SelectionChanged(this, new SelectionChangedEventArgs(prev));
SwitchingTabsNow = true;
Delta = 480;
if ((prev > value && !(value == 0 && prev >= ItemsCount - 2)) || (prev < value && prev == 0 && value == ItemsCount - 1))
Delta = -480;
}
SelectedIndexSetFirstTime = false;
}
}
/// <summary>
/// The indexer that enables access to separate pivot pages.
/// </summary>
/// <param name="i">The index of page.</param>
/// <returns>The PivotGameItem object that perpesents the page.</returns>
public PivotGameItem this[int i]
{
get { return Items[i]; }
}
/// <summary>
/// Gets the amount of pages in pivot.
/// </summary>
public int ItemsCount
{
get { return Items.Count; }
}
/// <summary>
/// Indicates whether the pages are changing at the moment
/// </summary>
public bool ChangingPages
{
get { return Delta!=0;}
}
#endregion
#region Touches
/// <summary>
/// Gets or sets the current state of the touch panel.
/// It should be initialized before calling base.Update(gameTime).
/// </summary>
protected TouchCollection Touches { get; set; }
#endregion
#endregion
#region Constructors
/// <summary>
/// The constructor which initializes the GraphicsDeviceManager object.
/// </summary>
public PivotGame()
{
GraphicsDeviceManager = new GraphicsDeviceManager(this);
GraphicsDeviceManager.PreferredBackBufferWidth = 480;
GraphicsDeviceManager.PreferredBackBufferHeight = 800;
GraphicsDeviceManager.IsFullScreen = true;
FontLoader = new ResourceContentManager(this.Services, DCL.Phone.Xna.Fonts.ResourceManager);
}
#endregion
#region Pivot Methods
/// <summary>
/// Adds a new item to the pivot pages collection.
/// </summary>
/// <param name="pgi">The item to add.</param>
public void AddItem(PivotGameItem pgi)
{
Items.Add(pgi);
pgi.Parent = this;
}
public void RemoveItem(PivotGameItem pgi)
{
Items.Remove(pgi);
}
public void RemoveItemAt(int index)
{
Items.RemoveAt(index);
}
//Used for handling the "Back" button.
private int GetLastVisitedIndexFromCallStack()
{
if (CallStack.Count == 0) return -1;
else
{
int i = CallStack[CallStack.Count - 1];
CallStack.RemoveAt(CallStack.Count - 1);
return i;
}
}
#endregion
#region Standard Methods
/// <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()
{
Items = new List<PivotGameItem>();
AddItem(new PivotGameItem());
selInd = 0;
#region BasicEffect
BasicEffect = new BasicEffect(GraphicsDevice);
BasicEffect.LightingEnabled = true;
BasicEffect.PreferPerPixelLighting = true;
//BasicEffect.EnableDefaultLighting();
BasicEffect.VertexColorEnabled = false;
BasicEffect.AmbientLightColor = new Vector3(0.2f, 0.2f, 0.2f);
BasicEffect.SpecularColor = new Vector3(1, 1, 1);
BasicEffect.SpecularPower = 60;
// Set direction of light here, not position!
BasicEffect.DirectionalLight0.Direction = new Vector3(-1, -1, -1);
BasicEffect.DirectionalLight0.DiffuseColor = new Vector3(1, 1, 1);
BasicEffect.DirectionalLight0.SpecularColor = new Vector3(1, 1, 1);
BasicEffect.DirectionalLight0.Enabled = true;
BasicEffect.Alpha = 1;
Projection = ProjectionType.Perspective;
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, CameraScale / Zoom), new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / Zoom);
#endregion
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()
{
#region Default fonts
HeaderFont = FontLoader.Load<SpriteFont>("Segoe48Bold");
TitleFont = FontLoader.Load<SpriteFont>("Segoe16Bold");
ContentFont = FontLoader.Load<SpriteFont>("Segoe16");
#endregion
SpriteBatch = new SpriteBatch(GraphicsDevice);
#region Splash screen
if (SplashScreenImage != null)
{
SpriteBatch.Begin();
SpriteBatch.Draw(SplashScreenImage, new Vector2(0, 0), Color.White);
SpriteBatch.End();
GraphicsDevice.Present();
}
#endregion
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
#region BasicEffect
if (BasicEffect != null)
{
BasicEffect.Dispose();
BasicEffect = null;
}
#endregion
#region SpriteBatch
if (SpriteBatch != null)
{
SpriteBatch.Dispose();
SpriteBatch = null;
}
#endregion
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
#region "Back" button
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
int prev = GetLastVisitedIndexFromCallStack();
if (prev == -1)
this.Exit();
else
{
int temp = selInd;
selInd = prev; //To avoid adding the item to the call stack
this[selInd].headerPosition = new Vector2(10, 40);
if (SelectionChanged != null)
SelectionChanged(this, new SelectionChangedEventArgs(temp));
SwitchingTabsNow = true;
Delta = -480;
if ((prev > temp && !(temp == 0 && prev >= ItemsCount - 2)) || (prev < temp && prev == 0 && temp == ItemsCount - 1))
Delta = 480;
}
}
#endregion
#region Touches
if (Touches.Count == 0) Touches = TouchPanel.GetState();
if (Touches.Count == 1 && !SwitchingTabsNow)
{
#region Switching tabs
if (Touches[0].State == TouchLocationState.Pressed &&
Touches[0].Position.Y >= this[SelectedIndex].headerPosition.Y &&
Touches[0].Position.Y <= this[SelectedIndex].headerPosition.Y + HeaderFont.MeasureString(this[SelectedIndex].Header).Y)
{
int ind = SelectedIndex;
float temp1, temp2 = this[ind].headerPosition.X + HeaderFont.MeasureString(this[ind].Header).X + 10;
do
{
temp1 = temp2;
ind++;
if (ind == Items.Count) ind=0;
temp2 += HeaderFont.MeasureString(this[ind].Header).X + 10;
if (Touches[0].Position.X > temp1 && Touches[0].Position.X <= temp2)
{
SelectedIndex = ind;
break;
}
}while (temp1 < 480);
}
#endregion
#region Moving finger beyond the scene area
else if (Touches[0].State == TouchLocationState.Moved &&
!(Touches[0].Position.X - Delta > this[SelectedIndex].DrawingArea.X &&
Touches[0].Position.X - Delta < this[SelectedIndex].DrawingArea.X + this[SelectedIndex].DrawingArea.Width &&
//Touches[0].Position.Y > this[SelectedIndex].DrawingArea.Y &&
Touches[0].Position.Y < this[SelectedIndex].DrawingArea.Y + this[SelectedIndex].DrawingArea.Height))
{
TouchLocation prevTouch;
if (Touches[0].TryGetPreviousLocation(out prevTouch))
{
Delta += (int)(Touches[0].Position.X - prevTouch.Position.X);
this[SelectedIndex].headerPosition = new Vector2
(10 + HeaderFont.MeasureString(this[SelectedIndex].Header).X * Delta / 480, 40);
if (Projection == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X - (float)Delta / 60, SceneCenterTranslation.Y, CameraScale / Zoom), new Vector3(SceneCenterTranslation.X - (float)Delta / 60, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / Zoom);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-CameraScale / Zoom * (0.5f + (float)Delta / 480) + SceneCenterTranslation.X,
CameraScale / Zoom * (0.5f - (float)Delta / 480) + SceneCenterTranslation.X,
-CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
-CameraScale, CameraScale);
}
}
}
#endregion
#region Releasing finger - we may have to switch tabs
else if (Touches[0].State == TouchLocationState.Released)
{
if (Delta > 100)
{
Delta = 0;
SelectedIndex = (SelectedIndex == 0) ? (ItemsCount - 1) : (SelectedIndex - 1);
}
else if (Delta < -100)
{
Delta = 0;
SelectedIndex = (SelectedIndex == ItemsCount-1) ? (0) : (SelectedIndex + 1);
}
else
{
Delta = 0;
}
this[SelectedIndex].headerPosition = new Vector2(10, 40);
if (Projection == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, CameraScale / Zoom), new Vector3(SceneCenterTranslation.X, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / Zoom);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-CameraScale / Zoom / 2 + SceneCenterTranslation.X,
CameraScale / Zoom / 2 + SceneCenterTranslation.X,
-CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
-CameraScale, CameraScale);
}
}
#endregion
}
#endregion
#region Switching tabs animation
if (SwitchingTabsNow)
{
Delta += (Delta<0)?80:-80;
if (Delta == 0) SwitchingTabsNow = false;
if (Projection == ProjectionType.Perspective)
{
BasicEffect.View = Matrix.CreateLookAt(new Vector3(SceneCenterTranslation.X - (float)Delta / 60, SceneCenterTranslation.Y, CameraScale / Zoom), new Vector3(SceneCenterTranslation.X - (float)Delta / 60, SceneCenterTranslation.Y, 0), Vector3.Up);
BasicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), (float)GraphicsDeviceManager.PreferredBackBufferWidth / GraphicsDeviceManager.PreferredBackBufferHeight, 0.1f, 2 * CameraScale / Zoom);
}
else
{
BasicEffect.View = Matrix.Identity;
BasicEffect.Projection = Matrix.CreateOrthographicOffCenter(-CameraScale / Zoom * (0.5f + (float)Delta / 480) + SceneCenterTranslation.X,
CameraScale / Zoom * (0.5f - (float)Delta / 480) + SceneCenterTranslation.X,
-CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
CameraScale * GraphicsDeviceManager.PreferredBackBufferHeight / GraphicsDeviceManager.PreferredBackBufferWidth / Zoom / 2 + SceneCenterTranslation.Y,
-CameraScale, CameraScale);
}
}
#endregion
this[SelectedIndex].Update();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
Items[SelectedIndex].Draw();
base.Draw(gameTime);
}
#endregion
#region Other methods
/// <summary>
/// Draws a string (considers the possible page's displacement).
/// </summary>
/// <param name="font">Font of the text.</param>
/// <param name="text">The text to draw</param>
/// <param name="position">The position of the left upper corner of the text.</param>
/// <param name="color">Color of the text.</param>
public void DrawString(SpriteFont font, string text, Vector2 position, Color color)
{
SpriteBatch.DrawString(font, text, position + deltaVector, color);
}
/// <summary>
/// Renders a texture (considers the possible page's displacement).
/// </summary>
/// <param name="sprite">The texture to draw.</param>
/// <param name="position">The position of the left upper corner of the texture.</param>
/// <param name="color">Color of the texture.</param>
public void DrawSprite(Texture2D sprite, Vector2 position, Color color)
{
SpriteBatch.Draw(sprite, position + deltaVector, color);
}
#endregion
}
/// <summary>
/// Arguments for the SelectionChanged event that contain the previous selected page index.
/// </summary>
public class SelectionChangedEventArgs : EventArgs
{
/// <summary>
/// The index of the page that was current before the selection changed.
/// </summary>
public int PreviousIndex { get; set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="previousIndex">The index of the page that was current before the selection changed.</param>
public SelectionChangedEventArgs(int previousIndex)
{
PreviousIndex = previousIndex;
}
}
/// <summary>
/// The projection type for BasicEffect
/// </summary>
public enum ProjectionType
{
/// <summary>
/// Perspective projection.
/// </summary>
Perspective,
/// <summary>
/// Orthographic projection.
/// </summary>
Orthographic
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.