blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
bb7d2d40894f1394c9d46d421f2ae9e152569bda
|
C#
|
iArmanKarimi/TvSeriesLogs
|
/TvSeriesLogsDb/SeriesDB.cs
| 2.875
| 3
|
using LiteDB;
using TvSeriesLogsDb.Helper;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
namespace TvSeriesLogsDb
{
public class SeriesDb : IDisposable
{
private LiteDatabase db;
private ILiteCollection<Series> collection;
private const string FILE = "series.db";
private const string APP_NAME = "TvSeriesLogs";
private const string COLL_SERIES = "series";
private string PATH = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
public SeriesDb()
{
if (!Debugger.IsAttached)
Directory.CreateDirectory(Path.Combine(PATH, APP_NAME));
db = new LiteDatabase(Debugger.IsAttached ? FILE : Path.Combine(PATH, APP_NAME, FILE));
collection = db.GetCollection<Series>(COLL_SERIES);
collection.EnsureIndex(c => c.Name);
}
public Option<Series> FindById(int id)
{
var series = collection.FindById(id);
return new Option<Series>
{
Value = series,
IsNull = series == null,
};
}
public Option<Series> FindOne(Expression<Func<Series, bool>> func)
{
var series = collection.FindOne(func);
return new Option<Series>
{
Value = series,
IsNull = series == null,
};
}
/// <returns>Number of items that were removed</returns>
public bool Remove(int id) => collection.Delete(id);
public int RemoveAll() => collection.DeleteAll();
public bool ExistsById(int id) => collection.Exists(s => s.Id == id);
public bool Exists(Expression<Func<Series, bool>> func) => collection.Exists(func);
/// <returns>Id of the added series</returns>
public int Add(Series series) => collection.Insert(series);
/// <summary>updates considering the id</summary>
/// <returns>false if document wasn't found in collection</returns>
public bool Update(Series series) => collection.Update(series);
/// <summary>updates considering the id</summary>
/// <returns>false if document wasn't found in collection</returns>
public bool Update(int id, Series series) => collection.Update(id, series);
public IEnumerable<Series> GetAll() => collection.FindAll();
public IEnumerable<Series> Find(Expression<Func<Series, bool>> exp) => collection.Find(exp);
public IEnumerable<Series> Filter(string name, ushort limit, bool caseSensitive, bool orderByIndwx = true)
{
var items = GetAll();
var filtered = items.Where(FilterPredicate);
if (orderByIndwx)
filtered = filtered.OrderBy(i => i.Name.IndexOf(name));
bool FilterPredicate(Series series) =>
caseSensitive
? series.Name.Contains(name)
: series.Name.ToLower().Contains(name.ToLower());
return filtered.Take(limit);
}
public void Dispose() => db.Dispose();
}
}
|
dee381b1b395e8d561418ec1f8bb637d647ed9a9
|
C#
|
hong-rong/MyRepository
|
/MyLibrary/LeetCode/CodingSummary.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lc
{
public class CodingSummary
{
public void Lc19()
{
int n = 5;
while (--n >= 0)
{
//execute 5 times
//start point 4, end point 0, inclusive, so 4-0+1=5
}
}
}
}
|
953781cbf795546ca267c936c79c92c4f2e0b89b
|
C#
|
shendongnian/download4
|
/first_version_download2/229365-18003549-44690315-6.cs
| 3.34375
| 3
|
class CompareFooToBar : IEqualityComparer<Foo>
{
Bar bar;
public CompareFooToBar(Bar bar) { this.bar = bar;}
public bool Equals(Foo x, Foo y)
{
// hack - ignore y completely, assuming Contains pass element as x
return x.Bar == bar;
}
public int GetHashCode(Foo x)
{
return 0;
}
}
foos.Contains(null, new CompareFooToBar(bar))
|
ba14e307a70f12166dd8d7c93d07829e79f21c31
|
C#
|
todor-enikov/TelerikAcademy
|
/Unit-testing with C# - 2016/03. Mocking and JustMock/Cars/Cars.Tests.JustMock/CarsRepositoryTests.cs
| 2.734375
| 3
|
using System;
using NUnit.Framework;
using Cars.Models;
using Cars.Data;
using System.Collections.Generic;
using Moq;
using Cars.Tests.JustMock.Mocks;
using Cars.Contracts;
using System.Linq;
namespace Cars.Tests.JustMock
{
[TestFixture]
public class CarsRepositoryTests
{
[Test]
public void Add_ShouldAddCarToCarRepository()
{
// Arrange
var car = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var db = new Database();
db.Cars = new List<Car>();
var count = db.Cars.Count;
var carsRepository = new CarsRepository(db);
// Act
carsRepository.Add(car);
// Assert
Assert.AreEqual(1, db.Cars.Count);
}
[Test]
public void Add_ShouldThrowArgumentException_IfCarIsNull()
{
// Arrange
Car car = null;
var db = new Database();
db.Cars = new List<Car>();
var count = db.Cars.Count;
var carsRepository = new CarsRepository(db);
// Act and Assert
Assert.Throws<ArgumentException>(() => carsRepository.Add(car), "Null car cannot be added");
}
[Test]
public void Remove_ShouldremoveCarFromCarsRepository_WhenIsCalled()
{
// Arrange
var car = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var db = new Database();
db.Cars = new List<Car>();
var carsRepository = new CarsRepository(db);
// Act
carsRepository.Add(car);
carsRepository.Remove(car);
// Assert
Assert.AreEqual(0, db.Cars.Count);
}
[Test]
public void Remove_ShouldThrowArgumentException_IfCarIsNull()
{
// Arrange
Car car = null;
var carsRepository = new CarsRepository();
// Act and Assert
var ex = Assert.Throws<ArgumentException>(() => carsRepository.Remove(car));
Assert.IsTrue(ex.Message.Contains("Null car cannot be removed"));
}
[Test]
public void GetById_ShouldFindCarById()
{
// Arrange
var car = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(new List<Car>() { });
var fakeDB = mock.Object;
fakeDB.Cars.Add(car);
var carsRepository = new CarsRepository(fakeDB);
// Act
var result = carsRepository.GetById(1);
// Assert
mock.Verify(m => m.Cars, Times.Exactly(2));
}
[Test]
public void GetById_ShouldThrowException_IfThereIsNoCarWithThatId()
{
// Arrange
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(new List<Car>() { }); ;
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act and Assert
var ex = Assert.Throws<ArgumentException>(() => carsRepository.GetById(7));
Assert.IsTrue(ex.Message.Contains("Car with such Id could not be found"));
}
[Test]
public void All_ShouldReturnAllOfTheCarsInTheDB()
{
// Arrange
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var secondCar = new Car { Id = 2, Make = "Moskvich", Model = "12-tak", Year = 1980 };
var thirdCar = new Car { Id = 3, Make = "Lada", Model = "7-marka", Year = 1991 };
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(new List<Car>() { });
var fakeDB = mock.Object;
fakeDB.Cars.Add(firstCar);
fakeDB.Cars.Add(secondCar);
fakeDB.Cars.Add(thirdCar);
var carsRepository = new CarsRepository(fakeDB);
// Act
var result = carsRepository.All();
//Assert
Assert.AreEqual(3, result.Count);
}
[Test]
public void SortedByMake_ShouldReturnSortedListOfCarsByMake()
{
// Arrange
var datebase = new List<Car>();
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var secondCar = new Car { Id = 2, Make = "Moskvich", Model = "12-tak", Year = 1980 };
var thirdCar = new Car { Id = 3, Make = "Lada", Model = "7-marka", Year = 1991 };
datebase.Add(firstCar);
datebase.Add(secondCar);
datebase.Add(thirdCar);
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(datebase);
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act
var sortedListByMake = carsRepository.SortedByMake();
var expected = "Audi";
// Assert
Assert.AreEqual(expected, (sortedListByMake.First()).Make);
}
[Test]
public void SortedByYear_ShouldReturnSortedListOfCarsByYear()
{
// Arrange
var datebase = new List<Car>();
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var secondCar = new Car { Id = 2, Make = "Moskvich", Model = "12-tak", Year = 1980 };
var thirdCar = new Car { Id = 3, Make = "Lada", Model = "7-marka", Year = 1991 };
datebase.Add(firstCar);
datebase.Add(secondCar);
datebase.Add(thirdCar);
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(datebase);
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act
var sortedListByYear = carsRepository.SortedByYear();
var expected = 2005;
// Assert
Assert.AreEqual(expected, (sortedListByYear.First()).Year);
}
[Test]
public void Search_ShouldReturnCarByGivenString()
{
// Arrange
var datebase = new List<Car>();
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
datebase.Add(firstCar);
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(datebase);
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act
var result = carsRepository.Search("Audi");
// Assert
mock.Verify(m => m.Cars, Times.Exactly(1));
}
[Test]
public void Search_ShouldReturnListOfAllCars_IfStringIsNullOrEmpty()
{
// Arrange
var datebase = new List<Car>();
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
var secondCar = new Car { Id = 2, Make = "Moskvich", Model = "12-tak", Year = 1980 };
datebase.Add(firstCar);
datebase.Add(secondCar);
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(datebase);
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act
var result = carsRepository.Search("");
// Assert
mock.Verify(m => m.Cars, Times.Exactly(1));
}
[Test]
public void Testing_GetterOnClassCarsRepository()
{
// Arrange
var datebase = new List<Car>();
var firstCar = new Car { Id = 1, Make = "Audi", Model = "A5", Year = 2005 };
datebase.Add(firstCar);
var mock = new Mock<IDatabase>();
mock.Setup(m => m.Cars).Returns(datebase);
var fakeDB = mock.Object;
var carsRepository = new CarsRepository(fakeDB);
// Act
var totalCars = carsRepository.TotalCars;
var expected = 1;
// Assert
Assert.AreEqual(expected, totalCars);
}
}
}
|
20bbd20cb9d089abddf6462526d3df35e76d2835
|
C#
|
Ironlung13/LabWork_Exceptions
|
/MatrixIncompatibleSizingException.cs
| 2.921875
| 3
|
using System;
namespace LabWork_Exceptions
{
class MatrixIncompatibleSizingException : ApplicationException
{
public (int x, int y) Size1 { get; }
public (int x, int y) Size2 { get; }
public MatrixIncompatibleSizingException(Matrix a, Matrix b)
{
Size1 = a.Size;
Size2 = b.Size;
}
public MatrixIncompatibleSizingException(Matrix a, Matrix b, string message) : base(message)
{
Size1 = a.Size;
Size2 = b.Size;
}
public MatrixIncompatibleSizingException(Matrix a, Matrix b, string message, Exception inner) : base(message, inner)
{
Size1 = a.Size;
Size2 = b.Size;
}
}
}
|
c8c41080f3a1bf68ceb399932861bfa08d7a9770
|
C#
|
RyanChang0369/tMLH2
|
/tMLH2/FileMethods.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tMLH2
{
static class FileMethods
{
/// <summary>
/// Reads all lines of the file without causing a lock.
/// </summary>
/// <exception cref="FileNotFoundException"></exception>
/// <param name="fileName">The file to read.</param>
/// <returns>The contents of the file.</returns>
public static string SilentlyReadAllLines(string fileName)
{
using (FileStream fs = File.Open(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
return sr.ReadToEnd();
}
}
}
}
}
|
f3fc6917590c47574c1cdac263f6edf7200f5179
|
C#
|
planettelex/Bloom
|
/Shared/Bloom.Domain/Models/PlaylistActivity.cs
| 2.859375
| 3
|
using System;
using System.Data.Linq.Mapping;
namespace Bloom.Domain.Models
{
/// <summary>
/// Represents an association between a playlist and an activity.
/// </summary>
[Table(Name = "playlist_activity")]
public class PlaylistActivity
{
/// <summary>
/// Creates a new playlist activity instance.
/// </summary>
/// <param name="playlist">The playlist.</param>
/// <param name="activity">The activity.</param>
public static PlaylistActivity Create(Playlist playlist, Activity activity)
{
return new PlaylistActivity
{
PlaylistId = playlist.Id,
ActivityId = activity.Id
};
}
/// <summary>
/// Gets or sets the playlist identifier.
/// </summary>
[Column(Name = "playlist_id", IsPrimaryKey = true)]
public Guid PlaylistId { get; set; }
/// <summary>
/// Gets or sets the activity identifier.
/// </summary>
[Column(Name = "activity_id", IsPrimaryKey = true)]
public Guid ActivityId { get; set; }
}
}
|
1161fbb02c75847111917f95b02e0947b314e40f
|
C#
|
ivanalubar/MemoryGame
|
/MemoryGame/MemoryGame/Form3.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MemoryGame.Properties;
namespace MemoryGame
{
public partial class Form3 : Form
{
public bool rezultat;
public bool _allowClick = true;
private PictureBox _firstGuess;
private readonly Random _random = new Random();
private readonly Timer _clickTimer = new Timer();
int ticks = 50;
readonly Timer timer = new Timer { Interval = 1000 };
public Form3()
{
InitializeComponent();
SetRandomImages();
HideImages();
StartGameTimer();
_clickTimer.Interval = 1000;
_clickTimer.Tick += _clickTimer_Tick;
}
private PictureBox[] PictureBoxes
{
get { return Controls.OfType<PictureBox>().ToArray(); }
}
private static IEnumerable<Image> Images
{
get
{
return new Image[]
{
Resources.img1,
Resources.img2,
Resources.img3,
Resources.img4,
Resources.img5,
Resources.img6,
Resources.img7,
Resources.img8
};
}
}
private void StartGameTimer()
{
timer.Start();
timer.Tick += delegate
{
ticks--;
if (ticks == -1)
{
timer.Stop();
MessageBox.Show("Times up.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
rezultat = false;
ResetImages();
timer.Stop();
this.Close();
}
var time = TimeSpan.FromSeconds(ticks);
label1.Text = "00:" + time.ToString("ss");
};
}
private void ResetImages()
{
foreach (var pic in PictureBoxes)
{
pic.Tag = null;
pic.Visible = true;
}
HideImages();
SetRandomImages();
ticks = 50;
timer.Start();
}
private void HideImages()
{
foreach (var pic in PictureBoxes)
{
pic.Image = Resources.img0;
}
}
private PictureBox GetFreeSlot()
{
int br;
do
{
br = _random.Next(0, PictureBoxes.Count());
}
while (PictureBoxes[br].Tag != null);
return PictureBoxes[br];
}
private void SetRandomImages()
{
foreach (var Image in Images)
{
GetFreeSlot().Tag = Image;
GetFreeSlot().Tag = Image;
}
}
private void _clickTimer_Tick(object sender, EventArgs e)
{
HideImages();
_allowClick = true;
_clickTimer.Stop();
}
private void pictureBox16_Click_1(object sender, EventArgs e)
{
if (!_allowClick) return;
var pic = (PictureBox)sender;
if (_firstGuess == null)
{
_firstGuess = pic;
pic.Image = (Image)pic.Tag;
return;
}
pic.Image = (Image)pic.Tag;
if (pic.Image == _firstGuess.Image && pic != _firstGuess)
{
pic.Visible = _firstGuess.Visible = false;
{
_firstGuess = pic;
}
HideImages();
}
else
{
_allowClick = false;
_clickTimer.Start();
}
_firstGuess = null;
if (PictureBoxes.Any(p => p.Visible))
return;
MessageBox.Show("You won!!!!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
rezultat = true;
timer.Stop();
this.Close();
}
private void Form3_Load(object sender, EventArgs e)
{
BackColor = Color.White;
}
}
}
|
4ae5d1078d9fb5725ca1c029b31a50fa92a9f50d
|
C#
|
m-sadegh-sh/FaraMedia
|
/src/Libraries/FaraMedia.Services/Querying/Billing/OrderQuery.fixed.cs
| 2.53125
| 3
|
namespace FaraMedia.Services.Querying.Billing {
using System;
using System.Collections.Generic;
using System.Linq;
using FaraMedia.Core;
using FaraMedia.Core.Domain.Billing;
using FaraMedia.Core.Domain.Security;
using FaraMedia.Core.Operators;
public sealed class OrderQuery : EntityQueryBase<Order, OrderQuery> {
public OrderQuery(IEnumerable<Order> entities) : base(entities) {}
public OrderQuery(IQueryable<Order> entities) : base(entities) {}
public OrderQuery WithGuid(Guid? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
GuidOperator @operator = GuidOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case GuidOperator.Equal:
Entities = Entities.Where(o => o.Guid == value);
return this;
case GuidOperator.NotEqual:
Entities = Entities.Where(o => o.Guid != value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithPlaceDateUtc(DateTime? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
IntegralOperator @operator = IntegralOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case IntegralOperator.Equal:
Entities = Entities.Where(o => o.PlaceDateUtc == value);
return this;
case IntegralOperator.NotEqual:
Entities = Entities.Where(o => o.PlaceDateUtc != value);
return this;
case IntegralOperator.GreaterThanOrEqual:
Entities = Entities.Where(o => o.PlaceDateUtc >= value);
return this;
case IntegralOperator.GreaterThan:
Entities = Entities.Where(o => o.PlaceDateUtc > value);
return this;
case IntegralOperator.LessThanOrEqual:
Entities = Entities.Where(o => o.PlaceDateUtc <= value);
return this;
case IntegralOperator.LessThan:
Entities = Entities.Where(o => o.PlaceDateUtc < value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithPlaceDateUtcBetween(DateTime? from = null,
ArgumentEvaluationMode fromMode = ArgumentEvaluationMode.IgnoreNeutral,
DateTime? to = null,
ArgumentEvaluationMode toMode = ArgumentEvaluationMode.IgnoreNeutral,
RangeOperator @operator = RangeOperator.Inside) {
switch (@operator) {
case RangeOperator.Inside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.PlaceDateUtc >= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.PlaceDateUtc == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.PlaceDateUtc <= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.PlaceDateUtc == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
case RangeOperator.Outside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.PlaceDateUtc <= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.PlaceDateUtc == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.PlaceDateUtc >= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.PlaceDateUtc == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
default:
throw new NotSupportedEnumException(@operator);
}
return this;
}
public OrderQuery WithBuyer(User value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
EntityOperator @operator = EntityOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case EntityOperator.Equal:
Entities = Entities.Where(o => o.Buyer == value);
return this;
case EntityOperator.NotEqual:
Entities = Entities.Where(o => o.Buyer != value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithBuyerId(long? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
IntegralOperator @operator = IntegralOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case IntegralOperator.Equal:
Entities = Entities.Where(o => o.Buyer.Id == value);
return this;
case IntegralOperator.NotEqual:
Entities = Entities.Where(o => o.Buyer.Id != value);
return this;
case IntegralOperator.GreaterThanOrEqual:
Entities = Entities.Where(o => o.Buyer.Id >= value);
return this;
case IntegralOperator.GreaterThan:
Entities = Entities.Where(o => o.Buyer.Id > value);
return this;
case IntegralOperator.LessThanOrEqual:
Entities = Entities.Where(o => o.Buyer.Id <= value);
return this;
case IntegralOperator.LessThan:
Entities = Entities.Where(o => o.Buyer.Id < value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithBuyerIdBetween(long? from = null,
ArgumentEvaluationMode fromMode = ArgumentEvaluationMode.IgnoreNeutral,
long? to = null,
ArgumentEvaluationMode toMode = ArgumentEvaluationMode.IgnoreNeutral,
RangeOperator @operator = RangeOperator.Inside) {
switch (@operator) {
case RangeOperator.Inside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.Buyer.Id >= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Buyer.Id == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.Buyer.Id <= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Buyer.Id == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
case RangeOperator.Outside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.Buyer.Id <= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Buyer.Id == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.Buyer.Id >= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Buyer.Id == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
default:
throw new NotSupportedEnumException(@operator);
}
return this;
}
public OrderQuery WithBuyerIp(string value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
StringOperator @operator = StringOperator.Exact,
StringDirection direction = StringDirection.SourceToExpected) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case StringOperator.Exact:
switch (direction) {
case StringDirection.SourceToExpected:
case StringDirection.ExpectedToSource:
case StringDirection.TwoWay:
Entities = Entities.Where(o => o.BuyerIp == value);
return this;
default:
throw new NotSupportedEnumException(direction);
}
case StringOperator.Contains:
switch (direction) {
case StringDirection.SourceToExpected:
Entities = Entities.Where(o => o.BuyerIp.Contains(value));
return this;
case StringDirection.ExpectedToSource:
Entities = Entities.Where(o => value.Contains(o.BuyerIp));
return this;
case StringDirection.TwoWay:
Entities = Entities.Where(o => o.BuyerIp.Contains(value) || value.Contains(o.BuyerIp));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case StringOperator.StartsWith:
switch (direction) {
case StringDirection.SourceToExpected:
Entities = Entities.Where(o => o.BuyerIp.StartsWith(value));
return this;
case StringDirection.ExpectedToSource:
Entities = Entities.Where(o => value.StartsWith(o.BuyerIp));
return this;
case StringDirection.TwoWay:
Entities = Entities.Where(o => o.BuyerIp.StartsWith(value) || value.StartsWith(o.BuyerIp));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case StringOperator.EndsWith:
switch (direction) {
case StringDirection.SourceToExpected:
Entities = Entities.Where(o => o.BuyerIp.EndsWith(value));
return this;
case StringDirection.ExpectedToSource:
Entities = Entities.Where(o => value.EndsWith(o.BuyerIp));
return this;
case StringDirection.TwoWay:
Entities = Entities.Where(o => o.BuyerIp.EndsWith(value) || value.EndsWith(o.BuyerIp));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithStatus(OrderStatus value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
EntityOperator @operator = EntityOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case EntityOperator.Equal:
Entities = Entities.Where(o => o.Status == value);
return this;
case EntityOperator.NotEqual:
Entities = Entities.Where(o => o.Status != value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithStatusId(long? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
IntegralOperator @operator = IntegralOperator.Equal) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case IntegralOperator.Equal:
Entities = Entities.Where(o => o.Status.Id == value);
return this;
case IntegralOperator.NotEqual:
Entities = Entities.Where(o => o.Status.Id != value);
return this;
case IntegralOperator.GreaterThanOrEqual:
Entities = Entities.Where(o => o.Status.Id >= value);
return this;
case IntegralOperator.GreaterThan:
Entities = Entities.Where(o => o.Status.Id > value);
return this;
case IntegralOperator.LessThanOrEqual:
Entities = Entities.Where(o => o.Status.Id <= value);
return this;
case IntegralOperator.LessThan:
Entities = Entities.Where(o => o.Status.Id < value);
return this;
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithStatusIdBetween(long? from = null,
ArgumentEvaluationMode fromMode = ArgumentEvaluationMode.IgnoreNeutral,
long? to = null,
ArgumentEvaluationMode toMode = ArgumentEvaluationMode.IgnoreNeutral,
RangeOperator @operator = RangeOperator.Inside) {
switch (@operator) {
case RangeOperator.Inside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.Status.Id >= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Status.Id == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.Status.Id <= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Status.Id == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
case RangeOperator.Outside:
switch (fromMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(from))
Entities = Entities.Where(o => o.Status.Id <= from);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Status.Id == from);
break;
default:
throw new NotSupportedEnumException(fromMode);
}
switch (toMode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (!Neutrals.Is(to))
Entities = Entities.Where(o => o.Status.Id >= to);
break;
case ArgumentEvaluationMode.Explicit:
Entities = Entities.Where(o => o.Status.Id == to);
break;
default:
throw new NotSupportedEnumException(toMode);
}
break;
default:
throw new NotSupportedEnumException(@operator);
}
return this;
}
public OrderQuery WithLine(OrderLine value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Lines.Any(ol => ol == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Lines.All(ol => ol == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Lines.Any(ol => ol != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Lines.All(ol => ol != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithLineId(long? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Lines.Any(ol => ol.Id == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Lines.All(ol => ol.Id == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Lines.Any(ol => ol.Id != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Lines.All(ol => ol.Id != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithNote(OrderNote value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Notes.Any(on => on == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Notes.All(on => on == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Notes.Any(on => on != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Notes.All(on => on != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithNoteId(long? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Notes.Any(on => on.Id == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Notes.All(on => on.Id == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Notes.Any(on => on.Id != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Notes.All(on => on.Id != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithRequest(TransactionRequest value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Requests.Any(tr => tr == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Requests.All(tr => tr == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Requests.Any(tr => tr != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Requests.All(tr => tr != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
public OrderQuery WithRequestId(long? value = null,
ArgumentEvaluationMode mode = ArgumentEvaluationMode.IgnoreNeutral,
CollectionOperator @operator = CollectionOperator.Equal,
CollectionDirection direction = CollectionDirection.Any) {
switch (mode) {
case ArgumentEvaluationMode.IgnoreNeutral:
if (Neutrals.Is(value))
return this;
break;
case ArgumentEvaluationMode.Explicit:
break;
default:
throw new NotSupportedEnumException(mode);
}
switch (@operator) {
case CollectionOperator.Equal:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Requests.Any(tr => tr.Id == value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Requests.All(tr => tr.Id == value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
case CollectionOperator.NotEqual:
switch (direction) {
case CollectionDirection.Any:
Entities = Entities.Where(o => o.Requests.Any(tr => tr.Id != value));
return this;
case CollectionDirection.All:
Entities = Entities.Where(o => o.Requests.All(tr => tr.Id != value));
return this;
default:
throw new NotSupportedEnumException(direction);
}
default:
throw new NotSupportedEnumException(@operator);
}
}
}
}
|
5f1bb9337111e81ee0f47e4339c0b15a2d63ba1b
|
C#
|
dev-innovacion/AssetsApp
|
/assetsapp/RivkaBase/Form/Field/CustomFieldBinder.cs
| 2.546875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Rivka.Form.Field
{
public class CustomFieldBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string type = (request.Form.Get("type").Split(',')).First();
var model = Activator.CreateInstance(Type.GetType("Rivka.Form.Field." + type));
var props = model.GetType().GetProperties();
foreach (var property in props)
{
//TODO:Por el momento Ignora el el bindeo de la lista
if (property.GetValue(model, null) is IList) {
continue;
}
if (property.Name == "listId" && (type == "MultiSelectField" || type == "DropDownField" || type == "RadioField"))
{
object readvalue = request.Form.Get("CustomList");
property.SetValue(model, Convert.ChangeType(readvalue, property.PropertyType), null);
continue;
}
if (property.PropertyType == typeof(bool))
{
var readvalue = request.Form.Get(property.Name);
bool value = readvalue.Contains("true");
property.SetValue(model, Convert.ChangeType(value, property.PropertyType), null);
continue;
}
else
{
object readvalue = request.Form.Get(property.Name);
property.SetValue(model, Convert.ChangeType(readvalue, property.PropertyType), null);
}
}
return model;
}
}
}
|
81a1d490be4ae51d45285be6bc47b23fec4896cc
|
C#
|
MatthewWessley/NightmareOfKansasCityChateau
|
/ChateauLibrary/Players.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChateauLibrary
{
public class Players : Character
{
public SelectPlayer PlayerChoice { get; set; }
public Weapons EquippedWeapon { get; set; }
public Players(string name, int life, int maxLife, int block, int hitBonus, Weapons equippedWeapon, SelectPlayer playerChoice)
: base(name, life, maxLife, block, hitBonus)
{
EquippedWeapon = equippedWeapon;
switch (PlayerChoice)
{
case SelectPlayer.Attacker:
MaxLife += 10;
break;
case SelectPlayer.Defender:
Block += 10;
break;
case SelectPlayer.Analytic:
HitBonus += 10;
break;
default:
break;
}
}
public override string ToString()
{
return string.Format($"****{Name}****\nLife: {Life} of {MaxLife}\nHit Bonus: {CalcHitBonus()}\nBlock: {Block}\nPlayer Chosen: {PlayerChoice}");
}
public override int CalcHitBonus()
{
return HitBonus;
}
public override int CalcDamage()
{
return new Random().Next(EquippedWeapon.MinDamage, EquippedWeapon.MaxDamage + 1);
}
}
}
|
4386854259c0b08ca3a89b6d394f0835dc795227
|
C#
|
rhysgale/2D-Platformer-Game
|
/CastleRunnerGame/PhysicsEngine/PhysicsEngine/GameDrawing/MapObject.cs
| 2.734375
| 3
|
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using PhysicsEngine.Physics.Shapes;
namespace PhysicsEngine.GameDrawing
{
//Class for combining the textures with physics objects.
internal class MapObject
{
internal Body _BoundingBox { get; set; }
internal List<Rectangle> _DrawRectList { get; set; } //Mainly for floor.
internal TextureType _Type { get; set; }
internal bool _ObjectTouched { get; set; } //used for objects that can be collected. Need to be removed from the game.
internal bool _HitEvent { get; set; } //Whether the map object can be picked up or not
internal MapObject(TextureType type, Body boundingBox)
{
_DrawRectList = new List<Rectangle>();
_Type = type;
_BoundingBox = boundingBox;
switch (boundingBox._Shape)
{
case Polygon poly:
if (poly._Vertices.Count == 4)
{
if (_Type == TextureType.Floor)
{
var numTiles = (int) (poly._Vertices[1].X - poly._Vertices[0].X) / 50;
var rectanglePosition = new Point((int) poly._Vertices[0].X, (int) poly._Vertices[0].Y);
for (; numTiles > 0; numTiles--)
{
_DrawRectList.Add(new Rectangle(rectanglePosition, new Point(50, 50)));
rectanglePosition.X += 50;
}
}
else
{
var sizeX = (int)(poly._Vertices[1].X - poly._Vertices[0].X);
var sizeY = (int)(poly._Vertices[3].Y - poly._Vertices[0].Y);
var rectanglePosition = new Point((int)poly._Vertices[0].X, (int)poly._Vertices[0].Y);
_DrawRectList.Add(new Rectangle(rectanglePosition, new Point(sizeX, sizeY)));
}
}
else //Different kinda polygon
{
//TODO: Handle different kind of polygon
}
break;
case Circle circ:
int size = circ._Radius * 2;
Point pos = new Point((int)circ._Centre.X - circ._Radius, (int)circ._Centre.Y - circ._Radius);
_DrawRectList.Add(new Rectangle(pos, new Point(size)));
break;
}
}
internal void UpdatePos(Vector2 pos)
{
for (int i = 0; i < _DrawRectList.Count; i++)
{
_DrawRectList[i] = new Rectangle((int)(_DrawRectList[i].X + pos.X), (int)(_DrawRectList[i].Y + pos.Y),
_DrawRectList[i].Width, _DrawRectList[i].Height);
}
_BoundingBox._Shape.TransformShape(pos);
}
internal void DrawMapObject()
{
//Where we draw the object to the screen.
if (DungeonEscape._ShowBoundingBoxes == false)
{
foreach (var rectangle in _DrawRectList)
{
DungeonEscape._Renderer.Draw(DungeonEscape._Textures.GetTexture(_Type), rectangle, Color.White);
}
}
else
{
_BoundingBox._Shape.DebugDraw();
}
}
}
}
|
fcaefb117c929a1061cf0d99730623b84102a432
|
C#
|
HalfSteps/KreditRechner-LAP
|
/[DB-AG] Online_Kredit.BusinessLogic/KreditVerwaltung.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using _DB_AG__Online_Kredit.BusinessLogic;
using System.Threading;
namespace _DB_AG__Online_Kredit.BusinessLogic
{
public class KreditVerwaltung
{
/// <summary>
/// Erzeugt einen "leeren" dummy Kunden
/// zu dem in Folge alle Konsumkredit Daten
/// verknüpft werden können.
/// </summary>
/// <returns>einen leeren Kunden wenn erfolgreich, ansonsten null</returns>
public static Kunde ErzeugeKunde()
{
Debug.WriteLine("KreditVerwaltung: ErzeugeKunde");
Debug.Indent();
Kunde newKunde = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
newKunde = new BusinessLogic.Kunde()
{
Vorname = "anonym",
Nachname = "anonym",
Geschlecht = "w"
};
context.AlleKunden.Add(newKunde);
Debug.WriteLine("ErzeugeKunde: DBContextSave");
int anzahlZeilenBetroffen = context.SaveChanges();
Debug.WriteLine($"{anzahlZeilenBetroffen} Kunden angelegt!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in ErzeugeKunde");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return newKunde;
}
public static bool KreditSpeichern(double kreditBetrag, short laufzeit, int idKunde)
{
Debug.WriteLine("KreditVerwaltung: KreditSpeichern");
Debug.Indent();
bool erfolgreich = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde != null)
{
Debug.WriteLine("KreditSpeichern: Create KreditWunsch");
KreditWunsch kreditWunsch = context.AlleKreditWünsche.FirstOrDefault(x => x.ID == idKunde);
if (kreditWunsch == null)
{
/// lege einen neuen an
kreditWunsch = new KreditWunsch();
context.AlleKreditWünsche.Add(kreditWunsch);
}
kreditWunsch.Betrag = (decimal)kreditBetrag;
kreditWunsch.Laufzeit = laufzeit;
kreditWunsch.ID = idKunde;
}
Debug.WriteLine("KreditSpeichern: DBContextSave");
int anzahlZeilenBetroffen = context.SaveChanges();
Debug.WriteLine("KreditSpeichern: BoolchangeErfolgreich");
erfolgreich = anzahlZeilenBetroffen >= 1;
Debug.WriteLine($"{anzahlZeilenBetroffen} Kredit gespeichert!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KreditSpeichern");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich;
}
public static bool ArbeitgeberSpeichern(string firmenName, int idBeschäftigungsArt, int idBranche, string beschäftigtSeit, int idKunde)
{
Debug.WriteLine("KreditVerwaltung: ArbeitgeberSpeichern");
Debug.Indent();
bool erfolgreich = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde.Arbeitgeber != null)
{
aktKunde.Arbeitgeber.BeschaeftigtSeit = DateTime.Parse(beschäftigtSeit);
aktKunde.Arbeitgeber.FKBranche = idBranche;
aktKunde.Arbeitgeber.FKBeschaeftigungsArt = idBeschäftigungsArt;
aktKunde.Arbeitgeber.Firma = firmenName;
Debug.WriteLine("ArbeitgeberSpeichern: OverwriteDBContextSave");
context.SaveChanges();
Debug.WriteLine("Arbeitgeber: BoolSetErfolgreich");
erfolgreich = true;
Debug.WriteLine("ArbeitgeberDaten gespeichert!");
}
else if (aktKunde != null)
{
Arbeitgeber neuerArbeitgeber = new Arbeitgeber()
{
BeschaeftigtSeit = DateTime.Parse(beschäftigtSeit),
FKBranche = idBranche,
FKBeschaeftigungsArt = idBeschäftigungsArt,
Firma = firmenName
};
aktKunde.Arbeitgeber = neuerArbeitgeber;
Debug.WriteLine("ArbeitgeberSpeichern: DBContextSave");
int anzahlZeilenBetroffen = context.SaveChanges();
Debug.WriteLine("Arbeitgeber: BoolchangeErfolgreich");
erfolgreich = anzahlZeilenBetroffen >= 1;
Debug.WriteLine($"{anzahlZeilenBetroffen} ArbeitgeberDaten gespeichert!");
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in ArbeitgeberSpeichern");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich;
}
public static List<BeschaeftigungsArt> BeschaeftigungenLaden()
{
Debug.WriteLine("KreditVerwaltung: BeschaeftigungenLaden");
Debug.Indent();
List<BeschaeftigungsArt> alleBeschaeftigungen = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleBeschaeftigungen = context.AlleBeschaeftigungsArten.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in Beschaeftigungsart");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleBeschaeftigungen;
}
public static List<Branche> BranchenLaden()
{
Debug.WriteLine("KreditVerwaltung: BranchenLaden");
Debug.Indent();
List<Branche> alleBranchen = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleBranchen = context.AlleBranchen.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in BranchenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleBranchen;
}
public static bool FinanzielleSituationSpeichern(double nettoEinkommen, double ratenVerpflichtungen, double wohnkosten, double einkünfteAlimenteUnterhalt, double unterhaltsZahlungen, int idKunde)
{
Debug.WriteLine("KreditVerwaltung: FinanzielleSituationSpeichern");
Debug.Indent();
bool erfolgreich = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
/// speichere zum Kunden die Angaben
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde.FinanzielleSituation != null)
{
aktKunde.FinanzielleSituation.MonatsEinkommenNetto = (decimal)nettoEinkommen;
aktKunde.FinanzielleSituation.AusgabenAlimenteUnterhalt = (decimal)unterhaltsZahlungen;
aktKunde.FinanzielleSituation.EinkuenfteAlimenteUnterhalt = (decimal)einkünfteAlimenteUnterhalt;
aktKunde.FinanzielleSituation.Wohnkosten = (decimal)wohnkosten;
aktKunde.FinanzielleSituation.Raten = (decimal)ratenVerpflichtungen;
aktKunde.FinanzielleSituation.ID = idKunde;
Debug.WriteLine("FinanzielleSituationSpeichern: OverwriteDBContextSave");
context.SaveChanges();
Debug.WriteLine("FinanzielleSituationSpeichern: BoolSetErfolgreich");
erfolgreich = true;
Debug.WriteLine("FinanzielleSituationSpeichern: gespeichert!");
}
else if (aktKunde != null)
{
FinanzielleSituation neueFinanzielleSituation = new FinanzielleSituation()
{
MonatsEinkommenNetto = (decimal)nettoEinkommen,
AusgabenAlimenteUnterhalt = (decimal)unterhaltsZahlungen,
EinkuenfteAlimenteUnterhalt = (decimal)einkünfteAlimenteUnterhalt,
Wohnkosten = (decimal)wohnkosten,
Raten = (decimal)ratenVerpflichtungen,
ID = idKunde
};
context.AlleFinanzielleSituationen.Add(neueFinanzielleSituation);
Debug.WriteLine("FinanzielleSituationSpeichern: DBContextSave");
int anzahlZeilenBetroffen = context.SaveChanges();
Debug.WriteLine("FinanzielleSituationSpeichern: BoolchangeErfolgreich");
erfolgreich = anzahlZeilenBetroffen >= 1;
Debug.WriteLine($"{anzahlZeilenBetroffen} FinanzielleSituation gespeichert!");
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in FinanzielleSituation");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich;
}
/// <summary>
/// Liefert alle Schulabschlüsse zurück
/// </summary>
/// <returns>alle Schulabschlüsse oder null bei einem Fehler</returns>
public static List<Schulabschluss> BildungsangabenLaden()
{
Debug.WriteLine("KreditVerwaltung: BildungsangabenLaden");
Debug.Indent();
List<Schulabschluss> alleAbschlüsse = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleAbschlüsse = context.AlleSchulabschluesse.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in BildungsAngabenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleAbschlüsse;
}
public static List<Familienstand> FamilienstandLaden()
{
Debug.WriteLine("KreditVerwaltung: FamilienstandLaden");
Debug.Indent();
List<Familienstand> alleFamilienStandsAngaben = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleFamilienStandsAngaben = context.AlleFamilienstandAngaben.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in FamilienStandAngabenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleFamilienStandsAngaben;
}
public static List<Land> LaenderLaden()
{
Debug.WriteLine("KreditVerwaltung LaenderLaden");
Debug.Indent();
List<Land> alleLänder = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleLänder = context.AlleLänder.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in LaenderLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleLänder;
}
/// <summary>
/// Liefert alle Wohnarten zurück
/// </summary>
/// <returns>alle Wohnarten oder null bei einem Fehler</returns>
public static List<Wohnart> WohnartenLaden()
{
Debug.WriteLine("KreditVerwaltung: WohnartenLaden");
Debug.Indent();
List<Wohnart> alleWohnarten = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleWohnarten = context.AlleWohnarten.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in WohnartenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleWohnarten;
}
/// <summary>
/// Liefert alle IdentifikatikonsArt zurück
/// </summary>
/// <returns>alle IdentifikatikonsArt oder null bei einem Fehler</returns>
public static List<IdentifikationsArt> IdentifikationsangabenLaden()
{
Debug.WriteLine("KreditVerwaltung: IdentifikiationsangabenLaden");
Debug.Indent();
List<IdentifikationsArt> alleIdentifikationsArten = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleIdentifikationsArten = context.AlleIdentifikationsArten.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in IdentifikiationsAngabenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleIdentifikationsArten;
}
public static List<Titel> TitelLaden()
{
Debug.WriteLine("KreditVerwaltung: TitelLaden");
Debug.Indent();
List<Titel> alleTitel = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
alleTitel = context.AlleTitel.ToList();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in TitelLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return alleTitel;
}
public static bool PersönlicheDatenSpeichern(int? idTitel, string geschlecht, DateTime geburtsDatum, string vorname, string nachname, int idBildung, int idFamilienstand, int idIdentifikationsart, string identifikationsNummer, string idStaatsbuergerschaft, int idWohnart, int idKunde)
{
Debug.WriteLine("KreditVerwaltung: PersönlicheDatenSpeichern");
Debug.Indent();
bool erfolgreich = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
/// speichere zum Kunden die Angaben
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde != null)
{
aktKunde.Vorname = vorname;
aktKunde.Nachname = nachname;
aktKunde.FKFamilienstand = idFamilienstand;
aktKunde.FKSchulabschluss = idBildung;
aktKunde.FKStaatsangehoerigkeit = idStaatsbuergerschaft;
aktKunde.FKTitel = idTitel;
aktKunde.FKIdentifikationsArt = idIdentifikationsart;
aktKunde.IdentifikationsNummer = identifikationsNummer;
aktKunde.Geschlecht = geschlecht;
aktKunde.FKWohnart = idWohnart;
Debug.WriteLine("PersönlicheDatenSpeichern: DBContextSave");
context.SaveChanges();
Debug.WriteLine("PersönlicheDatenSpeichern: BoolSetErfolgreich");
erfolgreich = true;
Debug.WriteLine("PersönlicheDatenSpeichern: gespeichert!");
}
//Debug.WriteLine("PersönlicheDatenSpeichern: DBContextSave");
//int anzahlZeilenBetroffen = context.SaveChanges();
//Debug.WriteLine("PersönlicheDatenSpeichern: BoolchangeErfolgreich");
//erfolgreich = anzahlZeilenBetroffen >= 1;
//Debug.WriteLine($"{anzahlZeilenBetroffen} PersönlicheDaten gespeichert!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in PersönlicheDatenSpeichern");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich;
}
public static bool KontoInformationenSpeichern(string bankName, string iban, string bic, bool neuesKonto, int idKunde)
{
Debug.WriteLine("KreditVerwaltung: KontoInformationenSpeichern");
Debug.Indent();
bool erfolgreich = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
/// speichere zum Kunden die Angaben
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde.KontoDaten != null)
{
aktKunde.KontoDaten.Bank = bankName;
aktKunde.KontoDaten.IBAN = iban;
aktKunde.KontoDaten.BIC = bic;
aktKunde.KontoDaten.HatKonto = !neuesKonto;
aktKunde.KontoDaten.ID = idKunde;
Debug.WriteLine("KontoInformationenSpeichern: DBContextSave");
context.SaveChanges();
Debug.WriteLine("KontoInformationenSpeichern: BoolSetErfolgreich");
erfolgreich = true;
Debug.WriteLine("KontoInformationenSpeichern: gespeichert!");
}
else if (aktKunde != null)
{
KontoDaten neueKontoDaten = new KontoDaten()
{
Bank = bankName,
IBAN = iban,
BIC = bic,
HatKonto = !neuesKonto,
ID = idKunde
};
context.AlleKontoDaten.Add(neueKontoDaten);
Debug.WriteLine("KontoInformationenSpeichern: DBContextSave");
int anzahlZeilenBetroffen = context.SaveChanges();
Debug.WriteLine("KontoInformationenSpeichern: BoolchangeErfolgreich");
erfolgreich = anzahlZeilenBetroffen >= 1;
Debug.WriteLine($"{anzahlZeilenBetroffen} Konto-Daten gespeichert!");
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KontoInformationenSpeichern");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich;
}
public static bool KontaktdatenSpeichern(string strasse, string hausnummer, string mail, string telefonNummer, int idKunde, string ort, string idplz, string idland)
{
Debug.WriteLine("KreditVerwaltung: KontaktDatenSpeichern");
Debug.Indent();
bool erfolgreich1 = false;
bool erfolgreich2 = false;
try
{
using (var context = new dbKreditRechnerEntities())
{
Kunde aktKunde = context.AlleKunden.Where(x => x.ID == idKunde).FirstOrDefault();
if (aktKunde.KontaktDaten != null /*|| aktKunde.KontaktDaten.Ort != null*/)
{
Debug.WriteLine("KontaktDatenSpeichern: KontaktDaten erneut");
aktKunde.KontaktDaten.Strasse = strasse;
aktKunde.KontaktDaten.Hausnummer = hausnummer;
aktKunde.KontaktDaten.EMail = mail;
aktKunde.KontaktDaten.Telefonnummer = telefonNummer;
aktKunde.KontaktDaten.ID = idKunde;
Debug.WriteLine("KontaktDatenSpeichern: KontaktDaten.Ort erneut");
aktKunde.KontaktDaten.Ort.Bezeichnung = ort;
aktKunde.KontaktDaten.Ort.PLZ = idplz;
//aktKunde.KontaktDaten.Ort.FKLand = idland;
aktKunde.KontaktDaten.Ort.ID = idKunde;
Debug.WriteLine("KontaktDatenSpeichern: DBContextSave");
context.SaveChanges();
Debug.WriteLine("KontaktDatenSpeichern: BoolSetErfolgreich");
erfolgreich1 = true;
erfolgreich2 = true;
Debug.WriteLine("KontaktDatenSpeichern: gespeichert!");
}
else if (aktKunde != null)
{
//aktKunde.KontaktDaten.Strasse = strasse;
//aktKunde.KontaktDaten.Hausnummer = hausnummer;
//aktKunde.KontaktDaten.EMail = mail;
//aktKunde.KontaktDaten.Telefonnummer = telefonNummer;
//aktKunde.KontaktDaten.Ort.Bezeichnung = ort;
//aktKunde.KontaktDaten.Ort.PLZ = idplz;
//aktKunde.KontaktDaten.Ort.FKLand = idland;
KontaktDaten newKontakt = new KontaktDaten()
{
Strasse = strasse,
Hausnummer = hausnummer,
EMail = mail,
Telefonnummer = telefonNummer,
ID = idKunde
};
context.AlleKontaktDaten.Add(newKontakt);
Debug.WriteLine("KontaktDatenSpeichern: 1.DBContextSave");
int anzahlZeilenBetroffen1 = context.SaveChanges();
Debug.WriteLine("KontaktDatenSpeichern: BoolchangeErfolgreich");
erfolgreich1 = anzahlZeilenBetroffen1 >= 1;
Debug.WriteLine("KontaktDatenSpeichern: NewOrtKontakt");
Ort newOrtKontakt = new Ort()
{
ID = idKunde,
Bezeichnung = ort,
PLZ = idplz,
FKLand = idland
};
context.AlleOrte.Add(newOrtKontakt);
Debug.WriteLine("KontaktDatenSpeichern: 2.DBContextSave");
int anzahlZeilenBetroffen2 = context.SaveChanges();
Debug.WriteLine("KontaktDatenSpeichern: BoolchangeErfolgreich");
erfolgreich2 = anzahlZeilenBetroffen2 >= 1;
Debug.WriteLine($"{anzahlZeilenBetroffen2} KontaktDaten gespeichert!");
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KontaktDatenSpeichern");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return erfolgreich1 & erfolgreich2;
}
#region [Zusammenfassung: Kundendaten laden]
public static Kunde KundeLaden(int idKunde)
{
Debug.WriteLine("KreditVerwaltung: KundeLaden");
Debug.Indent();
Kunde aktKunde = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
aktKunde = context.AlleKunden
.Include("Arbeitgeber")
.Include("Arbeitgeber.BeschaeftigungsArt")
.Include("Arbeitgeber.Branche")
.Include("Familienstand")
.Include("FinanzielleSituation")
.Include("IdentifikationsArt")
.Include("KontaktDaten")
.Include("KontaktDaten.Ort")
.Include("KontaktDaten.Ort.Land")
.Include("KontoDaten")
.Include("KreditWunsch")
.Include("Schulabschluss")
.Include("Titel")
.Include("Wohnart")
.Include("Staatsangehoerigkeit")
.Where(x => x.ID == idKunde).FirstOrDefault();
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KundeLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return aktKunde;
}
public static KreditWunsch KreditLaden(int k_id)
{
Debug.WriteLine("KreditVerwaltung: KreditLaden");
Debug.Indent();
KreditWunsch wunsch = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
wunsch = context.AlleKreditWünsche.Where(x => x.ID == k_id).FirstOrDefault();
Debug.WriteLine("KreditRahmen geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KreditLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return wunsch;
}
public static FinanzielleSituation FinanzielleSituationLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: FinanzielleSituationLaden");
Debug.Indent();
FinanzielleSituation finanzielleSituation = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
finanzielleSituation = context.AlleFinanzielleSituationen.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("FinanzielleSituation geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in FinanzielleSituationLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return finanzielleSituation;
}
public static Arbeitgeber ArbeitgeberLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: ArbeitgeberLaden");
Debug.Indent();
Arbeitgeber aktArbeitgeber = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
aktArbeitgeber = context.AlleArbeitgeber.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("Arbeitgeber geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in ArbeitgeberLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return aktArbeitgeber;
}
public static Kunde PersönlicheDatenLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: PersönlicheDatenLaden");
Debug.Indent();
Kunde persönlicheDaten = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
persönlicheDaten = context.AlleKunden.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("PersönlicheDatenLaden geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in PersönlicheDatenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return persönlicheDaten;
}
public static KontoDaten KontoInformationenLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: KontoInformationenLaden");
Debug.Indent();
KontoDaten kontoDaten = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
kontoDaten = context.AlleKontoDaten.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("KontoInformationen geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KontoInformationenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return kontoDaten;
}
public static KontaktDaten KontaktDatenLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: KontaktDatenLaden");
Debug.Indent();
KontaktDaten kontaktDaten = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
kontaktDaten = context.AlleKontaktDaten.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("KontaktDaten geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in KontaktDatenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return (kontaktDaten);
}
public static Ort OrtDatenLaden(int id)
{
Debug.WriteLine("KreditVerwaltung: OrtDatenLaden");
Debug.Indent();
Ort kontaktOrt = null;
try
{
using (var context = new dbKreditRechnerEntities())
{
kontaktOrt = context.AlleOrte.Where(x => x.ID == id).FirstOrDefault();
Debug.WriteLine("KontaktOrt geladen!");
}
}
catch (Exception ex)
{
Debug.WriteLine("Fehler in OrtDatenLaden");
Debug.Indent();
Debug.WriteLine(ex.Message);
Debug.Unindent();
Debugger.Break();
}
Debug.Unindent();
return (kontaktOrt);
}
//public static Ort LandDatenLaden(int id)
//{
// Debug.WriteLine("KreditVerwaltung: LandDatenLaden");
// Debug.Indent();
// Land kontaktLand = null;
// try
// {
// using (var context = new dbKreditRechnerEntities())
// {
// kontaktLand = context.AlleLänder.Where(x => x.ID == id).FirstOrDefault();
// Debug.WriteLine("KontaktOrt geladen!");
// }
// }
// catch (Exception ex)
// {
// Debug.WriteLine("Fehler in OrtDatenLaden");
// Debug.Indent();
// Debug.WriteLine(ex.Message);
// Debug.Unindent();
// Debugger.Break();
// }
// Debug.Unindent();
// return (kontaktOrt);
//}
#endregion
}
}
|
b4ad11e9a0ad9284738d124aea8afd790794026e
|
C#
|
danielmsorensen/Room_Manager
|
/Assets/Scripts/ClickHandler.cs
| 2.5625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
[System.Serializable] public class Event : UnityEngine.Events.UnityEvent { }
public Event OnRightClick = new Event();
public bool mouseOver { get; private set; }
void Update() {
if(Input.GetMouseButtonUp(1) && mouseOver) {
OnRightClick.Invoke();
}
}
public void OnPointerEnter(PointerEventData eventData) {
mouseOver = true;
}
public void OnPointerExit(PointerEventData eventData) {
mouseOver = false;
}
}
|
be624d931ca10dad25f94ff838c2e9a167931ec0
|
C#
|
theMagnificentJay/CSharpFundamentals
|
/12_GeneralStore/Controllers/ProductController.cs
| 2.796875
| 3
|
using _12_GeneralStore.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace _12_GeneralStore.Controllers
{
public class ProductController : ApiController
{
private readonly ApplicationDbContext _context = new ApplicationDbContext();
[HttpPost]
public async Task<IHttpActionResult> Post(Product product)
{
if (ModelState.IsValid)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return Ok(); //200 (ok) status
}
return BadRequest(ModelState); // 400 Bad request
}
[HttpGet]
public async Task<IHttpActionResult> GetAll()
{
List<Product> products = await _context.Products.ToListAsync();
return Ok(products); // 200 (ok) Here's your list
}
[HttpGet]
public async Task<IHttpActionResult> GetById([FromUri]int id)
{
Product product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
|
cd8a85d48df64c896dbadeb53627e6c857729d0f
|
C#
|
movchan74/moving_game
|
/Assets/utils/HyperCasual/Core/Extensions/ListExtensions/ListPopExtensions.cs
| 3.4375
| 3
|
using System.Collections.Generic;
namespace HyperCasual.Extensions
{
/// <summary>
/// Extends generic lists with common popping operations.
/// </summary>
public static class ListPopExtensions
{
public static T PopLast<T>(this List<T> list)
{
return list.Pop(list.Count - 1);
}
public static T PopFirst<T>(this List<T> list)
{
return list.Pop(0);
}
public static T Pop<T>(this List<T> list, int index)
{
var item = list[index];
list.RemoveAt(index);
return item;
}
}
}
|
b49388fada06f4d6e86c3b9d9fa14ac17dc5cb4c
|
C#
|
JorisverhelstCode/ContactWeb
|
/ContactWeb/Database/IPersonsDatabase.cs
| 3.203125
| 3
|
using ContactWeb.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ContactWeb.Database
{
public interface IPeopleDatabase
{
Person Insert(Person movie);
IEnumerable<Person> GetPeople();
Person GetPerson(int id);
void Delete(int id);
void Update(int id, Person movie);
}
public class PersonsDatabase : IPeopleDatabase
{
private int _counter;
private readonly List<Person> _people;
public PersonsDatabase()
{
if (_people == null)
{
_people = new List<Person>();
LoadAllPeople();
}
}
public Person GetPerson(int id)
{
return _people.FirstOrDefault(x => x.ID == id);
}
public IEnumerable<Person> GetPeople()
{
return _people;
}
public Person Insert(Person person)
{
_counter++;
person.ID = _counter;
_people.Add(person);
return person;
}
public void Delete(int id)
{
var movie = _people.SingleOrDefault(x => x.ID == id);
if (movie != null)
{
_people.Remove(movie);
}
}
public void Update(int id, Person updatedPerson)
{
var person = _people.SingleOrDefault(x => x.ID == id);
if (person != null)
{
person.FirstName = updatedPerson.FirstName;
person.Description = updatedPerson.Description;
person.LastName = updatedPerson.LastName;
person.PhoneNumber = updatedPerson.PhoneNumber;
person.Adress = updatedPerson.Adress;
person.DateOfBirth = updatedPerson.DateOfBirth;
person.Email = updatedPerson.Email;
}
}
public void LoadAllPeople()
{
}
}
}
|
103df0612df1040faef7f06fdbb5098893921ea9
|
C#
|
sabal90/Netty-CSharp
|
/Netty/netty/resolver/InetSocketAddress.cs
| 2.90625
| 3
|
using System;
using System.Net;
using System.Net.Sockets;
namespace io.netty.resolver
{
public class InetSocketAddress : SocketAddress
{
// Private implementation class pointed to by all public methods.
private class InetSocketAddressHolder
{
// The hostname of the Socket Address
private String hostname;
// The IP address of the Socket Address
private InetAddress addr;
// The port number of the Socket Address
private int port;
public InetSocketAddressHolder(String hostname, InetAddress addr, int port)
{
this.hostname = hostname;
this.addr = addr;
this.port = port;
}
private int getPort()
{
return port;
}
private InetAddress getAddress()
{
return addr;
}
public String getHostName()
{
if (hostname != null)
return hostname;
if (addr != null)
return addr.getHostName();
return null;
}
private String getHostString()
{
if (hostname != null)
return hostname;
if (addr != null)
{
if (addr.holder().getHostName() != null)
return addr.holder().getHostName();
else
return addr.getHostAddress();
}
return null;
}
private bool isUnresolved()
{
return addr == null;
}
public String toString()
{
if (isUnresolved())
{
return hostname + ":" + port;
}
else
{
return addr.toString() + ":" + port;
}
}
// public bool equals(Object obj)
// {
// if (obj == null || !(obj is InetSocketAddressHolder))
// return false;
// InetSocketAddressHolder that = (InetSocketAddressHolder)obj;
// bool sameIP;
// if (addr != null)
// sameIP = addr.Equals(that.addr);
// else if (hostname != null)
// sameIP = (that.addr == null) &&
// hostname.equalsIgnoreCase(that.hostname);
// else
// sameIP = (that.addr == null) && (that.hostname == null);
// return sameIP && (port == that.port);
// }
// public int hashCode()
// {
// if (addr != null)
// return addr.hashCode() + port;
// if (hostname != null)
// return hostname.toLowerCase().hashCode() + port;
// return port;
// }
}
private InetSocketAddressHolder holder = null;
private static int checkPort(int port)
{
if (port < 0 || port > 0xFFFF)
throw new ArgumentException("port out of range:" + port);
return port;
}
private static String checkHost(String hostname)
{
if (hostname == null)
throw new ArgumentException("hostname can't be null");
return hostname;
}
private int port;
private String hostName;
private InetSocketAddress(AddressFamily family = AddressFamily.InterNetwork) : base(family) { }
public static InetSocketAddress Create(String host, int port)
{
return new InetSocketAddress(checkPort(port), checkHost(host));//new IPEndPoint(IPAddress.Parse(inetHost), inetPort).Serialize();
}
private InetSocketAddress(int port, String hostName) : this()
{
this.hostName = hostName;
this.port = port;
}
// public InetSocketAddress(int port) : this(InetAddress.anyLocalAddress(), port) { }
// public InetSocketAddress(InetAddress addr, int port) : this()
// {
// holder = new InetSocketAddressHolder(
// null,
// addr == null ? InetAddress.anyLocalAddress() : addr,
// checkPort(port));
// }
public String getHostName()
{
return holder.getHostName();
}
}
}
|
7b0f363c5c96b70daeadd12d9d650d94413b18b2
|
C#
|
John-D-S/gooble-lump
|
/Assets/Gooble Lump/Scripts/SpringyThingyController.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpringyThingyController : MonoBehaviour
{
//all the parts that make up the player
[Header("-- Parts --")]
[SerializeField, Tooltip("The Top Half of the ball")]
private Rigidbody2D halfA;
[SerializeField, Tooltip("The Bottom Half of the ball")]
private Rigidbody2D halfB;
[SerializeField, Tooltip("The Gameobject that indicates the direction of the ball")]
private GameObject directionIndicator;
[SerializeField, Tooltip("The linerenderer that will show when the wing is activated")]
private LineRenderer wingLine;
[Header("-- Physics Settings --")]
[SerializeField, Tooltip("The distance between the two halves when extended")]
private float extendedLength = -2.5f;
[SerializeField, Tooltip("The force in the joint between the two halves.")]
private float springForce = 1f;
[SerializeField, Tooltip("Scales the amount of torque applied to the player")]
private float torqueMultiplier = 7.5f;
[SerializeField, Tooltip("How much the extended wing is affected by aerodynamics")]
float AerodynamicAffect = 0.75f;
//the joint connecting the two halves
[SerializeField, HideInInspector]
private RelativeJoint2D joint;
//the default distance between halves
[SerializeField, HideInInspector]
private float defaultJointLength;
/// <summary>
/// determines whether or not the direction indicator is active
/// </summary>
private bool IndicateDirection
{
get
{
if (directionIndicator)
return directionIndicator.activeSelf;
return false;
}
set
{
if (directionIndicator)
directionIndicator.SetActive(value);
}
}
/// <summary>
/// this will return the position in the middle of both halves of the ball
/// </summary>
public Vector2 AveragePosition
{
get => Vector2.Lerp(halfA.position, halfB.position, 0.5f);
set { }
}
/// <summary>
/// returns the average z rotation of both halves
/// </summary>
public float AverageZRotation
{
get => Vector2.SignedAngle(Vector3.up, halfA.position - halfB.position);
set { }
}
/// <summary>
/// returns the direction from the back half to the front half
/// </summary>
public Vector2 averageForwardDirection
{
get => (halfA.position - halfB.position).normalized;
}
private bool extended;
/// <summary>
/// this controls whether or not the ball is extended
/// </summary>
private bool Extended
{
get => extended;
set
{
//setting the linear offset of the joint causes the halves of the ball to spring apart/ together.
joint.linearOffset = value ? Vector2.up * extendedLength : Vector2.up * defaultJointLength;
extended = value;
}
}
/// <summary>
/// returns whether or not the ball is currently extended
/// </summary>
public bool isExtended
{
get => extended;
}
// how much torque is currently being applied
float currentTorque;
#region Torque Stuff
/// <summary>
/// appies a force to each side in opposite directions to rotate the player
/// </summary>
void AddTorqueToBothHalves(float torqueToAdd)
{
Vector2 forceDirection = Vector2.Perpendicular(averageForwardDirection);
halfA.AddForce(forceDirection * torqueToAdd);
halfB.AddForce(forceDirection * -torqueToAdd);
}
/// <summary>
/// returns the torque required to rotate the player so that they are facing a target.
/// </summary>
private float RotateTowardsTarget(Vector2 target)
{
Vector2 directionToTarget = (target - AveragePosition).normalized;
Vector2 forwardDirection = averageForwardDirection;
//this is used to calculate whether to turn left or right
Vector2 leftDirection = Vector2.Perpendicular(forwardDirection);
float angularVelocity = Mathf.Lerp(halfA.angularVelocity, halfB.angularVelocity, 0.5f);
float turnDirection = Mathf.Sign((Vector2.Dot(forwardDirection, directionToTarget) + 1) * 0.5f * Vector2.Dot(leftDirection, directionToTarget));
float dotProductToTarget = Mathf.Abs(Vector2.Dot(leftDirection, directionToTarget));
//the -angularVelocity here stops the player from overshooting and swinging back and fourth
float torqueToAdd = Mathf.Lerp(-angularVelocity * 0.0025f, turnDirection, dotProductToTarget) * torqueMultiplier;
return torqueToAdd;
}
/// <summary>
/// applies currentTorque and lerps it down to 0
/// </summary>
void ApplyTorque()
{
AddTorqueToBothHalves(currentTorque * 15);
//currentTorque decays back down to zero.
currentTorque = Mathf.Lerp(currentTorque, 0, 25f);
}
#endregion
void ApplyAerodynamics()
{
if (Extended)
{
Vector2 averageVelocity = Vector2.Lerp(halfA.velocity, halfB.velocity, 0.5f);
Vector2 directionPerpandicularToWing = Vector2.Perpendicular((halfB.position - halfA.position).normalized);
//this is the angle between the average velocity of the wing and the direction perpandicular to it.
float angle = Vector2.Angle(averageVelocity, directionPerpandicularToWing);
float forceToApply = -averageVelocity.magnitude * Mathf.Cos(Mathf.Deg2Rad * angle) * AerodynamicAffect;
halfA.AddForce(forceToApply * directionPerpandicularToWing);
halfB.AddForce(forceToApply * directionPerpandicularToWing);
Debug.DrawLine(AveragePosition, AveragePosition + averageVelocity, Color.green);
Debug.DrawLine(AveragePosition, AveragePosition + forceToApply * directionPerpandicularToWing, Color.red);
}
}
/// <summary>
/// updates the Physics based on the mouse controls
/// </summary>
private void MouseControlsUpdate()
{
Extended = Input.GetMouseButton(0);
Vector2 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
currentTorque = RotateTowardsTarget(mousePositionInWorld);
if (!extended)
IndicateDirection = true;
else
IndicateDirection = false;
}
/// <summary>
/// Updates the Wing lineRenderer
/// </summary>
private void UpdateWingLineRenderer()
{
if (wingLine)
{
if (Extended)
{
wingLine.enabled = true;
wingLine.SetPosition(0, halfA.position);
wingLine.SetPosition(1, halfB.position);
}
else
{
wingLine.enabled = false;
}
}
}
private void OnValidate()
{
if (halfA && halfB)
{
RelativeJoint2D halfAHasJoint = halfA.GetComponent<RelativeJoint2D>();
if (halfAHasJoint)
joint = halfAHasJoint;
else
joint = halfB.GetComponent<RelativeJoint2D>();
}
if (joint)
{
defaultJointLength = joint.linearOffset.y;
joint.maxForce = springForce;
}
}
private void Awake()
{
StaticObjectHolder.player = this;
}
private void Update()
{
MouseControlsUpdate();
UpdateWingLineRenderer();
}
private void FixedUpdate()
{
ApplyAerodynamics();
ApplyTorque();
}
}
|
78375e95833f7e0c089feea3da763995e7942808
|
C#
|
mastoj/TJ.CQRS
|
/TJ.CQRS/Messaging/MessageRouter.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using TJ.Extensions;
namespace TJ.CQRS.Messaging
{
public abstract class MessageRouter : IEventRouter, ICommandRouter
{
private Dictionary<Type, List<Action<IMessage>>> _messageRoutes;
public MessageRouter()
{
_messageRoutes = new Dictionary<Type, List<Action<IMessage>>>();
}
public void Register<TMessage>(Action<TMessage> route) where TMessage : class, IMessage
{
List<Action<IMessage>> routes;
var type = typeof(TMessage);
if (_messageRoutes.TryGetValue(type, out routes).IsFalse())
{
routes = new List<Action<IMessage>>();
_messageRoutes.Add(type, routes);
}
routes.Add((y) => route(y as TMessage));
}
public bool TryGetValue(Type commandType, out List<Action<IMessage>> handlers)
{
return _messageRoutes.TryGetValue(commandType, out handlers);
}
}
}
|
26a9c90196c24157a6d58d27b5e54bd61bfd638a
|
C#
|
JoFox911/ITEA_UnityCourses
|
/FPS/Assets/Scripts/Bot/BotFSM/State/SearchingEnemyState.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace BotLogic
{
public class SearchingEnemyState : BaseState<BotSharedContext>
{
private Transform _destinationPoint;
private List<Transform> _searchingPointsList;
public SearchingEnemyState(BotSharedContext sharedContext) : base(sharedContext)
{
}
public override void OnStateEnter()
{
Debug.Log($"[{GetType().Name}][{MethodBase.GetCurrentMethod().Name}] - OK");
if (_sharedContext == null)
{
return;
}
SetNewDistinationPoint();
}
public override void Execute()
{
if (!_sharedContext.SoldierState.IsAlive())
{
_stateSwitcher.Switch(typeof(DeadState));
}
else if (_sharedContext.EnemySpyManager.IsAnyEnemySpyed)
{
_stateSwitcher.Switch(typeof(EnemyAttackState));
}
else if (_sharedContext.MovementManager.IsMovementCompleted)
{
//take next enemy searching point
SetNewDistinationPoint();
}
}
private void SetNewDistinationPoint()
{
_searchingPointsList = _sharedContext.MapHelper.EnemySearchingPoints.Where(point => point != _destinationPoint).ToList();
_destinationPoint = Common.SetectOneOfTheNearestPoint(_searchingPointsList,
_sharedContext.MovementManager.GetCurrentPossition(), _searchingPointsList.Count);
_sharedContext.MovementManager.MoveToTarget(_destinationPoint.position);
}
}
}
|
4466e99fb99867e349ae77981e32cd40a51a60fe
|
C#
|
mbrinkg8tr/SpiralNumberGenerator
|
/src/NumericSpiral/Controllers/SpiralDataController.cs
| 3.1875
| 3
|
using System;
using Microsoft.AspNet.Mvc;
using Newtonsoft.Json;
namespace NumericSpiral.Controllers
{
public class SpiralDataController : Controller
{
public string Generate(int id)
{
// Basic numeric validation
if (id < 0) return "[[0]]";
// Determine the size of the grid and allocate memory
id++;
double b = Math.Sqrt(id);
int a = (int) Math.Truncate(b);
if (b - a > 0) a++;
int i = (int) Math.Pow(a, 2);
int[,] result = new int[a,a];
// Set Initial Conditions
int x = a-1, y = 0;
int xr = -1, yr = 0;
// Draw the spiral in memory using left turns
for (var p = i; p > 0; p--)
{
// Set the number in memory, move on to
// the next location
result[y, x] = p-1;
x += xr;
y += yr;
// Turn detection
if (!(x < 0 || y < 0 || x > a-1 || y > a-1))
if (result[y, x] == 0) continue;
// Turn cases
if (xr == -1)
{
x++; y++; xr = 0; yr = 1;
continue;
}
p++;
if (yr == 1)
{
y--; xr = 1; yr = 0;
continue;
}
if (xr == 1)
{
x--; xr = 0; yr = -1;
continue;
}
if (yr == -1)
{
y++; xr = -1; yr = 0;
}
}
return JsonConvert.SerializeObject(result);
}
}
}
|
059659028f1048fa49ef29ba4ed6a8b168fa8a33
|
C#
|
amgorder/artist
|
/Repositories/ArtistsRepository.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using artist.Model;
using Dapper;
namespace artist.Repositories
{
public class ArtistsRepository
{
public readonly IDbConnection _db;
public ArtistsRepository(IDbConnection db)
{
_db = db;
}
internal IEnumerable<Artist> Get()
{
string sql = @"SELECT * FROM artists; ";
return _db.Query<Artist>(sql);
}
internal Artist Get(int Id)
{
string sql = @"SELECT * FROM artists
WHERE id = @Id; ";
return _db.QueryFirstOrDefault<Artist>(sql, new { Id });
}
internal Artist Create(Artist newArtist)
{
string sql = @"
INSERT INTO artists
(name, description )
VALUES
(@Name, @Description);
SELECT LAST_INSERT_ID();";
int id = _db.ExecuteScalar<int>(sql, newArtist);
newArtist.Id = id;
return newArtist
;
}
internal Artist Edit(Artist artistToEdit)
{
//After you go an update it make sure to go and select it again
string sql = @"
UPDATE artists
SET
name = @Name,
description = @Description
WHERE id = @Id;
SELECT * FROM artists
WHERE id = @Id;";
return _db.QueryFirstOrDefault<Artist>(sql, artistToEdit);
}
internal void Delete(int id)
{
string sql = "DELETE FROM artists WHERE id = @id;";
_db.Execute(sql, new { id });
return;
}
}
}
|
d7810898c8ee8357790f6358f7738e402b275451
|
C#
|
futugyou/TeslaAPI
|
/TeslaApi.Contract/HttpClientUtils.cs
| 2.640625
| 3
|
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using TeslaApi.Contract;
namespace TeslaApi
{
public static class HttpClientUtils
{
class NullClass
{
}
public static async Task<Response> UtilsPostAsync<Response>(this HttpClient httpClient, string path)
{
return await httpClient.UtilsPostAsync<NullClass, Response>(null, path, "");
}
public static async Task<Response> UtilsPostAsync<Request, Response>(this HttpClient httpClient, Request request, string path)
{
return await httpClient.UtilsPostAsync<Request, Response>(request, path, "");
}
public static async Task<Response> UtilsPostAsync<Response>(this HttpClient httpClient, string path, string token)
{
return await httpClient.UtilsPostAsync<NullClass, Response>(null, path, token);
}
public static async Task<Response> UtilsPostAsync<Request, Response>(this HttpClient httpClient, Request? request, string path, string token)
{
HttpContent? content = default;
if (request != null)
{
var json = JsonSerializer.Serialize(request, JsonSerializerExtensions.CreateJsonSetting());
content = new StringContent(json, Encoding.UTF8, TeslaApiConst.MEDIA_TYPE);
}
try
{
if (!string.IsNullOrEmpty(token))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TeslaApiConst.TESLA_Authorization_Type, token);
}
var responseMessage = await httpClient.PostAsync(path, content);
var result = await responseMessage.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<Response>(result, JsonSerializerExtensions.CreateJsonSetting());
if (response == null)
{
throw new HttpRequestException(result);
}
return response;
}
catch (Exception)
{
throw;
}
}
public static async Task<Response> UtilsGetAsync<Response>(this HttpClient httpClient, string path)
{
return await UtilsGetAsync<Response>(httpClient, path, "");
}
public static async Task<Response> UtilsGetAsync<Response>(this HttpClient httpClient, string path, string token)
{
try
{
if (!string.IsNullOrEmpty(token))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TeslaApiConst.TESLA_Authorization_Type, token);
}
var responseMessage = await httpClient.GetAsync(path);
var result = await responseMessage.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<Response>(result, JsonSerializerExtensions.CreateJsonSetting());
if (response == null)
{
throw new HttpRequestException(result);
}
return response;
}
catch (Exception)
{
throw;
}
}
}
}
|
17c1af3854a5f86651ec4bad0997dbee695801e9
|
C#
|
theslyone/frapid
|
/src/Libraries/Frapid.CommandLine/Commands/Create/MvcProjectCreator.cs
| 2.6875
| 3
|
using System;
using System.IO;
using System.Text;
using Frapid.Framework;
using Frapid.Configuration;
namespace frapid.Commands.Create
{
internal sealed class MvcProjectCreator
{
internal MvcProjectCreator(string projectName)
{
this.ProjectName = projectName;
this.TempDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp", this.ProjectName + "-" + this.GetRandomNumber());
}
internal string TempDirectory { get; }
internal string ProjectName { get; }
private int GetRandomNumber()
{
var rnd = new Random();
return rnd.Next(52);
}
internal void Create()
{
try
{
this.CreateTempDirectory();
this.CopyProject();
this.EditContents();
this.RenameFileNames();
this.CreateArea();
}
finally
{
Directory.Delete(this.TempDirectory, true);
}
}
private void CreateArea()
{
Console.WriteLine("Creating Area");
string destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "Areas", this.ProjectName);
Directory.CreateDirectory(destination);
FileHelper.CopyDirectory(this.TempDirectory, destination);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("The app {0} has been created on the following directory {1}.", this.ProjectName, destination);
Console.ForegroundColor = ConsoleColor.White;
}
private void CopyProject()
{
string source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "Templates", "MVCProject");
FileHelper.CopyDirectory(source, this.TempDirectory);
Console.WriteLine("Copying project files");
}
private void EditContents()
{
Console.WriteLine("Editing contents");
this.ReplaceContent("MVCProject.csproj");
this.ReplaceContent("MVCProject.sln");
this.ReplaceContent(@"Properties\AssemblyInfo.cs");
this.ReplaceContent(@"Views\web.config");
this.ReplaceContent("AreaRegistration.cs");
}
private void RenameFile(string original, string renamed)
{
string originalFile = Path.Combine(this.TempDirectory, original);
string renamedFile = Path.Combine(this.TempDirectory, renamed);
if (File.Exists(originalFile))
{
File.Move(originalFile, renamedFile);
}
}
private void ReplaceContent(string fileName)
{
string file = Path.Combine(this.TempDirectory, fileName);
string contents = File.ReadAllText(file, Encoding.UTF8);
contents = contents.Replace("MVCProject", this.ProjectName);
File.WriteAllText(file, contents, Encoding.UTF8);
}
private void RenameFileNames()
{
Console.WriteLine("Renaming files");
this.RenameFile("MVCProject.csproj", this.ProjectName + ".csproj");
this.RenameFile("MVCProject.sln", this.ProjectName + ".sln");
this.RenameFile("MVCProject.sln.DotSettings", this.ProjectName + ".sln.DotSettings");
this.RenameFile("MVCProject.sln.DotSettings.user", this.ProjectName + ".sln.DotSettings.user");
}
private void CreateTempDirectory()
{
Console.WriteLine("Creating temp directory {0}.", this.TempDirectory);
Directory.CreateDirectory(this.TempDirectory);
}
}
}
|
e32d2fae386ef6145f6face1a170cfe9cd1bac0a
|
C#
|
halilbayir/BilgeAdam
|
/YildizSekilleri/Program.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YildizSekilleri
{
class Program
{
static void Main(string[] args)
{
int i ,j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < i; j++)
{
if (j == 0 && j == 5)
{ }
Console.WriteLine();
}
}
}
Console.Read();
}
}
|
efd3252c44a1797a00ffd98bf4a2a5682a577821
|
C#
|
andreivorona/CSharpWebBasic25October2020
|
/Apps/Git/Services/RepositoriesService.cs
| 2.9375
| 3
|
namespace Git.Services
{
using Git.Data;
using Git.ViewModels.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
public class RepositoriesService : IRepositoriesService
{
private readonly ApplicationDbContext db;
public RepositoriesService(ApplicationDbContext db)
{
this.db = db;
}
public void CreateRepository(string userId, string name, string repositoryType)
{
bool isPublic = false;
if (repositoryType == "Public")
{
isPublic = true;
}
var repo = new Repository
{
OwnerId = userId,
Name = name,
IsPublic = isPublic,
CreatedOn = DateTime.UtcNow,
};
this.db.Repositories.Add(repo);
this.db.SaveChanges();
}
public IEnumerable<RepositoryViewModel> GetAll()
{
var repo = this.db.Repositories
.Where(x => x.IsPublic == true)
.Select(x => new RepositoryViewModel
{
Id = x.Id,
Name = x.Name,
CreatedOn = x.CreatedOn,
Owner = x.Owner.Username,
CommitsCount = this.db.Commits.Count(),
}).ToList();
return repo;
}
}
}
|
b90e738d8e9741642f188cc23431937e147a052e
|
C#
|
michiel-schoofs/AngularAPI
|
/TatsugotchiWebAPI/Data/Repository/AnimalRepository.cs
| 3.046875
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using TatsugotchiWebAPI.Model;
using TatsugotchiWebAPI.Model.Interfaces;
namespace TatsugotchiWebAPI.Data.Repository {
public class AnimalRepository : IAnimalRepository {
private ApplicationDBContext _context;
private DbSet<Animal> _animals;
#region Constructor
public AnimalRepository(ApplicationDBContext context) {
_context = context;
_animals = context.Animals;
}
#endregion
#region Interface Methods
//Can be called from request and background worker
public void AddAnimal(Animal animal, bool isMultithreaded=false) {
if (isMultithreaded) {
using(ApplicationDBContext context = new ApplicationDBContext()) {
context.Badges.Load();
context.Animals.Load();
context.Animals.Add(animal);
context.SaveChanges();
}
}else {
_animals.Add(animal);
SaveChanges();
}
}
public ICollection<Animal> GetAllAnimals() {
return _animals
.Include(a => a.AnimalBadges)
.ThenInclude(ab=>ab.Badge)
.Include(a => a.Owner)
.Include(a=>a.Type)
.Include(a=>a.AnimalEggs)
.ThenInclude(ae=>ae.Egg)
.Include(a=>a.Gender)
.ToList();
}
public Animal GetAnimal(int id) {
return _animals.FirstOrDefault(a => a.ID == id);
}
public ICollection<Animal> GetNotDeceasedAnimals(ApplicationDBContext context)
{
context.Animals.Load();
return context.Animals.Where(a => !a.IsDeceased && !a.RanAway).ToList();
}
public void RemoveAnimal(Animal animal) {
_animals.Remove(animal);
SaveChanges();
}
public void SaveChanges() {
_context.SaveChanges();
}
#endregion
}
}
|
d9bee45e2697528f051968434dcb70b313e1d329
|
C#
|
soulhez/Unity_GenericBinarySerializer
|
/Assets/BinarySerializer/BinarySerializer.cs
| 2.828125
| 3
|
using UnityEngine;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// BinarySerializer is tool to save your game data in files as binary
/// so that no body can read it or modify it,
/// this tool is generic.
///
/// Allowed types : int, float , strings, ...(all .Net types)
/// But for unity types it accepts only 5 types: Vector2, Vector3, Vector4, Color, Quaternion.
///
/// Developed by Hamza Herbou
/// GITHUB : https://github.com/herbou
/// </summary>
public class BinarySerializer {
static string folderName = "GameData";
static string persistentDataPath = Application.persistentDataPath;
static SurrogateSelector surrogateSelector = GetSurrogateSelector ( );
/// <summary>
/// Save data to disk.
/// </summary>
/// <param name="data">your dataClass instance.</param>
/// <param name="filename">the file where you want to save data.</param>
/// <returns></returns>
public static void Save <T> ( T data, string filename ) {
if ( IsSerializable <T> ( ) ) {
if ( !Directory.Exists ( GetDirectoryPath ( ) ) )
Directory.CreateDirectory ( GetDirectoryPath ( ) );
BinaryFormatter formatter = new BinaryFormatter ( );
formatter.SurrogateSelector = surrogateSelector;
FileStream file = File.Create ( GetFilePath ( filename ) );
formatter.Serialize ( file, data );
file.Close ( );
}
}
/// <summary>
/// Save data to disk.
/// </summary>
/// <param name="filename">the file where you saved data.</param>
/// <returns></returns>
public static T Load<T> ( string filename ) {
T data = System.Activator.CreateInstance <T> ( );
if ( IsSerializable <T> ( ) ) {
if ( HasSaved ( filename ) ) {
BinaryFormatter formatter = new BinaryFormatter ( );
formatter.SurrogateSelector = surrogateSelector;
FileStream file = File.Open ( GetFilePath ( filename ), FileMode.Open );
data = ( T )formatter.Deserialize ( file );
file.Close ( );
}
}
return data;
}
static bool IsSerializable<T> ( ) {
bool isSerializable = typeof( T ).IsSerializable;
if ( !isSerializable ) {
string type = typeof( T ).ToString ( );
Debug.LogError (
"Class <b><color=white>" + type + "</color></b> is not marked as Serializable, "
+ "make sure to add <b><color=white>[System.Serializable]</color></b> at the top of your " + type + " class."
);
}
return isSerializable;
}
/// <summary>
/// Check if data is saved.
/// </summary>
/// <param name="filename">the file where you saved data</param>
/// <returns></returns>
public static bool HasSaved ( string filename ) {
return File.Exists ( GetFilePath ( filename ) );
}
/// <summary>
/// Delete a data file.
/// </summary>
/// <param name="filename">the file where you saved data</param>
/// <returns></returns>
public static void DeleteDataFile ( string filename ) {
if ( HasSaved ( filename ) )
File.Delete ( GetFilePath ( filename ) );
}
/// <summary>
/// Delete all data files.
/// </summary>
/// <returns></returns>
public static void DeleteAllDataFiles ( ) {
if ( Directory.Exists ( GetDirectoryPath ( ) ) )
Directory.Delete ( GetDirectoryPath ( ), true );
}
/// <summary>
/// Get the path where data is saved.
/// </summary>
/// <returns></returns>
public static string GetDataPath ( ) {
return GetDirectoryPath ( ) + "/";
}
static string GetDirectoryPath ( ) {
return persistentDataPath + "/" + folderName;
}
static string GetFilePath ( string filename ) {
return GetDirectoryPath ( ) + "/" + filename;
}
//Other non-serialized types /// SS: Serialization Surrogate
//Vector2 , Vector3 , Vector4 , Color , Quaternion.
static SurrogateSelector GetSurrogateSelector ( ) {
SurrogateSelector surrogateSelector = new SurrogateSelector ( );
Vector2_SS v2_ss = new Vector2_SS ( );
Vector3_SS v3_ss = new Vector3_SS ( );
Vector4_SS v4_ss = new Vector4_SS ( );
Color_SS co_ss = new Color_SS ( );
Quaternion_SS qu_ss = new Quaternion_SS ( );
surrogateSelector.AddSurrogate ( typeof( Vector2 ), new StreamingContext ( StreamingContextStates.All ), v2_ss );
surrogateSelector.AddSurrogate ( typeof( Vector3 ), new StreamingContext ( StreamingContextStates.All ), v3_ss );
surrogateSelector.AddSurrogate ( typeof( Vector4 ), new StreamingContext ( StreamingContextStates.All ), v4_ss );
surrogateSelector.AddSurrogate ( typeof( Color ), new StreamingContext ( StreamingContextStates.All ), co_ss );
surrogateSelector.AddSurrogate ( typeof( Quaternion ), new StreamingContext ( StreamingContextStates.All ), qu_ss );
return surrogateSelector;
}
class Vector2_SS: ISerializationSurrogate {
//Serialize Vector2
public void GetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context ) {
Vector2 v2 = ( Vector2 )obj;
info.AddValue ( "x", v2.x );
info.AddValue ( "y", v2.y );
}
//Deserialize Vector2
public System.Object SetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector ) {
Vector2 v2 = ( Vector2 )obj;
v2.x = ( float )info.GetValue ( "x", typeof( float ) );
v2.y = ( float )info.GetValue ( "y", typeof( float ) );
obj = v2;
return obj;
}
}
class Vector3_SS: ISerializationSurrogate {
//Serialize Vector3
public void GetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context ) {
Vector3 v3 = ( Vector3 )obj;
info.AddValue ( "x", v3.x );
info.AddValue ( "y", v3.y );
info.AddValue ( "z", v3.z );
}
//Deserialize Vector3
public System.Object SetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector ) {
Vector3 v3 = ( Vector3 )obj;
v3.x = ( float )info.GetValue ( "x", typeof( float ) );
v3.y = ( float )info.GetValue ( "y", typeof( float ) );
v3.z = ( float )info.GetValue ( "z", typeof( float ) );
obj = v3;
return obj;
}
}
class Vector4_SS: ISerializationSurrogate {
//Serialize Vector4
public void GetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context ) {
Vector4 v4 = ( Vector4 )obj;
info.AddValue ( "x", v4.x );
info.AddValue ( "y", v4.y );
info.AddValue ( "z", v4.z );
info.AddValue ( "w", v4.w );
}
//Deserialize Vector4
public System.Object SetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector ) {
Vector4 v4 = ( Vector4 )obj;
v4.x = ( float )info.GetValue ( "x", typeof( float ) );
v4.y = ( float )info.GetValue ( "y", typeof( float ) );
v4.z = ( float )info.GetValue ( "z", typeof( float ) );
v4.w = ( float )info.GetValue ( "w", typeof( float ) );
obj = v4;
return obj;
}
}
class Color_SS: ISerializationSurrogate {
//Serialize Color
public void GetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context ) {
Color color = ( Color )obj;
info.AddValue ( "r", color.r );
info.AddValue ( "g", color.g );
info.AddValue ( "b", color.b );
info.AddValue ( "a", color.a );
}
//Deserialize Color
public System.Object SetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector ) {
Color color = ( Color )obj;
color.r = ( float )info.GetValue ( "r", typeof( float ) );
color.g = ( float )info.GetValue ( "g", typeof( float ) );
color.b = ( float )info.GetValue ( "b", typeof( float ) );
color.a = ( float )info.GetValue ( "a", typeof( float ) );
obj = color;
return obj;
}
}
class Quaternion_SS: ISerializationSurrogate {
//Serialize Quaternion
public void GetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context ) {
Quaternion qua = ( Quaternion )obj;
info.AddValue ( "x", qua.x );
info.AddValue ( "y", qua.y );
info.AddValue ( "z", qua.z );
info.AddValue ( "w", qua.w );
}
//Deserialize Quaternion
public System.Object SetObjectData ( System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector ) {
Quaternion qua = ( Quaternion )obj;
qua.x = ( float )info.GetValue ( "x", typeof( float ) );
qua.y = ( float )info.GetValue ( "y", typeof( float ) );
qua.z = ( float )info.GetValue ( "z", typeof( float ) );
qua.w = ( float )info.GetValue ( "w", typeof( float ) );
obj = qua;
return obj;
}
}
}
|
20118627b46de05250650a425f4ea62b146ea179
|
C#
|
jakub-zieba/more-or-less-game
|
/ClassLibrary/ClassLibrary/QuestionTemplate.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
/// <summary>
/// Zawiera wzór dla pytań używanych w całej aplikacji a także enum będący podstawą
/// mechanik które funkcjonują w klasach operujących na pytaniach
/// </summary>
public enum Answer
{
less,
equals,
more,
}
public class QuestionTemplate
{
public string text;
public Answer correctAnswer;
public int value;
public QuestionTemplate(string _text, Answer _correctAnswer, int _value)
{
text = _text;
correctAnswer = _correctAnswer;
value = _value;
}
}
}
|
84666551b496f082d1ad8d772fd01a22a367c7ae
|
C#
|
mirostanchev/SoftUni-Software-Engineering
|
/CSharp OOP-Advanced/ExercisesAndLabs/Generics-Exercises/07-08-09.CustomList/CustomList.cs
| 4.03125
| 4
|
namespace _07_08_09.CustomList
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class CustomList<T>
where T : IComparable<T>
{
private IList<T> data;
public CustomList()
{
this.data = new List<T>();
}
public CustomList(IList<T> collection)
{
this.data = new List<T>(collection);
}
public void Add(T element)
{
this.data.Add(element);
}
public T Remove(int index)
{
var element = this.data[index];
this.data.RemoveAt(index);
return element;
}
public bool Contains(T element)
{
if (this.data.Contains(element))
{
return true;
}
return false;
}
public void Swap(int index1, int index2)
{
var temp = this.data[index1];
this.data[index1] = this.data[index2];
this.data[index2] = temp;
}
public int CountGreaterThan(T element)
{
int count = 0;
foreach (var item in this.data)
{
if (item.CompareTo(element) > 0)
{
count++;
}
}
return count;
}
public T Max()
{
return this.data.Max();
}
public T Min()
{
return this.data.Min();
}
public string Print()
{
var sb = new StringBuilder();
foreach (var item in this.data)
{
sb.AppendLine(item.ToString());
}
return sb.ToString().Trim();
}
public IList<T> GetCollection()
{
return this.data;
}
}
}
|
f049125f39c7ca6c9a8018beb963011200d82327
|
C#
|
gustavobalbino04/Aula27_28_29_30_CRUD
|
/Program.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
namespace Aula27_28_29_30
{
class Program
{
static void Main(string[] args)
{
Produto produto = new Produto();
produto.Codigo= 1;
produto.Nome = "Air force";
produto.Preco = 399.99f;
produto.Inserir(produto);
produto.Remover("Adiddas");
List<Produto> lista = new List<Produto>();
lista = produto.Ler();
foreach(Produto item in lista){
Console.WriteLine($"R${item.Preco} - Nome{item.Nome}");
}
}
}
}
|
affbc3e17efd064c8786bea41188fdbcf200a1fa
|
C#
|
AhnHyobeom/Temperature-management-program
|
/Temperature management program/Form1.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports; // Add for UART communication
using MySql.Data.MySqlClient; // Add for MySQL
using System.Data.Common;
namespace Temperature_management_program
{
public partial class Form1 : Form
{
String connStr = "Server=127.0.0.1;Uid=root;Pwd=1234;Database=tmp_db;Charset=UTF8";
MySqlConnection conn;
MySqlCommand cmd;
String sql = "";
MySqlDataReader reader;
string datain = ""; // UART로 부터 들어온 data를 읽어 들이는 변수
int[] inputSensorData; // UART로 부터 들어온 data Parsing Array
int inputSensorDataIndex = 0;
DateTime[] dateAry = new DateTime[30]; // for date draw chart
int[] t_room1_arr = new int[30]; // for room1 draw chart
int[] t_room2_arr = new int[30]; // for room2 draw chart
int[] t_room3_arr = new int[30]; // for room2 draw chart
DateTime from_day;
DateTime to_day;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label12_r1_com_state.ForeColor = Color.Red;
label13_r2_com_state.ForeColor = Color.Red;
label15_r3_com_state.ForeColor = Color.Red;
dateTimePicker1_from.CustomFormat = "yyyy-MM-dd";
dateTimePicker1_from.Format = DateTimePickerFormat.Custom;
dateTimePicker2_to.CustomFormat = "yyyy-MM-dd";
dateTimePicker2_to.Format = DateTimePickerFormat.Custom;
inputSensorData = new int[11];
conn = new MySqlConnection(connStr);
conn.Open();
cmd = new MySqlCommand("", conn);
try
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 115200;
serialPort1.Open(); // 예외 처리 집어 넣을것
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("UART Open Execption Error" + Environment.NewLine);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if(datain == "")
{
return;
}
drawChart();
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//datain = serialPort1.ReadExisting(); // STM32로부터 들어온 data를 전부 reading
// 주의할 점은 현재 115200bps로 설정 1char당 약 0.1ms 소요 시간 over에 유의
datain = serialPort1.ReadLine();
this.Invoke(new EventHandler(dataParse));
}
private void dataParse(object sender, EventArgs e)
{
string[] temp = datain.Split(' ');
// 0, 1, 2 -> current tmp 3, 4, 5 -> air conditioner state 6, 7, 8 -> desire tmp
switch (inputSensorDataIndex)
{
case 0:
if(temp.Length != 2 || temp[0] != "cur_room1")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox1_r1_cur_tmp.Text = inputSensorData[0].ToString();
break;
case 1:
if (temp.Length != 2 || temp[0] != "cur_room2")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox4_r2_cur_tmp.Text = inputSensorData[1].ToString();
break;
case 2:
if (temp.Length != 2 || temp[0] != "cur_room3")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox6_r3_cur_tmp.Text = inputSensorData[2].ToString();
saveDB();
break;
case 3:
if (temp.Length != 2 || temp[0] != "stat_room1")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
if (inputSensorData[3] == 0)
{
label12_r1_com_state.Text = "OFF";
label12_r1_com_state.ForeColor = Color.Red;
}
else
{
label12_r1_com_state.Text = "ON";
label12_r1_com_state.ForeColor = Color.Green;
}
break;
case 4:
if (temp.Length != 2 || temp[0] != "stat_room2")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
if (inputSensorData[4] == 0)
{
label13_r2_com_state.Text = "OFF";
label13_r2_com_state.ForeColor = Color.Red;
}
else
{
label13_r2_com_state.Text = "ON";
label13_r2_com_state.ForeColor = Color.Green;
}
break;
case 5:
if (temp.Length != 2 || temp[0] != "stat_room3")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
if (inputSensorData[5] == 0)
{
label15_r3_com_state.Text = "OFF";
label15_r3_com_state.ForeColor = Color.Red;
}
else
{
label15_r3_com_state.Text = "ON";
label15_r3_com_state.ForeColor = Color.Green;
}
break;
case 6:
if (temp.Length != 2 || temp[0] != "dsr_room1")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox2_r1_des_tmp.Text = inputSensorData[inputSensorDataIndex].ToString();
break;
case 7:
if (temp.Length != 2 || temp[0] != "dsr_room2")
{
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox3_r2_des_tmp.Text = inputSensorData[inputSensorDataIndex].ToString();
break;
case 8:
if (temp.Length != 2 || temp[0] != "dsr_room3")
{
inputSensorDataIndex++;
break;
}
inputSensorData[inputSensorDataIndex] = int.Parse(temp[1]);
textBox5_r3_des_tmp.Text = inputSensorData[inputSensorDataIndex].ToString();
break;
case 9:
int mode = 0;
try
{
mode = int.Parse(datain);
inputSensorData[inputSensorDataIndex] = mode;
if (inputSensorData[inputSensorDataIndex] == 1)
{
label19_current_mode.Text = "NORMAL";
label19_current_mode.ForeColor = Color.Green;
}
if (inputSensorData[inputSensorDataIndex] == 2)
{
label19_current_mode.Text = "SETTING";
label19_current_mode.ForeColor = Color.BlueViolet;
}
}
catch (FormatException)
{
MessageBox.Show("Mode Setting FormatException !!!");
}
break;
case 10:
int cycle = 15;
try
{
cycle = int.Parse(datain);
inputSensorData[inputSensorDataIndex] = cycle;
label19_cycle.Refresh();
label19_cycle.Text = (cycle / 15) + "000ms";
}
catch (FormatException)
{
break;
}
break;
default:
break;
}
if (++inputSensorDataIndex >= 11)
{
inputSensorDataIndex = 0;
}
}
private void saveDB()
{
string t_date = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
sql = "INSERT INTO tmp(t_date, t_room1, t_room2, t_room3) VALUES ('";
sql += t_date + "'";
for (int i = 0; i < 3; i++)
{
sql += ", " + inputSensorData[i];
}
sql += ")";
try
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
catch (MySqlException)
{
MessageBox.Show("DB INSERT FAIL!!!");
}
}
private void drawChart()
{
sql = "SELECT t_date, t_room1, t_room2, t_room3 FROM tmp ORDER BY t_date DESC LIMIT 1";
cmd.CommandText = sql;
reader = cmd.ExecuteReader();
reader.Read();
DateTime date = new DateTime();
date = (DateTime)reader["t_date"];
int t_room1 = (int)reader["t_room1"];
int t_room2 = (int)reader["t_room2"];
int t_room3 = (int)reader["t_room3"];
reader.Close();
//한칸씩 당기기
for (int i = 0; i < t_room1_arr.Length - 1; i++)
{
dateAry[i] = dateAry[i + 1];
t_room1_arr[i] = t_room1_arr[i + 1];
t_room2_arr[i] = t_room2_arr[i + 1];
t_room3_arr[i] = t_room3_arr[i + 1];
}
//최신 데이터를 마지막에 넣기
dateAry[dateAry.Length - 1] = date;
t_room1_arr[t_room1_arr.Length - 1] = t_room1;
t_room2_arr[t_room2_arr.Length - 1] = t_room2;
t_room3_arr[t_room3_arr.Length - 1] = t_room3;
//차트 그리기
chart1.Series[0].Points.Clear();
chart1.Series[1].Points.Clear();
chart1.Series[2].Points.Clear();
int index = 0;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Interval = 2;
for (int i = 0; i < t_room1_arr.Length; i++)
{
chart1.Series[0].Points.AddXY(dateAry[i] + " " + index, t_room1_arr[i]);
chart1.Series[1].Points.AddXY(dateAry[i] + " " + index, t_room2_arr[i]);
chart1.Series[2].Points.AddXY(dateAry[i] + " " + index++, t_room3_arr[i]);
}
}
private void button2_db_search_day_Click(object sender, EventArgs e)
{
label19_search_contents.Text = "";
sql = "SELECT t_date, t_room1, t_room2, t_room3 FROM tmp WHERE t_date BETWEEN '";
sql += from_day.Year + "-" + from_day.Month + "-" + from_day.Day + "-00-00-00' AND '";
sql += to_day.Year + "-" + to_day.Month + "-" + to_day.Day + "-23-59-59'";
dbSearchListViewInit();
label19_search_contents.Text = from_day.Year + "-" + from_day.Month + "-" + from_day.Day + "-00-00-00 ~ " +
to_day.Year + "-" + to_day.Month + "-" + to_day.Day + "-23-59-59";
}
private void button3_db_search_advanced_Click(object sender, EventArgs e)
{
label19_search_contents.Text = "";
sql = "SELECT t_date, t_room1, t_room2, t_room3 FROM tmp WHERE t_date BETWEEN '";
string advanced_str = textBox1_db_search_advanced.Text;
advanced_str.Replace(" ", "");
string[] temp = advanced_str.Split('~');
sql += temp[0] + "' AND '";
sql += temp[1] + "'";
dbSearchListViewInit();
label19_search_contents.Text = temp[0] + " ~ " + temp[1];
textBox1_db_search_advanced.Text = "";
}
private void dbSearchListViewInit()
{
try
{
cmd.CommandText = sql;
reader = cmd.ExecuteReader();
// Search ListView 상단 설정
listView1_db_search.Clear();
listView1_db_search.View = View.Details;
listView1_db_search.Columns.Add("시간");
listView1_db_search.Columns.Add("Room#1");
listView1_db_search.Columns.Add("Room#2");
listView1_db_search.Columns.Add("Room#3");
ListViewItem item;
int room1 = 0;
int room2 = 0;
int room3 = 0;
DateTime date = new DateTime();
while (reader.Read())
{
date = (DateTime)reader["t_date"];
room1 = (int)reader["t_room1"];
room2 = (int)reader["t_room2"];
room3 = (int)reader["t_room3"];
item = new ListViewItem(date.ToString());
item.SubItems.Add(room1.ToString());
item.SubItems.Add(room2.ToString());
item.SubItems.Add(room3.ToString());
listView1_db_search.Items.Add(item);
}
// 폭 조절하기 (열 사이즈에 맞춤)
for (int i = 0; i < listView1_db_search.Columns.Count; i++)
{
listView1_db_search.Columns[i].TextAlign = HorizontalAlignment.Center;
listView1_db_search.Columns[i].Width = -2;
}
reader.Close();
}
catch(MySqlException)
{
MessageBox.Show("DB Search FAIL !!!");
}
}
private void dateTimePicker1_from_ValueChanged(object sender, EventArgs e)
{
from_day = dateTimePicker1_from.Value;
}
private void dateTimePicker2_to_ValueChanged(object sender, EventArgs e)
{
to_day = dateTimePicker2_to.Value;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if(trackBar1.Value >= -9 && trackBar1.Value <= 9)
{
serialPort1.WriteLine("room1 0" + trackBar1.Value.ToString() + Environment.NewLine);
}
else
{
serialPort1.WriteLine("room1 " + trackBar1.Value.ToString() + Environment.NewLine);
}
textBox2_r1_des_tmp.Text = trackBar1.Value.ToString();
}
private void trackBar2_Scroll(object sender, EventArgs e)
{
if (trackBar1.Value >= -9 && trackBar1.Value <= 9)
{
serialPort1.WriteLine("room2 0" + trackBar2.Value.ToString() + Environment.NewLine);
}
else
{
serialPort1.WriteLine("room2 " + trackBar2.Value.ToString() + Environment.NewLine);
}
textBox3_r2_des_tmp.Text = trackBar2.Value.ToString();
}
private void trackBar3_Scroll(object sender, EventArgs e)
{
if (trackBar1.Value >= -9 && trackBar1.Value <= 9)
{
serialPort1.WriteLine("room3 0" + trackBar3.Value.ToString() + Environment.NewLine);
}
else
{
serialPort1.WriteLine("room3 " + trackBar3.Value.ToString() + Environment.NewLine);
}
textBox5_r3_des_tmp.Text = trackBar3.Value.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
int cycle = 15;
try
{
cycle = int.Parse(textBox7_interval.Text.ToString());
serialPort1.WriteLine("interval " + cycle.ToString() + Environment.NewLine);
textBox7_interval.Text = "";
}
catch(FormatException)
{
MessageBox.Show("Press Button : FormatException !!!");
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
serialPort1.Close();
}
}
}
|
7e628c16158d613b3a639141ad120bf91a499bff
|
C#
|
danielapochini/desafio-automacao-api
|
/DesafioAutomacaoAPI/Utils/Settings/AppSettings.cs
| 2.625
| 3
|
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace DesafioAutomacaoAPI.Utils.Settings
{
public class AppSettings
{
public Uri BaseUrl { get; set; }
public string Token { get; set; }
public string ConnectionString { get; set; }
public AppSettings()
{
BaseUrl = new Uri(ReturnParamAppSettings("URL_BASE"));
Token = ReturnParamAppSettings("TOKEN");
ConnectionString = ReturnParamAppSettings("CONNECTION_STRING");
}
public static string ReturnParamAppSettings(string nameParam)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
#if DEV
.AddJsonFile($"appsettings.DEV.json", optional: false, reloadOnChange: true)
#endif
#if HML
.AddJsonFile($"appsettings.HML.json", optional: false, reloadOnChange: true)
#endif
.AddEnvironmentVariables()
.Build();
return config[nameParam].ToString();
}
}
}
|
f81abc2eef1e9511350225a9613d9586c55f3e10
|
C#
|
shendongnian/download4
|
/code1/58992-4196573-8838352-2.cs
| 2.609375
| 3
|
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}
|
6b9d2d2874d198ae60bb49ea101b32db652e6b26
|
C#
|
MortezaShoja/Learning-XML
|
/XML/86-06-03 - 3/C#/Server/server.cs
| 2.953125
| 3
|
using System;
using System.Runtime.Remoting;
using General;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels;
namespace Server
{
class CustomerManager: MarshalByRefObject, ICustomerManager
{
public CustomerManager()
{
Console.WriteLine("CustomerManager.constructor: Object created");
}
public Customer getCustomer(int id)
{
Console.WriteLine("CustomerManager.getCustomer): Called");
Customer tmp = new Customer();
tmp.FirstName = "John";
tmp.LastName = "Doe";
tmp.DateOfBirth = new DateTime(1970,7,4);
Console.WriteLine("CustomerManager.getCustomer(): Returning " +
"Customer-Object");
return tmp;
}
}
class ServerStartup
{
static void Main(string[] args)
{
Console.WriteLine ("ServerStartup.Main(): Server started");
HttpChannel chnl = new HttpChannel(1234);
ChannelServices.RegisterChannel(chnl);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(CustomerManager),
"CustomerManager.soap",
WellKnownObjectMode.Singleton);
// the server will keep running until keypress.
Console.ReadLine();
}
}
}
|
40bb2d3cb0b5811a3da78186948de109903142d7
|
C#
|
andry-tino/code-alive
|
/src/src-client/src/ClientSource/sources/Basic.cs
| 2.796875
| 3
|
/// <summary>
/// Andrea Tino - 2018
/// </summary>
namespace CodeAlive.ClientSource.Basic
{
using System;
using System.Threading;
using CodeAlive.Communication.RenderingApi;
internal class SourceRunner : ISource
{
ICommunicationService svc;
int pause; // In ms, 0 = no pause
/// <summary>
/// Creates a new instance of the <see cref="SourceRunner"/> class.
/// </summary>
/// <param name="svc"></param>
/// <param name="pause"></param>
public SourceRunner(ICommunicationService svc, int pause = 0)
{
this.svc = svc;
this.pause = pause;
}
public void Run()
{
// Create an instance (the root object)
//this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Create an instance" });
//this.svc.RenderNewCell(new NewInstanceRenderingRequest() { InstanceId = "root" });
//this.Pause();
// Create an instance
var person = new Person();
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Create an instance" });
this.svc.RenderNewCell(new NewInstanceRenderingRequest() { InstanceId = "Person@person" });
this.Pause();
// Assign a property
person.Name = "Claus";
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Person.Name", SourceInstanceId = "Cell", DstInstanceId = "Person@person" });
this.Pause();
// Assign a property
person.Surname = "Valca";
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Person.Surname", SourceInstanceId = "Cell", DstInstanceId = "Person@person" });
this.Pause();
// Create an instance
var piano = new Instrument();
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Create an instance" });
this.svc.RenderNewCell(new NewInstanceRenderingRequest() { InstanceId = "Instrument@piano" });
this.Pause();
// Assign a property
piano.Name = "Classic Piano";
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Instrument.Name", SourceInstanceId = "Cell", DstInstanceId = "Instrument@piano" });
this.Pause();
// Create an instance
var harmonica = new Instrument();
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Create an instance" });
this.svc.RenderNewCell(new NewInstanceRenderingRequest() { InstanceId = "Instrument@harmonica" });
this.Pause();
// Assign a property
harmonica.Name = "Harmonica";
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Instrument.Name", SourceInstanceId = "Cell", DstInstanceId = "Instrument@harmonica" });
this.Pause();
// Assign a property
person.Instrument1 = piano;
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderReference(new GetReferenceRenderingRequest() { InstanceId = "Instrument@piano", ParentInstanceId = "Person@person" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Person.Instrument1", SourceInstanceId = "Instrument@piano", DstInstanceId = "Person@person" });
this.Pause();
// Assign a property
person.Instrument2 = harmonica;
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Assign a property" });
this.svc.RenderReference(new GetReferenceRenderingRequest() { InstanceId = "Instrument@harmonica", ParentInstanceId = "Person@person" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Person.Instrument2", SourceInstanceId = "Instrument@harmonica", DstInstanceId = "Person@person" });
this.Pause();
// Execute a method returning a value
var result = person.Play();
this.svc.Echo(new DiagnosticRenderingRequest() { Content = "Execute a method returning a value" });
this.svc.RenderInteraction(new InteractionRenderingRequest() { InvocationName = "Person.Play", SourceInstanceId = "Cell", DstInstanceId = "Person@person" });
this.Pause();
}
public void RunOriginal()
{
var person = new Person();
person.Name = "Claus";
person.Surname = "Valca";
var piano = new Instrument();
piano.Name = "Classic Piano";
var harmonica = new Instrument();
harmonica.Name = "Harmonica";
person.Instrument1 = piano;
person.Instrument2 = harmonica;
var result = person.Play();
}
private void Pause()
{
if (this.pause > 0)
{
Thread.Sleep(this.pause);
}
}
#region Types
/// <summary>
/// Represents a person in this program.
/// </summary>
private class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public Instrument Instrument1 { get; set; }
public Instrument Instrument2 { get; set; }
public string Play()
{
var result = "";
if (this.Instrument1 != null)
{
result += this.Instrument1.Play();
}
if (this.Instrument2 != null)
{
result += this.Instrument2.Play();
}
return result;
}
}
/// <summary>
/// Represents an instrument in this program.
/// </summary>
private class Instrument
{
public string Name { get; set; }
public string Play()
{
return $"{this.Name}: Ding Ding Dong";
}
}
#endregion
}
}
|
ad40f08af81c7ebb1e4e2631eef4563c8bba77f3
|
C#
|
hummerd/democode
|
/csharp/MergeTool.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace MergeTool
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 6)
{
PrintHelp();
return 0;
}
try
{
var basePath = GetArg("b", args);
var firstPath = GetArg("f", args);
var secondPath = GetArg("s", args);
var baseCP = GetArg("bcp", args);
var baseEncoding = baseCP == null
? Encoding.UTF8
: Encoding.GetEncoding(int.Parse(baseCP));
var firstCP = GetArg("fcp", args);
var firstEncoding = firstCP == null
? Encoding.UTF8
: Encoding.GetEncoding(int.Parse(firstCP));
var secondCP = GetArg("scp", args);
var secondEncoding = secondCP == null
? Encoding.UTF8
: Encoding.GetEncoding(int.Parse(secondCP));
using (var baseFile = new StreamReader(basePath, baseEncoding))
using (var firstFile = new StreamReader(firstPath, firstEncoding))
using (var secondFile = new StreamReader(secondPath, secondEncoding))
{
var merge = new Merger();
var resultPath = GetArg("r", args);
var resultCP = GetArg("rcp", args);
var resultEncoding = resultCP == null
? Encoding.UTF8
: Encoding.GetEncoding(int.Parse(resultCP));
var result = resultPath != null
? new StreamWriter(resultPath, false, resultEncoding)
: Console.Out;
try
{
merge.Merge(
baseFile,
firstFile,
secondFile,
result);
}
finally
{
if (resultPath != null)
result.Dispose();
}
}
}
catch (Exception ex)
{
//1. Можно добавить логирование ошибки
//2. Можно сделать более подробный анализ ошибки
Console.Error.WriteLine(ex.ToString());
return -1;
}
return 0;
}
private static void PrintHelp()
{
//По хорошему строки надо выносить в ресурсы, но в учебных целях все напишем здесь
var msg = "Использование MergeTool: " + Environment.NewLine +
"MergeTool.exe -b [basePath] -bcp <baseCodePage> -f [firstPath] -fcp <firstCodePage> -s [secondPath] -scp <secondCodePage> -r <resultPath> -rcp <resultCodePage>" + Environment.NewLine +
"basePath - Обязательный параметр. Путь к базовому файлу]" + Environment.NewLine +
"baseCodePage - Опциональный параметр. Кодировка базового файла. По умолчанию UTF8" + Environment.NewLine +
"..." + Environment.NewLine +
"resultPath - Опциональный параметр. Путь к результирующему файлу. По умолчанию результат выводится в консоль." + Environment.NewLine +
"...";
Console.WriteLine(msg);
}
private static string GetArg(string argName, string[] args)
{
var ix = Array.IndexOf(args, "-" + argName);
if (ix < 0)
ix = Array.IndexOf(args, "/" + argName);
if (ix < 0)
return null;
if (ix + 1 >= args.Length)
return null;
return args[ix + 1];
}
}
/// <summary>
/// Всякие общие хелперы
/// </summary>
public static class Util
{
public static List<string> ReadToArray(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
var result = new List<string>();
var line = reader.ReadLine();
int i = 0;
while (line != null)
{
result.Add(line);
line = reader.ReadLine();
}
return result;
}
public static bool IsTrimmedStringsEqual(string str1, string str2)
{
Predicate<char> notWhiteSearch = c => !char.IsWhiteSpace(c);
var symStart1 = FindCharIndex(str1, notWhiteSearch);
var symStart2 = FindCharIndex(str2, notWhiteSearch);
if (symStart1 == -1
&& symStart2 == -1)
return true;
if (symStart1 == -1
|| symStart2 == -1)
return false;
var symEnd1 = FindLastCharIndex(str1, notWhiteSearch);
var symEnd2 = FindLastCharIndex(str2, notWhiteSearch);
var len1 = symEnd1 - symStart1 + 1;
int len2 = symEnd2 - symStart2 + 1;
return string.Compare(str1, symStart1, str2, symStart2, Math.Max(len1, len2)) == 0;
}
public static int FindCharIndex(string str, Predicate<char> predicate)
{
if (predicate == null)
throw new ArgumentNullException("predicate");
if (string.IsNullOrEmpty(str))
return -1;
for (int i = 0; i < str.Length; i++)
{
if (predicate(str[i]))
return i;
}
return -1;
}
public static int FindLastCharIndex(string str, Predicate<char> predicate)
{
if (predicate == null)
throw new ArgumentNullException("predicate");
if (string.IsNullOrEmpty(str))
return -1;
for (int i = str.Length - 1; i >= 0; i--)
{
if (predicate(str[i]))
return i;
}
return -1;
}
public static bool IsSubSetOf<T>(
List<T> contained,
int containedStart,
int containedLength,
List<T> contains,
int containsStart,
int containsLength,
Func<T, T, bool> equal)
{
if (contained == null)
throw new ArgumentNullException("contained");
if (contains == null)
throw new ArgumentNullException("contains");
if (equal == null)
throw new ArgumentNullException("equal");
if (containedStart > contained.Count - 1
|| containedStart + containedLength > contained.Count)
throw new IndexOutOfRangeException("containedStart or containedLength out of range");
if (containsStart > contains.Count - 1
|| containsStart + containsLength > contains.Count)
throw new IndexOutOfRangeException("containsStart or containsLength out of range");
if (containedLength > containsLength)
return false;
var firstContained = contained[containedStart];
var ix = contains.FindIndex(
containsStart,
containsLength,
s => equal(firstContained, s));
if (ix < 0)
return false;
var containsLeft = containsLength - (ix - containsStart);
if (containsLeft < containedLength)
return false;
for (int i = 1; i < containedLength; i++)
{
if (!equal(contains[ix + i], contained[containedStart + i]))
return false;
}
return true;
}
}
/// <summary>
/// Класс для выполнения слияний
/// </summary>
public class Merger
{
private enum LineChange
{
NotChanged,
Added,
Removed,
Cahnged
}
private enum MergeSource
{
Conflict,
First,
Second
}
private class DiffInfo
{
public DiffInfo(int baseLine, int changedLine, LineChange action)
{
BaseLine = baseLine;
ChangedLine = changedLine;
Action = action;
}
public int BaseLine;
public int ChangedLine;
public LineChange Action;
public override string ToString()
{
return BaseLine + " " + ChangedLine + " " + Action;
}
}
private class MergeInfo
{
public MergeInfo(int lineIndex, MergeSource source)
{
LineIndex = lineIndex;
Source = source;
}
public int LineIndex;
public MergeSource Source;
public override string ToString()
{
return LineIndex + " " + Source;
}
}
private bool m_debugMode;
public Merger()
: this(false)
{
}
public Merger(bool debug)
{
m_debugMode = debug;
}
public void Merge(
TextReader baseReader,
TextReader first,
TextReader second,
TextWriter resultWriter)
{
var baseFile = Util.ReadToArray(baseReader);
var firstFile = Util.ReadToArray(first);
var secondFile = Util.ReadToArray(second);
List<DiffInfo> baseToFirst;
List<DiffInfo> baseToSecond;
using (var task1 = Task.Factory.StartNew(() => FindDiff(baseFile, firstFile)))
using (var task2 = Task.Factory.StartNew(() => FindDiff(baseFile, secondFile)))
{
task1.Wait();
task2.Wait();
baseToFirst = task1.Result;
baseToSecond = task2.Result;
}
var resultDiff = MergeDiffs(baseToFirst, firstFile, baseToSecond, secondFile);
WriteResultTo(resultWriter, resultDiff, firstFile, secondFile);
}
private List<DiffInfo> FindDiff(
List<string> baseFile,
List<string> changedFile)
{
var result = new List<DiffInfo>(baseFile.Count + changedFile.Count);
int changeMatchIndex = 0;
for (var baseIndex = 0; baseIndex < baseFile.Count; baseIndex++)
{
var baseLine = baseFile[baseIndex];
var changedIndex = changedFile.FindIndex(changeMatchIndex, ch => Util.IsTrimmedStringsEqual(ch, baseLine));
var diff = new DiffInfo(baseIndex, changedIndex, LineChange.NotChanged);
//Строка не найдена, значит она удалена(либо изменена, но это мы выясним позднее)
if (changedIndex == -1)
{
diff.Action = LineChange.Removed;
}
else
{
//Между строками в измененном файле "дырка", значит строки между baseMatchIndex и changedIndex
//либо изменились, либо добавились
if (changedIndex > changeMatchIndex)
{
var lastAdded = result.FindLastIndex(di => di.ChangedLine != -1) + 1;
//"Дырке" в измененном файле соответствуют некоторые строки в базовом,
//помечаем их как измененные
for (int i = lastAdded; i < result.Count; i++)
{
result[i].ChangedLine = changeMatchIndex++;
result[i].Action = LineChange.Cahnged;
}
//Строки, пропущенные в измененном, помечаем как добавленные
for (int i = changeMatchIndex; i < changedIndex; i++)
{
result.Add(new DiffInfo(-1, i, LineChange.Added));
}
}
changeMatchIndex = changedIndex + 1;
}
result.Add(diff);
}
//Остатки из измененного файла
for (int i = changeMatchIndex; i < changedFile.Count; i++)
{
result.Add(new DiffInfo(-1, i, LineChange.Added));
}
return result;
}
private List<MergeInfo> MergeDiffs(
IList<DiffInfo> baseToFirst,
List<string> first,
IList<DiffInfo> baseToSecond,
List<string> second)
{
var result = new List<MergeInfo>((baseToFirst.Count + baseToSecond.Count)/2);
int firstDiffIndex = 0;
int secondDiffIndex = 0;
while(true)
{
//Добавляем добавленное из первого и второго
var firstAfterAdded = AddAddedLines(firstDiffIndex, result, baseToFirst, MergeSource.First);
var secondAfterAdded = AddAddedLines(secondDiffIndex, result, baseToSecond, MergeSource.Second);
//Обрабатываем случай когда один добавленный блок полностью содержится в
//другом в этом же месте(один добавил метод А, другой метод А и Б)
var addedLenFirst = firstAfterAdded - firstDiffIndex;
var addedLenSecond = secondAfterAdded - secondDiffIndex;
if (addedLenFirst > 0 && addedLenSecond > 0)
{
var secondInFirst = Util.IsSubSetOf(
second,
baseToSecond[secondDiffIndex].ChangedLine,
addedLenSecond,
first,
baseToFirst[firstDiffIndex].ChangedLine,
addedLenFirst,
(s1, s2) => Util.IsTrimmedStringsEqual(s1, s2));
if (secondInFirst)
{
var addedSecond = result.Count - addedLenSecond;
result.RemoveRange(addedSecond, addedLenSecond);
}
else
{
var firstInSecond = Util.IsSubSetOf(
first,
baseToFirst[firstDiffIndex].ChangedLine,
addedLenFirst,
second,
baseToSecond[secondDiffIndex].ChangedLine,
addedLenSecond,
(s1, s2) => Util.IsTrimmedStringsEqual(s1, s2));
if (firstInSecond)
{
var addedFirst = result.Count - addedLenSecond - addedLenFirst;
result.RemoveRange(addedFirst, addedLenFirst);
}
}
}
//Так как мы идем по строчкам из базового файла, то закончатся они одновременно в первом и втором
if (firstAfterAdded >= baseToFirst.Count)
break;
//Теперь обрабатываем изменение строки из базового файла
var firstDiff = baseToFirst[firstAfterAdded];
var secondDiff = baseToSecond[secondAfterAdded];
if (firstDiff.Action == LineChange.NotChanged
&& secondDiff.Action == LineChange.NotChanged)
result.Add(new MergeInfo(firstDiff.ChangedLine, MergeSource.First));
else if (firstDiff.Action == LineChange.Cahnged
&& secondDiff.Action == LineChange.NotChanged)
result.Add(new MergeInfo(firstDiff.ChangedLine, MergeSource.First));
else if (firstDiff.Action == LineChange.NotChanged
&& secondDiff.Action == LineChange.Cahnged)
result.Add(new MergeInfo(secondDiff.ChangedLine, MergeSource.Second));
else if (firstDiff.Action == LineChange.Cahnged
|| secondDiff.Action == LineChange.Cahnged)
{
var bothChanged = firstDiff.Action == LineChange.Cahnged
&& secondDiff.Action == LineChange.Cahnged;
if (bothChanged && Util.IsTrimmedStringsEqual(
first[firstDiff.ChangedLine],
second[secondDiff.ChangedLine]))
{
result.Add(new MergeInfo(firstDiff.ChangedLine, MergeSource.First));
}
else
{
result.Add(new MergeInfo(secondDiff.ChangedLine, MergeSource.Conflict));
}
}
//Остальные случаи это удаление строчки, просто не добавляем ее в результат
firstDiffIndex = firstAfterAdded + 1;
secondDiffIndex = secondAfterAdded + 1;
}
return result;
}
private int AddAddedLines(
int startIndex,
List<MergeInfo> dest,
IList<DiffInfo> diff,
MergeSource source)
{
var i = startIndex;
for (; i < diff.Count; i++)
{
if (diff[i].Action != LineChange.Added)
return i;
dest.Add(new MergeInfo(diff[i].ChangedLine, source));
}
return i;
}
private void WriteResultTo(
TextWriter writer,
IList<MergeInfo> resultDiff,
IList<string> firstFile,
IList<string> secondFile)
{
for (int i = 0; i < resultDiff.Count; i++)
{
var diff = resultDiff[i];
string line;
if (diff.Source == MergeSource.First)
line = firstFile[diff.LineIndex];
else if (diff.Source == MergeSource.Second)
line = secondFile[diff.LineIndex];
else
line = "*Конфликт*";
if (m_debugMode)
{
var prefix = (diff.Source == MergeSource.First ? "f" : "s") + " " + diff.LineIndex;
prefix = prefix.PadRight(5, ' ');
line = prefix + line;
}
writer.WriteLine(line);
}
}
}
}
|
f494606d1aed80379b9276ccaf4f3431c0a1650f
|
C#
|
Didnelpsun/AchieveDream
|
/Objects/Simple.cs
| 2.765625
| 3
|
namespace AchieveDream.Objects
{
public class Simple
{
private int _ID;
private string _Name;
public int ID
{
set
{
_ID = value;
}
get
{
return _ID;
}
}
public string Name
{
set
{
_Name = value;
}
get
{
return _Name;
}
}
public Simple(int id, string name)
{
_ID = id;
_Name = name;
}
}
}
|
446e692fec742a2e28eb5eccaad061bfab2c377a
|
C#
|
Cenaoi/App.Company
|
/Cenaoi.ModelFilter/ModelFilter.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Cenaoi.CModel;
using System.Data.SqlClient;
using Model;
using System.Configuration;
namespace Cenaoi.ModelFilter
{
public class ModelFilter
{
private string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
public Cenaoi.CModel.CModel GetData<T>()
{
Type type = typeof(T);
PropertyInfo[] fields = type.GetProperties();
StringBuilder sql = new StringBuilder();
sql.Append("SELECT ");
int i = 0;
foreach (var field in fields)
{
sql.Append(field.Name);
if (i++ < fields.Length - 1)
{
sql.Append(",");
}
}
sql.Append(" FROM ");
sql.Append(type.Name);
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
Cenaoi.CModel.CModel model = new Cenaoi.CModel.CModel(typeof(C_ACCOUNT));
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
foreach (var field in fields)
{
string f_name = field.Name;
model[f_name] = reader[f_name];
}
}
reader.Close();
return model;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
}
}
|
e4970ad3d7fcd8ab53fc5649122e8d2b6d3b33d7
|
C#
|
chrisa23/Fibrous
|
/Fibrous/Internal/Scheduling/AsyncCronScheduler.cs
| 2.78125
| 3
|
using System;
using System.Threading.Tasks;
using Quartz;
namespace Fibrous
{
internal class AsyncCronScheduler : IDisposable
{
private readonly Func<Task> _action;
private readonly CronExpression _cronExpression;
private readonly IAsyncScheduler _scheduler;
private bool _running = true;
private IDisposable _sub;
//make use of current timespan scheduling
//but with UTC and add hour on ambiguous when time < now
public AsyncCronScheduler(IAsyncScheduler scheduler, Func<Task> action, string cron)
{
_scheduler = scheduler;
_action = async () =>
{
await action();
await ScheduleNextAsync();
};
//parse cron
//find next and schedule
//on next, repeat
//TODO: try parse without and then with seconds
_cronExpression = new CronExpression(cron);
_ = ScheduleNextAsync();
}
public void Dispose()
{
_running = false;
_sub?.Dispose();
#if DEBUG
Console.WriteLine("Dispose");
#endif
}
private Task ScheduleNextAsync()
{
if (!_running)
{
return Task.CompletedTask;
}
DateTimeOffset? next = _cronExpression.GetNextValidTimeAfter(DateTimeOffset.Now);
if (next.HasValue)
{
DateTime utc = next.Value.UtcDateTime;
DateTime now = DateTime.UtcNow;
TimeSpan span = utc - now;
if (!_running)
{
return Task.CompletedTask;
}
_sub = _scheduler.Schedule(_action, span);
#if DEBUG
Console.WriteLine(span);
#endif
}
return Task.CompletedTask;
}
}
}
|
3153505c6e2555e5f030a9d9ea3f8c945476b1ab
|
C#
|
bryant1410/BoC
|
/Src/Commons.InversionOfControl.SimpleInjector/AllowMultipleConstructorResolutionBehavior.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SimpleInjector;
using SimpleInjector.Advanced;
namespace BoC.InversionOfControl.SimpleInjector
{
public class AllowMultipleConstructorResolutionBehavior : IConstructorResolutionBehavior
{
public ConstructorInfo GetConstructor(Type serviceType, Type implementationType)
{
VerifyTypeIsConcrete(implementationType);
return GetSinglePublicConstructor(implementationType);
}
private static void VerifyTypeIsConcrete(Type implementationType)
{
if (!implementationType.IsAbstract && !implementationType.IsArray && implementationType != typeof(object) && !typeof(Delegate).IsAssignableFrom(implementationType))
return;
throw new ActivationException(string.Format("Type {0} should be concrete", implementationType));
}
private static ConstructorInfo GetSinglePublicConstructor(Type implementationType)
{
return (
from ctor in implementationType.GetConstructors()
orderby ctor.GetParameters().Length descending
select ctor)
.First();
}
}
}
|
710f95ee2386bf4e45b47b4b66ba7ebcd20ae099
|
C#
|
DigitalMachinist/artificial-neural-network
|
/ArtificialNeuralNetwork/MLPIntegration/Program.cs
| 3.125
| 3
|
using System;
using ArtificialNeuralNetwork;
namespace MLPIntegration
{
enum Colour { Black, Red, Green, Blue };
class Program
{
static void Main( string[] args )
{
Console.WriteLine( "======================================" );
Console.WriteLine( "MLP Red-Green-Blue Colour Sorting Test" );
Console.WriteLine( "======================================" );
Console.WriteLine();
Console.WriteLine( "=== Training Data ===" );
Console.WriteLine();
// Set up a sufficent set of training data for the perceptron
// Note: This data is a set of colours in RGB format, bounded [0, 255]. The perceptron
// is to be trained to output -1f for colours that are more RED, and output 1f for
// colours that are more BLUE.
float[] RED = new float[] { 1, 0, 0 };
float[] GREEN = new float[] { 0, 1, 0 };
float[] BLUE = new float[] { 0, 0, 1 };
TrainingSet[] trainingData = new TrainingSet[] {
new TrainingSet( new float[] { 0, 0, 255 }, BLUE ),
new TrainingSet( new float[] { 0, 0, 192 }, BLUE ),
new TrainingSet( new float[] { 0, 200, 0 }, GREEN ),
new TrainingSet( new float[] { 243, 80, 59 }, RED ),
new TrainingSet( new float[] { 255, 0, 77 }, RED ),
new TrainingSet( new float[] { 86, 140, 45 }, GREEN ),
new TrainingSet( new float[] { 77, 93, 190 }, BLUE ),
new TrainingSet( new float[] { 255, 98, 89 }, RED ),
new TrainingSet( new float[] { 120, 165, 96 }, GREEN ),
new TrainingSet( new float[] { 208, 0, 49 }, RED ),
new TrainingSet( new float[] { 67, 15, 210 }, BLUE ),
new TrainingSet( new float[] { 134, 243, 210 }, GREEN ),
new TrainingSet( new float[] { 82, 117, 174 }, BLUE ),
new TrainingSet( new float[] { 168, 42, 89 }, RED ),
new TrainingSet( new float[] { 0, 43, 0 }, GREEN ),
new TrainingSet( new float[] { 248, 80, 68 }, RED ),
new TrainingSet( new float[] { 128, 80, 255 }, BLUE ),
new TrainingSet( new float[] { 34, 75, 50 }, GREEN ),
new TrainingSet( new float[] { 228, 105, 116 }, RED )
};
// Dump the training data set
foreach ( TrainingSet data in trainingData )
{
Console.WriteLine(
"DATASET >> Input: (" + data.Inputs[ 0 ] + ", " + data.Inputs[ 1 ] + ", " + data.Inputs[ 2 ] + "), " +
"Output: " + data.Outputs[ 0 ] + ", " + data.Outputs[ 1 ] + ", " + data.Outputs[ 2 ] + ")"
);
}
Console.WriteLine();
Console.WriteLine( "=== Test Results ===" );
Console.WriteLine();
// Set up the MLP and configure its inputs to receive values bounded [0, 255]
// Note: This is to allow the MLP to normalize inputs to the range [0, 1]
MLP testMLP = new MLP( 3, 10, 3, ActivationFunction.Threshold );
testMLP.Inputs[ 0 ].MinValue = 0f;
testMLP.Inputs[ 0 ].MaxValue = 255f;
testMLP.Inputs[ 1 ].MinValue = 0f;
testMLP.Inputs[ 1 ].MaxValue = 255f;
testMLP.Inputs[ 2 ].MinValue = 0f;
testMLP.Inputs[ 2 ].MaxValue = 255f;
// Train the MLP
testMLP.Train( trainingData, 0.1f, 2f, -0.2f, 0.2f );
// Test some arbitrary input to verify the trained node can categorize colours correctly
int repetitions = 1000;
int correctCount = 0;
for ( int i = 0; i < repetitions; i++ )
{
testMLP.Inputs[ 0 ].Value = (int)Helper.Random( 0f, 255f );
testMLP.Inputs[ 1 ].Value = (int)Helper.Random( 0f, 255f );
testMLP.Inputs[ 2 ].Value = (int)Helper.Random( 0f, 255f );
testMLP.Cycle();
// Categorize input colour the old-fashioned way
Colour inputColour = Colour.Black;
if ( testMLP.Inputs[ 0 ].Value > testMLP.Inputs[ 1 ].Value )
{
if ( testMLP.Inputs[ 0 ].Value > testMLP.Inputs[ 2 ].Value )
{
// Input colour is red
inputColour = Colour.Red;
}
else
{
if ( testMLP.Inputs[ 1 ].Value > testMLP.Inputs[ 2 ].Value )
{
// Input colour is green
inputColour = Colour.Green;
}
else
{
// Input colour is blue
inputColour = Colour.Blue;
}
}
}
else
{
if ( testMLP.Inputs[ 1 ].Value > testMLP.Inputs[ 2 ].Value )
{
// Input colour is green
inputColour = Colour.Green;
}
else
{
if ( testMLP.Inputs[ 2 ].Value > testMLP.Inputs[ 0 ].Value )
{
// Input colour is blue
inputColour = Colour.Blue;
}
else
{
// Input colour is red
inputColour = Colour.Red;
}
}
}
// Categorize the output colour from the values of the output terminals
Colour outputColour = Colour.Black;
if ( testMLP.Outputs[ 0 ].Value > 0.9f )
{
outputColour = Colour.Red;
}
else if ( testMLP.Outputs[ 1 ].Value > 0.9f )
{
outputColour = Colour.Green;
}
else if ( testMLP.Outputs[ 2 ].Value > 0.9f )
{
outputColour = Colour.Blue;
}
// Check the answer for correctness
bool correct = ( inputColour == outputColour );
Console.WriteLine(
( ( correct ) ? "CORRECT" : "WRONG" ) + " >> " +
"Input: " + inputColour + ", " +
"Output: " + outputColour + ", " +
"Input Colour: (" + testMLP.Inputs[ 0 ].Value + ", " + testMLP.Inputs[ 1 ].Value + ", " + testMLP.Inputs[ 2 ].Value + "), " +
"Output Signals: (" + testMLP.Outputs[ 0 ].Value + ", " + testMLP.Outputs[ 1 ].Value + ", " + testMLP.Outputs[ 2 ].Value + ")"
);
if ( correct ) correctCount++;
}
float percentCorrect = 100f * (float)correctCount / (float)repetitions;
Console.WriteLine();
Console.WriteLine( percentCorrect + "% ( " + correctCount + " / " + repetitions + " )" );
Console.WriteLine();
Console.WriteLine( "Training Step: " + testMLP.TrainingStep );
Console.WriteLine( "Training Epochs: " + testMLP.TrainingEpochs );
Console.WriteLine( "Training MSE: " + testMLP.TrainingMeanSquaredError );
Console.ReadKey();
}
}
}
|
8cc4d7d08342464a748066fc600aa41a69473520
|
C#
|
pcastrillongr/PabloCastrillon_ExamenEntornos
|
/Examenfinalentornos_pablocastrillon/models/Reptil.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examenfinalentornos_pablocastrillon.models
{
//clase con atributos
class Reptil:Animal
{
string especie;
Boolean venenoso;
public Reptil(string especie, bool venenoso,string nombre, string fechanacimiento, double peso, string comentarios):base( nombre, fechanacimiento, peso, comentarios)
{
this.Especie = especie;
this.Venenoso = venenoso;
}
public string Especie
{
get
{
return especie;
}
set
{
especie = value;
}
}
public bool Venenoso
{
get
{
return venenoso;
}
set
{
venenoso = value;
}
}
public override String ToString()
{
return "nombre:"+Nombre+ "||especie:" +especie+ "||venenoso:" + venenoso + "||fechanacimiento:" + Fechanacimiento + " ||peso:" + Peso+"||comentarios:"+Comentarios;
}
}
}
|
646408116c9ef23fe00e276fe7cfa13f55797950
|
C#
|
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
|
/fulldocset/add/codesnippet/CSharp/p-system.windows.forms.s_120_1.cs
| 2.5625
| 3
|
// Draw the scroll bar in its normal state.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Visual styles are not enabled.
if (!ScrollBarRenderer.IsSupported)
{
this.Parent.Text = "CustomScrollBar Disabled";
return;
}
this.Parent.Text = "CustomScrollBar Enabled";
// Draw the scroll bar track.
ScrollBarRenderer.DrawRightHorizontalTrack(e.Graphics,
ClientRectangle, ScrollBarState.Normal);
// Draw the thumb and thumb grip in the current state.
ScrollBarRenderer.DrawHorizontalThumb(e.Graphics,
thumbRectangle, thumbState);
ScrollBarRenderer.DrawHorizontalThumbGrip(e.Graphics,
thumbRectangle, thumbState);
// Draw the scroll arrows in the current state.
ScrollBarRenderer.DrawArrowButton(e.Graphics,
leftArrowRectangle, leftButtonState);
ScrollBarRenderer.DrawArrowButton(e.Graphics,
rightArrowRectangle, rightButtonState);
// Draw a highlighted rectangle in the left side of the scroll
// bar track if the user has clicked between the left arrow
// and thumb.
if (leftBarClicked)
{
clickedBarRectangle.X = thumbLeftLimit;
clickedBarRectangle.Width = thumbRectangle.X - thumbLeftLimit;
ScrollBarRenderer.DrawLeftHorizontalTrack(e.Graphics,
clickedBarRectangle, ScrollBarState.Pressed);
}
// Draw a highlighted rectangle in the right side of the scroll
// bar track if the user has clicked between the right arrow
// and thumb.
else if (rightBarClicked)
{
clickedBarRectangle.X =
thumbRectangle.X + thumbRectangle.Width;
clickedBarRectangle.Width =
thumbRightLimitRight - clickedBarRectangle.X;
ScrollBarRenderer.DrawRightHorizontalTrack(e.Graphics,
clickedBarRectangle, ScrollBarState.Pressed);
}
}
|
d817489a3101659e16cb498acf967f596068b9fe
|
C#
|
NikhilPinnamaraju/CS_HRMS_WCF
|
/wcfemplib/Empservice.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using System.Reflection;
using emplib;
namespace wcfemplib
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class Empservice : IEmpservice
{
public void addfield(employee emp)
{
AdoConected d = new AdoConected();
d.addfield(emp);
}
public List<employee> GetEmployees()
{
AdoConected d = new AdoConected();
List<employee> lst= d.GetAllemps();
return lst;
}
public void DeleteEmpById(int ecode)
{
AdoConected d = new AdoConected();
d.DeleteEmpById(ecode);
}
public void UpdateEmpById(employee emp)
{
AdoConected d = new AdoConected();
d.UpdateEmpById(emp);
}
public employee GetEmpById(int ecode)
{
AdoConected d = new AdoConected();
employee emp= d.GetEmpById(ecode);
return emp;
}
}
}
|
eebe43022a669460d3ff9870beee278c6ec8a2ad
|
C#
|
fabiomaulo/hunabku
|
/src/EntitiesWithDI/EntitiesWithDI/DI.cs
| 2.640625
| 3
|
using System;
using Castle.Windsor;
namespace EntitiesWithDI
{
public class DI
{
private static IWindsorContainer container;
private DI() {}
public static IWindsorContainer Container
{
get
{
if (container == null)
{
throw new InvalidOperationException("Container was not initialized. Use StackContainer.");
}
return container;
}
}
public static void StackContainer(IWindsorContainer c)
{
container = c;
}
}
}
|
a780d91ff6ca90b80c42768cc865cce1c9da2eb2
|
C#
|
NikolaHadzhiev/Programming-Algorithms
|
/Recursion + Combinatorics/Generate01Vector/Program.cs
| 3.65625
| 4
|
using System;
namespace Generate01Vector
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
int[] vector = new int[number];
Generate(0, vector);
}
private static void Generate(int index, int[] vector)
{
if (index >= vector.Length)
{
Console.WriteLine(string.Join(' ', vector));
return;
}
for (int i = 0; i <= 1; i++)
{
vector[index] = i;
Generate(index + 1, vector);
}
}
}
}
|
feef5eee5c9da559c9144f418e24ec67c365b2d8
|
C#
|
SergiiKholodylo/family-money
|
/FamilyMoneyLib.NetStandard/Storages/Cached/CachedTransactionStorage.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using FamilyMoneyLib.NetStandard.Bases;
using FamilyMoneyLib.NetStandard.Storages.Interfaces;
namespace FamilyMoneyLib.NetStandard.Storages.Cached
{
public class CachedTransactionStorage:ITransactionStorage
{
private bool _isDirty = true;
private IEnumerable<ITransaction> _cache;
private readonly ITransactionStorage _storage;
public CachedTransactionStorage(ITransactionStorage transactionStorage)
{
_storage = transactionStorage;
}
public ITransaction CreateTransaction(ITransaction transaction)
{
var result = _storage.CreateTransaction(transaction);
_isDirty = true;
return result;
}
public ITransaction CreateTransaction(IAccount account, ICategory category, string name, decimal total, DateTime timestamp,
long id, decimal weight, IProduct product, ITransaction parentTransaction)
{
var result = _storage.CreateTransaction(account,category,name,total,timestamp,id,weight,product,parentTransaction);
_isDirty = true;
return result;
}
public void DeleteTransaction(ITransaction transaction)
{
_storage.DeleteTransaction(transaction);
_isDirty = true;
}
public IEnumerable<ITransaction> GetAllTransactions()
{
if (!_isDirty) return _cache;
_cache = _storage.GetAllTransactions();
_isDirty = false;
return _cache;
}
public void UpdateTransaction(ITransaction transaction)
{
_storage.UpdateTransaction(transaction);
_isDirty = true;
}
public void AddChildTransaction(ITransaction parent, ITransaction child)
{
_storage.AddChildTransaction(parent,child);
_isDirty = true;
}
public void DeleteChildrenTransactions(ITransaction parent)
{
_storage.DeleteChildrenTransactions(parent);
_isDirty = true;
}
public void DeleteChildTransaction(ITransaction parent, ITransaction child)
{
_storage.DeleteChildTransaction(parent,child);
_isDirty = true;
}
public void DeleteAllData()
{
_storage.DeleteAllData();
_isDirty = true;
}
}
}
|
98015349a4fc784634d0269014e8d57dad9af5db
|
C#
|
Kobudzik/Projects-advanced_aspects-C-sharp
|
/Design Patterns/Behavioral/1.2 ChainOfResponsibility/1. ChainOfResponsibility/Program.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1.ChainOfResponsibility
{
class Program
{
static void Main(string[] args)
{
// Here I define all of the objects in the chain
Chain chainCalc1 = new AddNumbers();
Chain chainCalc2 = new SubtractNumbers();
// Here I tell each object where to forward the
// data if it can't process the request
chainCalc1.setNextChain(chainCalc2);
// Define the data in the Numbers Object
// and send it to the first Object in the chain
Numbers request = new Numbers(4, 2, "add");
chainCalc1.calculate(request);
request = new Numbers(4, 2, "sub");
chainCalc1.calculate(request);
request = new Numbers(4, 2, "div");
chainCalc1.calculate(request);
Console.ReadKey();
}
}
}
|
36975bfde6009b25f6a528c304754394613d82a8
|
C#
|
Lylat212/asd
|
/Presentacion/Formularios/Form2.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Negocio.Objetos;
namespace Presentacion.Formularios
{
public partial class Form2 : Form
{
private int y = 73;
const int altura = 50;
List<DataSintoma> list;
private int indice = -1;
public Form2()
{
InitializeComponent();
Initcombox();
}
private void Initcombox()
{
this.list = new List<DataSintoma>();
DataSintoma ds1 = new DataSintoma(1, "tos");
this.list.Add(ds1);
DataSintoma ds2 = new DataSintoma(2, "gripe");
this.list.Add(ds2);
cmbsintomas.DataSource = this.list;
cmbsintomas.ValueMember = "id";
cmbsintomas.DisplayMember = "sintoma";
//listo los sintomas;
foreach (var item in this.list)
{
TextBox txt = new TextBox();
txt.Width = 46;
txt.Height = 17;
txt.Location = new Point(40,y);
txt.Text = item.Id.ToString();
txt.Name = item.Id.ToString();
TextBox txt2 = new TextBox();
txt.Width = 46;
txt.Height = 17;
txt.Location = new Point(40, y);
txt.Text = item.Id.ToString();
txt.Name = item.Id.ToString();
this.Controls.Add(txt);
//cuadro de ponderacion
//aumentar la y
}
}
private void button1_Click(object sender, EventArgs e)
{
//int indice = cmbsintomas.SelectedIndex;
if (this.indice != -1)
{
long id = this.list[this.indice].Id;
string sintoma = this.list[this.indice].Sintoma;
MessageBox.Show("id:" + id + " el sintoma es: " + sintoma);
}
//List<>
}
private void cmbsintomas_SelectedIndexChanged(object sender, EventArgs e)
{
this.indice = cmbsintomas.SelectedIndex;
}
}
}
|
60d103b68fd5d281b8eb104eef3107a7563a3300
|
C#
|
Odonno/SimpleEventSourcing
|
/SimpleEventSourcing/InMemoryEventView.cs
| 3.359375
| 3
|
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace SimpleEventSourcing
{
/// <summary>
/// The base class for creating Event View (Read Model of an Event Sourcing architecture).
/// The State is a real live-data updated whenever an observed event is pushed.
/// </summary>
public abstract class InMemoryEventView<TEvent, TState>
where TEvent : SimpleEvent
where TState : class, new()
{
private readonly Subject<TState> _stateSubject = new Subject<TState>();
/// <summary>
/// Gets the current state of the view.
/// </summary>
public TState State { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryEventView{TState}"/> class.
/// </summary>
/// <param name="events">The event stream to listen to in order to update the state.</param>
/// <param name="initialState">The initial state to use in the view; if <c>null</c>, a default value is constructed using <c>new TState()</c>.</param>
protected InMemoryEventView(IObservable<TEvent> events, TState initialState = null)
{
State = initialState ?? new TState();
events.Subscribe(@event =>
{
State = Reduce(State, @event);
_stateSubject.OnNext(State);
});
}
/// <summary>
/// Observes the state of the store.
/// </summary>
/// <returns>An <see cref="IObservable{TState}"/> that can be subscribed to in order to receive updates about state changes.</returns>
public IObservable<TState> ObserveState()
{
return _stateSubject.DistinctUntilChanged();
}
/// <summary>
/// Observes a value derived from the state of the view.
/// </summary>
/// <typeparam name="TPartial">The type of the partial state to be observed.</typeparam>
/// <param name="selector">
/// The mapping function that can be applied to get the desired partial state of type <typeparamref name="TPartial"/> from an instance of <typeparamref name="TState"/>.
/// </param>
/// <returns></returns>
public IObservable<TPartial> ObserveState<TPartial>(Func<TState, TPartial> selector)
{
return _stateSubject.Select(selector).DistinctUntilChanged();
}
/// <summary>
/// Reduces the specified state using the specified event and returns the new state. Does not mutate the current state of the view.
/// Implementations should override this method to provide functionality specific to their use case.
/// </summary>
/// <param name="state">The state to reduce.</param>
/// <param name="event">The event to use for reducing the specified state.</param>
/// <returns>The state that results from applying <paramref name="action"/> on <paramref name="state"/>.</returns>
protected abstract TState Reduce(TState state, TEvent @event);
}
}
|
2cc203b99d9c4e46d637549dd0528ddcd8db7155
|
C#
|
chungminhde/Chess-Chinese-3D
|
/Chess/Assets/Script/ChessPiece/BKing.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BKing : Piece {
public override List<Vector2Int> MoveLocations(Vector2Int gridPoint)
{
List<Vector2Int> locations = new List<Vector2Int>();
if (gridPoint.y == 8)
{
if (gridPoint.x > 3)
{
locations.Add(new Vector2Int(gridPoint.x - 1, gridPoint.y));
}
if (gridPoint.x < 5)
{
locations.Add(new Vector2Int(gridPoint.x + 1, gridPoint.y));
}
locations.Add(new Vector2Int(gridPoint.x, gridPoint.y + 1));
}
if (gridPoint.y == 9)
{
if (gridPoint.x > 3)
{
locations.Add(new Vector2Int(gridPoint.x - 1, gridPoint.y));
}
if (gridPoint.x < 5)
{
locations.Add(new Vector2Int(gridPoint.x + 1, gridPoint.y));
}
locations.Add(new Vector2Int(gridPoint.x, gridPoint.y + 1));
locations.Add(new Vector2Int(gridPoint.x, gridPoint.y - 1));
}
if (gridPoint.y == 10)
{
if (gridPoint.x > 3)
{
locations.Add(new Vector2Int(gridPoint.x - 1, gridPoint.y));
}
if (gridPoint.x < 5)
{
locations.Add(new Vector2Int(gridPoint.x + 1, gridPoint.y));
}
locations.Add(new Vector2Int(gridPoint.x, gridPoint.y - 1));
}
return locations;
}
}
|
7deecd808a9fece97f53f562768f1ec4c4761bf2
|
C#
|
BerryBlum/tech_academy_c_sharp_projects
|
/carRentalApplication/carRentalApplication/Controllers/HomeController.cs
| 2.6875
| 3
|
using carRentalApplication.Models;
using System;
using System.Web.Mvc;
namespace carRentalApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
[HttpPost]
public ActionResult GetQuote(string firstName, string lastName, string emailAddress,
string dateOfBirth, int speedingTickets, int carYear,
string carMake, string carModel, int insuranceCoverage = 0, int underInfluence = 0) //parse for actual date for dateofbirth from string
{
if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName) || string.IsNullOrEmpty(emailAddress) || string.IsNullOrEmpty(dateOfBirth))
{
return View("~/Views/Shared/Error.cshtml");
}
else
{
using (db_carRentalEntities db = new db_carRentalEntities())
{
var getQuote = new rentalChart();
getQuote.FirstName = firstName;
getQuote.LastName = lastName;
getQuote.EmailAddress = emailAddress;
getQuote.DateOfBirth = dateOfBirth;
getQuote.UnderInfluence = underInfluence;
getQuote.SpeedingTickets = speedingTickets;
getQuote.CarMake = carMake;
getQuote.CarModel = carModel;
getQuote.CarYear = carYear;
getQuote.FullCoverage = insuranceCoverage;
getQuote.MonthlyTotal = MonthlyTotal(getQuote.DateOfBirth, getQuote.SpeedingTickets, getQuote.CarMake, getQuote.CarModel, getQuote.CarYear, getQuote.UnderInfluence, getQuote.FullCoverage);
db.rentalCharts.Add(getQuote);
db.SaveChanges();
return View("GetQuote", getQuote);
}
}
}
private static decimal MonthlyTotal(string dateOfBirth, int speedingTickets, string carMake,
string carModel, int carYear, int underInfluence = 0, int fullCoverage = 0)
{
string birth = dateOfBirth;
TimeSpan span = DateTime.Now - DateTime.Parse(birth);
int age = Convert.ToInt32(span.Days / 365);
decimal total = 50;
if (16 <= age && age < 18)
{
total += 100;
}
else if (18 <= age && age < 25)
{
total += 25;
}
else if (100 <= age)
{
total += 25;
}
else if (age < 16)
{
return total;
}
if (carYear < 2000)
{
total += 25;
}
else if (2015 <= carYear)
{
total += 25;
}
total += speedingTickets * 10;
if (carMake.ToLower() == "porsche")
{
if (carModel.ToLower() == "911 carrera")
{
total += 25;
}
total += 25;
}
if (underInfluence != 0)
{
total = Convert.ToDecimal(decimal.ToDouble(total) * 1.25);
}
if (fullCoverage != 0)
{
total = Convert.ToDecimal(decimal.ToDouble(total) * 1.5);
}
return total;
}
}
}
|
b8e2cf784bab7d4e03f1b4687885361cf70d68e8
|
C#
|
prbarcelon/GwApiNET
|
/GwApiNET/GwApiNET/IApiRequestHandler.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GwApiNET.ResponseObjects;
using RestSharp;
namespace GwApiNET
{
/// <summary>
/// Interface definition to handle api requests.
/// </summary>
/// <typeparam name="T">Expected object that will be parsed</typeparam>
public interface IApiRequestHandler<T> where T : ResponseObject
{
/// <summary>
/// api parser
/// </summary>
IApiResponseParser<T> Parser { get; set; }
/// <summary>
/// ignore cache forces an updated GW2 response
/// </summary>
bool IgnoreCache { get; set; }
/// <summary>
/// request handler. retrives a response using the IApiRequest
/// </summary>
/// <param name="request">request</param>
/// <returns>ResponseObject for the given request</returns>
T HandleRequest(IApiRequest request);
/// <summary>
/// Network handler to use when handling the request.
/// This is only used if IgnoreCache = true or the cache has no
/// valid ResponseObject
/// </summary>
INetworkHandler Network { get; set; }
}
/// <summary>
/// Interface definition to handle api requests.
/// </summary>
/// <typeparam name="T">Expected object that will be parsed</typeparam>
public interface IApiRequestHandlerAsync<T> : IApiRequestHandler<T> where T : ResponseObject
{
/// <summary>
/// Asynchronous parser.
/// </summary>
IApiResponseParserAsync<T> AsyncParser { get; set; }
/// <summary>
/// Asynchronous request handler
/// </summary>
/// <param name="request">api request</param>
/// <returns>requested ResponseObject of type T</returns>
Task<T> HandleRequestAsync(IApiRequest request);
}
/// <summary>
/// Asynchronous parser interface
/// </summary>
/// <typeparam name="T">ResponseObject type</typeparam>
public interface IApiResponseParserAsync<T> : IApiResponseParser<T>
{
/// <summary>
/// Parses the response object.
/// </summary>
/// <param name="apiResponse">raw response from the GW2 Server</param>
/// <returns>Parsed object</returns>
Task<T> ParseAsync(object apiResponse);
}
/// <summary>
/// Response Parser Interface definition.
/// <remarks>Each GW2 API response will likely have it's own IApiResponseParser{T}</remarks>
/// </summary>
/// <typeparam name="T">Expected output object</typeparam>
public interface IApiResponseParser<out T>
{
/// <summary>
/// Parses the response object.
/// </summary>
/// <param name="apiResponse">raw response from the GW2 Server</param>
/// <returns>Parsed object</returns>
T Parse(object apiResponse);
}
}
|
c07b698560f503a96cfdd61177051147c0abac2d
|
C#
|
XDelenclos/Exercice-c-
|
/ExoCSharp2/menu 3/Program.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Multiples(int Cadre, string CouleurTxt)
{
int Chiffre, Multiplicateur, i;
Chiffre = GetInteger("Saisissez votre chiffre :", CouleurTxt);
Multiplicateur = GetInteger("Saisissez votre multiplicateur :", CouleurTxt);
string[] Enonce = { Convert.ToString("Vous souhaitez multiplier " + Chiffre + " par " + Multiplicateur + " :") };
string[] BdPage = new string[Multiplicateur];
i = 1;
while (i <= Multiplicateur)
{
BdPage[(i-1)] = (Chiffre + " x " + i + " = " + Convert.ToString(Chiffre * i));
i++;
}
Console.Clear();
Faire1tablo("Table de Multiplication", BdPage, Enonce, Cadre, CouleurTxt);
}
static void Somme_Moyenne(int Cadre, string CouleurTxt)
{
string[] Enonce = { "Vous avez choisi de calculer la somme et la moyenne des valeurs suivantes :", "" };
int i = 0;
int boucle = GetInteger("Combien souhaitez vous entrer de valeur? ", CouleurTxt);
int[] TabTemp = new int[boucle];
int somme = 0;
int saisie = 0;
while (i != boucle)
{
saisie = GetInteger("Saisissez un chiffre :", CouleurTxt);
TabTemp[i] = saisie;
somme = somme + TabTemp[i];
i++;
}
foreach (int val in TabTemp)
{ Enonce[1] += (val + " "); }
int moyenne = somme / boucle;
string[] BdPage = { Convert.ToString("La somme de vos valeurs est de : " + somme + " et la moyenne est de : " + moyenne) };
Console.Clear();
Faire1tablo("Somme et Moyenne.",BdPage ,Enonce, Cadre, CouleurTxt);
}
static void NbCaractere(int Cadre, string CouleurTxt)
{
string Phrase = GetString("Entrez une phrase : ", CouleurTxt);
char Lettre = Convert.ToChar(GetString("Quelle lettre souhaitez vous compter ? ", CouleurTxt));
int NbLettre = 0;
string[] Enonce = { "Vous avez choisi de rechercher", "La lettre : " +Lettre, "Dans le texte : "+Phrase };
foreach (char lettre in Phrase)
{
if (Lettre == lettre)
{ NbLettre++; }
}
string[] BdPage = { "Il y a " + NbLettre + " fois", "la lettre " + Lettre , "dans le texte : " + Phrase };
Console.Clear();
Faire1tablo("Nombre de caractère.", BdPage, Enonce, Cadre, CouleurTxt);
}
static int NbVoyelle(string CouleurTxt)
{
string Voyelle = "aeiouyAEIOUYéèàäâêëïîôùöò";
string Phrase, c;
int NbLettre;
Phrase = GetString("Saisie de la phrase :", CouleurTxt);
NbLettre = 0;
for (int i = 0; i < Phrase.Length; i++)
{
c = Phrase.Substring(i, 1);
for (int o = 0; o < Voyelle.Length; o++)
{
if (c == Voyelle.Substring(o, 1))
{
NbLettre++;
}
}
}
return NbLettre;
}
static string Repetition(char C, int Longueur)
{
string Caracteres = new string(C, Longueur);
return Caracteres;
}
static string GetString(string Phrase, string CouleurTxt)
{
ColorIn(Phrase, CouleurTxt);
string PhraseLu = Console.ReadLine();
return PhraseLu;
}
static int GetInteger(string Phrase, string CouleurTxt)
{
ColorIn(Phrase, CouleurTxt);
Console.WriteLine();
int NombreLu = Convert.ToInt32(Console.ReadLine());
return NombreLu;
}
static string ColorIn(string TxT, string CouleurTxt)//System.ConsoleColor c
{
ConsoleColor color;
Enum.TryParse(CouleurTxt, out color);
Console.ForegroundColor = color;
Console.Write(TxT);
return TxT;
}
static int LongMax(string[] Txt)
{
int NbCarac = 0; // nbre de caractères de la chaine
int Size = 0; // nbre max de caractères dans les chaines
foreach (string Phrase in Txt)
{
NbCarac = Phrase.Length;
if (Size < NbCarac)
{
Size = NbCarac;
}
}
return Size;
}
/*static void CalculEspace()
{
}*/
static int Faire1Choix(string CouleurTxt)
{
int UserChoice = GetInteger("Saisissez votre choix :", CouleurTxt);
return UserChoice;
}
static int MaxDe(int a, int b)
{
if (a > b)
return a;
else
return b;
}
static int LongTxt(string Ligne)
{
int Size = 0;
return Size;
}
static void Faire1tablo(string Titre, string[] BdPage, string[] TxtAfficher, int Cadre, string CouleurTxt)
{
char[][] Contour = new char[4][];
Contour[0] = new char[] { '\u250c' /* ┌ */, '\u2500' /* ─ */, '\u2510' /* ┐ */, '\u2502' /* │ */, '\u2514' /* └ */, '\u2518' /* ┘ */, '\u251c' /* ├ */, '\u2524' /* ┤ */};
Contour[1] = new char[] { '\u2553' /* ╓ */, '\u2500' /* ─ */, '\u2556' /* ╖ */, '\u2551' /* ║ */, '\u2559' /* ╙ */, '\u255c' /* ╜ */, '\u255f' /* ╟ */, '\u2562' /* ╢ */};
Contour[2] = new char[] { '\u2554' /* ╔ */, '\u2550' /* ═ */, '\u2557' /* ╗ */, '\u2551' /* ║ */, '\u255a' /* ╚ */, '\u255d' /* ╝ */, '\u2560' /* ╠ */, '\u2563' /* ╣ */}; // angle inf gauche
Contour[3] = new char[] { '\u2552' /* ╒ */, '\u2550' /* ═ */, '\u2555' /* ╕ */, '\u2502' /* │ */, '\u2558' /* ╘ */, '\u255b' /* ╛ */, '\u255e' /* ╞ */, '\u2561' /* ╡ */}; // angle inf droit
//Centrage Titre
int EspaceMax = MaxDe((LongMax(TxtAfficher)), (LongMax(BdPage)));
int EspaceAvantTitre = (( EspaceMax - Titre.Length + 2) / 2);
int EspaceApresTitre = EspaceMax - EspaceAvantTitre - Titre.Length +2;
//Centrage Bas de page
int EspaceAvantBdP = ((EspaceMax - BdPage.Length + 2) / 2);
int EspaceApresBdP = EspaceMax - EspaceAvantBdP - BdPage.Length + 2;
// 1ère ligne du Cadre
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][0])
+ (Convert.ToString(Repetition(Contour[Convert.ToInt32(Cadre)][1], LongMax(TxtAfficher) + 2))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][2])))
, CouleurTxt
);
Console.WriteLine();
// Affichage du Titre
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][3])
+ (Repetition(' ', (EspaceAvantTitre))
+ Titre
+ (Repetition(' ', (EspaceApresTitre))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][3]))))
, CouleurTxt
);
Console.WriteLine();
//Affichage intersection
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][6])
+ (Convert.ToString(Repetition(Contour[Convert.ToInt32(Cadre)][1], LongMax(TxtAfficher) + 2))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][7])))
, CouleurTxt
);
Console.WriteLine();
// Affichage du Contenu
foreach (string ligne in TxtAfficher)
{
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][3])
+ " "
+ ligne
+ (Repetition(' ', (LongMax(TxtAfficher) - ligne.Length))
+ " "
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][3])))
, CouleurTxt
);
Console.WriteLine();
}
//Affichage intersection
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][6])
+ (Convert.ToString(Repetition(Contour[Convert.ToInt32(Cadre)][1], LongMax(TxtAfficher) + 2))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][7])))
, CouleurTxt
);
Console.WriteLine();
//Affichage bas de page
foreach (string ligne in BdPage)
{
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][3])
+ (Repetition(' ', EspaceAvantBdP)
+ " "
+ ligne
+ " "
+ (Repetition(' ', (EspaceApresBdP))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][3]))))
, CouleurTxt
);
Console.WriteLine();
}
// Dernière ligne du Cadre
ColorIn(
Convert.ToString(Contour[Convert.ToInt32(Cadre)][4])
+ (Convert.ToString(Repetition(Contour[Convert.ToInt32(Cadre)][1], LongMax(TxtAfficher) + 2))
+ (Convert.ToString(Contour[Convert.ToInt32(Cadre)][5])))
, CouleurTxt
);
Console.WriteLine();
}
static void MenuPrincipal(int Cadre, string CouleurTxt)
{
int UserChoice = 0;
string[] Contenu = { "1. Option.", "2. Multiples.", "3. Somme et Moyenne.", "4. Recherche du nombre de voyelle.", "5. Recherche du nombre des caractères suivants." };
string[] BdPage = { "V1.0 Menu\u00a9" };
Faire1tablo("Menu Principal", BdPage , Contenu, Cadre, CouleurTxt);
UserChoice = Faire1Choix(CouleurTxt);
switch (UserChoice)
{
case 1:
Console.Clear();
Option(Cadre, CouleurTxt);
break;
case 2:
Console.Clear();
Multiples(Cadre, CouleurTxt);
break;
case 3:
Console.Clear();
Somme_Moyenne(Cadre, CouleurTxt);
Console.ReadLine();
break;
case 4:
Console.Clear();
NbVoyelle(CouleurTxt);
break;
case 5:
Console.Clear();
NbCaractere(Cadre, CouleurTxt);
break;
default:
Console.Clear();
Console.WriteLine("Saisie invalide, veuillez recommencer");
MenuPrincipal(Cadre, CouleurTxt);
break;
}
}
static void Option(int Cadre, string CouleurTxt)
{
int UserChoice = 0;
string[] ContenuOption = { "1. Paramètrage de la Couleur", "2. Choix du Cadre" };
string[] BdPage = { "V1.0 Menu\u00a9" };
Faire1tablo("Option Générale.", BdPage, ContenuOption, Cadre, CouleurTxt);
UserChoice = Faire1Choix(CouleurTxt);
// switch (UserChoice)
{
//case 1:
}
}
static void Main()
{
//Valeur par défaut
string CouleurTxt = "White";
int SelectionDuCadre = 0;
MenuPrincipal(SelectionDuCadre, CouleurTxt);/*
string[] Couleur = { "White", "Green", "DarkGray", "Red" };
string[] Titre = { "Menu Principal", "Option", "Multiples", "Somme et Moyenne.", "Recherche du nombre de voyelle.", "Recherche du nombre des caractères suivants." };
int Choix;
int ColorTxt = 0;
Console.WriteLine("Choix du Cadre");
Choix = Faire1Choix();
switch (Choix)
{
case 1:
SelectionDuCadre = 0;
break;
case 2:
SelectionDuCadre = 1;
break;
case 3:
SelectionDuCadre = 2;
break;
case 4:
SelectionDuCadre = 3;
break;
default:
Console.WriteLine("Sélection non valide, retour au menu principal");
break;
}
Console.WriteLine("Choix de la couleur:");
Choix = Faire1Choix();
switch (Choix)
{
case 0:
ColorTxt = 0;
break;
case 1:
ColorTxt = 1;
break;
case 2:
ColorTxt = 2;
break;
case 3:
ColorTxt = 3;
break;
default:
ColorTxt = 0;
break;
}
Faire1tablo("Somme et Moyenne", "/u2666 V1.0 Menu /u169 /u2666", Contenu, SelectionDuCadre, Couleur[ColorTxt]);*/
}
}
|
3f0f89fb0deacbf50fc4758c64de854588cd6867
|
C#
|
EliasDeMa/MediaCollection
|
/MediaCollection/Services/PhotoService.cs
| 2.609375
| 3
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MediaCollection.Services
{
public class PhotoService : IPhotoService
{
private readonly IWebHostEnvironment _hostEnvironment;
public PhotoService(IWebHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
public string AddPhoto(IFormFile photo)
{
string uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(photo.FileName);
var path = Path.Combine(_hostEnvironment.WebRootPath, "imgs", uniqueFileName);
using var stream = new FileStream(path, FileMode.Create);
photo.CopyTo(stream);
return "/imgs/" + uniqueFileName;
}
public void DeletePhoto(string fileName)
{
var prevPath = Path.Combine(_hostEnvironment.WebRootPath, "imgs", fileName.Replace("/imgs/", ""));
System.IO.File.Delete(prevPath);
}
}
}
|
e9b98a65cf7d8709e48756d457fece215d6e4218
|
C#
|
kenny5660/C-sharp
|
/Redactor_Vector_Graph/Redactor_Vector_Graph/Figure_class.cs
| 2.65625
| 3
|
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace Redactor_Vector_Graph {
[DataContract]
public class PointW {
public static double zoom = 1;
public static Point offset = new Point(0, 0);
[DataMember] public double X;
[DataMember] public double Y;
public PointW(double setX, double setY) {
X = setX;
Y = setY;
}
public PointW(int setX, int setY) {
ToPointW(new Point(setX, setY));
}
public PointW() {
X = 0;
Y = 0;
}
public void ToPointW(Point point) {
X = (point.X - offset.X) / zoom;
Y = (point.Y - offset.Y) / zoom;
}
public static PointW ScrnToPointW(Point point) {
return new PointW((point.X - offset.X) / zoom, (point.Y - offset.Y) / zoom);
}
public Point ToScrPnt() {
return new Point((int)Math.Round(X * zoom) + offset.X, (int)Math.Round(Y * zoom) + offset.Y);
}
public PointW Clone() {
return new PointW(X, Y);
}
}
[KnownType(typeof(PolyLine))]
[KnownType(typeof(Line))]
[KnownType(typeof(RectangularFigure))]
[KnownType(typeof(Rect))]
[KnownType(typeof(RoundedRect))]
[KnownType(typeof(Ellipse))]
[DataContract]
public abstract class Figure {
public List<Anchor> anchorArray = new List<Anchor>(8);
public Dictionary<string, Prop> propArray = new Dictionary<string, Prop>(5);
[DataMember] public Color colorFill;
[DataMember] public Color colorPen;
[DataMember] public float widthPen;
[DataMember] public PointW startPointW;
[DataMember] public PointW endPointW;
[DataMember] public bool isFill = false;
[DataMember] public bool isSelected = false;
public Rectangle rectColider;
public virtual void Draw(Graphics graphics) { }
public virtual void Move(PointW offset) { }
public virtual void AddPoint(PointW pointW) { }
public virtual bool SelectPoint(Point pntClick) { return false; }
public virtual void DrawColider(Graphics graphics) { }
public virtual bool SelectArea(Rectangle area) { return false; }
public virtual void Load() { }
public virtual string ToSvgFormat() { return ""; }
}
[DataContract]
public class PolyLine : Figure {
[DataMember] public List<PointW> pointsArray = new List<PointW>(10);
public PolyLine(Pen setPen, PointW start) {
colorPen = setPen.Color;
widthPen = setPen.Width;
pointsArray.Add(start);
Load();
}
public override void Load() {
anchorArray = new List<Anchor>(8);
propArray = new Dictionary<string, Prop>(5);
for (int i = 0; i <= pointsArray.Count - 1; i++) {
anchorArray.Add(new Anchor(pointsArray, i, SetMaxMin));
}
startPointW = pointsArray[0].Clone();
endPointW = new PointW(0.0, 0.0);
foreach (var pointW in pointsArray) {
startPointW.X = Math.Min(startPointW.X, pointW.X);
startPointW.Y = Math.Min(startPointW.Y, pointW.Y);
endPointW.X = Math.Max(endPointW.X, pointW.X);
endPointW.Y = Math.Max(endPointW.Y, pointW.Y);
}
propArray.Add("PropColor", new PropColor(Color.Black));
propArray.Add("PropPenWidth", new PropPenWidth());
((PropColor)propArray["PropColor"]).colorButton.color = colorPen;
((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth = widthPen;
}
public override bool SelectPoint(Point pntClick) {
const int dist = 20;
foreach (PointW pointW in pointsArray) {
if ((Math.Pow(pointW.ToScrPnt().X - pntClick.X, 2.0) + Math.Pow(pointW.ToScrPnt().Y - pntClick.Y, 2.0)) <= dist * dist) {
isSelected = true;
return true;
}
}
isSelected = false;
return false;
}
public override void Move(PointW offset) {
foreach (PointW pointW in pointsArray) {
pointW.X += offset.X;
pointW.Y += offset.Y;
}
}
public override bool SelectArea(Rectangle area) =>
area.Contains(startPointW.ToScrPnt()) && area.Contains(endPointW.ToScrPnt());
public override void AddPoint(PointW pointW) {
pointsArray.Add(pointW);
startPointW.X = Math.Min(startPointW.X, pointW.X);
startPointW.Y = Math.Min(startPointW.Y, pointW.Y);
endPointW.X = Math.Max(endPointW.X, pointW.X);
endPointW.Y = Math.Max(endPointW.Y, pointW.Y);
anchorArray.Add(new Anchor(pointsArray, pointsArray.Count - 1, SetMaxMin));
}
public void SetMaxMin(PointW pointW) {
startPointW.X = Math.Min(startPointW.X, pointW.X);
startPointW.Y = Math.Min(startPointW.Y, pointW.Y);
endPointW.X = Math.Max(endPointW.X, pointW.X);
endPointW.Y = Math.Max(endPointW.Y, pointW.Y);
}
public override void Draw(Graphics graphics) {
colorPen = ((PropColor)propArray["PropColor"]).colorButton.color;
widthPen = ((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth;
Pen pen = new Pen(colorPen);
pen.Width = widthPen;
PointW lastPointW = pointsArray[0];
foreach (PointW pointW in pointsArray) {
graphics.DrawLine(pen, pointW.ToScrPnt(), lastPointW.ToScrPnt());
lastPointW = pointW;
}
}
public override void DrawColider(Graphics graphics) {
if (isSelected) {
foreach (Anchor anchor in anchorArray) {
anchor.Draw(graphics);
}
}
}
public override string ToSvgFormat() {
string str = "<polyline points='";
foreach(var PointW in pointsArray) {
str += PointW.ToScrPnt().X+","+PointW.ToScrPnt().Y+" ";
}
str += "' stroke-width='" + widthPen + "' stroke='" + ColorTranslator.ToHtml(colorPen) + "' fill = 'none'/> ";
return str;
}
}
[Serializable]
public class Line : Figure {
public Line(Pen setPen, PointW start) {
colorPen = setPen.Color;
widthPen = setPen.Width;
startPointW = start;
Load();
}
public override void Load() {
anchorArray = new List<Anchor>(8);
propArray = new Dictionary<string, Prop>(5);
anchorArray.Add(new Anchor(ref startPointW));
anchorArray.Add(new Anchor(ref endPointW));
propArray.Add("PropColor", new PropColor(Color.Black));
propArray.Add("PropPenWidth", new PropPenWidth());
((PropColor)propArray["PropColor"]).colorButton.color = colorPen;
((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth = widthPen;
}
public override void Move(PointW offset) {
startPointW.X += offset.X;
startPointW.Y += offset.Y;
endPointW.X += offset.X;
endPointW.Y += offset.Y;
}
public override bool SelectPoint(Point pntClick) {
const int dist = 20;
double A, B, C, distToline, distToEndPoint, distToSatrtPoint, lineLength;
A = startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y;
B = endPointW.ToScrPnt().X - startPointW.ToScrPnt().X;
C = -(startPointW.ToScrPnt().X * A + startPointW.ToScrPnt().Y * B);
lineLength = Math.Sqrt(Math.Pow(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X, 2.0) + Math.Pow(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y, 2.0));
distToline = (Math.Abs(A * pntClick.X + B * pntClick.Y + C) / (Math.Sqrt(A * A + B * B)));
distToSatrtPoint = Math.Sqrt(Math.Pow(startPointW.ToScrPnt().X - pntClick.X, 2.0) + Math.Pow(startPointW.ToScrPnt().Y - pntClick.Y, 2.0)) - lineLength;
distToEndPoint = Math.Sqrt(Math.Pow(endPointW.ToScrPnt().X - pntClick.X, 2.0) + Math.Pow(endPointW.ToScrPnt().Y - pntClick.Y, 2.0)) - lineLength;
if (distToline <= dist && distToSatrtPoint < dist && distToEndPoint < dist) {
isSelected = true;
return true;
}
isSelected = false;
return false;
}
public override bool SelectArea(Rectangle area) =>
area.Contains(startPointW.ToScrPnt()) && area.Contains(endPointW.ToScrPnt());
public override void AddPoint(PointW pointW) {
endPointW = pointW;
anchorArray[0] = new Anchor(ref startPointW);
anchorArray[1] = new Anchor(ref endPointW);
}
public override void Draw(Graphics graphics) {
colorPen = ((PropColor)propArray["PropColor"]).colorButton.color;
widthPen = ((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth;
Pen pen = new Pen(colorPen);
pen.Width = widthPen;
graphics.DrawLine(pen, startPointW.ToScrPnt(), endPointW.ToScrPnt());
}
public override void DrawColider(Graphics graphics) {
if (isSelected) {
anchorArray[0].Draw(graphics);
anchorArray[1].Draw(graphics);
}
}
public override string ToSvgFormat() {
return "<line x1='"+startPointW.ToScrPnt().X+ "' y1='" + startPointW.ToScrPnt().Y + "' x2='" + endPointW.ToScrPnt().X + "' y2='" + endPointW.ToScrPnt().Y + "' stroke-width='"+widthPen+ "' stroke='"+ ColorTranslator.ToHtml(colorPen) + "'/> ";
}
}
[DataContract]
public class RectangularFigure : Figure {
public override void Load() {
anchorArray = new List<Anchor>(8);
propArray = new Dictionary<string, Prop>(5);
anchorArray.Add(new Anchor(ref startPointW));
anchorArray.Add(new Anchor(ref endPointW));
propArray.Add("PropColor", new PropColor(Color.Black));
propArray.Add("PropPenWidth", new PropPenWidth());
propArray.Add("PropFill", new PropFill(Color.Black));
((PropColor)propArray["PropColor"]).colorButton.color = colorPen;
((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth = widthPen;
((PropFill)propArray["PropFill"]).propColor.colorButton.color = colorFill;
((PropFill)propArray["PropFill"]).checkBox.Checked = isFill;
}
public override void Move(PointW offset) {
startPointW.X += offset.X;
startPointW.Y += offset.Y;
endPointW.X += offset.X;
endPointW.Y += offset.Y;
}
public override void AddPoint(PointW pointW) {
endPointW = pointW;
anchorArray[0] = new Anchor(ref startPointW);
anchorArray[1] = new Anchor(ref endPointW);
}
protected void DrawColiderRect(Graphics g, Rectangle rect) {
rectColider = rect;
Pen penColider = new Pen(Color.Gray);
penColider.Width = 3;
penColider.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
g.DrawRectangle(penColider, rect);
anchorArray[0].Draw(g);
anchorArray[1].Draw(g);
}
}
[DataContract]
public class Rect : RectangularFigure {
int x, y, width, height;
public Rect(Pen pen, PointW start, Color? setColorFill = null) {
colorPen = pen.Color;
widthPen = pen.Width;
startPointW = start;
endPointW = start;
if (setColorFill.HasValue) {
colorFill = (Color)setColorFill;
isFill = true;
}
Load();
}
public override bool SelectPoint(Point pntClick) {
if (rectColider.Contains(pntClick)) {
isSelected = true;
return true;
}
isSelected = false;
return false;
}
public override bool SelectArea(Rectangle area) =>
area.Contains(startPointW.ToScrPnt()) && area.Contains(endPointW.ToScrPnt());
public override void Draw(Graphics graphics) {
colorPen = ((PropColor)propArray["PropColor"]).colorButton.color;
widthPen = ((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth;
colorFill = ((PropFill)propArray["PropFill"]).propColor.colorButton.color;
isFill = ((PropFill)propArray["PropFill"]).checkBox.Checked;
Pen pen = new Pen(colorPen);
pen.Width = widthPen;
x = Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X);
y = Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y);
width = Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X);
height = Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y);
graphics.DrawRectangle(pen, new Rectangle(x, y, width, height));
if (isFill)
graphics.FillRectangle(new SolidBrush(colorFill), new Rectangle(x + (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero),
y + (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero), width - (int)(widthPen), height - (int)(widthPen)));
rectColider = new Rectangle(x - (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero), y - (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero),
width + (int)(widthPen), height + (int)(widthPen));
}
public override void DrawColider(Graphics graphics) {
if (isSelected)
DrawColiderRect(graphics, new Rectangle(x, y, width, height));
}
public override string ToSvgFormat() {
string strColorFill = "rgba(255, 255, 255, 0)";
if (isFill)
strColorFill = ColorTranslator.ToHtml(colorFill);
x = Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X);
y = Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y);
width = Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X);
height = Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y);
return "<rect x=\""+x+"\" y=\"" +y+ "\" width=\"" + width + "\" height=\"" + height + "\" " +
"fill=\""+ strColorFill + "\" stroke-width=\""+widthPen+"\" stroke=\""+ ColorTranslator.ToHtml(colorPen) + "\"/>";
}
}
[DataContract]
public class RoundedRect : RectangularFigure {
[DataMember] public int radius = 25;
int x, y, width, height;
public RoundedRect(Pen setPen, PointW start, int setRadius, Color? setColorFill = null) {
colorPen = setPen.Color;
widthPen = setPen.Width;
startPointW = start;
endPointW = start;
radius = setRadius;
if (setColorFill.HasValue) {
colorFill = (Color)setColorFill;
isFill = true;
}
Load();
}
public override void Load() {
anchorArray = new List<Anchor>(8);
propArray = new Dictionary<string, Prop>(5);
anchorArray.Add(new Anchor(ref startPointW));
anchorArray.Add(new Anchor(ref endPointW));
propArray.Add("PropColor", new PropColor(Color.Black));
propArray.Add("PropPenWidth", new PropPenWidth());
propArray.Add("PropFill", new PropFill(Color.Black));
((PropColor)propArray["PropColor"]).colorButton.color = colorPen;
((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth = widthPen;
((PropFill)propArray["PropFill"]).propColor.colorButton.color = colorFill;
((PropFill)propArray["PropFill"]).checkBox.Checked = isFill;
propArray.Add("PropRadius", new PropRadius(25));
((PropRadius)propArray["PropRadius"]).numeric.Value = radius;
}
public override bool SelectPoint(Point pntClick) {
if (rectColider.Contains(pntClick)) {
isSelected = true;
return true;
}
isSelected = false;
return false;
}
public override bool SelectArea(Rectangle area) =>
area.Contains(startPointW.ToScrPnt()) && area.Contains(endPointW.ToScrPnt());
public override void Draw(Graphics graphics) {
colorPen = ((PropColor)propArray["PropColor"]).colorButton.color;
widthPen = ((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth;
colorFill = ((PropFill)propArray["PropFill"]).propColor.colorButton.color;
isFill = ((PropFill)propArray["PropFill"]).checkBox.Checked;
radius = (int)((PropRadius)propArray["PropRadius"]).numeric.Value;
Pen pen = new Pen(colorPen);
pen.Width = widthPen;
x = Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X);
y = Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y);
width = Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X);
height = Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y);
rectColider = new Rectangle(x - (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero), y - (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero),
width + (int)(widthPen), height + (int)(widthPen));
int diameter = radius * 2;
if (diameter * 2 > rectColider.Width & rectColider.Width <= rectColider.Height) {
diameter = rectColider.Width + 1;
}
if (diameter * 2 > rectColider.Height & rectColider.Width >= rectColider.Height) {
diameter = rectColider.Height + 1;
}
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(rectColider.Location, size);
GraphicsPath path = new GraphicsPath();
if (radius == 0) {
graphics.DrawRectangle(pen, new Rectangle(x, y, width, height));
if (isFill)
graphics.FillRectangle(new SolidBrush(colorFill), new Rectangle(x + (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero), y + (int)Math.Round(widthPen / 2, MidpointRounding.AwayFromZero), width - (int)(widthPen), height - (int)(widthPen)));
return;
}
path.AddArc(arc, 180, 90);
arc.X = rectColider.Right - diameter;
path.AddArc(arc, 270, 90);
arc.Y = rectColider.Bottom - diameter;
path.AddArc(arc, 0, 90);
arc.X = rectColider.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
graphics.DrawPath(pen, path);
if (isFill)
graphics.FillPath(new SolidBrush(colorFill), path);
}
public override void DrawColider(Graphics graphics) {
if (isSelected)
DrawColiderRect(graphics, rectColider);
}
public override string ToSvgFormat() {
string strColorFill = "rgba(255, 255, 255, 0)";
if (isFill)
strColorFill = ColorTranslator.ToHtml(colorFill);
x = Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X);
y = Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y);
width = Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X);
height = Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y);
return "<rect x=\"" + x + "\" y=\"" + y + "\" rx=\"" + radius + "\" ry=\"" + radius + "\" width=\"" + width + "\" height=\"" + height + "\" " +
"fill=\"" + strColorFill + "\" stroke-width=\"" + widthPen + "\" stroke=\"" + ColorTranslator.ToHtml(colorPen) + "\"/>";
}
}
[DataContract]
public class Ellipse : RectangularFigure {
public Ellipse(Pen setPen, PointW start, Color? setColorFill = null) {
colorPen = setPen.Color;
widthPen = setPen.Width;
startPointW = start;
endPointW = start;
if (setColorFill.HasValue) {
colorFill = (Color)setColorFill;
isFill = true;
}
Load();
}
public override bool SelectPoint(Point pntClick) {
double A = (endPointW.ToScrPnt().X - startPointW.ToScrPnt().X) / 2;
double B = (endPointW.ToScrPnt().Y - startPointW.ToScrPnt().Y) / 2;
if (((Math.Pow((pntClick.X - startPointW.ToScrPnt().X - A) / A, 2) + (Math.Pow((pntClick.Y - startPointW.ToScrPnt().Y - B) / B, 2))) <= 1)) {
isSelected = true;
return true;
}
isSelected = false;
return false;
}
public override bool SelectArea(Rectangle area) =>
area.Contains(startPointW.ToScrPnt()) && area.Contains(endPointW.ToScrPnt());
public override void Draw(Graphics graphics) {
colorPen = ((PropColor)propArray["PropColor"]).colorButton.color;
widthPen = ((PropPenWidth)propArray["PropPenWidth"]).numWidthPen.penWidth;
colorFill = ((PropFill)propArray["PropFill"]).propColor.colorButton.color;
rectColider = new Rectangle(startPointW.ToScrPnt(),
new Size(endPointW.ToScrPnt().X - startPointW.ToScrPnt().X, endPointW.ToScrPnt().Y - startPointW.ToScrPnt().Y));
Pen pen = new Pen(colorPen);
pen.Width = widthPen;
graphics.DrawEllipse(pen, rectColider);
if (isFill)
graphics.FillEllipse(new SolidBrush(colorFill), rectColider);
}
public override void DrawColider(Graphics graphics) {
if (isSelected)
DrawColiderRect(graphics, new Rectangle(Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X), Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y),
Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X), Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y)));
}
public override string ToSvgFormat() {
string strColorFill = "rgba(255, 255, 255, 0)";
if (isFill)
strColorFill = ColorTranslator.ToHtml(colorFill);
int x = Math.Min(startPointW.ToScrPnt().X, endPointW.ToScrPnt().X);
int y = Math.Min(startPointW.ToScrPnt().Y, endPointW.ToScrPnt().Y);
int width = Math.Abs(startPointW.ToScrPnt().X - endPointW.ToScrPnt().X)/2;
int height = Math.Abs(startPointW.ToScrPnt().Y - endPointW.ToScrPnt().Y)/2;
return "<ellipse cx='"+ (x + width) + "' cy='"+(y+height)+"' rx='"+width+"' ry='"+height+ "' fill =\"" + strColorFill + "\" stroke-width=\"" + widthPen + "\" stroke=\"" + ColorTranslator.ToHtml(colorPen) + "\"/>";
}
}
public class Anchor {
public PointW editedPoint;
public PointW anchorPoint;
public delegate void EditCallBack(PointW editedPoint);
public EditCallBack editCallBack;
public Rectangle rect;
public Anchor(ref PointW editedPointSet) {
editedPoint = editedPointSet;
}
public Anchor(List<PointW> editedPointSet, int index, EditCallBack editCallBack) {
editedPoint = editedPointSet[index];
this.editCallBack = editCallBack;
}
public void EditPoint(Point pointTo) {
PointW pointW = PointW.ScrnToPointW(pointTo);
editedPoint.X = pointW.X;
editedPoint.Y = pointW.Y;
if (editCallBack != null) {
editCallBack.Invoke(editedPoint);
}
}
public void Draw(Graphics g) {
const int width = 4;
Point point = editedPoint.ToScrPnt();
Pen pen = new Pen(Color.Black);
pen.Width = 2;
rect = new Rectangle(point.X - width, point.Y - width, width * 2, width * 2);
g.DrawRectangle(pen, rect);
g.FillRectangle(new SolidBrush(Color.White), rect);
}
}
}
|
5d5069dc64770b98c360316a619b852a9a3a5183
|
C#
|
DumanBG/C-Advance-2020-SoftUni
|
/06.DefiningClasses/06.SpeedRacing/Car.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace _06.SpeedRacing
{
public class Car
{
private string model;
private double fuelAmount;
private double fuelConsumptionPerKilometer;
private double travelledDistance;
public Car(string model, double fuelAmount, double fuelConsumptionPerKilometer)
{
this.Model = model;
this.FuelAmount = fuelAmount;
this.FuelConsumptionPerKilometer = fuelConsumptionPerKilometer;
this.TravelledDistance = 0;
}
public string Model { get => this.model; set => this.model =value; }
public double FuelAmount { get => this.fuelAmount; set => this.fuelAmount = value; }
public double FuelConsumptionPerKilometer { get => this.fuelConsumptionPerKilometer; set => this.fuelConsumptionPerKilometer = value; }
public double TravelledDistance
{
get { return this.travelledDistance; }
set
{
if (value < 0)
{
throw new ArgumentException("Travelled distance cannot be negative.");
}
this.travelledDistance = value;
}
}
public void Drive( double distanceToDrive)
{
if((this.FuelAmount-distanceToDrive *this.fuelConsumptionPerKilometer) >=0)
{
this.travelledDistance += distanceToDrive;
this.fuelAmount -= distanceToDrive * this.fuelConsumptionPerKilometer;
}
else
{
Console.WriteLine("Insufficient fuel for the drive");
}
}
}
}
|
481aea6fd3eb3183db80f77b610e4c98dd22949e
|
C#
|
LaCinquette/HydrogenOrbitsEquations
|
/PhysicsProject/ElectronDistribution.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhysicsProject
{
public static class ElectronDistribution
{
public delegate double R(double r);
// атомные единицы измерения
public static double Z = 1;
public static double a0 = 1;
// характеристика положения электрона
private static int n;
private static int l;
public static R GetElectronDistribution(int n, int l)
{
ElectronDistribution.n = n;
ElectronDistribution.l = l;
return D_nl();
}
private static R D_nl()
{
(int n, int l) electronCharacteristics = (n, l);
switch (electronCharacteristics)
{
case (1, 0):
return D_10;
case (2, 0):
return D_20;
case (2, 1):
return D_21;
case (3, 0):
return D_30;
case (3, 1):
return D_31;
case (3, 2):
return D_32;
case (4, 0):
return D_40;
case (4, 1):
return D_41;
case (4, 2):
return D_42;
case (4, 3):
return D_43;
default:
throw new Exception("Incorrect n and l");
}
}
private static double R_10(double r)
{
return (double)2 * Math.Pow((Z / a0), (double)3 / 2) * Math.Exp(-(double)Z * r / a0);
}
private static double D_10(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_10(r), 2);
}
private static double R_20(double r)
{
return (double)((double)1 / (2 * Math.Sqrt(2))) * Math.Pow((Z / a0), (double)3 / 2) * ((double)2 - (double)Z * r / a0) * Math.Exp(-(double)Z * r / (2 * a0));
}
private static double D_20(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_20(r), 2);
}
private static double R_21(double r)
{
return (double)((double)1 / (2 * Math.Sqrt(6))) * Math.Pow((Z / a0), (double)5 / 2) * r * Math.Exp(-(double)Z * r / (2 * a0));
}
private static double D_21(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_21(r), 2);
}
private static double R_30(double r)
{
return (double)((double)1 / (9 * Math.Sqrt(3))) * Math.Pow((Z / a0), (double)3 / 2) * ((double)6 - (double)4 * Z * r / a0 + Math.Pow((double)2 * Z * r / (3 * a0), 2)) * Math.Exp(-(double)Z * r / (3 * a0));
}
private static double D_30(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_30(r), 2);
}
private static double R_31(double r)
{
return (double)((double)1 / 27 * Math.Sqrt((double)2 / 3)) * Math.Pow((Z / a0), (double)5 / 2) * ((double)4 - (double)2 * Z * r / (3 * a0)) * r * Math.Exp(-(double)Z * r / (3 * a0));
}
private static double D_31(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_31(r), 2);
}
private static double R_32(double r)
{
return (double)((double)2 / 81 * Math.Sqrt((double)2 / 15)) * Math.Pow((Z / a0), (double)7 / 2) * Math.Pow(r, 2) * Math.Exp(-(double)Z * r / (3 * a0));
}
private static double D_32(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_32(r), 2);
}
private static double R_40(double r)
{
return (double)((double)1 / 96) * Math.Pow((Z / a0), (double)3 / 2) * ((double)24 - (double)18 * Z * r / a0 + (double)12 * Math.Pow((double)Z * r / (2 * a0), 2) - Math.Pow((double)Z * r / (2 * a0), 3)) * Math.Exp(-(double)Z * r / (4 * a0));
}
private static double D_40(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_40(r), 2);
}
private static double R_41(double r)
{
return (double)((double)1 / (64*Math.Sqrt(15))) * Math.Pow((Z / a0), (double)5 / 2) * ((double)20 - (double)5 * Z * r / a0 + Math.Pow((double)Z * r / (2 * a0), 2)) * r * Math.Exp(-(double)Z * r / (4 * a0));
}
private static double D_41(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_41(r), 2);
}
private static double R_42(double r)
{
return (double)((double)1 / (384 * Math.Sqrt(5))) * Math.Pow((Z / a0), (double)7 / 2) * ((double)6 - (double)Z * r / (2 * a0)) * Math.Pow(r, 2) * Math.Exp(-(double)Z * r / (4 * a0));
}
private static double D_42(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_42(r), 2);
}
private static double R_43(double r)
{
return (double)((double)1 / (384 * Math.Sqrt(35))) * Math.Pow((Z / a0), (double)7 / 2)* Math.Pow(r, 3) * Math.Exp(-(double)Z * r / (4 * a0));
}
private static double D_43(double r)
{
return 4 * Math.PI * Math.Pow(r, 2) * Math.Pow(R_43(r), 2);
}
}
}
|
99771f9467c15589d692c8dea6cfdce319166179
|
C#
|
Uko1ove/UnityPairProject
|
/Assets/Scripts/Time/LocalTime.cs
| 2.734375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LocalTimeText : MonoBehaviour, ITime
{
public void ApplyNewTime(int seconds, int minutes, int hours)
{
if(minutes < 9)
{
if(hours < 9)
{
gameObject.GetComponent<Text>().text = $"0{hours}:0{minutes}";
}
else
{
gameObject.GetComponent<Text>().text = $"{hours}:0{minutes}";
}
}
else if(minutes > 9)
{
if (hours < 9)
{
gameObject.GetComponent<Text>().text = $"0{hours}:{minutes}";
}
else
{
gameObject.GetComponent<Text>().text = $"{hours}:{minutes}";
}
}
}
}
|
6a7065edc72a914dcd3b98cb4e8c698786ea0b3d
|
C#
|
pdrosos/TelerikAcademy
|
/C# Fundamentals - Part II/01. Arrays/Evaluated Homeworks/01/Arrays/MergeSort/Program.cs
| 4.03125
| 4
|
using System;
//Merge sort
class Program
{
static void Main()
{
int[] myArray = { 2, 9, 5, 1, 3, 4, 8, 7, 6 };
int[] result = MergeSort(myArray);
foreach (var item in result)
{
Console.Write(item + " ");
}
}
private static int[] MergeSort(int[] myArray)
{
if (myArray.Length == 1)
{
return myArray;
}
int mid = myArray.Length / 2;
int[] left = new int[mid];
int[] right = new int[myArray.Length - mid];
for (int i = 0; i < mid; i++)
{
left[i] = myArray[i];
}
for (int i = 0; i < myArray.Length - mid; i++)
{
right[i] = myArray[i + mid];
}
left = MergeSort(left);
right = MergeSort(right);
int[] result = new int[myArray.Length];
int leftPoint = 0;
int rightPoint = 0;
for (int i = 0; i < result.Length; i++)
{
if (rightPoint == right.Length || ((leftPoint < left.Length) && (left[leftPoint] <= right[rightPoint])))
{
result[i] = left[leftPoint];
leftPoint++;
}
else if (leftPoint == left.Length || ((rightPoint < right.Length) && (right[rightPoint] <= left[leftPoint])))
{
result[i] = right[rightPoint];
rightPoint++;
}
}
return result;
}
}
|
1eaa3006250f17ebc88dd6e2ddcaa8c871865c01
|
C#
|
Notim/ChainRepository.Net
|
/ChainRepository/ChainNodeVendors/DefaultChainNodeAbstract.cs
| 2.65625
| 3
|
using System;
namespace GenericChainRepository.ChainNodeVendors {
public abstract class DefaultChainNodeAbstract<T> : IChainNode<T> {
public IChainNode<T> Next { get; set; }
public abstract T Execute(T contracted);
}
public class DefaultChainNodeFuncAbstract<T> : DefaultChainNodeAbstract<T> where T : new() {
public override T Execute(T contracted) {
contracted = NextExpr(contracted);
return Next.Execute(contracted);
}
public Func<T, T> NextExpr { get; set; } = tin => new T();
}
}
|
56ec0dd7d50f6ae2e93e363fc7ff29e95e41e041
|
C#
|
sidit77/SurviveCore
|
/SurviveCore/Physics/PhysicsWorld.cs
| 2.875
| 3
|
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using SurviveCore.World;
namespace SurviveCore.Physics {
public class PhysicsWorld {
private readonly BlockWorld world;
public PhysicsWorld(BlockWorld world) {
this.world = world;
}
public bool IsGrounded(Vector3 pos) {
return !CanMoveToY(pos, -0.05f);
}
//TODO use a binary search
public Vector3 ClampToWorld(Vector3 pos, Vector3 mov) {
const float pecision = 0.005f;
bool x = true;
while(x && !CanMoveToX(pos, mov.X))
x = Math.Abs(mov.X /= 2) > pecision;
bool y = true;
while(y && !CanMoveToY(pos, mov.Y))
y = Math.Abs(mov.Y /= 2) > pecision;
bool z = true;
while(z && !CanMoveToZ(pos, mov.Z))
z = Math.Abs(mov.Z /= 2) > pecision;
return new Vector3(x ? mov.X : 0, y ? mov.Y : 0, z ? mov.Z : 0);
}
public bool CanMoveTo(Vector3 pos) {
return IsAir(pos + new Vector3(-0.4f, 0.40f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, 0.40f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, 0.40f, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, 0.40f, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, -1.50f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, -1.50f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, -1.50f, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, -1.50f, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, -0.55f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, -0.55f, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, -0.55f, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, -0.55f, 0.4f));
}
private bool CanMoveToY(Vector3 pos, float dy) {
float y = (dy < 0 ? -1.5f : 0.4f) + dy;
return IsAir(pos + new Vector3(-0.4f, y, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, y, -0.4f)) &&
IsAir(pos + new Vector3( 0.4f, y, 0.4f)) &&
IsAir(pos + new Vector3(-0.4f, y, 0.4f));
}
private bool CanMoveToX(Vector3 pos, float dx) {
float x = (dx < 0 ? -0.4f : 0.4f) + dx;
return IsAir(pos + new Vector3(x, 0.40f, -0.4f)) &&
IsAir(pos + new Vector3(x, 0.40f, 0.4f)) &&
IsAir(pos + new Vector3(x, -0.55f, -0.4f)) &&
IsAir(pos + new Vector3(x, -0.55f, 0.4f)) &&
IsAir(pos + new Vector3(x, -1.50f, -0.4f)) &&
IsAir(pos + new Vector3(x, -1.50f, 0.4f));
}
private bool CanMoveToZ(Vector3 pos, float dz) {
float z = (dz < 0 ? -0.4f : 0.4f) + dz;
return IsAir(pos + new Vector3( -0.4f, 0.40f, z)) &&
IsAir(pos + new Vector3( 0.4f, 0.40f, z)) &&
IsAir(pos + new Vector3( -0.4f, -0.55f, z)) &&
IsAir(pos + new Vector3( 0.4f, -0.55f, z)) &&
IsAir(pos + new Vector3( -0.4f, -1.50f, z)) &&
IsAir(pos + new Vector3( 0.4f, -1.50f, z));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsAir(Vector3 pos) {
return !world.GetBlock(pos).HasHitbox();
}
}
}
|
d38a4fa1f74e7eeba266290fb0ba559b301042c1
|
C#
|
rTanabe0205/Raider
|
/3laps/GameEngine/Image.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace GameEngine
{
class Image:GameObject
{
public SpriteRenderer spriteRenderer;
public Image(string assetName, int width, int height, int drawLayer, Transform transform):base(assetName, transform)
{
AddComponent(new SpriteRenderer(assetName, width, height, transform, drawLayer));
spriteRenderer = (SpriteRenderer)GetComponent("SpriteRenderer");
}
public override GameObject Clone()
{
return null;
}
public override void Hit(RectangleCollider rectangleCollider)
{
}
public override void Start()
{
}
public override void Update()
{
}
}
}
|
0be641ace42f02779c300efc145ec9a92c459e2a
|
C#
|
shahabattarnezhad/cleanArchitecture
|
/Employee.Application/Handlers/CommandHandlers/CreateEmployeeHandler.cs
| 2.71875
| 3
|
using Employee.Application.Commands;
using Employee.Application.Mappers;
using Employee.Application.Responses;
using Employee.Core.Repositories;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Employee.Application.Handlers.CommandHandlers
{
public class CreateEmployeeHandler : IRequestHandler<CreateEmployeeCommand, EmployeeResponse>
{
private readonly IEmployeeRepository _repository;
public CreateEmployeeHandler(IEmployeeRepository repository)
{
_repository = repository;
}
public async Task<EmployeeResponse> Handle(CreateEmployeeCommand request, CancellationToken cancellationToken)
{
var employeeEntitiy = EmployeeMapper.Mapper.Map<Employee.Core.Entities.Employee>(request);
if (employeeEntitiy is null)
{
throw new ApplicationException("Issue with mapper");
}
var newEmployee = await _repository.AddAsync(employeeEntitiy);
var employeeResponse = EmployeeMapper.Mapper.Map<EmployeeResponse>(newEmployee);
return employeeResponse;
}
}
}
|
d892959006bb6e7c2f4488cd61f37c3727056106
|
C#
|
bpourian/CRM-contact-book
|
/MyTinyContacts.cs
| 3.375
| 3
|
using SnapsLibrary;
public class MyTinyContacts
{
/// <summary>
/// tidies contact name to lowercase and removes spaces
/// </summary>
/// <param name="name">name to be converted</param>
/// <returns>tidied contact name</returns>
string tidy(string name)
{
name = name.ToLower().Trim();
return name;
}
/// <summary>
/// Stores contact details to local storage
/// </summary>
/// <param name="name">name of contact</param>
/// <param name="address">address for the contact</param>
/// <param name="phone">phone number for the contact</param>
void storeContact( string name, string address, string phone)
{
name = tidy(name);
SnapsEngine.SaveStringToLocalStorage(itemName: name + ":address", itemValue: address);
SnapsEngine.SaveStringToLocalStorage(itemName: name + ":phone", itemValue: phone);
}
/// <summary>
/// creates new contact by capturing information from user
/// </summary>
void newContact()
{
string name = SnapsEngine.ReadString("Enter contact name");
string address = SnapsEngine.ReadMultiLineString("Enter contact address");
string phone = SnapsEngine.ReadString("Eneter contact phone number");
storeContact(name: name, address: address, phone: phone);
}
/// <summary>
/// Retrieves contact information from local storage
/// </summary>
/// <param name="name">Name of contact to search for</param>
/// <param name="address">Address of contact which will be returned</param>
/// <param name="phone">Phone number of contact which will be returned</param>
/// <returns></returns>
bool fetchOutContact(string name, out string address, out string phone)
{
name = tidy(name);
address = SnapsEngine.FetchStringFromLocalStorage(itemName: name +":address");
phone = SnapsEngine.FetchStringFromLocalStorage(itemName: name +":phone");
if (address == null || phone == null) return false;
return true;
}
/// <summary>
/// Searches for the contact name provided and displays it. Gives option to edit details.
/// </summary>
void findContact()
{
string name = SnapsEngine.ReadString("Enter name of contact");
string address, phone;
if (fetchOutContact(name, out address, out phone))
{
SnapsEngine.ClearTextDisplay();
SnapsEngine.AddLineToTextDisplay("Name: " + name);
SnapsEngine.AddLineToTextDisplay("Address: " + address);
SnapsEngine.AddLineToTextDisplay("Phone: " + phone);
SnapsEngine.AddLineToTextDisplay("");
string command = SnapsEngine.SelectFrom2Buttons("Edit Contact", "Exit Contact");
if (command == "Edit Contact")
{
EditContact(name);
}
if (command == "Exit Contact")
{
}
}
else
{
SnapsEngine.AddLineToTextDisplay("Contact not found");
}
SnapsEngine.WaitForButton("Press to continue");
SnapsEngine.ClearTextDisplay();
}
/// <summary>
/// Gives option to edit an existing contact
/// </summary>
/// <param name="name">Name of contact who's details will be edited</param>
void EditContact(string name)
{
string address = SnapsEngine.ReadMultiLineString("Enter contact address");
string phone = SnapsEngine.ReadString("Enter contact phone number");
storeContact(name: name, address: address, phone: phone);
}
/// <summary>
/// Captures user password
/// </summary>
void SetPassword()
{
string passWord = SnapsEngine.ReadString("Enter a new password");
StorePassword(passWord);
}
/// <summary>
/// Saves user password to a specific location
/// </summary>
/// <param name="password">Password provided by user</param>
void StorePassword(string password)
{
SnapsEngine.SaveStringToLocalStorage(itemName: "Password", itemValue: password);
}
/// <summary>
/// Retrieves saved password
/// </summary>
/// <param name="passPhrase">This variable will be updated with the password</param>
/// <returns></returns>
string fetchPassword(out string passPhrase)
{
passPhrase = SnapsEngine.FetchStringFromLocalStorage("Password");
return passPhrase;
}
public void StartProgram()
{
bool exit = true;
while (exit)
{
SnapsEngine.SetTitleString("Contact Book");
string passwordTry = SnapsEngine.ReadPassword("Enter Password");
string pass = fetchPassword(passPhrase: out pass);
string adminPass = "happy";
if ((passwordTry == pass) || (passwordTry == adminPass))
{
while (true)
{
string command = SnapsEngine.SelectFrom4Buttons("New Contact", "Find Contact", "Set Password", "Exit");
if (command == "New Contact")
{
newContact();
}
if (command == "Find Contact")
{
findContact();
}
if (command == "Set Password")
{
SetPassword();
}
if ( command == "Exit")
{
exit = false;
break;
}
}
}
else
{
SnapsEngine.ClearTextDisplay();
SnapsEngine.AddLineToTextDisplay("You have entered the wrong password, try again");
}
}
}
}
|
0ac1fcabfd19fc0858b54f2212797738cadb97bb
|
C#
|
dmos01/MancalaWPF
|
/Mancala/Game/Choose Computer Cup.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
namespace Mancala.Game
{
public partial class PageGameBoard
{
byte tempChosenCup; //In case multiple capturing opportunities are available.
byte[] testCups;
void ChooseComputerCup()
{
ChosenCup = -1;
//Each harder difficulty adds an additional thing to check for (if the checks from easier difficulties fail).
if (player2Type != Enums.PlayerType.Easy)
{
//Therefore Normal, Hard or Very Hard
SearchForFreeTurn();
if (chosenCup == null && player2Type != Enums.PlayerType.Normal)
{
//Therefore Hard or Very Hard
if (capturing)
SearchForCapturing();
if (chosenCup == null && multipleLaps)
SearchForMultipleLapsThatGiveAnExtraTurn();
//By elimination
if (chosenCup == null && player2Type == Enums.PlayerType.VeryHard)
WeightedRandom();
}
}
//The difficulty is Easy or all other checks have fallen through. Use random.
if (chosenCup == null)
Random();
CupClick(chosenCup.CupControl, null);
}
void SearchForFreeTurn()
{
byte requiredNumberOfStones = 1;
for (byte i = 5; i != 255; i--)
{
if (cups[i].NumberOfStones == requiredNumberOfStones)
{
ChosenCup = i;
break;
}
requiredNumberOfStones++;
}
}
void SearchForCapturing()
{
testCups = new byte[14];
tempChosenCup = 0; //In case multiple capturing opportunities are available.
byte numCapturedStonesWithTempChosenCup = 0; //In case multiple capturing opportunities are available.
for (byte testChosen = 5; testChosen != 255; testChosen--)
{
if (cups[testChosen].NumberOfStones == 0)
continue;
//Recreate number of stones.
for (byte i = 0; i < cups.Length; i++)
testCups[i] = cups[i].NumberOfStones;
stonesToMove = testCups[testChosen];
sowInto = testChosen + 1;
bool landInMancala; //But not necessarily finish in.
do
landInMancala = TestSowingOneStone(testChosen);
while (stonesToMove > 0);
if (landInMancala) //Would be free turn, but not capturing.
continue;
byte numCapturedStones = testCups[12 - (sowInto - 1)];
//Stones will be captured — and more than previous tests.
if (numCapturedStones > numCapturedStonesWithTempChosenCup && testCups[sowInto - 1] == 1)
{
//The final sowed cup is on player 2's side.
if (sowInto - 1 < 6)
{
tempChosenCup = testChosen;
numCapturedStonesWithTempChosenCup = numCapturedStones;
}
}
}
if (numCapturedStonesWithTempChosenCup > 0)
ChosenCup = tempChosenCup;
}
void SearchForMultipleLapsThatGiveAnExtraTurn()
{
testCups = new byte[14];
for (byte testChosen = 5; testChosen != 255; testChosen--)
{
if (cups[testChosen].NumberOfStones == 0)
continue;
//Recreate number of stones.
for (byte i = 0; i < cups.Length; i++)
testCups[i] = cups[i].NumberOfStones;
bool landInMancala; //But not necessarily finish in.
int multipleLapsChosen = testChosen;
sowInto = testChosen + 1;
do
{
stonesToMove = testCups[multipleLapsChosen];
requireMultipleLaps = false;
//Do one lap.
do
landInMancala = TestSowingOneStone(multipleLapsChosen);
while (stonesToMove > 0);
//Prepare to repeat loop if another lap required.
if (landInMancala == false && testCups[sowInto - 1] > 1)
{
requireMultipleLaps = true;
multipleLapsChosen = sowInto - 1;
}
} while (requireMultipleLaps);
//If final lap landed in Mancala.
if (landInMancala)
ChosenCup = testChosen;
}
}
void WeightedRandom()
{
//Randomly choose a cup, but give more weight to cups with more stones
//In this case, cups with 1-3 stones are given 1 weight, 4-6 are given 2, etc.
//(Higher weights better.) This gives more variance.
List<byte> weightedCupNumbers = new();
for (byte cup = 5; cup != 255; cup--)
{
byte weightCounter = 0;
int numStones = cups[cup].NumberOfStones;
while (numStones > 0)
{
weightCounter++;
numStones -= 3;
}
while (weightCounter > 0)
{
weightedCupNumbers.Add(cup);
weightCounter--;
}
}
ChosenCup = weightedCupNumbers[new Random().Next(0, weightedCupNumbers.Count)];
}
void Random()
{
do
{
ChosenCup = new Random().Next(0, 6);
} while (chosenCup.NumberOfStones == 0);
}
/// <summary>
/// Returns true if the lap ends in a Mancala.
/// </summary>
/// <param name="testChosenCup"></param>
/// <returns></returns>
bool TestSowingOneStone(int testChosenCup)
{
stonesToMove -= 1;
testCups[testChosenCup] -= 1;
switch (sowInto)
{
case 13 when currentPlayer == Enums.Player.Player1 && stonesToMove == 0:
return true;
case 13:
testCups[0]++;
sowInto = 1;
break;
case 6 when currentPlayer == Enums.Player.Player2:
{
switch (stonesToMove)
{
case 0:
return true;
case > 0:
stonesToMove--;
testCups[testChosenCup]--;
testCups[7]++;
sowInto = 8;
break;
}
break;
}
case 6:
testCups[6]++;
sowInto = 7;
break;
default:
testCups[sowInto]++;
sowInto++;
break;
}
return false;
}
}
}
|
948b1e2acbc88bbc5e00297f8a8639f1387842e9
|
C#
|
vukuri258/Lap2-BT
|
/lap2/Controllers/BookController.cs
| 2.609375
| 3
|
using lap2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace VNExpress.Controllers
{
public class BookController : Controller
{
// GET: Book
public string HelloTeacher(string university)
{
return "hellloooo mn - University: "+ university;
}
public ActionResult ListBook()
{
var books = new List<string>();
books.Add("HTML5 & CSS3 The complete Manual - Author Name Book 1");
books.Add("HTML5 & CSS Reponsive web Design cookbook - Author Name Book 2");
books.Add("Professional ASP.NET MVC5 - Author Name Book 2");
ViewBag.Books = books;
return View();
}
public ActionResult ListBookModel()
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
return View(books);
}
public ActionResult EditBook(int id)
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
Book book = new Book();
foreach(Book b in books)
{
if (b.Id == id)
{
book = b;
break;
}
}
if (book == null)
{
return HttpNotFound();
}
return View(book);
}
[HttpPost, ActionName("EditBook")]
[ValidateAntiForgeryToken]
public ActionResult EditBook(int id, string Title, string Author, string ImageCover)
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
if (id == null)
{
return HttpNotFound();
}
foreach (Book b in books)
{
if (b.Id == id)
{
b.Title = Title;
b.Author = Author;
b.ImageCover = ImageCover;
break;
}
}
return View("ListBookModel", books);
}
public ActionResult CreateBook()
{
return View();
}
[HttpPost, ActionName("CreateBook")]
[ValidateAntiForgeryToken]
public ActionResult Contact([Bind(Include = "Id,Title,Author,ImageCover")] Book book)
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
try
{
if (ModelState.IsValid)
{
//Them sach
books.Add(book);
}
}
catch (RetryLimitExceededException)
{
ModelState.AddModelError("", "Error Save Data");
}
return View("ListBookModel", books);
}
public ActionResult DeleteBook(int Id)
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
Book book = new Book();
foreach (Book b in books)
{
if (b.Id == Id)
{
book = b;
break;
}
}
if (book == null)
{
return HttpNotFound();
}
return View(book);
}
[HttpPost, ActionName("DeleteBook")]
[ValidateAntiForgeryTokenAttribute]
public ActionResult Delete(int Id)
{
var books = new List<Book>();
books.Add(new Book(1, "HTML & CSS3 The complete Manual", "Author Name Book 1", "/Content/image/IMG_7921.JPG"));
books.Add(new Book(2, "HTML5 & CSS Reponsive web Design cookbook", "Author Name Book 2", "/Content/image/IMG_7922.JPG"));
books.Add(new Book(3, "Professional ASP.NET MVC5", "Author Name Book 2", "/Content/image/IMG_7926.JPG"));
foreach (Book b in books)
{
if (b.Id == Id)
{
books.Remove(b);
break;
}
}
return View("ListBookModel", books);
}
}
}
|
89c84003fd28eed856f113a0c2e6ccc1adcb566a
|
C#
|
uvbs/FullSource
|
/Source/Source/Tools/GameDesignerEditor/Controls/CustomLoadTree_Activity/FindForm.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CustomLoadTree_Activity
{
public partial class FindForm : Form
{
Form_Activity m_Parent;
TreeNode CurFindPos;
public FindForm(Form_Activity parent)
{
InitializeComponent();
m_Parent = parent;
TopMost = true;
}
private void button1_Click(object sender, EventArgs e)
{
m_Parent.Tree.ExpandAll();
while(true)
{
if (CurFindPos == null)
{
MessageBox.Show("δҵһڵ");
CurFindPos = m_Parent.Tree.Nodes[0];
break;
}
if (CurFindPos.Text.Contains(textBox1.Text))
{
m_Parent.Tree.SelectedNode = CurFindPos;
m_Parent.Tree.LabelEdit = true;
CurFindPos.BeginEdit();
CurFindPos.EndEdit(true);
m_Parent.Tree.LabelEdit = false;
CurFindPos = CurFindPos.NextVisibleNode;
break;
}
else
{
CurFindPos = CurFindPos.NextVisibleNode;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
Hide();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
CurFindPos = m_Parent.Tree.Nodes[0];
}
}
}
|
6083dcb3d346a4d8ac3d003f3037a60e2f6ee82d
|
C#
|
tompi/BridgeScoringHelper
|
/Scoring/Tournament/Round.cs
| 3.0625
| 3
|
using System.Collections.Generic;
using Scoring.Game;
using Scoring.Players;
using Scoring.Score;
namespace Scoring.Tournament
{
public class Round
{
public int Number;
public List<BoardResult> BoardResults;
public Round(int number)
{
Number = number;
BoardResults = new List<BoardResult>();
}
public void AddBoardResult(BoardResult result)
{
BoardResults.Add(result);
}
public void AddContract(Contract contract, Table table, int boardNumber)
{
BoardResult boardResult = GetBoardResult(boardNumber);
boardResult.AddContract(contract, table);
}
private BoardResult GetBoardResult(int boardNumber)
{
foreach (BoardResult b in BoardResults)
{
if (b.Board.Number == boardNumber)
{
return b;
}
}
// Does not exist yet, create board:
Board board = new Board(boardNumber);
BoardResult boardResult = new BoardResult(board);
AddBoardResult(boardResult);
return boardResult;
}
public List<BoardResult> Score(IScoringEngine engine)
{
foreach (BoardResult res in BoardResults)
{
res.Score(engine);
}
return BoardResults;
}
public int GetMaxTableNr()
{
int maxTableNr = 0;
foreach (BoardResult br in BoardResults)
{
foreach (Result r in br.Results)
{
if (r.Table.Number > maxTableNr)
{
maxTableNr = r.Table.Number;
}
}
}
return maxTableNr;
}
public Result GetResult(int boardNumber, int tableNumber)
{
BoardResult br = GetBoardResult(boardNumber);
foreach (Result result in br.Results)
{
if (result.Table != null && result.Table.Number == tableNumber)
{
return result;
}
}
return null;
}
}
}
|
a65f2b61118e379b616f10fb4df6c44df5b4d627
|
C#
|
alwaysresist/Lab5
|
/Lab5_/Cockroach.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
namespace Lab5_
{
public class Cockroach
{
public Bitmap image;
const int step = 40;
int x;
int y;
direction trend = direction.Up;
public Cockroach(Bitmap _image)
{
image = _image;
}
public int X
{
get => x;
set => x = value;
}
public int Y
{
get => y;
set => y = value;
}
public Bitmap Image
{
get => image;
set => image = value;
}
public void newcoordinates(int dx, int dy)
{
x = dx;
y = dy;
}
public void Step()
{
switch (trend)
{
case direction.Right:
{
X += step;
}
break;
case direction.Down:
{
Y += step;
}
break;
case direction.Left:
{
X -= step;
}
break;
case direction.Up:
{
Y -= step;
}
break;
}
}
public void ChangeTrend(char c)
{
direction newtrend = trend;
for (direction y = direction.Up; y <= direction.Left; y++)
if (char.ToLower(c) == char.ToLower(y.ToString()[0]))
{
newtrend = y;
break;
}
switch (trend)
{
case direction.Up:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
}
break;
case direction.Right:
switch (newtrend)
{
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
}
break;
case direction.Down:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
}
break;
case direction.Left:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
}
break;
}
trend = newtrend;
}
}
}
|
a6a871a6865fdd2e5ab40cf34bbbefd320b59577
|
C#
|
shuhari/Shuhari.Framework
|
/Shuhari.Framework.Testing.Mvc/Web/MockHttpSession.cs
| 2.53125
| 3
|
using System.Collections.Generic;
using System.Web;
namespace Shuhari.Framework.Web
{
/// <summary>
/// Mock session
/// </summary>
internal class MockHttpSession : HttpSessionStateBase
{
/// <summary>
/// Initialize
/// </summary>
public MockHttpSession()
{
_items = new Dictionary<string, object>();
}
private readonly Dictionary<string, object> _items;
/// <inheritdoc />
public override object this[string name]
{
get { return _items.ContainsKey(name) ? _items[name] : null; }
set { _items[name] = value; }
}
/// <inheritdoc />
public override void Remove(string name)
{
_items.Remove(name);
}
}
}
|
90429cfaff5f1e130d63162b80a6ae98e4a6b136
|
C#
|
MarcoLopezDev/apiDoble
|
/apiDoble/apiDoble/Controllers/DataController.cs
| 2.609375
| 3
|
using Microsoft.AspNetCore.Mvc;
using Azure.Messaging.ServiceBus;
using System;
using apiProductorParcial.Models;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text.Json;
namespace apiProductorParcial.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DataController : ControllerBase
{
[HttpPost]
public async Task<bool> EnviarAsync([FromBody] Data data)
{
var x = Int32.Parse(data.random);
if (x % 2 == 0)//Enviar a qParMarco
{
//queue1 -> Shared access policies -> enviar -> Primary Connection String -> copiar
string connectionString = "Endpoint=sb://qparmarco.servicebus.windows.net/;SharedAccessKeyName=envia;SharedAccessKey=VsOQUZWsn0u4nh/8qfBi8C/riQSvtlMgPRziDMy+mmw=;EntityPath=queue2";
string queueName = "queue2";
//Instalar paquetes newton (JsonConvert)
string mensaje = JsonConvert.SerializeObject(data);
await using (ServiceBusClient client = new ServiceBusClient(connectionString))
{
// Create a sender for the queue
ServiceBusSender sender = client.CreateSender(queueName);
// Create a message that we can send
ServiceBusMessage message = new ServiceBusMessage(mensaje);
// Send the message
await sender.SendMessageAsync(message);
Console.WriteLine($"Sent a single message to the queue: {queueName}");
}
return true;
}
else if (x % 2 == 1) //Enviar a qImpar
{
//queue1 -> Shared access policies -> enviar -> Primary Connection String -> copiar
string connectionString = "Endpoint=sb://qimparmarco.servicebus.windows.net/;SharedAccessKeyName=envia;SharedAccessKey=M+jx45FlRofKxyP9tbEyZxQW6F83Fb4pwrhmsD7/hsQ=;EntityPath=queue1";
string queueName = "queue1";
//Instalar paquetes newton (JsonConvert)
string mensaje = JsonConvert.SerializeObject(data);
await using (ServiceBusClient client = new ServiceBusClient(connectionString))
{
// Create a sender for the queue
ServiceBusSender sender = client.CreateSender(queueName);
// Create a message that we can send
ServiceBusMessage message = new ServiceBusMessage(mensaje);
// Send the message
await sender.SendMessageAsync(message);
Console.WriteLine($"Sent a single message to the queue: {queueName}");
}
return true;
}
else
return false;
}
}
}
|
729fbf953c4cd7b378b6f490971f08c2070ba565
|
C#
|
liiabutler/Refazer
|
/Code-Hunt-data/users/User002/Sector3-Level5/attempt013-20140920-054312-winning3.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
public static class Program {
public static int[][] Puzzle(int x, int y) {
List<int[]> list = new List<int[]>();
for (int i = 1; i <= 8; i++)
for (int j = 1; j <= 8; j++)
if (Math.Abs((i-x)*(j-y))==2) list.Add(new int[]{i,j});
return list.ToArray();
}
}
|
07ca19b8ce2988d081f7573ec8a7270cfafaa188
|
C#
|
SherryShi0108/LeetCode
|
/CSharp/Find Smallest Letter Greater Than Target.cs
| 3.609375
| 4
|
//Source : https://leetcode.com/problems/find-smallest-letter-greater-than-target/
//Author : Xinruo Shi
//Date : 2019-12-10
//Language: C#
/*******************************************************************************************************************************
*
* Given a list of sorted characters letters containing only lowercase letters, and given a target letter target,
* find the smallest element in the list that is larger than the given target.
*
* Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.
*
* Input: letters = ["c", "f", "j"] ; target = "a" ;
* Output: "c"
*
* Input: letters = ["c", "f", "j"] ; target = "c"
* Output: "f"
*
* Input: letters = ["c", "f", "j"] ; target = "d"
* Output: "f"
*
* Input: letters = ["c", "f", "j"] ; target = "g"
* Output: "j"
*
* Input: letters = ["c", "f", "j"] ; target = "j"
* Output: "c"
*
* Input: letters = ["c", "f", "j"] ; target = "k"
* Output: "c"
*
* Note:
* letters has a length in range [2, 10000].
* letters consists of lowercase letters, and contains at least 2 unique letters.
* target is a lowercase letter.
*
*******************************************************************************************************************************/
using System.Collections.Generic;
using System.Data;
using System.Linq;
public class Solution744
{
// --------------- O(logn) 116ms --------------- 27.5MB ---------------(95% 25%) ※
/*
* Binary Search
*/
public char NextGreatestLette_1(char[] letters, char target)
{
int i = 0;
int j = letters.Length;
while (i<j)
{
int mid = i + (j - i) / 2; // int mid = i + ((j - i) >> 1);
if (letters[mid] <= target)
{
i = mid + 1;
}
else
{
j = mid;
}
}
return i >= letters.Length ? letters[0] : letters[i]; // return letter[i%letter.length];
}
// --------------- O(n) 136ms --------------- 27.8MB ---------------(13% 25%)
/*
* Linear Scan
*/
public char NextGreatestLette_2(char[] letters, char target)
{
for (int i = 0; i < letters.Length; i++)
{
if (letters[i] > target)
{
return letters[i];
}
}
return letters[0];
}
}
/**************************************************************************************************************
* NextGreatestLette_1 *
**************************************************************************************************************/
|
7a7e359857b53e93f1d59682b8366807fd230c8e
|
C#
|
henningms/trafikanten-api-w8
|
/TrafikantenApi/Models/Street.cs
| 2.6875
| 3
|
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace TrafikantenApi.Models
{
[DataContract]
public class Street : Place
{
private ObservableCollection<House> _houses;
[DataMember]
public ObservableCollection<House> Houses
{
get
{
return _houses;
}
set
{
_houses = value;
NotifyPropertyChanged("Houses");
}
}
}
[DataContract]
public class House : BaseModel
{
private long _x, _y;
private string _name;
[DataMember]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
[DataMember]
public long X
{
get
{
return _x;
}
set
{
_x = value;
NotifyPropertyChanged("X");
}
}
[DataMember]
public long Y
{
get
{
return _y;
}
set
{
_y = value;
NotifyPropertyChanged("Y");
}
}
}
}
|
6bb8cde4849e55d84f4355c137ee8b45f11e8183
|
C#
|
netintellect/PluralsightSpaJumpStartFinal
|
/Telerik/DemoApp/Examples/Map/WPF/Theatre/BookingViewModel.cs
| 2.671875
| 3
|
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Telerik.Windows.Controls;
using System.Windows.Media;
namespace Telerik.Windows.Examples.Map.Theatre
{
public class BookingViewModel : ViewModelBase, IDataErrorInfo
{
private string _email;
private DateTime? _cardExpirationDate;
private string _performanceTitle;
private TheatreSeatInfoCollection _selectedSeats;
private string _cardHolderName;
private string _cardNumber;
private bool _isFormSubmitted = false;
private bool _isBuyOptionSelected = true;
private bool _isReserveOptionSelected = false;
public BookingViewModel()
: this("", new TheatreSeatInfoCollection())
{
}
public BookingViewModel(string title, TheatreSeatInfoCollection seats)
{
this.PerformanceTitle = title;
this.SelectedSeats = seats;
this.Email = "john.smith@gmail.com";
this.CardholderName = "John Smith";
this.CardNumber = "1234567891011";
this.CardExpirationDate = DateTime.Today.AddYears(1);
}
public string PerformanceTitle
{
get
{
return this._performanceTitle;
}
set
{
if (this._performanceTitle != value)
{
this._performanceTitle = value;
this.OnPropertyChanged("PerformanceTitle");
}
}
}
public bool IsBuyOptionSelected
{
get
{
return this._isBuyOptionSelected;
}
set
{
if (this._isBuyOptionSelected != value)
{
this._isBuyOptionSelected = value;
this.OnPropertyChanged("IsBuyOptionSelected");
}
}
}
public bool IsReserveOptionSelected
{
get
{
return this._isReserveOptionSelected;
}
set
{
if (this._isReserveOptionSelected != value)
{
this._isReserveOptionSelected = value;
this.OnPropertyChanged("IsReserveOptionSelected");
}
}
}
public TheatreSeatInfoCollection SelectedSeats
{
get
{
return this._selectedSeats;
}
set
{
if (this._selectedSeats != value)
{
this._selectedSeats = value;
this.OnPropertyChanged("SelectedSeats");
}
}
}
public string Email
{
get
{
return this._email;
}
set
{
if (this._email != value)
{
this._email = value;
this.OnPropertyChanged("Email");
}
}
}
public string CardholderName
{
get
{
return this._cardHolderName;
}
set
{
if (this._cardHolderName != value)
{
this._cardHolderName = value;
this.OnPropertyChanged("CardholderName");
}
}
}
public string CardNumber
{
get
{
return this._cardNumber;
}
set
{
if (this._cardNumber != value)
{
this._cardNumber = value;
this.OnPropertyChanged("CardNumber");
}
}
}
public DateTime? CardExpirationDate
{
get
{
return this._cardExpirationDate;
}
set
{
if (this._cardExpirationDate != value)
{
this._cardExpirationDate = value;
this.OnPropertyChanged("CardExpirationDate");
}
}
}
public bool IsFormSubmitted
{
get
{
return this._isFormSubmitted;
}
set
{
this._isFormSubmitted = value;
}
}
public string Error
{
get
{
return null;
}
}
public string this[string propertyName]
{
get
{
switch (propertyName)
{
case "Email":
if (!Regex.IsMatch(this.Email, @"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,4}\b"))
return "Please enter valid email address";
break;
case "CardholderName":
if (string.IsNullOrEmpty(this.CardholderName))
return "Please enter valid cardholder's name";
break;
case "CardNumber":
if (string.IsNullOrEmpty(this.CardNumber))
return "Please enter valid card number (13-16 digits)";
break;
case "CardExpirationDate":
if (this.CardExpirationDate < DateTime.Today || this.CardExpirationDate > DateTime.Today.AddYears(5))
return string.Format("Please enter valid expiration date prior to {0:MM/dd/yyyy}", DateTime.Today.AddYears(5));
break;
default:
break;
}
return null;
}
}
}
}
|
7032efcaed8b79dbe64e02953a9c1f128e80332c
|
C#
|
shendongnian/download4
|
/first_version_download2/490941-44478082-149085512-6.cs
| 3.359375
| 3
|
public abstract class ViewModelBase : INotifyPropertyChanged
{
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Item : ViewModelBase, INotifyPropertyChanged
{
private string _approver;
public int Id { get; set; }
public string Name { get; set; }
public string Approver
{
get { return _approver; }
set
{
if (_approver != value)
{
_approver = value;
RaisePropertyChanged(nameof(Approver));
}
}
}
}
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
UpdateDataCommand = new RelayCommand(_ => UpdateAll());
}
public ObservableCollection<Item> AllItems { get; set; } = new ObservableCollection<Item>();
public ICommand UpdateDataCommand { get; set; }
private void UpdateAll()
{
//Fetch from DB
var items = new[]
{
new Item {Id=1, Name="Item 1", Approver="Lance"},
new Item {Id=2, Name="Item 2", Approver="John"}
};
AllItems.Clear();
foreach (var item in items)
{
AllItems.Add(item);
}
}
}
|
f57f7654c5d7862a9752b7e20264a71483bcf7ea
|
C#
|
patrickhuber/Pliant
|
/hosts/Pliant.PerfViewApp/Program.cs
| 2.59375
| 3
|
using Pliant.Json;
using Pliant.Runtime;
using System;
using System.IO;
namespace Pliant.PerfViewApp
{
internal class Program
{
private static void Main(string[] args)
{
var sampleBnf = File.ReadAllText(
Path.Combine(Environment.CurrentDirectory, "10000.json"));
var grammar = new JsonGrammar();
var loopCount = 100;
for (long i = 0; i < loopCount; i++)
{
Console.WriteLine($"Iteration {i} of {loopCount}");
var parseEngine = new ParseEngine(grammar);
var parseRunner = new ParseRunner(parseEngine, sampleBnf);
while (!parseRunner.EndOfStream() && parseRunner.Read()) { }
var result = parseRunner.ParseEngine.IsAccepted();
}
}
}
}
|
cb5cb764ec17e9c7c5ed3304f23418ad50c12465
|
C#
|
pirocorp/Databases-Advanced---Entity-Framework
|
/Exercises/07. Code First/Exercise/HospitalDatabase/Data/ModelConfigs/VisitationConfig.cs
| 2.515625
| 3
|
namespace P01_HospitalDatabase.Data.ModelConfigs
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Data.Models;
public class VisitationConfig : IEntityTypeConfiguration<Visitation>
{
public void Configure(EntityTypeBuilder<Visitation> builder)
{
builder.HasKey(x => x.VisitationId);
builder.HasOne(x => x.Patient)
.WithMany(x => x.Visitations)
.HasForeignKey(x => x.PatientId);
builder.HasOne(x => x.Doctor)
.WithMany(x => x.Visitations)
.HasForeignKey(x => x.DoctorId);
builder.Property(x => x.Comments)
.HasMaxLength(250)
.IsRequired(true);
}
}
}
|
3d177d0c2b300357d8cd138e76f59dcd4dc105ae
|
C#
|
cacayue/MyCouldBook
|
/src/mycouldbook-aspnet-core/src/MyCouldBook.Core/BookListManagement/Books/DomainService/BookManager.cs
| 2.75
| 3
|
using Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using MyCouldBook.BookListManagement.RelationShipps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyCouldBook.BookListManagement.Books.DomainService
{
/// <summary>
/// 领域服务层一个模块的核心业务逻辑
///</summary>
public class BookManager :MyCouldBookDomainServiceBase, IBookManager
{
private readonly IRepository<Book,long> _bookRepository;
private readonly IRepository<BookAndBookTag, long> _bookAndBookTagRepository;
/// <summary>
/// Book的构造方法
/// 通过构造函数注册服务到依赖注入容器中
///</summary>
public BookManager(IRepository<Book, long> bookRepository,
IRepository<BookAndBookTag, long> bookAndBookTagRepository) {
_bookRepository = bookRepository;
_bookAndBookTagRepository = bookAndBookTagRepository;
}
#region 查询判断的业务
/// <summary>
/// 返回表达式数的实体信息即IQueryable类型
/// </summary>
/// <returns></returns>
public IQueryable<Book> QueryBooks()
{
return _bookRepository.GetAll();
}
/// <summary>
/// 返回即IQueryable类型的实体,不包含EF Core跟踪标记
/// </summary>
/// <returns></returns>
public IQueryable<Book> QueryBooksAsNoTracking()
{
return _bookRepository.GetAll().AsNoTracking();
}
/// <summary>
/// 根据Id查询实体信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<Book> FindByIdAsync(long id)
{
var entity = await _bookRepository.GetAsync(id);
return entity;
}
/// <summary>
/// 检查实体是否存在
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<bool> IsExistAsync(long id)
{
var result = await _bookRepository.GetAll().AnyAsync(a => a.Id == id);
return result;
}
#endregion
public async Task<Book> CreateAsync(Book entity)
{
entity.Id = await _bookRepository.InsertAndGetIdAsync(entity);
return entity;
}
public async Task UpdateAsync(Book entity)
{
await _bookRepository.UpdateAsync(entity);
}
public async Task DeleteAsync(long id)
{
//TODO:删除前的逻辑判断,是否允许删除
await _bookRepository.DeleteAsync(id);
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task BatchDelete(List<long> input)
{
//TODO:删除前的逻辑判断,是否允许删除
await _bookRepository.DeleteAsync(a => input.Contains(a.Id));
}
/// <summary>
/// 创建书籍与标签关系
/// </summary>
/// <param name="bookId"></param>
/// <param name="tagIds"></param>
/// <returns></returns>
public async Task CreateBookAndBookTag(long bookId, ICollection<long> tagIds)
{
await _bookAndBookTagRepository.DeleteAsync(item=>item.BookId== bookId);
await CurrentUnitOfWork.SaveChangesAsync();
var newTagId = new List<long>();
foreach (var tagId in tagIds)
{
if (newTagId.Exists(a=>a == tagId))
{
continue;
}
await _bookAndBookTagRepository.InsertAsync(new BookAndBookTag
{
BookId = bookId,
TagId = tagId
});
newTagId.Add(tagId);
}
}
public async Task<ICollection<BookAndBookTag>> GetBooksByTagId(long? tagId)
{
return await _bookAndBookTagRepository.GetAll()
.AsNoTracking().Where(a => a.TagId == tagId).ToListAsync();
}
public async Task<ICollection<BookAndBookTag>> GetBookTagsByBookId(long? bookId)
{
return await _bookAndBookTagRepository.GetAll()
.AsNoTracking().Where(a => a.BookId == bookId).ToListAsync();
}
}
}
|
4a0225244e349ab7d1293924881264afa6e94dec
|
C#
|
SelectiveHouse/Window-Tracker
|
/DesktopTracker.Terminal/Program.cs
| 2.75
| 3
|
using DesktopTracker.Terminal.Timers;
using Microsoft.Azure.EventHubs;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DesktopTracker.Terminal
{
internal class Program
{
private static EventHubClient eventHubClient;
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
#region STRING/AZURE SETUP
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var connectionStringBuilder = new EventHubsConnectionStringBuilder(configuration.GetSection("ConnectionStrings:DesktopTrackerHub").Value)
{
EntityPath = configuration.GetSection("DesktopTrackerEventHub:CloseMessage").Value
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
#endregion
AutoResetEvent autoEvent = new AutoResetEvent(false);
Console.WriteLine("Checking Active Windows at: {0:h:mm:ss.fff} \n",
DateTime.UtcNow);
#region WINDOW TIMER
//Enter null for no break clause, e.g. program goes on forever
ActiveChecker activeWindows = new ActiveChecker(null);
//1000 = 1 second etc.
Timer foregroundTimer = new Timer(activeWindows.CheckWindows, autoEvent, 0, 5000);
#endregion
#region HIBERNATE TIMER
//Enter max time for Kiosk to hibernate
DateTime maxTimeForHibernate = DateTime.UtcNow.AddMinutes(30);
HibernateChecker hibernateChecker = new HibernateChecker(maxTimeForHibernate);
//Checks silently every 0.25 seconds
Timer hibernateTimer = new Timer(hibernateChecker.CheckHibernate, autoEvent, 0, 250);
#endregion
#if DEBUG
//Keeps console open
Console.ReadLine();
#endif
}
}
}
|
def44326f1d41785d897ace3d088ca1aa5905031
|
C#
|
Koseng/ConnectivityPlugin
|
/src/Connectivity.Plugin.WindowsPhone8/ConnectivityImplementation.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Phone.Net.NetworkInformation;
using Plugin.Connectivity.Abstractions;
using System.Diagnostics;
using System.Net.NetworkInformation;
using Windows.Networking.Connectivity;
using System.Windows;
namespace Plugin.Connectivity
{
/// <summary>
/// Implementation for WinPhone 8
/// </summary>
public class ConnectivityImplementation : BaseConnectivity
{
bool isConnected;
/// <summary>
/// Default constructor
/// </summary>
public ConnectivityImplementation()
{
isConnected = IsConnected;
//Must register for both for WP8 for some reason.
DeviceNetworkInformation.NetworkAvailabilityChanged += NetworkAvailabilityChanged;
NetworkChange.NetworkAddressChanged += NetworkAddressChanged;
}
void NetworkAddressChanged(object sender, EventArgs e)
{
UpdateStatus();
}
void NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
{
UpdateStatus();
}
private void UpdateStatus()
{
var previous = isConnected;
var newConnected = IsConnected;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (previous != newConnected)
OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected });
OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = newConnected, ConnectionTypes = this.ConnectionTypes });
});
}
Version WinPhone81 = new Version(8, 1, 0, 0);// I know technically it was 8.10.x.x, but this is fine
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
public override bool IsConnected
{
get
{
//if this is a 8.0 device you must use old school is network available
if (Environment.OSVersion.Version < WinPhone81)
return (isConnected = DeviceNetworkInformation.IsNetworkAvailable);
try
{
//else if running newer then you are alright to use connection profile.
var profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
isConnected = false;
else
isConnected = profile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None;
return isConnected;
}
catch (NotImplementedException ex)
{
return (isConnected = DeviceNetworkInformation.IsNetworkAvailable);
}
}
}
/// <summary>
/// Tests if a host name is pingable
/// </summary>
/// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param>
/// <param name="msTimeout">Timeout in milliseconds</param>
/// <returns></returns>
public override async Task<bool> IsReachable(string host, int msTimeout = 5000)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
if (!IsConnected)
return false;
return await Task.Run(() =>
{
var manualResetEvent = new ManualResetEvent(false);
var reachable = false;
DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint(host, 80), result =>
{
reachable = result.NetworkInterface != null;
manualResetEvent.Set();
}, null);
manualResetEvent.WaitOne(TimeSpan.FromMilliseconds(msTimeout));
return reachable;
});
}
/// <summary>
/// Tests if a remote host name is reachable
/// </summary>
/// <param name="host">Host name can be a remote IP or URL of website</param>
/// <param name="port">Port to attempt to check is reachable.</param>
/// <param name="msTimeout">Timeout in milliseconds.</param>
/// <returns></returns>
public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
if (!IsConnected)
return false;
host = host.Replace("http://www.", string.Empty).
Replace("http://", string.Empty).
Replace("https://www.", string.Empty).
Replace("https://", string.Empty).
TrimEnd('/');
return await Task.Run(() =>
{
try
{
var clientDone = new ManualResetEvent(false);
var reachable = false;
var hostEntry = new DnsEndPoint(host, port);
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
socketEventArg.Completed += (s, e) =>
{
reachable = e.SocketError == SocketError.Success;
clientDone.Set();
};
clientDone.Reset();
socket.ConnectAsync(socketEventArg);
clientDone.WaitOne(msTimeout);
return reachable;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
return false;
}
});
}
/// <summary>
/// Returns connection types active
/// </summary>
public override IEnumerable<ConnectionType> ConnectionTypes
{
get
{
var networkInterfaceList = new NetworkInterfaceList();
foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.InterfaceState == ConnectState.Connected))
{
ConnectionType type;
switch (networkInterfaceInfo.InterfaceSubtype)
{
case NetworkInterfaceSubType.Desktop_PassThru:
type = ConnectionType.Desktop;
break;
case NetworkInterfaceSubType.WiFi:
type = ConnectionType.WiFi;
break;
case NetworkInterfaceSubType.Unknown:
type = ConnectionType.Other;
break;
default:
type = ConnectionType.Cellular;
break;
}
yield return type;
}
}
}
/// <summary>
/// Returns list of Bandwidths
/// </summary>
public override IEnumerable<UInt64> Bandwidths
{
get
{
var networkInterfaceList = new NetworkInterfaceList();
return
networkInterfaceList.Where(
networkInterfaceInfo => networkInterfaceInfo.InterfaceState == ConnectState.Connected
&& networkInterfaceInfo.InterfaceSubtype != NetworkInterfaceSubType.Unknown)
.Select(networkInterfaceInfo => (UInt64)networkInterfaceInfo.Bandwidth)
.ToArray();
}
}
private bool disposed = false;
/// <summary>
/// Dispose of class
/// </summary>
/// <param name="disposing"></param>
public override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
DeviceNetworkInformation.NetworkAvailabilityChanged -= NetworkAvailabilityChanged;
NetworkChange.NetworkAddressChanged -= NetworkAddressChanged;
}
disposed = true;
}
base.Dispose(disposing);
}
}
}
|
2317c3fab901613c08e1cc15d813f655fbf759cb
|
C#
|
hugo3011mendez/DI-T5-Ejercicio2
|
/Etiqueta Aviso/EtiquetaAviso.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Etiqueta_Aviso
{
public enum eMarca // Defino el enumerado para los adornos
{
Nada,
Cruz,
Circulo,
ImagenDeForma
}
public partial class EtiquetaAviso : Control // Hago un componente personalizado, dibujando en vez de metiendo componentes de Windows Forms
{
int xMarca, yMarca; // Para conseguir las coordenadas máximas de la marca en cuestión
int grosor; //Grosor de las líneas de dibujo
int offsetX; //Desplazamiento a la derecha del texto
int offsetY; //Desplazamiento hacia abajo del texto
public EtiquetaAviso()
{
InitializeComponent();
}
[Category("Marca")]
[Description("Indica que no se mostrará ninguna marca con la etiqueta")]
private eMarca marca = eMarca.Nada; // En esta variable usaremos todos los posibles datos elegidos del enumerado
// Aquí guardaremos el enumerado eMarca
public eMarca Marca
{
set
{
marca = value;
this.Refresh();
}
get { return marca; }
}
// Creo una variable para indicar la imagen que se dibujará si se escoge ImagenDeForma para la etiqueta aviso
private Image imagenMarca;
[Category("Marca")]
[Description("Guarda la imagen que se muestra como marca cuando se escoge esta opción")]
public Image ImagenMarca
{
set
{
imagenMarca = value;
}
get
{
return imagenMarca;
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Graphics g = pe.Graphics;
//Esta propiedad provoca mejoras en la apariencia o en la eficiencia a la hora de dibujar
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if (Gradiente && Color1Gradiente != null && Color2Gradiente != null)
{
LinearGradientBrush gradientColor = new LinearGradientBrush(
new PointF(0, 0),
new PointF(this.Width, this.Height),
Color1Gradiente,
Color2Gradiente);
g.FillRectangle(gradientColor, new RectangleF(
0, 0,
this.Width, this.Height));
}
//Dependiendo del valor de la propiedad marca dibujamos una
//Cruz o un Círculo
switch (Marca)
{
case eMarca.Circulo:
grosor = 20;
// Actualizo el valor de las coordenadas máximas de la marca
xMarca = grosor;
yMarca = grosor;
g.DrawEllipse(new Pen(Color.Green, grosor), grosor, grosor, this.Font.Height, this.Font.Height);
offsetX = this.Font.Height + grosor;
offsetY = grosor;
break;
case eMarca.Cruz:
grosor = 5;
Pen lapiz = new Pen(Color.Red, grosor);
// Actualizo el valor de las coordenadas máximas de la marca
xMarca = this.Font.Height;
yMarca = this.Font.Height;
g.DrawLine(lapiz, grosor, grosor, this.Font.Height, this.Font.Height);
g.DrawLine(lapiz, this.Font.Height, grosor, grosor, this.Font.Height);
offsetX = this.Font.Height + grosor;
offsetY = grosor / 2;
//Es recomendable liberar recursos de dibujo pues se pueden realizar muchos y cogen memoria
lapiz.Dispose();
break;
case eMarca.ImagenDeForma: // Dibujo la imagen establecida en la variable imagenMarca
if (ImagenMarca != null)
{
try
{
// Actualizo el valor de las coordenadas máximas de la marca
xMarca = 40;
yMarca = 40;
g.DrawImage(ImagenMarca, 0, 0, 40, 40);
// Y establezco los offsets para escribir el texto que se quiera
offsetX = this.Font.Height + 20;
offsetY = 10;
}
catch (ArgumentException)
{
Marca = eMarca.Nada;
}
}
else
{
Marca = eMarca.Nada;
}
break;
case eMarca.Nada:
// Pongo los valores a 0 cuando es Nada
offsetX = 0;
offsetY = 0;
grosor = 0;
break;
}
// Finalmente pintamos el Texto desplazado si fuera necesario
SolidBrush b = new SolidBrush(this.ForeColor);
g.DrawString(this.Text, this.Font, b, offsetX + grosor, offsetY);
Size tam = g.MeasureString(this.Text, this.Font).ToSize();
this.Size = new Size(tam.Width + offsetX + grosor, tam.Height + offsetY * 2);
b.Dispose();
}
protected override void OnTextChanged(EventArgs e) //Creamos un On para cada vez que se lanza el evento TextChanged
{
base.OnTextChanged(e);
this.Refresh(); // Y lanzo Refresh() para que se dibuje con todo
}
private bool gradiente = false;
[Category("Fondo")]
[Description("Indica si se dibuja el gradiente de fondo o no")]
public bool Gradiente
{
set
{
gradiente = value;
this.Refresh();
}
get
{
return gradiente;
}
}
private Color color1Gradiente;
[Category("Fondo")]
[Description("Es el primer color que influye en el gradiente al formarse")]
public Color Color1Gradiente
{
set
{
color1Gradiente = value;
this.Refresh();
}
get
{
return color1Gradiente;
}
}
private Color color2Gradiente;
[Category("Fondo")]
[Description("Es el segundo color que influye en el gradiente al formarse")]
public Color Color2Gradiente
{
set
{
color2Gradiente = value;
this.Refresh();
}
get
{
return color2Gradiente;
}
}
[Category("Eventos")]
[Description("Se lanza cuando se hace click sobre la marca, si existe")]
public event EventHandler ClickEnMarca;
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
if (Marca != eMarca.Nada)
{
if (e.X <= xMarca && e.Y <= yMarca)
{
ClickEnMarca?.Invoke(this, EventArgs.Empty);
}
}
}
}
}
|
ddd8882ab06f964e2f93140901675a89db6df8b1
|
C#
|
tavisca-ysant/SRPAndOCPDemo
|
/SRPAndOCPDemo/Repository.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SRPAndOCPDemo
{
public class Database : IRepository
{
private List<Entity> _entitySet = new List<Entity>();
private static int _primaryKey = 1;
public List<Entity> Display()
{
return _entitySet;
}
public void Insert(Entity entity)
{
_entitySet.Add(entity);
_primaryKey++;
}
public Entity Retrieve(int primaryKey)
{
foreach(var entity in _entitySet)
{
if (entity.GetPrimaryKey() == primaryKey)
return entity;
}
throw new EntityDoesNotExist();
}
}
}
|
26e9a12d61906882866bcd841f9f8528b6dc40c4
|
C#
|
RedRevenge94/szh
|
/szh_backend/szh/measurement/MeasurementType.cs
| 2.890625
| 3
|
using DbManager.Db;
using System;
using System.Collections.Generic;
namespace szh.measurement {
public class MeasurementType : Entity {
public int id;
public string name;
public string acronym;
public static string GetNameOfMeasurementType(int id) {
return pgSqlSingleManager.ExecuteSQL($"select name from measurement.measurement_type where id = {id}")[0]["name"];
}
public static List<MeasurementType> GetMeasurementTypes() {
return GetMeasurementType($"select * from measurement.measurement_type");
}
private static List<MeasurementType> GetMeasurementType(string query) {
List<MeasurementType> measurementTypes = new List<MeasurementType>();
foreach (var measurementType in pgSqlSingleManager.ExecuteSQL(query)) {
MeasurementType newMeasurementType = new MeasurementType() {
id = Int32.Parse(measurementType["id"]),
name = measurementType["name"],
acronym = measurementType["acronym"]
};
measurementTypes.Add(newMeasurementType);
}
return measurementTypes;
}
}
}
|
fead7f384cdfee5759b53b1c5872cfe38ace0226
|
C#
|
Cheeseman5/PDF-Toolbox
|
/PDFToolbox/Converters/ImageToSourceConverter.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Windows.Media.Imaging;
using System.Windows.Data;
namespace PDFToolbox.Converters
{
public class ImageToSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Image image = value as Image;
if (image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, image.RawFormat);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
return null;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
2c2ba66e3e88c0f492973a4d4c006234852e2878
|
C#
|
gregsochanik/papertrailapp-archive-reader
|
/src/LogReader/DateRange.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using MoreLinq;
namespace LogReader
{
public class DateRange
{
public DateRange(DateTime fromDate, TimeSpan to)
{
From = fromDate;
To = fromDate.Add(to).AddDays(-1);
}
public DateRange(DateTime fromDate, DateTime toDate)
{
From = fromDate;
To = toDate;
}
public DateTime From { get; private set; }
public DateTime To { get; private set; }
public IEnumerable<DateTime> AsDays()
{
return Enumerable.Range(0, To.Subtract(From).Days + 1).Select(d => From.AddDays(d));
}
public IEnumerable<IEnumerable<DateTime>> AsWeeks()
{
return AsDays().Batch(7);
}
}
}
|
d49877be96daf701eadb773f909563901dfa465f
|
C#
|
Procedure-Sao/C-VS
|
/vs项目/十六章/十六章/DBqq.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 十六章
{
class DBqq
{
private string strConn = "Data Source=.;Initial Catalog=QQDB;User ID=sa;Password=825516949";
SqlConnection conn = null;
SqlCommand cmd = null;
#region 检查管理员信息
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool CheckAdmin( string name,string pwd)
{
try
{
conn = new SqlConnection(strConn);
conn.Open();
string sql = " select count(*) from admin where LoginId='" + name + "' and LoginPwd='" + pwd + "'";
// 创建SqlCommand对象
SqlCommand comm = new SqlCommand(sql, conn);
int Reat = (int)comm.ExecuteScalar();
if (Reat != 1)
{
return false;
}
else
{
return true;
}
}
catch (Exception )
{
return false;
}
finally
{
conn.Close();
}
}
#endregion
#region 获取学生信息列表
/// <summary>
/// 获取学生信息列表
/// </summary>
/// <returns></returns>
public SqlDataReader GetUser()
{
try
{
conn = new SqlConnection(strConn);
conn.Open();
string sql = "select u.UserId,u.UserName,l.LevelName,u.Email,u.OnLineDay from UserInfo as u inner join Level as l on(u.LevelId=l.LevelId)";
cmd = new SqlCommand(sql,conn);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
return null;
}
}
#endregion
#region 更新在线天数
public int update(string name, string ui)
{
conn = new SqlConnection(strConn);
try
{
conn.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine("update UserInfo set [OnLineDay]='" + ui + "' where [UserId]='" + name + "'");
cmd = new SqlCommand(sb.ToString(), conn);
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
}
#endregion
#region 添加用户
/// <summary>
/// 添加用户
/// </summary>
/// <param name="userName"></param>
/// <param name="userPwd"></param>
/// <param name="email"></param>
/// <returns></returns>
public int InsertUser(string userName,string userPwd,string email)
{
try
{
conn = new SqlConnection(strConn);
conn.Open();
string sql = "insert into [admin] values ('" + userName + "','" + userPwd + "','" + email + "')";
cmd = new SqlCommand(sql, conn);
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
}
#endregion
#region 更新等级
public int UpdateUserLevel(int userId, int iLevel)
{
try
{
conn.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine(" UPDATE");
sb.AppendLine(" from [UserInfo]");
sb.AppendLine(" SET");
sb.AppendLine(" [LevelId]=" + iLevel);
sb.AppendLine(" WHERE");
sb.AppendLine(" [UserId]=" + userId);
cmd = new SqlCommand(sb.ToString(), conn);
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
}
#endregion
#region 删除用户信息
/// <summary>
/// 删除用户信息
/// </summary>
/// <returns></returns>
public int DeleteUserInfo(string shu)
{
try
{
conn = new SqlConnection(strConn);
conn.Open();
string sql = "delete from UserInfo where [UserId]= '" + shu + "'";
cmd = new SqlCommand(sql, conn);
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
}
#endregion
#region 获取账户Id和在线天数
public SqlDataReader GetUserIdAndOnlineDay()
{
try
{
conn.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine(" SELECT");
sb.AppendLine(" UserId");
sb.AppendLine(" ,OnLineDay");
sb.AppendLine(" FROM");
sb.AppendLine(" UserInfo ");
SqlCommand comm = new SqlCommand(sb.ToString(), conn);
return comm.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
return null;
}
}
#endregion
}
}
|
1a716e1dc4d2737d757d125b44b7e2b57a88b5af
|
C#
|
shendongnian/download4
|
/code8/1466429-40127513-129628540-4.cs
| 2.765625
| 3
|
class SpecificAdaptee
{
...
public void FireEvent2()
{
int a = 42;
if (Event2 != null)
Event2(this, ref a);
Console.WriteLine("A value after the event is {0}", a);
}
}
private static void OnAdaptedEvent2(object sender, AdaptedEventArgs2 args)
{
Console.WriteLine($"{nameof(OnAdaptedEvent2)}({sender}, {args.A})");
args.A = 15;
}
|
57c2c6c5c0e5fc64186e2af8bcf46c88237153d5
|
C#
|
seungyongshim/SQLite-Blob-POC
|
/UserRepository.cs
| 3.09375
| 3
|
using Dapper;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
namespace SQLite_Blob_POC
{
public class UserRepository
{
public UserRepository(Func<SqliteConnection> dbConnect)
{
DbConnect = dbConnect;
}
private Func<SqliteConnection> DbConnect { get; }
public void Delete(long key)
{
using (var c = DbConnect())
{
c.Open();
c.Execute($@"DELETE FROM USERS WHERE USER_ID = {key}");
}
}
public void Delete(User userInformation)
{
using (var c = DbConnect())
{
c.Open();
c.Execute($@"DELETE FROM USERS WHERE USER_ID = {userInformation.USER_ID}");
}
}
public IEnumerable<User> FindAll()
{
using (var c = DbConnect())
{
c.Open();
return c.Query<User>("SELECT * FROM USERS");
}
}
public void InitializeDatabase()
{
using (var c = DbConnect())
{
c.Open();
var tableCommand = "CREATE TABLE IF NOT "
+ "EXISTS USERS "
+ "("
+ "USER_ID INTEGER PRIMARY KEY, "
+ "PASSWORD TEXT, "
+ "USER_NAME TEXT, "
+ "USER_GROUP TEXT, "
+ "BLOB BLOB "
+ ")";
SqliteCommand createTable = new SqliteCommand(tableCommand, c);
createTable.ExecuteReader();
}
}
public void Insert(User user)
{
using (var c = DbConnect())
{
c.Open();
c.Execute(@"INSERT INTO USERS (PASSWORD, USER_NAME, USER_GROUP, BLOB)" +
"VALUES (:PASSWORD, :USER_NAME, :USER_GROUP, :BLOB)", user);
}
}
}
}
|
1fa731c93634f1704f29cb7aec97b44e83f990c7
|
C#
|
bubdm/Archi.Net-ExposedAndDBaseModels
|
/GenericStructure.Framework/Exceptions/BaseException.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericStructure.Framework.Exceptions
{
public class BaseException : Exception
{
public string Name { get; set; }
public BaseException(string exceptionName) : base()
{
this.Name = exceptionName;
}
}
}
|
7aac376ce0907936204ff10e50bec55af93df7a3
|
C#
|
a-leggett/Storage
|
/StorageTest/Mocks/MockBinarySearchable.cs
| 3.140625
| 3
|
using Storage;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorageTest.Mocks
{
class MockBinarySearchable : IBinarySearchable<long, string>
{
public SortedList<long, string> SortedList { get; private set; }
public MockBinarySearchable(long count, int seed, params long[] keysToAvoid)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
this.Count = count;
SortedList = new SortedList<long, string>((int)count);
Random r = new Random(seed/*Fixed seed for consistent tests*/);
for(long i = 0; i < count; i++)
{
long key = r.Next();
while (keysToAvoid.Contains(key) || SortedList.ContainsKey(key))
key++;
SortedList.Add(key, key.ToString());
}
}
public MockBinarySearchable(IEnumerable<KeyValuePair<long, string>> pairs)
{
this.Count = pairs.Count();
SortedList = new SortedList<long, string>();
foreach (var pair in pairs)
SortedList.Add(pair.Key, pair.Value);
}
public long Count { get; private set; }
public long GetKeyAt(long index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index));
return SortedList.ElementAt((int)index).Key;
}
public string GetValueAt(long index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index));
return SortedList.ElementAt((int)index).Value;
}
}
}
|
6487b93d41f4e73b61111414125738e782bf3c6d
|
C#
|
leakalmar/ISBolnice
|
/Projekat/Hospital-IS/Service/UserService.cs
| 2.828125
| 3
|
using System.Collections.Generic;
namespace Service
{
public class UserService
{
public List<int> AllUserIDs { get; set; } = new List<int>();
public int MaxId {get; set;}
private static UserService instance = null;
public static UserService Instance
{
get
{
if (instance == null)
{
instance = new UserService();
}
return instance;
}
}
private UserService()
{
}
public void GetAllUsersIDs()
{
AllUserIDs = AdministrationEmployeeService.Instance.GetEmployeIDs();
AllUserIDs.AddRange(DoctorService.Instance.GetDoctorIds());
AllUserIDs.AddRange(PatientService.Instance.GetPatientIDs());
}
public void FindMaxID()
{
int max = 0;
foreach(int id in AllUserIDs)
{
if (max < id)
{
max = id;
}
}
MaxId = max;
}
public int GenerateUserID()
{
FindMaxID();
AllUserIDs.Add(++MaxId);
return MaxId;
}
}
}
|
8845e8688e0308513047300ed3153886449ccc3a
|
C#
|
VaskoViktorov/SoftUni-Homework
|
/07. OOP Advanced C# - 18.07.2017/04. Generics - Exercises/03. Generic Box of Integer/01 Generic Box/IBox.cs
| 2.78125
| 3
|
namespace _01_Generic_Box
{
public interface IBox<T>
{
T Value { get; }
void Generate(T value);
string ToString();
}
}
|
81fd8cc0bc6f0600e06e87628a7767f0e9a8b3d0
|
C#
|
LYHarry/UtilCore
|
/Easycode.Common/Extensions/StrExtChar.cs
| 3.65625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Easycode.Extensions
{
/// <summary>
/// 字符串扩展帮助类
/// <para>处理特殊字符串</para>
/// </summary>
public static partial class StrExtension
{
/// <summary>
/// 截取掉两边空格
/// </summary>
/// <param name="source">待截取字符串</param>
/// <returns>返回截取掉两边空格后的字符串</returns>
public static string ToTrim(this string source)
{
return (source ?? string.Empty).Trim();
}
/// <summary>
/// 是否为空字符串
/// </summary>
/// <param name="source">待判断字符串</param>
/// <returns>为空返回 true 否则 false </returns>
public static bool IsEmpty(this string source)
{
return string.IsNullOrWhiteSpace(ToTrim(source));
}
/// <summary>
/// 是否有值
/// </summary>
/// <param name="source">待判断字符串</param>
/// <returns>不为空返回 true 否则 false </returns>
public static bool HasValue(this string source) => !IsEmpty(source);
}
}
|
59d33877d2e7e5bcd9b6cc9c8a5a921af9d5ecfa
|
C#
|
senivlm/HW8_2
|
/HW8_21/Utilita.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace HW8_21
{
class Utilita
{
private readonly string pathStorage1 = @"C:\\Users\\admin\\source\\repos\\HW8_21\\HW8_21\\Storage1.txt";
private readonly string pathStorage2 = @"C:\\Users\\admin\\source\\repos\\HW8_21\\HW8_21\\Storage2.txt";
private string[] reader1;
private string[] reader2;
private const string Message_File = "Check path Properly";
Storage storage1;
Storage storage2;
public Utilita()
{
try
{
reader1 = File.ReadAllLines(pathStorage1);
reader2 = File.ReadAllLines(pathStorage2);
}
catch (IOException)
{
Console.WriteLine("Message_File");
Environment.Exit(1);
}
storage1 = Initilization(reader1);
storage2 = Initilization(reader2);
}
public Utilita(string path, string path2)
{
try
{
reader1 = File.ReadAllLines(path);
reader2 = File.ReadAllLines(path2);
}
catch (IOException)
{
Console.WriteLine("Message_File");
Environment.Exit(1);
}
storage1 = Initilization(reader1);
storage2 = Initilization(reader2);
}
public Storage Initilization(string[] reader1)
{
string[] sub;
Product[] product = new Product[reader1.Length];
for (int i = 0; i < reader1.Length; i++)
{
sub = reader1[i].Split(' ');
product[i] = new Product(sub[0], Convert.ToDouble(sub[1]));
}
return new Storage(product);
}
public void allFunc(Program.More_or_Less del)
{
string result = null;
string result1 = null;
result = storage2.gotFirst(storage1);
Console.WriteLine("Only in First");
Console.WriteLine(result);
Console.WriteLine("Evrything is diffrent");
result1 = storage2.gotFirst(storage1);
Console.WriteLine(result + result1);
result = null;
result1 = null;
Console.WriteLine("Similar");
result = storage1.HasTwo(storage2, del);
Console.WriteLine(result);
}
}
}
|
ab47075ea319f6261803f37d598a257e919ea19c
|
C#
|
zbaghdasaryan/ADO.NET
|
/Concepts_Connections/02_ConnectionStrings/Program.cs
| 3.09375
| 3
|
using System;
using System.Data.SqlClient;
namespace CBS.ADO_NET.ConnectionUsing
{
class Program
{
static void Connection_StateChange(object sender, System.Data.StateChangeEventArgs e)
{
SqlConnection connection = sender as SqlConnection;
Console.WriteLine();
Console.WriteLine //вывод информации о соединении и его состоянии
(
"Connection to" + Environment.NewLine +
"Data Source: " + connection.DataSource + Environment.NewLine +
"Database: " + connection.Database + Environment.NewLine +
"State: " + connection.State
);
}
static void Main(string[] args)
{
string conStr = @"Data Source=DESKTOP-DTQ5Q8H;Initial Catalog=ShopDB;Integrated Security=True;Connect Timeout=30;
Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; //строка подключения
// для указания базы данных, к котрой нужно подключиться кроме параметра Initial Catalog можно пользоваться параметром DataBase,
using (SqlConnection connection = new SqlConnection(conStr))
// при использовании объекта SqlConnection в блоке using можно не заботиться о закрытии физического соединения с источником данных,
// даже если в блоке using генерируется исключительная ситуация
{
connection.StateChange += Connection_StateChange; // событие, вызываемое при изменении состояния соединения
try
{
connection.Open();
//throw new Exception("error"); // раскомментировать
}
catch (Exception e)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ForegroundColor = ConsoleColor.Gray;
}
} // connection.Dispose();
}
}
}
|
d6de8f0b7cd7d5c23a0688207981068f953cb741
|
C#
|
lucle/Book-Store
|
/BookShop.WebComponents/Logging/LoggerAttribute.cs
| 2.515625
| 3
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System;
namespace BookShop.WebComponents.Logging
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true,
Inherited = true)]
public sealed class LoggerAttribute : ActionFilterAttribute
{
public LoggerAttribute(string logMessage)
{
this.LogMessage = logMessage;
}
public string LogMessage { get; }
public LogLevel LogLevel { get; set; } = LogLevel.Information;
private EventId _eventId;
private string GetLogMessage(ModelStateDictionary modelState)
{
var logMessage = this.LogMessage;
foreach (var key in modelState.Keys)
{
logMessage = logMessage.Replace("{" + key + "}", modelState[key].RawValue?.ToString());
}
return logMessage;
}
private ILogger GetLogger(HttpContext context, ControllerActionDescriptor action)
{
var logger = context
.RequestServices
.GetService(typeof(ILogger<>)
.MakeGenericType(action.ControllerTypeInfo.UnderlyingSystemType)) as ILogger;
return logger;
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var cad = context.ActionDescriptor as ControllerActionDescriptor;
var logMessage = this.GetLogMessage(context.ModelState);
var logger = this.GetLogger(context.HttpContext, cad);
var duration = TimeSpan.FromMilliseconds(Environment.TickCount - this._eventId.Id);
logger.Log(this.LogLevel, this._eventId, $"After {cad.ControllerName}.{cad.ActionName} with {logMessage} and result {context.HttpContext.Response.StatusCode} in {duration}", null, (state, ex) => state.ToString());
base.OnActionExecuted(context);
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var cad = context.ActionDescriptor as ControllerActionDescriptor;
var logMessage = this.GetLogMessage(context.ModelState);
var logger = this.GetLogger(context.HttpContext, cad);
this._eventId = new EventId(Environment.TickCount, $"{cad.ControllerName}.{cad.ActionName}");
logger.Log(this.LogLevel, this._eventId, $"Before {cad.ControllerName}.{cad.ActionName} with {logMessage}", null, (state, ex) => state.ToString());
base.OnActionExecuting(context);
}
}
}
|