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
|
|---|---|---|---|---|---|---|
156df2fde6f4af9898f350b99615121c82757867
|
C#
|
luosandong/Lushu
|
/CommonDal/SqlGenerator.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CommonDal
{
public interface ISqlGenerator
{
string Insert<T>(T model);
string Update<T>(T model);
string Get(Type type);
string Delete<T>(T model);
string GetCondition(Dictionary<string, object> QueryParams);
}
public class SqlGenerator
{
public virtual char ParameterPrefix => '@';
public virtual char OpenQuote => '[';
public virtual char CloseQuote => ']';
protected string GetTableName(Type type)
{
TableAttribute attr = type.GetCustomAttribute(typeof(TableAttribute)) as TableAttribute;
return attr.Name;
}
public virtual string Delete<T>(T model)
{
string sql = $"DELETE FROM {GetTableName(typeof(T))} WHERE 1=1 ";
var key = model.GetType().GetProperties().FirstOrDefault(property => (property.GetCustomAttribute(typeof(KeyAttribute))) != null);
if (key != null)
{
sql += $"AND {key.Name}={ParameterPrefix}{key.Name}";
}
return sql;
}
protected virtual string BuildUpdate(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
foreach (var property in properties)
{
if ((property.GetCustomAttribute(typeof(MapIgnoreAttribute)) as MapIgnoreAttribute) != null) continue;
var fieldDef =
property.GetCustomAttribute(typeof(FieldDefAttribute)) as FieldDefAttribute;
if (fieldDef != null)
{
fields.Add($"{this.OpenQuote}{fieldDef.ColumnName}{this.CloseQuote}={ParameterPrefix}{property.Name}");
}
else
{
fields.Add($"{this.OpenQuote}{property.Name}{this.CloseQuote}={ParameterPrefix}{property.Name}");
}
}
return string.Join(",", fields.ToArray());
}
protected Tuple<string,string> BuildField(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
List<string> fieldParameter = new List<string>();
foreach (var property in properties)
{
if ((property.GetCustomAttribute(typeof(MapIgnoreAttribute)) as MapIgnoreAttribute) != null) continue;
var fieldDef =
property.GetCustomAttribute(typeof(FieldDefAttribute)) as FieldDefAttribute;
if (fieldDef != null)
{
fields.Add($"`{fieldDef.ColumnName}`");
}
else
{
fields.Add($"`{property.Name}`");
}
fieldParameter.Add($"{ParameterPrefix}{property.Name}");
}
return new Tuple<string, string>(string.Join(",", fields.ToArray()), string.Join(",", fieldParameter.ToArray()));
}
protected string BuidFieldParameter(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
foreach (var property in properties)
{
fields.Add($"@{property.Name}");
}
return string.Join(",", fields.ToArray());
}
protected List<PropertyInfo> GetProperties(Type type)
{
return (from property in type.GetProperties() let ignore = property.GetCustomAttribute(typeof(MapIgnoreAttribute)) != null where !ignore select property).ToList();
}
public string Update<T>(T model)
{
var properties = GetProperties(model.GetType());
var tableName = GetTableName(typeof(T));
StringBuilder sb = new StringBuilder($"UPDATE {OpenQuote}{tableName}{CloseQuote} SET {BuildUpdate(properties)} WHERE Id=@Id ");
string sql = sb.ToString();
return sql;
}
}
public class MySqlSqlGenerator : SqlGenerator, ISqlGenerator
{
public override char OpenQuote => '`';
public override char CloseQuote => '`';
public string Get(Type type)
{
string sql = $"SELECT {BuildField(GetProperties(type)).Item1} FROM {GetTableName(type)}";
return sql;
}
public string GetCondition(Dictionary<string, object> QueryParams)
{
string condition = " WHERE 1=1 ";
foreach (var kv in QueryParams)
{
condition += $" AND {OpenQuote}{kv.Key}{CloseQuote}={ParameterPrefix}{kv.Key} ";
}
return condition;
}
public string Insert<T>(T model)
{
string sql = $"insert into {GetTableName(model.GetType())} ({BuildField(GetProperties(model.GetType())).Item1}) values ({BuildField(GetProperties(model.GetType())).Item2});";
return sql;
}
}
public class SqlServerSqlGenerator: SqlGenerator,ISqlGenerator
{
public List<PropertyInfo> Properties { get; set; }
public string Insert<T>(T model)
{
var properties = GetProperties(model.GetType());
var tableName = GetTableName(typeof(T));
StringBuilder sb = new StringBuilder($"INSERT INTO [{tableName}] ({BuidField(properties)}) VALUES({BuidFieldParameter(properties)})");
string sql = sb.ToString();
return sql;
}
public string Get(Type type)
{
string sql = $"SELECT {BuidField(GetProperties(type))} FROM {GetTableName(type)}";
return sql;
}
public string Delete<T>(T model)
{
string sql = $"DELETE FROM {GetTableName(model.GetType())}";
return sql;
}
private string BuildUpdate(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
foreach (var property in properties)
{
fields.Add($"[{property.Name}]=@{property.Name}");
}
return string.Join(",", fields.ToArray());
}
private string BuidField(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
foreach (var property in properties)
{
fields.Add($"[{property.Name}]");
}
return string.Join(",", fields.ToArray());
}
private string BuidFieldParameter(List<PropertyInfo> properties)
{
List<string> fields = new List<string>();
foreach (var property in properties)
{
fields.Add($"@{property.Name}");
}
return string.Join(",", fields.ToArray());
}
public string GetCondition(Dictionary<string, object> QueryParams)
{
throw new NotImplementedException();
}
}
}
|
ecfe6efae313ba423eab86ee475c68d08fe1a6b5
|
C#
|
IsaacGutierrez/SearchMyHome
|
/SearchMyHome/SearchMyHome/Models/Validators/EmailDuplicatedAttribute.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using SearchMyHome.DataAccess;
namespace SearchMyHome.Models.Validators
{
public class EmailDuplicatedAttribute:ValidationAttribute
{
private string _emailToValidate;
private SearchMyHomeDBEntities _entities = new SearchMyHomeDBEntities();
public bool IsEmailValid(object value)
{
this._emailToValidate = (string)value;
string[] Eamils = _entities.Suscriptor.Select(model => model.correoElectronico).ToArray();
bool ExistEmail = Eamils.Contains(this._emailToValidate);
return ExistEmail;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (IsEmailValid(value)) {
return new ValidationResult(this.ErrorMessage);
}
return ValidationResult.Success;
}
}
}
|
8c0c445dbcc46b36e264639cc8de25895af5ddc2
|
C#
|
SaschaDoe/HowToSoftwareDevelopment
|
/Katas/SumOfDigitsKata/SumOfDigitsKataTests/UnitTests/SumOfDigitsExtensionTests.cs
| 2.9375
| 3
|
using SumOfDigitsKata;
using Xunit;
namespace SumOfDigitsKataTests
{
public class SumOfDigitsExtensionTests
{
#region SumOfDigits
[Fact]
[Trait("Category", "Unit")]
public void Zero()
{
Assert.Equal(0,0.SumOfDigits());
}
[Fact]
[Trait("Category", "Unit")]
public void One_When_One()
{
Assert.Equal(1,1.SumOfDigits());
}
[Fact]
[Trait("Category", "Unit")]
public void One_When_Ten()
{
Assert.Equal(1,10.SumOfDigits());
}
[Fact]
[Trait("Category", "Unit")]
public void Two_When_Eleven()
{
Assert.Equal(2,11.SumOfDigits());
}
[Fact]
[Trait("Category", "Unit")]
public void Three_When_111()
{
Assert.Equal(3,111.SumOfDigits());
}
#endregion
}
}
|
ba9e689e99e4fc43f7478de9422d715068ab4011
|
C#
|
kovacsgaborab/Telekocsi_Form
|
/Telekocsi_Form/Auto.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Telekocsi_Form
{
class Auto
{
public string Indulas { get; set; }
public string Cel { get; set; }
public string Rendszam { get; set; }
public string Telefonszam { get; set; }
public int Ferohely { get; set; }
public string Utvonal { get; private set; }
public Auto(string sor)
{
string[] a = sor.Split(';');
Indulas = a[0];
Cel = a[1];
Rendszam = a[2];
Telefonszam = a[3];
Ferohely = Convert.ToInt32(a[4]);
Utvonal = Indulas + "-" + Cel;
}
}
}
|
dac15c67392d1ddb3b2181fd85576db0cd9c27d0
|
C#
|
Game-Folk/BrackeysJams2021.1
|
/BrackeysJam2021.1/Assets/Scripts/MonkeySpawner.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonkeySpawner : MonoBehaviour
{
[SerializeField] private bool spawnOnATimer = false;
[SerializeField] private float secondsPerSpawn = 1f;
[SerializeField] private int numToSpawn = 3;
[SerializeField] private GameObject monkey = null;
public static MonkeySpawner instance;
private void Awake()
{
if (instance != null)
{
Debug.LogError("More than one MonkeySpawner in scene!");
return;
}
instance = this;
}
// Start is called before the first frame update
void Start()
{
if(spawnOnATimer)
StartCoroutine(SpawnMonkeysLoop());
}
private IEnumerator SpawnMonkeysLoop()
{
while(true)
{
yield return new WaitForSeconds(secondsPerSpawn);
SpawnMonkeys(numToSpawn);
}
}
public void SpawnMonkeys(int num)
{
for(int i = 0; i < num; i++)
{
GameObject go = Instantiate(monkey, transform.position, Quaternion.identity);
}
}
}
|
5f4f8ead5844d00ce7a4b1c5f28d0107e2416a36
|
C#
|
nirdobovizki/MvvmMonkey
|
/MvvmMonkey.Wpf/MvvmMonkey.Wpf/ViewLocator.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace NirDobovizki.MvvmMonkey
{
public static class ViewLocator
{
public static void RegisterViews(ResourceDictionary resources, Assembly assembly)
{
foreach(var currentType in assembly.GetTypes())
{
var viewModelName = currentType.Name;
if (!viewModelName.EndsWith("ViewModel", StringComparison.Ordinal)) continue;
var viewName = viewModelName.Substring(0, viewModelName.Length - 5); // "ViewModel" -> "View"
var viewType = assembly.GetTypes().SingleOrDefault(x => string.CompareOrdinal(x.Name, viewName) == 0);
if (viewType == null)
{
System.Diagnostics.Trace.WriteLine(string.Format("MvvmMonkey.ViewLocator: can't find view class {0} for view model {1}", viewName, viewModelName));
continue;
}
var template = new DataTemplate
{
DataType = currentType,
VisualTree = new FrameworkElementFactory(viewType)
};
System.Diagnostics.Trace.WriteLine(string.Format("{0} => {1}", viewName, viewModelName));
resources.Add(new DataTemplateKey(currentType), template);
}
}
}
}
|
fe0f3665c0a5309d478c371bc0c8598dbe807275
|
C#
|
kazenetu/WinHttpConnectJsonLib
|
/ASPdotNETCore2/Domain/Service/ServiceBase.cs
| 2.859375
| 3
|
namespace Domain.Service
{
/// <summary>
/// サービスクラスのスーパークラス
/// </summary>
public class ServiceBase
{
#region クラス定数
/// <summary>
/// 1ページあたりのレコード数
/// </summary>
protected const int PageCount = 20;
/// <summary>
/// 更新結果
/// </summary>
public enum UpdateResult
{
/// <summary>
/// 成功
/// </summary>
OK,
/// <summary>
/// 失敗:バージョン違い(排他エラー)
/// </summary>
ErrorVaersion,
/// <summary>
/// 失敗
/// </summary>
Error
};
#endregion
#region クラスメソッド
/// <summary>
/// レコード数から総ページ数を取得
/// </summary>
/// <param name="recordCount">レコード数</param>
/// <returns>総ページ数(レコード数がゼロ件の場合は-1)</returns>
protected int getTotalPageCount(int recordCount)
{
int pageCount = -1;
if (recordCount > 0)
{
pageCount = recordCount / PageCount;
if (recordCount <= PageCount)
{
pageCount = 0;
}
else
{
if (recordCount - pageCount * PageCount > 0)
{
pageCount++;
}
}
}
return pageCount;
}
#endregion
}
}
|
b6941f78c46892e6cfc6c087bd125a1a68dbc58f
|
C#
|
Ivan-Dimitrov-bg/.Net-framework
|
/03.C# OOP/02.Defining Classes 2/DefineClass/Point3D.cs
| 4.21875
| 4
|
using System;
struct Point3D
{
private static readonly Point3D pointZero = new Point3D(0, 0, 0);
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public Point3D(double x, double y, double z) : this()
{
X = x;
Y = y;
Z = z;
}
public static Point3D Start()
{
return pointZero;
}
public void ToString()
{
Console.WriteLine("The coordinates of the point are: ");
Console.WriteLine("X = {0} Y = {1} Z = {2}", X, Y, Z);
}
}
|
9debf218eaa39d22d1d20e86e9f521e2ad76ba5f
|
C#
|
LalitAkRadadiya/trainingAssigment
|
/Web API - Hotel Management System/System/HMS.Entities/MapEntities.cs
| 2.515625
| 3
|
using AutoMapper;
using HMS.Data.Model;
using HMS.Entities.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HMS.Entities
{
class MapEntities
{
public KeyValuePair<Hotel, HotelViewModel> MapDealerViewModel()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Hotel, HotelViewModel>();
});
IMapper mapper = config.CreateMapper();
var source = new Hotel();
var destination = mapper.Map<Hotel, HotelViewModel>(source);
return new KeyValuePair<Hotel, HotelViewModel>(source, destination);
}
public KeyValuePair<Room, RoomViewModel> MapCustomerViewModel()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Room, RoomViewModel>();
});
IMapper mapper = config.CreateMapper();
var source = new Room();
var destination = mapper.Map<Room, RoomViewModel>(source);
return new KeyValuePair<Room, RoomViewModel>(source, destination);
}
public KeyValuePair<Booking, BookingViewModel> MapVehicleViewModel()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Booking, BookingViewModel>();
});
IMapper mapper = config.CreateMapper();
var source = new Booking();
var destination = mapper.Map<Booking, BookingViewModel>(source);
return new KeyValuePair<Booking, BookingViewModel>(source, destination);
}
}
}
|
855f17a050489028dcba6e716b4af94d8d80f892
|
C#
|
frogconn/Hospital
|
/DataAccessor/Accessor/PatientAccessor.cs
| 2.765625
| 3
|
using BLToolkit.Data;
using BLToolkit.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataAccess
{
public class PatientAccessor
{
public List<Patient> FindAll()
{
using (var db = new DbManager())
{
var query = new SqlQuery<Patient>(db);
return query.SelectAll();
}
}
public Patient FindById(int id)
{
using (var db = new DbManager())
{
var query = new SqlQuery<Patient>();
return query.SelectByKey(id);
}
}
public void Insert(Patient model)
{
using (var db = new DbManager())
{
var query = new SqlQuery<Patient>();
query.Insert(model);
}
}
public void Update(Patient model)
{
using (var db = new DbManager())
{
var query = new SqlQuery<Patient>();
query.Update(model);
}
}
public void InsertOrUpdate(Patient model)
{
var modelInDb = this.FindById(model.ID);
if (modelInDb == null)
this.Insert(model);
else
this.Update(model);
}
public void Delete(int ID)
{
using (var db = new DbManager())
{
var query = new SqlQuery<Patient>();
query.DeleteByKey(ID);
}
}
}
}
|
0cdda85a392d607d67a93263fda22cc8cc721a9f
|
C#
|
shendongnian/download4
|
/code9/1699260-48791400-166890526-2.cs
| 2.671875
| 3
|
using UnityEngine;
public class FormShifting : MonoBehaviour {
public GameObject myObject1;
public GameObject myObject2;
int high;
void Update () {
if (Input.GetKeyDown(KeyCode.UpArrow) && high == 0)
{
myObject1.SetActive(false);
myObject2.SetActive(true);
high = 1;
}
if (Input.GetKeyDown(KeyCode.DownArrow) && high == 1)
{
myObject2.SetActive(false);
myObject1.SetActive(true);
high = 0;
}
}
}
|
584b12685da758f76520137d3d81c19fe7834b93
|
C#
|
RadSt/Essentials
|
/Lesson8/Task3/Task3/Program.cs
| 2.921875
| 3
|
using System;
namespace Task3
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Введите кол-во часов");
var hours = Convert.ToInt32(Console.ReadLine());
var accauntant = new Accauntant();
if (accauntant.AskForBonus(Workers.Worker, hours))
{
Console.WriteLine("Нужно дать премию");
}
else
{
Console.WriteLine("Обойдется");
}
Console.ReadKey();
}
}
}
|
b48bea07d3ae6e43814d9738d29f2d6d6d208a50
|
C#
|
maxmind/MaxMind-DB-Reader-dotnet
|
/MaxMind.Db/Metadata.cs
| 2.546875
| 3
|
#region
using System;
using System.Collections.Generic;
#endregion
namespace MaxMind.Db
{
/// <summary>
/// Data about the database file itself
/// </summary>
public sealed class Metadata
{
/// <summary>
/// Construct a metadata object.
/// </summary>
/// <param name="binaryFormatMajorVersion"></param>
/// <param name="binaryFormatMinorVersion"></param>
/// <param name="buildEpoch"></param>
/// <param name="databaseType"></param>
/// <param name="description"></param>
/// <param name="ipVersion"></param>
/// <param name="languages"></param>
/// <param name="nodeCount"></param>
/// <param name="recordSize"></param>
[Constructor]
[CLSCompliant(false)]
public Metadata(
[Parameter("binary_format_major_version")] int binaryFormatMajorVersion,
[Parameter("binary_format_minor_version")] int binaryFormatMinorVersion,
[Parameter("build_epoch")] ulong buildEpoch,
[Parameter("database_type")] string databaseType,
IDictionary<string, string> description,
[Parameter("ip_version")] int ipVersion,
IReadOnlyList<string> languages,
[Parameter("node_count")] long nodeCount,
[Parameter("record_size")] int recordSize
)
{
BinaryFormatMajorVersion = binaryFormatMajorVersion;
BinaryFormatMinorVersion = binaryFormatMinorVersion;
BuildEpoch = buildEpoch;
DatabaseType = databaseType;
Description = description;
IPVersion = ipVersion;
Languages = languages;
NodeCount = nodeCount;
RecordSize = recordSize;
}
/// <summary>
/// The major version number for the MaxMind DB binary format used by the database.
/// </summary>
public int BinaryFormatMajorVersion { get; }
/// <summary>
/// The minor version number for the MaxMind DB binary format used by the database.
/// </summary>
public int BinaryFormatMinorVersion { get; }
internal ulong BuildEpoch { get; }
/// <summary>
/// The date-time of the database build.
/// </summary>
public DateTime BuildDate => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(BuildEpoch);
/// <summary>
/// The MaxMind DB database type.
/// </summary>
public string DatabaseType { get; }
/// <summary>
/// A map from locale codes to the database description in that language.
/// </summary>
public IDictionary<string, string> Description { get; }
/// <summary>
/// The IP version that the database supports. This will be 4 or 6.
/// </summary>
public int IPVersion { get; }
/// <summary>
/// A list of locale codes for languages that the database supports.
/// </summary>
public IReadOnlyList<string> Languages { get; }
internal long NodeCount { get; }
internal int RecordSize { get; }
internal long NodeByteSize => RecordSize / 4;
internal long SearchTreeSize => NodeCount * NodeByteSize;
}
}
|
1c349d7066209772f6cac9d2a697f87804ec25db
|
C#
|
adin10/MistralIntership-EmployeeManager
|
/EmployeeManager.Common/FileUploadHelper.cs
| 2.765625
| 3
|
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace EmployeeManager.Common
{
public class FileUploadHelper
{
public static async Task<string> Upload(IFormFile file, string rootPath)
{
var folderName = Path.Combine("Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(rootPath, folderName, fileName);
var apiPath = $"https://localhost:5001/{folderName}/{fileName}";
if (file.Length > 0)
{
using (var stream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
return apiPath;
}
}
}
|
64a2cca8dc3851e3487d13fd0579125ba380d6ba
|
C#
|
saerich/RaiderZ-Evolved-SDK
|
/CommonLibraryNET/0.9.6/Examples/Example_Cryptography.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Security.Cryptography;
using ComLib.Entities;
using ComLib.Account;
using ComLib;
using ComLib.Cryptography;
using ComLib.Application;
namespace ComLib.Samples
{
/// <summary>
/// Example of ActiveRecord Initialization/Configuration.
/// </summary>
public class Example_Cryptography : App
{
/// <summary>
/// Run the application.
/// </summary>
public override BoolMessageItem Execute()
{
// 1. Encrypt using default provider. ( Symmetric TripleDes )
string plainText = "www.knowledgedrink.com";
string encrypted = Crypto.Encrypt(plainText);
string decrypted = Crypto.Decrypt(encrypted);
Console.WriteLine("====================================================");
Console.WriteLine("CRYPTOGRAPHY ");
Console.WriteLine("Encrypted : " + plainText + " to " + encrypted);
Console.WriteLine("Decrypted : " + encrypted + " to " + decrypted);
Console.WriteLine(Environment.NewLine);
// 2. Use non-static encryption provider.
ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider());
string hashed = crypto.Encrypt("my baby - 2002 honda accord ex coupe");
Console.WriteLine(hashed);
// 3. Change the crypto provider on the static helper.
ICrypto crypto2 = new CryptoSym("new key", new TripleDESCryptoServiceProvider());
Crypto.Init(crypto2);
string encryptedWithNewKey = Crypto.Encrypt("www.knowledgedrink.com");
Console.WriteLine(string.Format("Encrypted text : using old key - {0}, using new key - {1}", encrypted, encryptedWithNewKey));
return BoolMessageItem.True;
}
}
}
|
463725c27bee30aa0bceb5468c664f59decf4066
|
C#
|
funwie/Checkout.PaymentGateway
|
/src/PaymentGateway.Domain/ValueObjects/Address.cs
| 2.8125
| 3
|
using PaymentGateway.SeedWork;
using System.Collections.Generic;
namespace PaymentGateway.Domain.ValueObjects
{
public class Address : ValueObject<Address>
{
public string HouseNumber { get; }
public string Line1 { get; }
public string Line2 { get; }
public string City { get; }
public string Postcode { get; }
public string Country { get; }
public Address(string houseNumber, string line1, string line2, string city, string postcode, string country)
{
HouseNumber = houseNumber;
Line1 = line1;
Line2 = line2;
City = city;
Postcode = postcode;
Country = country;
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return HouseNumber;
yield return Line1;
yield return Line2;
yield return City;
yield return Postcode;
yield return Country;
}
}
}
|
97508efe634edb64ffe45ff44e76fd17b27bf06c
|
C#
|
marcussacana/MangaUnhost
|
/MangaUnhost/Styles.cs
| 2.515625
| 3
|
using System;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
#region Global Functions/ Subs/ Enums
internal static class DrawHelpers {
public static GraphicsPath RoundRectangle(Rectangle Rectangle, int Curve) {
GraphicsPath P = new GraphicsPath();
int ArcRectangleWidth = Curve * 2;
P.AddArc(new Rectangle(Rectangle.X, Rectangle.Y, ArcRectangleWidth, ArcRectangleWidth), -180F, 90F);
P.AddArc(new Rectangle(Rectangle.Width - ArcRectangleWidth + Rectangle.X, Rectangle.Y, ArcRectangleWidth, ArcRectangleWidth), -90F, 90F);
P.AddArc(new Rectangle(Rectangle.Width - ArcRectangleWidth + Rectangle.X, Rectangle.Height - ArcRectangleWidth + Rectangle.Y, ArcRectangleWidth, ArcRectangleWidth), 0F, 90F);
P.AddArc(new Rectangle(Rectangle.X, Rectangle.Height - ArcRectangleWidth + Rectangle.Y, ArcRectangleWidth, ArcRectangleWidth), 90F, 90F);
P.AddLine(new Point(Rectangle.X, Rectangle.Height - ArcRectangleWidth + Rectangle.Y), new Point(Rectangle.X, Curve + Rectangle.Y));
return P;
}
public static GraphicsPath RoundRect(float x, float y, float w, float h, float r = 0.3F, bool TL = true, bool TR = true, bool BR = true, bool BL = true) {
GraphicsPath tempRoundRect = null;
float d = Math.Min(w, h) * r;
var xw = x + w;
var yh = y + h;
tempRoundRect = new GraphicsPath();
if (TL) {
tempRoundRect.AddArc(x, y, d, d, 180, 90);
} else {
tempRoundRect.AddLine(x, y, x, y);
}
if (TR) {
tempRoundRect.AddArc(xw - d, y, d, d, 270, 90);
} else {
tempRoundRect.AddLine(xw, y, xw, y);
}
if (BR) {
tempRoundRect.AddArc(xw - d, yh - d, d, d, 0, 90);
} else {
tempRoundRect.AddLine(xw, yh, xw, yh);
}
if (BL) {
tempRoundRect.AddArc(x, yh - d, d, d, 90, 90);
} else {
tempRoundRect.AddLine(x, yh, x, yh);
}
tempRoundRect.CloseFigure();
return tempRoundRect;
}
}
internal enum MouseState : byte {
None = 0,
Over = 1,
Down = 2,
Block = 3
}
#endregion
public class VSContainer : ContainerControl {
private bool InstanceFieldsInitialized = false;
private void InitializeInstanceFields() {
_Form = Form.ActiveForm;
}
#region Declarations
private bool _AllowClose = true;
private bool _AllowMinimize = true;
private bool _AllowMaximize = true;
private int _FontSize = 12;
private bool _ShowIcon = true;
private bool _NoTitleWrap = false;
private MouseState State = MouseState.None;
private int MouseXLoc;
private int MouseYLoc;
private bool CaptureMovement = false;
private const int MoveHeight = 35;
private Point MouseP = new Point(0, 0);
private Color _FontColour = Color.FromArgb(153, 153, 153);
private Color _BaseColour = Color.FromArgb(45, 45, 48);
private Color _IconColour = Color.FromArgb(255, 255, 255);
private Color _ControlBoxColours = Color.FromArgb(248, 248, 248);
private Color _BorderColour = Color.FromArgb(15, 15, 18);
private Color _HoverColour = Color.FromArgb(63, 63, 65);
private Color _PressedColour = Color.FromArgb(0, 122, 204);
private Font _Font = new Font("Microsoft Sans Serif", 9);
public enum __IconStyle {
VSIcon,
FormIcon
}
private __IconStyle _IconStyle = __IconStyle.FormIcon;
public enum __FormOrWhole {
WholeApplication,
Form
}
private __FormOrWhole _FormOrWhole = __FormOrWhole.WholeApplication;
private Form _Form;
#endregion
#region Properties
[Category("Control")]
public __FormOrWhole FormOrWhole {
get {
return _FormOrWhole;
}
set {
_FormOrWhole = value;
Invalidate();
}
}
[Category("Control")]
public Form Form {
get {
return _Form;
}
set {
if (value == null) {
return;
} else {
_Form = value;
}
Invalidate();
}
}
[Category("Control")]
public __IconStyle IconStyle {
get {
return _IconStyle;
}
set {
_IconStyle = value;
Invalidate();
}
}
[Category("Control")]
public int FontSize {
get {
return _FontSize;
}
set {
_FontSize = value;
Invalidate();
}
}
[Category("Control")]
public bool NoTitleWrap
{
get
{
return _NoTitleWrap;
}
set
{
_NoTitleWrap = value;
Invalidate();
}
}
[Category("Control")]
public new string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
Invalidate();
}
}
[Category("Control")]
public bool AllowMinimize {
get {
return _AllowMinimize;
}
set {
_AllowMinimize = value;
Invalidate();
}
}
[Category("Control")]
public bool AllowMaximize {
get {
return _AllowMaximize;
}
set {
_AllowMaximize = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowIcon {
get {
return _ShowIcon;
}
set {
_ShowIcon = value;
Invalidate();
}
}
[Category("Control")]
public bool AllowClose {
get {
return _AllowClose;
}
set {
_AllowClose = value;
Invalidate();
}
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color HoverColour {
get {
return _HoverColour;
}
set {
_HoverColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color FontColour {
get {
return _FontColour;
}
set {
_FontColour = value;
Invalidate();
}
}
private bool _ShowDots = false;
public bool ShowDots
{
get
{
return _ShowDots;
}
set
{
_ShowDots = value;
Invalidate();
}
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) {
base.OnMouseUp(e);
CaptureMovement = false;
State = MouseState.Over;
Invalidate();
}
protected override void OnMouseEnter(EventArgs e) {
base.OnMouseEnter(e);
State = MouseState.Over;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
base.OnMouseLeave(e);
State = MouseState.None;
Invalidate();
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
MouseXLoc = e.Location.X;
MouseYLoc = e.Location.Y;
Invalidate();
if (CaptureMovement) {
Parent.Location = MousePosition - (Size)MouseP;
}
if (e.Y > 26) {
Cursor = Cursors.Arrow;
} else {
Cursor = Cursors.Hand;
}
}
private delegate void _InvokeForm(MouseEventArgs e);
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
if (MouseXLoc > Width - 30 && MouseXLoc < Width && MouseYLoc < 26) {
if (_AllowClose) {
if (_FormOrWhole == __FormOrWhole.Form) {
if (_Form == null) {
Environment.Exit(0);
} else {
if (_Form.InvokeRequired) {
_Form.Invoke(new _InvokeForm(OnMouseDown), e);
} else {
_Form.Close();
}
}
} else {
Environment.Exit(0);
}
}
} else if (MouseXLoc > Width - 60 && MouseXLoc < Width - 30 && MouseYLoc < 26) {
if (_AllowMaximize) {
switch (FindForm().WindowState) {
case FormWindowState.Maximized:
FindForm().WindowState = FormWindowState.Normal;
break;
case FormWindowState.Normal:
FindForm().WindowState = FormWindowState.Maximized;
break;
}
}
} else if (MouseXLoc > Width - 90 && MouseXLoc < Width - 60 && MouseYLoc < 26) {
if (_AllowMinimize) {
switch (FindForm().WindowState) {
case FormWindowState.Normal:
FindForm().WindowState = FormWindowState.Minimized;
break;
case FormWindowState.Maximized:
FindForm().WindowState = FormWindowState.Minimized;
break;
}
}
} else if (e.Button == System.Windows.Forms.MouseButtons.Left && (new Rectangle(0, 0, Width - 90, MoveHeight)).Contains(e.Location)) {
CaptureMovement = true;
MouseP = e.Location;
} else if (e.Button == System.Windows.Forms.MouseButtons.Left && (new Rectangle(Width - 90, 22, 75, 13)).Contains(e.Location)) {
CaptureMovement = true;
MouseP = e.Location;
} else if (e.Button == System.Windows.Forms.MouseButtons.Left && (new Rectangle(Width - 15, 0, 15, MoveHeight)).Contains(e.Location)) {
CaptureMovement = true;
MouseP = e.Location;
} else {
Focus();
}
State = MouseState.Down;
Invalidate();
}
#endregion
#region Draw Control
public VSContainer() {
if (!InstanceFieldsInitialized) {
InitializeInstanceFields();
InstanceFieldsInitialized = true;
}
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
this.DoubleBuffered = true;
this.BackColor = _BaseColour;
this.Dock = DockStyle.Fill;
}
protected override void OnCreateControl() {
base.OnCreateControl();
ParentForm.FormBorderStyle = FormBorderStyle.None;
ParentForm.AllowTransparency = false;
ParentForm.TransparencyKey = Color.Fuchsia;
ParentForm.FindForm().StartPosition = FormStartPosition.CenterParent;
Dock = DockStyle.Fill;
Invalidate();
}
private Point[] Points1 = {
new Point(9, 11),
new Point(16, 17)
};
private Point[] Points2 = {
new Point(9, 22),
new Point(16, 17)
};
private Point[] Points3 = {
new Point(16, 17),
new Point(26, 7)
};
private Point[] Points4 = {
new Point(16, 17),
new Point(25, 26)
};
protected override void OnPaint(PaintEventArgs e) {
if (!(FindForm().MaximumSize == Screen.PrimaryScreen.WorkingArea.Size))
FindForm().MaximumSize = Screen.PrimaryScreen.WorkingArea.Size;
var G = e.Graphics;
G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
G.SmoothingMode = SmoothingMode.AntiAlias;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
G.FillRectangle(new SolidBrush(_BaseColour), new Rectangle(0, 0, Width, Height));
G.DrawRectangle(new Pen(_BorderColour), new Rectangle(0, 0, Width, Height));
switch (State) {
case MouseState.Over:
if (_AllowClose && MouseXLoc > Width - 30 && MouseXLoc < Width && MouseYLoc < 26) {
G.FillRectangle(new SolidBrush(_HoverColour), new Rectangle(Width - 30, 1, 29, 25));
} else if (_AllowMaximize && MouseXLoc > Width - 60 && MouseXLoc < Width - 30 && MouseYLoc < 26) {
G.FillRectangle(new SolidBrush(_HoverColour), new Rectangle(Width - 60, 1, 30, 25));
} else if (_AllowMinimize && MouseXLoc > Width - 90 && MouseXLoc < Width - 60 && MouseYLoc < 26) {
G.FillRectangle(new SolidBrush(_HoverColour), new Rectangle(Width - 90, 1, 30, 25));
}
break;
}
//'Close Button
if (_AllowClose) {
G.DrawLine(new Pen(_ControlBoxColours, 2F), Width - 20, 10, Width - 12, 18);
G.DrawLine(new Pen(_ControlBoxColours, 2F), Width - 20, 18, Width - 12, 10);
}
//'Minimize Button
if (_AllowMinimize) {
G.FillRectangle(new SolidBrush(_ControlBoxColours), Width - 79, 17, 8, 2);
}
//'Maximize Button
if (_AllowMaximize) {
if (FindForm().WindowState == FormWindowState.Normal) {
G.DrawString("1", new Font("Webdings", 9, FontStyle.Bold), new SolidBrush(_ControlBoxColours), new RectangleF(new Point(Width - 51, 5), new Size(20, 20)));
} else if (FindForm().WindowState == FormWindowState.Maximized) {
G.DrawString("2", new Font("Webdings", 9, FontStyle.Bold), new SolidBrush(_ControlBoxColours), new RectangleF(new Point(Width - 51, 5), new Size(20, 20)));
}
}
var TitleFormat = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Near
};
if (NoTitleWrap) {
TitleFormat.FormatFlags |= StringFormatFlags.NoWrap;
}
if (_ShowIcon) {
var TitleArea = new RectangleF(37F, 0F, Width - 110, 32F);
var eta = new RectangleF(TitleArea.Width + 33F, 0, Width - 100, 30F);
switch (_IconStyle) {
case __IconStyle.FormIcon:
//G.DrawIcon(FindForm().Icon, new Rectangle(6, 6, 22, 22));
G.DrawImage(MangaUnhost.Properties.Resources.Book, 6, 6, 22, 22);
G.DrawString(Text, _Font, new SolidBrush(_FontColour), TitleArea, TitleFormat);
break;
default:
G.DrawLines(new Pen(_IconColour, 3F), Points1);
G.DrawLines(new Pen(_IconColour, 3F), Points2);
G.DrawLines(new Pen(_IconColour, 4F), Points3);
G.DrawLines(new Pen(_IconColour, 4F), Points4);
G.DrawLine(new Pen(_IconColour, 3F), new Point(9, 11), new Point(9, 22));
G.DrawLine(new Pen(_IconColour, 4F), 26, 6, 26, 28);
G.DrawString(Text, _Font, new SolidBrush(_FontColour), TitleArea, TitleFormat);
break;
}
if (_ShowDots)
{
G.DrawString("...", _Font, new SolidBrush(_FontColour), eta, TitleFormat);
}
} else {
var TitleArea = new RectangleF(5F, 0F, Width - 80, 30F);
var eta = new RectangleF(TitleArea.Width -1, 0, Width - 100, 30F);
// Funcionando no modo BR
//G.DrawString(Text.Substring(0, 20) + "...", _Font, new SolidBrush(_FontColour), TitleArea, TitleFormat);
G.DrawString(Text, _Font, new SolidBrush(_FontColour), TitleArea, TitleFormat);
if(_ShowDots)
{
G.DrawString("...", _Font, new SolidBrush(_FontColour), eta, TitleFormat);
}
}
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
public class VSButton : Control {
#region Declarations
private MouseState State = MouseState.None;
private Color _FontColour = Color.FromArgb(153, 153, 153);
private Color _BaseColour = Color.FromArgb(45, 45, 48);
private Color _IconColour = Color.FromArgb(255, 255, 255);
private Color _BorderColour = Color.FromArgb(15, 15, 18);
private Color _HoverColour = Color.FromArgb(60, 60, 62);
private Color _PressedColour = Color.FromArgb(37, 37, 39);
private bool _ShowBorder = true;
private bool _ShowImage = false;
private bool _ShowText = true;
private Image _Image = null;
private StringAlignment _TextAlignment = StringAlignment.Center;
private __ImageAlignment _ImageAlignment = __ImageAlignment.Left;
#endregion
#region Properties
public enum __ImageAlignment {
Left,
Middle,
Right
}
[Category("Control")]
public __ImageAlignment ImageAlignment {
get {
return _ImageAlignment;
}
set {
if (_ShowText && (value == __ImageAlignment.Middle)) {
_ImageAlignment = __ImageAlignment.Left;
} else {
_ImageAlignment = value;
}
Invalidate();
}
}
[Category("Control")]
public Image ImageChoice {
get {
return _Image;
}
set {
_Image = value;
Invalidate();
}
}
[Category("Control")]
public StringAlignment TextAlignment {
get {
return _TextAlignment;
}
set {
_TextAlignment = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowImage {
get {
return _ShowImage;
}
set {
_ShowImage = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowText {
get {
return _ShowText;
}
set {
if ((_ImageAlignment == __ImageAlignment.Middle) && (ShowImage == true) && (value == true)) {
_ImageAlignment = __ImageAlignment.Left;
}
_ShowText = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowBorder {
get {
return _ShowBorder;
}
set {
_ShowBorder = value;
Invalidate();
}
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
[Category("Colours")]
public Color HoverColour {
get {
return _HoverColour;
}
set {
_HoverColour = value;
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color FontColour {
get {
return _FontColour;
}
set {
_FontColour = value;
}
}
public object Indentifier;
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) {
base.OnMouseUp(e);
State = MouseState.Over;
Invalidate();
}
protected override void OnMouseEnter(EventArgs e) {
base.OnMouseEnter(e);
State = MouseState.Over;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
base.OnMouseLeave(e);
State = MouseState.None;
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
State = MouseState.Down;
Invalidate();
}
#endregion
#region Draw Control
public VSButton() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
this.DoubleBuffered = true;
this.BackColor = _BaseColour;
}
protected override void OnPaint(PaintEventArgs e) {
var G = e.Graphics;
G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
G.SmoothingMode = SmoothingMode.AntiAlias;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
switch (State) {
case MouseState.None:
G.FillRectangle(new SolidBrush(_BaseColour), new Rectangle(0, 0, Width, Height));
break;
case MouseState.Over:
G.FillRectangle(new SolidBrush(_HoverColour), new Rectangle(0, 0, Width, Height));
break;
case MouseState.Down:
G.FillRectangle(new SolidBrush(_PressedColour), new Rectangle(0, 0, Width, Height));
break;
}
if (_ShowBorder) {
G.DrawRectangle(new Pen(_BorderColour, 1F), new Rectangle(0, 0, Width, Height));
}
if (_ShowImage) {
if (_ShowText) {
if ((Width > 50) && (Height > 30)) {
if (_ImageAlignment == __ImageAlignment.Left) {
G.DrawImage(_Image, new Rectangle(10, 10, Height - 20, Height - 20));
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(0 + (Height - 5), 0, (Width - 20) - (Height - 10), Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
} else if (_ImageAlignment == __ImageAlignment.Right) {
G.DrawImage(_Image, new Rectangle((Width - 20) - (Height - 20), 10, Height - 20, Height - 20));
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(10, 0, (Width - 20) - (Height - 20), Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
}
} else {
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(10, 0, Width - 20, Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
}
} else {
if (_ImageAlignment == __ImageAlignment.Left) {
G.DrawImage(_Image, new Rectangle(10, 10, Height - 20, Height - 20));
} else if (_ImageAlignment == __ImageAlignment.Middle) {
G.DrawImage(_Image, new Rectangle(Convert.ToInt32((Width / 2) - ((Height - 20) / 2)), 10, Height - 20, Height - 20));
} else {
G.DrawImage(_Image, new Rectangle((Width - 10) - (Height - 20), 10, Height - 20, Height - 20));
}
}
} else {
if (_ShowText) {
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(10, 0, Width - 20, Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
}
}
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
#region Functions
public void PerformClick()
{
OnClick(EventArgs.Empty);
}
#endregion
}
public class VSSeperator : Control {
#region Declarations
private Color _FontColour = Color.FromArgb(153, 153, 153);
private Color _LineColour = Color.FromArgb(0, 122, 204);
private Font _Font = new Font("Microsoft Sans Serif", 8);
private bool _ShowText;
private StringAlignment _TextAlignment = StringAlignment.Center;
private __TextLocation _TextLocation = __TextLocation.Left;
private bool _AddEndNotch = false;
private bool _UnderlineText = false;
private bool _ShowTextAboveLine = false;
private bool _OnlyUnderlineText = false;
#endregion
#region Properties
[Category("Control")]
public __TextLocation TextLocation {
get {
return _TextLocation;
}
set {
_TextLocation = value;
Invalidate();
}
}
[Category("Control")]
public StringAlignment TextAlignment {
get {
return _TextAlignment;
}
set {
_TextAlignment = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowTextAboveLine {
get {
return _ShowTextAboveLine;
}
set {
_ShowTextAboveLine = value;
Invalidate();
}
}
[Category("Control")]
public bool OnlyUnderlineText {
get {
return _OnlyUnderlineText;
}
set {
_OnlyUnderlineText = value;
Invalidate();
}
}
[Category("Control")]
public bool UnderlineText {
get {
return _UnderlineText;
}
set {
_UnderlineText = value;
Invalidate();
}
}
[Category("Control")]
public bool AddEndNotch {
get {
return _AddEndNotch;
}
set {
_AddEndNotch = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowText {
get {
return _ShowText;
}
set {
_ShowText = value;
Invalidate();
}
}
[Category("Colours")]
public Color LineColour {
get {
return _LineColour;
}
set {
_LineColour = value;
}
}
[Category("Colours")]
public Color FontColour {
get {
return _FontColour;
}
set {
_FontColour = value;
}
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
if (_ShowText && (Height < Font.Size * 2 + 3)) {
this.Size = new Size(Width, Convert.ToInt32(Font.Size * 2 + 3));
}
Invalidate();
}
public enum __TextLocation {
Left,
Middle,
Right
}
#endregion
#region Draw Control
public VSSeperator() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
this.DoubleBuffered = true;
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e) {
var G = e.Graphics;
G.TextRenderingHint = TextRenderingHint.AntiAlias;
G.SmoothingMode = SmoothingMode.AntiAlias;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
if (_ShowText && !_ShowTextAboveLine) {
switch (_TextLocation) {
case __TextLocation.Left:
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(0, 0, Convert.ToInt32(G.MeasureString(Text, Font).Width + 10), Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
G.DrawLine(new Pen(_LineColour), new Point(Convert.ToInt32(G.MeasureString(Text, Font).Width + 20), Convert.ToInt32(Height / 2)), new Point(Convert.ToInt32(Width), Convert.ToInt32(Height / 2)));
if (_AddEndNotch) {
G.DrawLine(new Pen(_LineColour), new Point(Width - 1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(Width - 1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
}
if (_UnderlineText) {
G.DrawLine(new Pen(_LineColour), 0, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3, Convert.ToInt32(G.MeasureString(Text, Font).Width + 20), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3);
G.DrawLine(new Pen(_LineColour), Convert.ToInt32(G.MeasureString(Text, Font).Width + 20), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3, Convert.ToInt32(G.MeasureString(Text, Font).Width + 20), Convert.ToInt32(Height / 2));
}
break;
case __TextLocation.Middle:
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(Convert.ToInt32((Width / 2) - (G.MeasureString(Text, Font).Width / 2.0) - 10), 0, Convert.ToInt32(G.MeasureString(Text, Font).Width) + 10, Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
G.DrawLine(new Pen(_LineColour), new Point(0, Convert.ToInt32(Height / 2)), new Point((Convert.ToInt32((Width / 2) - (G.MeasureString(Text, Font).Width / 2.0) - 20)), Convert.ToInt32(Height / 2)));
G.DrawLine(new Pen(_LineColour), new Point((Convert.ToInt32((Width / 2) + (G.MeasureString(Text, Font).Width / 2.0) + 10)), Convert.ToInt32(Height / 2)), new Point(Width, Convert.ToInt32(Height / 2)));
if (_AddEndNotch) {
G.DrawLine(new Pen(_LineColour), new Point(Width - 1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(Width - 1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
G.DrawLine(new Pen(_LineColour), new Point(1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
}
if (_UnderlineText) {
G.DrawLine(new Pen(_LineColour), (Convert.ToInt32((Width / 2) - (G.MeasureString(Text, Font).Width / 2.0) - 20)), Convert.ToInt32(Height / 2), (Convert.ToInt32((Width / 2) - (G.MeasureString(Text, Font).Width / 2.0) - 20)), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3);
G.DrawLine(new Pen(_LineColour), (Convert.ToInt32((Width / 2) + (G.MeasureString(Text, Font).Width / 2.0) + 10)), Convert.ToInt32(Height / 2), (Convert.ToInt32((Width / 2) + (G.MeasureString(Text, Font).Width / 2.0) + 10)), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3);
G.DrawLine(new Pen(_LineColour), (Convert.ToInt32((Width / 2) - (G.MeasureString(Text, Font).Width / 2.0) - 20)), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3, (Convert.ToInt32((Width / 2) + (G.MeasureString(Text, Font).Width / 2.0) + 10)), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3);
}
break;
case __TextLocation.Right:
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(Convert.ToInt32(Width - G.MeasureString(Text, Font).Width - 10), 0, Convert.ToInt32(G.MeasureString(Text, Font).Width + 10), Height), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Center });
G.DrawLine(new Pen(_LineColour), new Point(0, Convert.ToInt32(Height / 2)), new Point(Convert.ToInt32(Width - G.MeasureString(Text, Font).Width - 20), Convert.ToInt32(Height / 2)));
if (_AddEndNotch) {
G.DrawLine(new Pen(_LineColour), new Point(1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
}
if (_UnderlineText) {
G.DrawLine(new Pen(_LineColour), Convert.ToInt32(Width - G.MeasureString(Text, Font).Width - 20), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3, Width, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3);
G.DrawLine(new Pen(_LineColour), Convert.ToInt32(Width - G.MeasureString(Text, Font).Width - 20), Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0) + 3, Convert.ToInt32(Width - G.MeasureString(Text, Font).Width - 20), Convert.ToInt32(Height / 2));
}
break;
}
} else if ((_ShowText) && (_ShowTextAboveLine)) {
if (_OnlyUnderlineText) {
G.DrawLine(new Pen(_LineColour), new Point(5, Convert.ToInt32(Height / 2) + 6), new Point(Convert.ToInt32(G.MeasureString(Text, Font).Width + 8), Convert.ToInt32(Height / 2) + 6));
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(5, 0, Width - 10, Convert.ToInt32(Height / 2 + 3)), new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far });
} else {
G.DrawLine(new Pen(_LineColour), new Point(0, Convert.ToInt32(Height / 2) + 6), new Point(Width, Convert.ToInt32(Height / 2) + 6));
if (_AddEndNotch) {
G.DrawLine(new Pen(_LineColour), new Point(Width - 1, Convert.ToInt32(Height / 2) - 5), new Point(Width - 1, Convert.ToInt32((Height / 2) + 5)));
G.DrawLine(new Pen(_LineColour), new Point(1, Convert.ToInt32(Height / 2) - 5), new Point(1, Convert.ToInt32((Height / 2) + 5)));
}
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(5, 0, Width - 10, Convert.ToInt32(Height / 2 + 3)), new StringFormat { Alignment = _TextAlignment, LineAlignment = StringAlignment.Far });
}
} else {
if (_OnlyUnderlineText) {
G.DrawLine(new Pen(_LineColour), new Point(5, Convert.ToInt32(Height / 2) + 6), new Point(Convert.ToInt32(G.MeasureString(Text, Font).Width + 8), Convert.ToInt32(Height / 2) + 6));
G.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(5, 0, Width - 10, Convert.ToInt32(Height / 2 + 3)), new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far });
} else {
G.DrawLine(new Pen(_LineColour), new Point(0, Convert.ToInt32(Height / 2)), new Point(Width, Convert.ToInt32(Height / 2)));
if (_AddEndNotch) {
G.DrawLine(new Pen(_LineColour), new Point(Width - 1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(Width - 1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
G.DrawLine(new Pen(_LineColour), new Point(1, Convert.ToInt32((Height / 2) - G.MeasureString(Text, Font).Height / 2.0)), new Point(1, Convert.ToInt32((Height / 2) + G.MeasureString(Text, Font).Height / 2.0)));
}
}
}
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
public class VSStatusBar : Control {
#region Variables
private Color _TextColour = Color.FromArgb(255, 255, 255);
private Color _BaseColour = Color.FromArgb(0, 122, 204); //Color.FromArgb(45, 45, 48);
private Color _WaitingBaseColour = Color.FromArgb(104, 33, 122);
private Color _RectColour = Color.FromArgb(45, 45, 48); //Color.FromArgb(0, 122, 204);
private Color _BorderColour = Color.FromArgb(27, 27, 29);
private Color _SeperatorColour = Color.FromArgb(45, 45, 48);
private bool _ShowLine = true;
private LinesCount _LinesToShow = LinesCount.One;
private AmountOfStrings _NumberOfStrings = AmountOfStrings.One;
private bool _ShowBorder = true;
private StringFormat _FirstLabelStringFormat;
private string _FirstLabelText = "Label1";
private Alignments _FirstLabelAlignment = Alignments.Left;
private StringFormat _SecondLabelStringFormat;
private string _SecondLabelText = "Label2";
private Alignments _SecondLabelAlignment = Alignments.Center;
private StringFormat _ThirdLabelStringFormat;
private string _ThirdLabelText = "Label3";
private Alignments _ThirdLabelAlignment = Alignments.Center;
#endregion
#region Properties
[Category("First Label Options")]
public string FirstLabelText {
get {
return _FirstLabelText;
}
set {
_FirstLabelText = value;
Invalidate();
}
}
[Category("First Label Options")]
public Alignments FirstLabelAlignment {
get {
return _FirstLabelAlignment;
}
set {
switch (value) {
case Alignments.Left:
_FirstLabelStringFormat = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_FirstLabelAlignment = value;
break;
case Alignments.Center:
_FirstLabelStringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_FirstLabelAlignment = value;
break;
case Alignments.Right:
_FirstLabelStringFormat = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_FirstLabelAlignment = value;
break;
}
}
}
[Category("Second Label Options")]
public string SecondLabelText {
get {
return _SecondLabelText;
}
set {
_SecondLabelText = value;
Invalidate();
}
}
[Category("Second Label Options")]
public Alignments SecondLabelAlignment {
get {
return _SecondLabelAlignment;
}
set {
switch (value) {
case Alignments.Left:
_SecondLabelStringFormat = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_SecondLabelAlignment = value;
break;
case Alignments.Center:
_SecondLabelStringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_SecondLabelAlignment = value;
break;
case Alignments.Right:
_SecondLabelStringFormat = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_SecondLabelAlignment = value;
break;
}
}
}
[Category("Third Label Options")]
public string ThirdLabelText {
get {
return _ThirdLabelText;
}
set {
_ThirdLabelText = value;
Invalidate();
}
}
[Category("Third Label Options")]
public Alignments ThirdLabelAlignment {
get {
return _ThirdLabelAlignment;
}
set {
switch (value) {
case Alignments.Left:
_ThirdLabelStringFormat = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_ThirdLabelAlignment = value;
break;
case Alignments.Center:
_ThirdLabelStringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_ThirdLabelAlignment = value;
break;
case Alignments.Right:
_ThirdLabelStringFormat = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap };
_ThirdLabelAlignment = value;
break;
}
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color WaitingBaseColour {
get {
return _WaitingBaseColour;
}
set {
_WaitingBaseColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color TextColour {
get {
return _TextColour;
}
set {
_TextColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color SeperatorColour {
get {
return _SeperatorColour;
}
set {
_SeperatorColour = value;
Invalidate();
}
}
public enum LinesCount : int {
None = 0,
One = 1,
Two = 2
}
public enum AmountOfStrings {
One,
Two,
Three
}
public enum Alignments {
Left,
Center,
Right
}
private bool _showImage = true;
public bool showImage {
get => _showImage;
set {
_showImage = value;
Invalidate();
}
}
private Image _imageToShow;
public Image imagetoShow {
get => _imageToShow;
set {
_imageToShow = value;
Invalidate();
}
}
[Category("Control")]
public AmountOfStrings AmountOfString {
get {
return _NumberOfStrings;
}
set {
_NumberOfStrings = value;
}
}
[Category("Control")]
public LinesCount LinesToShow {
get {
return _LinesToShow;
}
set {
_LinesToShow = value;
}
}
public bool ShowBorder {
get {
return _ShowBorder;
}
set {
_ShowBorder = value;
}
}
protected override void CreateHandle() {
base.CreateHandle();
Dock = DockStyle.Bottom;
}
[Category("Colours")]
public Color RectangleColor {
get {
return _RectColour;
}
set {
_RectColour = value;
}
}
public bool ShowLine {
get {
return _ShowLine;
}
set {
_ShowLine = value;
}
}
#endregion
#region Draw Control
public VSStatusBar() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
DoubleBuffered = true;
Font = new Font("Segoe UI", 9);
Size = new Size(Width, 20);
Cursor = Cursors.Arrow;
}
protected override void OnPaint(PaintEventArgs e) {
var G = e.Graphics;
Rectangle Base = new Rectangle(0, 0, Width, Height);
G.SmoothingMode = SmoothingMode.HighQuality;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
G.FillRectangle(new SolidBrush(_FirstLabelText.EndsWith("...") || _FirstLabelText.Contains("... ") ? WaitingBaseColour : BaseColour), Base);
switch (_LinesToShow) {
case LinesCount.None:
if (_NumberOfStrings == AmountOfStrings.One) {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(5, 1, Width - 5, Height), _FirstLabelStringFormat);
} else if (_NumberOfStrings == AmountOfStrings.Two) {
var FirstRectangle = new Rectangle(5, 1, Convert.ToInt32((Width / 2 - 6)), Height);
var SecondRectangle = new Rectangle(Convert.ToInt32(Width - (Width / 2 + 5)), 1, Convert.ToInt32(Width / 2 - 4), Height);
var PenPointA = new Point(Convert.ToInt32(Width / 2), 6);
var PenPointB = new Point(Convert.ToInt32(Width - (Width / 3) * 2), Height - 6);
if (_SecondLabelAlignment == Alignments.Right) {
var Measured = G.MeasureString(_FirstLabelText, Font, FirstRectangle.Width, _FirstLabelStringFormat);
if (Measured.Width < FirstRectangle.Width) {
FirstRectangle.Width = (int)Measured.Width + 1;
PenPointA = new Point(FirstRectangle.X + FirstRectangle.Width + 1, 6);
PenPointB = new Point(FirstRectangle.X + FirstRectangle.Width + 1, Height - 6);
SecondRectangle = new Rectangle(PenPointA.X + 4, SecondRectangle.Y, Width - (PenPointA.X + 4), SecondRectangle.Height);
}
}
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), FirstRectangle, _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), SecondRectangle, _SecondLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), PenPointA, PenPointB);
} else {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(5, 1, Convert.ToInt32((Width - (Width / 3) * 2) - 6), Height), _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) * 2 + 5), 1, Convert.ToInt32(Width - (Width / 3) * 2 - 6), Height), _SecondLabelStringFormat);
G.DrawString(_ThirdLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) + 5), 1, Convert.ToInt32(Width / 3 - 6), Height), _ThirdLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3) * 2), 6), new Point(Convert.ToInt32(Width - (Width / 3) * 2), Height - 6));
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3)), 6), new Point(Convert.ToInt32(Width - (Width / 3)), Height - 6));
}
break;
case LinesCount.One:
if (_NumberOfStrings == AmountOfStrings.One) {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(22, 1, Width, Height), _FirstLabelStringFormat);
} else if (_NumberOfStrings == AmountOfStrings.Two) {
var FirstRectangle = new Rectangle(22, 1, Convert.ToInt32((Width / 2 - 24)), Height);
var SecondRectangle = new Rectangle(Convert.ToInt32((Width / 2 + 5)), 1, Convert.ToInt32(Width / 2 - 10), Height);
var PenPointA = new Point(Convert.ToInt32(Width / 2), 6);
var PenPointB = new Point(Convert.ToInt32(Width - (Width / 3) * 2), Height - 6);
if (_SecondLabelAlignment == Alignments.Right) {
var Measured = G.MeasureString(_FirstLabelText, Font, FirstRectangle.Width, _FirstLabelStringFormat);
if (Measured.Width < FirstRectangle.Width) {
FirstRectangle.Width = (int)Measured.Width + 1;
PenPointA = new Point(FirstRectangle.X + FirstRectangle.Width + 1, 6);
PenPointB = new Point(FirstRectangle.X + FirstRectangle.Width + 1, Height - 6);
SecondRectangle = new Rectangle(PenPointA.X + 4, SecondRectangle.Y, Width - (PenPointA.X + 4), SecondRectangle.Height);
}
}
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), FirstRectangle, _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), SecondRectangle, _SecondLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), PenPointA, PenPointB);
} else {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(22, 1, Convert.ToInt32((Width - 78) / 3), Height), _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) * 2 + 5), 1, Convert.ToInt32(Width - (Width / 3) * 2 - 12), Height), _SecondLabelStringFormat);
G.DrawString(_ThirdLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) + 6), 1, Convert.ToInt32(Width / 3 - 22), Height), _ThirdLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3) * 2), 6), new Point(Convert.ToInt32(Width - (Width / 3) * 2), Height - 6));
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3)), 6), new Point(Convert.ToInt32(Width - (Width / 3)), Height - 6));
}
//Icon
if (_showImage == true && _imageToShow != null)
//G.FillRectangle(new SolidBrush(_RectColour), new Rectangle(5, 10, 14, 3));
G.DrawImage(new Bitmap(_imageToShow), new Rectangle(2, 10, 15, 15));
break;
case LinesCount.Two:
if (_NumberOfStrings == AmountOfStrings.One) {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(22, 1, Width - 44, Height), _FirstLabelStringFormat);
} else if (_NumberOfStrings == AmountOfStrings.Two) {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(22, 1, Convert.ToInt32((Width - 46) / 2), Height), _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32((Width / 2 + 5)), 1, Convert.ToInt32(Width / 2 - 28), Height), _SecondLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width / 2), 6), new Point(Convert.ToInt32(Width / 2), Height - 6));
} else {
G.DrawString(_FirstLabelText, Font, new SolidBrush(_TextColour), new Rectangle(22, 1, Convert.ToInt32((Width - 78) / 3), Height), _FirstLabelStringFormat);
G.DrawString(_SecondLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) * 2 + 5), 1, Convert.ToInt32(Width - (Width / 3) * 2 - 12), Height), _SecondLabelStringFormat);
G.DrawString(_ThirdLabelText, Font, new SolidBrush(_TextColour), new Rectangle(Convert.ToInt32(Width - (Width / 3) + 6), 1, Convert.ToInt32(Width / 3 - 22), Height), _ThirdLabelStringFormat);
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3) * 2), 6), new Point(Convert.ToInt32(Width - (Width / 3) * 2), Height - 6));
G.DrawLine(new Pen(_SeperatorColour, 1F), new Point(Convert.ToInt32(Width - (Width / 3)), 6), new Point(Convert.ToInt32(Width - (Width / 3)), Height - 6));
}
G.FillRectangle(new SolidBrush(_SeperatorColour), new Rectangle(5, 10, 14, 3));
G.FillRectangle(new SolidBrush(_SeperatorColour), new Rectangle(Width - 20, 10, 14, 3));
break;
}
if (_ShowBorder) {
G.DrawRectangle(new Pen(_BorderColour, 2F), new Rectangle(0, 0, Width, Height));
} else {
}
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
[DefaultEvent("Scroll")]
public class VSVerticalScrollBar : Control {
#region Declarations
private Color _BaseColour = Color.FromArgb(62, 62, 66);
private Color _ThumbNormalColour = Color.FromArgb(104, 104, 104);
private Color _ThumbHoverColour = Color.FromArgb(158, 158, 158);
private Color _ThumbPressedColour = Color.FromArgb(239, 235, 239);
private Color _ArrowNormalColour = Color.FromArgb(153, 153, 153);
private Color _ArrowHoveerColour = Color.FromArgb(39, 123, 181);
private Color _ArrowPressedColour = Color.FromArgb(0, 113, 171);
private Color _OuterBorderColour;
private Color _ThumbBorderColour;
public int _Minimum = 0;
public int _Maximum = 100;
private int _Value = 0;
public int _SmallChange = 1;
private int _ButtonSize = 16;
public int _LargeChange = 10;
private bool _ShowOuterBorder = false;
private bool _ShowThumbBorder = false;
private __InnerLineCount _AmountOfInnerLines = __InnerLineCount.None;
private Point _MousePos = new Point(_MouseXLoc, _MouseYLoc);
private MouseState _ThumbState = MouseState.None;
private MouseState _ArrowState = MouseState.None;
private static int _MouseXLoc;
private static int _MouseYLoc;
private int ThumbMovement;
private Rectangle TSA;
private Rectangle BSA;
private Rectangle Shaft;
private Rectangle Thumb;
private bool ShowThumb;
private bool ThumbPressed;
private int _ThumbSize = 24;
#endregion
#region Properties & Events
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color ThumbNormalColour {
get {
return _ThumbNormalColour;
}
set {
_ThumbNormalColour = value;
}
}
[Category("Colours")]
public Color ThumbHoverColour {
get {
return _ThumbHoverColour;
}
set {
_ThumbHoverColour = value;
}
}
[Category("Colours")]
public Color ThumbPressedColour {
get {
return _ThumbPressedColour;
}
set {
_ThumbPressedColour = value;
}
}
[Category("Colours")]
public Color ArrowNormalColour {
get {
return _ArrowNormalColour;
}
set {
_ArrowNormalColour = value;
}
}
[Category("Colours")]
public Color ArrowHoveerColour {
get {
return _ArrowHoveerColour;
}
set {
_ArrowHoveerColour = value;
}
}
[Category("Colours")]
public Color ArrowPressedColour {
get {
return _ArrowPressedColour;
}
set {
_ArrowPressedColour = value;
}
}
[Category("Colours")]
public Color OuterBorderColour {
get {
return _OuterBorderColour;
}
set {
_OuterBorderColour = value;
}
}
[Category("Colours")]
public Color ThumbBorderColour {
get {
return _ThumbBorderColour;
}
set {
_ThumbBorderColour = value;
}
}
[Category("Control")]
public int Minimum {
get {
return _Minimum;
}
set {
_Minimum = value;
if (value > _Value) {
_Value = value;
}
if (value > _Maximum) {
_Maximum = value;
}
_Minimum = value;
InvalidateLayout();
}
}
[Category("Control")]
public int Maximum {
get {
return _Maximum;
}
set {
if (value < _Value) {
_Value = value;
}
if (value < _Minimum) {
_Minimum = value;
}
_Maximum = value;
InvalidateLayout();
}
}
[Category("Control")]
public int Value {
get {
return _Value;
}
set {
if (value == _Value) {
return;
}
else if (value < _Minimum) {
_Value = _Minimum;
}
else if (value > _Maximum) {
_Value = _Maximum;
}
else {
_Value = value;
}
InvalidatePosition();
if (Scroll != null)
Scroll(this);
}
}
[Category("Control")]
public int SmallChange {
get {
return _SmallChange;
}
set {
if (value < 1)
_SmallChange = 1;
else
_SmallChange = value;
InvalidateLayout();
}
}
[Category("Control")]
public int LargeChange {
get {
return _LargeChange;
}
set {
if (value < 1)
_LargeChange = 1;
else
_LargeChange = value;
InvalidateLayout();
}
}
[Category("Control")]
public int ButtonSize {
get {
return _ButtonSize;
}
set {
if (value < 16) {
_ButtonSize = 16;
}
else {
_ButtonSize = value;
}
InvalidateLayout();
}
}
[Category("Control")]
public bool ShowOuterBorder {
get {
return _ShowOuterBorder;
}
set {
_ShowOuterBorder = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowThumbBorder {
get {
return _ShowThumbBorder;
}
set {
_ShowThumbBorder = value;
Invalidate();
}
}
[Category("Control")]
public __InnerLineCount AmountOfInnerLines {
get {
return _AmountOfInnerLines;
}
set {
_AmountOfInnerLines = value;
}
}
protected override void OnSizeChanged(EventArgs e) {
InvalidateLayout();
}
private void InvalidateLayout() {
//'End Height here goes with end in invalidateposition() for starting height of thumb
TSA = new Rectangle(0, 0, Width, 16);
BSA = new Rectangle(0, Height - ButtonSize, Width, ButtonSize);
//'End height here should be double the start for symetry
Shaft = new Rectangle(0, TSA.Bottom + 1, Width, Convert.ToInt32(Height - Height / 8 - 8));
ShowThumb = Convert.ToBoolean(((_Maximum - _Minimum)));
if (ShowThumb) {
Thumb = new Rectangle(4, 0, Width - 8, Convert.ToInt32(Height / 8));
}
if (Scroll != null)
Scroll(this);
InvalidatePosition();
}
public enum __InnerLineCount {
None,
One,
Two,
Three
}
public delegate void ScrollEventHandler(object sender);
public event ScrollEventHandler Scroll;
public void InvalidatePosition() {
Thumb.Y = Convert.ToInt32(((_Value - _Minimum) / (double)(_Maximum - _Minimum)) * (Shaft.Height - _ThumbSize) + 16);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Left && ShowThumb) {
if (TSA.Contains(e.Location)) {
_ArrowState = MouseState.Down;
ThumbMovement = _Value - _SmallChange;
} else if (BSA.Contains(e.Location)) {
ThumbMovement = _Value + _SmallChange;
_ArrowState = MouseState.Down;
} else {
if (Thumb.Contains(e.Location)) {
_ThumbState = MouseState.Down;
Invalidate();
return;
} else {
if (e.Y < Thumb.Y) {
ThumbMovement = _Value - _LargeChange;
} else {
ThumbMovement = _Value + _LargeChange;
}
}
}
Value = Math.Min(Math.Max(ThumbMovement, _Minimum), _Maximum);
Invalidate();
InvalidatePosition();
}
}
protected override void OnMouseMove(MouseEventArgs e) {
_MouseXLoc = e.Location.X;
_MouseYLoc = e.Location.Y;
if (TSA.Contains(e.Location)) {
_ArrowState = MouseState.Over;
} else if (BSA.Contains(e.Location)) {
_ArrowState = MouseState.Over;
} else if (!(_ArrowState == MouseState.Down)) {
_ArrowState = MouseState.None;
}
if (Thumb.Contains(e.Location) && !(_ThumbState == MouseState.Down)) {
_ThumbState = MouseState.Over;
} else if (!(_ThumbState == MouseState.Down)) {
_ThumbState = MouseState.None;
}
Invalidate();
if (_ThumbState == MouseState.Down || _ArrowState == MouseState.Down && ShowThumb) {
int ThumbPosition = e.Y + 2 - TSA.Height - (_ThumbSize / 2);
int ThumbBounds = Shaft.Height - _ThumbSize;
ThumbMovement = Convert.ToInt32((ThumbPosition / (double)ThumbBounds) * (_Maximum - _Minimum)) - _Minimum;
Value = Math.Min(Math.Max(ThumbMovement, _Minimum), _Maximum);
InvalidatePosition();
}
}
protected override void OnMouseUp(MouseEventArgs e) {
if (Thumb.Contains(e.Location)) {
_ThumbState = MouseState.Over;
} else if (!(Thumb.Contains(e.Location))) {
_ThumbState = MouseState.None;
}
if (e.Location.Y < 16 || e.Location.Y > Width - 16) {
_ThumbState = MouseState.Over;
} else if (!(e.Location.Y < 16) || e.Location.Y > Width - 16) {
_ThumbState = MouseState.None;
}
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
_ThumbState = MouseState.None;
_ArrowState = MouseState.None;
Invalidate();
}
protected override void OnMouseEnter(EventArgs e) {
base.OnMouseEnter(e);
Invalidate();
}
#endregion
#region Draw Control
public VSVerticalScrollBar() {
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
Size = new Size(19, 50);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(_BaseColour);
Point[] TrianglePointTop = {
new Point(Convert.ToInt32(Width / 2), 5),
new Point(Convert.ToInt32(Width / 4), 11),
new Point(Convert.ToInt32(Width / 2 + Width / 4), 11)
};
Point[] TrianglePointBottom = {
new Point(Convert.ToInt32(Width / 2), Height - 5),
new Point(Convert.ToInt32(Width / 4), Height - 11),
new Point(Convert.ToInt32(Width / 2 + Width / 4), Height - 11)
};
switch (_ThumbState) {
case MouseState.None:
using (SolidBrush SBrush = new SolidBrush(_ThumbNormalColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
case MouseState.Over:
using (SolidBrush SBrush = new SolidBrush(_ThumbHoverColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
case MouseState.Down:
using (SolidBrush SBrush = new SolidBrush(_ThumbPressedColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
}
switch (_ArrowState) {
case MouseState.Down:
if (!(Thumb.Contains(_MousePos))) {
using (SolidBrush SBrush = new SolidBrush(_ThumbNormalColour)) {
g.FillRectangle(SBrush, Thumb);
}
}
if (_MouseYLoc < 16) {
g.FillPolygon(new SolidBrush(_ArrowPressedColour), TrianglePointTop);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointBottom);
} else if (_MouseXLoc > Width - 16) {
g.FillPolygon(new SolidBrush(_ArrowPressedColour), TrianglePointBottom);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointTop);
} else {
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointTop);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointBottom);
}
break;
case MouseState.Over:
if (_MouseYLoc < 16) {
g.FillPolygon(new SolidBrush(_ArrowHoveerColour), TrianglePointTop);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointBottom);
} else if (_MouseXLoc > Width - 16) {
g.FillPolygon(new SolidBrush(_ArrowHoveerColour), TrianglePointBottom);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointTop);
} else {
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointTop);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointBottom);
}
break;
case MouseState.None:
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointTop);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointBottom);
break;
}
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
public class VSHorizontalScrollBar : Control {
#region Declarations
private Color _BaseColour = Color.FromArgb(62, 62, 66);
private Color _ThumbNormalColour = Color.FromArgb(104, 104, 104);
private Color _ThumbHoverColour = Color.FromArgb(158, 158, 158);
private Color _ThumbPressedColour = Color.FromArgb(239, 235, 239);
private Color _ArrowNormalColour = Color.FromArgb(153, 153, 153);
private Color _ArrowHoveerColour = Color.FromArgb(39, 123, 181);
private Color _ArrowPressedColour = Color.FromArgb(0, 113, 171);
private Color _OuterBorderColour;
private Color _ThumbBorderColour;
private int _Minimum = 0;
private int _Maximum = 100;
private int _Value = 0;
private int _SmallChange = 1;
private int _ButtonSize = 16;
private int _LargeChange = 10;
private bool _ShowOuterBorder = false;
private bool _ShowThumbBorder = false;
private __InnerLineCount _AmountOfInnerLines = __InnerLineCount.None;
private Point _MousePos = new Point(_MouseXLoc, _MouseYLoc);
private MouseState _ThumbState = MouseState.None;
private MouseState _ArrowState = MouseState.None;
private static int _MouseXLoc;
private static int _MouseYLoc;
private int ThumbMovement;
private Rectangle LSA;
private Rectangle RSA;
private Rectangle Shaft;
private Rectangle Thumb;
private bool ShowThumb;
private bool ThumbPressed;
private int _ThumbSize = 24;
#endregion
#region Properties & Events
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color ThumbNormalColour {
get {
return _ThumbNormalColour;
}
set {
_ThumbNormalColour = value;
}
}
[Category("Colours")]
public Color ThumbHoverColour {
get {
return _ThumbHoverColour;
}
set {
_ThumbHoverColour = value;
}
}
[Category("Colours")]
public Color ThumbPressedColour {
get {
return _ThumbPressedColour;
}
set {
_ThumbPressedColour = value;
}
}
[Category("Colours")]
public Color ArrowNormalColour {
get {
return _ArrowNormalColour;
}
set {
_ArrowNormalColour = value;
}
}
[Category("Colours")]
public Color ArrowHoveerColour {
get {
return _ArrowHoveerColour;
}
set {
_ArrowHoveerColour = value;
}
}
[Category("Colours")]
public Color ArrowPressedColour {
get {
return _ArrowPressedColour;
}
set {
_ArrowPressedColour = value;
}
}
[Category("Colours")]
public Color OuterBorderColour {
get {
return _OuterBorderColour;
}
set {
_OuterBorderColour = value;
}
}
[Category("Colours")]
public Color ThumbBorderColour {
get {
return _ThumbBorderColour;
}
set {
_ThumbBorderColour = value;
}
}
[Category("Control")]
public int Minimum {
get {
return _Minimum;
}
set {
_Minimum = value;
if (value > _Value) {
_Value = value;
}
if (value > _Maximum) {
_Maximum = value;
}
InvalidateLayout();
}
}
[Category("Control")]
public int Maximum {
get {
return _Maximum;
}
set {
if (value < _Value) {
_Value = value;
}
if (value < _Minimum) {
_Minimum = value;
}
InvalidateLayout();
}
}
[Category("Control")]
public int Value {
get {
return _Value;
}
set {
if (value == _Value) {
return;
}
else if (value < _Minimum) {
_Value = _Minimum;
}
else if (value > _Maximum) {
_Value = _Maximum;
}
else {
_Value = value;
}
InvalidatePosition();
if (Scroll != null)
Scroll(this);
}
}
[Category("Control")]
public int SmallChange {
get {
return _SmallChange;
}
set {
if (value < 1)
_SmallChange = 1;
else
_SmallChange = value;
}
}
[Category("Control")]
public int LargeChange {
get {
return _LargeChange;
}
set {
if (value < 1)
_LargeChange = 1;
else
_LargeChange = value;
}
}
[Category("Control")]
public int ButtonSize {
get {
return _ButtonSize;
}
set {
if (value < 16) {
_ButtonSize = 16;
}
else {
_ButtonSize = value;
}
}
}
[Category("Control")]
public bool ShowOuterBorder {
get {
return _ShowOuterBorder;
}
set {
_ShowOuterBorder = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowThumbBorder {
get {
return _ShowThumbBorder;
}
set {
_ShowThumbBorder = value;
Invalidate();
}
}
[Category("Control")]
public __InnerLineCount AmountOfInnerLines {
get {
return _AmountOfInnerLines;
}
set {
_AmountOfInnerLines = value;
}
}
protected override void OnSizeChanged(EventArgs e) {
InvalidateLayout();
}
private void InvalidateLayout() {
//'End width here goes with end in invalidateposition() for starting height of thumb
LSA = new Rectangle(0, 0, 16, Height);
RSA = new Rectangle(Width - ButtonSize, 0, ButtonSize, Height);
//'End width here should be double the start for symetry
Shaft = new Rectangle(LSA.Right + 1, 0, Convert.ToInt32(Width - Width / 8 - 8), Height);
ShowThumb = Convert.ToBoolean(((_Maximum - _Minimum)));
if (ShowThumb) {
Thumb = new Rectangle(0, 4, Convert.ToInt32(Width / 8), Height - 8);
}
if (Scroll != null)
Scroll(this);
InvalidatePosition();
}
public enum __InnerLineCount {
None,
One,
Two,
Three
}
public delegate void ScrollEventHandler(object sender);
public event ScrollEventHandler Scroll;
private void InvalidatePosition() {
Thumb.X = Convert.ToInt32(((_Value - _Minimum) / (double)(_Maximum - _Minimum)) * (Shaft.Width - _ThumbSize) + 16);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Left && ShowThumb) {
if (LSA.Contains(e.Location)) {
_ArrowState = MouseState.Down;
ThumbMovement = _Value - _SmallChange;
} else if (RSA.Contains(e.Location)) {
ThumbMovement = _Value + _SmallChange;
_ArrowState = MouseState.Down;
} else {
if (Thumb.Contains(e.Location)) {
_ThumbState = MouseState.Down;
Invalidate();
return;
} else {
if (e.X < Thumb.X) {
ThumbMovement = _Value - _LargeChange;
} else {
ThumbMovement = _Value + _LargeChange;
}
}
}
Value = Math.Min(Math.Max(ThumbMovement, _Minimum), _Maximum);
Invalidate();
InvalidatePosition();
}
}
protected override void OnMouseMove(MouseEventArgs e) {
_MouseXLoc = e.Location.X;
_MouseYLoc = e.Location.Y;
if (LSA.Contains(e.Location)) {
_ArrowState = MouseState.Over;
} else if (RSA.Contains(e.Location)) {
_ArrowState = MouseState.Over;
} else if (!(_ArrowState == MouseState.Down)) {
_ArrowState = MouseState.None;
}
if (Thumb.Contains(e.Location) && !(_ThumbState == MouseState.Down)) {
_ThumbState = MouseState.Over;
} else if (!(_ThumbState == MouseState.Down)) {
_ThumbState = MouseState.None;
}
Invalidate();
if (_ThumbState == MouseState.Down || _ArrowState == MouseState.Down && ShowThumb) {
int ThumbPosition = e.X + 2 - LSA.Width - (_ThumbSize / 2);
int ThumbBounds = Shaft.Width - _ThumbSize;
ThumbMovement = Convert.ToInt32((ThumbPosition / (double)ThumbBounds) * (_Maximum - _Minimum)) - _Minimum;
Value = Math.Min(Math.Max(ThumbMovement, _Minimum), _Maximum);
InvalidatePosition();
}
}
protected override void OnMouseUp(MouseEventArgs e) {
if (Thumb.Contains(e.Location)) {
_ThumbState = MouseState.Over;
} else if (!(Thumb.Contains(e.Location))) {
_ThumbState = MouseState.None;
}
if (e.Location.X < 16 || e.Location.X > Width - 16) {
_ThumbState = MouseState.Over;
} else if (!(e.Location.X < 16) || e.Location.X > Width - 16) {
_ThumbState = MouseState.None;
}
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
_ThumbState = MouseState.None;
_ArrowState = MouseState.None;
Invalidate();
}
protected override void OnMouseEnter(EventArgs e) {
base.OnMouseEnter(e);
Invalidate();
}
#endregion
#region Draw Control
public VSHorizontalScrollBar() {
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
Size = new Size(50, 19);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(_BaseColour);
Point[] TrianglePointLeft = {
new Point(5, Convert.ToInt32(Height / 2)),
new Point(11, Convert.ToInt32(Height / 4)),
new Point(11, Convert.ToInt32(Height / 2 + Height / 4))
};
Point[] TrianglePointRight = {
new Point(Width - 5, Convert.ToInt32(Height / 2)),
new Point(Width - 11, Convert.ToInt32(Height / 4)),
new Point(Width - 11, Convert.ToInt32(Height / 2 + Height / 4))
};
switch (_ThumbState) {
case MouseState.None:
using (SolidBrush SBrush = new SolidBrush(_ThumbNormalColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
case MouseState.Over:
using (SolidBrush SBrush = new SolidBrush(_ThumbHoverColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
case MouseState.Down:
using (SolidBrush SBrush = new SolidBrush(_ThumbPressedColour)) {
g.FillRectangle(SBrush, Thumb);
}
break;
}
switch (_ArrowState) {
case MouseState.Down:
if (!(Thumb.Contains(_MousePos))) {
using (SolidBrush SBrush = new SolidBrush(_ThumbNormalColour)) {
g.FillRectangle(SBrush, Thumb);
}
}
if (_MouseXLoc < 16) {
g.FillPolygon(new SolidBrush(_ArrowPressedColour), TrianglePointLeft);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointRight);
} else if (_MouseXLoc > Width - 16) {
g.FillPolygon(new SolidBrush(_ArrowPressedColour), TrianglePointRight);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointLeft);
} else {
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointLeft);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointRight);
}
break;
case MouseState.Over:
if (_MouseXLoc < 16) {
g.FillPolygon(new SolidBrush(_ArrowHoveerColour), TrianglePointLeft);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointRight);
} else if (_MouseXLoc > Width - 16) {
g.FillPolygon(new SolidBrush(_ArrowHoveerColour), TrianglePointRight);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointLeft);
} else {
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointLeft);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointRight);
}
break;
case MouseState.None:
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointLeft);
g.FillPolygon(new SolidBrush(_ArrowNormalColour), TrianglePointRight);
break;
}
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
public class VSListBoxWBuiltInScrollBar : Control {
#region Declarations
private List<VSListBoxItem> _Items = new List<VSListBoxItem>();
private readonly List<VSListBoxItem> _SelectedItems = new List<VSListBoxItem>();
private bool _MultiSelect = true;
private int ItemHeight = 24;
private VSVerticalScrollBar VerticalScrollbar;
private Color _BaseColour = Color.FromArgb(37, 37, 38);
private Color _NonSelectedItemColour = Color.FromArgb(62, 62, 64);
private Color _SelectedItemColour = Color.FromArgb(47, 47, 47);
private Color _BorderColour = Color.FromArgb(35, 35, 35);
private Color _FontColour = Color.FromArgb(199, 199, 199);
private int _SelectedWidth = 1;
private int _SelectedHeight = 1;
private bool _DontShowInnerScrollbarBorder = false;
private bool _ShowWholeInnerBorder = true;
#endregion
#region Properties
[Category("Colours")]
public Color FontColour {
get {
return _FontColour;
}
set {
_FontColour = value;
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color SelectedItemColour {
get {
return _SelectedItemColour;
}
set {
_SelectedItemColour = value;
}
}
[Category("Colours")]
public Color NonSelectedItemColour {
get {
return _NonSelectedItemColour;
}
set {
_NonSelectedItemColour = value;
}
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
[Category("Control")]
public int SelectedHeight {
get {
return _SelectedHeight;
}
}
[Category("Control")]
public int SelectedWidth {
get {
return _SelectedWidth;
}
}
[Category("Control")]
public bool DontShowInnerScrollbarBorder {
get {
return _DontShowInnerScrollbarBorder;
}
set {
_DontShowInnerScrollbarBorder = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowWholeInnerBorder {
get {
return _ShowWholeInnerBorder;
}
set {
_ShowWholeInnerBorder = value;
Invalidate();
}
}
[Category("Control"), System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
public VSListBoxItem[] Items {
get {
return _Items.ToArray();
}
set {
_Items = new List<VSListBoxItem>(value);
Invalidate();
InvalidateScroll();
}
}
[Category("Control")]
public VSListBoxItem[] SelectedItems {
get {
return _SelectedItems.ToArray();
}
}
[Category("Control")]
public bool MultiSelect {
get {
return _MultiSelect;
}
set {
_MultiSelect = value;
if (_SelectedItems.Count > 1) {
_SelectedItems.RemoveRange(1, _SelectedItems.Count - 1);
}
Invalidate();
}
}
private void HandleScroll(object sender) {
Invalidate();
}
private void InvalidateScroll() {/*
if (Convert.ToInt32(Math.Round(((_Items.Count) * ItemHeight) / (double)_SelectedHeight)) < Convert.ToDouble((((_Items.Count) * ItemHeight) / (double)_SelectedHeight))) {
VerticalScrollbar._Maximum = Convert.ToInt32(Math.Ceiling(((_Items.Count) * ItemHeight) / (double)_SelectedHeight));
} else if (Convert.ToInt32(Math.Round(((_Items.Count) * ItemHeight) / (double)_SelectedHeight)) == 0) {
VerticalScrollbar._Maximum = 1;
} else {
VerticalScrollbar._Maximum = Convert.ToInt32(Math.Round(((_Items.Count) * ItemHeight) / (double)_SelectedHeight));
}*/
int TotalHeight = (_Items.Count) * ItemHeight;
if (TotalHeight > Height) {
VerticalScrollbar.Maximum = 100;
VerticalScrollbar.SmallChange = ItemHeight;
int StepSize = ((Height / ItemHeight) / 4) * ItemHeight;
VerticalScrollbar.LargeChange = (int)(StepSize * (100/(double)Height));
VerticalScrollbar.ButtonSize = TotalHeight / VerticalScrollbar.LargeChange;
} else
VerticalScrollbar.Maximum = 1;
VerticalScrollbar.Visible = VerticalScrollbar._Maximum > 1;
Invalidate();
}
private void InvalidateLayout() {
VerticalScrollbar.Location = new Point(Width - VerticalScrollbar.Width - 2, 2);
VerticalScrollbar.Size = new Size(18, Height - 4);
Invalidate();
}
public class VSListBoxItem {
public string Text { get; set; }
public override string ToString() {
return Text;
}
}
public override Font Font {
get {
return base.Font;
}
set {
ItemHeight = Convert.ToInt32(Graphics.FromHwnd(Handle).MeasureString("@", Font).Height);
if (VerticalScrollbar != null) {
VerticalScrollbar._SmallChange = 1;
VerticalScrollbar._LargeChange = 1;
}
base.Font = value;
InvalidateLayout();
}
}
public void AddItem(string Items) {
VSListBoxItem Item = new VSListBoxItem();
Item.Text = Items;
_Items.Add(Item);
Invalidate();
InvalidateScroll();
}
public void AddItems(string[] Items) {
foreach (var I in Items) {
VSListBoxItem Item = new VSListBoxItem();
Item.Text = I;
_Items.Add(Item);
}
Invalidate();
InvalidateScroll();
}
public void RemoveItemAt(int index) {
_Items.RemoveAt(index);
Invalidate();
InvalidateScroll();
}
public void RemoveItem(VSListBoxItem item) {
_Items.Remove(item);
Invalidate();
InvalidateScroll();
}
public void RemoveItems(VSListBoxItem[] items) {
foreach (VSListBoxItem I in items) {
_Items.Remove(I);
}
Invalidate();
InvalidateScroll();
}
protected override void OnSizeChanged(EventArgs e) {
_SelectedWidth = Width;
_SelectedHeight = Height;
InvalidateScroll();
InvalidateLayout();
base.OnSizeChanged(e);
}
private void Vertical_MouseDown(object sender, MouseEventArgs e) {
Focus();
}
protected override void OnMouseDown(MouseEventArgs e) {
Focus();
if (e.Button == MouseButtons.Left) {
int Offset = GetScrollOffset();
int Index = ((e.Y + Offset) / ItemHeight);
if (Index > _Items.Count - 1) {
Index = -1;
}
if (!(Index == -1)) {
if (ModifierKeys == Keys.Control && _MultiSelect) {
if (_SelectedItems.Contains(_Items[Index])) {
_SelectedItems.Remove(_Items[Index]);
} else {
_SelectedItems.Add(_Items[Index]);
}
} else {
_SelectedItems.Clear();
_SelectedItems.Add(_Items[Index]);
}
}
Invalidate();
}
base.OnMouseDown(e);
}
private int GetScrollOffset() {
//int Offset = Convert.ToInt32(VerticalScrollbar.Value * (VerticalScrollbar.Maximum + (Height - (ItemHeight))));
int MaxHeight = (ItemHeight * Items.Length) - Height;
if (MaxHeight < 0)
return 0;
int Offset = (int)(((MaxHeight) * VerticalScrollbar.Value) / (double)100);
return Offset;
}
public int GetElementIndex(Point Point) {
int Offset = GetScrollOffset();
int Index = ((Point.Y + Offset) / ItemHeight);
if (Index > _Items.Count - 1) {
Index = -1;
}
return Index;
}
protected override void OnMouseWheel(MouseEventArgs e) {
int Move = (-(e.Delta * SystemInformation.MouseWheelScrollLines / 120) * (2 / 2)) * ItemHeight;
int Value = Math.Max(Math.Min(VerticalScrollbar.Value + Move, VerticalScrollbar.Maximum), VerticalScrollbar.Minimum);
VerticalScrollbar.Value = Value;
base.OnMouseWheel(e);
}
#endregion
#region Draw Control
public VSListBoxWBuiltInScrollBar() {
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
VerticalScrollbar = new VSVerticalScrollBar();
VerticalScrollbar._SmallChange = 1;
VerticalScrollbar._LargeChange = 1;
VerticalScrollbar.Scroll += HandleScroll;
VerticalScrollbar.MouseDown += Vertical_MouseDown;
Controls.Add(VerticalScrollbar);
InvalidateLayout();
}
protected override void OnPaint(PaintEventArgs e) {
var G = e.Graphics;
G.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
G.SmoothingMode = SmoothingMode.HighQuality;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
G.Clear(_BaseColour);
VSListBoxItem AllItems = null;
int Offset = GetScrollOffset();
int StartIndex = 0;
if (Offset == 0) {
StartIndex = 0;
} else {
StartIndex = Convert.ToInt32(Offset / ItemHeight);
}
int EndIndex = Math.Min(StartIndex + (Height / ItemHeight), _Items.Count - 1);
if (!_DontShowInnerScrollbarBorder && !_ShowWholeInnerBorder && VerticalScrollbar.Visible) {
G.DrawLine(new Pen(_BorderColour, 2F), VerticalScrollbar.Location.X - 1, 0, VerticalScrollbar.Location.X - 1, Height);
}
for (int I = StartIndex; I < _Items.Count; I++) {
AllItems = Items[I];
int Y = ((I * ItemHeight) + 1 - Offset) + Convert.ToInt32((ItemHeight / 2.0) - 8);
if (_SelectedItems.Contains(AllItems)) {
G.FillRectangle(new SolidBrush(_SelectedItemColour), new Rectangle(0, (I * ItemHeight) + 1 - Offset, Width - (VerticalScrollbar.Visible ? 19 : 0), ItemHeight - 1));
} else {
G.FillRectangle(new SolidBrush(_NonSelectedItemColour), new Rectangle(0, (I * ItemHeight) + 1 - Offset, Width - (VerticalScrollbar.Visible ? 19 : 0), ItemHeight - 1));
}
G.DrawLine(new Pen(_BorderColour), 0, ((I * ItemHeight) + 1 - Offset) + ItemHeight - 1, Width - (VerticalScrollbar.Visible ? 18 : 0), ((I * ItemHeight) + 1 - Offset) + ItemHeight - 1);
if (G.MeasureString(AllItems.Text, new Font("Segoe UI", 8)).Width > (_SelectedWidth) - (VerticalScrollbar.Visible ? 30 : 11)) {
G.DrawString(AllItems.Text, new Font("Segoe UI", 8), new SolidBrush(_FontColour), new Rectangle(7, Y, Width - (VerticalScrollbar.Visible ? 35 : 16), 15));
G.DrawString("...", new Font("Segoe UI", 8), new SolidBrush(_FontColour), new Rectangle(Width - (VerticalScrollbar.Visible ? 32 : 13), Y, 15, 15));
} else {
G.DrawString(AllItems.Text, new Font("Segoe UI", 8), new SolidBrush(_FontColour), new Rectangle(7, Y, Width - (VerticalScrollbar.Visible ? 34 : 15), Y + 10));
}
G.ResetClip();
}
G.DrawRectangle(new Pen(Color.FromArgb(35, 35, 35), 2F), 1, 1, Width - 2, Height - 2);
G.InterpolationMode = (InterpolationMode)7;
if (_ShowWholeInnerBorder && VerticalScrollbar.Visible) {
G.DrawLine(new Pen(_BorderColour, 2F), VerticalScrollbar.Location.X - 1, 0, VerticalScrollbar.Location.X - 1, Height);
}
}
#endregion
}
public class VSRadialProgressBar : Control {
#region Declarations
private Color _BorderColour = Color.FromArgb(28, 28, 28);
private Color _BaseColour = Color.FromArgb(45, 45, 48);
private Color _ProgressColour = Color.FromArgb(62, 62, 66);
private Color _TextColour = Color.FromArgb(153, 153, 153);
private int _Value = 0;
private int _Maximum = 100;
private int _StartingAngle = 110;
private int _RotationAngle = 255;
private bool _ShowText = false;
private Font _Font = new Font("Segoe UI", 20);
#endregion
#region Properties
[Category("Control")]
public int Maximum {
get {
return _Maximum;
}
set {
if (value < _Value) {
_Value = value;
}
_Maximum = value;
Invalidate();
}
}
[Category("Control")]
public int Value {
get {
switch (_Value) {
case 0:
return 0;
Invalidate();
break;
default:
return _Value;
Invalidate();
break;
}
}
set {
if (value > _Maximum) {
value = _Maximum;
Invalidate();
}
_Value = value;
Invalidate();
}
}
public void Increment(int Amount) {
Value += Amount;
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color TextColour {
get {
return _TextColour;
}
set {
_TextColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color ProgressColour {
get {
return _ProgressColour;
}
set {
_ProgressColour = value;
Invalidate();
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
Invalidate();
}
}
[Category("Control")]
public int StartingAngle {
get {
return _StartingAngle;
}
set {
_StartingAngle = value;
Invalidate();
}
}
[Category("Control")]
public int RotationAngle {
get {
return _RotationAngle;
}
set {
_RotationAngle = value;
Invalidate();
}
}
[Category("Control")]
public bool ShowText {
get {
return _ShowText;
}
set {
_ShowText = value;
Invalidate();
}
}
//Protected Overrides Sub OnSizeChanged(e As EventArgs)
// Dim g As Graphics
// If Height < g.MeasureString(CStr(_Value), Font).Height * 2 Then
// Me.Size = New Size(CInt(g.MeasureString(CStr(_Value), Font).Height * 2), CInt(g.MeasureString(CStr(_Value), Font).Height * 2))
// End If
// MyBase.OnSizeChanged(e)
//End Sub
#endregion
#region Draw Control
public VSRadialProgressBar() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
Size = new Size(78, 78);
BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e) {
Bitmap B = new Bitmap(Width, Height);
var G = Graphics.FromImage(B);
G.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
G.SmoothingMode = SmoothingMode.HighQuality;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
G.Clear(BackColor);
if (_Value == 0) {
G.DrawArc(new Pen(new SolidBrush(_BorderColour), 1 + 6), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle - 3, _RotationAngle + 5);
G.DrawArc(new Pen(new SolidBrush(_BaseColour), 1 + 3), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle, _RotationAngle);
if (_ShowText)
G.DrawString(Convert.ToString(_Value), _Font, new SolidBrush(_TextColour), new Point(Convert.ToInt32(Width / 2), Convert.ToInt32(Height / 2 - 1)), new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
else if (_Value == _Maximum) {
G.DrawArc(new Pen(new SolidBrush(_BorderColour), 1 + 6), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle - 3, _RotationAngle + 5);
G.DrawArc(new Pen(new SolidBrush(_BaseColour), 1 + 3), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle, _RotationAngle);
G.DrawArc(new Pen(new SolidBrush(_ProgressColour), 1 + 3), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle, _RotationAngle);
if (_ShowText)
G.DrawString(Convert.ToString(_Value), _Font, new SolidBrush(_TextColour), new Point(Convert.ToInt32(Width / 2), Convert.ToInt32(Height / 2 - 1)), new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
else {
G.DrawArc(new Pen(new SolidBrush(_BorderColour), 1 + 6), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle - 3, _RotationAngle + 5);
G.DrawArc(new Pen(new SolidBrush(_BaseColour), 1 + 3), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle, _RotationAngle);
G.DrawArc(new Pen(new SolidBrush(_ProgressColour), 1 + 3), Convert.ToInt32(3 / 2.0) + 1, Convert.ToInt32(3 / 2.0) + 1, Width - 3 - 4, Height - 3 - 3, _StartingAngle, Convert.ToInt32((_RotationAngle / (double)_Maximum) * _Value));
if (_ShowText)
G.DrawString(Convert.ToString(_Value), _Font, new SolidBrush(_TextColour), new Point(Convert.ToInt32(Width / 2), Convert.ToInt32(Height / 2 - 1)), new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
base.OnPaint(e);
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.DrawImageUnscaled(B, 0, 0);
B.Dispose();
}
#endregion
}
public class VSTabControl : TabControl {
#region Declarations
private Color _TextColour = Color.FromArgb(255, 255, 255);
private Color _BackTabColour = Color.FromArgb(28, 28, 28);
private Color _BaseColour = Color.FromArgb(45, 45, 48);
private Color _ActiveColour = Color.FromArgb(0, 122, 204);
private Color _BorderColour = Color.FromArgb(30, 30, 30);
private Color _HorizLineColour = Color.FromArgb(0, 122, 204);
private StringFormat CenterSF = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center };
#endregion
#region Properties
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
[Category("Colours")]
public Color HorizontalLineColour {
get {
return _HorizLineColour;
}
set {
_HorizLineColour = value;
}
}
[Category("Colours")]
public Color TextColour {
get {
return _TextColour;
}
set {
_TextColour = value;
}
}
[Category("Colours")]
public Color BackTabColour {
get {
return _BackTabColour;
}
set {
_BackTabColour = value;
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color ActiveColour {
get {
return _ActiveColour;
}
set {
_ActiveColour = value;
}
}
protected override void CreateHandle() {
base.CreateHandle();
Alignment = TabAlignment.Top;
}
private TabPage predraggedTab;
protected override void OnMouseDown(MouseEventArgs e) {
predraggedTab = getPointedTab();
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e) {
predraggedTab = null;
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
if (e.Button == MouseButtons.Left && predraggedTab != null) {
this.DoDragDrop(predraggedTab, DragDropEffects.Move);
}
base.OnMouseMove(e);
}
protected override void OnDragOver(DragEventArgs drgevent) {
TabPage draggedTab = (TabPage)drgevent.Data.GetData(typeof(TabPage));
TabPage pointedTab = getPointedTab();
if (draggedTab == predraggedTab && pointedTab != null) {
drgevent.Effect = DragDropEffects.Move;
if (!(pointedTab == draggedTab)) {
swapTabPages(draggedTab, pointedTab);
}
}
base.OnDragOver(drgevent);
}
private TabPage getPointedTab() {
for (int i = 0; i < this.TabPages.Count; i++) {
if (this.GetTabRect(i).Contains(this.PointToClient(Cursor.Position))) {
return this.TabPages[i];
}
}
return null;
}
private void swapTabPages(TabPage src, TabPage dst) {
int srci = this.TabPages.IndexOf(src);
int dsti = this.TabPages.IndexOf(dst);
this.TabPages[dsti] = src;
this.TabPages[srci] = dst;
if (this.SelectedIndex == srci) {
this.SelectedIndex = dsti;
} else if (this.SelectedIndex == dsti) {
this.SelectedIndex = srci;
}
this.Refresh();
}
#endregion
#region Draw Control
public VSTabControl() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
DoubleBuffered = true;
SizeMode = TabSizeMode.Normal;
ItemSize = new Size(240, 16);
AllowDrop = true;
}
protected override void OnPaint(PaintEventArgs e) {
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.Clear(_BaseColour);
try {
SelectedTab.BackColor = _BackTabColour;
} catch (Exception ex) {
}
try {
SelectedTab.BorderStyle = BorderStyle.None;
} catch (Exception ex) {
}
for (var i = 0; i < TabCount; i++) {
Rectangle Base = new Rectangle(new Point(GetTabRect(i).Location.X + 2, GetTabRect(i).Location.Y), new Size(GetTabRect(i).Width, GetTabRect(i).Height));
Rectangle BaseSize = new Rectangle(Base.Location, new Size(Base.Width, Base.Height));
if (i == SelectedIndex) {
g.FillRectangle(new SolidBrush(_BaseColour), BaseSize);
g.FillRectangle(new SolidBrush(_ActiveColour), new Rectangle(Base.X - 5, Base.Y - 3, Base.Width, Base.Height + 5));
g.DrawString(TabPages[i].Text, Font, new SolidBrush(_TextColour), BaseSize, CenterSF);
} else {
g.FillRectangle(new SolidBrush(_BaseColour), BaseSize);
g.DrawString(TabPages[i].Text, Font, new SolidBrush(_TextColour), BaseSize, CenterSF);
}
}
g.DrawLine(new Pen(_HorizLineColour, 2F), new Point(0, 19), new Point(Width, 19));
g.FillRectangle(new SolidBrush(_BackTabColour), new Rectangle(0, 20, Width, Height - 20));
//g.DrawRectangle(new Pen(_BorderColour, 2F), new Rectangle(0, 0, Width, Height));
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
#endregion
}
public class VSNormalTextBox : Control {
#region Declarations
private MouseState State = MouseState.None;
private System.Windows.Forms.TextBox TB;
private Color _BaseColour = Color.FromArgb(51, 51, 55);
private Color _TextColour = Color.FromArgb(153, 153, 153);
private Color _BorderColour = Color.FromArgb(35, 35, 35);
private Styles _Style = Styles.NotRounded;
private HorizontalAlignment _TextAlign = HorizontalAlignment.Left;
private int _MaxLength = 32767;
private bool _ReadOnly;
private bool _UseSystemPasswordChar;
private bool _Multiline;
#endregion
#region TextBox Properties
public enum Styles {
Rounded,
NotRounded
}
[Category("Options")]
public HorizontalAlignment TextAlign {
get {
return _TextAlign;
}
set {
_TextAlign = value;
if (TB != null) {
TB.TextAlign = value;
}
}
}
[Category("Options")]
public int MaxLength {
get {
return _MaxLength;
}
set {
_MaxLength = value;
if (TB != null) {
TB.MaxLength = value;
}
}
}
[Category("Options")]
public bool ReadOnly {
get {
return _ReadOnly;
}
set {
_ReadOnly = value;
if (TB != null) {
TB.ReadOnly = value;
}
}
}
[Category("Options")]
public bool UseSystemPasswordChar {
get {
return _UseSystemPasswordChar;
}
set {
_UseSystemPasswordChar = value;
if (TB != null) {
TB.UseSystemPasswordChar = value;
}
}
}
[Category("Options")]
public bool Multiline {
get {
return _Multiline;
}
set {
_Multiline = value;
if (TB != null) {
TB.Multiline = value;
if (value) {
TB.Height = Height - 7;
} else {
Height = TB.Height + 7;
}
}
}
}
[Category("Options")]
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
if (TB != null) {
TB.Text = value;
}
}
}
[Category("Options")]
public override Font Font {
get {
return base.Font;
}
set {
base.Font = value;
if (TB != null) {
TB.Font = value;
TB.Location = new Point(3, 5);
TB.Width = Width - 6;
if (!_Multiline) {
Height = TB.Height + 7;
}
}
}
}
protected override void OnCreateControl() {
base.OnCreateControl();
if (!(Controls.Contains(TB))) {
Controls.Add(TB);
}
}
private void OnBaseTextChanged(object s, EventArgs e) {
Text = TB.Text;
}
private void OnBaseKeyDown(object s, KeyEventArgs e) {
if (e.Control && e.KeyCode == Keys.A) {
TB.SelectAll();
e.SuppressKeyPress = true;
}
if (e.Control && e.KeyCode == Keys.C) {
TB.Copy();
e.SuppressKeyPress = true;
}
}
protected override void OnResize(EventArgs e) {
TB.Location = new Point(5, 5);
TB.Width = Width - 10;
if (_Multiline) {
TB.Height = Height - 7;
} else {
Height = TB.Height + 7;
}
base.OnResize(e);
}
public Styles Style {
get {
return _Style;
}
set {
_Style = value;
Invalidate();
}
}
public void SelectAll() {
TB.Focus();
TB.SelectAll();
}
#endregion
#region Colour Properties
[Category("Colours")]
public Color BackgroundColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color TextColour {
get {
return _TextColour;
}
set {
_TextColour = value;
}
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
#endregion
#region Mouse States
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
State = MouseState.Down;
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
State = MouseState.Over;
TB.Focus();
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
base.OnMouseLeave(e);
State = MouseState.None;
Invalidate();
}
#endregion
#region Draw Control
public VSNormalTextBox() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
BackColor = Color.Transparent;
TB = new System.Windows.Forms.TextBox();
TB.Height = 20;
TB.Font = new Font("Segoe UI", 10);
TB.Text = Text;
TB.BackColor = _BaseColour;
TB.ForeColor = _TextColour;
TB.MaxLength = _MaxLength;
TB.Multiline = false;
TB.ReadOnly = _ReadOnly;
TB.UseSystemPasswordChar = _UseSystemPasswordChar;
TB.BorderStyle = BorderStyle.None;
TB.Location = new Point(5, 5);
TB.Width = Width - 35;
TB.TextChanged += OnBaseTextChanged;
TB.KeyDown += OnBaseKeyDown;
}
protected override void OnPaint(PaintEventArgs e) {
var g = e.Graphics;
GraphicsPath GP = null;
Rectangle Base = new Rectangle(0, 0, Width, Height);
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(BackColor);
TB.BackColor = _BaseColour;
TB.ForeColor = _TextColour;
switch (_Style) {
case Styles.Rounded:
GP = DrawHelpers.RoundRectangle(Base, 6);
g.FillPath(new SolidBrush(Color.FromArgb(42, 42, 42)), GP);
g.DrawPath(new Pen(new SolidBrush(Color.FromArgb(35, 35, 35)), 2F), GP);
GP.Dispose();
break;
case Styles.NotRounded:
g.FillRectangle(new SolidBrush(_BaseColour), new Rectangle(0, 0, Width - 1, Height - 1));
g.DrawRectangle(new Pen(Color.FromArgb(63, 63, 70), 2F), new Rectangle(0, 0, Width, Height));
break;
}
g.InterpolationMode = (InterpolationMode)7;
}
#endregion
}
public class VSGroupBox : ContainerControl {
#region Declarations
private Color _MainColour = Color.FromArgb(37, 37, 38);
private Color _HeaderColour = Color.FromArgb(45, 45, 48);
private Color _TextColour = Color.FromArgb(129, 129, 131);
private Color _BorderColour = Color.FromArgb(2, 118, 196);
#endregion
#region Properties
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
[Category("Colours")]
public Color TextColour {
get {
return _TextColour;
}
set {
_TextColour = value;
}
}
[Category("Colours")]
public Color HeaderColour {
get {
return _HeaderColour;
}
set {
_HeaderColour = value;
}
}
[Category("Colours")]
public Color MainColour {
get {
return _MainColour;
}
set {
_MainColour = value;
}
}
#endregion
#region Draw Control
public VSGroupBox() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
Size = new Size(160, 110);
Font = new Font("Segoe UI", 10F, FontStyle.Regular);
}
protected override void OnPaint(PaintEventArgs e) {
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.FillRectangle(new SolidBrush(_MainColour), new Rectangle(0, 28, Width, Height));
g.FillRectangle(new SolidBrush(_HeaderColour), new Rectangle(0, 0, Width, 28));
g.FillRectangle(new SolidBrush(Color.FromArgb(33, 33, 33)), new Rectangle(0, 28, Width, 1));
g.DrawString(Text, Font, new SolidBrush(_TextColour), new Point(5, 5));
g.DrawRectangle(new Pen(_BorderColour, 2F), new Rectangle(0, 0, Width, Height));
g.InterpolationMode = (InterpolationMode)7;
}
#endregion
}
public class VSComboBox : ComboBox {
#region Declarations
private int _StartIndex = 0;
private Color _BorderColour = Color.FromArgb(35, 35, 35);
private Color _BaseColour = Color.FromArgb(51, 51, 55);
private Color _FontColour = Color.FromArgb(255, 255, 255);
private Color _LineColour = Color.FromArgb(0, 122, 204);
private Color _SqaureColour = Color.FromArgb(51, 51, 55);
private Color _ArrowColour = Color.FromArgb(153, 153, 153);
private Color _SqaureHoverColour = Color.FromArgb(52, 52, 52);
private MouseState State = MouseState.None;
#endregion
#region Properties & Events
[Category("Colours")]
public Color LineColour {
get {
return _LineColour;
}
set {
_LineColour = value;
}
}
[Category("Colours")]
public Color SqaureColour {
get {
return _SqaureColour;
}
set {
_SqaureColour = value;
}
}
[Category("Colours")]
public Color ArrowColour {
get {
return _ArrowColour;
}
set {
_ArrowColour = value;
}
}
[Category("Colours")]
public Color SqaureHoverColour {
get {
return _SqaureHoverColour;
}
set {
_SqaureHoverColour = value;
}
}
protected override void OnMouseEnter(EventArgs e) {
base.OnMouseEnter(e);
State = MouseState.Over;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e) {
base.OnMouseLeave(e);
State = MouseState.None;
Invalidate();
}
[Category("Colours")]
public Color BorderColour {
get {
return _BorderColour;
}
set {
_BorderColour = value;
}
}
[Category("Colours")]
public Color BaseColour {
get {
return _BaseColour;
}
set {
_BaseColour = value;
}
}
[Category("Colours")]
public Color FontColour {
get {
return _FontColour;
}
set {
_FontColour = value;
}
}
public int StartIndex {
get {
return _StartIndex;
}
set {
_StartIndex = value;
try {
base.SelectedIndex = value;
} catch {
}
Invalidate();
}
}
protected override void OnTextChanged(System.EventArgs e) {
base.OnTextChanged(e);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e) {
Invalidate();
OnMouseClick(e);
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) {
Invalidate();
base.OnMouseUp(e);
}
#endregion
#region Draw Control
public void ReplaceItem(object sender, System.Windows.Forms.DrawItemEventArgs e) {
e.DrawBackground();
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
Rectangle Rect = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width + 1, e.Bounds.Height + 1);
try {
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) {
e.Graphics.FillRectangle(new SolidBrush(_SqaureColour), Rect);
e.Graphics.DrawString(base.GetItemText(base.Items[e.Index]), Font, new SolidBrush(_FontColour), 1, e.Bounds.Top + 2);
} else {
e.Graphics.FillRectangle(new SolidBrush(_BaseColour), Rect);
e.Graphics.DrawString(base.GetItemText(base.Items[e.Index]), Font, new SolidBrush(_FontColour), 1, e.Bounds.Top + 2);
}
} catch {
}
e.DrawFocusRectangle();
Invalidate();
}
public VSComboBox() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
BackColor = Color.Transparent;
DrawMode = DrawMode.OwnerDrawFixed;
DropDownStyle = ComboBoxStyle.DropDownList;
Width = 163;
Font = new Font("Segoe UI", 10);
SubscribeToEvents();
}
protected override void OnPaint(PaintEventArgs e) {
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(BackColor);
try {
Rectangle Square = new Rectangle(Width - 25, 0, Width, Height);
g.FillRectangle(new SolidBrush(_BaseColour), new Rectangle(0, 0, Width - 25, Height));
if (State == MouseState.None) {
g.FillRectangle(new SolidBrush(_SqaureColour), Square);
}
else if (State == MouseState.Over) {
g.FillRectangle(new SolidBrush(_SqaureHoverColour), Square);
}
g.DrawLine(new Pen(_LineColour, 2), new Point(Width - 26, 1), new Point(Width - 26, Height - 1));
try {
g.DrawString(Text, Font, new SolidBrush(_FontColour), new Rectangle(3, 0, Width - 20, Height), new StringFormat { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Near, FormatFlags = StringFormatFlags.NoWrap });
} catch {
}
g.DrawRectangle(new Pen(_BorderColour, 2), new Rectangle(0, 0, Width, Height));
Point[] P = {
new Point(Width - 17, 11),
new Point(Width - 13, 5),
new Point(Width - 9, 11)
};
g.FillPolygon(new SolidBrush(_ArrowColour), P);
g.DrawPolygon(new Pen(_ArrowColour), P);
Point[] P1 = {
new Point(Width - 17, 15),
new Point(Width - 13, 21),
new Point(Width - 9, 15)
};
g.FillPolygon(new SolidBrush(_ArrowColour), P1);
g.DrawPolygon(new Pen(_ArrowColour), P1);
} catch {
}
g.InterpolationMode = (InterpolationMode)7;
}
#endregion
private bool EventsSubscribed = false;
private void SubscribeToEvents() {
if (EventsSubscribed)
return;
else
EventsSubscribed = true;
this.DrawItem += ReplaceItem;
}
}
|
82037de98facf53dc172f2ea57708624072fffbe
|
C#
|
denisb1/mono-studentska-praksa
|
/Day6/Day6.Service/CourseService.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using Day6.DAL;
using Day6.Models.DTO;
using Day6.Models.REST;
using Day6.Repository;
namespace Day6.Service
{
public class CourseService : IGenericService<CourseRest>
{
private readonly IRepositoryWork _repositoryWork;
private readonly IMapper _mapper;
private readonly IGenericRepository<CourseDb> _repo;
public CourseService(IRepositoryWork repositoryWork, IMapper mapper)
{
_repositoryWork = repositoryWork;
_mapper = mapper;
_repo = _repositoryWork.CourseDbRepository;
}
public async Task<CourseRest> GetById(Guid id)
{
var course = await _repo
.Get(x => x.Id == id);
return _mapper.Map<CourseRest>(course);
}
private async Task<IList<CourseDto>> GetAll()
{
var students = await _repo.GetAll();
return _mapper.Map<IList<CourseDto>>(students);
}
public async Task<IList<CourseRest>> GetAll(string where, string order)
{
Func<IQueryable<CourseDb>, IOrderedQueryable<CourseDb>> orderBy = null;
Expression<Func<CourseDb, bool>> expression = null;
if (where != null) expression = x => x.CourseName.ToLower().Contains(where.ToLower());
if (order != null)
orderBy = order.ToLower() switch
{
"coursename" => x => x.OrderBy(y => y.CourseName),
"coursename_desc" => x => x.OrderByDescending(y => y.CourseName),
"ects" => x => x.OrderBy(y => y.Ects),
"ects_desc" => x => x.OrderByDescending(y => y.Ects),
_ => null
};
if (where == null && order == null)
return _mapper.Map<IList<CourseRest>>(await GetAll());
var courses = await _repo.GetAll(expression, orderBy);
return _mapper.Map<IList<CourseRest>>(courses);
}
public async Task Insert(CourseRest course)
{
await _repo.Insert(_mapper.Map<CourseDb>(course));
await _repositoryWork.Save();
}
public async Task Update(Guid id, CourseRest newCourse)
{
var oldCourse = await _repo.Get(q => q.Id == id);
if (oldCourse == null) throw new ArgumentException("Doesn't exist.");
_mapper.Map(newCourse, oldCourse);
_repo.Update(oldCourse);
await _repositoryWork.Save();
}
public async Task Delete(CourseRest course)
{
var courses = await _repo.GetAll(q =>
q.CourseName == course.CourseName &&
q.Ects == course.Ects
);
if (courses == null) throw new ArgumentException("Doesn't exist.");
_repo.DeleteRange(courses);
await _repositoryWork.Save();
}
public async Task Delete(Guid id)
{
var course = await _repo.Get(x => x.Id == id);
if (course == null) throw new ArgumentException("Doesn't exist.");
await _repo.Delete(id);
await _repositoryWork.Save();
}
}
}
|
b148c3a4505613004c0bd955661ebb9d42ac7d34
|
C#
|
davidwhitney/CodingGamePen
|
/CodingGamePenCore/ThereIsNoSpoon.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeingGamePen.Fakes;
using NUnit.Framework;
namespace CodeingGamePen
{
[TestFixture(Explicit = true)]
public class ThereIsNoSpoon
{
public static FakeConsole Console { get; set; }
[SetUp]
public void SetUp() => Console = new FakeConsole();
[Test]
public void Execute()
{
Console.AddInput(
"2", "2", "00", "0.");
Simulate(1);
Assert.That(Console.Outputs[0], Is.EqualTo("0 0 1 0 0 1"));
Console = new FakeConsole();
Console.AddInput(
"5", "1", "0.0.0");
Simulate(1);
Assert.That(Console.Outputs[0], Is.EqualTo("0 0 2 0 -1 -1"));
}
[Test]
public void Execute2()
{
Console.AddInput("5", "1", "0.0.0");
Simulate(1);
Assert.That(Console.Outputs[0], Is.EqualTo("0 0 2 0 -1 -1"));
}
[Test]
public void Execute3()
{
Console.AddInput("3", "3", "0.0", "...", "0.0");
Simulate(1);
Assert.That(Console.Outputs[0], Is.EqualTo("0 0 2 0 0 2"));
Assert.That(Console.Outputs[1], Is.EqualTo("2 0 -1 -1 2 2"));
}
private void Simulate(int i)
{
var width = int.Parse(Console.ReadLine()); // the number of cells on the X axis
var height = int.Parse(Console.ReadLine()); // the number of cells on the Y axis
var rowStrings = new List<string>();
for (var heightY = 0; heightY < height; heightY++)
{
rowStrings.Add(Console.ReadLine());
Console.Error.WriteLine(rowStrings.Last());
}
for (var y = 0; y < rowStrings.Count; y++)
{
for (var x = 0; x < width; x++)
{
var thisNode = SafeGet(rowStrings, y, x);
if (thisNode == '.') continue;
var columnStrings = string.Join("", rowStrings.Select(row => row[x]).ToList());
var nextX = rowStrings[y].IndexOf("0", x + 1);
var right = SafeGet(rowStrings, y, nextX);
int nextXy;
if (right == '0')
{
nextXy = y;
}
else
{
nextX = nextXy = -1;
}
var nextY = columnStrings.IndexOf('0', y + 1);
var down = SafeGet(columnStrings.Select(s => s.ToString()).ToList(), nextY, 0);
int nextYx;
if (down == '0')
{
nextYx = x;
}
else
{
nextY = nextYx = -1;
}
var formattableString = $"{x} {y} {nextX} {nextXy} {nextYx} {nextY}";
Console.WriteLine(formattableString);
}
}
}
private static char SafeGet(List<string> collection, int y, int x)
{
try { return collection[y][x]; }
catch { return '.'; }
}
}
}
|
6f9c92a210718a4e77ed98069b25f07e33aecf60
|
C#
|
SenkoVlad/c_sharp_mysql
|
/Report.cs
| 2.625
| 3
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Forms
{
public partial class Report : Form
{
MySqlConnection conn = new MySqlConnection("server=localhost;user=root;database=Barbershop;password=147852369;charset=utf8;");
public Report()
{
InitializeComponent();
}
private void Report_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenConnection();
DateTime thisDay = DateTime.Today;
int visits = 0;
double score = 0;
double Consumables = 0;
string sql = "select Money, Visitors, Date,Consumables from report where " +
"TIMESTAMPDIFF(DAY,Date,'" + thisDay.ToString("yyyy.MM.dd") + "') < "+Convert.ToInt16(comboBox1.Text)+";";
MySqlCommand command = new MySqlCommand(sql,conn);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Consumables+= Convert.ToDouble(reader[3]);
score += Convert.ToDouble(reader[0]);
visits+=Convert.ToInt16(reader[1]);
}
label5.Text = score.ToString();
label7.Text = visits.ToString();
label10.Text = (Consumables / Convert.ToInt32(comboBox1.Text)).ToString();
if (visits > 0)
{
label4.Text = Math.Round((score / visits), 2).ToString();
}
else
{
MessageBox.Show("За данный период не было клиентов", "Отчёт");
}
CloseConnection();
reader.Close();
}
public void OpenConnection()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
public void CloseConnection()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form1 obj = new Form1();
obj.Show();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Report_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void button4_Click(object sender, EventArgs e)
{
this.Hide();
Edit_Reprot obj = new Edit_Reprot();
obj.Show();
}
private void button5_Click(object sender, EventArgs e)
{
DateTime thisDay = DateTime.Today;
string sql_report = "INSERT INTO `barbershop`.`report` (`Date`, `Visitors`, `Money`,`Consumables`) VALUES ('" + thisDay.ToString("yyyy.MM.dd") + "'," +
" '0', '0', '"+Convert.ToDouble(textBox1.Text)+"');";
try
{
OpenConnection();
MySqlCommand command = new MySqlCommand(sql_report, conn);
command.ExecuteScalar();
CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка!");
throw;
}
}
}
}
|
c3d7cd3dd775d04b16c477961ef14be0d68b3b72
|
C#
|
CamdenBoBamden/FFDungeonGame
|
/Game/Components/Monster.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Components
{
public class Monster : Character
{
public int XPDrop { get; set; }
public int GoldDrop { get; set; }
public Monster(string name, int level, int maxHealth, int health, int maxMP, int mp, int maxAttack, int minAttack, int defense, int xpDrop, int goldDrop) : base(name,
level, maxHealth, health, maxMP, mp, maxAttack, minAttack, defense)
{
XPDrop = xpDrop;
GoldDrop = goldDrop;
}
public override string ToString()
{
return string.Format("{0} monster level {1}", Name, Level);
}
}
}
|
a8ac53ffba33c544be44b4dd063c10b16f4a595a
|
C#
|
bmsimons/huecli
|
/Preferences.cs
| 2.96875
| 3
|
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
namespace huecli
{
public class Preferences
{
public string PreferencesFile { get; set; }
public string PreferencesString { get; set; }
public FileStream fs { get; set; }
public Preferences(string file = null)
{
if (file == null)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
PreferencesFile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+"\\huecli-preferences.json";
}
else
{
PreferencesFile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+"/huecli-preferences.json";
}
}
else
{
PreferencesFile = file;
}
}
public void Load()
{
fs = File.Open(PreferencesFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
}
public void Save()
{
byte[] contents = new UTF8Encoding(true).GetBytes(PreferencesString);
fs.Write(contents, 0, contents.Length);
}
public void Close()
{
fs.Close();
}
}
}
|
3ede0a951f3b4e876bd2b13045f5bc611f63840b
|
C#
|
Avokadoen/shipwrecked
|
/Assets/ProjectAssets/Equipment/Common/Scripts/OABulletPool.cs
| 2.71875
| 3
|
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class OABulletPool : MonoBehaviour
{
[SerializeField]
[Tooltip("Size of the pool")]
[Range(1, 200)]
private int size = 50;
[SerializeField]
[Tooltip("Max allowed size of the pool")]
private int maxSize = 200;
// total objects that that are bound to this pool
private int pooledCount;
[SerializeField]
[Tooltip("Prefab that is meant to be pooled")]
private GameObject prefab;
[SerializeField]
private OABallisticBullet[] freePool;
void Awake()
{
OAExtentions.AssertObjectNotNull(
prefab,
$"OAObjectPool is missing prefab!"
);
OAExtentions.AssertObjectNotNull(
prefab.GetComponent<OABallisticBullet>(),
$"OAObjectPool prefab is no a OABallisticBullet!"
);
freePool = new OABallisticBullet[maxSize];
for (var i = 0; i < size; i++)
{
InstantiateBullet(i);
}
pooledCount = size;
}
/// <summary>
/// Retrieves the next object in the pool
/// Object will be re-collected after max duration is reached
/// Object will be null if there is no objects left in the pool
/// </summary>
/// <returns>A gameobject from the free pool</returns>
public OABallisticBullet GetNext()
{
if (size <= 0)
{
if (pooledCount < maxSize)
{
InstantiateBullet();
pooledCount += 1;
size = 1;
} else
{
return null; // TODO: return a fake OABallisticBullet?
}
}
var element = freePool[size - 1];
size -= 1;
element.transform.parent = null;
return element;
}
// TODO: ensure it has the same composition as the prefab
public void ReturnObject(OABallisticBullet obj)
{
obj.transform.parent = transform;
freePool[size] = obj;
size += 1;
obj.gameObject.SetActive(false);
}
private void InstantiateBullet(int index = -1)
{
index = (index > -1) ? index : size;
if (index < 0 || index >= maxSize)
return;
var pooledObject = Instantiate(prefab);
pooledObject.transform.parent = transform;
pooledObject.SetActive(false);
var pooledBullet = pooledObject.GetComponent<OABallisticBullet>();
pooledBullet.Pool = this;
freePool[index] = pooledBullet;
}
}
|
177826da718e982be5328c5f020620d41cbc1dd2
|
C#
|
sjha8169/repos
|
/TwitterApiConsumer/TwitterApiConsumer.Base/Service/SampledStreamService.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwitterApiConsumer.Base.Store;
using TwitterApiConsumer.Base.Client;
using Newtonsoft.Json;
using TwitterApiConsumer.Base.JsonObjects;
using TwitterApiConsumer.Base.Model;
using System.Text.RegularExpressions;
using TwitterApiConsumer.Base.Constants;
using TwitterApiConsumer.Base.Logger;
using System.Configuration;
namespace TwitterApiConsumer.Base.Service
{
public class SampledStreamService : AbstractService<SampledStreamModel>
{
#region Private Field
private readonly string _samplingPeriodInSeconds = ConfigurationManager.AppSettings["SamplingPeriodInSeconds"];
#endregion
#region Construction
public SampledStreamService(IStore<SampledStreamModel> store) : base(store)
{
DataStorage = store;
}
#endregion
#region Private Property
private IStore<SampledStreamModel> DataStorage { get; set; }
#endregion
#region Public Property
public int SamplingPeriodInSeconds
{
get
{
int result;
if (!string.IsNullOrEmpty(_samplingPeriodInSeconds) && int.TryParse(_samplingPeriodInSeconds, out result))
{
return result;
}
else
{
return 1;
}
}
}
#endregion
#region Public Method
/// <summary>
/// Starts streaming on background thread and returns Datetime when streaming started
/// </summary>
public DateTime StartSampledStream()
{
Task.Run(() => new SampledStreamClient().StartStreaming(ConvertFromJsonAndStore));
return DateTime.Now;
}
/// <summary>
/// starts a new thread per stream received to process and save
/// </summary>
/// <param name="json"></param>
private void ConvertFromJsonAndStore(string json)
{
Task task = new TaskFactory().StartNew((jobj) =>
{
var sampledStreamModel = JsonToModelConverter(jobj.ToString());
StoreModel(sampledStreamModel);
}, json);
//task.ContinueWith((ret) =>
//{
// if(ret.IsFaulted)
// {
// new Logger.LogWritter().Write(ret.Exception.ToString());
// }
//});
}
/// <summary>
/// converts json string to .net object
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public SampledStreamModel JsonToModelConverter(string json)
{
SampledStreamModel result = null;
try
{
SampledStreamJsonObject jObject = JsonConvert.DeserializeObject<SampledStreamJsonObject>(json);
if (jObject?.data != null)
{
SampledStreamModel model = new SampledStreamModel();
string emoji = FindEmoji(jObject.data.text);
model.Emoji = !string.IsNullOrEmpty(emoji) ? new List<string>() { emoji } : new List<string>();
model.HasEmoji = !string.IsNullOrEmpty(emoji);
if (jObject.data.entities?.hashtags != null && jObject.data.entities.hashtags.Count > 0)
{
model.HashTags = jObject.data.entities.hashtags.Select(c => c.tag).ToList();
}
if (jObject.data.entities?.urls != null && jObject.data.entities.urls.Count > 0)
{
model.HasUrl = true;
if (jObject?.includes?.media != null && jObject.includes.media.Count > 0 && jObject.includes.media.Any(c => c.type.ToLower() == "photo"))
{
model.HasPhotoUrl = true;
}
model.UrlDomain = new List<string>();
foreach (var url in jObject.data.entities.urls)
{
Uri uri = new Uri(url.expanded_url);
model.UrlDomain.Add(uri.Host);
}
}
result = model;
}
}
catch(Exception ex)
{
new LogWritter().Write(ex.ToString());
}
return result;
}
/// <summary>
/// Saves
/// </summary>
/// <param name="sampledStreamModel"></param>
/// <returns></returns>
public bool StoreModel(SampledStreamModel sampledStreamModel)
{
bool result = false;
try
{
DataStorage.Store(sampledStreamModel);
result = true;
}
catch (Exception ex)
{
new Logger.LogWritter().Write(ex.ToString());
}
return result;
}
/// <summary>
/// Retrived data for sampled period
/// </summary>
/// <returns></returns>
public async Task<Tuple<long, List<SampledStreamModel>>> RetriveModel()
{
Tuple<long, List<SampledStreamModel>> result = null;
try
{
result = await Task.Run(() => DataStorage.Retrive(DateTime.Now));
}
catch(Exception ex)
{
new Logger.LogWritter().Write(ex.ToString());
}
return result;
}
#endregion
#region Private Method
private string FindEmoji(string text)
{
Regex rgx = new Regex(Emoji.EmojiPattern);
//var y = rgx.IsMatch(text);
//to find emojis in text
string emoji = rgx.Match(text).Value;
return emoji;
}
#endregion
}
}
|
ffc35085238d5e133a9d52cc95af0a46fcd4df87
|
C#
|
mike1d1/algo-and-data-structures
|
/Sorting/Bubble.cs
| 4.03125
| 4
|
namespace Sorting
{
class Bubble
{
public static void Bubblesort(int[] arr)
{
for(int i = 0; i<arr.Length; i++)
{
for(int j = arr.Length-1; j>i; j--)
{
if(arr[j] < arr[j-1])
{
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
}
// Another version of bubble sort
public static void BubblesortEasy(int[] arr)
{
bool switched = false;
do
{
switched = false;
for(int i = 1; i<arr.Length; i++)
{
if(arr[i-1] > arr[i])
{
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
switched = true;
}
}
} while(switched);
}
// Yet another implementation of bubble sort
public static void OptimizedBubbleSort(int[] arr)
{
bool switched = false;
int n = arr.Length;
do
{
switched = false;
for(int i = 1; i<n; i++)
{
if(arr[i-1] > arr[i])
{
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
switched = true;
}
}
n--;
} while(switched);
}
}
}
|
bb8f433aaf2f2ef5ab8950bc46f5de0e66f1a8e3
|
C#
|
Gab-km/Funcy
|
/Funcy/Future/MaybeTC.cs
| 2.734375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using Funcy.Future.Computations;
using Funcy.Patterns;
namespace Funcy.Future
{
public abstract class MaybeTC<T> : IStructuralEquatable, IStructuralComparable, IComputableTC<MaybeTC, T>
{
public abstract bool IsSome { get; }
public abstract bool IsNone { get; }
public MaybeTC()
{
this.Pointed = new MaybeTC();
}
public SomeTC<T> ToSome()
{
return (SomeTC<T>)this;
}
public NoneTC<T> ToNone()
{
return (NoneTC<T>)this;
}
IPointed<MaybeTC> IFunctorTC<MaybeTC, T>.Pointed { get { return this.Pointed; } }
public MaybeTC Pointed { get; private set; }
IFunctorTC<MaybeTC, TReturn> IFunctorTC<MaybeTC, T>.FMap<TReturn>(Func<T, TReturn> f)
{
return this.FMap<TReturn>(f);
}
public abstract MaybeTC<TReturn> FMap<TReturn>(Func<T, TReturn> f);
IApplicativeTC<MaybeTC, TReturn> IApplicativeTC<MaybeTC, T>.Apply<TReturn>(IApplicativeTC<MaybeTC, Func<T, TReturn>> f)
{
return this.Apply<TReturn>((MaybeTC<Func<T, TReturn >>)f);
}
public MaybeTC<TReturn>Apply<TReturn>(MaybeTC<Func<T,TReturn>>f)
{
if (f.IsSome)
{
return this.FMap<TReturn>(f.ToSome().Value);
}
else
{
return MaybeTC.None<TReturn>();
}
}
IApplicativeTC<MaybeTC, T> IApplicativeTC<MaybeTC, T>.ApplyLeft<TReturn>(IApplicativeTC<MaybeTC, TReturn> other)
{
return this.ApplyLeft<TReturn>((MaybeTC<TReturn >)other);
}
public MaybeTC<T> ApplyLeft<TReturn>(MaybeTC<TReturn> other)
{
return this;
}
IApplicativeTC<MaybeTC, TReturn> IApplicativeTC<MaybeTC, T>.ApplyRight<TReturn>(IApplicativeTC<MaybeTC, TReturn> other)
{
return this.ApplyRight<TReturn>((MaybeTC<TReturn>)other);
}
public MaybeTC<TReturn> ApplyRight<TReturn>(MaybeTC<TReturn> other)
{
return other;
}
IApplicativeTC<MaybeTC, TReturn> IApplicativeTC<MaybeTC, T>.FMapA<TReturn>(Func<T, TReturn> f)
{
return this.FMapA(f);
}
public MaybeTC<TReturn> FMapA<TReturn>(Func<T, TReturn> f)
{
return this.FMap<TReturn>(f);
}
IComputableTC<MaybeTC, TReturn> IComputableTC<MaybeTC, T>.Compute<TReturn>(Func<T, TReturn> f)
{
return this.Compute(f);
}
public MaybeTC<TReturn> Compute<TReturn>(Func<T, TReturn> f)
{
return this.FMap<TReturn>(f);
}
IComputableTC<MaybeTC, TReturn> IComputableTC<MaybeTC, T>.ComputeWith<TReturn>(Func<T, IComputableTC<MaybeTC, TReturn>> f)
{
return this.ComputeWith<TReturn>(x => (MaybeTC<TReturn>)(f(x)));
}
public abstract MaybeTC<TReturn> ComputeWith<TReturn>(Func<T, MaybeTC<TReturn>> f);
public abstract bool Equals(object other, IEqualityComparer comparer);
public abstract int GetHashCode(IEqualityComparer comparer);
public abstract int CompareTo(object other, IComparer comparer);
}
public class MaybeTC : IPointed<MaybeTC>
{
public static MaybeTC<TSource> Some<TSource>(TSource value)
{
return new SomeTC<TSource>(value);
}
public static MaybeTC<TSource> None<TSource>()
{
return new NoneTC<TSource>();
}
IFunctorTC<MaybeTC, TSource> IPointed<MaybeTC>.Point<TSource>(TSource value)
{
return this.Point<TSource>(value);
}
public MaybeTC<TSource> Point<TSource>(TSource value)
{
return MaybeTC.Some<TSource>(value);
}
}
public sealed class SomeTC<T> : MaybeTC<T>, IExtractor<T>
{
public T Value { get; private set; }
public SomeTC(T value)
{
this.Value = value;
}
public override bool IsNone { get { return !this.IsSome; } }
public override bool IsSome { get { return true; } }
public override MaybeTC<TReturn> FMap<TReturn>(Func<T, TReturn> f)
{
return new SomeTC<TReturn>(f(this.Value));
}
public override MaybeTC<TReturn> ComputeWith<TReturn>(Func<T, MaybeTC<TReturn>> f)
{
return f(this.Value);
}
public override bool Equals(object other, IEqualityComparer comparer)
{
if (other == null) return false;
if (other is SomeTC<T>)
{
var some = (SomeTC<T>)other;
return comparer.Equals(this.Value, some.Value);
}
else
{
return false;
}
}
public override bool Equals(object obj)
{
return this.Equals(obj, EqualityComparer<T>.Default);
}
public override int GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(this.Value);
}
public override int GetHashCode()
{
return this.GetHashCode(EqualityComparer<T>.Default);
}
public override int CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (other is SomeTC<T>)
{
var some = (SomeTC<T>)other;
return comparer.Compare(this.Value, some.Value);
}
else if (other is NoneTC<T>)
{
return 1;
}
else
{
throw new ArgumentException("'other' is neither instance of SomeTC nor NoneTC.");
}
}
T IExtractor<T>.Extract()
{
return this.Value;
}
}
public sealed class NoneTC<T> : MaybeTC<T>
{
public override bool IsNone { get { return true; } }
public override bool IsSome { get { return !this.IsNone; } }
public override MaybeTC<TReturn> ComputeWith<TReturn>(Func<T, MaybeTC<TReturn>> f)
{
return MaybeTC.None<TReturn>();
}
public override MaybeTC<TReturn> FMap<TReturn>(Func<T, TReturn> f)
{
return MaybeTC.None<TReturn>();
}
public override bool Equals(object other, IEqualityComparer comparer)
{
if (other == null) return false;
if (other is NoneTC<T>)
{
var none = (NoneTC<T>)other;
return comparer.Equals(this.GetType().DeclaringType, none.GetType().DeclaringType);
}
else
{
return false;
}
}
public override bool Equals(object obj)
{
return this.Equals(obj, EqualityComparer<T>.Default);
}
public override int GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode();
}
public override int GetHashCode()
{
return this.GetHashCode(EqualityComparer<T>.Default);
}
public override int CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (other is SomeTC<T>)
{
return -1;
}
else if (other is NoneTC<T>)
{
var none = (None<T>)other;
return comparer.Compare(this.GetType().DeclaringType, none.GetType().DeclaringType);
}
else
{
throw new ArgumentException("'other' is neither instance of SomeTC nor NoneTC.");
}
}
}
}
|
b250e882ebd3a30c7138bcd5b7be67c82a23c545
|
C#
|
Aeris94/LearningCsharp
|
/DelegatesAndEvents/GenericDelegates.cs
| 3.796875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
public delegate T2 Calc<T1, T2>(T1 a, T1 b);
class Program
{
public static int RectArea(int a, int b)
{
return a * b;
}
public static double TriangleArea(int a, int b)
{
return (0.5*a*b);
}
static void Main(string[] args)
{
Calc<int, int> rect = new Calc<int, int>(RectArea);
Console.WriteLine("The area of the rectangle: {0}.", rect(2, 3));
Calc<int, double> triangle = new Calc<int, double>(TriangleArea);
Console.WriteLine("The area of the triangle: {0}.", triangle(2, 3));
}
}
}
|
8bad492ded3f08325afb0fe3caaf20bd5bce1df5
|
C#
|
leighmckenna/GDAPS1
|
/Abstraction/Abstraction/Drgn.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Abstraction
{
public abstract class Drgn
{
protected Random rng;
protected string name;
public string Name
{
get { return name; }
}
protected int health;
public int Health
{
get { return health; }
set { health = value; }
}
public abstract int Attack();
public abstract int TakeDamage(int d);
public Drgn()
{
}
public Drgn(string n, int h, Random r)
{
name = n;
health = h;
rng = r;
}
public bool IsDead()
{
bool alive = true;
if (health <= 0)
{
alive = false;
}
return alive;
}
}
}
|
cf52049e9876a3b49f84a7483f279b4b51b23199
|
C#
|
alagalia/CSharp-OOP-Advanced-New
|
/Generics/Generic/03.GenericBoxInteger/BoxInteger.cs
| 3.8125
| 4
|
namespace _03.GenericBoxInteger
{
using System;
public class BoxInteger
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
var line = int.Parse(Console.ReadLine());
Console.WriteLine(new Box<int>(line));
}
}
}
public class Box<T>
{
public Box(T value)
{
this.Value = value;
}
private T Value { get; set; }
public override string ToString()
{
return this.Value.GetType().FullName + ": " + this.Value;
}
}
}
|
baf6cebdcc9caad9228a04d59e5929542df23aba
|
C#
|
jamdmasud/PharmacyDesktopApplication
|
/PharmacyDesktopApplication/UI/MedicineEditForm.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Migrations;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PharmacyDesktopApplication.Entities;
namespace PharmacyDesktopApplication.UI
{
public partial class MedicineEditForm : Form
{
public MedicineEditForm()
{
InitializeComponent();
}
public MedicineEditForm(string purchaseId)
{
InitializeComponent();
ShowMedicineDetails(purchaseId);
}
private void ShowMedicineDetails(string id)
{
PharmacyDbContext db = new PharmacyDbContext();
var purchase =
db.PurchaseSub.Where(a => a.Id == id).OrderByDescending(a => a.CreatedDate).Select(s => new
{
s.Id,
s.MedicinId,
s.Quantity,
s.UnitPrice,
}).FirstOrDefault();
if (purchase != null)
{
Medicine medicine = db.Medicine.Find(purchase.MedicinId);
txtMedicineName.Text = medicine.Name;
dtpExpiredDate.Value = medicine.ExpiredDate;
txtQuantity.Text = purchase.Quantity.ToString();
txtUnitPrice.Text = purchase.UnitPrice.ToString(CultureInfo.CurrentCulture);
medicineId.Text = purchase.MedicinId;
purchasedId.Text = purchase.Id;
}
}
private void button1_Click(object sender, EventArgs e)
{
PharmacyDbContext db = new PharmacyDbContext();
PurchaseSub sub = db.PurchaseSub.FirstOrDefault(a => a.Id == purchasedId.Text);
if (sub != null)
{
sub.UnitPrice = Convert.ToDecimal(txtUnitPrice.Text);
sub.Quantity = int.Parse(txtQuantity.Text);
sub.Total = (sub.Quantity*sub.UnitPrice);
db.PurchaseSub.AddOrUpdate(sub);
}
Medicine medicine = db.Medicine.FirstOrDefault(a => a.Id == medicineId.Text);
if (medicine != null)
{
medicine.ExpiredDate = dtpExpiredDate.Value;
db.Medicine.AddOrUpdate(medicine);
}
db.SaveChanges();
MessageBox.Show(@"Update successful!", "Success", MessageBoxButtons.OK);
this.Close();
}
}
}
|
9116ee75a502261645646956a16567b283dff4a0
|
C#
|
brann0n/StendenKoffieMachine
|
/KoffieMachineBot/Program.cs
| 2.625
| 3
|
using Discord;
using Discord.WebSocket;
using System;
using KoffieMachineBot.Modules;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;
using System.Reflection;
namespace KoffieMachineBot
{
public class Program
{
DiscordSocketClient _client;
CommandService _commands;
IServiceProvider _services;
CommandHandler _handler;
static void Main(string[] args) => new Program().StartBotAsync().GetAwaiter().GetResult();
public async Task StartBotAsync()
{
//check if the config was loaded successfully
if (string.IsNullOrEmpty(BotConfig.bot.Token))
{
Console.WriteLine("No Authtoken present, please check the config file and restart the bot.");
Console.ReadLine();
return;
}
//Set log Level
_client = new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Verbose
});
//Assign client event triggers.
_client.Log += Log;
//Connect the bot to discord
await _client.LoginAsync(TokenType.Bot, BotConfig.bot.Token);
await _client.StartAsync();
//assign the current client object to the global client object
Global.Client = _client;
//set status to prefix
await _client.SetGameAsync($"prefix {BotConfig.bot.CmdPrefix}", type: ActivityType.Listening);
_commands = new CommandService();
_services = new ServiceCollection()
.AddSingleton<DiscordSocketClient>(_client)
.AddSingleton<CommandService>(_commands)
.AddSingleton<HttpClient>() // ???
.BuildServiceProvider();
Global.Commands = _commands;
//discover all of the commands in this assembly and load them.
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
//assign the command handler
_handler = new CommandHandler(_client, _services, _commands);
Global.Commands = _commands;
//stay in this function forever
await Task.Delay(-1);
}
private async Task Log(LogMessage msg)
{
await Task.Yield(); // doet niks, maar weg met die kutte async warnings
Console.WriteLine(msg.Message);
}
}
}
|
f9ecff336287da18670ae793040bd221af49a39a
|
C#
|
piotr-pierzgalski/PrimeCounterAPI
|
/PrimeCounterAPI/Controllers/PrimeCounterController.cs
| 2.59375
| 3
|
using System.Threading.Tasks;
using Commands.CreatePrimeCounter;
using Commands.DeletePrimeCounter;
using Commands.IncrementPrimeCounter;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Queries.GetPrimeCounter;
namespace PrimeCounterAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PrimeCounterController : ControllerBase
{
private IMediator _mediator;
public PrimeCounterController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet()]
public async Task<ActionResult<GetPrimeCounterQueryResult>> GetPrimeCounter(string name)
{
var result = await _mediator.Send(new GetPrimeCounterQuery(name));
if (!result.Item1)
{
return NotFound();
}
else
{
return result.Item2;
}
}
[HttpPost("create")]
public async Task<ActionResult> CreatePrimeCounter(string name)
{
var result = await _mediator.Send(new CreatePrimeCounterCommand(name));
if(!result)
{
return Conflict();
}
else
{
return Ok();
}
}
[HttpPost("increment")]
public async Task<ActionResult> IncrementPrimeCounter(string name)
{
var result = await _mediator.Send(new IncrementPrimeCounterCommand(name));
if (!result)
{
return NotFound();
}
else
{
return Ok();
}
}
[HttpDelete]
public async Task<ActionResult> DeletePrimeCounter(string name)
{
var result = await _mediator.Send(new DeletePrimeCounterCommand(name));
if (!result)
{
return NotFound();
}
else
{
return Ok();
}
}
}
}
|
13d82dea1f10bdb7521660963c88b5716344eab2
|
C#
|
WojcikMikolaj/GraphsLibrary
|
/GraphLibrary/GraphExtenders/SpanningTreeExtenders/BoruvkaExtender.cs
| 2.875
| 3
|
using GraphLibrary.DataStructuresClasses;
using GraphLibrary.ExceptionClasses;
using System.Collections.Generic;
namespace GraphLibrary.GraphExtenders.SpanningTreeExtenders
{
public static class BoruvkaExtender
{
public static (bool connected, Graph tree) Boruvka(this Graph g)
{
if (g.Directed)
{
throw new WrongGraphException("Graph must be an undirected graph");
}
int numberOfTrees = g.VerticesCount;
Graph tree = g.IsolatedGraph(false);
UnionFind unionFind = new UnionFind(g.VerticesCount);
PairingHeap<Edge>[] heaps = new PairingHeap<Edge>[g.VerticesCount];
HashSet<int> activeHeaps = new HashSet<int>();
for (int i = 0; i < g.VerticesCount; i++)
{
heaps[i] = new PairingHeap<Edge>((x, y) => x.Weight > y.Weight);
activeHeaps.Add(i);
foreach (Edge e in g.GetEdgesFrom(i))
{
heaps[i].Insert(e);
}
}
OrdinaryList<(int, int)> heapsToMerge = new OrdinaryList<(int, int)>();
EdgesList edges = new EdgesList();
while (true)
{
foreach (int heapId in activeHeaps)
{
var result = heaps[heapId].ExtractMinimum();
if (result.HasValue)
{
edges.Push(result.value);
}
}
if (edges.IsEmpty() && numberOfTrees > 1)
{
return (false, tree);
}
while (!edges.IsEmpty())
{
Edge e = edges.Pop();
if (null == tree.GetEdge(e.From, e.To))
{
int heapOneId = unionFind.FindParent(e.From);
int heapTwoId = unionFind.FindParent(e.To);
if (heapOneId != heapTwoId)
{
tree.AddEdge(e);
unionFind.Union(e.From, e.To);
heapsToMerge.Push((heapOneId, heapTwoId));
if (unionFind.FindParent(e.From) == heapOneId)
{
heaps[heapOneId].Concatenate(heaps[heapTwoId]);
heaps[heapTwoId] = null;
activeHeaps.Remove(heapTwoId);
}
else
{
heaps[heapTwoId].Concatenate(heaps[heapOneId]);
heaps[heapOneId] = null;
activeHeaps.Remove(heapOneId);
}
numberOfTrees--;
}
}
}
if (numberOfTrees == 1)
{
return (true, tree);
}
}
}
}
}
|
7ef9924d2fa8596aa6b6bb1c7a7d867eec3c6d44
|
C#
|
vesopk/TechModuleExtended-Exercises
|
/SimpleArrayProcessing/MultiplyArrayOfDouble/MultiplyArrayOfDouble.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class MultiplyArrayOfDouble
{
public static void Main()
{
var numbers = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
var numberToMultiply = double.Parse(Console.ReadLine());
var result = new double[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
result[i] = numbers[i] * numberToMultiply;
}
Console.WriteLine(string.Join(" ",result));
}
}
|
9743f10e7fb2f98f026b4e8a82603b8a9b1c80bc
|
C#
|
horizongir/ode.net
|
/Ode.Net/Joints/JointFeedback.cs
| 2.796875
| 3
|
using Ode.Net.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ode.Net.Joints
{
/// <summary>
/// Represents a data object that stores the feedback forces applied by
/// a joint on its connected bodies.
/// </summary>
/// <remarks>
/// All memory management of joint feedbacks is, for now, left
/// entirely up to the user. Be sure not to use additional references
/// to the same JointFeedback structure after calling Dispose().
/// The user is also expected to manage the reference which is registered
/// with a given Joint. If you dispose a JointFeedback without first
/// setting the reference on the Joint to null, you risk a memory
/// violation exception.
/// This behaviour may be refined in the future to adhere to managed
/// code memory management design patterns. For now it is left as is from
/// the ODE lower-level library code.
/// </remarks>
public sealed class JointFeedback : IDisposable
{
readonly dJointFeedbackHandle handle;
/// <summary>
/// Initializes a new instance of the <see cref="JointFeedback"/> class.
/// </summary>
public JointFeedback()
{
handle = new dJointFeedbackHandle();
}
internal dJointFeedbackHandle Handle
{
get { return handle; }
}
/// <summary>
/// Gets the force that the joint applies to the first body.
/// </summary>
public Vector3 ForceOnBody1
{
get { return handle.ForceOnBody1; }
}
/// <summary>
/// Gets the torque that the joint applies to the first body.
/// </summary>
public Vector3 TorqueOnBody1
{
get { return handle.TorqueOnBody1; }
}
/// <summary>
/// Gets the force that the joint applies to the second body.
/// </summary>
public Vector3 ForceOnBody2
{
get { return handle.ForceOnBody2; }
}
/// <summary>
/// Gets the torque that the joint applies to the second body.
/// </summary>
public Vector3 TorqueOnBody2
{
get { return handle.TorqueOnBody2; }
}
/// <summary>
/// Destroys the feedback data object.
/// </summary>
public void Dispose()
{
handle.Close();
}
}
}
|
6cc462f0568fa13e2fff11dfc4205c044107fd71
|
C#
|
robpocko/JobLogger
|
/JobLogger.API/Model/CodeBranchAPI.cs
| 2.578125
| 3
|
using JobLogger.DAL;
using System.Collections.Generic;
using System.Linq;
namespace JobLogger.API.Model
{
public class CodeBranchAPI : APIBase
{
public string Name { get; set; }
public List<CheckInAPI> BranchCheckIns { get; set; }
public static CodeBranch To(CodeBranchAPI item)
{
return new CodeBranch
{
ID = item.ID,
Name = item.Name,
BranchCheckIns = CheckInAPI.To(item.BranchCheckIns)
};
}
public static CodeBranchAPI From(CodeBranch item)
{
return new CodeBranchAPI
{
ID = item.ID,
Name = item.Name
};
}
public static ICollection<CodeBranchAPI> From(ICollection<CodeBranch> items)
{
if (items != null)
{
ICollection<CodeBranchAPI> list = new List<CodeBranchAPI>();
foreach (var item in items)
{
list.Add(From(item));
}
return list;
}
else
{
return null;
}
}
}
}
|
fcf00e00da1ddb44272d37c0eaac6c0060a157d6
|
C#
|
gruntwurk/text-data-simplifier
|
/PageProfile.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using static GruntWurk.QuickLog;
using static GruntWurk.NumberUtils;
using static GruntWurk.StringUtils;
namespace GruntWurk {
/// <summary>
/// Describes a paginated data file (aka a "line printer report"), including specifications for the page header (if any),
/// page footer (if any), and group headers (if any).
/// Also specifies whether data "rows" consist of one line each, or are wrapped onto continuation lines.
/// Each band (page header, page foorter, group header, and data row) can have multiple fields defined.
/// </summary>
public class PageProfile {
public bool HasHeader;
public bool HasFooter;
public bool HasGroup;
public bool HasCondition;
public int HeaderLinesStart;
public int HeaderLinesEnd;
public int DataLinesStart;
public int DataLinesEnd;
public int DataLinesPerRow;
public int FooterLinesStart;
public int FooterLinesEnd;
public int GroupLinesPerRow;
public FieldSpec GroupTrigger;
public List<FieldSpec> HeaderFields;
public List<FieldSpec> DataFields;
public List<FieldSpec> GroupFields;
public List<FieldSpec> FooterFields;
public FieldSpec ConditionFieldSpec;
public string ConditionValue;
public string ConditionAction;
/// <summary>
/// Constructor #1
/// </summary>
public PageProfile() {
Clear();
}
/// <summary>
/// Constructor #2
/// </summary>
/// <param name="spec"></param>
public PageProfile(IniFile spec) {
Clear();
InitializeFromIniFile(spec);
}
public void SetHeaderLines(string arg) {
try {
HasHeader = true;
HeaderLinesStart = StartOfRangeSpec(arg);
HeaderLinesEnd = EndOfRangeSpec(arg);
} catch (FormatException) {
throw new ArgumentException("Invalid Lines specification: " + arg, "Page Header section");
}
}
public void SetFooterLines(string arg) {
if (arg == "") {
return;
}
try {
HasFooter = true;
FooterLinesStart = StartOfRangeSpec(arg);
FooterLinesEnd = EndOfRangeSpec(arg);
} catch (FormatException) {
throw new ArgumentException("Invalid Lines specification: " + arg, "Footer section");
}
}
public void SetDataLines(string arg) {
if (arg == "") {
return;
}
DataLinesStart = StartOfRangeSpec(arg);
DataLinesEnd = EndOfRangeSpec(arg);
}
public void SetDataLinesPerRow(string arg) {
if (arg == "") {
return;
}
if (!int.TryParse(arg, out DataLinesPerRow)) {
throw new ArgumentException("Invalid Lines Per Row: " + arg, "Data section");
}
}
public void SetGroupLinesPerRow(string arg) {
if (arg == "") {
return;
}
HasGroup = true;
if (!int.TryParse(arg, out GroupLinesPerRow)) {
throw new ArgumentException("Invalid Lines Per Row: " + arg, "Data section");
}
}
public void SetGroupTrigger(string arg) {
if (arg == "") {
return;
}
HasGroup = true;
GroupTrigger = new FieldSpec(arg);
}
public void AddHeaderField(string arg) {
if (arg == "") {
return;
}
try {
HeaderFields.Add(new FieldSpec(arg));
} catch (FormatException) {
throw new ArgumentException("Invalid field specification: " + arg, "Page Header section");
}
}
public void AddDataField(string arg) {
if (arg == "") {
return;
}
try {
DataFields.Add(new FieldSpec(arg));
} catch (FormatException) {
throw new ArgumentException("Invalid field specification: " + arg, "Data section");
}
}
public void AddGroupField(string arg) {
if (arg == "") {
return;
}
try {
GroupFields.Add(new FieldSpec(arg));
} catch (FormatException) {
throw new ArgumentException("Invalid field specification: " + arg, "Group Header section");
}
}
public void AddFooterField(string arg) {
if (arg == "") {
return;
}
try {
FooterFields.Add(new FieldSpec(arg));
} catch (FormatException) {
throw new ArgumentException("Invalid field specification: " + arg, "Page Footer section");
}
}
private void Clear() {
HasHeader = false;
HeaderLinesStart = 0;
HeaderLinesEnd = 0;
DataLinesStart = 1;
DataLinesEnd = 0;
DataLinesPerRow = 1;
HasFooter = false;
HasCondition = false;
FooterLinesStart = 0;
FooterLinesEnd = 0;
GroupLinesPerRow = 0;
HeaderFields = new List<FieldSpec>();
DataFields = new List<FieldSpec>();
GroupFields = new List<FieldSpec>();
FooterFields = new List<FieldSpec>();
}
private void InitializeFromIniFile(IniFile spec) {
List<IniFileEntry> fieldEntries;
SetHeaderLines(spec.GetString("Page Header", "Lines", ""));
SetDataLines(spec.GetString("Data", "Lines", ""));
SetDataLinesPerRow(spec.GetString("Data", "Lines Per Row", ""));
SetGroupLinesPerRow(spec.GetString("Group Header", "Lines Per Row", ""));
SetGroupTrigger(spec.GetString("Group Header", "Trigger", ""));
SetFooterLines(spec.GetString("Page Footer", "Lines", ""));
// Header fields
fieldEntries = spec.GetAll("Page Header");
foreach (IniFileEntry entry in fieldEntries) {
if (entry.key == "Field") {
AddHeaderField(entry.value);
}
}
// Data fields
fieldEntries = spec.GetAll("Data");
foreach (IniFileEntry entry in fieldEntries) {
if (entry.key == "Field") {
AddDataField(entry.value);
}
}
// Group fields
fieldEntries = spec.GetAll("Group Header");
foreach (IniFileEntry entry in fieldEntries) {
if (entry.key == "Field") {
AddGroupField(entry.value);
}
}
// Footer fields
fieldEntries = spec.GetAll("Page Footer");
foreach (IniFileEntry entry in fieldEntries) {
if (entry.key == "Field") {
AddFooterField(entry.value);
}
}
// TODO Change this to a field spec (like the group trigger)
if (spec.Sections.ContainsKey("CONDITION")) {
Dictionary<string, IniFileEntry> submap = spec.Sections["CONDITION"];
if (submap.Count > 0) {
if (submap.Keys.Contains("FIELD") && submap.Keys.Contains("VALUE")) {
HasCondition = true;
ConditionFieldSpec = new FieldSpec(submap["FIELD"].value);
ConditionValue = submap["VALUE"].value;
if (submap.Keys.Contains("ACTION")) {
ConditionAction = submap["ACTION"].value;
if (ConditionAction != "Next Page") {
throw new ArgumentException("Invalid Condition Action. Only 'Next Page' is currenly supported.");
}
} else {
log("Condition action of 'Next Page' was assumed, even though it was not specified.");
ConditionAction = "Next Page";
}
} else {
throw new ArgumentException("Field or Value specification is missing", "Contition");
}
}
}
}
public void Dump() {
log("===== Page Profile =====");
List<string> elements = new List<string>();
if (HasHeader) {
elements.Add(string.Format("Page Header {0}..{1}", HeaderLinesStart, HeaderLinesEnd));
} else {
elements.Add("No Page Header");
}
if (HasGroup) {
elements.Add(string.Format("Group Header {0} lines per row", GroupLinesPerRow));
elements.Add(string.Format("Group Header trigger {0} @ line {1}, col {2}", GroupTrigger.FieldName, GroupTrigger.LineNo, GroupTrigger.ColNo));
} else {
elements.Add("No Group Header");
}
elements.Add(string.Format("Data {0}..{1}/{2}", DataLinesStart, DataLinesEnd, DataLinesPerRow));
if (HasFooter) {
elements.Add(string.Format("Page Footer {0}..{1}", FooterLinesStart, FooterLinesEnd));
} else {
elements.Add("No Page Footer");
}
log(string.Join("; ", elements));
log("");
}
/// <summary>
/// Returns the DataLinesEnd spec, adjusted for the fact that it might be 0 or negative, in which case it's an offset with respect to the total count of lines on the current page (or whatever count is passed in).
/// </summary>
/// <param name="LineCount"></param>
/// <returns></returns>
public int AdjustedDataLinesEnd(int LineCount) {
return (DataLinesEnd > 0) ? DataLinesEnd : LineCount + DataLinesEnd;
}
}
}
|
464768490c596d27eaf6902c2606c688261a491a
|
C#
|
danbarua/Grasp
|
/Source/Grasp/Compilation/CalculationCycleException.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
namespace Grasp.Compilation
{
/// <summary>
/// Indicates a set of calculations contains a cycle
/// </summary>
public class CalculationCycleException : Exception
{
/// <summary>
/// Initializes an exception with the specified calculation context and repeated calculation
/// </summary>
/// <param name="context">The calculations above the repeated one from the root</param>
/// <param name="repeatedCalculation">The calculation repeated in the context of the root</param>
public CalculationCycleException(IEnumerable<Calculation> context, Calculation repeatedCalculation)
{
Contract.Requires(context != null);
Contract.Requires(repeatedCalculation != null);
Context = context.ToList().AsReadOnly();
RepeatedCalculation = repeatedCalculation;
}
/// <summary>
/// Initializes an exception with the specified calculation contextm, repeated calculation, and message
/// </summary>
/// <param name="context">The calculations above the repeated one from the root</param>
/// <param name="repeatedCalculation">The calculation repeated in the context of the root</param>
/// <param name="message">The message that describes the error</param>
public CalculationCycleException(IEnumerable<Calculation> context, Calculation repeatedCalculation, string message)
: base(message)
{
Contract.Requires(context != null);
Contract.Requires(repeatedCalculation != null);
Context = context.ToList().AsReadOnly();
RepeatedCalculation = repeatedCalculation;
}
/// <summary>
/// Initializes an exception with the specified calculation context, repeated calculation, message, and inner exception
/// </summary>
/// <param name="context">The calculations above the repeated one from the root</param>
/// <param name="repeatedCalculation">The calculation repeated in the context of the root</param>
/// <param name="message">The message that describes the error</param>
/// <param name="inner">The exception that is the cause of this exception</param>
public CalculationCycleException(IEnumerable<Calculation> context, Calculation repeatedCalculation, string message, Exception inner)
: base(message, inner)
{
Contract.Requires(context != null);
Contract.Requires(repeatedCalculation != null);
Context = context.ToList().AsReadOnly();
RepeatedCalculation = repeatedCalculation;
}
/// <summary>
/// Gets the calculations above the repeated one from the root
/// </summary>
public ReadOnlyCollection<Calculation> Context { get; private set; }
/// <summary>
/// Gets the calculation repeated in the context of the root
/// </summary>
public Calculation RepeatedCalculation { get; private set; }
}
}
|
7e64b3de91af43be77514ca702860cf7fbaf1239
|
C#
|
hboesendorfer/AgOpenGPS
|
/SourceCode/GPS/Forms/FormShiftPos.cs
| 2.53125
| 3
|
using System;
using System.Windows.Forms;
namespace AgOpenGPS
{
public partial class FormShiftPos : Form
{
//class variables
private readonly FormGPS mf = null;
public FormShiftPos(Form callingForm)
{
//get copy of the calling main form
mf = callingForm as FormGPS;
InitializeComponent();
label27.Text = gStr.gsNorth;
label2.Text = gStr.gsWest;
label3.Text = gStr.gsEast;
label4.Text = gStr.gsSouth;
this.Text = gStr.gsShiftGPSPosition;
}
private void FormShiftPos_Load(object sender, EventArgs e)
{
nudEast.Value = (decimal)mf.pn.fixOffset.easting * 100;
nudNorth.Value = (decimal)mf.pn.fixOffset.northing * 100;
}
private void btnNorth_MouseDown(object sender, MouseEventArgs e)
{
nudNorth.UpButton();
mf.pn.fixOffset.northing = (double)nudNorth.Value / 100;
}
private void btnSouth_MouseDown(object sender, MouseEventArgs e)
{
nudNorth.DownButton();
mf.pn.fixOffset.northing = (double)nudNorth.Value / 100;
}
private void btnWest_MouseDown(object sender, MouseEventArgs e)
{
nudEast.DownButton();
mf.pn.fixOffset.easting = (double)nudEast.Value / 100;
}
private void btnEast_MouseDown(object sender, MouseEventArgs e)
{
nudEast.UpButton();
mf.pn.fixOffset.easting = (double)nudEast.Value / 100;
}
private void nudNorth_ValueChanged(object sender, EventArgs e)
{
mf.pn.fixOffset.northing = (double)nudNorth.Value / 100;
}
private void nudEast_ValueChanged(object sender, EventArgs e)
{
mf.pn.fixOffset.easting = (double)nudEast.Value / 100;
}
private void btnZero_Click(object sender, EventArgs e)
{
nudEast.Value = 0;
nudNorth.Value = 0;
mf.pn.fixOffset.easting = 0;
mf.pn.fixOffset.northing = 0;
}
private void bntOK_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
0abf6382b8947ad74dab6640df2e7ae009a180b4
|
C#
|
Phamotx/Tag-game
|
/Tagged/Assets/Scripts/Controller.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class Controller : MonoBehaviour
{
[SerializeField]
private LayerMask collisionLayer;
const float widthOfSkin = 0.020f;
[SerializeField]
private int horizontalRayCount = 4;
[SerializeField]
private int verticalRayCount = 4;
float horizontalRaySpacing;
float verticalRaySpacing;
BoxCollider2D collider;
RaycastOriginPosition rayPos;
public CollisonInfo collisonInfo;
void Start()
{
collider = GetComponent<BoxCollider2D>();
CalculateRaySpacing();
}
private void Update()
{
}
public void Move(Vector3 velocity)
{
collisonInfo.Reset();
UpdateRaycastOriginPosition();
if (velocity.x != 0)
{
HorizontalCollison(ref velocity);
}
if (velocity.y != 0)
{
VerticalCollison(ref velocity);
}
transform.Translate(velocity);
}
void HorizontalCollison(ref Vector3 velocity)
{
float directionX = Mathf.Sign(velocity.x);
float rayLength = Mathf.Abs(velocity.x) + widthOfSkin;
for (int i = 0; i < horizontalRayCount; i++)
{
Vector2 rayOrigin = (directionX == -1) ? rayPos.bottomLeft : rayPos.bottomRight;
rayOrigin += Vector2.up * (horizontalRaySpacing * i);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionLayer);
Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red);
if (hit)
{
velocity.x = (hit.distance - widthOfSkin) * directionX;
rayLength = hit.distance;
collisonInfo.left = (directionX == -1);
collisonInfo.right = (directionX == 1);
}
}
}
void VerticalCollison(ref Vector3 velocity)
{
float directionY = Mathf.Sign(velocity.y);
float rayLength = Mathf.Abs(velocity.y) + widthOfSkin;
for (int i = 0; i < verticalRayCount; i++)
{
Vector2 rayOrigin = (directionY == -1) ? rayPos.bottomLeft : rayPos.topLeft;
rayOrigin += Vector2.right*(verticalRaySpacing*i+velocity.x);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionLayer);
Debug.DrawRay(rayOrigin, Vector2.up * directionY*rayLength, Color.red);
if (hit)
{
velocity.y = (hit.distance-widthOfSkin) * directionY;
rayLength = hit.distance;
collisonInfo.below = (directionY == -1);
collisonInfo.above = (directionY == 1);
}
}
}
void UpdateRaycastOriginPosition()
{
Bounds bounds = collider.bounds;
bounds.Expand(widthOfSkin * -2f);
rayPos.bottomLeft = new Vector2(bounds.min.x, bounds.min.y);
rayPos.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
rayPos.topLeft = new Vector2(bounds.min.x, bounds.max.y);
rayPos.topRight = new Vector2(bounds.max.x, bounds.max.y);
}
void CalculateRaySpacing()
{
Bounds bounds = collider.bounds;
bounds.Expand(widthOfSkin * -2f);
horizontalRayCount = Mathf.Clamp(horizontalRayCount, 2, int.MaxValue);
verticalRayCount = Mathf.Clamp(verticalRayCount, 2, int.MaxValue);
horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1);
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);
}
struct RaycastOriginPosition
{
public Vector2 topLeft, topRight;
public Vector2 bottomLeft, bottomRight;
}
public struct CollisonInfo
{
public bool above, below;
public bool right, left;
public void Reset()
{
above = below = right = left = false;
}
}
}
|
eceafed551ea3ac1d8da3731b3ecd77d5c13d876
|
C#
|
juanramon89/rad
|
/PArticulo/PArticulo/Main.cs
| 2.9375
| 3
|
using System;
using MySql.Data.MySqlClient;
using System.Data;
using Pserpis;
namespace PArticulo
{
class MainClass
{
public static void Main (string[] args)
{
string connectionString =
"Server=localhost;" +
"Database=dbrepaso;" +
"User Id=root;" +
"Password=sistemas";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
mySqlConnection.Open();
MySqlCommand updateMySqlCommand = mySqlConnection.CreateCommand();
//string hora = DateTime.Now.ToString();
updateMySqlCommand.CommandText = "update articulo set nombre =@nombre where id=1";
string nombre = "nombre";
string valor = DateTime.Now.ToString();
/*
// Pasar como parametro:
MySqlParameter mySqlParameter = updateMySqlCommand.CreateParameter();
mySqlParameter.ParameterName = "nombre";
mySqlParameter.Value = DateTime.Now.ToString();
updateMySqlCommand.Parameters.Add(mySqlParameter);
//Ejecutar update:
updateMySqlCommand.ExecuteNonQuery();
*/
MyClass.introduccionParametro(nombre,valor,updateMySqlCommand);
mostrar(mySqlConnection);
//Borrado de datos:
MySqlCommand deleteMySqlCommand = mySqlConnection.CreateCommand();
deleteMySqlCommand.CommandText = "DELETE FROM articulo WHERE id=@numero";
MySqlParameter delMySqlParameter = deleteMySqlCommand.CreateParameter();
delMySqlParameter.ParameterName = "numero";
delMySqlParameter.Value = 5;
deleteMySqlCommand.Parameters.Add(delMySqlParameter);
deleteMySqlCommand.ExecuteNonQuery();
mostrar(mySqlConnection);
//Insertar datos:
MySqlCommand insertMySqlCommand = mySqlConnection.CreateCommand();
insertMySqlCommand.CommandText = "INSERT INTO articulo (id, nombre, categoria, precio)"+
"VALUES('5','articulo 5','null','null')";
insertMySqlCommand.ExecuteNonQuery();
mostrar(mySqlConnection);
mySqlConnection.Close();
/*
//Conectamos y abrimos la BD:
IDbConnection dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
//Creamos el comando para hacer un update en la BD:
IDbCommand updateDbCommand = dbConnection.CreateCommand();
updateDbCommand.CommandText = "update articulo set nombre =@nombre where id=1";
//Creamos el parametro que introduciremos para modificar:
IDbDataParameter dbDataParameter = updateDbCommand.CreateParameter();
dbDataParameter.ParameterName = "nombre";
dbDataParameter.Value = DateTime.Now.ToString();
//Añadimos el parametro a la consulta:
updateDbCommand.Parameters.Add(dbDataParameter);
//Ejecutamos update:
updateDbCommand.ExecuteNonQuery();
IDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandText = "SELECT * FROM articulo";
IDataReader dataReader = dbCommand.ExecuteReader();
dataReader.Read();
while(dataReader.Read()){
Console.WriteLine("id={0} nombre{1}", dataReader["id"], dataReader["nombre"]);
}
dataReader.Close();
dbConnection.Close();
*/
}
public static void mostrar(MySqlConnection mySqlConnection){
//Vemos el resultado de la tabla:
MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT * FROM articulo";
MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while(mySqlDataReader.Read()){
Console.WriteLine("id={0} nombre{1}", mySqlDataReader["id"], mySqlDataReader["nombre"]);
}
mySqlDataReader.Close();
}
}
}
|
dcabecc631fd96257eae190c1155d5fd1bffed4a
|
C#
|
rachel2386/CodeLab1Final
|
/CodeLab1Final/Assets/GameManager.cs
| 2.75
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public int gameTimeInSeconds = 30;
private float timeInSeconds;
public static int gameState = 0;
private int gameOverState = 1;
private int winState = 2;
private int playerHP = 5;
private TextMeshProUGUI timerText;
private TextMeshProUGUI hpText;
private TextMeshProUGUI stateText;
// Start is called before the first frame update
void Start()
{
timerText = GameObject.Find("TimerText").GetComponent<TextMeshProUGUI>();
hpText = GameObject.Find("HPText").GetComponent<TextMeshProUGUI>();
stateText = GameObject.Find("StateText").GetComponent<TextMeshProUGUI>();
timeInSeconds = (float) gameTimeInSeconds;
}
// Update is called once per frame
void Update()
{
if (gameState == 0)
{
CountDown();
}
UpdateText();
}
public void damagePlayer()
{
print("playerDamaged");
if (playerHP > 0)
playerHP--;
else
{
gameState = 1;
}
}
void CountDown()
{
if (timeInSeconds >= 0)
timeInSeconds -= Time.deltaTime;
else
gameState = winState;
}
void UpdateText()
{
switch (gameState)
{
case 0:
timerText.text = Mathf.RoundToInt(timeInSeconds % 60).ToString();
stateText.text = "";
break;
case 1:
stateText.text = "YOU LOSE";
stateText.color = Color.red;
break;
default:
stateText.text = "YOU WIN";
stateText.color = Color.green;
break;
}
hpText.text = "HP:" + playerHP;
}
}
|
a66696ee655cf4aa10f9b497ed27344ca6bd2177
|
C#
|
frobnic/0xA2Switch
|
/0xA2Switch/Program.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0xA2Switch
{
class Program
{
static void Main(string[] args)
{
char c;
Console.Write("Bitte antworten Sie!!!");
c = Console.ReadKey().KeyChar;
c = char.ToLower(c);
Console.WriteLine();
switch (c)
{
case 'j':
case 'o':
case 'y':
Console.WriteLine("Sie haben mit 'Ja' geantwortet");
break;
case 'n':
Console.WriteLine("Sie haben mit 'Nein' geantwortet");
break;
default:
Console.WriteLine("Sie haben eine falsche Eingabe gemacht");
break;
}
}
}
}
|
3de9c015aa0e360b39f2ab9254609a1b70e0d523
|
C#
|
Ghasem313/GroupAssignments2
|
/GroupAssignment2/PlayingCard.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GroupAssignment2
{
public enum PlayingCardColor
{
Clubs = 0, Diamonds, Hearts, Spades // Poker suit order, Spades highest
}
public enum PlayingCardValue
{
Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Knight, Queen, King, Ace // Poker Value order
}
public class PlayingCard
{
public PlayingCardColor Color { get; init; }
public PlayingCardValue Value { get; init; }
public string BlackOrRed
{
get
{
if (Color == PlayingCardColor.Clubs || Color == PlayingCardColor.Spades)
return "Black";
return "Red";
}
}
/// <summary>
/// Returns "Face" for Ace,Knight, Queen, King. Otherwise it returns "Value".
///
/// </summary>
string FaceOrValue
{
get
{
//YOUR CODE
//to return "Face" or "Value"
//Use switch expression
}
}
public override string ToString() => $"{Value} of {Color}, a {BlackOrRed} {FaceOrValue} card";
/// <summary>
/// Constructor that generates a random card
/// </summary>
public PlayingCard()
{
//YOUR CODE
// write a constructor that generates a random card.
// I.e., PlayingCard card1 = new PlayingCard(); generates a random card.
}
}
}
|
0d27d7ac64e8baad0044e5479bea05af9d9b449e
|
C#
|
gregolsky/Glimpse.RavenDb
|
/Glimpse.RavenDb.Tests/JsonTests.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace Glimpse.RavenDb.Tests
{
public class JsonTests
{
private RavenDbTab tab = new RavenDbTab();
[Fact]
public void CanHandleNonJson()
{
var result = tab.ParseJsonResult("The server returned an Error 404.");
Assert.Equal("The server returned an Error 404.", result);
}
[Fact]
public void CanProcessString()
{
var result = tab.ParseJsonResult(@"{""key"":""data""}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.Equal("data", data[1][1]);
}
[Fact]
public void CanProcessInt()
{
var result = tab.ParseJsonResult(@"{""key"":12}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.Equal((Int64)12, data[1][1]);
}
[Fact]
public void CanProcessFloat()
{
var result = tab.ParseJsonResult(@"{""key"":12.34}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.Equal(12.34m, data[1][1]);
}
[Fact]
public void CanProcessBoolean()
{
var result = tab.ParseJsonResult(@"{""key"":true}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.Equal(true, data[1][1]);
}
[Fact]
public void CanProcessSubObject()
{
var result = tab.ParseJsonResult(@"{""key"":{""subkey"":""data""}}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.IsType<List<object[]>>(data[1][1]);
var subdata = data[1][1] as List<object[]>;
Assert.Equal(2, subdata.Count);
Assert.Equal("subkey", subdata[1][0]);
Assert.Equal("data", subdata[1][1]);
}
[Fact]
public void CanProcessValueArray()
{
var result = tab.ParseJsonResult(@"{""array"":[true,false,true]}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("array", data[1][0]);
Assert.IsType<List<object[]>>(data[1][1]);
var subdata = data[1][1] as List<object[]>;
Assert.Equal(4, subdata.Count);
Assert.Equal("Values", subdata[0][0]);
Assert.Equal(true, subdata[1][0]);
Assert.Equal(false, subdata[2][0]);
Assert.Equal(true, subdata[3][0]);
}
[Fact]
public void CanProcessObjectArray()
{
var result = tab.ParseJsonResult(@"{""array"":[{""key1"":""val1"",""key2"":""val2""},{""key1"":""val3"",""key2"":""val4""},{""key1"":""val5"",""key2"":""val6""}]}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("array", data[1][0]);
Assert.IsType<List<object[]>>(data[1][1]);
var subdata = data[1][1] as List<object[]>;
Assert.Equal(4, subdata.Count);
Assert.Equal("key1", subdata[0][0]);
Assert.Equal("key2", subdata[0][1]);
Assert.Equal("val1", subdata[1][0]);
Assert.Equal("val2", subdata[1][1]);
Assert.Equal("val3", subdata[2][0]);
Assert.Equal("val4", subdata[2][1]);
Assert.Equal("val5", subdata[3][0]);
Assert.Equal("val6", subdata[3][1]);
}
[Fact]
public void WillFilterFields()
{
Profiler.HideFields("filterThisField");
var result = tab.ParseJsonResult(@"{""key"":""data"",""filterThisField"":""data""}");
Assert.NotNull(result);
Assert.IsType<List<object[]>>(result);
var data = result as List<object[]>;
Assert.Equal(2, data.Count);
Assert.Equal("key", data[1][0]);
Assert.Equal("data", data[1][1]);
}
[Fact]
public void CanLoadCompleteDocument()
{
string json;
using (var reader = new StreamReader(typeof(JsonTests).Assembly.GetManifestResourceStream("Glimpse.RavenDb.Tests.ExampleJSON.txt")))
{
json = reader.ReadToEnd();
}
var result = tab.ParseJsonResult(json);
Assert.NotNull(result);
}
}
}
|
c1644254be1fcf5417cc55a44bfee268f90d1d97
|
C#
|
EmPCoder/CSharpPlayground
|
/Arrays/ForeachProgram.cs
| 3.953125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arrays
{
class ForeachProgram
{
//static void Main(string[] args)
//{
// int[] nums = new int[10];
// // 0 -> 0
// // 1 -> 1
// for(int i = 0; i < 10; i++)
// {
// nums[i] = i + 10;//denotes it for starting at 10
// }
// //for each int in j prints out its position as well as the value
// for(int j = 0; j < nums.Length; j++)
// {
// Console.WriteLine("Element {0} = {1}", j, nums[j]);
// }
// int counter = 0;
// // create variable called k and run through whole array
// foreach(int k in nums)
// {
// Console.WriteLine("Element {0} = {1}", counter, k); counter++;
// }
// // create an array with 5 of your best friends
// // create a foreach loop which greets all of them
// string[] names = { "Matt", "Becca", "Brandon", "Dylan", "Tiger" };
// foreach(string m in names)
// {
// Console.WriteLine("Hello {0} Good day aint it? ", m);
// }
// Console.ReadKey();
//}
}
}
|
21f82b6d646ac837951a78f9ef930ac84e6998c4
|
C#
|
RodrigoHBD/.NET-CORE-Plataforma-Omega
|
/MercadoLivreService/HttpClient/HttpClient.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace HttpClientLibrary
{
public class HttpClientLib
{
public static async Task<DataType> Get<DataType, ErrorType>(GetRequest req)
{
try
{
var response = await HttpRequester.GetAsync(req);
return ResponseHandler.HanldeResponse<DataType, ErrorType>(response);
}
catch (Exception e)
{
throw;
}
}
public static async Task<DataType> Post<DataType, ErrorType>(PostRequest req)
{
try
{
var response = await HttpRequester.PostAsync(req);
return ResponseHandler.HanldeResponse<DataType, ErrorType>(response);
}
catch (Exception e)
{
throw;
}
}
public static async Task Post(PostRequest req)
{
try
{
var response = await HttpRequester.PostAsync(req);
ResponseHandler.HanldeResponse(response);
}
catch (Exception e)
{
throw;
}
}
}
}
|
dd10ac309252cfcea4fa6a0748268cc20fd5a839
|
C#
|
Lxp5970/z3s
|
/ZZZS/XS/xs/Common/MD5Helper.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class MD5Helper
{
/// <summary>
/// MD5加密
/// </summary>
/// <param name="pToEncrypt"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string MD5Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
private static string key = "Z5h9A7o0";
/// <summary>
/// 对称加密解密的密钥
/// </summary>
public static string Key
{
get
{
return key;
}
set
{
key = value;
}
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="encryptString"></param>
/// <returns></returns>
public static string DesEncrypt(string encryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="decryptString"></param>
/// <returns></returns>
public static string DesDecrypt(string decryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
|
872031549f10ca47a48e7e0585d96796dd542f5c
|
C#
|
CatherinePD/OOP-labs
|
/Lab7/Lab7/Exceptions/NegativeArgumentException.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab7.Exceptions
{
public class NegativeArgumentException : ArgumentException
{
public NegativeArgumentException()
:base("Аргумент не может быть меньше нуля")
{
}
public NegativeArgumentException(string argumentName)
:base($"Аргумент {argumentName} не может быть меньше нуля")
{
}
}
}
|
11d733da970f54dd03a2330e0c8da093de4b1bdb
|
C#
|
bambom/URPACT
|
/Assets/ACT/Script/Action/Data/AnimSlot.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.ComponentModel;
namespace Data
{
[Serializable]
public class AnimSlot
{
const String ANIM_CATEGORY = "动画设置";
String mAnimation = "";
[XmlAttribute("Animation"), DisplayName("动画"), Description("动画的名字"), Category(ANIM_CATEGORY)]
public String Animation { get { return mAnimation; } set { mAnimation = value; } }
int mStart = 0;
[XmlAttribute("Start"), DisplayName("起始"), DefaultValue(0), Description("动画起始的在原动画的百分比"), Category(ANIM_CATEGORY)]
public int Start { get { return mStart; } set { mStart = value; } }
int mEnd = 100;
[XmlAttribute("End"), DisplayName("结束"), DefaultValue(100), Description("动画结束的在原动画的百分比"), Category(ANIM_CATEGORY)]
public int End { get { return mEnd; } set { mEnd = value; } }
int mWeight = 1;
[XmlAttribute("Weight"), DisplayName("权重"), DefaultValue(1), Description("动画的权重"), Category(ANIM_CATEGORY)]
public int Weight { get { return mWeight; } set { mWeight = value; } }
List<AnimControl> mAnimControlList = new List<AnimControl>();
public List<AnimControl> AnimControlList { get { return mAnimControlList; } set { mAnimControlList = value; } }
public void AddStartEnd()
{
AnimControl start_control = new AnimControl();
start_control.ActionTimeProportion = 0;
start_control.AnimTimeProportion = Start;
AnimControlList.Add(start_control);
AnimControl end_control = new AnimControl();
end_control.ActionTimeProportion = 100;
end_control.AnimTimeProportion = End;
AnimControlList.Add(end_control);
}
public bool IsFullAnim() { return mStart == 0 && mEnd == 100; }
public override string ToString()
{
return mAnimation + "[" + Weight + "]";
}
}
[Serializable]
public class AnimControl
{
const String ANIM_CONTROL_CATEGORY = "动画控制";
int mActionTimeProportion = 0;
[DisplayName("动作时间比例")]
[Description("动作时间比例")]
[Category(ANIM_CONTROL_CATEGORY)]
public int ActionTimeProportion { get { return mActionTimeProportion; } set { mActionTimeProportion = value; } }
int mAnimTimeProportion = 0;
[DisplayName("动画时间比例")]
[Description("动画时间比例")]
[Category(ANIM_CONTROL_CATEGORY)]
public int AnimTimeProportion { get { return mAnimTimeProportion; } set { mAnimTimeProportion = value; } }
public override string ToString()
{
return "动画控制";
}
}
}
|
1d2f7829865dcac2dcba087f5719b57f2c476028
|
C#
|
lyakyb/Reminderer
|
/Reminderer/Repositories/ScheduleRepository.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reminderer.Framework;
using Reminderer.Models;
namespace Reminderer.Repositories
{
public class ScheduleRepository : IScheduleRepository
{
private readonly IDatabaseManager _databaseManager;
public ScheduleRepository(IDatabaseManager databaseManager)
{
_databaseManager = databaseManager;
CreateSchedulesTable();
}
public void Add(Schedule schedule)
{
string s = $"INSERT INTO {Constants.SchedulesTable} (Description, ExtraDetail, DesiredDateTime, ShouldRemind, NumDaysBeforeNotify) VALUES (@descParam,@extParam,@ddtParam,@remindParam,@numDaysParam)";
var id = _databaseManager.InsertUpdateDeleteWithParamsGetLastInsertId(s, DictionaryRepresentationForSchedule(schedule));
schedule.Id = id;
}
public void Delete(Schedule schedule)
{
string s = $"DELETE FROM {Constants.SchedulesTable} WHERE Id=@idParam";
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("@idParam", schedule.Id);
var result = _databaseManager.InsertUpdateDeleteWithParams(s, dict);
if (result != 1)
{
//exception handling
}
}
public List<Schedule> ReadAll()
{
string s = $"SELECT * FROM {Constants.SchedulesTable}";
List<Schedule> schedules = new List<Schedule>();
var ds = _databaseManager.ReadData(s);
foreach (DataRow dr in ds.Tables[0].Rows)
{
Schedule schedule = ScheduleFromDataRow(dr);
schedules.Add(schedule);
}
return schedules;
}
public void Update(Schedule schedule)
{
string query = $"UPDATE {Constants.SchedulesTable} SET Description=@descParam, ExtraDetail=@extParam, DesiredDateTime=@ddtParam, ShouldRemind=@remindParam, NumDaysBeforeNotify=@numDaysParam WHERE id=@idParam";
var dict = DictionaryRepresentationForSchedule(schedule);
dict.Add("@idParam", schedule.Id);
var result = _databaseManager.InsertUpdateDeleteWithParams(query, dict);
if (result != 1)
{
}
}
private void CreateSchedulesTable()
{
string s = $"SELECT name FROM sqlite_master WHERE name='{Constants.SchedulesTable}'";
var result = _databaseManager.ExecuteScalarCommand(s);
if (result != null && string.Equals(result.ToString(), Constants.SchedulesTable))
{
Console.WriteLine("Table exists already");
return;
}
s = $"CREATE TABLE {Constants.SchedulesTable} (id INTEGER PRIMARY KEY AUTOINCREMENT, Description text, ExtraDetail text, DesiredDateTime text, ShouldRemind integer, NumDaysBeforeNotify int)";
_databaseManager.ExecuteNonQueryCommand(s);
}
private Dictionary<string, object> DictionaryRepresentationForSchedule(Schedule schedule)
{
schedule.ExtraDetail = schedule.ExtraDetail == null ? "-" : schedule.ExtraDetail;
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("@numDaysParam", schedule.NumDaysBeforeNotify);
dict.Add("@descParam", schedule.Description);
dict.Add("@extParam", schedule.ExtraDetail);
dict.Add("@ddtParam", schedule.DesiredDateTime.ToBinary());
dict.Add("@remindParam", schedule.ShouldRemind);
return dict;
}
private Schedule ScheduleFromDataRow(DataRow dr)
{
Schedule s = new Schedule();
s.Description = dr["Description"].ToString();
s.ExtraDetail = dr["ExtraDetail"].ToString();
s.DesiredDateTime = DateTime.FromBinary(long.Parse(dr["DesiredDateTime"].ToString()));
s.ShouldRemind = int.Parse(dr["ShouldRemind"].ToString()) != 0;
s.Id = int.Parse(dr["id"].ToString());
s.NumDaysBeforeNotify = int.Parse(dr["NumDaysBeforeNotify"].ToString());
return s;
}
}
}
|
460e56fe16d0e9ac43bd96ceb0f3e0710efcc643
|
C#
|
Pathoschild/smapi-mod-dump
|
/source/~Shockah/ProjectFluent/PublicAPI/IFluentApi.cs
| 2.59375
| 3
|
/*************************************************
**
** You're viewing a file in the SMAPI mod dump, which contains a copy of every open-source SMAPI mod
** for queries and analysis.
**
** This is *not* the original file, and not necessarily the latest version.
** Source repository: https://github.com/Shockah/Stardew-Valley-Mods
**
*************************************************/
using StardewModdingAPI;
using StardewValley;
using StardewValley.GameData;
using System;
using System.Collections.Generic;
namespace Shockah.ProjectFluent
{
/// <summary>The Project Fluent API which other mods can access.</summary>
public interface IFluentApi
{
#region Locale
/// <summary>The default locale of the game (en-US).</summary>
IGameLocale DefaultLocale { get; }
/// <summary>The current locale of the game.</summary>
IGameLocale CurrentLocale { get; }
/// <summary>All of the currently known locales.</summary>
IEnumerable<IGameLocale> AllKnownLocales { get; }
/// <summary>Get a locale built into the vanilla game.</summary>
/// <remarks>The <see cref="LocalizedContentManager.LanguageCode.mod"/> is not a valid argument for this method, as it is not a real language code.</remarks>
/// <param name="languageCode">A built-in locale language code.</param>
IGameLocale GetBuiltInLocale(LocalizedContentManager.LanguageCode languageCode);
/// <summary>Get a locale provided by a mod.</summary>
/// <param name="language">A mod-provided language.</param>
IGameLocale GetModLocale(ModLanguage language);
#endregion
#region Localizations
/// <summary>Get an <see cref="IFluent{}"/> instance that allows retrieving Project Fluent translations for a specific locale.</summary>
/// <param name="locale">A locale for which to retrieve the translations.</param>
/// <param name="mod">The mod for which to retrieve the translations.</param>
/// <param name="file">An optional file name to retrieve the translations from.</param>
IFluent<string> GetLocalizations(IGameLocale locale, IManifest mod, string? file = null);
/// <summary>Get an <see cref="IFluent{}"/> instance that allows retrieving Project Fluent translations for the current locale.</summary>
/// <remarks>The returned instance's locale will change automatically if the <see cref="CurrentLocale"/> changes.</remarks>
/// <param name="mod">The mod for which to retrieve the translations.</param>
/// <param name="file">An optional file name to retrieve the translations from.</param>
IFluent<string> GetLocalizationsForCurrentLocale(IManifest mod, string? file = null);
#endregion
#region Specialized types
/// <summary>Get a specialized <see cref="IEnumFluent{}"/> instance that allows retrieving Project Fluent translations for an <see cref="Enum"/> type.</summary>
/// <typeparam name="EnumType">The <see cref="Enum"/> type to retrieve translations for.</typeparam>
/// <param name="baseFluent">The underlying <see cref="IFluent{}"/> instance.</param>
/// <param name="keyPrefix">The prefix all of the <see cref="Enum"/> values are prefixed with.</param>
IEnumFluent<EnumType> GetEnumFluent<EnumType>(IFluent<string> baseFluent, string keyPrefix) where EnumType : struct, Enum;
/// <summary>Get a specialized <see cref="IFluent{}"/> instance that allows retrieving Project Fluent translations for values of a given generic type Input.</summary>
/// <typeparam name="T">The type to retrieve translations for.</typeparam>
/// <param name="baseFluent">The underlying <see cref="IFluent{}"/> instance.</param>
/// <param name="mapper">The (Input -> Output) mapper.</param>
IFluent<Input> GetMappingFluent<Input, Output>(IFluent<Output> baseFluent, Func<Input, Output> mapper);
#endregion
#region Custom Fluent functions
/// <summary>Create a <see cref="string"/> value usable with Project Fluent functions.</summary>
/// <param name="value">The <see cref="string"/> value.</param>
IFluentFunctionValue CreateStringValue(string value);
/// <summary>Create a <see cref="int"/> value usable with Project Fluent functions.</summary>
/// <param name="value">The <see cref="int"/> value.</param>
IFluentFunctionValue CreateIntValue(int value);
/// <summary>Create a <see cref="long"/> value usable with Project Fluent functions.</summary>
/// <param name="value">The <see cref="long"/> value.</param>
IFluentFunctionValue CreateLongValue(long value);
/// <summary>Create a <see cref="float"/> value usable with Project Fluent functions.</summary>
/// <param name="value">The <see cref="float"/> value.</param>
IFluentFunctionValue CreateFloatValue(float value);
/// <summary>Create a <see cref="double"/> value usable with Project Fluent functions.</summary>
/// <param name="value">The <see cref="double"/> value.</param>
IFluentFunctionValue CreateDoubleValue(double value);
/// <summary>Register a new function for the Project Fluent translations.</summary>
/// <remarks>
/// The registered function will be available by the translations in the form of:
/// <list type="bullet">
/// <item><c>CAPITALIZED_UNDERSCORED_MOD_ID_AND_THEN_THE_FUNCTION_NAME</c> in all contexts</item>
/// <item><c>FUNCTION_NAME</c> in the <paramref name="mod"/> context.</item>
/// </list>
/// </remarks>
/// <param name="mod">The mod you want to register the function for. Keep in mind other mods can also access the function, if they provide the fully qualified name.</param>
/// <param name="name">The name of the function.<br/>Fluent function names can only contain uppercase letters, digits, and the <c>_</c> and <c>-</c> characters. They must also start with an uppercase letter.</param>
/// <param name="function">The function to register.</param>
void RegisterFunction(IManifest mod, string name, FluentFunction function);
/// <summary>Unregister a Project Fluent translation function.</summary>
/// <param name="mod">The mod you want to unregister the function for.</param>
/// <param name="name">The name of the function.<br/>Fluent function names can only contain uppercase letters, digits, and the <c>_</c> and <c>-</c> characters. They must also start with an uppercase letter.</param>
void UnregisterFunction(IManifest mod, string name);
#endregion
}
}
|
67160fcd386560acfd5319fd5fff5baf4702e0a8
|
C#
|
ArturoMora/SIGCOFOO
|
/INEEL.DataAccess.GEN/Repositories/CH/DetalleEvaluacionConductualesRepository.cs
| 2.640625
| 3
|
using INEEL.DataAccess.GEN.Contexts;
using INEEL.DataAccess.GEN.Models.CH;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace INEEL.DataAccess.GEN.Repositories.CH
{
public class DetalleEvaluacionConductualesRepository : IDisposable
{
//----------- AYUDA:
// DetalleConductualesRepository: nombre de clase (y tipicamente el constructor)
// FooDbContext.- tu Contexto : DbContext
// FooEntity.- es el modelo
// FooDbSet.- es el nombre de la variable tipo DbSet en el DbContext (
// ejemplo: public virtual DbSet<Category> Categories { get; set; }
// :: FooDbSet =Categories )
// FooID.- es el ID del modelo (ID de la tabla)
private SIGCOCHContext _db;
public DetalleEvaluacionConductualesRepository()
{
_db = new SIGCOCHContext();
}
//public async Task<IEnumerable<FooEntity>> OtrosMetodos(){ ... }
public async Task<IEnumerable<DetalleEvaluacionCompetenciasConductuales>> GetAll()
{
try
{
var entities = await _db.detalleConductuales.AsNoTracking().ToListAsync();
return entities;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task<IEnumerable<DetalleEvaluacionCompetenciasConductuales>> GetByClaveEvaluacion(int clave)
{
try
{
var entities = await _db.detalleConductuales
.Where( e => e.claveEvaluacion == clave)
.Include(e => e.matriz)
.Include(e => e.matriz.competencia)
.Include(e => e.matriz.descnivel)
.Include(e => e.matriz.descnivel.nivel)
.AsNoTracking().ToListAsync();
return entities;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task<IEnumerable<AuxilarDatosConductuales>> GetByClaveEvaluacionResultado(int clave)
{
try
{
List<AuxilarDatosConductuales> listaCompetencias = new List<AuxilarDatosConductuales>();
var entities = await _db.detalleConductuales
.Where(e => e.claveEvaluacion == clave)
.Include(e => e.matriz)
.Include(e => e.matriz.competencia)
.Include(e => e.matriz.descnivel)
.Include(e => e.matriz.descnivel.nivel)
.AsNoTracking().ToListAsync();
foreach (var item in entities)
{
AuxilarDatosConductuales datos = new AuxilarDatosConductuales();
datos.claveEvaluacion = item.claveEvaluacion;
datos.competencia = item.matriz.competencia.Competencia;
datos.comportamiento = item.matriz.descnivel.Comportamiento;
datos.justificacion = item.justificacion;
datos.MatrizId = item.MatrizId;
datos.nivel = item.matriz.descnivel.nivel.Descripcion;
datos.valorReal = item.valorReal;
listaCompetencias.Add(datos);
}
return listaCompetencias;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task<DetalleEvaluacionCompetenciasConductuales> Get(int id)
{
try
{
var entities = await _db.detalleConductuales.AsNoTracking()
// .Include(x=> x.FK)
.FirstOrDefaultAsync(e => e.DetalleId == id);
return entities;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task<DetalleEvaluacionCompetenciasConductuales> GetByMatriz(int id)
{
try
{
var entities = await _db.detalleConductuales.AsNoTracking()
// .Include(x=> x.FK)
.FirstOrDefaultAsync(e => e.MatrizId == id);
return entities;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task<DetalleEvaluacionCompetenciasConductuales> GetByMatrizEvaluacion(BusquedaNivel param)
{
try
{
var entities = await _db.detalleConductuales.AsNoTracking()
// .Include(x=> x.FK)
.FirstOrDefaultAsync(e => e.MatrizId == param.matrizId && e.claveEvaluacion == param.claveEvaluacion);
return entities;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task Create(DetalleEvaluacionCompetenciasConductuales model)
{
try
{
var entities = await _db.detalleConductuales
.FirstOrDefaultAsync(e => e.MatrizId == model.MatrizId && e.claveEvaluacion == model.claveEvaluacion);
if (entities != null)
{
model.DetalleId = entities.DetalleId;
_db.Entry(entities).CurrentValues.SetValues(model);
await _db.SaveChangesAsync();
}
else
{
_db.detalleConductuales.Add(model);
await _db.SaveChangesAsync();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task Update(DetalleEvaluacionCompetenciasConductuales model)
{
try
{
var _model = await _db.detalleConductuales.FirstOrDefaultAsync(e => e.DetalleId == model.DetalleId);
if (_model != null)
{
_db.Entry(_model).CurrentValues.SetValues(model);
await _db.SaveChangesAsync();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public async Task Delete(int id)
{
try
{
var _model = await _db.detalleConductuales.FirstOrDefaultAsync(e => e.DetalleId == id);
if (_model != null)
{
_db.detalleConductuales.Remove(_model);
await _db.SaveChangesAsync();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public void Dispose()
{
_db.Dispose(); //ayudar al recolector de basura
}
}
}
|
8b5d67f7f969ac98d78889ab1c083b3fce7840e8
|
C#
|
slimi00/statbus
|
/src/nscreg.Server.Common/Models/DataSources/DataSourceVm.cs
| 2.5625
| 3
|
using System.Collections.Generic;
using nscreg.Data.Entities;
namespace nscreg.Server.Common.Models.DataSources
{
/// <summary>
/// View data source model
/// </summary>
public class DataSourceVm
{
private DataSourceVm(DataSource item)
{
Id = item.Id;
Name = item.Name;
Description = item.Description;
Priority = (int) item.Priority;
AllowedOperations = (int) item.AllowedOperations;
AttributesToCheck = item.AttributesToCheckArray;
StatUnitType = (int) item.StatUnitType;
Restrictions = item.Restrictions;
VariablesMapping = item.VariablesMapping;
CsvDelimiter = item.CsvDelimiter;
OriginalCsvAttributes = item.OriginalAttributesArray;
CsvSkipCount = item.CsvSkipCount;
}
/// <summary>
/// Method for creating a view of a data source model
/// </summary>
/// <param name="item">item</param>
/// <returns></returns>
public static DataSourceVm Create(DataSource item) => new DataSourceVm(item);
public int Id { get; }
public string Name { get; }
public string Description { get; }
public int Priority { get; }
public int AllowedOperations { get; }
public IEnumerable<string> AttributesToCheck { get; }
public IEnumerable<string> OriginalCsvAttributes { get; }
public int StatUnitType { get; set; }
public string Restrictions { get; }
public string VariablesMapping { get; }
public string CsvDelimiter { get; }
public int CsvSkipCount { get; }
}
}
|
c636e638e585e9fa78e2ac89d33bfff062d83a11
|
C#
|
zhangsai521314/StudyLog4net
|
/StudyLog4net/Program.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
namespace StudyLog4net_File
{
/// <summary>
/// 此App.config是按日期分割日志,一天记录是一个文件
/// </summary>
class Program
{
static void Main(string[] args)
{
try
{
for (int i = 0; i < 2; i++)
{
Log4net.Info("sss", "StudyLog4net");
}
DataTable tb = new DataTable();
DataRow ro = tb.Rows[0];
}
catch (Exception ex)
{
Log4net.Error(MethodBase.GetCurrentMethod(), ex, "");
//Log4net.Error(MethodBase.GetCurrentMethod(), ex, "ConsoleAppender");
}
Console.ReadKey();
}
}
}
|
9dfcc2a187ac8d4db79e9fa1097f3297c3fa43b5
|
C#
|
savras/other-coding-problems
|
/leetcode/Easy/575. DistributeCandies.cs
| 3.421875
| 3
|
public class Solution {
public int DistributeCandies(int[] candies) {
var len = candies.Length;
var half = len / 2;
var hs = new HashSet<int>();
for(var i = 0; i < len; i++) {
if(!hs.Contains(candies[i])){
hs.Add(candies[i]);
}
if(hs.Count >= half) {
break;
}
}
var result = Math.Min(half, hs.Count);
return result;
}
}
|
e1d461e9b0df379a7255aa594951ca1542e6fe8e
|
C#
|
IvayloNikolov36/UrbanSolution
|
/UrbanSolution.Data/MigrationHelpers/ProcedureHelpers.cs
| 2.59375
| 3
|
namespace UrbanSolution.Data.MigrationHelpers
{
using Microsoft.EntityFrameworkCore.Migrations;
public static class ProcedureHelpers
{
public static void CreateAssignUserToRoleProcedure(MigrationBuilder builder)
{
builder
.Sql(@"CREATE PROC [dbo].AssignUserToRole @userId NVARCHAR(450), @role NVARCHAR(256)
AS
BEGIN
DECLARE @roleId NVARCHAR(450) = (SELECT Id FROM [dbo].[AspNetRoles] WHERE [Name] = @role);
IF @roleId IS NULL
BEGIN
RAISERROR('Invalid role name!', 16, 1);
RETURN
END
DECLARE @usersCount INT = (SELECT COUNT(*) FROM [dbo].[AspNetUsers] WHERE [Id] = @userId);
IF @usersCount <> 1
BEGIN
RAISERROR('Invalid user id', 16, 2);
RETURN
END
DECLARE @userRoleCount INT = (SELECT COUNT(*) FROM [dbo].[AspNetUserRoles] AS ur
WHERE ur.UserId = @userId AND ur.RoleId = @roleId);
IF @userRoleCount > 0
BEGIN
RAISERROR('User is already assigned to this role', 16, 3);
RETURN
END
INSERT INTO [dbo].[AspNetUserRoles] (UserId, RoleId)
VALUES (@userId, @roleId)
END");
}
public static void DropAssignUserToRoleProcedure(MigrationBuilder builder)
{
builder.Sql("DROP PROC [dbo].AssignUserToRole");
}
public static void CreateRemoveUserRoleProcedure(MigrationBuilder builder)
{
builder
.Sql(@"CREATE PROC [dbo].RemoveUserRole @userId NVARCHAR(450), @role NVARCHAR(256)
AS
BEGIN
DECLARE @roleId NVARCHAR(450) = (SELECT Id FROM [dbo].[AspNetRoles] WHERE [Name] = @role);
IF @roleId IS NULL
BEGIN
RAISERROR('Invalid role name!', 16, 1);
RETURN
END
DECLARE @usersCount INT = (SELECT COUNT(*) FROM [dbo].[AspNetUsers] WHERE [Id] = @userId);
IF @usersCount <> 1
BEGIN
RAISERROR('Invalid user id', 16, 2);
RETURN
END
DECLARE @userRoleCount INT = (SELECT COUNT(*) FROM [dbo].[AspNetUserRoles] AS ur
WHERE ur.UserId = @userId AND ur.RoleId = @roleId);
IF @userRoleCount = 0 --user is not in this role
BEGIN
RAISERROR('Can not remove user from role!', 16, 3);
RETURN
END
DELETE [dbo].[AspNetUserRoles] WHERE UserId = @userId AND RoleId = @roleId;
END");
}
public static void DropRemoveUserRoleProcedure(MigrationBuilder builder)
{
builder.Sql("DROP PROC [dbo].RemoveUserRole");
}
}
}
|
aeab0fc99d5d354b17bfd95c7e24a1c233f71b2d
|
C#
|
nebtrx/hypertimer
|
/HyperTimerTest/Program.cs
| 3.15625
| 3
|
using System;
using System.Threading;
using System.Timers;
using System.Timers.Providers;
namespace HyperTimerTest
{
class Program
{
private static TimeSpan _total;
static void Main(string[] args)
{
HyperTimer
.Configure()
.UseTimerServicesProvider(new DefaultTimerServicesProvider());
Console.WriteLine("Running hypertimer with an interval of 1 sec for over 15 cycles");
Console.WriteLine("Then waits 5 sec(while timer keep running), throttles 3 sec," );
Console.WriteLine("displays some info, and continues until end.\n");
var timer = HyperTimer.StartNew(1000, timer_Elapsed, timer_Stopped)
.StopIn(15)
.Wait(5000);
timer.Throttle(3000);
//timer.Delay(1000);
Console.WriteLine(" Progress Until last Cycle: {0}", timer.TotalElapsedUntilLastCycle);
Console.WriteLine(" Total Elapsed Progress: {0}", timer.TotalElapsed);
Console.ReadLine();
Console.WriteLine("Total: {0}", _total);
timer.Dispose();
}
static void timer_Elapsed(IHyperTimer sender, DetailedElapseEventArgs args)
{
Console.WriteLine("Cycles Completed:{0}, Cycles Left: {1} TE: {2} Prog: {3}", args.CyclesCompleted, args.CyclesLeft, args.TotalElapsed, args.Elapsed);
_total += args.Elapsed;
}
static void timer_Stopped(object sender, EventArgs args)
{
Console.WriteLine("Stopped");
}
}
}
|
c4a51e6da82491a4d7bef417645baf88e7329248
|
C#
|
neehouse/IISLogAnalyzerSiteExtension
|
/WebAnalytics/Models/Metrics/MetricParameter.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebAnalytics.Model.Metrics
{
public struct MetricParameter
{
//Interesting. The jsonConvert needs these variables to be public to serialize them successfully, if they are private it cannot access them
//name of the parameter that our consumers should used to assosciate a value with
public string Name { get; set; }
//A description of this parameter so that consumers have better context about what their usings
public string Description { get; set; }
//Default value for parameter
public string Value { get; set; }
public MetricParameter(string name, string description, string defaultValue):this()
{
Name = name;
Description = description;
Value = defaultValue;
}
}
}
|
8cc003c940e6a8560b1bfe7fc942d5d9924d5c9d
|
C#
|
JonaJ23/WPF-projekt
|
/Store/RegisterWIndow.xaml.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DatabaseConnection;
namespace Store
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Submit_Click(object sender, RoutedEventArgs e)
{
//Lägger till ny användare samt hänvisar tillbaka till LoginWindow.
using (var ctx = new Context())
{
if (FirstName.Text.Length == 0)
{
MessageBox.Show("Please enter your first name.");
}
else if (UserName.Text.Length == 0)
{
MessageBox.Show("Please enter a username.");
}
else if (PasswordField.Password.Length == 0)
{
MessageBox.Show("Please enter a password.");
}
else if (Email.Text.Length == 0)
{
MessageBox.Show("Please enter an e-mailadress.");
}
else
{
State.User = API.GetCustomerByName(Email.Text);
if (State.User != null)
{
MessageBox.Show("Username already taken.");
UserName.Clear();
}
else
{
ctx.Customers.Add(new Customer { Name = FirstName.Text, UserName = UserName.Text, Password = PasswordField.Password, Email = Email.Text });
ctx.SaveChanges();
MessageBox.Show("You've made an account!");
var next_window = new LoginWindow();
next_window.Show();
this.Close();
}
}
}
}
// Hänvisar tillbaka till LoginWindow
private void Cancel_Click(object sender, RoutedEventArgs e)
{
var next_windowTwo = new LoginWindow();
next_windowTwo.Show();
this.Close();
}
}
}
|
f914a0dd7d32089b4f2444cab9a503cbf189dc8d
|
C#
|
junyong-tsui/csharpexamples
|
/src/IISServer/MyAspxPage.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IISServer
{
/// <summary>
/// 我的aspx页面
/// </summary>
public class MyAspxPage:IHttpHandler
{
/// <summary>
///
/// </summary>
/// <param name="httpcontext"></param>
public void ProcessRequest(HttpContext httpcontext)
{
string htm = string.Format(@"<html><head><title>我的第一个处理程序</title></head><body><h1>{0}</h1></body></html>",DateTime.Now.ToString());
httpcontext.HttpResponse.StateCode = "200";
httpcontext.HttpResponse.StateDescription = "OK";
httpcontext.HttpResponse.Body = Encoding.UTF8.GetBytes(htm);
}
}
}
|
257ec4ae457ca73324edc3ae5f1cb4bdd65bcb19
|
C#
|
jayscope/GameWork.Core
|
/GameWork.Core.States/Event/EventStateTransition.cs
| 3.109375
| 3
|
using System;
namespace GameWork.Core.States.Event
{
public abstract class EventStateTransition
{
internal event Action<string, object> EnterStateEvent;
internal event Action<string> ExitStateEvent;
/// <summary>
/// Called when the transition is being Entered.
/// Override and add your logic here.
/// </summary>
/// <param name="fromStateName"></param>
/// <param name="arg"></param>
protected virtual void OnEnter(string fromStateName, object arg)
{
}
/// <summary>
/// Called when the transition is being Exited.
/// Override and add your logic here.
/// </summary>
/// <param name="toStateName"></param>
protected virtual void OnExit(string toStateName)
{
}
/// <summary>
/// Call this to initiate state change.
/// </summary>
/// <param name="toStateName"></param>
/// <param name="arg"></param>
protected virtual void EnterState(string toStateName, object arg = null)
{
EnterStateEvent?.Invoke(toStateName, arg);
}
/// <summary>
/// Call this to complete state change.
/// </summary>
/// <param name="toStateName"></param>
protected virtual void ExitState(string toStateName)
{
ExitStateEvent?.Invoke(toStateName);
}
internal virtual void Enter(string fromStateName, object arg)
{
OnEnter(fromStateName, arg);
}
internal virtual void Exit(string toStateName)
{
OnExit(toStateName);
}
}
}
|
4cb7cc70440f6ab33e024b5e68fc4555e04c24dc
|
C#
|
Killercodes/nExtensions
|
/Object/ObjectBase.cs
| 3.234375
| 3
|
public class ObjectBase
{
/*
Person p = new Person();
p["FirstName"] = "addressline2";
p["AddressLine1"] = "bangalore";
p["AddressLine2"].dump();
*/
private void Set(string propname,object value)
{
if(this.GetType().GetProperties().Where(_ => _.Name == propname).Any())
{
var prop = this.GetType().GetProperties().Where(_ => _.Name == propname).First();
prop.SetValue(this, value, null);
}
else if(this.GetType().GetFields().Where(_ => _.Name == propname).Any())
{
var field = this.GetType().GetFields().Where(_ => _.Name == propname).First();
field.SetValue(this,value);
}
}
private object Get(string propname)
{
if(this.GetType().GetProperties().Where(_ => _.Name == propname).Any())
{
var prop = this.GetType().GetProperties().Where(_ => _.Name == propname).First();
return prop.GetValue(this);
}
else if(this.GetType().GetFields().Where(_ => _.Name == propname).Any())
{
var field = this.GetType().GetFields().Where(_ => _.Name == propname).First();
return field.GetValue(this);
}
return null;
}
public object this[string name]
{
set { Set(name,value); }
get { return Get(name); }
}
}
|
67ad5528cabf089238c364091cd66c3b72a1484f
|
C#
|
AlexanderSilvaB/BT-Designer
|
/Behavior Tree Designer/ParallelNode.cs
| 2.546875
| 3
|
using Behavior_Tree_Designer.Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Behavior_Tree_Designer
{
[Serializable]
public class ParallelNode : Node
{
public ParallelNode() : base(NodeType.Composite)
{
Icon = Resources.iconfinder_arrow_7_393270;
Tag = "Parallel";
Text = "Parallel";
}
public override bool Run(NodeStatus status)
{
Status = NodeStatus.Success;
if (status == NodeStatus.None)
Status = NodeStatus.None;
NodeStatus forced = status;
NodeStatus[] all = new NodeStatus[Nodes.Count];
for (int i = 0; i < Nodes.Count; i++)
{
Nodes[i].Run(forced);
all[i] = Nodes[i].Status;
if (forced == NodeStatus.Unknown && Nodes[i].Status == NodeStatus.Running)
{
Status = NodeStatus.Running;
}
else if (forced == NodeStatus.Unknown && Nodes[i].Status == NodeStatus.Failure)
{
Status = NodeStatus.Failure;
}
}
return true;
}
}
}
|
0140b03b25d51c20db416bf43fb2c7bd8b839a09
|
C#
|
fadi426/ProfileApplicationAPI
|
/ProfileApplication/ProfileApplication/Models/Scraper/ImgScraper.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
namespace ProfileApplication.Helpers.Scraper
{
public class ImgScraper : Scraper
{
public ImgScraper(string url, string className)
{
this.Url = url;
this.ClassName = className;
}
public override List<string> Scrape()
{
List<string> result = new List<string>();
try
{
//Get the content of the URL from the Web
var web = new HtmlWeb();
var doc = web.Load(Url);
//Filter the content
doc.DocumentNode.Descendants()
.Where(n => n.Name == "script")
.ToList()
.ForEach(n => n.Remove());
var nodes = doc.DocumentNode.SelectNodes($"//*[@class='{ClassName}']");
List<string> srcs = new List<string>();
//Scrape the img src from the element
foreach (var node in nodes)
{
srcs.Add(node.SelectSingleNode("img").GetAttributeValue("src",""));
}
result = srcs;
}
catch
{
Console.WriteLine("Something went wrong during the scraping process");
}
return result;
}
}
}
|
abc26ccd9719262926db2401ec6a06eeadc03d5d
|
C#
|
zhenyaracheva/TelerikAcademy
|
/OOP/Homeworks/DefiningClassesPart1/GSMTaskMain/Call.cs
| 3.4375
| 3
|
namespace GSMTaskMain
{
using System;
using System.Text;
public class Call
{
private DateTime dateTimeCall;
private Contact dialedPhoneNumber;
private double duration;
public Call(DateTime currentDateTime, Contact currentContact, double currentDuration)
{
this.dateTimeCall = currentDateTime;
this.dialedPhoneNumber = currentContact;
this.duration = currentDuration;
}
public DateTime DateTimeCall
{
get
{
return this.dateTimeCall;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Date cannot be null!");
}
this.dateTimeCall = value;
}
}
public Contact DialedPhoneNumber
{
get
{
return this.dialedPhoneNumber;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Dailded number cannot be null!");
}
this.dialedPhoneNumber = value;
}
}
public double Duration
{
get
{
return this.duration;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("Phone duration cannot be smaller than 0!");
}
this.duration = value;
}
}
public override string ToString()
{
var result = new StringBuilder();
result.AppendLine(this.DateTimeCall.ToString());
result.AppendLine(string.Format("Name: {0}", this.DialedPhoneNumber.Name));
result.AppendLine(string.Format("Phone number: {0}", this.DialedPhoneNumber.Number));
result.Append(string.Format("Duration: {0}", this.Duration.ToString()));
return result.ToString();
}
}
}
|
15375d7a592c262b0030df80dfdcb92834e85dcc
|
C#
|
LaurenDeveloper/SharedKernel
|
/src/Infrastructure/Caching/DistributedCacheHelper.cs
| 2.5625
| 3
|
using Microsoft.Extensions.Caching.Distributed;
using SharedKernel.Application.Caching;
using SharedKernel.Application.Serializers;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SharedKernel.Infrastructure.Caching
{
internal class DistributedCacheHelper : ICacheHelper
{
private readonly IDistributedCache _distributedCache;
private readonly IBinarySerializer _binarySerializer;
private static readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1, 1);
public DistributedCacheHelper(
IDistributedCache distributedCache,
IBinarySerializer binarySerializer)
{
_distributedCache = distributedCache;
_binarySerializer = binarySerializer;
}
public async Task SetAsync<T>(string key, T value, TimeSpan? timeSpan = null)
{
try
{
await Semaphore.WaitAsync();
await _distributedCache.SetAsync(key, _binarySerializer.Serialize(value),
new DistributedCacheEntryOptions());
}
finally
{
Semaphore.Release();
}
}
public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> generator, TimeSpan? timeSpan = null)
{
try
{
await Semaphore.WaitAsync();
var value = await _distributedCache.GetAsync(key);
if (value != default && value.Length != 0)
return _binarySerializer.Deserialize<T>(value);
var valueToCache = await generator();
await _distributedCache.SetAsync(key, _binarySerializer.Serialize(valueToCache),
new DistributedCacheEntryOptions());
return valueToCache;
}
finally
{
Semaphore.Release();
}
}
public void Remove(string key)
{
_distributedCache.Remove(key);
}
}
}
|
8a32268af66da4bb6e07417e988cce71f6cd5fc5
|
C#
|
dmitrynovik/Boggle
|
/MORF.Solution/ArrayExtensions.cs
| 3.3125
| 3
|
using System;
using System.Linq;
namespace MORF.Solution
{
public static class ArrayExtensions
{
public static int[] GetMostCommonElements(this int[] array)
{
if (array == null) throw new ArgumentNullException("array");
var countedElements = array.GroupBy(a => a).Select(g => new { Count = g.Count(), Element = g.Key });
if (countedElements.Any())
{
return countedElements.Where(g => g.Count == countedElements.Max(c => c.Count))
.Select(g => g.Element)
.ToArray();
}
return new int[0];
}
}
}
|
480b930069b8ff2e9f8d65a7b2bbc12904958372
|
C#
|
jmbillings/KataGameOfLife
|
/GameOfLifeKata/StringGameOutput.cs
| 3.125
| 3
|
using System;
using System.Text;
namespace GameOfLifeKata
{
public class StringGameOutput : IGameOutput
{
public string OutputGameGrid(bool[,] gameGrid)
{
var gridStringBuilder = new StringBuilder();
for (var rowIndex = 0; rowIndex < gameGrid.GetLength(0); rowIndex++)
{
var rowStringBuilder = new StringBuilder();
for (var colIndex = 0; colIndex < gameGrid.GetLength(1); colIndex++)
{
rowStringBuilder.Append(gameGrid[rowIndex, colIndex] ? '*' : '.');
}
gridStringBuilder.Append(rowStringBuilder.Append('\n'));
}
return (gridStringBuilder.ToString());
}
}
}
|
a7879fb3effc50b937fab0b81ce074190f24e9bf
|
C#
|
Greevis/WebroomsSyncApp
|
/RhsSync/clsRhsGuest.cs
| 2.828125
| 3
|
using System;
using System.IO;
using System.Text;
namespace RhsSync
{
/// <summary>
/// Summary description for clsRhsGuest.
/// </summary>
public class clsRhsGuest : clsBase
{
/// <summary>
/// Initialiser
/// </summary>
public clsRhsGuest()
{
}
#region Publicly Exposed Variables
// public struct rhsGuest
// {
/// <summary>
/// Name of Guest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 0 - 27
/// </description>
/// <description>
/// 28
/// </description></item></list></summary>
public string GuestName;
/// <summary>
/// Whether the Guest is In House at the moment or Not (Y or N)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 28
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string GuestInHouse;
/// <summary>
/// Guest's favoured room, if they have one
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 29 - 30
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short GuestRoom;
/// <summary>
/// Number of Adults staying
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 31
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string Adult;
/// <summary>
/// Number of Children staying
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 32
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string Child;
/// <summary>
/// First Address Field
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 33 - 57
/// </description>
/// <description>
/// 25
/// </description></item></list></summary>
public string Address1;
/// <summary>
/// Second Address Field
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 33 - 57
/// </description>
/// <description>
/// 25
/// </description></item></list></summary>
public string Address2; // Pos: 58 - 82 Length: 25
/// <summary>
/// Third Address Field
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 83 - 107
/// </description>
/// <description>
/// 25
/// </description></item></list></summary>
public string Address3;
/// <summary>
/// Fourth Address Field
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 108 - 132
/// </description>
/// <description>
/// 25
/// </description></item></list></summary>
public string Address4;
/// <summary>
/// Car registration number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 133 - 138
/// </description>
/// <description>
/// 6
/// </description></item></list></summary>
public string Rego;
/// <summary>
/// Contact Phone Number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 139 - 148
/// </description>
/// <description>
/// 10
/// </description></item></list></summary>
public string Phone;
/// <summary>
/// Class of Guest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 149 - 150
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short GuestClass;
/// <summary>
/// Rate that this Guest Pays (Basic type: Currency)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 151 - 158
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public double GuestRate;
/// <summary>
/// Number of the Nights the Guest is staying for this reservation
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 159 - 160
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Nights;
/// <summary>
/// First Night of Guest Booking (Basic type: rhsDate)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 161 - 166
/// </description>
/// <description>
/// 6
/// </description></item></list></summary>
public rhsDate DateIn;
/// <summary>
/// Comments added by the Guest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 167 - 195
/// </description>
/// <description>
/// 29
/// </description></item></list></summary>
public string Comment;
/// <summary>
/// Name of the Voucher, should the guest have one
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 196 - 215
/// </description>
/// <description>
/// 20
/// </description></item></list></summary>
public string Voucher;
/// <summary>
/// If the Guest is a regular.
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 216 - 217
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Regular;
/// <summary>
/// A reference to extra data regarding this Guest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 218 - 219
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short ExtRec;
/// <summary>
/// Reference to a Note file added by the Proprietor (0 = No notes)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 220 - 221
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Notes;
/// <summary>
/// Member Number (for Frequent Reward programmes)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 222 - 223
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short MemberNo;
/// <summary>
/// Number of Associated Group (0 = no group)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 224 - 225
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Group;
/// <summary>
/// Transaction Record (of base type rhsAccount)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 226 - 329
/// </description>
/// <description>
/// 104
/// </description></item></list></summary>
public rhsAccount[] Trans;
/// <summary>
/// Name of Contact
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 330 - 358
/// </description>
/// <description>
/// 29
/// </description></item></list></summary>
public string Contact;
/// <summary>
/// Contact Mobile Phone Number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 359 - 372
/// </description>
/// <description>
/// 14
/// </description></item></list></summary>
public string Mobile;
/// <summary>
/// Unallocated Member
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 373 - 381
/// </description>
/// <description>
/// 9
/// </description></item></list></summary>
public string Spare;
/// <summary>
/// Number of Guest's Company, if any
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 382 - 383
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Company;
/// <summary>
/// Comments Regarding Arrival (e.g. associated travel arrangement)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 384 - 400
/// </description>
/// <description>
/// 17
/// </description></item></list></summary>
public string ArrivalDesc;
/// <summary>
/// Comments Regarding Departure (e.g. associated travel arrangement)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 401 - 417
/// </description>
/// <description>
/// 17
/// </description></item></list></summary>
public string DepartDesc;
/// <summary>
/// Where this guest came from
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 418 - 419
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Origin;
/// <summary>
/// Whether this Guest is GST Exclusive
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 420 - 421
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short GSTExcl;
/// <summary>
/// Reference to how the Guest found the establishment
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 422 - 423
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short Source;
/// <summary>
/// Credit Card Number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 424 - 443
/// </description>
/// <description>
/// 20
/// </description></item></list></summary>
public string CreditCard;
/// <summary>
/// Credit Card Expiry Date
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 444 - 448
/// </description>
/// <description>
/// 5
/// </description></item></list></summary>
public string ExpiryDate;
/// <summary>
/// Contact Fax Number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 449 - 458
/// </description>
/// <description>
/// 10
/// </description></item></list></summary>
public string FaxNumber;
/// <summary>
/// Comments added by the user
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 459 - 487
/// </description>
/// <description>
/// 29
/// </description></item></list></summary>
public string UserComment;
/// <summary>
/// If this Guest has left or not
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 488
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string Departed;
/// <summary>
/// Guest's time of Departure
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 489 - 493
/// </description>
/// <description>
/// 5
/// </description></item></list></summary>
public string DepartTime;
/// <summary>
/// Contact Phone Number Prefix
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 494 - 497
/// </description>
/// <description>
/// 4
/// </description></item></list></summary>
public string PhonePrefix;
/// <summary>
/// Contact Fax Number Prefix
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 498 - 501
/// </description>
/// <description>
/// 4
/// </description></item></list></summary>
public string FaxPrefix;
/// <summary>
/// 'RegularNum', ignored
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 502 - 509
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public string RegularNum;
/// <summary>
/// Type of Invoice
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 510
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string InvoiceType;
/// <summary>
/// Alternative Guest Rate (Basic type: Currency)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 511 - 518
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public double GuestRate2;
/// <summary>
/// Reference to Type of Foreign Exchange the guest has been quoted in
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 519 - 520
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short ForexType;
/// <summary>
/// Details of any Package the guest has booked useing.
/// This is an RHS user defined type (UDT), the details of which are:
/// Length of each structure: 36 bytes
/// Number of Structures: 5
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 521 - 700
/// </description>
/// <description>
/// 180
/// </description></item></list></summary>
public string[] Package;
/// <summary>
/// Type of Room the Guest prefers to stay in.
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 701 - 702
/// </description>
/// <description>
/// 2
/// </description></item></list></summary>
public short RoomType;
/// <summary>
/// 'Extenstion' Details .
/// This is an RHS user defined type (UDT), the details of which are:
/// Length of each structure: 2 bytes
/// Number of Structures: 4
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 703 - 710
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public short[] Extension;
/// <summary>
/// 'LockExt'
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 711
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string LockExt;
/// <summary>
/// Whether the guest has Checked In or Not
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 712
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string CheckedIn;
/// <summary>
/// Type of Guest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 713
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string GuestType;
/// <summary>
/// Reservation Number
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 714 - 719
/// </description>
/// <description>
/// 6
/// </description></item></list></summary>
public string ResNumber;
/// <summary>
/// PPV
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 720
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string PPV;
/// <summary>
/// ADContent
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 721
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string ADContent;
/// <summary>
/// Wireless
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 722 - 731
/// </description>
/// <description>
/// 10
/// </description></item></list></summary>
public string Wireless;
/// <summary>
/// BBUsage
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 732 - 739
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public string BBUsage;
/// <summary>
/// email
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 740 - 783
/// </description>
/// <description>
/// 44
/// </description></item></list></summary>
public string email;
/// <summary>
/// HSIPortStatus
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 784
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string HSIPortStatus;
/// <summary>
/// GuestHSIPort
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 785 - 787
/// </description>
/// <description>
/// 3
/// </description></item></list></summary>
public string GuestHSIPort;
/// <summary>
/// VIPGuest
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 788
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string VIPGuest;
/// <summary>
/// 'HSICodes' Details .
/// This is an RHS user defined type (UDT), the details of which are:
/// Length of each structure: 2 bytes
/// Number of Structures: 4
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 789 - 800
/// </description>
/// <description>
/// 12
/// </description></item></list></summary>
public string[] HSICodes;
/// <summary>
/// IPTraxStep
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 801
/// </description>
/// <description>
/// 1
/// </description></item></list></summary>
public string IPTraxStep;
/// <summary>
/// RoomAlias
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 802 - 809
/// </description>
/// <description>
/// 8
/// </description></item></list></summary>
public string RoomAlias;
/// <summary>
/// Unused Data (Makes the structure up to 1024 Bytes)
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 810 - 1009
/// </description>
/// <description>
/// 200
/// </description></item></list></summary>
public string Expanded;
/// <summary>
/// WebRmNumber
/// <list type="table"><listheader><term>
/// Position in Structure
/// </term><term>
/// Length in Bytes
/// </term></listheader>
/// <item><description>
/// 1010 - 1023
/// </description>
/// <description>
/// 14
/// </description></item></list></summary>
public string WebRmNumber;
// }
#endregion
#region writeRhsGuestFile
/// <summary>
/// Write data to the the guest file
/// </summary>
/// <param name="guestFileName">File to write data to</param>
public bool writeRhsGuestFile(string guestFileName)
{
int lengthOfGuestRecord = 1024;
string currentFunction = "readGuestFile";
Decoder d = Encoding.UTF8.GetDecoder();
FileStream dataFileStream;
BinaryWriter binWriter;
//See if we can access the file
try
{
dataFileStream = new FileStream(guestFileName, FileMode.Create, FileAccess.Write);
binWriter = new BinaryWriter(dataFileStream, ascii);
}
catch (System.UnauthorizedAccessException e)
{
LogThis(DateTime.Now, "Error Opening File",
e.ToString() + e.Message + e.StackTrace, currentFunction, guestFileName);
return false;
}
catch (System.Exception e)
{
LogThis(DateTime.Now, "Error Opening File",
e.ToString() + e.Message + e.StackTrace, currentFunction, guestFileName);
return false;
}
//we can; lets get the data out of it
byte[] tempBytes = new byte[lengthOfGuestRecord];
//Attempt to write the file
try
{
binWriter.Write(toByteArrayFromString(GuestName, 28));
binWriter.Write(toByteArrayFromString(GuestInHouse, 1));
binWriter.Write(GuestRoom);
binWriter.Write(toByteArrayFromString(Adult, 1));
binWriter.Write(toByteArrayFromString(Child, 1));
binWriter.Write(toByteArrayFromString(Address1, 25));
binWriter.Write(toByteArrayFromString(Address2, 25));
binWriter.Write(toByteArrayFromString(Address3, 25));
binWriter.Write(toByteArrayFromString(Address4, 25));
binWriter.Write(toByteArrayFromString(Rego, 6));
binWriter.Write(toByteArrayFromString(Phone, 10));
binWriter.Write(GuestClass);
binWriter.Write(Convert.ToInt64(GuestRate * 10000));
binWriter.Write(Nights);
binWriter.Write(DateIn.day);
binWriter.Write(DateIn.month);
binWriter.Write(DateIn.year);
binWriter.Write(toByteArrayFromString(Comment, 29));
binWriter.Write(toByteArrayFromString(Voucher, 20));
binWriter.Write(Regular);
binWriter.Write(ExtRec);
binWriter.Write(Notes);
binWriter.Write(MemberNo);
binWriter.Write(Group);
for (int counter = 0; counter < 2; counter++)
{
binWriter.Write(Trans[counter].First);
binWriter.Write(Trans[counter].Last);
binWriter.Write(Trans[counter].Allocated);
binWriter.Write(Trans[counter].Guest);
binWriter.Write(Trans[counter].Size);
binWriter.Write(Trans[counter].Pay);
binWriter.Write(Trans[counter].Debtor);
binWriter.Write(Trans[counter].Invoice);
binWriter.Write(Trans[counter].Printed);
binWriter.Write(Trans[counter].Balance);
binWriter.Write(Trans[counter].Tax );
binWriter.Write(toByteArrayFromString(Trans[counter].Name, 10));
binWriter.Write(toByteArrayFromString(Trans[counter].Unused, 16));
}
binWriter.Write(toByteArrayFromString(Contact, 29));
binWriter.Write(toByteArrayFromString(Mobile, 14));
binWriter.Write(toByteArrayFromString(Spare, 9));
binWriter.Write(Company);
binWriter.Write(toByteArrayFromString(ArrivalDesc, 17));
binWriter.Write(toByteArrayFromString(DepartDesc, 17));
binWriter.Write(Origin);
binWriter.Write(GSTExcl);
binWriter.Write(Source);
binWriter.Write(toByteArrayFromString(CreditCard, 20));
binWriter.Write(toByteArrayFromString(ExpiryDate, 5));
binWriter.Write(toByteArrayFromString(FaxNumber, 10));
binWriter.Write(toByteArrayFromString(UserComment, 29));
binWriter.Write(toByteArrayFromString(Departed, 1));
binWriter.Write(toByteArrayFromString(DepartTime, 5));
binWriter.Write(toByteArrayFromString(PhonePrefix, 4));
binWriter.Write(toByteArrayFromString(FaxPrefix, 4));
binWriter.Write(toByteArrayFromString(RegularNum, 8));
binWriter.Write(toByteArrayFromString(InvoiceType, 1));
binWriter.Write(Convert.ToInt64(GuestRate2 * 10000));
binWriter.Write(ForexType);
for (int counter = 0; counter < 5; counter++)
binWriter.Write(toByteArrayFromString(Package[counter], 36));
binWriter.Write(RoomType);
for (int counter = 0; counter < 4; counter++)
binWriter.Write(Extension[counter]);
binWriter.Write(toByteArrayFromString(LockExt, 1));
binWriter.Write(toByteArrayFromString(CheckedIn, 1));
binWriter.Write(toByteArrayFromString(GuestType, 1));
binWriter.Write(toByteArrayFromString(ResNumber, 6));
binWriter.Write(toByteArrayFromString(PPV, 1));
binWriter.Write(toByteArrayFromString(ADContent, 1));
binWriter.Write(toByteArrayFromString(Wireless, 10));
binWriter.Write(toByteArrayFromString(BBUsage, 8));
binWriter.Write(toByteArrayFromString(email, 44));
binWriter.Write(toByteArrayFromString(HSIPortStatus, 1));
binWriter.Write(toByteArrayFromString(GuestHSIPort, 3));
binWriter.Write(toByteArrayFromString(VIPGuest, 1));
for (int counter = 0; counter < 2; counter++)
binWriter.Write(toByteArrayFromString(HSICodes[counter], 6));
binWriter.Write(toByteArrayFromString(IPTraxStep, 1));
binWriter.Write(toByteArrayFromString(RoomAlias, 8));
binWriter.Write(toByteArrayFromString(Expanded, 200));
binWriter.Write(toByteArrayFromString(WebRmNumber, 14));
}
catch (System.UnauthorizedAccessException e)
{
LogThis(DateTime.Now, "Error Reading File",
e.ToString() + e.Message + e.StackTrace, currentFunction, guestFileName);
return false;
}
catch (System.Exception e)
{
LogThis(DateTime.Now, "Error Reading File",
e.ToString() + e.Message + e.StackTrace, currentFunction, guestFileName);
return false;
}
binWriter.Close();
dataFileStream.Close();
return true;
}
#endregion
}
}
|
04c1b17d651fd7690c4a811f1efd158c7f39aab2
|
C#
|
InariFox/Sunlight
|
/Sunlight/Sunlight/Common/Timer.cs
| 3.46875
| 3
|
using System;
namespace Sunlight.Common
{
class Timer
{
private int time;
private DateTime dt;
// 加算時間をセット(分)
public void setTime(int time)
{
this.time = time;
}
// 時間計算
public void calcTime()
{
dt = DateTime.Now;
TimeSpan addtime = TimeSpan.FromMinutes(time);
dt += addtime;
}
// 計算結果を返す
public DateTime getTime()
{
return dt;
}
}
}
|
610a79f2fb611ea34048982942d87d4d1df8debd
|
C#
|
webmasterdevlin/ThemeConverter
|
/ThemeConverter/ColorCompiler/CategoryCollectionRecord.cs
| 2.859375
| 3
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ThemeConverter.ColorCompiler
{
/// <summary>
/// Reads or writes a sequence of category records from a binary stream.
/// A CategoryCollectionRecord contains a sequence of CategoryRecords.
/// Each CategoryRecord contains a sequence of ColorRecords, and each
/// ColorRecord specifies a name and values for a single color.
/// CategoryCollectionRecords are merged together by a ColorTheme to
/// form the full theme.
/// </summary>
internal sealed class CategoryCollectionRecord
{
List<CategoryRecord> _categories;
public IList<CategoryRecord> Categories
{
get
{
return _categories;
}
}
public CategoryCollectionRecord()
{
_categories = new List<CategoryRecord>();
}
public void Write(BinaryWriter writer)
{
writer.Write(_categories.Count);
foreach (CategoryRecord theme in _categories)
{
theme.Write(writer);
}
}
}
}
|
8eb478970142ec68c8ebc622b34dc89a2ee3ffeb
|
C#
|
OsmSharp/core
|
/src/OsmSharp/Extensions.cs
| 2.671875
| 3
|
// The MIT License (MIT)
// Copyright (c) 2016 Ben Abelshausen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Globalization;
namespace OsmSharp
{
/// <summary>
/// Contains extension methods.
/// </summary>
public static class Extensions
{
/// <summary>
/// Returns a string representing the object in a culture invariant way.
/// </summary>
public static string ToInvariantString(this object obj)
{
return obj is IConvertible ? ((IConvertible)obj).ToString(CultureInfo.InvariantCulture)
: obj is IFormattable ? ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture)
: obj.ToString();
}
/// <summary>
/// Compares this OsmGeo object to another using type, id and version number. Nodes before ways, ways before relations.
/// </summary>
public static int CompareByIdVersionAndType(this OsmGeo osmGeo, OsmGeo other)
{
return osmGeo.CompareTo(other);
}
/// <summary>
/// Compares this OsmGeo object to another using type, and id. Nodes before ways, ways before relations.
/// </summary>
public static int CompareByIdAndType(this OsmGeo osmGeo, OsmGeo other)
{
if (osmGeo == null) { throw new ArgumentNullException("osmGeo"); }
if (other == null) { throw new ArgumentNullException("other"); }
if (osmGeo.Id == null) { throw new ArgumentException("To compare objects must have id set."); }
if (other.Id == null) { throw new ArgumentException("To compare objects must have id set."); }
if (osmGeo.Type == other.Type)
{
if (osmGeo.Id < 0 && other.Id < 0)
{
return other.Id.Value.CompareTo(osmGeo.Id.Value);
}
return osmGeo.Id.Value.CompareTo(other.Id.Value);
}
switch (osmGeo.Type)
{
case OsmGeoType.Node:
return -1;
case OsmGeoType.Way:
switch (other.Type)
{
case OsmGeoType.Node:
return 1;
case OsmGeoType.Relation:
return -1;
}
throw new Exception("Invalid OsmGeoType.");
case OsmGeoType.Relation:
return 1;
}
throw new Exception("Invalid OsmGeoType.");
}
}
}
|
9fbb8ef38f74b5e09aa1f2de3fc04816acd47615
|
C#
|
286studio/Sim286
|
/AVG/Assets/Naninovel/Editor/EditorResources.cs
| 2.578125
| 3
|
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace Naninovel
{
/// <summary>
/// Stores resource path to editor asset GUID map that is required by <see cref="EditorResourceProvider"/> when running under the Unity editor.
/// </summary>
/// <remarks>
/// When user assign specific project assets for the resources via the editor menus (eg, sprites for character appearance or audio clips for BGM), the assigned asset references are stored in this asset.
/// Before entering play mode in the editor, all the stored references are added to a <see cref="EditorResourceProvider"/> instance, which is included to the provider lists when the app is running under the editor.
/// When building the player, the referenced assets are copied to a temp `Resources` folder; this allows the assets to be packaged with the build and makes them available for <see cref="ProjectResourceProvider"/>.
/// </remarks>
[System.Serializable]
public class EditorResources : ScriptableObject
{
// Following types are modified by the editor via reflection.
#pragma warning disable CS0649
[System.Serializable]
public class ResourceCategory
{
public string Id;
public List<EditorResource> Resources;
}
[System.Serializable]
public struct EditorResource
{
public string Name, PathPrefix, Guid;
public string Path => $"{PathPrefix ?? string.Empty}/{Name ?? string.Empty}";
}
#pragma warning restore CS0649
[SerializeField] private List<ResourceCategory> resourceCategories = new List<ResourceCategory>();
private static string directoryPath => PathUtils.Combine(Application.dataPath, ConfigurationSettings.GeneratedDataPath);
private static string assetPath => PathUtils.AbsoluteToAssetPath(PathUtils.Combine(directoryPath, $"{nameof(EditorResources)}.asset"));
/// <summary>
/// Loads an existing asset from package data folder or creates a new default instance.
/// </summary>
public static EditorResources LoadOrDefault ()
{
var obj = AssetDatabase.LoadAssetAtPath<EditorResources>(assetPath);
if (!ObjectUtils.IsValid(obj))
{
obj = CreateInstance<EditorResources>();
obj.AddBuiltinAssets();
System.IO.Directory.CreateDirectory(directoryPath);
AssetDatabase.CreateAsset(obj, assetPath);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
return obj;
}
/// <summary>
/// Finds a resource record by the corresponding asset GUID or null if not found.
/// </summary>
/// <param name="guid">GUID of the asset to look for.</param>
public EditorResource? GetRecordByGuid (string guid)
{
foreach (var resourceCategory in resourceCategories)
foreach (var resource in resourceCategory.Resources)
if (resource.Guid.EqualsFast(guid))
return resource;
return null;
}
/// <summary>
/// Retrieves all the existing resources records in [path] -> [guid] map format.
/// </summary>
/// <param name="categoryId">When specified, will only fetch resources under the category.</param>
/// <param name="skipEmpty">When enabled, will skip records where either path or guid is not defined.</param>
public Dictionary<string, string> GetAllRecords (string categoryId = null, bool skipEmpty = true)
{
var records = new Dictionary<string, string>();
foreach (var resourceCategory in resourceCategories)
if (categoryId is null || resourceCategory.Id == categoryId)
foreach (var resource in resourceCategory.Resources)
if (!skipEmpty || (!string.IsNullOrEmpty(resource.Path) && !string.IsNullOrEmpty(resource.Guid)))
records[resource.Path] = resource.Guid;
return records;
}
/// <summary>
/// Attempts to find an added resource GUID based on its path (prefix + name).
/// </summary>
public string GetGuidByPath (string path)
{
var result = GetAllRecords().FirstOrDefault(kv => kv.Key == path);
if (result.Key != path) return null;
return result.Value;
}
/// <summary>
/// Attempts to find an added resource path (prefix + name) based on its GUID.
/// </summary>
public string GetPathByGuid (string guid)
{
var result = GetAllRecords().FirstOrDefault(kv => kv.Value == guid);
if (result.Value != guid) return null;
return result.Key;
}
/// <summary>
/// Adds a new record; don't forget to save the asset after the modification.
/// </summary>
public void AddRecord (string categoryId, string pathPrefix, string name, string guid)
{
var resource = new EditorResource { PathPrefix = pathPrefix, Name = name, Guid = guid };
var category = resourceCategories.Find(c => c.Id == categoryId);
if (category is null)
{
category = new ResourceCategory { Id = categoryId, Resources = new List<EditorResource>() };
resourceCategories.Add(category);
}
category.Resources.Add(resource);
}
/// <summary>
/// Removes a category with the provided ID and all the underlying records; don't forget to save the asset after the modification.
/// </summary>
public void RemoveCategory (string categoryId)
{
for (int i = 0; i < resourceCategories.Count; i++)
if (resourceCategories[i].Id == categoryId)
resourceCategories.RemoveAt(i);
}
/// <summary>
/// Removes all the records with provided GUID; don't forget to save the asset after the modification.
/// </summary>
public int RemoveAllRecordsWithGuid (string guid, string categoryId = null)
{
var removedCount = 0;
foreach (var resourceCategory in resourceCategories)
if (categoryId is null || resourceCategory.Id == categoryId)
removedCount += resourceCategory.Resources.RemoveAll(c => c.Guid == guid);
return removedCount;
}
/// <summary>
/// Removes all the records with provided path (prefix + name); don't forget to save the asset after the modification.
/// </summary>
public int RemoveAllRecordsWithPath (string pathPrefix, string name, string categoryId = null)
{
var removedCount = 0;
foreach (var resourceCategory in resourceCategories)
if (categoryId is null || resourceCategory.Id == categoryId)
removedCount += resourceCategory.Resources.RemoveAll(c => c.PathPrefix == pathPrefix && c.Name == name);
return removedCount;
}
/// <summary>
/// Draws a dropdown selection list of strings fed by existing resource paths records using automatic editor GUI layout.
/// </summary>
/// <param name="property">The property for which to assign value of the selected element.</param>
/// <param name="category">When specified, will only fetch resources under the category.</param>
/// <param name="pathPrefix">When specified, will only fetch resources under the path prefix and trim the prefix from the values.</param>
/// <param name="emptyOption">When specified, will include an additional option with the provided name and <see cref="string.Empty"/> value to the list.</param>
public void DrawPathPopup (SerializedProperty property, string category = null, string pathPrefix = null, string emptyOption = null)
{
DrawPathPopup(EditorGUILayout.GetControlRect(), property, category, pathPrefix, emptyOption);
}
/// <summary>
/// Draws a dropdown selection list of strings fed by existing resource paths records using the provided draw rect.
/// </summary>
public void DrawPathPopup (Rect rect, SerializedProperty property, string category = null, string pathPrefix = null, string emptyOption = null)
{
const string allLiteral = "*";
var options = new List<string>();
foreach (var resourceCategory in resourceCategories)
if (category is null || resourceCategory.Id == category ||
(category.Contains(allLiteral) && resourceCategory.Id.StartsWithFast(category.GetBefore("*"))))
foreach (var resource in resourceCategory.Resources)
{
if (pathPrefix is null)
{
options.Add(resource.Path);
continue;
}
var option = default(string);
if (pathPrefix == allLiteral)
option = resource.Path.Contains("/") ? resource.Path.GetAfter("/") : resource.Path;
else option = resource.Path.GetAfterFirst(pathPrefix + "/");
if (!string.IsNullOrEmpty(option))
options.Add(option);
}
if (options.Count == 0)
{
EditorGUI.PropertyField(rect, property, true);
return;
}
if (emptyOption != null)
options.Insert(0, emptyOption);
var curValue = emptyOption != null && string.IsNullOrEmpty(property.stringValue) ? emptyOption : property.stringValue;
var optionsArray = options.Select(o => new GUIContent(o)).ToArray();
var label = EditorGUI.BeginProperty(Rect.zero, null, property);
var curIndex = options.IndexOf(curValue);
var newIndex = EditorGUI.Popup(rect, label, curIndex, optionsArray);
var newValue = options.IsIndexValid(newIndex) ? options[newIndex] : options[0];
if (emptyOption != null && newValue == emptyOption)
newValue = string.Empty;
if (property.stringValue != newValue)
property.stringValue = newValue;
}
[InitializeOnLoadMethod]
private static void InitializeEditorProvider ()
{
void InitializeProvider ()
{
var records = LoadOrDefault().GetAllRecords();
var provider = new EditorResourceProvider();
foreach (var record in records)
if (EditorUtils.AssetExistsByGuid(record.Value))
provider.AddResourceGuid(record.Key, record.Value);
var providerField = typeof(ResourceProviderConfiguration).GetField(nameof(ResourceProviderConfiguration.EditorProvider), BindingFlags.Static | BindingFlags.Public);
providerField.SetValue(null, provider);
}
Engine.OnInitializationStarted -= InitializeProvider;
Engine.OnInitializationStarted += InitializeProvider;
}
[ContextMenu("Add Built-In Assets")]
private void AddBuiltinAssets ()
{
var config = default(ActorManagerConfiguration);
config = ConfigurationSettings.LoadOrDefaultAndSave<TextPrintersConfiguration>();
AddActorAsset(config, "Prefabs/TextPrinters/Dialogue.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/Fullscreen.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/Wide.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/Chat.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/Bubble.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/TMProDialogue.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/TMProFullscreen.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/TMProWide.prefab");
AddActorAsset(config, "Prefabs/TextPrinters/TMProBubble.prefab");
config = ConfigurationSettings.LoadOrDefaultAndSave<ChoiceHandlersConfiguration>();
AddActorAsset(config, "Prefabs/ChoiceHandlers/ButtonList.prefab");
AddActorAsset(config, "Prefabs/ChoiceHandlers/ButtonArea.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/Animate.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/DepthOfField.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/DigitalGlitch.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/Rain.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/ShakeBackground.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/ShakeCamera.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/ShakeCharacter.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/ShakePrinter.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/Snow.prefab");
AddAsset(SpawnConfiguration.DefaultPathPrefix, "Prefabs/FX/SunShafts.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/ClickThroughPanel.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/BacklogUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/CGGalleryUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/ConfirmationUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/ContinueInputUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/ExternalScriptsUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/LoadingUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/MovieUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/RollbackUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/SaveLoadUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/SceneTransitionUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/SettingsUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/TipsUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/TitleUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/VariableInputUI.prefab");
AddAsset(UIConfiguration.DefaultPathPrefix, "Prefabs/DefaultUI/PauseUI.prefab");
void AddActorAsset (ActorManagerConfiguration managerConfig, string relativeAssetPath)
{
var actorId = System.IO.Path.GetFileNameWithoutExtension(relativeAssetPath);
var actorMeta = managerConfig.GetMetadataOrDefault(actorId);
var category = $"{actorMeta.Loader.PathPrefix}/{actorMeta.Guid}";
var pathPrefix = actorMeta.Loader.PathPrefix;
var assetPath = $"{PathUtils.AbsoluteToAssetPath(PackagePath.PackageRootPath)}/{relativeAssetPath}";
var assetGuid = AssetDatabase.AssetPathToGUID(assetPath);
AddRecord(category, pathPrefix, actorId, assetGuid);
}
void AddAsset (string categoryId, string relativeAssetPath)
{
var resourceName = System.IO.Path.GetFileNameWithoutExtension(relativeAssetPath);
var assetPath = $"{PathUtils.AbsoluteToAssetPath(PackagePath.PackageRootPath)}/{relativeAssetPath}";
var assetGuid = AssetDatabase.AssetPathToGUID(assetPath);
AddRecord(categoryId, categoryId, resourceName, assetGuid);
}
}
}
}
|
9776bffa5460b744c9e9db782b017e0f153f374f
|
C#
|
guilhermeCoutinho/Unity-Ballz
|
/Assets/Scripts/GamePlay/BallHolder.cs
| 2.734375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallHolder : Singleton<BallHolder> {
public GameObject ballPrefab;
[Range (0,1)]
public float fireRate;
List<Ball> ballList = new List<Ball> ();
List<Ball> ballsInPlay = new List<Ball> () ;
bool waitingForFirstBallToArrive = false;
bool waitingForLastBallToArrive = false;
int ballsRemaining ;
Vector3 waitingPosition ;
void Awake () {
waitingPosition = transform.position;
}
public Vector3 GetPosition()
{
return waitingPosition;
}
public void OnNewPlayerMove () {
waitingForFirstBallToArrive = true;
waitingForLastBallToArrive = true;
}
public void AddBall () {
ballsRemaining ++ ;
GameObject GO = Instantiate
( ballPrefab,waitingPosition,Quaternion.identity,transform);
ballList.Add (GO.GetComponent<Ball> () );
}
public void FireBalls (Vector2 direction ) {
StartCoroutine ( fireBallCoroutine (direction) );
}
public int getNumberOfBallsInPlay () {
return ballsInPlay.Count;
}
public int getNumberOfBallRemaining () {
return ballsRemaining;
}
IEnumerator fireBallCoroutine (Vector2 direction) {
ballsInPlay.Clear () ;
Vector3 originalFiringPosition = waitingPosition;
ballsRemaining = ballList.Count;
for (int i = 0; i < ballList.Count; i++ )
{
ballsInPlay.Add (ballList[i]);
ballList[i].Stop (originalFiringPosition);
ballList[i].Fire (direction);
yield return new WaitForSeconds(fireRate);
ballsRemaining --;
}
}
public void ReturnBall (Ball b) {
b.Stop ();
ballsInPlay.Remove (b);
if (waitingForFirstBallToArrive){
waitingForFirstBallToArrive = false;
float xPosition = b.transform.position.x;
waitingPosition =
new Vector3 (xPosition,transform.position.y,transform.position.z);
EventBinder.TriggerEvent(EventBinder.ON_FIRST_BALL_ARRIVED);
}
if (waitingForLastBallToArrive && getNumberOfBallsInPlay() == 0){
waitingForLastBallToArrive = false;
ballsRemaining = ballList.Count;
EventBinder.TriggerEvent(EventBinder.ON_LAST_BALL_ARRIVED);
}
b.transform.position = new Vector3 (b.transform.position.x,
waitingPosition.y,b.transform.position.z);
b.MoveTo ( waitingPosition );
}
}
|
3591525270b494021ced2c714494bd8ee74fcccb
|
C#
|
valentinacomerci3/week5test
|
/Week5.LIbrettoADO/Repositories/RepositoryEsame.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Week5.LibrettoADO.Entities;
namespace Week5.LibrettoADO.Repositories
{
public class RepositoryEsame : IRepositoryEsame
{
const string connectionString = @"Server = .\SQLEXPRESS; Persist Security Info = False;
Integrated Security = true; Initial Catalog = Libretto;";
public bool Add(Esame item)
{
bool esito = true;
using(SqlConnection connection = new SqlConnection(connectionString))
{
//creo adapter
SqlDataAdapter adapter = new SqlDataAdapter();
//creo comandi: selezione e aggiunta
SqlCommand selectCommand = new SqlCommand()
{
Connection = connection,
CommandType = System.Data.CommandType.Text,
CommandText = "SELECT * FROM Esame"
};
SqlCommand insertCommand = new SqlCommand()
{
Connection = connection,
CommandType = System.Data.CommandType.Text,
CommandText = "INSERT INTO Esame VALUES (@ID, @Nome, @CFU, @DataEsame,@Voto,@Esito,@Studente)"
};
insertCommand.Parameters.Add("@ID", SqlDbType.Int, 999, "ID");
insertCommand.Parameters.Add("@Nome", SqlDbType.VarChar, 50, "Nome");
insertCommand.Parameters.Add("@CFU", SqlDbType.Int, 999, "CFU");
insertCommand.Parameters.Add("@DataEsame", SqlDbType.Date, 20, "DataEsame");
insertCommand.Parameters.Add("@Voto", SqlDbType.Int, 999, "Voto");
insertCommand.Parameters.Add("@Esito", SqlDbType.VarChar, 999, "Esito");
insertCommand.Parameters.Add("@Studente", SqlDbType.Int, 999, "Studente");
//associo i comandi che ho creato all'adapter
adapter.SelectCommand = selectCommand;
adapter.InsertCommand = insertCommand;
//creo il dataset
DataSet dataset = new DataSet();
try
{
//apro connessione
connection.Open();
adapter.Fill(dataset, "Esame");
//creo e poi aggiungo la riga al dataset
DataRow esame = dataset.Tables["Esame"].NewRow();
esame["ID"] = item.ID;
esame["Nome"] = item.Nome;
esame["CFU"] = item.CFU;
esame["DataEsame"] = item.DataEsame;
esame["Voto"] = item.Voto;
esame["Esito"] = item.Esito;
esame["Studente"] = item.Studente;
dataset.Tables["Esame"].Rows.Add(esame);
adapter.Update(dataset, "Esame");
}catch(SqlException ex)
{
Console.WriteLine(ex.Message);
return esito = false;
}catch(Exception e)
{
Console.WriteLine(e.Message);
return esito = false;
}
}
return true;
}
public IList<Esame> GetAll()
{
IList<Esame> esami = new List<Esame>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
//apertura connessione
connection.Open();
//creare il comando
SqlCommand command = new SqlCommand()
{
Connection = connection,
CommandType = System.Data.CommandType.Text,
CommandText = "SELECT * FROM Esame"
};
//esecuzione comando
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Esame esameDaAggiungere = new Esame()
{
ID = Int32.Parse(reader["ID"].ToString()),
Nome = reader["Nome"].ToString(),
CFU = Int32.Parse(reader["CFU"].ToString()),
DataEsame = DateTime.Parse(reader["DataEsame"].ToString()),
Voto = Int32.Parse(reader["Voto"].ToString()),
Esito= reader["Esito"].ToString(),
Studente = Int32.Parse(reader["Studente"].ToString()),
};
esami.Add(esameDaAggiungere);
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
return esami;
}
public IList<Esame> EsamiOrdinatiPerVotoData()
{
IEnumerable<Esame> esamiPerVotoData = GetAll().OrderBy(esame => esame.Studente);
return esamiPerVotoData.ToList();
}
}
}
|
990f579216bcbd5ae21d87a257b0b030d707a434
|
C#
|
vietnh/Binhyencd
|
/RealMusic/Utils/StringHelper.cs
| 3.234375
| 3
|
using System.Globalization;
using System.Linq;
using System.Text;
namespace RealMusic.Utils
{
public static class StringHelper
{
public static string RemoveDiacriticsAndLowerCase(this string str)
{
if (str == null) return null;
var chars =
from c in str.Normalize(NormalizationForm.FormD).ToCharArray()
let uc = CharUnicodeInfo.GetUnicodeCategory(c)
where uc != UnicodeCategory.NonSpacingMark
select c;
var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC).ToLower().Replace("đ", "d");
return cleanStr;
}
}
}
|
5de966f81eb3411d216bea466f798ac5b223da90
|
C#
|
jackmott/image-evolver
|
/GameLogic/GifExport.cs
| 3.203125
| 3
|
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.PixelFormats;
namespace GameLogic
{
/// <summary>
/// Store a number of frames as <see cref="Color"/> arrays. Supports exporting single
/// frames as a png image or multiple frames as a gif using ImageSharp.
/// </summary>
public class FrameStore
{
/// <summary>
/// Width of the frames in pixels.
/// </summary>
public int Width { get; }
/// <summary>
/// Height of the frames in pixels.
/// </summary>
public int Height { get; }
/// <summary>
/// The stored frames.
/// </summary>
public Color[][] Frames { get; }
private readonly Rgba32[] _rgbaBuffer;
private int _frameIndex;
/// <summary>
/// Number of frames that can be stored.
/// </summary>
public int FrameCapacity => Frames.Length;
/// <summary>
/// Number of stored frames.
/// </summary>
public int FrameCount { get; private set; }
/// <summary>
/// Create a new <see cref="FrameStore"/>.
/// </summary>
/// <param name="capacity">Number of frames to store.</param>
/// <param name="width">Width of each frame.</param>
/// <param name="height">Height of each frame.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="capacity"/>, <paramref name="width"/> or <paramref name="height"/>
/// are less than or equal to zero.
/// </exception>
public FrameStore(int capacity, int width, int height)
{
if (capacity <= 0)
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity should be larger than zero.");
if (width <= 0)
throw new ArgumentOutOfRangeException(nameof(width), "Width should be larger than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException(nameof(height), "Height should be larger than zero.");
Width = width;
Height = height;
Frames = new Color[capacity][];
var frameSize = width * height;
for (var i = 0; i < capacity; i++)
Frames[i] = new Color[frameSize];
_rgbaBuffer = new Rgba32[frameSize];
}
/// <summary>
/// Add a frame at the end of the store.
/// </summary>
/// <param name="frame">The frame to add.</param>
/// <exception cref="ArgumentException">If the frame size does not match.</exception>
public void PushFrame(Color[] frame)
{
if (Frames.Length < Width * Height)
throw new ArgumentException("Frame has less pixels than expected.", nameof(Frames));
for (var i = 0; i < Width * Height; i++)
Frames[_frameIndex][i] = frame[i];
_frameIndex = (_frameIndex + 1) % FrameCapacity;
if (FrameCount < FrameCapacity)
FrameCount++;
}
/// <summary>
/// Add a frame at the end of the store.
/// </summary>
/// <param name="frame">The frame to add.</param>
public void PushFrame(Texture2D frame)
{
if (frame == null)
throw new ArgumentNullException(nameof(frame));
frame.GetData(Frames[_frameIndex]);
_frameIndex = (_frameIndex + 1) % FrameCapacity;
if (FrameCount < FrameCapacity)
FrameCount++;
}
/// <summary>
/// Export a frame as a PNG image.
/// </summary>
/// <param name="path">Path to write the image to.</param>
/// <param name="index">Index of the frame.</param>
public void ExportFrame(string path, int index)
{
using (var stream = File.OpenWrite(path))
ExportFrame(stream, index);
}
/// <summary>
/// Export a frame as a PNG image.
/// </summary>
/// <param name="output">Stream to write the image to.</param>
/// <param name="index">Index of the frame.</param>
public void ExportFrame(Stream output, int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException();
if (index >= FrameCount)
throw new ArgumentOutOfRangeException();
var frameIndex = (_frameIndex + index) % FrameCapacity;
ConvertColorData(Frames[frameIndex], _rgbaBuffer);
using (var image = Image.LoadPixelData(_rgbaBuffer, Width, Height))
image.SaveAsPng(output);
}
/// <summary>
/// Export frames from the store as a GIF.
/// </summary>
/// <param name="output">Stream to write the GIF to.</param>
/// <param name="frameDelay">Delay between frames in units of 10ms.</param>
/// <param name="start">First frame to export.</param>
/// <param name="count">Number of frames to export.</param>
public void ExportGif(Stream output, int frameDelay)
{
using (var image = new Image<Rgba32>(Width, Height))
{
var frames = image.Frames;
for (var i = 1; i < FrameCapacity; i++)
{
ConvertColorData(Frames[i], _rgbaBuffer);
var frame = frames.AddFrame(_rgbaBuffer);
frame.MetaData.GetFormatMetaData(GifFormat.Instance).FrameDelay = frameDelay;
Transition.SetProgress(i / 4);
}
// remove the frame created with image creation
frames.RemoveFrame(0);
var encoder = new GifEncoder();
encoder.ColorTableMode = GifColorTableMode.Local;
image.SaveAsGif(output, encoder);
}
}
private static void ConvertColorData(Color[] mgBuffer, Rgba32[] isBuffer)
{
for (var i = 0; i < mgBuffer.Length; i++)
{
var c = mgBuffer[i];
isBuffer[i] = new Rgba32(c.R, c.G, c.B, c.A);
}
}
}
}
|
c4c7d45f1a57821b36231d9a55c4d9956e75a18c
|
C#
|
kkubli3246/BibleVerseStorage
|
/Services/Business/SercurityServices.cs
| 2.8125
| 3
|
using BibleVerseApplication.Models;
using BibleVerseApplication.Services.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BibleVerseApplication.Services.Business
{
public class SercurityServices
{
//Adds a New Bible Verse to DB through the Security DAO
public void AddVerse(BibleVerse verse)
{
SecurityDAO security = new SecurityDAO();
security.AddVerse(verse);
}
//Find a Verse Based on Input
//Returns the Tuple<BibleVerse, Bool> to the Controller
public Tuple<BibleVerse, bool> SearchVerse(BibleVerse verse)
{
SecurityDAO security = new SecurityDAO();
return security.SearchVerse(verse);
}
}
}
|
73b33f4f4e0f0fe443c8d7c763f5b65cb41546a6
|
C#
|
Lesssnik/Labs
|
/3 semester/C#/4 lab/LINQHTML.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using Rumyantsev.Lab2.Railroad;
namespace Rumyantsev.Lab4.XMLAndSerialization
{
/// <summary>
/// Save station`s timetable as html document
/// </summary>
class LINQHTML
{
/// <summary>
/// Create html file with information about timetable and save it
/// </summary>
/// <param name="Path">Where html file should be saved</param>
/// <param name="station">Station</param>
public void SaveTimetables(string Path, Station station)
{
FileStream fs = new FileStream(Path, FileMode.Create);
XDocument document = new XDocument();
document.AddFirst(new XElement("html"));
document.Root.Add(new XElement("head",
new XElement("title", station.Name)));
XElement body = new XElement("body");
XElement div = new XElement("div");
foreach (Timetable tt in station)
{
XElement inner = new XElement("div", new XAttribute("style", "width:800px;"));
inner.Add(new XElement("div", tt.FirstStation + " - " + tt.LastStation, new XAttribute("style", "border:solid; float:left; width:400px; heigth:20px;"), new XAttribute("align", "center")),
new XElement("div", tt.TimeOfArrival.ToString() + " - " + tt.TimeOfDeparture.ToString(), new XAttribute("style", "border:solid; float:left; width:150px; heigth:20px;"), new XAttribute("align", "center")),
new XElement("div", tt.FreqType, new XAttribute("style", "border:solid; float:left; width:150px; heigth:20px;"), new XAttribute("align", "center")),
new XElement("br"));
div.Add(inner);
}
body.Add(div);
document.Root.Add(body);
document.Save(fs);
fs.Close();
}
}
}
|
fd44cadbb92f4ea2618a2a3a20f6b6a0ea314ad2
|
C#
|
syncore/ReflexAPI
|
/ReflexApi/ServerList.cs
| 2.625
| 3
|
namespace ReflexAPI
{
using System.Collections.Generic;
using SteamData;
/// <summary>
/// Static class that holds an in-memory representation of the current server list and servers
/// that failed to query. <remarks> Persist so multiple user requests do not initiate a new
/// server list request. </remarks>
/// </summary>
public static class ServerList
{
/// <summary>
/// Gets all servers.
/// </summary>
/// <value>All servers.</value>
public static List<ServerData> AllServers { get; set; }
/// <summary>
/// Gets the list of server ip addresses and ports that failed to query.
/// </summary>
/// <value>The failed servers.</value>
public static List<string> FailedServers { get; set; }
/// <summary>
/// Gets or sets the query time.
/// </summary>
/// <value>
/// The query time.
/// </value>
public static string QueryTime { get; set; }
/// <summary>
/// Gets or sets the query time stamp.
/// </summary>
/// <value>
/// The query time stamp.
/// </value>
public static double QueryTimeStamp { get; set; }
}
}
|
b403a4411dfe4027ff76b33ec26debd47081b3d5
|
C#
|
SimLoNo/BookingTest
|
/BookingTest_1/SQLCommands.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace BookingTest_1
{
class SQLCommands
{//Opretter variabler til connectionstring og tider for checkin og checkud----------------------------
public string CheckInTime = " 15:00";
public string CheckOutTime = " 11:00";
public string ConString = "Data Source=.;Initial Catalog=BookingApp;Integrated Security=True";
//-------------------------------------------------------------------------------------------------
//Metode til at teste forbindelse------------------------------------------------------------------
public bool CheckConnection()
{ using (SqlConnection Con = new SqlConnection(ConString))
{
try
{ Con.Open();
Console.WriteLine("Connection!");
return true;
}
catch (Exception) {return false; }
}
}
//-------------------------------------------------------------------------------------------------
//Metode til at lave en booking hos hotellet-------------------------------------------------------
public void MakeBooking(Booking Bk)
{
using (SqlConnection Con = new SqlConnection(ConString))
{
try
{
Con.Open();
InfoCheck InfChk = new InfoCheck();
bool AlreadyBooked = false;
//Opretter Sql kommandoer til brug i koden------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SqlCommand CheckAvailable = new SqlCommand("SELECT BookingDateStart, BookingDateEnd FROM BookingTable", Con);
SqlCommand InsertBooking = new SqlCommand("INSERT INTO BookingTable(BookingDateStart, BookingDateEnd) VALUES ('" + Bk.BookingStart.ToString("MM-dd-yyyy") + CheckInTime+ "','" + Bk.BookingEnd.ToString("MM-dd-yyyy")+CheckOutTime + "')", Con);
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SqlDataReader ReaderBookings = CheckAvailable.ExecuteReader();
while (ReaderBookings.Read())
{
//Tjekker om der allerede er bookinger i den oenskede tidsperiode-------------------------------------------------------------------------
DateTime OldBookingStart = ReaderBookings.GetDateTime(0);
DateTime OldBookingEnd = ReaderBookings.GetDateTime(1);
if (InfChk.DateCheck(OldBookingStart, OldBookingEnd, Bk.BookingStart, Bk.BookingEnd) == true) AlreadyBooked = true;
//----------------------------------------------------------------------------------------------------------------------------------------
}
ReaderBookings.Close(); //Lukker forbindelsen der tjekker databasen
//Hvis der ikke er fundet nogle krydsende datoer i databasen, bliver bookingen lavet, eller bliver brugeren oplyst om at booking ikke er muligt----
if (AlreadyBooked == false)
{
Console.WriteLine("Booking tilgængelig.");
InsertBooking.ExecuteNonQuery(); }
else Console.WriteLine("Der er desværre ikke plads i denne tidsperiode.");
//-------------------------------------------------------------------------------------------------------------------------------------------------
}
catch (Exception Ex) { Console.WriteLine(Ex.Message); }
}
}
public Booking FindBooking(Booking Bk)
{
Booking FndBk = new Booking();
using(SqlConnection Con = new SqlConnection(ConString))
{
try
{
List<BookingPart> BkPList = new List<BookingPart>();
Con.Open();
SqlCommand SelectBooking = new SqlCommand("SELECT * FROM BookingTable WHERE BookingDateStart ='" + Bk.BookingStart.ToString("MM-dd-yyyy")+CheckInTime + "' AND BookingDateEnd='" + Bk.BookingEnd.ToString("MM-dd-yyyy")+CheckOutTime+"'", Con);
SqlDataReader Reader = SelectBooking.ExecuteReader();
while (Reader.Read())
{
FndBk.BookingId = Reader.GetInt32(0);
FndBk.BookingStart = Reader.GetDateTime(1);
FndBk.BookingEnd = Reader.GetDateTime(2);
}
}
catch (Exception Ex) { Console.WriteLine(Ex.Message," !FindBooking!"); }
return FndBk;
}
}
//-------------------------------------------------------------------------------------------------
//Metode til at teste loesninger til problemer i andre metoder-------------------------------------
public void InsertCheck(Booking Bk)
{
using (SqlConnection Con = new SqlConnection(ConString))
{
try
{
string D1 = Bk.BookingStart.ToString();
string D2 = Bk.BookingEnd.ToString();
Con.Open();
SqlCommand Cmd = new SqlCommand("INSERT INTO BookingTable(BookingDateStart, BookingDateEnd) VALUES ('"+Bk.BookingStart.ToString("MM-dd-yyyy")+"','"+Bk.BookingEnd.ToString("MM-dd-yyyy") +"')",Con);
Cmd.ExecuteNonQuery();
Console.WriteLine("Appers to have done it.");
}
catch (Exception Ex) { Console.WriteLine(Ex.Message); }
}
}
//-------------------------------------------------------------------------------------------------
}
}
|
965a4a1d8124d7393bf5bf9361a2453105a8865f
|
C#
|
garywei944/Untitled-Tower-Defense
|
/Assets/Scripts/Defender/Bullet.cs
| 2.71875
| 3
|
using UnityEngine;
namespace Sandbox.Gary
{
public class Bullet : MonoBehaviour
{
private Transform _mTarget;
public float speed = 80f;
public float damage = 20;
public float explosionRadius;
public void SetTarget(Transform target)
{
_mTarget = target;
}
private void Update()
{
if (!_mTarget)
{
Destroy(gameObject);
return;
}
var dir = _mTarget.position - transform.position;
if (Vector3.Distance(_mTarget.position, transform.position) < speed * Time.deltaTime)
{
// Hit target
HitTarget();
}
transform.Translate(dir.normalized * (speed * Time.deltaTime), Space.World);
transform.LookAt(_mTarget);
}
private void HitTarget()
{
if (explosionRadius > 0)
{
Explosion();
}
else
{
EnemyDamage(_mTarget, EnemyHealth.DamageType.Bullet);
}
Destroy(gameObject);
}
private void EnemyDamage(Component enemy, EnemyHealth.DamageType type)
{
var enemyHp = enemy.GetComponent<EnemyHealth>();
if (enemyHp)
{
enemyHp.Damage(damage, type);
}
}
private void Explosion()
{
var colliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach (var item in colliders)
{
if (item.CompareTag("Enemy"))
{
EnemyDamage(item, EnemyHealth.DamageType.Missile);
}
}
}
}
}
|
23b05dbc4c1e5ce3214d6a977cae81503941f16b
|
C#
|
bwr57/OSMPT
|
/OsmSharp.Tools/Math/VRP/Core/Routes/Symmetric/FixedSymmetricRoute.cs
| 2.921875
| 3
|
// OsmSharp - OpenStreetMap tools & library.
// Copyright (C) 2012 Abelshausen Ben
//
// This file is part of OsmSharp.
//
// OsmSharp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// OsmSharp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OsmSharp. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OsmSharp.Tools.Collections;
namespace OsmSharp.Tools.Math.VRP.Core.Routes.Symmetric
{
/// <summary>
/// A fast implementation of a route with a steady customer count.
/// </summary>
public class FixedSymmetricRoute : ISymmetricRoute, IEnumerable<int>
{
/// <summary>
/// Contains the list of customers in this symmetric route.
/// </summary>
private int[][] _customers;
/// <summary>
/// Creates a new fixed symmetric route.
/// </summary>
/// <param name="enumerable"></param>
public FixedSymmetricRoute(IEnumerable<int> enumerable)
{
List<int> customers = new List<int>(enumerable);
_customers = new int[customers.Count][];
_customers[customers[0]] = new int[2];
_customers[customers[0]][0] = customers[customers.Count - 1];
_customers[customers[0]][1] = customers[1];
for (int idx = 1; idx < customers.Count - 1; idx++)
{
_customers[customers[idx]] = new int[2];
_customers[customers[idx]][0] = customers[idx - 1];
_customers[customers[idx]][1] = customers[idx + 1];
}
_customers[customers[customers.Count - 1]] = new int[2];
_customers[customers[customers.Count - 1]][0] = customers[customers.Count - 2];
_customers[customers[customers.Count - 1]][1] = customers[0];
}
private FixedSymmetricRoute(int[][] customers)
{
_customers = new int[customers.Length][];
for (int idx = 0; idx < customers.Length; idx++)
{
_customers[idx] = customers[idx].Clone() as int[];
}
}
/// <summary>
/// Returns true if the route is empty.
/// </summary>
public bool IsEmpty
{
get
{
return _customers.Length == 0;
}
}
/// <summary>
/// Returns true if the route contains the two customers next to eachother.
/// </summary>
/// <param name="customer1"></param>
/// <param name="customer2"></param>
/// <returns></returns>
public bool Contains(int customer1, int customer2)
{
return _customers[customer1][0] == customer2
|| _customers[customer1][1] == customer1;
}
/// <summary>
/// Returns the neigbours of the given customer.
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public int[] GetNeigbours(int customer)
{
return _customers[customer];
}
/// <summary>
/// Removes two customers.
/// </summary>
/// <param name="customer1"></param>
/// <param name="customer2"></param>
public void Remove(int customer1, int customer2)
{
if (_customers[customer1][0] == customer2)
{
_customers[customer1][0] = -1;
}
else if (_customers[customer1][1] == customer2)
{
_customers[customer1][1] = -1;
}
if (_customers[customer2][0] == customer1)
{
_customers[customer2][0] = -1;
}
else if (_customers[customer2][1] == customer1)
{
_customers[customer2][1] = -1;
}
}
/// <summary>
/// Adds a new edge.
/// </summary>
/// <param name="customer1"></param>
/// <param name="customer2"></param>
public void Add(int customer1, int customer2)
{
if (_customers[customer1][0] == -1)
{
_customers[customer1][0] = customer2;
}
else if (_customers[customer1][1] == -1)
{
_customers[customer1][1] = customer2;
}
if (_customers[customer2][0] == -1)
{
_customers[customer2][0] = customer1;
}
else if (_customers[customer2][1] == -1)
{
_customers[customer2][1] = customer1;
}
}
/// <summary>
/// Clones this route.
/// </summary>
/// <returns></returns>
public object Clone()
{
return new FixedSymmetricRoute(_customers);
}
/// <summary>
/// Returns true if valid.
/// </summary>
/// <returns></returns>
public bool IsValid()
{
// always begin at zero.
int current = 0;
// get one of the neigbours of current.
int next = _customers[current][0];
int cnt = 1;
while (next > 0)
{
// get the neigbour that is not the current one.
int neighbour = _customers[next][0];
if (neighbour == current)
{
neighbour = _customers[next][1];
if (neighbour == current)
{
return false;
}
}
current = next;
next = neighbour;
if (cnt > _customers.Length)
{
return false;
}
cnt++;
}
return _customers.Length == cnt;
}
/// <summary>
/// Returns true if is valid.
/// </summary>
/// <returns></returns>
public bool IsValidNew()
{
// always begin at zero.
int current = 0;
// get one of the neigbours of current.
int next = _customers[current][0];
int cnt = 1;
HashSet<int> unique = new HashSet<int>();
unique.Add(next);
if (next < 0)
{
return false;
}
while (next != 0)
{
// get the neigbour that is not the current one.
int neighbour = _customers[next][0];
if (neighbour == current)
{
neighbour = _customers[next][1];
if (neighbour == current)
{
return false;
}
}
current = next;
next = neighbour;
if (cnt > _customers.Length)
{
return false;
}
if (next < 0)
{
return false;
}
unique.Add(next);
cnt++;
}
return _customers.Length == cnt &&
unique.Count == cnt;
}
/// <summary>
/// Returns true if the route is a round.
/// </summary>
public bool IsRound
{
get
{
return true;
}
}
/// <summary>
/// Returns a description of the route.
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder builder = new StringBuilder();
// always begin at zero.
int current = 0;
builder.Append(current);
// get one of the neigbours of current.
int next = _customers[current][0];
builder.Append("->");
builder.Append(next);
while (next != 0)
{
// get the neigbour that is not the current one.
int neighbour = _customers[next][0];
if (neighbour == current)
{
neighbour = _customers[next][1];
if (neighbour == current)
{
return "Invalid Route!";
}
}
current = next;
next = neighbour;
builder.Append("->");
builder.Append(next);
}
return builder.ToString();
}
#region IEnumerable<int>
/// <summary>
/// Returns the enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator<int> GetEnumerator()
{
return new SymmetricRouteEnumerator(_customers);
}
/// <summary>
/// Returns the enumerator.
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
private class SymmetricRouteEnumerator : IEnumerator<int>
{
private int[][] _customers;
/// <summary>
/// Creates a new enumerator.
/// </summary>
/// <param name="customers"></param>
public SymmetricRouteEnumerator(int[][] customers)
{
_customers = customers;
}
int _next = -1;
int _current = -1;
/// <summary>
/// Returns the current.
/// </summary>
public int Current
{
get
{
return _current;
}
}
/// <summary>
/// Disposes this object.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Returns the current.
/// </summary>
object System.Collections.IEnumerator.Current
{
get
{
return _current;
}
}
/// <summary>
/// Move to the next customer.
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
if (_next < 0)
{
// always begin at zero.
_current = 0;
// get one of the neigbours of current.
_next = _customers[_current][0];
return true;
}
else
{
// get the neigbour that is not the current one.
int neighbour = _customers[_next][0];
if (neighbour == _current)
{
neighbour = _customers[_next][1];
if (neighbour == _current)
{
return false;
}
}
_current = _next;
_next = neighbour;
return _current != 0;
}
}
/// <summary>
/// Resets this route.
/// </summary>
public void Reset()
{
_current = -1;
_next = -1;
}
}
/// <summary>
/// Inserts a new customer.
/// </summary>
/// <param name="from"></param>
/// <param name="customer"></param>
/// <param name="to"></param>
public void Insert(int from, int customer, int to)
{
this.Add(from, customer);
this.Add(customer, to);
}
/// <summary>
/// Returns the customer count.
/// </summary>
public int Count
{
get
{
return _customers.Length;
}
}
/// <summary>
/// Removes a customer.
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public bool Remove(int customer)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns the first customer.
/// </summary>
public int First
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Returns the last customer.
/// </summary>
public int Last
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Returns the index of the given customer.
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public int GetIndexOf(int customer)
{
int idx = 0;
foreach (int possible_customer in this)
{
if (possible_customer == customer)
{
return idx;
}
idx++;
}
return -1; // customer not found!
}
/// <summary>
/// Enumerates between.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public IEnumerable<int> Between(int from, int to)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns true if this customer is contained in the given route.
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public bool Contains(int customer)
{
throw new NotImplementedException();
}
/// <summary>
/// Replaces an edge.
/// </summary>
/// <param name="from"></param>
/// <param name="customer"></param>
public void ReplaceEdgeFrom(int from, int customer)
{
throw new NotImplementedException();
}
/// <summary>
/// Inserts a new edge.
/// </summary>
/// <param name="from"></param>
/// <param name="customer"></param>
public void InsertAfter(int from, int customer)
{
throw new NotImplementedException();
}
/// <summary>
/// Enumerates all edges.
/// </summary>
/// <returns></returns>
public IEnumerable<Edge> Edges()
{
throw new NotImplementedException();
}
/// <summary>
/// Inserts a new first customers.
/// </summary>
/// <param name="first"></param>
public void InsertFirst(int first)
{
throw new NotImplementedException();
}
/// <summary>
/// Replaces the first customer.
/// </summary>
/// <param name="first"></param>
public void ReplaceFirst(int first)
{
throw new NotImplementedException();
}
/// <summary>
/// Clears all customers in this route.
/// </summary>
public void Clear()
{
throw new NotImplementedException();
}
}
}
|
8b853d413245775ed03d037e5486b90f6db122cd
|
C#
|
chinian-main/CSharpe
|
/Demo_GreedySnack/Demo_GreedySnack/SnackBody.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo_GreedySnack
{
enum E_SnakeBody_Type
{
Head,
Body
}
class SnackBody:GameObject
{
private E_SnakeBody_Type type;
public SnackBody(E_SnakeBody_Type type,int x,int y)
{
this.type = type;
this.pos = new Position(x, y);
}
public override void Draw()
{
Console.SetCursorPosition(pos.x, pos.y);
Console.ForegroundColor = type == E_SnakeBody_Type.Head ? ConsoleColor.Yellow : ConsoleColor.Green;
Console.Write(type == E_SnakeBody_Type.Head ? "⊙" : "●");
}
}
}
|
d1cfe159f398ea55c53f0ebece918aed592c427d
|
C#
|
DarkWanderer/ClickHouse.Client
|
/ClickHouse.Client/Formats/PeekableStreamWrapper.cs
| 3.0625
| 3
|
using System;
using System.IO;
namespace ClickHouse.Client.Formats;
/// <summary>
/// Universal stream wrapper allowing to add 'PeekChar' support to streams with CanSeek=false
/// Suggestions for better solution wanted
/// </summary>
internal class PeekableStreamWrapper : Stream, IDisposable
{
private readonly Stream stream;
private bool hasReadAheadByte;
private int readAheadByte;
public PeekableStreamWrapper(Stream stream)
{
this.stream = stream;
hasReadAheadByte = false;
readAheadByte = 0;
}
public override bool CanRead => stream.CanRead;
public override bool CanSeek => stream.CanSeek;
public override bool CanWrite => stream.CanWrite;
public override long Length => stream.Length;
public override long Position { get => stream.Position; set => stream.Position = value; }
public override void Flush() => stream.Flush();
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (count == 0)
return 0;
var b = ReadByte();
if (b == -1)
throw new EndOfStreamException();
buffer[offset] = (byte)b;
var result = 1;
if (count > 1)
result += stream.Read(buffer, offset + 1, count - 1);
return result;
}
public override long Seek(long offset, SeekOrigin origin) => stream.Seek(offset, origin);
public override void SetLength(long value) => stream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => stream.Write(buffer, offset, count);
public override int ReadByte()
{
if (!hasReadAheadByte)
{
return stream.ReadByte();
}
hasReadAheadByte = false;
return readAheadByte;
}
public int Peek()
{
if (!hasReadAheadByte)
{
readAheadByte = stream.ReadByte();
hasReadAheadByte = true;
}
return readAheadByte;
}
public new void Dispose() => stream.Dispose();
}
|
ec8bc0138eef8454530d789603b1c40ccf350256
|
C#
|
AmadejusV/Csharp10.08
|
/BarberShop/Controllers/BookingController.cs
| 2.6875
| 3
|
using BarberShop.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BarberShop.Controllers
{
public class BookingController : Controller
{
public IActionResult Index()
{
Barber Aurimas = new Barber() { Name = "Aurimas", Surname = "Bajo" };
Barber Tomas = new Barber() { Name = "Tomas", Surname = "Sinickis" };
List<Booking> bookings = new List<Booking>()
{
new Booking(){Barber=Aurimas, BookingStatus=BookingStatus.available, AvailableTime=DateTime.Now}, //duomenys booking liste, kad prie ju prieit reikia listo tipa perduot i view
new Booking(){Barber=Tomas, BookingStatus=BookingStatus.available, AvailableTime=DateTime.Now},
new Booking(){Barber=Aurimas, BookingStatus=BookingStatus.available, AvailableTime=DateTime.Now.AddDays(-1)},
};
return View(bookings); //grazins bookings duomenis, leis juos panaduot
}
}
}
|
91f11c8544f592794cc4399fc832145514e4366e
|
C#
|
thezachcannon/BenefitsCalculator
|
/BenefitsCalculatorApi/Services/EmployeeService.cs
| 2.6875
| 3
|
using System.Collections.Generic;
using System.Threading.Tasks;
using BenefitsCalculatorApi.Domain.Models;
using BenefitsCalculatorApi.Domain.Services;
using BenefitsCalculatorApi.Domain.Repositories;
using BenefitsCalculatorApi.Domain.Services.Communication;
using System;
namespace BenefitsCalculatorApi.Services
{
public class EmployeeService : IEmployeeService
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeService(IEmployeeRepository employeeRepository)
{
this._employeeRepository = employeeRepository;
}
public async Task<IEnumerable<Employee>> GetEmployeesAsync()
{
return await _employeeRepository.GetEmployeesAsync();
}
public async Task<Employee> GetAsync(string id)
{
return await _employeeRepository.GetAsync(id);
}
public async Task<SaveEmployeeResponse> SaveAsync(Employee employee)
{
try
{
await _employeeRepository.AddAsync(employee);
return new SaveEmployeeResponse(employee);
}
catch (Exception ex)
{
return new SaveEmployeeResponse($"An error occurred when saving the category: {ex.Message}");
}
}
}
}
|
6f250c2e29b2b10f1862d37985fc793935e1803e
|
C#
|
SandraMuller/TravelTech
|
/WebForm/Database/FakeDatabase.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebForm.Models;
namespace WebForm.Database
{
class FakeDatabase
{
public List<Location> GetLocations()
{
var list = new List<Location>() {
new Location() { Name = "Upper Hutt", Value = "UpperHutt", Description = "Somewhere upper to here.", Region="Wellington"},
new Location() { Name = "Lower Hutt", Value = "LowerHutt", Description = "Somewhere lower to here.", Region="Wellington"},
new Location() { Name = "Paruma", Value = "Paruma", Description = "Madithupith", Region="Auckland"},
new Location() { Name = "Pukekuoae", Value = "Pukekuoae", Description = "Puke ko hi", Region="Auckland"}
};
return list;
}
public List<Region> GetRegions()
{
var list = new List<Region>() {
new Region() {regionName = "Wellington", regionValue = "Wellington" },
new Region() {regionName = "Auckland", regionValue = "Auckland"}
};
return list;
}
}
}
|
e2505a9faadc9397a497f15a814ce0ae070cc0c7
|
C#
|
Kryxzael/RoomShuffle
|
/Assets/RoomShuffle/Objects/Pickups/Weapon/WeaponPickupBase.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
public abstract class WeaponPickupBase : PickupScript
{
public PickupBase DroppableWeaponPrefab;
/// <summary>
/// Gets the weapon to pick up
/// </summary>
/// <returns></returns>
public abstract WeaponInstance GetWeapon();
protected virtual void Start()
{
var renderer = GetComponent<SpriteRenderer>();
renderer.sprite = GetWeapon().Template.Icon;
renderer.color = Color.white;
}
/// <summary>
/// <inheritdoc />
/// </summary>
public override void OnPickup()
{
var instance = GetWeapon();
//Attempt to place weapon in a free slot
for (int i = 0; i < Inventory.MAX_WEAPON_SLOTS; i++)
{
if (Commons.Inventory.WeaponSlots[i] == null)
{
Commons.Inventory.WeaponSlots[i] = instance;
return;
}
}
//If no free slots are found, drop current weapon, and replace it with the new one
var droppedWeapon = Commons.InstantiateInCurrentLevel(DroppableWeaponPrefab, GetComponentInParent<PickupBase>().transform.position).GetComponentInChildren<DroppedWeaponPickup>();
droppedWeapon.Weapon = Commons.Inventory.WeaponSlots[Commons.Inventory.SelectedWeaponSlot];
Commons.Inventory.WeaponSlots[Commons.Inventory.SelectedWeaponSlot] = instance;
}
}
|
b93126a770467ca37715d2ae1144efcb9503888c
|
C#
|
lajohnston/LemballEditor
|
/app/models/Objects/RotatableObject.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
namespace LemballEditor.Model
{
public abstract class RotatableObject : LevelObject
{
/// <summary>
///
/// </summary>
public bool Rotated { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="isoX"></param>
/// <param name="isoY"></param>
public RotatableObject(ushort id, ushort isoX, ushort isoY)
: base(id, isoX, isoY)
{
Rotated = false;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
public RotatableObject(ushort id)
: this(id, 0, 0)
{
}
/// <summary>
///
/// </summary>
public void Rotate()
{
// Invert the rotate value
Rotated = !Rotated;
// Inform interface
Program.OnObjectAlteration(this);
}
/// <summary>
///
/// </summary>
/// <param name="element"></param>
public RotatableObject(XmlElement element)
: base(element)
{
if (element.HasAttribute("rotated"))
Rotated = Convert.ToBoolean(element.GetAttribute("rotated"));
else
Rotated = false;
}
protected override XmlElement CompileXml(XmlElement element)
{
// Rotation
if (Rotated)
element.SetAttribute("rotated", "true");
// Position
return base.CompileXml(element);
}
}
}
|
4f085f74d2868cd3c39bbd7fa92a4f0fc7cf973c
|
C#
|
davuxcom/Deferno
|
/Deferno/User.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Deferno
{
class User
{
public System.Windows.Controls.TreeViewItem TreeItem { get; set; }
IRCLib.User u = null;
public User(IRCLib.User user)
{
u = user;
u.OnQuit += new IRCLib.User.QuitHandler(u_OnQuit);
u.OnModeChanged += new IRCLib.User.ModeChanged(u_OnModeChanged);
u.OnNickChanged += new IRCLib.User.NickChanged(u_OnNickChanged);
}
void u_OnNickChanged(string old, string newNick)
{
}
void u_OnModeChanged(IRCLib.User u)
{
throw new NotImplementedException();
}
void u_OnQuit(IRCLib.User u, string msg)
{
throw new NotImplementedException();
}
public override string ToString()
{
return u.DisplayMode + u.Nick;
}
public string Nick
{
get
{
return u.Nick;
}
}
public string Host
{
get
{
return u.Host;
}
}
public string UserName
{
get
{
return u.UserName;
}
}
}
}
|
b2767d79d316a36de70829c880159ce563207506
|
C#
|
danielpetisme/jhipster-net-sample-app-template
|
/src/JHipsterNetSampleApplication/Data/Extensions/DbSetExtensions.cs
| 2.734375
| 3
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace JHipsterNetSampleApplication.Data.Extensions {
public static class DbSetExtensions {
public static EntityEntry<TEntity> RemoveById<TEntity>(this DbSet<TEntity> receiver, object id)
where TEntity : class
{
var container = Activator.CreateInstance<TEntity>();
var idProperty = GetKeyProperty(container.GetType());
idProperty.SetValue(container, id, null);
receiver.Attach(container);
return receiver.Remove(container);
}
private static PropertyInfo GetKeyProperty(Type type)
{
var key = type.GetProperties().FirstOrDefault(p =>
p.Name.Equals("ID", StringComparison.OrdinalIgnoreCase)
|| p.Name.Equals(type.Name + "ID", StringComparison.OrdinalIgnoreCase));
if (key != null) return key;
key = type.GetProperties().FirstOrDefault(p =>
p.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute)));
if (key != null) return key;
//https://stackoverflow.com/questions/25141955/entityframework-6-how-to-get-identity-field-with-reflection
//TODO complete with FluentAPi
return null;
}
}
}
|
2f60dafb8d0c1c0513e4c9ad1917ab24dab4d682
|
C#
|
mtremion/Package-Menu
|
/PackageMenu/Assets/Scripts/DataBase/DataBaseAdd.cs
| 2.671875
| 3
|
using System;
using UnityEngine;
using MySql.Data.MySqlClient;
/// <summary>
/// This class contains function(s) to add data(s) in base.
/// </summary>
public class DataBaseAdd : MonoBehaviour
{
#region Private Members
DataBaseManager _dbManager = null;
MySqlConnection _con = null;
MySqlCommand _cmdSql = null;
MySqlDataReader _dataReader = null;
string _cmd = "";
#endregion
#region System
private void Awake()
{
_dbManager = GetComponent<DataBaseManager>();
}
#endregion
#region Main Methods
/// <summary>
/// Function use to change a password in the base.
/// </summary>
/// <param name="email">Email of the player that we want to change the password.</param>
/// <param name="newPassword">The new password.</param>
public void AddImgProfile(string pseudo, string str)
{
_con = _dbManager.m_dbConnection.m_con;
_cmd = "SELECT imgPlayerImage FROM playerimage WHERE idPlayer = (SELECT idPlayer from player WHERE pseudoPlayer = '" + pseudo + "')";
_cmdSql = new MySqlCommand(_cmd, _con);
try
{
Debug.Log("JE SELECT");
_dataReader = _cmdSql.ExecuteReader();
if(_dataReader.Read())
{
_dataReader.Close();
_cmd = "UPDATE playerimage SET imgPlayerImage = '" + str + "' WHERE idPlayer = (SELECT idPlayer from player WHERE pseudoPlayer = '" + pseudo + "')";
_cmdSql = new MySqlCommand(_cmd, _con);
try
{
_dataReader = _cmdSql.ExecuteReader();
_dataReader.Close();
_dbManager.m_dbGet.GetProfileImage(pseudo);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
else
{
_dataReader.Close();
_cmd = "INSERT INTO playerimage(idPlayer, imgPlayerImage) VALUES ( (SELECT idPlayer from player WHERE pseudoPlayer = '" + pseudo + "' ), '" + str + "' ) ";
_cmdSql = new MySqlCommand(_cmd, _con);
try
{
Debug.Log("J'INSERT");
_dataReader = _cmdSql.ExecuteReader();
_dataReader.Close();
_dbManager.m_dbGet.GetProfileImage(pseudo);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
_dataReader.Close();
}
#endregion
}
|
d086b951dd5935b6f820dd306c50c160b31837ed
|
C#
|
steamb23/Ahheui-CSharp
|
/Ahheui/Storages/Stack.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SteamB23.Ahheui.Storages
{
public class Stack : IStorage
{
Stack<double> stack;
public Stack()
{
stack = new Stack<double>();
}
public Stack(IEnumerable<double> collection)
{
stack = new Stack<double>(collection);
}
public Stack(int capacity)
{
stack = new Stack<double>(capacity);
}
void IStorage.Push(double item)
{
stack.Push(item);
}
double IStorage.Pop()
{
return stack.Pop();
}
double IStorage.Peek()
{
return stack.Peek();
}
void IStorage.Clear()
{
stack.Clear();
}
}
}
|
3793972f3f8dab37c70308647faca3748c9d2ae2
|
C#
|
shendongnian/download4
|
/code8/1349562-36448031-115010517-4.cs
| 2.578125
| 3
|
public ActionResult ViewA()
{
var sizeChoicesFromDb = "40,41,42,43"; // get from db
var myModel = new MyViewModel
{
SizeChoices = sizeChoicesFromDb .Split(',').ToList().ConvertAll(Int32.Parse)
};
return View(myModel);
}
|
c1b6f026c184bfb320a8020491ce8e8cc6c12e17
|
C#
|
shendongnian/download4
|
/first_version_download2/302138-43576239-143803054-2.cs
| 2.96875
| 3
|
private Expression<Func<Goods, bool>> LambdaConstructor (string propertyName, string inputText, Condition condition)
{
var item = Expression.Parameter(typeof(Goods), "item");
var prop = Expression.Property(item, propertyName);
var propertyInfo = typeof(Goods).GetProperty(propertyName);
var value = Expression.Constant(Convert.ChangeType(inputText, propertyInfo.PropertyType));
BinaryExpression equal;
switch (condition)
{
case Condition.eq:
equal = Expression.Equal(prop, value);
break;
case Condition.gt:
equal = Expression.GreaterThan(prop, value);
break;
case Condition.gte:
equal = Expression.GreaterThanOrEqual(prop, value);
break;
case Condition.lt:
equal = Expression.LessThan(prop, value);
break;
case Condition.lte:
equal = Expression.LessThanOrEqual(prop, value);
break;
default:
equal = Expression.Equal(prop, value);
break;
}
var lambda = Expression.Lambda<Func<Goods, bool>>(equal, item);
return lambda;
}
|
4e33a123080ec9aac86ae892a932836343452e01
|
C#
|
hach-que/RedMeansGo
|
/RedMeansGo/Pathing/BoringPath.cs
| 2.90625
| 3
|
//
// This source code is licensed in accordance with the licensing outlined
// on the main Tychaia website (www.tychaia.com). Changes to the
// license on the website apply retroactively.
//
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace RedMeansGo.Pathing
{
public class BoringPath : IPath
{
public IEnumerable<Vector2> YieldPositions(params object[] arguments)
{
var b = 300;
var invert = 1;
if (arguments.Length > 0 && (bool)arguments[0])
{
b = 500;
invert = -1;
}
for (var i = -20; i < 200; i++)
yield return new Vector2(b + (float)Math.Cos(i / 20.0) * 50 * invert, i * 2);
for (var i = 0; i < 300; i++)
yield return new Vector2(b + (float)Math.Cos(10) * 50 * invert + i * 2 * invert, 400 + (float)Math.Sin(i / 20.0) * 50);
}
}
}
|
fae024a107e07c84cce98ad0779c39f2f6df7b6b
|
C#
|
hicknhack-software/Twofold.Net
|
/src/Twofold.Core/Compilation/Rules/CallRule.cs
| 2.515625
| 3
|
/* Twofold.Net
* (C) Copyright 2016 HicknHack Software GmbH
*
* The original code can be found at:
* https://github.com/hicknhack-software/Twofold.Net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace HicknHack.Twofold.Compilation.Rules
{
using Extensions;
using Abstractions;
using Abstractions.Compilation;
using System.Collections.Generic;
/// <summary>
/// Rule which handles a template method call: "= <statement>"
/// </summary>
internal class CallRule : IParserRule
{
public List<AsbtractRenderCommand> Parse(FileLine line, IMessageHandler messageHandler)
{
var commands = new List<AsbtractRenderCommand>();
//
var beginSpan = line.CreateOriginalTextSpan(line.BeginNonSpace, line.BeginNonSpace + 1); //skip matched character
var scriptBegin = line.Text.IndexOfNot(beginSpan.End, line.End, CharExtensions.IsSpace);
var indentationSpan = line.CreateOriginalTextSpan(beginSpan.End, scriptBegin);
if (indentationSpan.IsEmpty == false)
{
var endSpan = line.CreateOriginalTextSpan(indentationSpan.End, indentationSpan.End);
commands.Add(new PushIndentationCommand(beginSpan, indentationSpan, endSpan));
}
//
var statementSpan = line.CreateOriginalTextSpan(indentationSpan.End, line.End);
var statementEndSpan = line.CreateOriginalTextSpan(statementSpan.End, statementSpan.End);
if (statementSpan.IsEmpty == false)
{
commands.Add(new StatementCommand(statementSpan, statementEndSpan));
}
//
if (indentationSpan.IsEmpty == false)
{
var popIndentationSpan = line.CreateOriginalTextSpan(line.End, line.End);
commands.Add(new PopIndentationCommand(popIndentationSpan));
}
return commands;
}
}
}
|
9fa48681def22d8106ed55e1cd0ce25deddf8bb2
|
C#
|
oscarcarlsson93/AcceleratedLearning
|
/MVC/Mvc02/Mvc02/Services/AuthService.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Mvc02.Models.ViewModels;
namespace Mvc02.Services
{
public class AuthService
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AuthService(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_roleManager = roleManager;
_signInManager = signInManager;
}
internal async Task<bool> UserExist(string email)
{
IdentityUser user = await _userManager.FindByEmailAsync(email);
return user != null;
}
internal async Task AddRoleToUser(AddRoleVm addrole)
{
if (!await _roleManager.RoleExistsAsync(addrole.Role))
await CreateRolesAsync(addrole.Role);
IdentityUser user = await _userManager.FindByEmailAsync(addrole.Email);
await _userManager.AddToRoleAsync(user, addrole.Role);
}
internal async Task<List<IdentityUser>> GetAllUsers()
{
List<IdentityUser> users = await _userManager.Users.ToListAsync();
var hejsan = await _userManager.GetRolesAsync(users[0]);
List<string> rolesList = new List<string>();
//rolesList.Add(hejsan);
//return users[0].Email.ToString();
return users;
}
internal async Task CreateRolesAsync(string role)
{
var newRole = new IdentityRole();
newRole.Name = role;
await _roleManager.CreateAsync(newRole);
}
// din kod här
}
}
|