text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class IncorruptEdu_TestOnlineResultList : System.Web.UI.Page
{
public string t_rand = "";
PDTech.OA.BLL.TestOnline toBll = new PDTech.OA.BLL.TestOnline();
PDTech.OA.BLL.OA_TEST_ANSWER answerBll = new PDTech.OA.BLL.OA_TEST_ANSWER();
PDTech.OA.BLL.TestAnswer taBll = new PDTech.OA.BLL.TestAnswer();
protected void Page_Load(object sender, EventArgs e)
{
t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff");
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
int record = 0;
IList<PDTech.OA.Model.TestAnswer> taList = new List<PDTech.OA.Model.TestAnswer>();
string title = AidHelp.FilterSpecial(txtTitle.Text);
if (!string.IsNullOrEmpty(title))
{
taList = taBll.Get_Paging_List(CurrentAccount.USER_ID, title, AspNetPager.PageSize, AspNetPager.CurrentPageIndex, out record);
}
else
{
taList = taBll.Get_Paging_List(CurrentAccount.USER_ID, null, AspNetPager.PageSize, AspNetPager.CurrentPageIndex, out record);
}
rpt_TestList.DataSource = taList;
rpt_TestList.DataBind();
AspNetPager.RecordCount = record;
}
public decimal GetTotalScore(string answerId)
{
decimal totalScore = 0;
IList<PDTech.OA.Model.OA_TEST_ANSWER> answerList = answerBll.GetModelList(" EDU_A_GUID = '" + answerId + "'");
foreach (PDTech.OA.Model.OA_TEST_ANSWER item in answerList)
{
totalScore += item.SCORE.Value;
}
return totalScore;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindData();
}
protected void AspNetPager_PageChanged(object sender, EventArgs e)
{
BindData();
}
} |
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public AchievementController AchievementController;
private bool inStealthMode = false;
private int currentDaysCount = 0;
private int numRedPotions = 0;
private int numBluePotions = 0;
private int numGreenPotions = 0;
void Start()
{
}
private void AnotherSmokingFreeDay()
{
currentDaysCount++;
AchievementController.AddCountToAchievement("1st day", 1.0f);
AchievementController.AddCountToAchievement("1st week", 1.0f);
}
void Update()
{
if (inStealthMode)
{
AchievementController.AddCountToAchievement("The Sports Man", Time.deltaTime);
}
}
void OnGUI()
{
float xPosition = 600.0f;
GUI.Label(new Rect(xPosition, 25.0f, 150.0f, 25.0f), "Smoking-free days: " + currentDaysCount);
if (GUI.Button (new Rect (xPosition + 150.0f, 25.0f, 100.0f, 25.0f), "Another day!"))
{
AnotherSmokingFreeDay ();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoreComponents
{
public static class PrimativeConstants
{
static List<Type> TypeList;
public static readonly Type byte_Type;
public static readonly Type ushort_Type;
public static readonly Type uint_Type;
public static readonly Type ulong_Type;
public static readonly Type sbyte_Type;
public static readonly Type short_Type;
public static readonly Type int_Type;
public static readonly Type long_Type;
public static readonly Type string_Type;
public static readonly Type bool_Type;
public static readonly Type char_Type;
public static readonly Type float_Type;
public static readonly Type double_Type;
public static readonly Type object_Type;
public static readonly Type DateTime_Type;
public static readonly Type TimeSpan_Type;
public static readonly Type Decimal_Type;
public static readonly Type Guid_Type;
public static readonly Type Array_Type;
public static readonly Type decimal_Type;
static PrimativeConstants()
{
byte_Type = typeof(byte);
ushort_Type = typeof(ushort);
uint_Type = typeof(uint);
ulong_Type = typeof(ulong);
sbyte_Type = typeof(sbyte);
short_Type = typeof(short);
int_Type = typeof(int);
long_Type = typeof(long);
string_Type = typeof(string);
bool_Type = typeof(bool);
byte_Type = typeof(byte);
char_Type = typeof(char);
float_Type = typeof(float);
double_Type = typeof(double);
object_Type = typeof(object);
DateTime_Type = typeof(DateTime);
TimeSpan_Type = typeof(TimeSpan);
decimal_Type = typeof(decimal);
Guid_Type = typeof(Guid);
Array_Type = typeof(Array);
TypeList = new List<Type>();
TypeList.Add(byte_Type);
TypeList.Add(ushort_Type);
TypeList.Add(uint_Type);
TypeList.Add(ulong_Type);
TypeList.Add(sbyte_Type);
TypeList.Add(short_Type);
TypeList.Add(int_Type);
TypeList.Add(long_Type);
TypeList.Add(string_Type);
TypeList.Add(byte_Type);
TypeList.Add(char_Type);
TypeList.Add(float_Type);
TypeList.Add(double_Type);
TypeList.Add(object_Type);
TypeList.Add(DateTime_Type);
TypeList.Add(TimeSpan_Type);
TypeList.Add(decimal_Type);
TypeList.Add(Guid_Type);
TypeList.Add(Array_Type);
}
public static Type[] GetTypeArray()
{
return TypeList.ToArray();
}
}
}
|
using Hayalpc.Fatura.Data.Models;
namespace Hayalpc.Fatura.Panel.Internal.Services.Interfaces
{
public interface IInstitutionService : IBaseService<Institution>
{
}
}
|
using AssetHub.DAL;
using AssetHub.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AssetHub.Infrastructure
{
public class AssetHubUserManager : UserManager<User>
{
public AssetHubUserManager(IUserStore<User> store) : base(store) { }
public static AssetHubUserManager Create(IdentityFactoryOptions<AssetHubUserManager> options, IOwinContext context)
{
var db = context.Get<AssetHubContext>();
var manager = new AssetHubUserManager(new UserStore<User>(db));
manager.UserValidator = new AssetHubUserValidator(manager)
{
RequireUniqueEmail = true,
};
return manager;
}
}
} |
using System.Collections.Generic;
using UnityEngine;
using SanAndreasUnity.Net;
using SanAndreasUnity.Utilities;
using System.Linq;
namespace SanAndreasUnity.Behaviours
{
public class SpawnManager : MonoBehaviour
{
public static SpawnManager Instance { get; private set; }
List<Transform> m_spawnPositions = new List<Transform>();
GameObject m_container;
public bool spawnPlayerWhenConnected = true;
public bool IsSpawningPaused { get; set; } = false;
public float spawnInterval = 4f;
float m_lastSpawnTime = 0f;
void Awake()
{
Instance = this;
}
void Start()
{
this.InvokeRepeating(nameof(RepeatedMethod), 1f, 1f);
Player.onStart += OnPlayerConnected;
}
void OnLoaderFinished()
{
if (!NetStatus.IsServer)
return;
// spawn players that were connected during loading process - this will always be the case for
// local player
UpdateSpawnPositions();
SpawnPlayers();
}
Transform GetSpawnFocusPos()
{
if (Ped.Instance)
return Ped.Instance.transform;
if (Camera.main)
return Camera.main.transform;
return null;
}
void RepeatedMethod()
{
if (!NetStatus.IsServer)
return;
this.UpdateSpawnPositions();
if (this.IsSpawningPaused)
return;
if (Time.time - m_lastSpawnTime >= this.spawnInterval)
{
// enough time passed
m_lastSpawnTime = Time.time;
this.SpawnPlayers();
}
}
void UpdateSpawnPositions()
{
if (!Loader.HasLoaded)
return;
if (!NetStatus.IsServer)
return;
Transform focusPos = GetSpawnFocusPos();
if (null == focusPos)
return;
if (null == m_container)
{
// create parent game object for spawn positions
m_container = new GameObject("Spawn positions");
// create spawn positions
m_spawnPositions.Clear();
for (int i = 0; i < 5; i++)
{
Transform spawnPos = new GameObject("Spawn position " + i).transform;
spawnPos.SetParent(m_container.transform);
m_spawnPositions.Add(spawnPos);
//NetManager.AddSpawnPosition(spawnPos);
}
}
// update spawn positions
m_spawnPositions.RemoveDeadObjects();
foreach (Transform spawnPos in m_spawnPositions)
{
spawnPos.position = focusPos.position + Random.insideUnitCircle.ToVector3XZ() * 15f;
}
}
void SpawnPlayers()
{
if (!NetStatus.IsServer)
return;
if (!Loader.HasLoaded)
return;
//var list = NetManager.SpawnPositions.ToList();
var list = m_spawnPositions;
list.RemoveDeadObjects();
if (list.Count < 1)
return;
foreach (var player in Player.AllPlayers)
{
SpawnPlayer(player, list);
}
}
public static Ped SpawnPlayer (Player player, List<Transform> spawns)
{
if (player.OwnedPed != null)
return null;
var spawn = spawns.RandomElement();
var ped = Ped.SpawnPed(Ped.RandomPedId, spawn.position, spawn.rotation, false);
ped.NetPlayerOwnerGameObject = player.gameObject;
ped.WeaponHolder.autoAddWeapon = true;
// this ped should not be destroyed when he gets out of range
ped.gameObject.DestroyComponent<OutOfRangeDestroyer>();
NetManager.Spawn(ped.gameObject);
player.OwnedPed = ped;
Debug.LogFormat("Spawned ped {0} for player {1}, time: {2}", ped.DescriptionForLogging, player.DescriptionForLogging,
F.CurrentDateForLogging);
return ped;
}
void OnPlayerConnected(Player player)
{
if (!NetStatus.IsServer)
return;
if (!Loader.HasLoaded) // these players will be spawned when loading process finishes
return;
if (!this.spawnPlayerWhenConnected)
return;
m_spawnPositions.RemoveDeadObjects();
SpawnPlayer(player, m_spawnPositions);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Planning
{
class PPOrder
{
public string type="";
public PrivacyPreservingLandmark lendmark1 = null;
public PrivacyPreservingLandmark lendmark2 = null;
public PPOrder(string typ, PrivacyPreservingLandmark l1, PrivacyPreservingLandmark l2)
{
type = typ;
lendmark1 = l1;
lendmark2 = l2;
}
public override string ToString()
{
string str = "";
str=lendmark1.ToString()+" --> "+lendmark2.ToString();
return str;
}
}
}
|
using HZH_Controls.Forms;
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 WinForm.UI
{
public partial class FormPrint :FrmWithOKCancel2
{
public FormPrint()
{
InitializeComponent();
}
protected override void DoEnter()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GSF;
using GSF.Concurrency;
namespace Server.LoadBalancing
{
/// <summary>
/// 이 인터페이스를 상속받아 로드밸런서를 구현한다.
/// </summary>
interface ILoadBalancer
{
/// <summary>
/// 초기화.
/// 초기부터 가지고 시작하는 호스트 목록이 인자로 들어옴
/// </summary>
/// <param name="hosts">서버 호스트 목록</param>
void Initialize(string[] hosts);
/// <summary>
/// 다음번에 접속할 호스트 주소를 가져온다.
/// </summary>
/// <returns>서버 호스트 주소</returns>
[ThreadSafe]
string GetNext();
}
}
|
using Library.DomainModels;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Library.Services.Interface
{
public interface IAuthorService
{
Task<Author> Create(string name);
Task<IEnumerable<Author>> GetAll();
Task<Author> GetById(int id);
Task<Author> GetByName(string name);
Task<Author> UpdateAuthor(Author author);
Task<Author> UpdateIsAlive(int id, bool isAlive);
Task DeleteAuthorById(int id);
}
}
|
//
// commercio.sdk - Sdk for Commercio Network
//
// Riccardo Costacurta
// Dec. 30, 2019
// BlockIt s.r.l.
//
/// Allows to easily generate new keys either to be used with AES or RSA key.
//
using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Asn1.X9;
namespace commercio.sdk
{
public class KeysHelper
{
#region Properties
#endregion
#region Constructors
#endregion
#region Public Methods
/// Generate a random nonce
public static byte[] generateRandomNonce(int length, int bit = 256)
{
DigestRandomGenerator wkRandomGenerator = new Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator(new Sha512Digest());
SecureRandom secureRandomGenerator = new SecureRandom(wkRandomGenerator);
List<byte> wkNonce = new List<byte>();
for (int i = 0; i < length; i++)
{
wkNonce.Add((byte) secureRandomGenerator.Next(0, bit));
}
byte[] nonce = wkNonce.ToArray();
return nonce;
}
public static byte[] generateRandomNonceUtf8(int length)
{
return generateRandomNonce(length, bit: 128);
}
/// Generates a new AES key having the desired [length].
// public static async Task<KeyParameter> generateAesKey(int length = 256)
public static KeyParameter generateAesKey(int length = 256)
{
// Get a secure random
SecureRandom mySecureRandom = _getSecureRandom();
// mySecureRandom.GenerateSeed generates byte[], so I must divide by 8 to have the intended number of bits (not by 16 as in Dart code)
KeyParameter key = new KeyParameter(mySecureRandom.GenerateSeed(length / 8));
return key;
}
/// Generates a new RSA key pair having the given [bytes] length.
/// If no length is specified, the default is going to be 2048.
// public static async Task<KeyPair> generateRsaKeyPair(int bytes = 2048)
public static KeyPair generateRsaKeyPair(int bytes = 2048, String type = null)
{
SecureRandom secureRandom = _getSecureRandom();
RsaKeyGenerationParameters keyGenerationParameters = new RsaKeyGenerationParameters(new BigInteger("65537", 10), secureRandom, bytes, 5);
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
AsymmetricCipherKeyPair rsaKeys = keyPairGenerator.GenerateKeyPair();
RsaKeyParameters rsaPubRaw = (RsaKeyParameters)rsaKeys.Public;
RsaKeyParameters rsaPrivRaw = (RsaKeyParameters)rsaKeys.Private;
// Return the key
return new KeyPair(new RSAPublicKey(rsaPubRaw, keyType: type), new RSAPrivateKey(rsaPrivRaw));
}
/// Generates a new random EC key pair.
// public static async Task<KeyPair> generateEcKeyPair()
public static KeyPair generateEcKeyPair( String type = null)
{
var curve = ECNamedCurveTable.GetByName("secp256k1");
ECDomainParameters domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
SecureRandom secureRandom = _getSecureRandom();
ECKeyGenerationParameters keyParams = new ECKeyGenerationParameters(domainParams, secureRandom);
ECKeyPairGenerator generator = new ECKeyPairGenerator("ECDSA");
generator.Init(keyParams);
AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
ECPrivateKeyParameters privateKey = keyPair.Private as ECPrivateKeyParameters;
ECPublicKeyParameters publicKey = keyPair.Public as ECPublicKeyParameters;
return new KeyPair(new ECPublicKey(publicKey, keyType: type), new ECPrivateKey(privateKey));
}
#endregion
#region Helpers
/// Generates a SecureRandom
/// C# has not a fortuna random generator, Just trying an approach with DigestRandomGenerator from BouncyCastle
private static SecureRandom _getSecureRandom()
{
// Start from a crypto seed from C# libraries
System.Security.Cryptography.RNGCryptoServiceProvider rngCsp = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] randomBytes = new byte[32];
rngCsp.GetBytes(randomBytes);
// Get a first random generator from BouncyCastle
VmpcRandomGenerator firstRandomGenerator = new Org.BouncyCastle.Crypto.Prng.VmpcRandomGenerator();
firstRandomGenerator.AddSeedMaterial(randomBytes);
byte[] seed = new byte[32];
firstRandomGenerator.NextBytes(seed, 0, 32);
// Create and seed the final Random Generator
DigestRandomGenerator wkRandomGenerator = new Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator(new Sha512Digest());
SecureRandom secureRandomGenerator = new SecureRandom(wkRandomGenerator);
secureRandomGenerator.SetSeed(seed);
return secureRandomGenerator;
}
#endregion
}
} |
using ProManager.Entities.Base;
using ProManager.Entities.SystemAdmin;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProManager.Entities.AgentAdmin
{
public class Agent_ServiceType : BaseTenantModel
{
[StringLength(30)]
public string Code { get; set; }
[StringLength(500)]
public string Description { get; set; }
public short Weight { get; set; }
public short Sort { get; set; }
public Guid? SystemServiceTypeId { get; set; }
[ForeignKey("SystemServiceTypeId")]
public virtual System_ServiceType System_ServiceType { get; set; }
}
}
|
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Xamarin.Forms;
using FractlExplorer.Utility;
using FractlExplorer.UWP;
[assembly: Dependency(typeof(ImageCreator))]
namespace FractlExplorer.UWP
{
public class ImageCreator : IImageCreator
{
public double ScaleFactor {
get
{
return DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
}
}
public Task<Stream> CreateAsync(int[] data, int width, int height)
{
return Task.Run(async () =>
{
var pixels = new byte[data.Length * sizeof(int)];
System.Buffer.BlockCopy(data, 0, pixels, 0, pixels.Length);
InMemoryRandomAccessStream mras = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(
BitmapEncoder.PngEncoderId, mras);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
(uint)width, (uint)height, 96, 96, pixels);
await encoder.FlushAsync();
mras.Seek(0);
return mras.AsStreamForRead();
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float unitPerSecs = 5;
private float anchoMundo = 6.7f;
void Update()
{
//Obtenemos el sentido de movimiento
float dir = Input.GetAxis("Horizontal");
//Calculamos el espacio deltax en base al sentido y la velocidad
float deltaX = dir * unitPerSecs * Time.deltaTime;
//DADO que no hay Rigidbody ==> Translate
if (transform.position.x + deltaX < anchoMundo && transform.position.x + deltaX > -anchoMundo)
transform.Translate(deltaX, 0, 0);
}
}
|
using System;
using System.Collections.Generic;
using Pfim;
using UnityEngine;
namespace Assets.FarmSim
{
public abstract class TextureLoader
{
private static readonly Dictionary<string, Texture2D> Cache = new Dictionary<string, Texture2D>();
private static Texture2D LoadTextureFromBytes(byte[] bytes, int width, int height, TextureFormat format, bool mipmap)
{
Texture2D texture;
try
{
texture = new Texture2D(width, height, format, mipmap, false);
texture.LoadRawTextureData(bytes);
texture.Apply();
}
catch (UnityException)
{
// Failed to load, usually is due to the texture data specifying that it has mipmaps but then doesn't contain enough data for all mipmaps??
// Load the texture without mipmap support
// In future: add some method for unity to compute mipmaps here instead
texture = new Texture2D(width, height, format, false, false);
texture.LoadRawTextureData(bytes);
texture.Apply();
}
return texture;
}
/// <summary>
/// Parses any DXT texture from raw bytes including header using Pfim.
/// </summary>
/// <param name="bytes"></param>
/// <param name="mipmap">Does the texture contain mipmap data</param>
/// <returns></returns>
private static Texture2D LoadTexturePfim(byte[] bytes, bool mipmap)
{
IImage imageData = Dds.Create(bytes, new PfimConfig());
imageData.Decompress();
ImageFormat frmt = imageData.Format;
TextureFormat texFrmt;
switch (imageData.Format)
{
case ImageFormat.Rgb24:
texFrmt = TextureFormat.RGB24;
break;
case ImageFormat.Rgba32:
texFrmt = TextureFormat.RGBA32;
break;
default:
throw new Exception($"Unknown raw image format {frmt}");
}
return LoadTextureFromBytes(imageData.Data, imageData.Width, imageData.Height, texFrmt, mipmap);
}
/// <summary>
/// Parses a DDS texture from raw bytes including header. If DXT3 is detected, Pfim is used instead since Unity doesn't natively support DXT3.
/// </summary>
/// <param name="ddsBytes"></param>
/// <returns></returns>
private static Texture2D LoadTextureDDS(byte[] ddsBytes)
{
byte ddsSizeCheck = ddsBytes[0x4];
if (ddsSizeCheck != 124)
throw new Exception("Invalid DDS DXTn texture. Unable to read"); //this header byte should be 124 for DDS image files
int height = ddsBytes[0xF] << 24 | ddsBytes[0xE] << 16 | ddsBytes[0xD] << 8 | ddsBytes[0xC];
int width = ddsBytes[0x13] << 24 | ddsBytes[0x12] << 16 | ddsBytes[0x11] << 8 | ddsBytes[0x10];
int mipmapCount = ddsBytes[0x1F] << 24 | ddsBytes[0x1E] << 16 | ddsBytes[0x1D] << 8 | ddsBytes[0x1C];
bool hasMipMaps = mipmapCount > 0;
TextureFormat textureFormat;
string texFormatStr = System.Text.Encoding.ASCII.GetString(ddsBytes, 0x54, 4);
switch (texFormatStr)
{
case "DXT1":
textureFormat = TextureFormat.DXT1;
break;
case "DXT3":
return LoadTexturePfim(ddsBytes, hasMipMaps);
case "DXT5":
textureFormat = TextureFormat.DXT5;
break;
default:
throw new Exception($"Unknown texture format {texFormatStr}");
}
const int ddsHeaderSize = 128;
byte[] dxtBytes = new byte[ddsBytes.Length - ddsHeaderSize];
Buffer.BlockCopy(ddsBytes, ddsHeaderSize, dxtBytes, 0, ddsBytes.Length - ddsHeaderSize);
return LoadTextureFromBytes(dxtBytes, width, height, textureFormat, hasMipMaps);
}
private static Texture2D LoadTexturePNGOrJPG(byte[] bytes)
{
Texture2D ret = new Texture2D(1, 1);
ret.LoadImage(bytes);
return ret;
}
public static Texture2D GetTexture(string url)
{
if (Cache.ContainsKey(url))
{
return Cache[url];
}
byte[] bytes = System.IO.File.ReadAllBytes(url);
Texture2D ret;
if (bytes[0] == 'D' && bytes[1] == 'D' && bytes[2] == 'S') // DDS
ret = LoadTextureDDS(bytes);
else if(bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G') // PNG
ret = LoadTexturePNGOrJPG(bytes);
else if (bytes[0] == 0xFF && bytes[1] == 0xD8) // JPG
ret = LoadTexturePNGOrJPG(bytes);
else
throw new Exception($"Unknown image format for {url}");
Cache[url] = ret;
return ret;
}
}
}
|
using AutoMapper;
using LuizalabsWishesManager.Domains.Repositories;
using LuizalabsWishesManager.Domains.Services;
using LuizalabsWishesManager.Services;
using Microsoft.Extensions.DependencyInjection;
using LuizalabsWishesManager.Data.Repositories;
namespace LuizalabsWishesManager.Shared
{
public class IoC
{
public static void RegisterMappings(IServiceCollection services)
{
services.AddTransient<IMapper, Mapper>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IProductService, ProductService>();
services.AddTransient<IWishService, WishService>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IProductRepository, ProductRepository>();
services.AddTransient<IWishRepository, WishRepository>();
services.AddTransient<IWishProductRepository, WishProductRepository>();
}
}
}
|
using System.Threading.Tasks;
using vega.API.Core.Models;
namespace vega.API.Core
{
public interface IModelRepository
{
void CreateModel(Model model);
Task<Model> GetModelById(int modelId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Accounting.Entity;
using System.Data.SqlClient;
using System.Data;
using Accounting.Utility;
namespace Accounting.DataAccess
{
public class DaOrder
{
public DaOrder() { }
public static DataTable GetOrders(string Where, string OrderBy)
{
DataTable dt = new DataTable();
try
{
using (SqlDataAdapter da = new SqlDataAdapter("SP_GET_Orders", ConnectionHelper.getConnection()))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@Where", SqlDbType.NVarChar, 500).Value = Where;
if (OrderBy != string.Empty)
da.SelectCommand.Parameters.Add("@OrderBy", SqlDbType.NVarChar, 500).Value = OrderBy;
da.Fill(dt);
da.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
public int saveUpdateOrderMaster(Order_Master obOrder_Master, SqlConnection con)
{
SqlCommand com = null;
SqlTransaction trans = null;
int lastID = 0;
try
{
com = new SqlCommand();
trans = con.BeginTransaction("11");
com.Transaction = trans;
com.Connection = con;
com.CommandText = "spSaveUpdateOrder_Master";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = obOrder_Master.OrderMID;
com.Parameters.Add("@OrderNo", SqlDbType.VarChar, 100).Value = obOrder_Master.OrderNo;
com.Parameters.Add("@OrderType", SqlDbType.VarChar, 50).Value = obOrder_Master.OrderType;
com.Parameters.Add("@OrderDate", SqlDbType.DateTime).Value = obOrder_Master.OrderDate;
com.Parameters.Add("@CustomerID", SqlDbType.Int).Value = obOrder_Master.CustomerID;
if (obOrder_Master.DeliveryDate == new DateTime(1900, 1, 1))
com.Parameters.Add("@DeliveryDate", SqlDbType.DateTime).Value = DBNull.Value;
else
com.Parameters.Add("@DeliveryDate", SqlDbType.DateTime).Value = obOrder_Master.DeliveryDate;
if (obOrder_Master.FactoryID <= 0)
com.Parameters.Add("@FactoryID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@FactoryID", SqlDbType.Int).Value = obOrder_Master.FactoryID;
com.Parameters.Add("@LedgerNo", SqlDbType.VarChar, 100).Value = obOrder_Master.LedgerNo;
com.Parameters.Add("@TotalOrderQty", SqlDbType.Money).Value = obOrder_Master.TotalOrderQty;
if (obOrder_Master.UnitID <= 0)
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = obOrder_Master.UnitID;
com.Parameters.Add("@OrderValue", SqlDbType.Money).Value = obOrder_Master.OrderValue;
if (obOrder_Master.CurrencyID <= 0)
com.Parameters.Add("@CurrencyID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@CurrencyID", SqlDbType.Int).Value = obOrder_Master.CurrencyID;
com.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
com.Parameters.Add("@UserID", SqlDbType.Int).Value = LogInInfo.UserID;
com.ExecuteNonQuery();
trans.Commit();
if (obOrder_Master.OrderMID == 0)
lastID = ConnectionHelper.GetID(con, "OrderMID", "Order_Master");
else
lastID = obOrder_Master.OrderMID;
//com.Parameters["@OrderMID"].Value;
}
catch (Exception ex)
{
trans.Rollback("11");
throw new Exception("Unable to Save or Update " + ex.Message);
}
return lastID;
}
public int saveUpdateOrder_Details(Order_Details obOrder_Details, SqlConnection con)
{
SqlCommand com = null;
SqlTransaction trans = null;
try
{
com = new SqlCommand();
trans = con.BeginTransaction();
com.Transaction = trans;
com.Connection = con;
com.CommandText = "spSaveUpdateOrder_Details";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderDID", SqlDbType.Int).Value = obOrder_Details.OrderDID;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = obOrder_Details.OrderMID;
com.Parameters.Add("@OrderQty", SqlDbType.Money).Value = obOrder_Details.OrderQty;
com.Parameters.Add("@ItemID", SqlDbType.Int).Value = obOrder_Details.ItemID;
if (obOrder_Details.UnitID <= 0)
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = obOrder_Details.UnitID;
if (obOrder_Details.PriceID <= 0)
com.Parameters.Add("@PriceID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@PriceID", SqlDbType.Int).Value = obOrder_Details.PriceID;
com.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = obOrder_Details.UnitPrice;
com.Parameters.Add("@OrderValue", SqlDbType.Money).Value = obOrder_Details.OrderValue;
com.Parameters.Add("@ColorCode", SqlDbType.VarChar, 100).Value = obOrder_Details.ColorCode;
com.Parameters.Add("@Labdip", SqlDbType.VarChar, 100).Value = obOrder_Details.Labdip;
com.Parameters.Add("@Remarks", SqlDbType.VarChar, 500).Value = obOrder_Details.Remarks;
com.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw new Exception("Unable to Save or Update " + ex.Message);
}
return 0;
}
public int saveUpdateOrderMaster(Order_Master obOrder_Master, SqlTransaction trans, SqlConnection con)
{
SqlCommand com = null;
int lastID = 0;
try
{
if (obOrder_Master.CompanyID <= 0) obOrder_Master.CompanyID = LogInInfo.CompanyID;
com = new SqlCommand("spSaveUpdateOrder_Master", con, trans);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = obOrder_Master.OrderMID;
com.Parameters.Add("@OrderNo", SqlDbType.VarChar, 100).Value = obOrder_Master.OrderNo;
com.Parameters.Add("@OrderType", SqlDbType.VarChar, 50).Value = obOrder_Master.OrderType;
com.Parameters.Add("@OrderDate", SqlDbType.DateTime).Value = obOrder_Master.OrderDate;
com.Parameters.Add("@CustomerID", SqlDbType.Int).Value = obOrder_Master.CustomerID;
if (obOrder_Master.DeliveryDate == new DateTime(1900, 1, 1))
com.Parameters.Add("@DeliveryDate", SqlDbType.DateTime).Value = DBNull.Value;
else
com.Parameters.Add("@DeliveryDate", SqlDbType.DateTime).Value = obOrder_Master.DeliveryDate;
if (obOrder_Master.FactoryID <= 0)
com.Parameters.Add("@FactoryID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@FactoryID", SqlDbType.Int).Value = obOrder_Master.FactoryID;
com.Parameters.Add("@LedgerNo", SqlDbType.VarChar, 100).Value = obOrder_Master.LedgerNo;
com.Parameters.Add("@TotalOrderQty", SqlDbType.Money).Value = obOrder_Master.TotalOrderQty;
if (obOrder_Master.UnitID <= 0)
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = obOrder_Master.UnitID;
com.Parameters.Add("@OrderValue", SqlDbType.Money).Value = obOrder_Master.OrderValue;
if (obOrder_Master.CurrencyID <= 0)
com.Parameters.Add("@CurrencyID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@CurrencyID", SqlDbType.Int).Value = obOrder_Master.CurrencyID;
com.Parameters.Add("@CompanyID", SqlDbType.Int).Value = obOrder_Master.CompanyID;
com.Parameters.Add("@UserID", SqlDbType.Int).Value = LogInInfo.UserID;
com.Parameters.Add("@Rate", SqlDbType.Money).Value = obOrder_Master.Rate;
com.Parameters.Add("@Buyer_ref", SqlDbType.VarChar, 500).Value = obOrder_Master.Buyer_ref;
com.ExecuteNonQuery();
//trans.Commit();
if (obOrder_Master.OrderMID == 0)
{
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(OrderMID),0) FROM Order_Master", con, trans);
lastID = Convert.ToInt32(cmd.ExecuteScalar());
}
else
lastID = obOrder_Master.OrderMID;
}
catch (Exception ex)
{
//trans.Rollback("11");
throw new Exception("Unable to Save or Update " + ex.Message);
}
return lastID;
}
public int saveUpdateOrder_Details(Order_Details obOrder_Details, SqlTransaction trans, SqlConnection con)
{
try
{
SqlCommand com = new SqlCommand("spSaveUpdateOrder_Details", con, trans);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderDID", SqlDbType.Int).Value = obOrder_Details.OrderDID;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = obOrder_Details.OrderMID;
com.Parameters.Add("@OrderQty", SqlDbType.Money).Value = obOrder_Details.OrderQty;
com.Parameters.Add("@ItemID", SqlDbType.Int).Value = obOrder_Details.ItemID;
if (obOrder_Details.UnitID <= 0)
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@UnitID", SqlDbType.Int).Value = obOrder_Details.UnitID;
if (obOrder_Details.PriceID <= 0)
com.Parameters.Add("@PriceID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@PriceID", SqlDbType.Int).Value = obOrder_Details.PriceID;
com.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = obOrder_Details.UnitPrice;
com.Parameters.Add("@OrderValue", SqlDbType.Money).Value = obOrder_Details.OrderValue;
com.Parameters.Add("@ColorCode", SqlDbType.VarChar, 100).Value = obOrder_Details.ColorCode;
com.Parameters.Add("@Labdip", SqlDbType.VarChar, 100).Value = obOrder_Details.Labdip;
com.Parameters.Add("@Remarks", SqlDbType.VarChar, 500).Value = obOrder_Details.Remarks;
if (obOrder_Details.CountID <= 0)
com.Parameters.Add("@CountID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@CountID", SqlDbType.Int).Value = obOrder_Details.CountID;
if (obOrder_Details.SizeID <= 0)
com.Parameters.Add("@SizeID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@SizeID", SqlDbType.Int).Value = obOrder_Details.SizeID;
if (obOrder_Details.ColorID <= 0)
com.Parameters.Add("@ColorID", SqlDbType.Int).Value = DBNull.Value;
else
com.Parameters.Add("@ColorID", SqlDbType.Int).Value = obOrder_Details.ColorID;
com.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Unable to Save or Update " + ex.Message);
}
return 0;
}
public DataTable loadFactory(int customerID, SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from Factory WHERE CustomerID=" + customerID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable loadDetail(SqlConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("select * from Order_Details", con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
public DataTable loadItems(SqlConnection con, string sItemName)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("spLoadItems", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@ItemName", SqlDbType.VarChar, 100).Value = sItemName;
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadSelectedItems(SqlConnection con, string ItemList)
{
SqlDataAdapter da = new SqlDataAdapter(" SELECT ItemID, ItemName, ColorsName, SizesName, CountName, ShadeNo FROM Vw_Items" +
" WHERE CompanyID=@CompanyID AND ( ItemID IN " + ItemList + " ) ", con);
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
public DataTable loadForm(SqlConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("spLoadOrderDetail", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@OrderDID", SqlDbType.Int).Value = -5;
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
public DataTable loadOrderNo(SqlConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("select OrderMID,OrderNo from Order_Master WHERE CompanyID=@CompanyID ", con);
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
//------------------------ Find Sales Order -----------------------------
public DataTable searchSelectedCustomer(SqlConnection con, DateTime sDate, DateTime eDate, string OrderNo)
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("spSearchOrder", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@OrderNo", SqlDbType.VarChar, 100).Value = OrderNo;
da.SelectCommand.Parameters.Add("@sDate", SqlDbType.DateTime).Value = sDate;
da.SelectCommand.Parameters.Add("@eDate", SqlDbType.DateTime).Value = eDate;
da.SelectCommand.Parameters.Add("@OrderType", SqlDbType.VarChar, 100).Value = "Sales Order";
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable Find(SqlConnection con, string OrderNo)
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("spFindOrder", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@OrderNo", SqlDbType.VarChar, 100).Value = OrderNo;
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadUnit(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select UnitsID,UnitsName from P_Units", con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void DeleteItems(SqlConnection con, int OrderDID)
{
SqlCommand com = null;
SqlTransaction trans = null;
try
{
com = new SqlCommand();
trans = con.BeginTransaction();
com.Connection = con;
com.Transaction = trans;
com.CommandText = "Delete from Order_Details Where OrderDID = @OrderDID";
com.Parameters.Add("@OrderDID", SqlDbType.Int).Value = OrderDID;
com.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw ex;
}
}
public void DeleteOrderItems(SqlConnection con, SqlTransaction trans, int orderId)
{
try
{
using (var com = new SqlCommand("Delete from Order_Details Where OrderMID = @OrderId", con, trans))
{
com.Parameters.Add("@OrderId", SqlDbType.Int).Value = orderId;
com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Delete(SqlConnection con, SqlTransaction trans, int OrderMasterID)
{
try
{
using (var com = new SqlCommand("spDeleteOrder", con, trans))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMasterID;
com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Delete(SqlConnection con, int OrderMasterID)
{
SqlCommand com = null;
SqlTransaction trans = null;
try
{
com = new SqlCommand();
trans = con.BeginTransaction();
com.Transaction = trans;
com.Connection = con;
com.CommandText = "spDeleteOrder";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMasterID;
com.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw new Exception("Unable to Delete Order" + ex.Message);
}
}
public double loadPrice(SqlConnection con, int CustomerID, int ItemID,int CountID,int SizeID,int ColorID,DateTime PriceDate)
{
try
{
double UnitPrice = 0.0;
if (con.State != ConnectionState.Open) con.Open();
SqlCommand cmd = new SqlCommand("Select dbo.fnGetPriceOfTime(@CustomerID, @ItemID,@CountID,@SizeID,@ColorID,@PriceDate) AS price", con);
cmd.Parameters.Add("@CustomerID", SqlDbType.Int).Value = CustomerID;
cmd.Parameters.Add("@ItemID", SqlDbType.Int).Value = ItemID;
cmd.Parameters.Add("@CountID", SqlDbType.Int).Value = CountID;
cmd.Parameters.Add("@SizeID", SqlDbType.Int).Value = SizeID ;
cmd.Parameters.Add("@ColorID", SqlDbType.Int).Value = ColorID;
cmd.Parameters.Add("@PriceDate", SqlDbType.DateTime).Value = PriceDate;
UnitPrice = Convert.ToDouble(cmd.ExecuteScalar());
return UnitPrice;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public Order_Master GetOrder_Master(SqlConnection con, string OrderNo)
{
DataTable dt = new DataTable();
Order_Master obOrderMaster = new Order_Master();
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from Order_Master WHERE OrderNo=@OrderNo AND CompanyID=@CompanyID", con);
da.SelectCommand.Parameters.Add("@OrderNo", SqlDbType.VarChar, 100).Value = OrderNo;
da.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = LogInInfo.CompanyID;
da.Fill(dt);
da.Dispose();
if (dt.Rows.Count == 0) return null;
obOrderMaster.OrderMID = dt.Rows[0].Field<int>("OrderMID");
obOrderMaster.OrderNo = dt.Rows[0].Field<string>("OrderNo");
obOrderMaster.LedgerNo = dt.Rows[0].Field<object>("LedgerNo") == DBNull.Value || dt.Rows[0].Field<object>("LedgerNo") == null ? "" : dt.Rows[0].Field<string>("LedgerNo");
obOrderMaster.OrderDate = dt.Rows[0].Field<DateTime>("OrderDate");
obOrderMaster.OrderValue = Convert.ToDouble(dt.Rows[0].Field<object>("OrderValue"));
obOrderMaster.TotalOrderQty = dt.Rows[0].Field<object>("TotalOrderQty") == DBNull.Value ? 0 : Convert.ToDouble(dt.Rows[0].Field<object>("TotalOrderQty"));
obOrderMaster.UnitID = dt.Rows[0].Field<object>("UnitID") == DBNull.Value || dt.Rows[0].Field<object>("UnitID") == null ? 0 : dt.Rows[0].Field<int>("UnitID");
obOrderMaster.FactoryID = dt.Rows[0].Field<object>("FactoryID") == DBNull.Value || dt.Rows[0].Field<object>("FactoryID") == null ? -1 : dt.Rows[0].Field<int>("FactoryID");
obOrderMaster.DeliveryDate = dt.Rows[0].Field<object>("DeliveryDate") == DBNull.Value || dt.Rows[0].Field<object>("DeliveryDate") == null ? new DateTime(1900, 1, 1) : dt.Rows[0].Field<DateTime>("DeliveryDate");
obOrderMaster.CustomerID = dt.Rows[0].Field<int>("CustomerID");
obOrderMaster.CurrencyID = Convert.ToInt32(dt.Rows[0].Field<int>("CurrencyID"));
obOrderMaster.CurrencyID = dt.Rows[0].Field<object>("CurrencyID") == DBNull.Value || dt.Rows[0].Field<object>("CurrencyID") == null ? -1 : dt.Rows[0].Field<int>("CurrencyID");
obOrderMaster.Rate = Convert.ToDouble(dt.Rows[0].Field<object>("Rate"));
obOrderMaster.Buyer_ref = dt.Rows[0].Field<string>("Buyer_ref");
}
catch (Exception ex)
{
throw ex;
}
return obOrderMaster;
}
public Order_Master GetOrder_Master(SqlConnection con, int OrderMasterID)
{
DataTable dt = new DataTable();
Order_Master obOrderMaster = new Order_Master();
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from Order_Master WHERE OrderMID=@OrderMID ", con);
da.SelectCommand.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMasterID;
da.Fill(dt);
da.Dispose();
if (dt.Rows.Count == 0) return null;
obOrderMaster.OrderMID = dt.Rows[0].Field<int>("OrderMID");
obOrderMaster.OrderNo = dt.Rows[0].Field<string>("OrderNo");
obOrderMaster.LedgerNo = dt.Rows[0].Field<object>("LedgerNo") == DBNull.Value || dt.Rows[0].Field<object>("LedgerNo") == null ? "" : dt.Rows[0].Field<string>("LedgerNo");
obOrderMaster.OrderDate = dt.Rows[0].Field<DateTime>("OrderDate");
obOrderMaster.OrderValue = Convert.ToDouble(dt.Rows[0].Field<object>("OrderValue"));
obOrderMaster.TotalOrderQty = dt.Rows[0].Field<object>("TotalOrderQty") == DBNull.Value ? 0 : Convert.ToDouble(dt.Rows[0].Field<object>("TotalOrderQty"));
obOrderMaster.UnitID = dt.Rows[0].Field<object>("UnitID") == DBNull.Value || dt.Rows[0].Field<object>("UnitID") == null ? 0 : dt.Rows[0].Field<int>("UnitID");
obOrderMaster.FactoryID = dt.Rows[0].Field<object>("FactoryID") == DBNull.Value || dt.Rows[0].Field<object>("FactoryID") == null ? -1 : dt.Rows[0].Field<int>("FactoryID");
obOrderMaster.DeliveryDate = dt.Rows[0].Field<object>("DeliveryDate") == DBNull.Value || dt.Rows[0].Field<object>("DeliveryDate") == null ? new DateTime(1900, 1, 1) : dt.Rows[0].Field<DateTime>("DeliveryDate");
obOrderMaster.CustomerID = dt.Rows[0].Field<int>("CustomerID");
obOrderMaster.CurrencyID = dt.Rows[0].Field<object>("CurrencyID") == DBNull.Value || dt.Rows[0].Field<object>("CurrencyID") == null ? -1 : dt.Rows[0].Field<int>("CurrencyID");
obOrderMaster.Buyer_ref = dt.Rows[0].Field<string>("Buyer_ref");
}
catch (Exception ex)
{
throw ex;
}
return obOrderMaster;
}
public DataTable getOrders(SqlConnection con, string Cols, string Where, DateTime st, DateTime ed)
{
DataTable dt = null;
try
{
string qstr = "SELECT " + Cols + ",(CASE WHEN ISNULL(T_PI_Details.PIDID,0) <=0 THEN NULL ELSE 'PI Opened' END) AS Status FROM Order_Master LEFT OUTER JOIN T_PI_Details ON Order_Master.OrderMID = T_PI_Details.OrderID " + Where + " Order By OrderNo";
SqlDataAdapter da = new SqlDataAdapter(qstr, con);
if (st != new DateTime(1900, 1, 1) && ed != new DateTime(1900, 1, 1))
{
da.SelectCommand.Parameters.Add("@startDate", SqlDbType.DateTime).Value = st;
da.SelectCommand.Parameters.Add("@endDate", SqlDbType.DateTime).Value = ed;
}
dt = new DataTable();
da.Fill(dt);
da.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
public DataTable getOrderItems(SqlConnection con, int OrderMasterID)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter("spSelectItemsOfanOrder", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMasterID;
da.Fill(dt);
da.Dispose();
}
catch (Exception ex)
{
return null;
throw ex;
}
return dt;
}
public DataTable GetOrderItems(SqlConnection con, int OrderID)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT Order_Details.ItemID, T_Item.ItemName, T_Item.ItemCategory, OrderQty, Order_Details.UnitPrice, OrderValue FROM Order_Details INNER JOIN T_Item ON Order_Details.ItemID = T_Item.ItemID WHERE OrderMID = @OrderMID", con);
da.SelectCommand.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderID;
da.Fill(dt);
da.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
public DataTable SelectOrNewAmendment(SqlConnection con, int OrderID, int AmendID)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter("spSelectOrNewAmendment", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderID;
da.SelectCommand.Parameters.Add("@AmendID", SqlDbType.Int).Value = AmendID;
da.Fill(dt);
da.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
public void UpdateOrderItemAmendment(SqlConnection con, SqlTransaction trans, int OrderMID, int OrderDID, int ItemID, double AmendQty, double AmendValue)
{
try
{
string qstr;
//qstr = "UPDATE Order_Details_A SET AmendQty = @AmendQty, AmendValue = @AmendValue "
// + " WHERE AmendID=(SELECT MAX(AmendID) FROM Order_Master_A) AND (OrderDID = @OrderDID) AND (OrderMID = @OrderMID)";
qstr = "spInsertUpdateAmendmentItems";
SqlCommand cmd = new SqlCommand(qstr, con, trans);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMID;
cmd.Parameters.Add("@OrderDID", SqlDbType.Int).Value = OrderDID;
cmd.Parameters.Add("@ItemID", SqlDbType.Int).Value = ItemID;
cmd.Parameters.Add("@AmendQty", SqlDbType.Money).Value = AmendQty;
cmd.Parameters.Add("@AmendValue", SqlDbType.Money).Value = AmendValue;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateOrderDetail(SqlConnection con, SqlTransaction trans, int OrderMID, int OrderDID, double OrderQty, double uPrice, double OrderValue)
{
try
{
string qstr = "UPDATE Order_Details SET OrderQty = @OrderQty, UnitPrice = @UnitPrice, OrderValue = @OrderValue "
+ " WHERE (OrderDID = @OrderDID) AND (OrderMID = @OrderMID)";
SqlCommand cmd = new SqlCommand(qstr, con, trans);
cmd.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMID;
cmd.Parameters.Add("@OrderDID", SqlDbType.Int).Value = OrderDID;
cmd.Parameters.Add("@OrderQty", SqlDbType.Money).Value = OrderQty;
cmd.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = uPrice;
cmd.Parameters.Add("@OrderValue", SqlDbType.Money).Value = OrderValue;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
public void CreateAmendment(SqlConnection con, SqlTransaction trans, int Stage, int OrderMID, DateTime AmendDate, string AmendComment, double TtlAQty, double TtlAValue)
{
try
{
SqlCommand cmd = new SqlCommand("spDoneOrderAmendment", con, trans);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@stage", SqlDbType.Int).Value = Stage;
cmd.Parameters.Add("@OrderMID", SqlDbType.Int).Value = OrderMID;
cmd.Parameters.Add("@AmendDate", SqlDbType.DateTime).Value = AmendDate;
cmd.Parameters.Add("@AmendComment", SqlDbType.VarChar, 500).Value = AmendComment;
cmd.Parameters.Add("@TotalAmendQty", SqlDbType.Money).Value = TtlAQty;
cmd.Parameters.Add("@TotalAmendValue", SqlDbType.Money).Value = TtlAValue;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable getAmendments(SqlConnection con, int OrderMID)
{
DataTable dt = new DataTable();
try
{
string qstr = "SELECT AmendID,OrderMID,OrderNo,AmendDate,AmendComment FROM Order_Master_A WHERE OrderMID = " + OrderMID.ToString();
SqlDataAdapter da = new SqlDataAdapter(qstr, con);
da.Fill(dt);
da.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
public DataTable LoadCurrency(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from Currency where CompanyID=" + LogInInfo.CompanyID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadItem(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select ItemID,ItemName from T_Item where CompanyID="+LogInInfo.CompanyID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadCount(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select CountID,CountName from T_Count where CompanyID=" + LogInInfo.CompanyID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadColor(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select ColorsID,ColorsName from P_Colors where CompanyID=" + LogInInfo.CompanyID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public DataTable loadSize(SqlConnection con)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select SizesID,SizesName from P_Sizes where CompanyID=" + LogInInfo.CompanyID.ToString(), con);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public int SuppCusCurrency(SqlConnection con, int SupCusID)
{
SqlCommand com = null;
SqlTransaction trans = null;
try
{
int ab;
com = new SqlCommand();
trans = con.BeginTransaction();
com.Connection = con;
com.Transaction = trans;
com.CommandText = "select CurrencyID from T_Ledgers where LedgerID=@SupCusID";
com.Parameters.Add("@SupCusID", SqlDbType.Int).Value = SupCusID;
ab=Convert.ToInt32( com.ExecuteScalar());
trans.Commit();
return ab;
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw new Exception(ex.Message);
}
}
}
}
|
namespace PaderbornUniversity.SILab.Hip.EventSourcing.Migrations
{
public interface IStreamMigrationArgs
{
IAsyncEnumerator<IEvent> GetExistingEvents();
void AppendEvent(IEvent ev);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPickups : MonoBehaviour
{
public Transform player;
List<float> lanes;
List<GameObject> pickUps;
const float leftLane = -1.5f, middleLane = 0f, rightLane = 1.5f;
public float spawnWait;
public GameObject waterPickup;
public GameObject sunPickup;
public GameObject insect;
public int spawnCount;
public bool gameActive = true;
public Vector2 spawnPos;
// Start is called before the first frame update
void Start()
{
StartCoroutine(StartSpawning());
lanes = new List<float>();
pickUps = new List<GameObject>();
lanes.Add(leftLane);
lanes.Add(middleLane);
lanes.Add(rightLane);
pickUps.Add(waterPickup);
pickUps.Add(sunPickup);
pickUps.Add(insect);
}
private void LateUpdate()
{
spawnPos.y = player.position.y + 10f;
}
public IEnumerator StartSpawning()
{
yield return new WaitForSeconds(2f);
while (gameActive)
{
for(int i = 0; i < spawnCount; i++)
{
//picks a random index from the pickups list
int randomPickup = Random.Range(0, pickUps.Count);
GameObject spawnPickup = pickUps[randomPickup];
// picks a random index in the lanes list
int randomLane = Random.Range(0, lanes.Count);
float spawnLane = lanes[randomLane];
Vector2 spawnPosition = new Vector2(spawnLane, spawnPos.y);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(spawnPickup, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
}
}
}
|
using System;
namespace PDTech.OA.Model
{
/// <summary>
/// VIEW_PRO_STEP_TYPE:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class VIEW_PRO_STEP_TYPE
{
public VIEW_PRO_STEP_TYPE()
{}
#region Model
private decimal? _project_step_id;
private decimal? _project_id;
private decimal? _step_id;
private DateTime? _start_time;
private DateTime? _end_time;
private decimal? _owner;
private decimal? _step_status;
private decimal? _attribute_log;
private string _step_name;
private decimal? _project_type;
/// <summary>
/// 项目任务步骤ID
/// </summary>
public decimal? PROJECT_STEP_ID
{
set{ _project_step_id=value;}
get{return _project_step_id;}
}
/// <summary>
/// 项目ID
/// </summary>
public decimal? PROJECT_ID
{
set{ _project_id=value;}
get{return _project_id;}
}
/// <summary>
/// 步骤ID
/// </summary>
public decimal? STEP_ID
{
set{ _step_id=value;}
get{return _step_id;}
}
/// <summary>
/// 开始时间
/// </summary>
public DateTime? START_TIME
{
set{ _start_time=value;}
get{return _start_time;}
}
/// <summary>
/// 结束时间
/// </summary>
public DateTime? END_TIME
{
set{ _end_time=value;}
get{return _end_time;}
}
/// <summary>
/// 代办人员ID
/// </summary>
public decimal? OWNER
{
set{ _owner=value;}
get{return _owner;}
}
/// <summary>
/// 任务完成状态 0 未开始 1 办理中 9 已完成
/// </summary>
public decimal? STEP_STATUS
{
set{ _step_status=value;}
get{return _step_status;}
}
/// <summary>
/// 扩展属性ID
/// </summary>
public decimal? ATTRIBUTE_LOG
{
set{ _attribute_log=value;}
get{return _attribute_log;}
}
/// <summary>
/// 步骤名称
/// </summary>
public string STEP_NAME
{
set{ _step_name=value;}
get{return _step_name;}
}
/// <summary>
/// 类型
/// </summary>
public decimal? PROJECT_TYPE
{
set{ _project_type=value;}
get{return _project_type;}
}
/// <summary>
/// 待办人员名称
/// </summary>
public string FULL_NAME
{
get;
set;
}
/// <summary>
/// 步骤URl地址
/// </summary>
public string URL
{
get;
set;
}
/// <summary>
/// 项目步骤备注
/// </summary>
public string REMARK
{
get;
set;
}
/// <summary>
/// 是否是开始步骤
/// </summary>
public string START_FLAG
{
get;
set;
}
/// <summary>
/// 计划完成时间
/// </summary>
public DateTime? PLAN_ENDTIME
{
get;
set;
}
/// <summary>
///
/// </summary>
public decimal? CHECK_STEP_ID
{
get;
set;
}
/// <summary>
/// 必要上一步的完成状态
/// </summary>
public decimal? P_STEP_STATUS
{
get;
set;
}
/// <summary>
/// 必要上一步的名称
/// </summary>
public string P_STEP_NAME
{
get;
set;
}
/// <summary>
/// 待办人员部门ID
/// </summary>
public decimal? DEPARTMENT_ID
{
get;
set;
}
/// <summary>
/// 部门名称
/// </summary>
public string DEPARTMENT_NAME
{
get;
set;
}
/// <summary>
/// 风险处置单ID
/// </summary>
public decimal? RISK_HANDLE_ARCHIVE_ID
{
get;
set;
}
/// <summary>
///
/// </summary>
public DateTime? LIMIT_TIME
{
get;
set;
}
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArmadaEngine.Camera;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using ArmadaEngine.Scenes.Sagey.Managers;
using Microsoft.Xna.Framework;
using ArmadaEngine.BaseObjects;
using Newtonsoft.Json;
using ArmadaEngine.TileMaps;
using TiledSharp;
using Microsoft.Xna.Framework.Input;
using ArmadaEngine.Helpers;
namespace ArmadaEngine.Scenes.Sagey
{
class SageyMainScene : Scene
{
public GameObjects.Player player;
SpriteFont font;
bool typingMode = false;
//public KbHandler kbHandler;
//Managers
InventoryManager _InvenManager;
TileMaps.TilemapManager _MapManager;
public NPCManager _NPCManager;
WorldObjectManager _WorldObjectManager;
ArmadaEngine.UI.UIManager _UIManager;
ChemistryManager _ChemistryManager;
ItemManager _ItemManager;
PlayerManager _PlayerManager;
BankManager _BankManager;
GatherableManager _GatherableManager;
DialogManager _DialogManager;
QuestManager _QuestManager;
EventManager _EventManager;
//UI
Vector2 mouseClickPos;
Sprite mouseCursor;
Texture2D _SelectTex;
Sprite _SelectedSprite = null;
bool BankMode = false;
const int TargetWidth = 480;
const int TargetHeight = 270;
Matrix Scale;
int effectIndex = 0;
List<Effect> effectsList = new List<Effect>();
Effect inverse;
Effect virtualBoy;
Effect brightness;
float brightnessIntensity = 0.5f;
Effect ColorFun;
float ColorFunMode = 0.1f;
bool shaderOn = false;
public SageyMainScene(ContentManager c, SceneManager sm, ArmadaCamera ca) : base(c, sm, ca)
{
this._Name = "Sagey";
_Content.RootDirectory = "Content/Scenes/Sagey";
player = new GameObjects.Player();
_UIManager = new ArmadaEngine.UI.UIManager(_Content);
_QuestManager = new QuestManager();
_MapManager = new TileMaps.TilemapManager();
_DialogManager = new Managers.DialogManager(_QuestManager);
_EventManager = new EventManager(_QuestManager);
_ItemManager = new Managers.ItemManager(_Content);
_InvenManager = new Managers.InventoryManager(_ItemManager);
_BankManager = new Managers.BankManager(_ItemManager, _InvenManager);
_WorldObjectManager = new Managers.WorldObjectManager(_MapManager, _InvenManager, _Content, player, _ItemManager);
_NPCManager = new Managers.NPCManager(_MapManager, _Content, player, _DialogManager, _InvenManager, _WorldObjectManager);
_GatherableManager = new Managers.GatherableManager(_MapManager, _InvenManager, _Content, player);
_ChemistryManager = new Managers.ChemistryManager(_InvenManager, _WorldObjectManager, _NPCManager, _Content, _ItemManager);
_PlayerManager = new Managers.PlayerManager(player, _InvenManager, _WorldObjectManager, _NPCManager, _MapManager, _GatherableManager);
_WorldObjectManager.SetGatherManager(_GatherableManager);
//kbHandler = new KbHandler();
_SelectedSprite = new Sprite();
//InputHelper.Init();
//_TestCamera = new TestCamera(GraphicsDevice);
//EVENTS
_DialogManager.BankOpened += HandleBankOpened;
_PlayerManager.BankOpened += HandleBankOpened;
_PlayerManager.PlayerMoved += HandlePlayerMoved;
_BankManager.AttachEvents(_EventManager);
_NPCManager.AttachEvents(_EventManager);
_ChemistryManager.AttachEvents(_EventManager);
_WorldObjectManager.AttachEvents(_EventManager);
_GatherableManager.AttachEvents(_EventManager);
}
public override void LoadContent()
{
base.LoadContent();
player.LoadContent("Art/Player", _Content);
_MapManager.LoadMap("0-0", _Content);
LoadMapNPCs(_MapManager.findMapByName("0-0"));
LoadMapObjects(_MapManager.findMapByName("0-0"));
//_MapManager.LoadMap("0-1", _Content);
font = _Content.Load<SpriteFont>("Fonts/Fipps");
_ItemManager.LoadItems("Content/Scenes/Sagey/JSON/ItemList.json");
_ChemistryManager.LoadRecipes("Content/Scenes/Sagey/JSON/RecipeList.json");
_ChemistryManager.LoadIcons();
_GatherableManager.LoadContent(_Content);
_SelectTex = _Content.Load<Texture2D>("Art/WhiteTexture");
_InvenManager.AddItem(Enums.ItemID.kItemFish, 1500);
_InvenManager.AddItem(Enums.ItemID.kItemStrawberry, 1000000);
_InvenManager.AddItem(Enums.ItemID.kItemSlimeGoo, 999999999);
_InvenManager.AddItem(Enums.ItemID.kItemBucket, 3);
_BankManager.AddItem(Enums.ItemID.kItemOre, 5);
_BankManager.AddItem(Enums.ItemID.kItemBucket, 4);
_BankManager.AddItem(Enums.ItemID.kItemFish, 1500);
_BankManager.AddItem(Enums.ItemID.kItemStrawberry, 1000000);
_BankManager.AddItem(Enums.ItemID.kItemSlimeGoo, 999999999);
_BankManager.AddItem(Enums.ItemID.kItemBucket, 3);
LoadGUI();
//check if save exists
////else start a new save
//bool saveExist = false;
string path = _Content.RootDirectory + @"\Save\save.txt";
//if (System.IO.File.Exists(path))
//{
// saveExist = true;
//}
//else
//{
// System.IO.Directory.CreateDirectory(_Content.RootDirectory + @"\Save\");
//}
//if (saveExist)
//{
// //load
// System.IO.StreamReader file = new System.IO.StreamReader(path);
// string line = file.ReadLine();
// if (line != null)
// {
// string[] playerPos = line.Split(' ');
// float.TryParse(playerPos[0], out var x);
// float.TryParse(playerPos[1], out var y);
// _PlayerManager.SetPosition(x, y);
// }
// bool bankMode = false;
// bool inventoryMode = false;
// while ((line = file.ReadLine()) != null)
// {
// if (line.Equals("B"))
// {
// bankMode = true;
// continue;
// }
// else if (line.Equals("BEnd"))
// {
// bankMode = false;
// continue;
// }
// if (line.Equals("I"))
// {
// inventoryMode = true;
// continue;
// }
// else if (line.Equals("IEnd"))
// {
// inventoryMode = false;
// continue;
// }
// if (bankMode || inventoryMode)
// {
// string[] items = line.Split(' ');
// Int32.TryParse(items[0], out int itemType);
// Enums.ItemID type = (Enums.ItemID)itemType;
// Int32.TryParse(items[1], out int amt);
// if (bankMode)
// {
// _BankManager.AddItem(type, amt);
// }
// else if (inventoryMode)
// {
// _InvenManager.AddItem(type, amt);
// }
// }
// }
// file.Close();
//}
//else
//{
// player._Position = new Vector2(32, 320);
// _InvenManager.AddItem(Enums.ItemID.kItemLog, 5);
// _InvenManager.AddItem(Enums.ItemID.kItemMatches);
// _InvenManager.AddItem(Enums.ItemID.kItemFish, 2);
// _InvenManager.AddItem(Enums.ItemID.kItemMilk, 1);
// _InvenManager.AddItem(Enums.ItemID.kItemBucket, 3);
// _BankManager.AddItem(Enums.ItemID.kItemLog, 10);
// _BankManager.AddItem(Enums.ItemID.kItemFish, 3);
//}
_QuestManager.GenerateQuest();
//List<Dialog> dList = new List<Dialog>();
//Dialog d1 = new Dialog();
//d1.ID = "NPC1";
//d1.textList.Add("I'm a talking slime!");
//d1.textList.Add("y = mx + b");
//d1.textList.Add("Do you know the muffin pan?");
//DialogOption option = new DialogOption();
//option.NextMsgID = "muffinYes";
//option.optiontext = "I think it's muffin pan though.";
//d1.options.Add(option);
//option = new DialogOption();
//option.NextMsgID = "muffinNo";
//option.optiontext = "That's not how the story goes...";
//d1.options.Add(option);
//dList.Add(d1);
//Dialog d2 = new Dialog();
//d2.ID = "MightyDucks";
//d2.textList.Add("I love Mike!");
//dList.Add(d2);
//List <Dialog> list2 = new List<Dialog>();
//List<Recipe> rList = new List<Recipe>();
//Recipe matches = new Recipes.MatchesRecipe();
//Recipe DoubleLog = new Recipes.DoubleLogRecipe();
//Recipe fishStick = new Recipes.FishStickRecipe();
//rList.Add(matches);
//rList.Add(DoubleLog);
//rList.Add(fishStick);
string text = JsonConvert.SerializeObject(_QuestManager.GetActiveQuests(), Newtonsoft.Json.Formatting.Indented);
path = _Content.RootDirectory + @"\JSON\Dialog_EN_US.json";
_DialogManager.LoadDialog(path);
_Content.RootDirectory = "Content/Scenes/Stest";
inverse = _Content.Load<Effect>("Inverse");
virtualBoy = _Content.Load<Effect>("VirtualBoy");
brightness = _Content.Load<Effect>("Brightness");
ColorFun = _Content.Load<Effect>("ColorFun");
effectsList.Add(inverse);
effectsList.Add(virtualBoy);
effectsList.Add(brightness);
effectsList.Add(ColorFun);
_Content.RootDirectory = "Content/Scenes/Sagey";
//_DialogManager.PlayMessage("NPC1");
//var dialog = System.IO.File.ReadAllText(path);
//list2 = JsonConvert.DeserializeObject<List<Dialog>>(dialog);
}
private void LoadGUI()
{
UI.InventoryPanel inv = new UI.InventoryPanel(_UIManager, _InvenManager);
inv.LoadContent("Panel");
inv.SetSize(new Vector2(300, 300));
inv.Setup();
inv.HidePanel();
inv.SetPosition(new Vector2(400, 100));
_UIManager.AddPanel(inv);
UI.BankPanel bnkp = new UI.BankPanel(_UIManager, _BankManager);
bnkp.LoadContent("Panel");
bnkp.SetSize(new Vector2(300, 300));
bnkp.Setup();
bnkp.ShowPanel();
bnkp.SetPosition(new Vector2(0, 0));
_UIManager.AddPanel(bnkp);
}
public void LoadMapNPCs(TileMap testMap)
{
TmxList<TmxObject> ObjectList = testMap.FindNPCs();
if (ObjectList != null)
{
foreach (TmxObject thing in ObjectList)
{
int adjustThingX = (int)(thing.X + (testMap._Postion.X + (thing.Width / 2)));
int adjustThingY = (int)(thing.Y + (testMap._Postion.Y + (thing.Height / 2)));
_NPCManager.CreateNPC(thing, new Vector2(adjustThingX, adjustThingY));
}
}
}
public void LoadMapObjects(TileMap testMap)
{
TmxList<TmxObject> ObjectList = testMap.FindObjects();
if (ObjectList != null)
{
foreach (TmxObject thing in ObjectList)
{
Vector2 newPos = new Vector2((int)thing.X + testMap._Postion.X, (int)thing.Y + testMap._Postion.Y);
//_WorldObjectManager.CreateObject(thing, newPos);
if (thing.Type == "Dirt")
{
_WorldObjectManager.CreateObject(thing, newPos);
}
else
{
_GatherableManager.CreateGatherable(thing, newPos);
}
}
}
}
public override void Update(GameTime gt)
{
base.Update(gt);
_EventManager.ProcessEvents();
//ProcessMouse(gt);
ProcessKeyboard(gt);
if (InputHelper.IsKeyPressed(Keys.J))
{
_BankManager.AddItem(Enums.ItemID.kItemBucket);
}
//if (typingMode && !kbHandler.typingMode) //ugly, but should show that input mode ended...?
//{
// processor.Parsetext(kbHandler.Input);
// if (processor.currentError != string.Empty) kbHandler.Input = processor.currentError;
// //kbHandler.Input = string.Empty;
//}
_PlayerManager.Update(gt);
_SelectedSprite = null;
if (_PlayerManager._FrontSprite != null)
{
_SelectedSprite = _PlayerManager._FrontSprite;
}
_NPCManager.UpdateNPCs(gt);
_WorldObjectManager.Update(gt);
_GatherableManager.Update(gt);
//ProcessCamera(gameTime);
//_Camera.SetPosition(player._Position);
_Camera._Position = player._Position;
_UIManager.Update(gt);
}
private void ProcessMouse(object gameTime)
{
//first check UI
}
private void ProcessKeyboard(GameTime gameTime)
{
if (InputHelper.IsKeyPressed(Keys.E))
{
_UIManager.TogglePanel("Bank");
}
if (InputHelper.IsKeyPressed(Keys.I))
{
_UIManager.TogglePanel("Inventory");
}
if (InputHelper.IsKeyPressed(Keys.Escape))
{
_UIManager.HideAll();
}
if(InputHelper.IsKeyPressed(Keys.F6))
{
shaderOn = !shaderOn;
}
if(InputHelper.IsKeyPressed(Keys.F7))
{
effectIndex++;
if(effectIndex == effectsList.Count)
{
effectIndex = 0;
}
}
if (InputHelper.IsKeyPressed(Keys.F9))
{
brightnessIntensity += 0.1f;
if (brightnessIntensity > 1.0f)
{
brightnessIntensity = 1.0f;
}
}
else if (InputHelper.IsKeyPressed(Keys.F8))
{
brightnessIntensity -= 0.1f;
if (brightnessIntensity < -1.0f)
{
brightnessIntensity = -1.0f;
}
}
if (InputHelper.IsKeyPressed(Keys.F10))
{
if(ColorFunMode == 0.1f)
{
ColorFunMode = 0.2f;
}
else
{
ColorFunMode = 0.1f;
}
}
}
public override void Draw(SpriteBatch spriteBatch, Rectangle b)
{
base.Draw(spriteBatch, b);
spriteBatch.Begin(SpriteSortMode.Immediate,
BlendState.AlphaBlend,
null,
null,
null,
null,
_Camera.GetTransform());
if (shaderOn)
{
effectsList[effectIndex].Techniques[0].Passes[0].Apply();
if(effectsList[effectIndex].Name == "Brightness")
{
effectsList[effectIndex].Parameters["Intensity"].SetValue(brightnessIntensity);
}
else if (effectsList[effectIndex].Name == "ColorFun")
{
effectsList[effectIndex].Parameters["Mode"].SetValue(ColorFunMode);
}
}
_MapManager.Draw(spriteBatch, _Camera._Viewport);
_PlayerManager.Draw(spriteBatch);
_NPCManager.DrawNPCs(spriteBatch);
_WorldObjectManager.Draw(spriteBatch);
_GatherableManager.Draw(spriteBatch);
//Vector2 invenBgpos = _UIManager.getUIElement("Inventory")._TopLeft;
//_InvenManager.Draw(spriteBatch, invenBgpos);
//mouseCursor.Draw(spriteBatch);
DrawSelectRect(spriteBatch);
//spriteBatch.DrawString(font, kbHandler.Input, camera.ToWorld(new Vector2(100, 100)), Color.Black);
//spriteBatch.DrawString(font, player._HP.ToString(), camera.ToWorld(new Vector2(200, 200)), Color.White);
//base.Draw(gt);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Immediate);
if (shaderOn)
{
effectsList[effectIndex].Techniques[0].Passes[0].Apply();
}
_UIManager.Draw(spriteBatch);
spriteBatch.DrawString(font, _PlayerManager.currentInteracttext, new Vector2(100, 100), Color.White);
spriteBatch.End();
}
private void DrawSelectRect(SpriteBatch sb)
{
int border = 3;
Rectangle rect;
if (_SelectedSprite != null)
{
rect = _SelectedSprite._BoundingBox;
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y, border, rect.Height + border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y, rect.Width + border, border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X + rect.Width, rect.Y, border, rect.Height + border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y + rect.Height, rect.Width + border, border), Color.White);
}
rect = _PlayerManager.CheckRect;
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y, border, rect.Height + border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y, rect.Width + border, border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X + rect.Width, rect.Y, border, rect.Height + border), Color.White);
sb.Draw(_SelectTex, new Rectangle(rect.X, rect.Y + rect.Height, rect.Width + border, border), Color.White);
}
public void HandleBankOpened(object sender, EventArgs args)
{
BankMode = true;
_UIManager.ShowPanel("Bank");
}
private void HandlePlayerMoved(object sender, EventArgs args)
{
BankMode = false;
_UIManager.HidePanel("Bank");
}
}
}
|
using System.Linq;
namespace CryptobotUi.Controllers.Cryptodb
{
partial class PnlsController
{
partial void OnPnlsRead(ref IQueryable<Models.Cryptodb.Pnl> items)
{
items = items.OrderByDescending(p => p.signal_id);
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using Nito.AsyncEx;
using TemporaryEmploymentCorp.DataAccess;
using TemporaryEmploymentCorp.Helpers.ReportViewer;
using TemporaryEmploymentCorp.Models.Company;
using TemporaryEmploymentCorp.Reports.Company;
using TemporaryEmploymentCorp.Views.Company;
namespace TemporaryEmploymentCorp.Modules
{
public class CompanyModule : ObservableObject
{
public ObservableCollection<CompanyModel> Companies { get; } = new ObservableCollection<CompanyModel>();
private IRepository _repository;
private CompanyModel _selectedCompany;
private NewCompanyModel _newCompany;
public INotifyTaskCompletion CompanyLoading { get; private set; }
public CompanyModule(IRepository repository)
{
_repository = repository;
// LoadPublishers();
CompanyLoading = NotifyTaskCompletion.Create(() => LoadCompaniesAsync());
}
public CompanyModule()
{
}
private async Task LoadCompaniesAsync()
{
var companies = await _repository.Company.GetRangeAsync();
Companies.Clear();
foreach (var company in companies)
{
Companies.Add(new CompanyModel(company, _repository));
await Task.Delay(10);
}
}
public CompanyModel SelectedCompany
{
get { return _selectedCompany; }
set
{
//will return to the before-editing stage
_selectedCompany?.CancelEditCommand.Execute(null);
_selectedCompany = value;
if (_selectedCompany != null)
{
_selectedCompany.LoadRelatedInfo();
}
RaisePropertyChanged(nameof(SelectedCompany));
}
}
public NewCompanyModel NewCompany
{
get { return _newCompany; }
set
{
_newCompany = value;
RaisePropertyChanged(nameof(NewCompany));
}
}
public ICommand AddCompanyCommand => new RelayCommand(AddCompanyProc);
public ICommand CancelCompanyCommand => new RelayCommand(CancelCompanyProc);
public ICommand PrintCompanyCommand => new RelayCommand(PrintCompanyProc);
private SingleInstanceWindowViewer<AllCompanyReportWindow> _AllCompanyReportWindow = new SingleInstanceWindowViewer<AllCompanyReportWindow>();
private void PrintCompanyProc()
{
_AllCompanyReportWindow.Show();
}
public ICommand SaveCompanyCommand => new RelayCommand(SaveCompanyProc, SaveCompanyCondition);
public ICommand DeleteCompanyCommand => new RelayCommand(DeleteCompanyProc, DeleteCompanyCondition);
private bool DeleteCompanyCondition()
{
if (SelectedCompany == null)
{
return false;
}
return true;
}
private async Task DeleteCompanyProcAsync()
{
var value = MessageBox.Show("Are you sure you want to delete?", "", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (value == MessageBoxResult.Yes)
{
try
{
NotifyTaskCompletion.Create(RemoveCompanyAsync);
}
catch (Exception e)
{
MessageBox.Show("Companies with openings cannot be deleted.");
}
}
else
{
return;
}
}
public async void DeleteCompanyProc()
{
await DeleteCompanyProcAsync();
}
private async Task RemoveCompanyAsync()
{
try
{
await Task.Run(() => _repository.Company.RemoveAsync(SelectedCompany.Model));
Companies.Remove(SelectedCompany);
}
catch (Exception e)
{
MessageBox.Show("Unable to delete company with openings.", "Company");
throw;
}
}
private void CancelCompanyProc()
{
NewCompany?.Dispose();
_AddCompanyWindow.Close();
}
private bool SaveCompanyCondition()
{
return (NewCompany != null) && NewCompany.HasChanges && !NewCompany.HasErrors;
}
private void SaveCompanyProc()
{
if (NewCompany == null) return;
if (!NewCompany.HasChanges) return;
NotifyTaskCompletion.Create(() => SaveAddCompanyAsync());
_AddCompanyWindow.Close();
}
private async Task SaveAddCompanyAsync()
{
try
{
await Task.Run(() => _repository.Company.AddAsync(NewCompany.ModelCopy)) ;
Companies.Add(new CompanyModel(NewCompany.ModelCopy, _repository));
}
catch (Exception e)
{
MessageBox.Show("An error occured during save. Reason: " + e.Message, "Company");
}
}
public AddCompanyWindow _AddCompanyWindow;
private void AddCompanyProc()
{
NewCompany = new NewCompanyModel();
_AddCompanyWindow = new AddCompanyWindow();
_AddCompanyWindow.Owner = Application.Current.MainWindow;
_AddCompanyWindow.ShowDialog();
}
private string _searchCompany;
public string SearchCompany
{
get { return _searchCompany; }
set
{
_searchCompany = value;
RaisePropertyChanged(nameof(SearchCompany));
var viewCompanyList = CollectionViewSource.GetDefaultView(Companies);
if (string.IsNullOrWhiteSpace(SearchCompany))
{
viewCompanyList.Filter = null;
}
else
{
viewCompanyList.Filter = obj =>
{
var cm = obj as CompanyModel;
var sc = SearchCompany.ToLowerInvariant();
if (cm == null) return false;
return cm.Model.CompanyAddress.ToLowerInvariant().Contains(sc) ||
cm.Model.CompanyName.ToLowerInvariant().Contains(sc);
;
};
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Grisaia.Categories;
using Grisaia.Categories.Sprites;
using Grisaia.Mvvm.ViewModel;
using Microsoft.Win32;
namespace Grisaia.SpriteViewer {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class SpriteSelectionWindow : Window {
#region Fields
//private double scale = 1.0;
//private bool centered = true;
//private int currentWidth = 0;
//private int currentHeight = 0;
//private Thickness expandShrink;
//private double savedScale = 1.0;
//private Vector savedNormalizedScroll = new Vector(-1, -1);
private bool supressEvents = false;
#endregion
#region Properties
public SpriteSelectionViewModel ViewModel => (SpriteSelectionViewModel) DataContext;
#endregion
#region Static Constructor
static SpriteSelectionWindow() {
DataContextProperty.AddOwner(typeof(SpriteSelectionWindow),
new FrameworkPropertyMetadata(
OnDataContextChanged));
}
#endregion
#region Constructors
public SpriteSelectionWindow() {
InitializeComponent();
}
#endregion
#region Event Handlers
private static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
SpriteSelectionWindow window = (SpriteSelectionWindow) d;
window.ViewModel.WindowOwner = window;
}
private void OnClosed(object sender, EventArgs e) {
ViewModel.WindowOwner = null;
}
private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e) {
Console.WriteLine("-------------------------------------");
}
#endregion
}
}
|
using CoordControl.Core.Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoordControl.Core
{
/// <summary>
/// Перекресток как узел УДС
/// </summary>
public sealed class NodeCross
{
/// <summary>
/// Участок перекрестка
/// </summary>
public RegionCross CrossRegion { get; set; }
/// <summary>
/// Перекресток узла
/// </summary>
public Cross EntityCross { get; set; }
/// <summary>
/// Получение левого входного перегона
/// </summary>
public IWay GetLeftEntryWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is Way) && ((Way)x).IsRightDirection
&& ((Way)x).EntityRoad.CrossRight != null && (((Way)x).EntityRoad.CrossRight.ID == EntityCross.ID))
||
((x is WayEntry) && (((WayEntry)x).EntityPass.CrossLeftPass != null)
&& (((WayEntry)x).EntityPass.CrossLeftPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение левого выходного перегона
/// </summary>
public IWay GetLeftExitWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is Way) && !((Way)x).IsRightDirection
&& ((Way)x).EntityRoad.CrossRight != null && (((Way)x).EntityRoad.CrossRight.ID == EntityCross.ID))
||
((x is WayExit) && (((WayExit)x).EntityPass.CrossRightPass != null)
&& (((WayExit)x).EntityPass.CrossRightPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение правого входного перегона
///
/// </summary>
public IWay GetRightEntryWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is Way) && !((Way)x).IsRightDirection
&& ((Way)x).EntityRoad.CrossLeft != null && (((Way)x).EntityRoad.CrossLeft.ID == EntityCross.ID))
||
((x is WayEntry) && (((WayEntry)x).EntityPass.CrossRightPass != null)
&& (((WayEntry)x).EntityPass.CrossRightPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение правого выходного перегона
/// </summary>
public IWay GetRightExitWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is Way) && ((Way)x).IsRightDirection
&& ((Way)x).EntityRoad.CrossLeft != null && (((Way)x).EntityRoad.CrossLeft.ID == EntityCross.ID))
||
((x is WayExit) && (((WayExit)x).EntityPass.CrossLeftPass != null)
&& (((WayExit)x).EntityPass.CrossLeftPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение верхнего входного перегона
/// </summary>
public IWay GetTopEntryWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is WayEntry) && (((WayEntry)x).EntityPass.CrossTopPass != null)
&& (((WayEntry)x).EntityPass.CrossTopPass.ID == EntityCross.ID))
);
}
/// <summary>
/// измеренные суммы числа стоящих ТС для
/// каждого подхода за период 5 минут
/// </summary>
private double[] NStop;
/// <summary>
/// измеренное количество ТС (для каждого подхода)
/// прошехавших перекресток за период 5 минут
/// </summary>
private double[] NMoved;
/// <summary>
/// Получение верхнего выходного перегона
///
/// </summary>
public IWay GetTopExitWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is WayExit) && (((WayExit)x).EntityPass.CrossBottomPass != null)
&& (((WayExit)x).EntityPass.CrossBottomPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение нижнего входного перегона
/// </summary>
public IWay GetBottomEntryWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is WayEntry) && (((WayEntry)x).EntityPass.CrossBottomPass != null)
&& (((WayEntry)x).EntityPass.CrossBottomPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение нижнего выходного перегона
/// </summary>
public IWay GetBottomExitWay()
{
return RouteEnvir.Instance.ListWays.First(
(x) =>
((x is WayExit) && (((WayExit)x).EntityPass.CrossTopPass != null)
&& (((WayExit)x).EntityPass.CrossTopPass.ID == EntityCross.ID))
);
}
/// <summary>
/// Получение плана текущего перекрестка
/// </summary>
public CrossPlan GetCrossPlan()
{
return RouteEnvir.Instance.EntityPlan.CrossPlans.First(
(x) => (x.Cross != null) && (x.Cross.ID == EntityCross.ID)
);
}
/// <summary>
/// расчет сдвига фаз относительно нулевого перекрестка
/// </summary>
/// <returns></returns>
public double CalcTimeOfCycle()
{
int phaseOffset = 0;
List<CrossPlan> cps = RouteEnvir.Instance.EntityPlan.CrossPlans.ToList();
foreach (CrossPlan cp in cps)
{
if (cp.Cross.Position <= EntityCross.Position)
phaseOffset += cp.PhaseOffset;
}
phaseOffset = phaseOffset % RouteEnvir.Instance.EntityPlan.Cycle;
double timeOfCycle = RouteEnvir.Instance.TimeCurrent % RouteEnvir.Instance.EntityPlan.Cycle - phaseOffset;
if (timeOfCycle < 0)
timeOfCycle += RouteEnvir.Instance.EntityPlan.Cycle;
return timeOfCycle;
}
/// <summary>
/// Расчет скорости на второстепенной улице
/// как максимальная скорость среди
/// левого и правого перегона
/// </summary>
/// <returns></returns>
public double CalcVerticalSpeed() {
double result = 0;
IWay leftEntry = GetLeftEntryWay();
if(leftEntry is Way)
result = ((Way)leftEntry).EntityRoad.Speed;
IWay rightEntry = GetRightEntryWay();
if ((rightEntry is Way) && ((Way)rightEntry).EntityRoad.Speed > result)
result = ((Way)rightEntry).EntityRoad.Speed;
return result;
}
/// <summary>
/// Перемещение ТП с перегона на перекресток
/// </summary>
/// <param name="wFrom">перегон, с которого происходит перемещение</param>
/// <param name="speed">скорость перемещения</param>
/// <returns>Фактически перемещенная часть ТП</returns>
private double MoveToCross(IWay wFrom, double speed, bool isHorisontal)
{
double avgDensity = wFrom.GetRegionLast().GetDensity();
double densityCoef = Way.CalcDensityCoef(wFrom.GetInfo().LinesCount, speed);
double velocity = CalcSpeedCoef() * ((speed / ModelConst.SPEED_COEF) - densityCoef * avgDensity);
double deltaFP = wFrom.GetRegionLast().FlowPart / ((isHorisontal) ? CrossRegion.Lenght : CrossRegion.Width)
* velocity * RouteEnvir.Instance.TimeScan;
deltaFP = CrossRegion.MoveToCross(wFrom.GetRegionLast(), deltaFP);
if (deltaFP != 0 && CrossRegion.FlowPart != 0)
CrossRegion.Velocity = velocity;
else if (CrossRegion.FlowPart == 0)
CrossRegion.Velocity = 0;
if (deltaFP < 0)
{ }
return deltaFP;
}
/// <summary>
/// Перемещение ТП с перекрестка на перегон
/// </summary>
/// <param name="wTo">перегон, на который идет перемещение</param>
/// <param name="flowPartSource">часть пототка перекрестка</param>
/// <param name="speed">максимальная скорость перемещения</param>
/// <param name="isHorisontal">горизонтальная ли улица для перемещения</param>
/// <returns>Фактически перемещенная часть ТП</returns>
private double MoveFromCross(IWay wTo, ref double flowPartSource, double speed, bool isHorisontal)
{
double avgDensity = wTo.GetRegionFirst().GetDensity();
double densityCoef = Way.CalcDensityCoef(wTo.GetInfo().LinesCount, speed);
double velocity = ((speed / ModelConst.SPEED_COEF) - densityCoef * avgDensity);
double deltaFP = flowPartSource / ((isHorisontal) ? CrossRegion.Lenght : CrossRegion.Width)
* velocity * RouteEnvir.Instance.TimeScan;
deltaFP = CrossRegion.MoveFromCross(wTo.GetRegionFirst(), ref flowPartSource, deltaFP);
wTo.GetRegionFirst().Velocity = (deltaFP != 0) ? velocity : 0;
return deltaFP;
}
/// <summary>
/// подсчет количества стоящих ТС на подходе
/// </summary>
/// <param name="wFrom"></param>
private double CalcNStop(IWay wFrom) {
double result = 0;
Region reg = wFrom.GetRegionLast();
while(reg != null && reg.Velocity == 0)
{
result += reg.FlowPart;
reg = reg.GetRegionPrev();
}
return result;
}
/// <summary>
/// возвращает суммарную задержку для всех подходов
/// взвешенную по интенсивностям
/// </summary>
/// <returns></returns>
public double CalcCrossDelay(bool isDirectSide)
{
int i;
if (isDirectSide)
i = 0;
else
i = 1;
double result = 0;
if (NMoved[i] != 0)
result = 1 * NStop[i] / NMoved[i];
return result;
}
/// <summary>
/// Перемещение ТП за интервал сканирования: части ТП забираются с подходов
/// части ТП перемещаются
/// </summary>
public void RunSimulationStep()
{
double timeOfPeriod = RouteEnvir.Instance.TimeCurrent % RouteEnvir.Instance.CalcMeasureInterval();
if (timeOfPeriod < 1.5 && timeOfPeriod > 0.5)
{
NStop = new double[2] { 0, 0 };
NMoved = new double[2] { 0, 0 };
}
//перемещение ТП с перекрестка на выходные перегоны
IWay leftExit = GetLeftExitWay();
double leftExitSpeed = ModelConst.SPEED_DEFAULT;
if (leftExit is Way)
leftExitSpeed = ((Way)leftExit).EntityRoad.Speed;
else if (leftExit is WayExit)
leftExitSpeed = ((WayExit)leftExit).GetInternalRoad().Speed;
MoveFromCross(leftExit, ref CrossRegion.ToLeftFlowPart, leftExitSpeed, true);
IWay rightExit = GetRightExitWay();
double rightExitSpeed = ModelConst.SPEED_DEFAULT;
if (rightExit is Way)
rightExitSpeed = ((Way)rightExit).EntityRoad.Speed;
else if (rightExit is WayExit)
rightExitSpeed = ((WayExit)rightExit).GetInternalRoad().Speed;
MoveFromCross(rightExit, ref CrossRegion.ToRightFlowPart, rightExitSpeed, true);
IWay topExit = GetTopExitWay();
MoveFromCross(topExit, ref CrossRegion.ToTopFlowPart, CalcVerticalSpeed(), false);
IWay botExit = GetBottomExitWay();
MoveFromCross(botExit, ref CrossRegion.ToBottomFlowPart, CalcVerticalSpeed(), false);
IWay leftWay = GetLeftEntryWay();
IWay rightWay = GetRightEntryWay();
//перемещение с перегонов на перекресток
if (GetLightStateFirst() == LightState.Green || GetLightStateFirst() == LightState.Yellow)
{
double leftSpeed = ModelConst.SPEED_DEFAULT;
if(leftWay is Way)
leftSpeed = ((Way)leftWay).EntityRoad.Speed;
else if(leftWay is WayEntry)
leftSpeed = ((WayEntry)leftWay).GetInternalRoad().Speed;
double deltaFP = MoveToCross(leftWay, leftSpeed, true);
if (!(leftWay is WayEntry))
NMoved[0] += deltaFP;
CrossRegion.ToRightFlowPart += deltaFP * leftWay.GetInfo().DirectPart / 100.0;
CrossRegion.ToBottomFlowPart += deltaFP * leftWay.GetInfo().RightPart / 100.0;
CrossRegion.ToTopFlowPart += deltaFP * leftWay.GetInfo().LeftPart / 100.0;
double rightSpeed = ModelConst.SPEED_DEFAULT;
if (rightWay is Way)
rightSpeed = ((Way)rightWay).EntityRoad.Speed;
else if (leftWay is WayEntry)
rightSpeed = ((WayEntry)rightWay).GetInternalRoad().Speed;
deltaFP = MoveToCross(rightWay, rightSpeed, true);
if (!(rightWay is WayEntry))
NMoved[1] += deltaFP;
CrossRegion.ToLeftFlowPart += deltaFP * rightWay.GetInfo().DirectPart / 100.0;
CrossRegion.ToTopFlowPart += deltaFP * rightWay.GetInfo().RightPart / 100.0;
CrossRegion.ToBottomFlowPart += deltaFP * rightWay.GetInfo().LeftPart / 100.0;
}
else if (GetLightStateSecond() == LightState.Green || GetLightStateSecond() == LightState.Yellow)
{
IWay way = GetTopEntryWay();
double deltaFP = MoveToCross(way, CalcVerticalSpeed(), false);
CrossRegion.ToBottomFlowPart += deltaFP * way.GetInfo().DirectPart / 100.0;
CrossRegion.ToLeftFlowPart += deltaFP * way.GetInfo().RightPart / 100.0;
CrossRegion.ToRightFlowPart += deltaFP * way.GetInfo().LeftPart / 100.0;
way = GetBottomEntryWay();
deltaFP = MoveToCross(way, CalcVerticalSpeed(), false);
CrossRegion.ToTopFlowPart += deltaFP * way.GetInfo().DirectPart / 100.0;
CrossRegion.ToRightFlowPart += deltaFP * way.GetInfo().RightPart / 100.0;
CrossRegion.ToLeftFlowPart += deltaFP * way.GetInfo().LeftPart / 100.0;
}
if (!(leftWay is WayEntry))
NStop[0] += CalcNStop(leftWay);
if (!(rightWay is WayEntry))
NStop[1] += CalcNStop(rightWay);
}
/// <summary>
/// Коэффициент уменьшения скорости на начале зеленого
/// и на желтом сигнале светофора
/// </summary>
/// <returns></returns>
private double CalcSpeedCoef() {
LightState light1 = GetLightStateFirst();
LightState light2 = GetLightStateSecond();
double speedCoef = 1;
if (light1 == LightState.Yellow || light2 == LightState.Yellow)
speedCoef = 0.5;
else
{
if(GreenTime > 6.0)
speedCoef = 1.0;
else
speedCoef = GreenTime / 6.0;
}
return speedCoef;
}
private double GreenTime;
/// <summary>
/// Получение состояния светофоров первой группы
/// (разрешает движение по магистральной улице во время первого такта)
/// </summary>
public LightState GetLightStateFirst()
{
double timeOfCycle = CalcTimeOfCycle();
CrossPlan cp = GetCrossPlan();
int t;
if (timeOfCycle < (t = cp.P1MainInterval))
{
GreenTime = timeOfCycle;
return LightState.Green;
}
else if (timeOfCycle < (t += cp.P1MediateInterval))
return LightState.Yellow;
else if (timeOfCycle < (t += cp.P2MainInterval))
return LightState.Red;
else
return LightState.YellowRed;
}
/// <summary>
/// Получение состояния светофоров второй группы
/// (разрешает движение по второстепенной улице во время второго такта)
/// </summary>
public LightState GetLightStateSecond()
{
double timeOfCycle = CalcTimeOfCycle();
CrossPlan cp = GetCrossPlan();
int t;
if (timeOfCycle < (t = cp.P1MainInterval))
return LightState.Red;
else if (timeOfCycle < (t += cp.P1MediateInterval))
return LightState.YellowRed;
else if (timeOfCycle < (t += cp.P2MainInterval))
{
GreenTime = timeOfCycle - cp.P1MediateInterval - cp.P1MainInterval;
return LightState.Green;
}
else
return LightState.Yellow;
}
public NodeCross(Cross cross)
{
EntityCross = cross;
CrossRegion = new RegionCross(this);
NStop = new double[2] { 0, 0 };
NMoved = new double[2] { 0, 0 };
}
}
}
|
using Serenity;
using Serenity.Data;
using Serenity.Services;
using System;
using System.Data;
using MyRequest = Serenity.Services.ListRequest;
using MyResponse = Serenity.Services.ListResponse<ARLink.Default.EmployeeSalaryRow>;
using MyRow = ARLink.Default.EmployeeSalaryRow;
namespace ARLink.Default
{
public interface IEmployeeSalaryListHandler : IListHandler<MyRow, MyRequest, MyResponse> {}
public class EmployeeSalaryListHandler : ListRequestHandler<MyRow, MyRequest, MyResponse>, IEmployeeSalaryListHandler
{
public EmployeeSalaryListHandler(IRequestContext context)
: base(context)
{
}
}
} |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using RealEstate.BusinessObjects;
using RealEstate.DataAccess;
namespace RealEstate.BusinessLogic
{
public class ContractAdvertisingBL
{
#region ***** Init Methods *****
ContractAdvertisingDA objContractAdvertisingDA;
public ContractAdvertisingBL()
{
objContractAdvertisingDA = new ContractAdvertisingDA();
}
#endregion
#region ***** Get Methods *****
/// <summary>
/// Get ContractAdvertising by contractadvertisingid
/// </summary>
/// <param name="contractadvertisingid">ContractAdvertisingID</param>
/// <returns>ContractAdvertising</returns>
public ContractAdvertising GetByContractAdvertisingID(int contractadvertisingid)
{
return objContractAdvertisingDA.GetByContractAdvertisingID(contractadvertisingid);
}
/// <summary>
/// Get all of ContractAdvertising
/// </summary>
/// <returns>List<<ContractAdvertising>></returns>
public List<ContractAdvertising> GetList()
{
string cacheName = "lstContractAdvertising";
if( ServerCache.Get(cacheName) == null )
{
ServerCache.Insert(cacheName, objContractAdvertisingDA.GetList(), "ContractAdvertising");
}
return (List<ContractAdvertising>) ServerCache.Get(cacheName);
}
/// <summary>
/// Get DataSet of ContractAdvertising
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetDataSet()
{
string cacheName = "dsContractAdvertising";
if( ServerCache.Get(cacheName) == null )
{
ServerCache.Insert(cacheName, objContractAdvertisingDA.GetDataSet(), "ContractAdvertising");
}
return (DataSet) ServerCache.Get(cacheName);
}
/// <summary>
/// Get all of ContractAdvertising paged
/// </summary>
/// <param name="recperpage">recperpage</param>
/// <param name="pageindex">pageindex</param>
/// <returns>List<<ContractAdvertising>></returns>
public List<ContractAdvertising> GetListPaged(int recperpage, int pageindex)
{
return objContractAdvertisingDA.GetListPaged(recperpage, pageindex);
}
/// <summary>
/// Get DataSet of ContractAdvertising paged
/// </summary>
/// <param name="recperpage">recperpage</param>
/// <param name="pageindex">pageindex</param>
/// <returns>DataSet</returns>
public DataSet GetDataSetPaged(int recperpage, int pageindex)
{
return objContractAdvertisingDA.GetDataSetPaged(recperpage, pageindex);
}
#endregion
#region ***** Add Update Delete Methods *****
/// <summary>
/// Add a new ContractAdvertising within ContractAdvertising database table
/// </summary>
/// <param name="obj_contractadvertising">ContractAdvertising</param>
/// <returns>key of table</returns>
public int Add(ContractAdvertising obj_contractadvertising)
{
ServerCache.Remove("ContractAdvertising", true);
return objContractAdvertisingDA.Add(obj_contractadvertising);
}
/// <summary>
/// updates the specified ContractAdvertising
/// </summary>
/// <param name="obj_contractadvertising">ContractAdvertising</param>
/// <returns></returns>
public void Update(ContractAdvertising obj_contractadvertising)
{
ServerCache.Remove("ContractAdvertising", true);
objContractAdvertisingDA.Update(obj_contractadvertising);
}
/// <summary>
/// Delete the specified ContractAdvertising
/// </summary>
/// <param name="contractadvertisingid">ContractAdvertisingID</param>
/// <returns></returns>
public void Delete(int contractadvertisingid)
{
ServerCache.Remove("ContractAdvertising", true);
objContractAdvertisingDA.Delete(contractadvertisingid);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace statistics {
// This class provides an interface to manage easily all the
// treat during a simulation
public class TreatList {
// convention : I do not have : -1 / Do have, no number required : 0 / Do have, level of X : X
// Attack
public Treat Assassin { get; set; } // OK
public Treat Brutal { get; set; } // OK
public Treat Strengh { get; set; } // OK
public Treat ArmourPiercing { get; set; } // OK
public Treat Sharp { get; set; } // OK
public Treat Strong { get; set; } // OK
public Treat Weak { get; set; } // OK
public Treat UnbreakableStrike { get; set; } // OK
// Defence
public Treat Parry { get; set; } // OK
public Treat Armour { get; set; } // OK
public Treat Toughness { get; set; } // OK
public Treat Durable { get; set; } // OK
public Treat ImpenetrableDefence { get; set; } // OK
// Ki
public Treat ForceOfWill { get; set; } // KOKO
public Treat IronMind { get; set; } // KOKO
public Treat StrongMind { get; set; } // KOKO
public Treat WeakMind { get; set; } // KOKO
// reroll
public Treat MartialProwess { get; set; } // KOKO
public Treat Dodge { get; set; } // KOKO // KOKO
public Treat Feint { get; set; }
// shoot
public Treat RangedDefence { get; set; } // KOKO
public Treat RapidFire { get; set; } // KOKO
public Treat Bonus { get; set; } // KOKO
// Dictionnary of the Treats
// The ki is the name of the treat
public Dictionary<string, Treat> TreatDictionnary { get; set; }
public void InitializeValue()
{
// Attack
Assassin = new Treat("Assassin", (int)Treat.TreatType.PhysicAttack +
(int)Treat.TreatType.RangeAttack, pValueNeed: false);
Brutal = new Treat("Brutal", (int)Treat.TreatType.PhysicAttack +
(int)Treat.TreatType.RangeAttack);
Strengh = new Treat("Strengh", Treat.TreatType.PhysicAttack);
ArmourPiercing = new Treat("Armour Piercing", Treat.TreatType.PhysicAttack, pValueNeed: false);
Sharp = new Treat("Sharp", Treat.TreatType.PhysicAttack, pValueNeed: false);
Strong = new Treat("Strong", Treat.TreatType.PhysicAttack, pValueNeed: false);
UnbreakableStrike = new Treat("Unbreakable Strike", Treat.TreatType.PhysicAttack);
Weak = new Treat("Weak", Treat.TreatType.PhysicAttack, pValueNeed: false);
// Defence
Parry = new Treat("Parry", Treat.TreatType.PhysicDefence);
Armour = new Treat("Armour", (int)Treat.TreatType.PhysicDefence +
(int)Treat.TreatType.RangeDefence);
Toughness = new Treat("Toughness", (int)Treat.TreatType.PhysicDefence +
(int)Treat.TreatType.RangeDefence);
Durable = new Treat("Durable", (int)Treat.TreatType.PhysicDefence +
(int)Treat.TreatType.RangeDefence, pValueNeed: false);
ImpenetrableDefence = new Treat("Impenetrable Defence",
Treat.TreatType.PhysicDefence, pValueNeed: false);
// Ki
ForceOfWill = new Treat("Force of Will", Treat.TreatType.KiAttack);
IronMind = new Treat("Iron Mind", Treat.TreatType.KiDefence);
StrongMind = new Treat("Strong Mind", (int)Treat.TreatType.KiAttack
+ (int)Treat.TreatType.KiDefence);
WeakMind = new Treat("Weak Mind", (int)Treat.TreatType.KiAttack
+ (int)Treat.TreatType.KiDefence);
// reroll
MartialProwess = new Treat("Martial Prowess", (int)Treat.TreatType.PhysicAttack
+ (int)Treat.TreatType.PhysicDefence);
Dodge = new Treat("Dodge", Treat.TreatType.PhysicDefence);
Feint = new Treat("Feint", (int)Treat.TreatType.PhysicAttack);
// shoot
RangedDefence = new Treat("Ranged Defence", (int)Treat.TreatType.RangeDefence);
RapidFire = new Treat("Rapid Fire", (int)Treat.TreatType.RangeAttack);
Bonus = new Treat("Bonus (Exhausted, big...)", (int)Treat.TreatType.RangeDefence);
}
private static void AddToDic(Dictionary<string, Treat> Dic, Treat Val)
{
Dic.Add(Val.Name, Val);
}
private void InitializeDictionary()
{
TreatDictionnary = new Dictionary<string, Treat>();
AddToDic(TreatDictionnary, Assassin);
AddToDic(TreatDictionnary, Brutal);
AddToDic(TreatDictionnary, Strengh);
AddToDic(TreatDictionnary, ArmourPiercing);
AddToDic(TreatDictionnary, Sharp);
AddToDic(TreatDictionnary, Strong);
AddToDic(TreatDictionnary, UnbreakableStrike);
AddToDic(TreatDictionnary, Weak);
AddToDic(TreatDictionnary, Parry);
AddToDic(TreatDictionnary, Armour);
AddToDic(TreatDictionnary, Toughness);
AddToDic(TreatDictionnary, Durable);
AddToDic(TreatDictionnary, ImpenetrableDefence);
AddToDic(TreatDictionnary, ForceOfWill);
AddToDic(TreatDictionnary, IronMind);
AddToDic(TreatDictionnary, StrongMind);
AddToDic(TreatDictionnary, WeakMind);
AddToDic(TreatDictionnary, MartialProwess);
AddToDic(TreatDictionnary, Dodge);
AddToDic(TreatDictionnary, Feint);
AddToDic(TreatDictionnary, RangedDefence);
AddToDic(TreatDictionnary, RapidFire);
AddToDic(TreatDictionnary, Bonus);
}
public TreatList()
{
InitializeValue();
InitializeDictionary();
}
public List<Treat> getTreatList()
{
// The string is the name
// The boolean indicates if the treat needs a value
var query =
from T in TreatDictionnary.Values
select T;
return query.ToList();
}
public List<Treat> getAttackerMeleeList()
{
// The string is the name
// The boolean indicates if the treat needs a value
var query =
from T in TreatDictionnary.Values
where (T.IsType(Treat.TreatType.PhysicAttack))
select T;
return query.ToList();
}
public List<Treat> getDefenderMeleeList()
{
// The string is the name
// The boolean indicates if the treat needs a value
var query =
from T in TreatDictionnary.Values
where (T.IsType(Treat.TreatType.PhysicDefence))
select T;
return query.ToList();
}
public bool Has(string name)
{
try {
return TreatDictionnary[name].Has;
} catch {
return false;
}
}
public void ResetTreatList()
{
foreach (KeyValuePair<string, statistics.Treat> kvp in TreatDictionnary) {
TreatDictionnary[kvp.Key].Has = false;
}
}
public void Modify(List<Tuple<string, string>> Treats)
{
if (Treats == null) return;
foreach (Tuple<string, string> T in Treats) {
Modify(T.Item1, T.Item2);
}
}
private void Modify(string treat, string value)
{
TreatDictionnary[treat].Has = true;
if (TreatDictionnary[treat].NeedValue) {
TreatDictionnary[treat].Value = int.Parse(value);
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace RMAT3.Models
{
public class UserGroup
{
public UserGroup()
{
UserPreferences = new List<UserPreference>();
}
public int UserGroupId { get; set; }
public int UserId { get; set; }
public DateTime AddTs { get; set; }
public string UpdatedByUserId { get; set; }
public DateTime UpdatedTs { get; set; }
public bool IsActiveInd { get; set; }
public string GroupCd { get; set; }
public string GroupNm { get; set; }
public virtual ICollection<UserPreference> UserPreferences { get; set; }
}
}
|
namespace E05_CalculateFactorialSum
{
using System;
public class CalculateFactorialSum
{
public static void Main(string[] args)
{
// Write a program that, for a given two integer
// numbers n and x, calculates the
// sum S = 1 + 1!/x + 2!/x2 + … + n!/x^n.
// Use only one loop. Print the result with 5 digits
// after the decimal point.
// Examples:
//
// n x S
// 3 2 2.75000
// 4 3 2.07407
// 5 -4 0.75781
Console.WriteLine("Please, enter two integer numbers !");
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
Console.Write("x = ");
int x = int.Parse(Console.ReadLine());
double result = 1;
double factorial = 1;
int xAtpowerN = 1;
for (int index = 1; index <= n; index++)
{
factorial *= index;
xAtpowerN *= x;
result += factorial / xAtpowerN;
}
Console.WriteLine("Result = {0}", result);
}
}
}
|
using ETModel;
namespace ETHotfix
{
[Message(CommonModelOpcode.User)]
public partial class User {}
[Message(CommonModelOpcode.Commodity)]
public partial class Commodity {}
[Message(CommonModelOpcode.SignInAward)]
public partial class SignInAward {}
[Message(CommonModelOpcode.UserSingInState)]
public partial class UserSingInState {}
[Message(CommonModelOpcode.GetGoodsOne)]
public partial class GetGoodsOne {}
//房间信息
[Message(CommonModelOpcode.RoomInfo)]
public partial class RoomInfo {}
//游戏匹配房间配置
[Message(CommonModelOpcode.MatchRoomConfig)]
public partial class MatchRoomConfig {}
//匹配到的玩家信息
[Message(CommonModelOpcode.MatchPlayerInfo)]
public partial class MatchPlayerInfo {}
}
namespace ETHotfix
{
public static partial class CommonModelOpcode
{
public const ushort User = 11001;
public const ushort Commodity = 11002;
public const ushort SignInAward = 11003;
public const ushort UserSingInState = 11004;
public const ushort GetGoodsOne = 11005;
public const ushort RoomInfo = 11006;
public const ushort MatchRoomConfig = 11007;
public const ushort MatchPlayerInfo = 11008;
}
}
|
using Redis.Cache.Sample.Services.Base;
using Redis.Cache.Sample.Services.MemoryCache;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace Redis.Cache.Sample.Services.RedisCache
{
public class RedisCacheService : IRedisCacheService
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
}
public async Task<T> GetValue<T>(string key)
{
var rDatabse = _connectionMultiplexer.GetDatabase();
var stringValue = await rDatabse.StringGetAsync(key);
if (stringValue.IsNullOrEmpty || !stringValue.HasValue)
{
return default;
}
return JsonSerializer.Deserialize<T>(stringValue);
}
public async Task RemoveValue(string key)
{
var rDatabse = _connectionMultiplexer.GetDatabase();
if (rDatabse.KeyExists(key) && !await rDatabse.KeyDeleteAsync(key))
{
//Shoul be logged or apply resilience
throw new Exception($"Cannot delete value with key '{key}' in database");
}
}
public async Task SetValue<T>(string key, T value)
{
var rDatabse = _connectionMultiplexer.GetDatabase();
if (!rDatabse.StringSet(key, JsonSerializer.Serialize(value)))
{
//Shoul be logged or apply resilience
throw new Exception("Cannot insert value in database");
}
}
public async Task SetValue<T>(string key, T value, TimeSpan expirationTimeSpan)
{
var rDatabse = _connectionMultiplexer.GetDatabase();
await rDatabse.StringSetAsync(key, JsonSerializer.Serialize(value), expirationTimeSpan);
}
public async Task PublishMessage(string message)
{
var rDatabse = _connectionMultiplexer.GetDatabase();
await rDatabse.PublishAsync("channelName", message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using prjQLNK.Control;
using prjQLNK.Model;
namespace prjQLNK
{
public partial class frmChiTietNguoiMat : DevExpress.XtraEditors.XtraForm
{
public frmChiTietNguoiMat()
{
InitializeComponent();
}
Process ctrl;
DataTable tblBaoTu, tblCanBo;
private void LoadTTBaoTu()
{
ctrl = new Process();
string makhaisinh = MKSNguoiMat.MaKhaiSinh;
tblBaoTu = ctrl.LayDuLieuCoDK("BAOTU", "MAKHAISINH='" + makhaisinh + "'");
}
private void LayTenCB()
{
ctrl = new Process();
tblCanBo = ctrl.LayDuLieuCoDK("CANBO", "MACANBO='" + macanbo + "'");
GanTenCanBo(tblCanBo);
}
private void GanTenCanBo(DataTable tbl)
{
if (tbl.Rows.Count > 0)
{
DataRow Dong = tbl.Rows[0];
lblNguoilap.Text = Dong["TENCANBO"].ToString();
}
}
string macanbo;
private void GanDuLieu(DataTable tbl)
{
if (tbl.Rows.Count > 0)
{
DataRow Dong = tbl.Rows[0];
dpkNgaymat.Text = Dong["NGAYMAT"].ToString();
txtLydomat.Text = Dong["LYDOMAT"].ToString();
txtGhichu.Text = Dong["GHICHU"].ToString();
txtNguoikhai.Text = Dong["NGUOIKHAI"].ToString();
lblNgayKhai.Text = Dong["NGAYKHAI"].ToString();
macanbo = Dong["MACANBO"].ToString();
LayTenCB();
}
}
private void frmChiTietNguoiMat_Load(object sender, EventArgs e)
{
DataProvider.connecstring = Ketnoi.strConnection;
LoadTTBaoTu();
GanDuLieu(tblBaoTu);
}
private bool BatLoi()
{
if (dpkNgaymat.Value.Day> NgayThang.ngay || dpkNgaymat.Value.Month>NgayThang.thang || dpkNgaymat.Value.Year>NgayThang.nam)
{
Messages.MessagesBox.Error("Ngày mất không hợp lệ!");
dpkNgaymat.Focus();
return false;
}
else if (txtLydomat.Text == "")
{
Messages.MessagesBox.Error("Nhập lý do mất!");
txtLydomat.Focus();
return false;
}
else if (txtNguoikhai.Text == "")
{
Messages.MessagesBox.Error("Nhập người khai tử!");
txtNguoikhai.Focus();
return false;
}
else
return true;
}
private void CapNhatDong(DataTable tbl)
{
DataRow Dong = tbl.Rows[0];
Dong["NGAYMAT"] = dpkNgaymat.Value;
Dong["LYDOMAT"] = txtLydomat.Text;
Dong["GHICHU"] = txtGhichu.Text;
Dong["NGUOIKHAI"] = txtNguoikhai.Text;
Dong["NGAYKHAI"] = DateTime.Parse(lblNgayKhai.Text);
Dong["MACANBO"] = ThongTinDN.Macanbo;
}
bool t = true;
private void AnHien()
{
dpkNgaymat.Enabled = t;
txtGhichu.Enabled = t;
txtLydomat.Enabled = t;
txtNguoikhai.Enabled = t;
}
private void btnSua_Click(object sender, EventArgs e)
{
if (btnSua.Text == "Sửa")
{
btnSua.Text = "Lưu";
btnSua.Image = Properties.Resources.Save1;
btnDong.Image = Properties.Resources.cancel;
t = true;
AnHien();
btnDong.Text = "Hủy";
lblNguoilap.Text = ThongTinDN.Tencanbo;
}
else if (btnSua.Text == "Lưu")
{
if (BatLoi())
{
if (Messages.MessagesBox.YesNo("Lưu thay đổi ?") == DialogResult.Yes)
{
ctrl = new Process();
CapNhatDong(tblBaoTu);
ctrl.CapNhatDuLieuBang1("BAOTU", "1=1", tblBaoTu);
t = false;
AnHien();
Messages.MessagesBox.Success("Đã lưu.");
btnSua.Text = "Sửa";
btnSua.Image = Properties.Resources.edit;
btnDong.Image = Properties.Resources.Close;
btnDong.Text = "Đóng";
}
}
}
}
private void btnDong_Click(object sender, EventArgs e)
{
if (btnDong.Text == "Hủy")
{
t = false;
AnHien();
btnDong.Text = "Đóng";
btnSua.Text = "Sửa";
btnSua.Image = Properties.Resources.edit;
btnDong.Image = Properties.Resources.Close;
GanDuLieu(tblBaoTu);
}
else
this.Close();
}
}
} |
using System;
using System.Globalization;
using System.Net;
using System.Web.Mvc;
using HtmlApp.Filters;
using Libraries.Dal;
using Libraries.Enums;
using Libraries.Models;
using Libraries.Properties;
namespace HtmlApp.Controllers
{
public class TransactionController : Controller
{
private XmlDal _xmlDal;
public XmlDal XmlDal => _xmlDal ?? ( _xmlDal = new XmlDal() );
private LocalDal _localDal;
public LocalDal LocalDal => _localDal ?? ( _localDal = new LocalDal() );
[HttpGet]
public ActionResult TransactionHistory()
{
try
{
var userId = Session["UserId"].ToString();
var data = Properties.Settings.Default.UseXmlDataStore
? XmlDal.GetTransactionHistory( userId )
: LocalDal.GetTransactionHistory( userId );
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = Json(data)
};
}
catch
{
return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
}
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Transaction( TransactionViewModel model )
{
//todo: validate that transaction view model properly
try
{
if ( Properties.Settings.Default.UseXmlDataStore )
{
XmlDal.SubmitTransaction( model );
}
else
{
LocalDal.SubmitTransaction( model );
}
return new HttpStatusCodeResult( HttpStatusCode.OK );
}
catch
{
return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
}
}
/************************************************************
*************************************************************
**
** Console Endpoints and Helper Methods
**
*************************************************************
*************************************************************/
[HttpGet, AuthorizeConsoleAppUser]
public ActionResult TransactionHistoryForConsole()
{
var valid = Session["UserId"] != null;
try
{
if ( valid )
{
var transactions = XmlDal.GetTransactionHistory( Session["UserId"].ToString() );
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = transactions
};
}
}
catch
{
return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
}
return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
}
[AuthorizeConsoleAppUser]
public ActionResult TransactionForConsole( TransactionRequestModel model )
{
try
{
if ( model.Type == TransactionType.GetHistory )
{
var transactionHistory = "No transactions found";
var transactions = XmlDal.GetTransactionHistory( model.UserId );
transactionHistory = GetTransactionSummaryString( transactions );
return new ContentResult {Content = transactionHistory};
}
var transactionModel = new TransactionViewModel
{
UserEmail = model.UserId,
Date = DateTime.UtcNow.ToString( CultureInfo.InvariantCulture ),
IsWithdraw = model.Type == TransactionType.Withdraw,
IsDeposit = model.Type == TransactionType.Deposit,
Amount = model.Amount ?? 0,
};
return new ContentResult
{
Content = XmlDal.SubmitTransaction( transactionModel )
? "Transaction was successfully tendered."
: "Transaction request denied"
};
}
catch (Exception)
{
return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
}
}
private string GetTransactionSummaryString(TransactionViewModel[] transactions)
{
var summaryString = "";
var balance = 0.0;
foreach ( var transaction in transactions )
{
balance += transaction.IsDeposit
? transaction.Amount
: transaction.Amount * -1;
summaryString += " "+transaction + "\n";
}
return string.Format( Resources.TransactionHistoryString, summaryString, balance );
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Newtonsoft.Json;
namespace server.Models {
public class JWT {
public JWT( GithubUser ghu ) {
_GhU = ghu;
}
private GithubUser _GhU;
private static readonly DateTime UnixEpoch = new DateTime( 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc );
public long sub { get { return _GhU.id; } }
public long iat { get { return DateTime.Now.Ticks; } }
public long exp { get { return DateTime.Now.Add( new TimeSpan( 1, 0, 0, 0 ) ).Ticks; } }
public string AsJwt() {
DateTime now = DateTime.UtcNow;
var claimset = new {
sub = _GhU.id,
iat = ((int)now.Subtract( UnixEpoch ).TotalSeconds).ToString( CultureInfo.InvariantCulture ),
exp = ((int)now.AddMinutes( 55 ).Subtract( UnixEpoch ).TotalSeconds).ToString( CultureInfo.InvariantCulture )
};
return string.Empty;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TankBot
{
public class Vehicle
{
public VehicleInfo vInfo
{
get
{
if (this.icon != null && this.icon != "")
{
string[] sp = this.icon.Split('/');
string last = sp[sp.Length - 1];
last = last.Substring(last.IndexOf('-') + 1);
string tankname = last.Substring(0, last.Length - 4);
return VehicleInfoGet.get(tankname);
}
else
return VehicleInfoGet.get("");
}
}
public void Clear()
{
username = "";
tankName = "";
uid = 0;
posScreen.Clear();
posRaw.Clear();
visible_on_minimap = false;
visible_on_screen = false;
visible_on_screen_last_ticks = 0;
speed = 0;
direction = 0;
cameraDirection = 0;
health = 1000;
pos_raw_history.Clear();
}
public string username = ""; // bbsang, duck_german, etc.s
public string tankName = ""; // kv-1s, is, etc.
public int uid; // an ??internal?? id
public bool posScreenUpdated;
public List<Tuple<Point, DateTime>> pos_raw_history = new List<Tuple<Point, DateTime>>();
public Point posScreen = new Point();
private Point _posRaw = new Point();
public double speedMinimapBase
{
get
{
int len = pos_raw_history.Count;
try
{
Tuple<Point, DateTime> last = pos_raw_history[len - 1];
for (int i = 0; i < len; i++)
{
Tuple<Point, DateTime> now = pos_raw_history[i];
if ((last.Item2 - now.Item2).Seconds < 1)
{
double meterPerSecond = TBMath.distance(last.Item1, now.Item1) / (last.Item2 - now.Item2).Seconds * TankBot.getInstance().mapSacle;
return meterPerSecond * 3.6; // km per hour
}
}
}
catch
{
return 0;
}
return 0;
}
}
public Point posRaw
{
get
{
return _posRaw;
}
set
{
_posRaw = value;
pos_raw_history.Add(new Tuple<Point, DateTime>(value, DateTime.Now));
}
}
public bool visible_on_screen;
public long visible_on_screen_last_ticks;
public bool visible_on_minimap;
public double speed;
public int health = 1000;
public Point pos
{
get { return new Point((posRaw.x + 105) / 21 + 1, (posRaw.y + 105) / 21 + 1); }
}
/// <summary>
/// north(up_minimap) consider 0 degree
/// east(right) consider 90 degree
/// wese(left) consider -90 degree
/// south(down) is -180 as well as 180
/// vehicle head direction
/// </summary>
public bool directionUpdated;
public double direction;
// camera's direction
public bool cameraDirectionUpdated;
public double cameraDirection;
public string icon;
}
}
|
using System.Collections.Generic;
using UnityEngine;
using System;
[System.Serializable]
public class TouchManager
{
public const int MAX_MULTITOUCH = 2;
public Action<Vector2>[] movementAction
= new Action<Vector2>[3];
public Action[] touchAction
= new Action[3];
public int[] TouchFingerId { get; private set; }
= new int[MAX_MULTITOUCH];
private float buttonExtent = 0.5f;
public float ButtonExtent
{
get => buttonExtent;
set => buttonExtent = Mathf.Clamp01(value);
}
private Vector2 ResolutionPos(Touch touch) => new Vector2(
touch.position.x / GameManager.ScreenSize.x,
touch.position.y / GameManager.ScreenSize.y);
public TouchManager()
{
for (int i = 0; i < MAX_MULTITOUCH; i++)
TouchFingerId[i] = -1;
}
#if UNITY_EDITOR
public void TouchUpdate()
{
Touch touch = default;
Vector2 touchPos = new Vector2(Input.mousePosition.x / GameManager.ScreenSize.x,
Input.mousePosition.y / GameManager.ScreenSize.y);
if (Input.GetMouseButtonDown(0)
&& touchPos.x < buttonExtent)
{
touch.fingerId = 1;
touch.position = Input.mousePosition;
TouchBegin(0, touch, touch.position);
}
else if (Input.GetMouseButton(0))
{
touch.fingerId = 1;
touch.position = Input.mousePosition;
TouchMove(0, touch, touch.position);
}
else if (Input.GetMouseButtonUp(0))
{
TouchEnd(0, touch, touch.position);
}
if (Input.GetKeyDown(KeyCode.Space))
{
touch.fingerId = 2;
TouchBegin(1, touch);
}
else if (Input.GetKey(KeyCode.Space))
{
TouchMove(1, touch);
}
else if (Input.GetKeyUp(KeyCode.Space))
{
TouchEnd(1, touch);
}
}
#else
public void TouchUpdate()
{
for(int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
switch (touch.phase)
{
case TouchPhase.Began:
if (ResolutionPos(touch).x < buttonExtent
&& TouchFingerId[0] == -1)
{
TouchBegin(0, touch, touch.position);
}
else if (ResolutionPos(touch).x > buttonExtent
&& TouchFingerId[1] == -1)
{
TouchBegin(1, touch);
}
break;
case TouchPhase.Moved:
case TouchPhase.Stationary:
if (TouchFingerId[0] != -1
&& touch.fingerId == TouchFingerId[0])
{
TouchMove(0, touch, touch.position);
}
else if (TouchFingerId[1] != 1
&& touch.fingerId == TouchFingerId[1])
{
TouchMove(1, touch);
}
break;
case TouchPhase.Ended:
case TouchPhase.Canceled:
if (touch.fingerId == TouchFingerId[0])
{
TouchEnd(0, touch, touch.position);
}
else if(touch.fingerId == TouchFingerId[1])
{
TouchEnd(1, touch);
}
break;
}
}
}
#endif
private void TouchBegin(int fingerId, Touch touch, Vector2 vec)
{
TouchFingerId[fingerId] = touch.fingerId;
movementAction[0]?.Invoke(vec);
}
private void TouchBegin(int fingerId, Touch touch)
{
TouchFingerId[fingerId] = touch.fingerId;
touchAction[0]?.Invoke();
}
private void TouchMove(int fingerId, Touch touch, Vector2 vec)
{
movementAction[1]?.Invoke(vec);
}
private void TouchMove(int fingerId, Touch touch)
{
touchAction[1]?.Invoke();
}
private void TouchEnd(int fingerId, Touch touch, Vector2 vec)
{
TouchFingerId[fingerId] = -1;
movementAction[2]?.Invoke(vec);
}
private void TouchEnd(int fingerId, Touch touch)
{
TouchFingerId[fingerId] = -1;
touchAction[2]?.Invoke();
}
} |
using System;
using MCCForms.Droid;
[assembly: Xamarin.Forms.Dependency (typeof (DocumentsPath_Droid))] //How to use in Forms project: DependencyService.Get<IDocumentsPath> ().GetDocumentsPath();
namespace MCCForms.Droid
{
public class DocumentsPath_Droid : IDocumentsPath
{
public DocumentsPath_Droid()
{
}
public string GetDocumentsPath ()
{
return Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
}
}
} |
namespace OmniGui.Layouts
{
using System;
using System.Linq;
using System.Reactive.Linq;
using Geometry;
using Zafiro.PropertySystem.Standard;
public class TextBoxView : Layout
{
public static readonly ExtendedProperty TextProperty = OmniGuiPlatform.PropertyEngine.RegisterProperty("Text",
typeof(TextBoxView),
typeof(string), new PropertyMetadata { DefaultValue = null });
public static readonly ExtendedProperty FontSizeProperty = OmniGuiPlatform.PropertyEngine.RegisterProperty("FontSize",
typeof(TextBoxView),
typeof(string), new PropertyMetadata { DefaultValue = 16F });
public static readonly ExtendedProperty AcceptsReturnProperty = OmniGuiPlatform.PropertyEngine.RegisterProperty("AcceptsReturn",
typeof(TextBoxView),
typeof(bool), new PropertyMetadata { DefaultValue = false });
private IDisposable changedSubscription;
private int cursorPositionOrdinal;
private IDisposable cursorToggleChanger;
private bool isCursorVisible;
private bool isFocused;
public TextBoxView(Platform platform) : base(platform)
{
var changedObservable = GetChangedObservable(TextProperty);
FormattedText = new FormattedText(Platform.TextEngine)
{
FontSize = 16,
Brush = new Brush(Colors.Black),
Constraint = Size.Infinite,
FontName = "Arial",
FontWeight = FontWeights.Normal
};
Pointer.Down.Subscribe(point =>
{
Platform.RenderSurface.ShowVirtualKeyboard();
Platform.RenderSurface.SetFocusedElement(this);
});
Keyboard.KeyInput.Where(Filter).Subscribe(args => AddText(args.Text));
Keyboard.SpecialKeys.Subscribe(ProcessSpecialKey);
NotifyRenderAffectedBy(TextProperty, FontSizeProperty);
Platform.RenderSurface.FocusedElement.Select(layout => layout == this)
.Subscribe(isFocused => IsFocused = isFocused);
GetChangedObservable(FontSizeProperty).Subscribe(o =>
{
if (FormattedText != null && o != null)
{
FormattedText.FontSize = (float)o;
}
});
changedSubscription = changedObservable
.Subscribe(o =>
{
FormattedText.Text = (string)o;
EnforceCursorLimits();
ForceRender();
});
}
private static Func<TextInputArgs, bool> Filter
{
get
{
return args =>
{
var isFiltered = args.Text.ToCharArray().First() != Chars.Backspace;
return isFiltered;
};
}
}
private bool IsFocused
{
get => isFocused;
set
{
if (isFocused != value)
{
if (value)
{
CreateCaretBlink();
}
else
{
DisableCaretBlink();
}
}
isFocused = value;
}
}
private bool IsCursorVisible
{
get => isCursorVisible;
set
{
isCursorVisible = value;
ForceRender();
}
}
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
private int CursorPositionOrdinal
{
get => cursorPositionOrdinal;
set
{
if (Text == null || value > Text.Length || value < 0)
{
return;
}
cursorPositionOrdinal = value;
ForceRender();
}
}
public string FontFamily => FormattedText.FontName;
private FormattedText FormattedText { get; }
private void DisableCaretBlink()
{
cursorToggleChanger?.Dispose();
}
private void CreateCaretBlink()
{
cursorToggleChanger?.Dispose();
IsCursorVisible = true;
var timelyObs = Observable.Interval(TimeSpan.FromSeconds(0.4));
cursorToggleChanger = timelyObs.Subscribe(_ => SwitchCursorVisibility());
}
private void EnforceCursorLimits()
{
if (Text?.Length < CursorPositionOrdinal)
{
CursorPositionOrdinal = Text.Length;
}
}
private void ProcessSpecialKey(KeyArgs args)
{
if (args.Key == MyKey.RightArrow)
{
CursorPositionOrdinal++;
}
else if (args.Key == MyKey.LeftArrow)
{
CursorPositionOrdinal--;
}
else if (args.Key == MyKey.Backspace)
{
RemoveBefore();
}
else if (args.Key == MyKey.Delete)
{
RemoveAfter();
}
}
private void SwitchCursorVisibility()
{
IsCursorVisible = !IsCursorVisible;
}
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public override void Render(IDrawingContext drawingContext)
{
if (!string.IsNullOrEmpty(Text))
{
drawingContext.DrawText(FormattedText, VisualBounds.Point, VisualBounds);
}
DrawCursor(drawingContext);
}
private void DrawCursor(IDrawingContext drawingContext)
{
if (IsCursorVisible && IsFocused)
{
var line = GetCursorSegment();
drawingContext.DrawLine(new Pen(new Brush(Colors.Black), 1), line.P1, line.P2);
}
}
private Segment GetCursorSegment()
{
var x = GetCursorX();
var y = GetCursorY();
var startPoint = new Point(x + VisualBounds.X, VisualBounds.Y);
var endPoint = new Point(x + VisualBounds.X, y + VisualBounds.Y);
return new Segment(startPoint, endPoint);
}
private double GetCursorY()
{
return Platform.TextEngine.GetHeight(FormattedText.FontName, FormattedText.FontSize);
}
private double GetCursorX()
{
if (string.IsNullOrEmpty(Text))
{
return 0;
}
var textBeforeCursor = Text.Substring(0, CursorPositionOrdinal);
var formattedTextCopy = new FormattedText(FormattedText, Platform.TextEngine)
{
Text = textBeforeCursor
};
var x = formattedTextCopy.DesiredSize.Width;
return x;
}
private void ForceRender()
{
Platform.RenderSurface.ForceRender();
}
public void AddText(string text)
{
if (!AcceptsReturn)
{
if (text == "\r" || text == Environment.NewLine)
{
return;
}
}
if (Text == null)
{
Text = text;
}
else
{
var firstPart = Text.Substring(0, CursorPositionOrdinal);
var secondPart = Text.Substring(CursorPositionOrdinal, Text.Length - CursorPositionOrdinal);
Text = firstPart + text + secondPart;
}
CursorPositionOrdinal++;
}
public bool AcceptsReturn
{
get => (bool) GetValue(AcceptsReturnProperty);
set => SetValue(AcceptsReturnProperty, value);
}
public void RemoveBefore()
{
if (CursorPositionOrdinal == 0)
{
return;
}
var leftPart = Text.Substring(0, CursorPositionOrdinal - 1);
var rightPart = Text.Substring(CursorPositionOrdinal, Text.Length - CursorPositionOrdinal);
Text = leftPart + rightPart;
}
public void RemoveAfter()
{
if (CursorPositionOrdinal == Text.Length)
{
return;
}
var leftPart = Text.Substring(0, CursorPositionOrdinal);
var lenghtOfRightPart = Text.Length - CursorPositionOrdinal - 1;
string rightPart;
if (lenghtOfRightPart > 0)
{
rightPart = Text.Substring(CursorPositionOrdinal + 1, lenghtOfRightPart);
}
else
{
rightPart = string.Empty;
}
Text = leftPart + rightPart;
}
protected override Size MeasureOverride(Size availableSize)
{
var textDesired = FormattedText.Text != null ? FormattedText.DesiredSize : Size.Empty;
var height = Math.Max(textDesired.Height, Platform.TextEngine.GetHeight(FontFamily, FormattedText.FontSize));
return new Size(textDesired.Width, height);
}
}
} |
#define SINGLE
using SocketClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TLBOT.DataManager {
public static partial class Extensions {
internal static T[] AppendArray<T>(this T[] Array, T Item) =>
Array.AppendArray(new T[] { Item });
internal static T[] AppendArray<T>(this T[] Array, T[] Items) {
T[] NewArray = new T[Array.Length + Items.Length];
Array.CopyTo(NewArray, 0);
Items.CopyTo(NewArray, Array.Length);
return NewArray;
}
#if SINGLE
internal static string Translate(this string String, string SourceLanguage, string TargetLanguage, Translator Client) {
if (SourceLanguage.Trim().ToLower() == TargetLanguage.Trim().ToLower())
return String;
if (Program.Cache.ContainsKey(String))
return Program.Cache[String];
for (int i = 0; i < 3; i++) {
try {
string Result = string.Empty;
var Thread = new Thread(() => {
try {
switch (Client) {
case Translator.CacheOnly:
if (Program.Cache.ContainsKey(String))
Result = Program.Cache[String];
else
Result = String;
break;
default:
Result = API.Translate(String, SourceLanguage, TargetLanguage, Local);
break;
}
} catch {
Result = null;
}
});
if (Program.ProxyInitialized) {
Thread.TimeoutStart(20000);
} else {
Thread.Start();
Thread.WaitForExit();
Program.ProxyInitialized = true;
}
if (string.IsNullOrWhiteSpace(Result))
continue;
Program.Cache[String] = Result;
return Result;
} catch {
Thread.Sleep(100);
}
}
return String;
}
#else
internal static string Translate(this string String, string SourceLang, string TargetLang, Translator Client) => TranslateMassive(new string[] { String }, SourceLang, TargetLang, Client).First();
#endif
internal static bool Local = false;
internal static string[] TranslateMassive(this string[] Strings, string SourceLanguage, string TargetLanguage, Translator Client) {
if (SourceLanguage.Trim().ToLower() == TargetLanguage.Trim().ToLower())
return Strings;
string[] NoCached = (from x in Strings where !Program.Cache.ContainsKey(x) select x).Distinct().ToArray();
string[] Result;
bool Error = false;
for (int i = 0; i < 5; i++) {
try {
if (NoCached?.Length == 0)
break;
Result = new string[0];
switch (Client) {
default:
try {
Result = API.Translate(NoCached, SourceLanguage, TargetLanguage, Local);
if (Result == null)
throw new Exception();
} catch (Exception ex) {
if (!Error && i + 1 >= 4)
MessageBox.Show(ex.Message, "TLBOT 2", MessageBoxButtons.OK, MessageBoxIcon.Error);
Error = true;
}
break;
}
if (Result.Length != NoCached.Length)
continue;
for (uint x = 0; x < NoCached.Length; x++) {
if (NoCached[x] != Result[x])
Program.Cache[NoCached[x]] = Result[x];
}
int Misseds = NoCached.Length;
NoCached = (from x in Strings where !Program.Cache.ContainsKey(x) select x).Distinct().ToArray();
if (Misseds == NoCached.Length)
break;
#if DEBUG
} catch (Exception ex){
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
#else
} catch {
#endif
Task.Delay(200).Wait();
}
}
Result = new string[Strings.LongLength];
for (uint i = 0; i < Strings.Length; i++) {
if (Program.Cache.ContainsKey(Strings[i]))
Result[i] = Program.Cache[Strings[i]];
else
Result[i] = Strings[i];
}
return Result;
}
internal static string[] TranslateMultithread(this string[] Strings, string SourceLanguage, string TargetLanguage, Translator Client, Action<uint> ProgressChanged = null) {
if (SourceLanguage.Trim().ToLower() == TargetLanguage.Trim().ToLower())
return Strings;
string[] NoCached = (from x in Strings where !Program.Cache.ContainsKey(x) select x).ToArray();
string[] Result;
for (int i = 0; i < 5; i++) {
try {
uint Finished = 0;
Result = new string[NoCached.Length];
Thread Thread = new Thread(() => {
var Options = new ParallelOptions() {
MaxDegreeOfParallelism = 20
};
Parallel.For(0, NoCached.Length, Options, x => {
if (Result[x] != null)
return;
Result[x] = NoCached[x].Translate(SourceLanguage, TargetLanguage, Client);
Finished++;
});
});
Thread.Start();
DateTime LastUpdateTime = DateTime.Now;
uint LastUpdate = 0;
while (Finished < Result.Length) {
if (ProgressChanged != null && LastUpdate != Finished) {
LastUpdate = Finished;
ProgressChanged(LastUpdate);
LastUpdateTime = DateTime.Now;
}
//Timeout Progress
if ((DateTime.Now - LastUpdateTime).TotalSeconds > 15) {
if (Thread.IsRunning()) {
Thread.Abort();
}
LastUpdateTime = DateTime.Now;
Thread.Start();
}
Thread.Sleep(10);
}
} catch {
Thread.Sleep(100);
}
}
Result = new string[Strings.LongLength];
for (uint i = 0; i < Strings.Length; i++) {
if (Program.Cache.ContainsKey(Strings[i]))
Result[i] = Program.Cache[Strings[i]];
else
Result[i] = Strings[i];
}
return Result;
}
public static void TimeoutStart(this Thread Thread, int Milliseconds) {
DateTime Begin = DateTime.Now;
Thread.Start();
while (Thread.IsRunning() && ((DateTime.Now - Begin).TotalMilliseconds < Milliseconds)) {
Task.Delay(100).Wait();
}
if (Thread.IsRunning())
Thread.Abort();
}
public static void WaitForExit(this Thread Thread) {
while (Thread.IsRunning()) {
Task.Delay(100).Wait();
}
}
public static void Translate(this Form Form, string TargetLanguage, Translator Client) {
try
{
List<string> Strings = new List<string>();
foreach (Control Control in GetControlHierarchy(Form))
{
if (Control is TextBox || Control is RichTextBox || Control is ComboBox)
continue;
Strings.Add(Control.Text);
}
string[] Translation = Strings.ToArray().TranslateMassive("PT", TargetLanguage, Client);
for (int i = 0; i < Strings.Count; i++)
Program.Cache[Strings[i]] = Translation[i];
}
catch { }
foreach (Control Control in GetControlHierarchy(Form))
{
if (Control is TextBox || Control is RichTextBox || Control is ComboBox)
continue;
try
{
Control.Invoke(new MethodInvoker(() =>
{
if (Program.Cache.ContainsKey(Control.Text))
Control.Text = Program.Cache[Control.Text];
}));
}
catch { }
}
}
private static IEnumerable<Control> GetControlHierarchy(Control root) {
var queue = new Queue<Control>();
queue.Enqueue(root);
do {
var control = queue.Dequeue();
yield return control;
foreach (var child in control.Controls.OfType<Control>())
queue.Enqueue(child);
} while (queue.Count > 0);
}
private static bool IsRunning(this Thread Thread) {
return Thread.ThreadState == ThreadState.Running || Thread.ThreadState == ThreadState.Background
|| Thread.ThreadState == ThreadState.WaitSleepJoin;
}
public static string Unescape(this string String) {
if (string.IsNullOrWhiteSpace(String))
return String;
string Result = string.Empty;
bool Special = false;
foreach (char c in String) {
if (c == '\\' & !Special) {
Special = true;
continue;
}
if (Special) {
switch (c) {
case '\\':
Result += '\\';
break;
case 'N':
case 'n':
Result += '\n';
break;
case 'T':
case 't':
Result += '\t';
break;
case 'R':
case 'r':
Result += '\r';
break;
case '"':
Result += '"';
break;
default:
Result += "\\" + c;
break;
}
Special = false;
} else
Result += c;
}
return Result;
}
public static string Escape(this string String) {
string Result = string.Empty;
foreach (char c in String) {
if (c == '\n')
Result += "\\n";
else if (c == '\\')
Result += "\\\\";
else if (c == '\t')
Result += "\\t";
else if (c == '\r')
Result += "\\r";
else if (c == '"')
Result += "\\\"";
else
Result += c;
}
return Result;
}
private static bool VerifingDialog = false;
public static bool IsDialogue(this string String, int? Caution = null) {
try {
if (string.IsNullOrWhiteSpace(String))
return false;
if (Program.ForceDialogues.ContainsKey(String))
return Program.ForceDialogues[String];
if (Program.FilterSettings.UseDB && Program.Cache.ContainsKey(String))
return true;
string[] DenyList = Program.FilterSettings.DenyList.Unescape().Split('\n').Where(x => !string.IsNullOrEmpty(x)).ToArray();
string[] IgnoreList = Program.FilterSettings.IgnoreList.Unescape().Split('\n').Where(x => !string.IsNullOrEmpty(x)).ToArray();
Quote[] Quotes = Program.FilterSettings.QuoteList.Unescape().Split('\n')
.Where(x => x.Length == 2)
.Select(x => {
return new Quote() { Start = x[0], End = x[1] };
}).ToArray();
string Str = String.Trim();
foreach (string Ignore in IgnoreList)
Str = Str.Replace(Ignore, "");
if (!VerifingDialog)
foreach (var Otimizator in Program.ExternalPlugins) {
try {
Otimizator.BeforeTranslate(ref Str, uint.MaxValue);
} catch { }
}
VerifingDialog = true;
foreach (string Deny in DenyList)
if (Str.ToLower().Contains(Deny.ToLower())) {
VerifingDialog = false;
return false;
}
Str = Str.Replace(Program.WordwrapSettings.LineBreaker, "\n");
if (string.IsNullOrWhiteSpace(Str))
return false;
string[] Words = Str.Split(' ');
char[] PontuationJapList = new char[] { '。', '?', '!', '…', '、', '―' };
char[] SpecialList = new char[] { '_', '=', '+', '#', ':', '$', '@' };
char[] PontuationList = new char[] { '.', '?', '!', '…', ',' };
int Spaces = Str.Where(x => x == ' ' || x == '\t').Count();
int Pontuations = Str.Where(x => PontuationList.Contains(x)).Count();
int WordCount = Words.Where(x => x.Length >= 2 && !string.IsNullOrWhiteSpace(x)).Count();
int Specials = Str.Where(x => char.IsSymbol(x)).Count();
Specials += Str.Where(x => char.IsPunctuation(x)).Count() - Pontuations;
int SpecialsStranges = Str.Where(x => SpecialList.Contains(x)).Count();
int Uppers = Str.Where(x => char.IsUpper(x)).Count();
int Latim = Str.Where(x => x >= 'A' && x <= 'z').Count();
int Numbers = Str.Where(x => x >= '0' && x <= '9').Count();
int NumbersJap = Str.Where(x => x >= '0' && x <= '9').Count();
int JapChars = Str.Where(x => (x >= '、' && x <= 'ヿ') || (x >= '。' && x <= 'ン')).Count();
int Kanjis = Str.Where(x => x >= '一' && x <= '龯').Count();
bool IsCaps = Optimizator.CaseFixer.GetLineCase(Str) == Optimizator.CaseFixer.Case.Upper;
bool IsJap = JapChars + Kanjis > Latim / 2;
//More Points = Don't Looks a Dialogue
//Less Points = Looks a Dialogue
int Points = 0;
if (Str.Length > 4) {
string ext = Str.Substring(Str.Length - 4, 4);
try {
if (System.IO.Path.GetExtension(ext).Trim('.').Length == 3)
Points += 2;
} catch { }
}
bool BeginQuote = false;
Quote? LineQuotes = null;
foreach (Quote Quote in Quotes) {
BeginQuote |= Str.StartsWith(Quote.Start.ToString());
if (Str.StartsWith(Quote.Start.ToString()) && Str.EndsWith(Quote.End.ToString())) {
Points -= 3;
LineQuotes = Quote;
break;
} else if (Str.StartsWith(Quote.Start.ToString()) || Str.EndsWith(Quote.End.ToString())) {
Points--;
LineQuotes = Quote;
break;
}
}
try {
char Last = (LineQuotes == null ? Str.Last() : Str.TrimEnd(LineQuotes?.End ?? ' ').Last());
if (IsJap && PontuationJapList.Contains(Last))
Points -= 3;
if (!IsJap && (PontuationList).Contains(Last))
Points -= 3;
} catch { }
try {
char First = (LineQuotes == null ? Str.First() : Str.TrimEnd(LineQuotes?.Start ?? ' ').First());
if (IsJap && PontuationJapList.Contains(First))
Points -= 3;
if (!IsJap && (PontuationList).Contains(First))
Points -= 3;
} catch { }
if (!IsJap) {
foreach (string Word in Words) {
int WNumbers = Word.Where(c => char.IsNumber(c)).Count();
int WLetters = Word.Where(c => char.IsLetter(c)).Count();
if (WLetters > 0 && WNumbers > 0) {
Points += 2;
}
if (Word.Trim(PontuationList).Where(c => PontuationList.Contains(c)).Count() != 0) {
Points += 2;
}
}
}
if (!BeginQuote && !char.IsLetter(Str.First()))
Points += 2;
if (Specials > WordCount)
Points++;
if (Specials > Latim + JapChars)
Points += 2;
if (SpecialsStranges > 0)
Points += 2;
if (SpecialsStranges > 3)
Points++;
if ((Pontuations == 0) && (WordCount <= 2) && !IsJap)
Points++;
if (Uppers > Pontuations + 2 && !IsCaps)
Points++;
if (Spaces > WordCount * 2)
Points++;
if (IsJap && Spaces == 0)
Points--;
if (!IsJap && Spaces == 0)
Points += 2;
if (WordCount <= 2 && Numbers != 0)
Points += (int)(Str.PercentOf(Numbers) / 10);
if (Str.Length <= 3 && !IsJap)
Points++;
if (Numbers >= Str.Length)
Points += 3;
if (!IsJap && WordCount == 1 && char.IsUpper(Str.First()) && !char.IsPunctuation(Str.TrimEnd().Last()))
Points++;
if (!IsJap && WordCount == 1 && !char.IsUpper(Str.First()))
Points++;
if (Words.Where(x => x.Where(y => char.IsUpper(y)).Count() > 1
&& x.Where(y => char.IsLower(y)).Count() > 1).Any())
Points += 2;
if (!IsJap && char.IsUpper(Str.TrimStart().First()) && char.IsPunctuation(Str.TrimEnd().Last()))
Points--;
if (!char.IsPunctuation(Str.TrimEnd().Last()))
Points++;
if (IsJap && Kanjis / 2 > JapChars)
Points--;
if (IsJap && JapChars > Kanjis)
Points--;
if (IsJap && Latim != 0)
Points += (int)(Str.PercentOf(Latim) / 10) + 2;
if (IsJap && NumbersJap != 0)
Points += (int)(Str.PercentOf(NumbersJap) / 10) + 2;
if (IsJap && Numbers != 0)
Points += (int)(Str.PercentOf(Numbers) / 10) + 3;
if (IsJap && Pontuations != 0)
Points += (int)(Str.PercentOf(Pontuations) / 10) + 2;
if (Str.Trim() == string.Empty)
return false;
if (Str.Trim().Trim(Str.Trim().First()) == string.Empty)
Points += 2;
if (IsJap != Program.FromAsian)
return false;
VerifingDialog = false;
bool Result = Points < (Caution ?? Program.FilterSettings.Sensitivity);
return Result;
} catch (Exception ex){
#if DEBUG
throw ex;
#else
return false;
#endif
}
}
internal static double PercentOf(this string String, int Value) {
var Result = Value / (double)String.Length;
return Result * 100;
}
}
}
|
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public float moveSpeed;
void Update () {
transform.position = new Vector3(transform.position.x + Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime,
transform.position.y + Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime,
transform.position.z);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using ExmploClaseInterfaz;
namespace ExmploClaseInterfaz
{
class Torreta : IGirar
{
public int Posicion { get; set; }
private ArrayList arryList1 = new ArrayList();
public void GirarHaciaDerecha()
{
arryList1.Add("D");
}
public void GirarHaciaIzquierda()
{
arryList1.Add("I");
}
public void Mostrar()
{
foreach(var element in arryList1)
{
if(element == "D")
{
Posicion = Posicion + 90;
}
else if (element == "I")
{
Posicion = Posicion - 90;
}
Posicion = (360 + Posicion) % 360;
Console.Write(element + " " + Posicion + " ");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace OCR
{
[Serializable()]
public class Polices:List<Police>
{
public void Enregistrer(String chemin)
{
XmlSerializer serializer = new XmlSerializer(typeof(Polices));
StreamWriter ecrivain = new StreamWriter(chemin);
serializer.Serialize(ecrivain, this);
ecrivain.Close();
}
public static Polices Charger(string chemin)
{
XmlSerializer deserializer = new XmlSerializer(typeof(Polices));
StreamReader lecteur = new StreamReader(chemin);
Polices p = (Polices)deserializer.Deserialize(lecteur);
lecteur.Close();
return p;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwitchStateSetter : MonoBehaviour
{
[SerializeField] private SOSwitchState _SwitchStateSO;
private SwitchStatesInput _SwichStatesInput;
private void Awake()
{
_SwichStatesInput = GetComponent<SwitchStatesInput>();
_SwitchStateSO.CreateRunTimeObject(_SwichStatesInput);
}
}
|
using Caliburn.Light;
namespace Demo.WpfDesignTime
{
public class ShellViewModel : BindableObject
{
private string _name;
private NestedViewModel _nestedViewModel;
public ShellViewModel()
{
NestedViewModel = new NestedViewModel();
Name = "Shell";
}
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
public NestedViewModel NestedViewModel
{
get { return _nestedViewModel; }
set { SetProperty(ref _nestedViewModel, value); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace CarParkingSystem.Models
{
public class Car
{
[Key]
public int Id { get; set;}
public string CarNo { get; set; }
public string CarName { get; set; }
public string LicenseNo { get; set; }
public virtual ICollection<Bill> Bills { get; set; }
public virtual ICollection<CheckIn> Checkins { get; set; }
public virtual ICollection<CheckOut> CheckOuts { get; set; }
public virtual ICollection<RegisteredUser> RegisteredUsers { get; set; }
public virtual ICollection<User> Users { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using TelesalesSchedule.Extensions;
using TelesalesSchedule.Models;
using TelesalesSchedule.Models.ViewModels;
namespace TelesalesSchedule.Controllers
{
public class ScheduleController : Controller
{
// GET: Schedule
public ActionResult Index()
{
return View();
}
//Get:
[Authorize]
public ActionResult Create()
{
DateTime nextMonday = DateTime.Now.AddDays(1);
while (nextMonday.DayOfWeek != DayOfWeek.Monday)
{
nextMonday = nextMonday.AddDays(1);
}
var nextSunday = nextMonday.AddDays(6);
ViewBag.Start = nextMonday.ToShortDateString();
ViewBag.End = nextSunday.ToShortDateString();
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(ScheduleEmployee model)
{
using (var db = new TelesalesScheduleDbContext())
{
var employee = db.Employees.Where(e => e.UserName == this.User.Identity.Name).FirstOrDefault();
if (employee == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
DateTime nextMonday = DateTime.Now.AddDays(1);
while (nextMonday.DayOfWeek != DayOfWeek.Monday)
{
nextMonday = nextMonday.AddDays(1);
}
var nextSunday = nextMonday.AddDays(6);
nextMonday = nextMonday.Date;
nextSunday = nextSunday.Date;
//chek if Employee Schedule is exist TODO:
if (employee.Schedules.Select(s => s.StartDate.Date).Contains(nextMonday.Date) || employee.Schedules.Select(s => s.StartDate.Date).Contains(nextSunday.Date))
{
ViewBag.ErrorMessage = "Schedule already exist. If you want you can edit it!";
return View();
}
else
{
string error = string.Empty;
error = CheckForPlace(db, employee, nextMonday, error, model.MondayStart, model.MondayEnd, model.MondayOptionalStart, model.MondayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.MondayError = error;
return View();
}
//ThuesdayCheck
var thuesday = nextMonday.AddDays(1);
error = CheckForPlace(db, employee, thuesday, error, model.ThuesdayStart, model.ThuesdayEnd, model.ThuesdayOptionalStart, model.ThuesdayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.ThuesdayError = error;
return View();
}
//Wednesday Check
var wednesday = thuesday.AddDays(1);
error = CheckForPlace(db, employee, wednesday, error, model.WednesdayStart, model.WednesdayEnd, model.WednesdayOptionalStart, model.WednesdayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.WednesdayError = error;
return View();
}
//Thursday Check
var thursday = wednesday.AddDays(1);
error = CheckForPlace(db, employee, thursday, error, model.ThursdayStart, model.ThursdayEnd, model.ThursdayOptionalStart, model.ThursdayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.ThursdayError = error;
return View();
}
//Friday Check
var friday = thursday.AddDays(1);
error = CheckForPlace(db, employee, friday, error, model.FridayStart, model.FridayEnd, model.FridayOptionalStart, model.FridayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.FridayError = error;
return View();
}
//Saturday Check
var saturday = friday.AddDays(1);
error = CheckForPlace(db, employee, saturday, error, model.SaturdayStart, model.SaturdayEnd, model.SaturdayOptionalStart, model.SaturdayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.SaturdayError = error;
return View();
}
//Sunday Check
error = CheckForPlace(db, employee, nextSunday, error, model.SundayStart, model.SundayEnd, model.SundayOptionalStart, model.SundayOptionalEnd);
if (!string.IsNullOrEmpty(error))
{
ViewBag.SundayError = error;
return View();
}
AddingScheduleToEmployee(db, nextMonday, nextSunday, model, employee);
db.SaveChanges();
this.AddNotification("Да си спазваш графика :)", NotificationType.SUCCESS);
}
}
return RedirectToAction("ListMySchedules");
}
}
[Authorize]
public ActionResult ListMySchedules()
{
using (var db = new TelesalesScheduleDbContext())
{
var emp = db.Employees.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
var schedules = emp.EmployeeSchedules.ToList().OrderByDescending(s => s.StartDate).ToList();
return View(schedules);
}
}
[Authorize(Roles = "Admin")]
public ActionResult ListAll()
{
using (var db = new TelesalesScheduleDbContext())
{
var schedules = db.EmployeeSchedules.Select(s => new DateModel
{
StartDate = s.StartDate,
EndDate = s.EndDate
}).Distinct().OrderByDescending(s => s.StartDate).ToList();
return View(schedules);
}
}
[Authorize(Roles = "Admin")]
public ActionResult EmployeesWithSchedules(DateModel model)
{
using (var db = new TelesalesScheduleDbContext())
{
//var schedules = db.Schedules.Where(s => s.StartDate == model.StartDate && s.EndDate == model.EndDate).Where(e => e.Employee.Schedules.Count > 0).ToList();
var employees = db.Employees.Where(e => e.IsDeleted == false).ToList();
var empSchedules = new List<EmployeeSchedule>();
foreach (var emp in employees)
{
//emp.Schedules.Where(s => s.StartDate == model.StartDate && s.EndDate == model.EndDate)
foreach (var schedule in emp.EmployeeSchedules)
{
if (schedule.StartDate == model.StartDate && schedule.EndDate == model.EndDate)
{
var sch = new EmployeeSchedule
{
Id = schedule.Id,
FullName = emp.FullName,
Hours = schedule.Hours
};
empSchedules.Add(sch);
}
}
}
return View(empSchedules);
}
}
[Authorize(Roles = "Admin")]
public ActionResult EmployeesWithoutSchedule(DateModel model)
{
using (var db = new TelesalesScheduleDbContext())
{
var employees = db.Employees.Where(e => e.IsDeleted == false).ToList();
var empSchedules = new List<EmployeeSchedule>();
foreach (var e in employees)
{
if (e.EmployeeSchedules.Count == 0)
{
var sch = new EmployeeSchedule
{
FullName = e.FullName
};
empSchedules.Add(sch);
}
else
{
int found = 0;
foreach (var schedule in e.EmployeeSchedules)
{
if (schedule.StartDate == model.StartDate)
{
found = 1;
}
}
if (found == 0)
{
var sch = new EmployeeSchedule
{
FullName = e.FullName
};
empSchedules.Add(sch);
}
}
}
return View(empSchedules);
}
}
//
// GET: Schedule/Details
[Authorize]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var db = new TelesalesScheduleDbContext())
{
var schedule = db.EmployeeSchedules
.FirstOrDefault(s => s.Id == id);
if (schedule == null)
{
return HttpNotFound();
}
return View(schedule);
}
}
//
// GET: Schedule/Edit
[Authorize(Roles = "Admin")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var context = new TelesalesScheduleDbContext())
{
var schedule = context.EmployeeSchedules
.FirstOrDefault(s => s.Id == id);
if (schedule == null)
{
return HttpNotFound();
}
var model = new ScheduleView();
model.Id = schedule.Id;
model.Hours = schedule.Hours.ToString();
ViewBag.StartDate = schedule.StartDate.ToShortDateString();
ViewBag.EndDate = schedule.EndDate.ToShortDateString();
ScheduleViewBuilder(schedule, model);
return View(model);
}
}
// POST: Schedule/Edit
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Edit(ScheduleView modelView)
{
// TODO: something is not right... almost fixed :)
if (ModelState.IsValid)
{
using (var context = new TelesalesScheduleDbContext())
{
var schedule = context.EmployeeSchedules.FirstOrDefault(s => s.Id == modelView.Id);
var employee = context.EmployeeSchedules.Where(s => s.Id == modelView.Id).Select(e => e.Employee).FirstOrDefault();
var monday = schedule.StartDate;
var sunday = schedule.EndDate;
var computers = context.Computers.ToList();
var model = new ScheduleView();
model.Id = schedule.Id;
ViewBag.StartDate = schedule.StartDate.ToShortDateString();
ViewBag.EndDate = schedule.EndDate.ToShortDateString();
model.Hours = schedule.Hours.ToString();
ScheduleViewBuilder(schedule, model);
CheckForEmptyString(model);
string error = string.Empty;
//If Monday Shift is Changed
if (modelView.MondayStart != model.MondayStart || modelView.MondayEnd != model.MondayEnd)
{
if (modelView.MondayStart == null && modelView.MondayEnd == null)
{
DateTime currentDayStart = monday;
DateTime currentDayEnd = monday;
currentDayStart = ConvertTime(model.MondayStart, currentDayStart);
currentDayEnd = ConvertTime(model.MondayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday;
DateTime currentDayEnd = monday;
if (model.MondayStart == null || model.MondayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday, error, schedule.MondayStart, schedule.MondayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.MondayStart, currentDayStart);
currentDayEnd = ConvertTime(model.MondayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday, error, schedule.MondayStart, schedule.MondayEnd, null, null);
}
}
}
//If Monday Optional Shift is changed
if (modelView.MondayOptionalStart != model.MondayOptionalStart || modelView.MondayOptionalEnd != model.MondayOptionalEnd)
{
if (modelView.MondayOptionalStart == null && modelView.MondayOptionalEnd == null)
{
DateTime currentDayStart = monday;
DateTime currentDayEnd = monday;
currentDayStart = ConvertTime(model.MondayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.MondayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday;
DateTime currentDayEnd = monday;
if (model.MondayOptionalStart == null || model.MondayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday, error, null, null, schedule.MondayOptionalStart, schedule.MondayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.MondayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.MondayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday, error, null, null, schedule.MondayOptionalStart, schedule.MondayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.MondayError = error;
return View();
}
// If Tuesday Shift is Changed
if (modelView.ThuesdayStart != model.ThuesdayStart || modelView.ThuesdayEnd != model.ThuesdayEnd)
{
if (modelView.ThuesdayStart == null && modelView.ThuesdayEnd == null)
{
DateTime currentDayStart = monday.AddDays(1);
DateTime currentDayEnd = monday.AddDays(1);
currentDayStart = ConvertTime(model.ThuesdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThuesdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(1);
DateTime currentDayEnd = monday.AddDays(1);
if (model.ThuesdayStart == null || model.ThuesdayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(1), error, schedule.ThuesdayStart, schedule.ThuesdayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.ThuesdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThuesdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(1), error, schedule.ThuesdayStart, schedule.ThuesdayEnd, null, null);
}
}
}
//If Tuesday Optional Shift is changed
if (modelView.ThuesdayOptionalStart != model.ThuesdayOptionalStart || modelView.ThuesdayOptionalEnd != model.ThuesdayOptionalEnd)
{
if (modelView.ThuesdayOptionalStart == null && modelView.ThuesdayOptionalEnd == null)
{
DateTime currentDayStart = monday.AddDays(1);
DateTime currentDayEnd = monday.AddDays(1);
currentDayStart = ConvertTime(model.ThuesdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThuesdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(1);
DateTime currentDayEnd = monday.AddDays(1);
if (model.ThuesdayOptionalStart == null || model.ThuesdayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(1), error, null, null, schedule.ThuesdayOptionalStart, schedule.ThuesdayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.ThuesdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThuesdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(1), error, null, null, schedule.ThuesdayOptionalStart, schedule.ThuesdayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.ThuesdayError = error;
return View();
}
// If Wednesday Shift is Changed
if (modelView.WednesdayStart != model.WednesdayStart || modelView.WednesdayEnd != model.WednesdayEnd)
{
if (modelView.WednesdayStart == null && modelView.WednesdayEnd == null)
{
DateTime currentDayStart = monday.AddDays(2);
DateTime currentDayEnd = monday.AddDays(2);
currentDayStart = ConvertTime(model.WednesdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.WednesdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(2);
DateTime currentDayEnd = monday.AddDays(2);
if (model.WednesdayStart == null || model.WednesdayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(2), error, schedule.WednesdayStart, schedule.WednesdayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.WednesdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.WednesdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(2), error, schedule.WednesdayStart, schedule.WednesdayEnd, null, null);
}
}
}
//If Wednesday Optional Shift is changed
if (modelView.WednesdayOptionalStart != model.WednesdayOptionalStart || modelView.WednesdayOptionalEnd != model.WednesdayOptionalEnd)
{
if (modelView.WednesdayOptionalStart == null && modelView.WednesdayOptionalEnd == null)
{
DateTime currentDayStart = monday.AddDays(2);
DateTime currentDayEnd = monday.AddDays(2);
currentDayStart = ConvertTime(model.WednesdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.WednesdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(2);
DateTime currentDayEnd = monday.AddDays(2);
if (model.WednesdayOptionalStart == null || model.WednesdayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(2), error, null, null, schedule.WednesdayOptionalStart, schedule.WednesdayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.WednesdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.WednesdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(2), error, null, null, schedule.WednesdayOptionalStart, schedule.WednesdayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.WednesdayError = error;
return View();
}
// If Thursday Shift is Changed
if (modelView.ThursdayStart != model.ThursdayStart || modelView.ThursdayEnd != model.ThursdayEnd)
{
if (modelView.ThursdayStart == null && modelView.ThursdayEnd == null)
{
DateTime currentDayStart = monday.AddDays(3);
DateTime currentDayEnd = monday.AddDays(3);
currentDayStart = ConvertTime(model.ThursdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThursdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(3);
DateTime currentDayEnd = monday.AddDays(3);
if (model.ThursdayStart == null || model.ThursdayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(3), error, schedule.ThursdayStart, schedule.ThursdayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.ThursdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThursdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(3), error, schedule.ThursdayStart, schedule.ThursdayEnd, null, null);
}
}
}
//If Thursday Optional Shift is changed
if (modelView.ThursdayOptionalStart != model.ThursdayOptionalStart || modelView.ThursdayOptionalEnd != model.ThursdayOptionalEnd)
{
if (modelView.ThursdayOptionalStart == null && modelView.ThursdayOptionalEnd == null)
{
DateTime currentDayStart = monday.AddDays(3);
DateTime currentDayEnd = monday.AddDays(3);
currentDayStart = ConvertTime(model.ThursdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThursdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(3);
DateTime currentDayEnd = monday.AddDays(3);
if (model.ThursdayOptionalStart == null || model.ThursdayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(3), error, null, null, schedule.ThursdayOptionalStart, schedule.ThuesdayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.ThursdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.ThursdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(3), error, null, null, schedule.ThursdayOptionalStart, schedule.ThuesdayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.ThursdayError = error;
return View();
}
// If Friday Shift is Changed
if (modelView.FridayStart != model.FridayStart || modelView.FridayEnd != model.FridayEnd)
{
if (modelView.FridayStart == null && modelView.FridayEnd == null)
{
DateTime currentDayStart = monday.AddDays(4);
DateTime currentDayEnd = monday.AddDays(4);
currentDayStart = ConvertTime(model.FridayStart, currentDayStart);
currentDayEnd = ConvertTime(model.FridayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(4);
DateTime currentDayEnd = monday.AddDays(4);
if (model.FridayStart == null || model.FridayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(4), error, schedule.FridayStart, schedule.FridayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.FridayStart, currentDayStart);
currentDayEnd = ConvertTime(model.FridayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(4), error, schedule.FridayStart, schedule.FridayEnd, null, null);
}
}
}
//If Friday Optional Shift is changed
if (modelView.FridayOptionalStart != model.FridayOptionalStart || modelView.FridayOptionalEnd != model.FridayOptionalEnd)
{
if (modelView.FridayOptionalStart == null && modelView.FridayOptionalEnd == null)
{
DateTime currentDayStart = monday.AddDays(4);
DateTime currentDayEnd = monday.AddDays(4);
currentDayStart = ConvertTime(model.FridayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.FridayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(4);
DateTime currentDayEnd = monday.AddDays(4);
if (model.FridayOptionalStart == null || model.FridayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(4), error, null, null, schedule.FridayOptionalStart, schedule.FridayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.FridayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.FridayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(4), error, null, null, schedule.FridayOptionalStart, schedule.FridayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.FridayError = error;
return View();
}
// If Saturday Shift is Changed
if (modelView.SaturdayStart != model.SaturdayStart || modelView.SaturdayEnd != model.SaturdayEnd)
{
if (modelView.SaturdayStart == null && modelView.SaturdayEnd == null)
{
DateTime currentDayStart = monday.AddDays(5);
DateTime currentDayEnd = monday.AddDays(5);
currentDayStart = ConvertTime(model.SaturdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.SaturdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(5);
DateTime currentDayEnd = monday.AddDays(5);
if (model.SaturdayStart == null || model.SaturdayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(5), error, schedule.SaturdayStart, schedule.SaturdayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.SaturdayStart, currentDayStart);
currentDayEnd = ConvertTime(model.SaturdayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(5), error, schedule.SaturdayStart, schedule.SaturdayEnd, null, null);
}
}
}
//If Saturday Optional Shift is changed
if (modelView.SaturdayOptionalStart != model.SaturdayOptionalStart || modelView.SaturdayOptionalEnd != model.SaturdayOptionalEnd)
{
if (modelView.SaturdayOptionalStart == null && modelView.SaturdayOptionalEnd == null)
{
DateTime currentDayStart = monday.AddDays(5);
DateTime currentDayEnd = monday.AddDays(5);
currentDayStart = ConvertTime(model.SaturdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.SaturdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = monday.AddDays(5);
DateTime currentDayEnd = monday.AddDays(5);
if (model.SaturdayOptionalStart == null || model.SaturdayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(5), error, null, null, schedule.SaturdayOptionalStart, schedule.SaturdayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.SaturdayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.SaturdayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, monday.AddDays(5), error, null, null, schedule.SaturdayOptionalStart, schedule.SaturdayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.SaturdayError = error;
return View();
}
// If Sunday Shift is Changed
if (modelView.SundayStart != model.SundayStart || modelView.SundayEnd != model.SundayEnd)
{
if (modelView.SundayStart == null && modelView.SundayEnd == null)
{
DateTime currentDayStart = sunday;
DateTime currentDayEnd = sunday;
currentDayStart = ConvertTime(model.SundayStart, currentDayStart);
currentDayEnd = ConvertTime(model.SundayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = sunday;
DateTime currentDayEnd = sunday;
if (model.SundayStart == null || model.SundayEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, sunday, error, schedule.SundayStart, schedule.SundayEnd, null, null);
}
else
{
currentDayStart = ConvertTime(model.SundayStart, currentDayStart);
currentDayEnd = ConvertTime(model.SundayEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, sunday, error, schedule.SundayStart, schedule.SundayEnd, null, null);
}
}
}
//If Sunday Optional Shift is changed
if (modelView.SundayOptionalStart != model.SundayOptionalStart || modelView.SundayOptionalEnd != model.SundayOptionalEnd)
{
if (modelView.SundayOptionalStart == null && modelView.SundayOptionalEnd == null)
{
DateTime currentDayStart = sunday;
DateTime currentDayEnd = sunday;
currentDayStart = ConvertTime(model.SundayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.SundayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
}
else
{
DateTime currentDayStart = sunday;
DateTime currentDayEnd = sunday;
if (model.SundayOptionalStart == null || model.SundayOptionalEnd == null)
{
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, sunday, error, null, null, schedule.SundayOptionalStart, schedule.SundayOptionalEnd);
}
else
{
currentDayStart = ConvertTime(model.SundayOptionalStart, currentDayStart);
currentDayEnd = ConvertTime(model.SundayOptionalEnd, currentDayEnd);
var ev = employee.Events.FirstOrDefault(e => e.StartDate == currentDayStart && e.EndDate == currentDayEnd);
//First remove event
context.Events.Remove(ev);
ChangeEmployeeSchedule(schedule, modelView);
error = CheckForPlace(context, employee, sunday, error, null, null, schedule.SundayOptionalStart, schedule.SundayOptionalEnd);
}
}
}
if (!string.IsNullOrEmpty(error))
{
ViewBag.SundayError = error;
return View();
}
context.SaveChanges();
this.AddNotification("Графика е променен.", NotificationType.SUCCESS);
return RedirectToAction("ListAll");
}
}
return View();
}
[Authorize(Roles = "Admin")]
public ActionResult MonthlySchedule()
{
return View();
}
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Monthly(MonthlyView model)
{
if(model == null)
{
//todo
}
int month = int.Parse(model.Month);
int year = DateTime.Now.Year;
DateTime dateStart = new DateTime(year, month, 1);
int lastDay = DateTime.DaysInMonth(year, month);
DateTime dateEnd = new DateTime(year, month, lastDay);
ViewBag.StartDate = dateStart.ToShortDateString();
ViewBag.EndDate = dateEnd.ToShortDateString();
var employees = new List<EmployeeDto>();
using (var db = new TelesalesScheduleDbContext())
{
var emp = db.Employees.ToList();
foreach (var e in emp)
{
var employee = new EmployeeDto
{
FullName = e.FullName
};
double hours = 0;
foreach (var ev in e.Events.Where(s => s.StartDate >= dateStart && s.EndDate <= dateEnd))
{
double diff = (ev.EndDate - ev.StartDate).TotalMinutes/60;
hours += diff;
}
employee.Hours = hours;
employees.Add(employee);
}
}
return View(employees);
}
[Authorize(Roles = "Admin")]
public ActionResult Daily()
{
DateTime date = DateTime.Now.Date;
var employees = new List<DailyView>();
using (var db = new TelesalesScheduleDbContext())
{
var users = db.Employees.Where(e => e.IsDeleted == false).ToList();
foreach (var user in users)
{
foreach (var ev in user.Events.Where(e => e.StartDate.Date == date))
{
var schedule = user.EmployeeSchedules.FirstOrDefault(e => e.StartDate <= date && e.EndDate >= date);
var employee = new DailyView
{
FullName = user.FullName,
StartDate = ev.StartDate.ToShortTimeString(),
EndDate = ev.EndDate.ToShortTimeString()
};
if (schedule != null)
{
employee.EmployeeScheduleID = schedule.Id;
}
else
{
employee.EmployeeScheduleID = null;
}
employees.Add(employee);
}
}
}
return View(employees);
}
private static string CheckForPlace(TelesalesScheduleDbContext db, Employee employee, DateTime day, string error, double? dayStart, double? dayEnd, double? dayStartOptional, double? dayEndOptional)
{
int found = 0;
int foundOptional = 0;
if (dayStart != null && dayEnd != null)
{
if (dayEnd - dayStart < 0.5)
{
error = "Невалидна смяна!";
return error;
}
DateTime currentDayStart = day.AddHours((double)dayStart);
DateTime currentDayEnd = day.AddHours((double)dayEnd);
var computers = db.Computers.Where(c => c.IsWorking == true).ToList();
foreach (var pc in computers)
{
if (found != 0)
{
break;
}
var ev = pc.Events.Where(e => e.StartDate.Date == currentDayStart.Date && e.EndDate.Date == currentDayEnd.Date).ToList();
if (ev.Count == 0)
{
found = 1;
var shift = new Event
{
StartDate = currentDayStart,
EndDate = currentDayEnd,
ComputerId = pc.Id,
EmployeeId = employee.Id
};
pc.Events.Add(shift);
break;
}
else
{
var check = ev.Any(e => currentDayStart <= e.EndDate && e.StartDate <= currentDayEnd);
if (!check)
{
found = 1;
var shift = new Event
{
StartDate = currentDayStart,
EndDate = currentDayEnd,
ComputerId = pc.Id,
EmployeeId = employee.Id
};
pc.Events.Add(shift);
break;
}
}
}
if (found == 0)
{
error = "Няма свободни места!";
}
}
if (dayStartOptional != null && dayEndOptional != null)
{
if (dayEndOptional - dayStartOptional < 0.5)
{
error = "Невалидна смяна!";
return error;
}
DateTime currentDayStart = day.AddHours((double)dayStartOptional);
DateTime currentDayEnd = day.AddHours((double)dayEndOptional);
var computers = db.Computers.Where(c => c.IsWorking == true).ToList();
foreach (var pc in computers)
{
if (foundOptional != 0)
{
break;
}
var ev = pc.Events.Where(e => e.StartDate.Date == currentDayStart.Date && e.EndDate.Date == currentDayEnd.Date).ToList();
if (ev.Count == 0)
{
foundOptional = 1;
var shift = new Event
{
StartDate = currentDayStart,
EndDate = currentDayEnd,
ComputerId = pc.Id,
EmployeeId = employee.Id
};
pc.Events.Add(shift);
break;
}
else
{
var check = ev.Any(e => currentDayStart <= e.EndDate && e.StartDate <= currentDayEnd);
if (!check)
{
foundOptional = 1;
var shift = new Event
{
StartDate = currentDayStart,
EndDate = currentDayEnd,
ComputerId = pc.Id,
EmployeeId = employee.Id
};
pc.Events.Add(shift);
break;
}
}
}
if (foundOptional == 0)
{
error = "Няма свободни места!";
}
}
return error;
}
public void ExportToExcel(DateModel model)
{
using (var db = new TelesalesScheduleDbContext())
{
var employees = db.Employees.ToList();
var empSchedules = new List<EmployeeSchedule>();
foreach (var emp in employees)
{
foreach (var schedule in emp.EmployeeSchedules)
{
if (schedule.StartDate == model.StartDate && schedule.EndDate == model.EndDate)
{
var sch = new EmployeeSchedule
{
Id = schedule.Id,
FullName = emp.FullName,
Hours = schedule.Hours
};
empSchedules.Add(sch);
}
}
}
var grid = new GridView();
grid.DataSource = from data in empSchedules.OrderBy(e => e.FullName)
select new
{
FullName = data.FullName,
Hours = data.Hours
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Employees.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter writer = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(writer);
grid.RenderControl(htmlTextWriter);
Response.Write(writer.ToString());
Response.End();
}
}
private static void ScheduleViewBuilder(ScheduleEmployee schedule, ScheduleView model)
{
// Monday
if (schedule.MondayStart != null && schedule.MondayEnd != null)
{
model.MondayStart = schedule.MondayStart.ToString();
model.MondayEnd = schedule.MondayEnd.ToString();
}
else
{
model.MondayStart = string.Empty;
model.MondayEnd = string.Empty;
}
if (schedule.MondayOptionalStart != null && schedule.MondayOptionalEnd != null)
{
model.MondayOptionalStart = schedule.MondayOptionalStart.ToString();
model.MondayOptionalEnd = schedule.MondayOptionalEnd.ToString();
}
else
{
model.MondayOptionalStart = string.Empty;
model.MondayOptionalEnd = string.Empty;
}
// Thuesday
if (schedule.ThuesdayStart != null && schedule.ThursdayEnd != null)
{
model.ThuesdayStart = schedule.ThuesdayStart.ToString();
model.ThuesdayEnd = schedule.ThuesdayEnd.ToString();
}
else
{
model.ThuesdayStart = string.Empty;
model.ThuesdayEnd = string.Empty;
}
if (schedule.ThuesdayOptionalStart != null && schedule.ThuesdayOptionalEnd != null)
{
model.ThuesdayOptionalStart = schedule.ThuesdayOptionalStart.ToString();
model.ThuesdayOptionalEnd = schedule.ThuesdayOptionalEnd.ToString();
}
else
{
model.ThuesdayOptionalStart = string.Empty;
model.ThuesdayOptionalEnd = string.Empty;
}
// Wednesday
if (schedule.WednesdayStart != null && schedule.WednesdayEnd != null)
{
model.WednesdayStart = schedule.WednesdayStart.ToString();
model.WednesdayEnd = schedule.WednesdayEnd.ToString();
}
else
{
model.WednesdayStart = string.Empty;
model.WednesdayEnd = string.Empty;
}
if (schedule.WednesdayOptionalStart != null && schedule.WednesdayOptionalEnd != null)
{
model.WednesdayOptionalStart = schedule.WednesdayOptionalStart.ToString();
model.WednesdayOptionalEnd = schedule.WednesdayOptionalEnd.ToString();
}
else
{
model.WednesdayOptionalStart = string.Empty;
model.WednesdayOptionalEnd = string.Empty;
}
// Thursday
if (schedule.ThursdayStart != null && schedule.ThursdayEnd != null)
{
model.ThursdayStart = schedule.ThursdayStart.ToString();
model.ThursdayEnd = schedule.ThursdayEnd.ToString();
}
else
{
model.ThursdayStart = string.Empty;
model.ThursdayEnd = string.Empty;
}
if (schedule.ThursdayOptionalStart != null && schedule.ThursdayOptionalEnd != null)
{
model.ThursdayOptionalStart = schedule.ThursdayOptionalStart.ToString();
model.ThursdayOptionalEnd = schedule.ThursdayOptionalEnd.ToString();
}
else
{
model.ThursdayOptionalStart = string.Empty;
model.ThursdayOptionalEnd = string.Empty;
}
// Friday
if (schedule.FridayStart != null && schedule.FridayEnd != null)
{
model.FridayStart = schedule.FridayStart.ToString();
model.FridayEnd = schedule.FridayEnd.ToString();
}
else
{
model.FridayStart = string.Empty;
model.FridayEnd = string.Empty;
}
if (schedule.FridayOptionalStart != null && schedule.FridayOptionalEnd != null)
{
model.FridayOptionalStart = schedule.FridayOptionalStart.ToString();
model.FridayOptionalEnd = schedule.FridayOptionalEnd.ToString();
}
else
{
model.FridayOptionalStart = string.Empty;
model.FridayOptionalEnd = string.Empty;
}
// Saturday
if (schedule.SaturdayStart != null && schedule.SaturdayEnd != null)
{
model.SaturdayStart = schedule.SaturdayStart.ToString();
model.SaturdayEnd = schedule.SaturdayEnd.ToString();
}
else
{
model.SaturdayStart = string.Empty;
model.SaturdayEnd = string.Empty;
}
if (schedule.SaturdayOptionalStart != null && schedule.SaturdayOptionalEnd != null)
{
model.SaturdayOptionalStart = schedule.SaturdayOptionalStart.ToString();
model.SaturdayOptionalEnd = schedule.SaturdayOptionalEnd.ToString();
}
else
{
model.SaturdayOptionalStart = string.Empty;
model.SaturdayOptionalEnd = string.Empty;
}
// Sunday
if (schedule.SundayStart != null && schedule.SundayEnd != null)
{
model.SundayStart = schedule.SundayStart.ToString();
model.SundayEnd = schedule.SundayEnd.ToString();
}
else
{
model.SundayStart = string.Empty;
model.SundayEnd = string.Empty;
}
if (schedule.SundayOptionalStart != null && schedule.SundayOptionalEnd != null)
{
model.SundayOptionalStart = schedule.SundayOptionalStart.ToString();
model.SundayOptionalEnd = schedule.SundayOptionalEnd.ToString();
}
else
{
model.SundayOptionalStart = string.Empty;
model.SundayOptionalEnd = string.Empty;
}
}
private static DateTime ConvertTime(string dayTime, DateTime currentDayStart)
{
double time = double.Parse(dayTime);
int hour = 0;
int minute = 0;
if (time % 1 == 0)
{
hour = (int)time;
}
else
{
hour = (int)(time - 0.5);
minute = 30;
}
return currentDayStart = currentDayStart.AddHours(hour).AddMinutes(minute);
}
private void CheckForEmptyString(ScheduleView model)
{
if (model.MondayStart == "" || model.MondayEnd == "")
{
model.MondayStart = null;
model.MondayEnd = null;
}
if (model.MondayOptionalStart == "" || model.MondayOptionalEnd == "")
{
model.MondayOptionalStart = null;
model.MondayOptionalEnd = null;
}
if (model.ThuesdayStart == "" || model.ThuesdayEnd == "")
{
model.ThuesdayStart = null;
model.ThuesdayEnd = null;
}
if (model.ThuesdayOptionalStart == "" || model.ThuesdayOptionalEnd == "")
{
model.ThuesdayOptionalStart = null;
model.ThuesdayOptionalEnd = null;
}
if (model.WednesdayStart == "" || model.WednesdayEnd == "")
{
model.WednesdayStart = null;
model.WednesdayEnd = null;
}
if (model.WednesdayOptionalStart == "" || model.WednesdayOptionalEnd == "")
{
model.WednesdayOptionalStart = null;
model.WednesdayOptionalEnd = null;
}
if (model.ThursdayStart == "" || model.ThursdayEnd == "")
{
model.ThursdayStart = null;
model.ThursdayEnd = null;
}
if (model.ThursdayOptionalStart == "" || model.ThursdayOptionalEnd == "")
{
model.ThursdayOptionalStart = null;
model.ThursdayOptionalEnd = null;
}
if (model.FridayStart == "" || model.FridayEnd == "")
{
model.FridayStart = null;
model.FridayEnd = null;
}
if (model.FridayOptionalStart == "" || model.FridayOptionalEnd == "")
{
model.FridayOptionalStart = null;
model.FridayOptionalEnd = null;
}
if (model.SaturdayStart == "" || model.SaturdayEnd == "")
{
model.SaturdayStart = null;
model.SaturdayEnd = null;
}
if (model.SaturdayOptionalStart == "" || model.SaturdayOptionalEnd == "")
{
model.SaturdayOptionalStart = null;
model.SaturdayOptionalEnd = null;
}
if (model.SundayStart == "" || model.SundayEnd == "")
{
model.SundayStart = null;
model.SundayEnd = null;
}
if (model.SundayOptionalStart == "" || model.SundayOptionalEnd == "")
{
model.SundayOptionalStart = null;
model.SundayOptionalEnd = null;
}
}
private void AddingScheduleToEmployee(TelesalesScheduleDbContext db, DateTime nextMonday, DateTime nextSunday, ScheduleEmployee model, Employee employee)
{
double hours = 0;
var schedule = new ScheduleEmployee
{
StartDate = nextMonday,
EndDate = nextSunday
};
//Monday
if (model.MondayStart != null && model.MondayEnd != null)
{
double mondayStart = (double)model.MondayStart;
double mondayEnd = (double)model.MondayEnd;
double mondayDiff = mondayEnd - mondayStart;
hours += mondayDiff;
schedule.MondayStart = mondayStart;
schedule.MondayEnd = mondayEnd;
if (model.MondayStart == 9 && model.MondayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.MondayOptionalStart != null && model.MondayOptionalEnd != null)
{
double mondayStart = (double)model.MondayOptionalStart;
double mondayEnd = (double)model.MondayOptionalEnd;
double mondayDiff = mondayEnd - mondayStart;
hours += mondayDiff;
schedule.MondayOptionalStart = mondayStart;
schedule.MondayOptionalEnd = mondayEnd;
}
//Thuesday
if (model.ThuesdayStart != null && model.ThuesdayEnd != null)
{
double thuesdayStart = (double)model.ThuesdayStart;
double thuesdayEnd = (double)model.ThuesdayEnd;
double thuesdayDiff = thuesdayEnd - thuesdayStart;
hours += thuesdayDiff;
schedule.ThuesdayStart = thuesdayStart;
schedule.ThuesdayEnd = thuesdayEnd;
if (model.ThuesdayStart == 9 && model.ThuesdayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.ThuesdayOptionalStart != null && model.ThuesdayOptionalEnd != null)
{
double thuesdayStart = (double)model.ThuesdayOptionalStart;
double thuesdayEnd = (double)model.ThuesdayOptionalEnd;
double thuesdayDiff = thuesdayStart - thuesdayEnd;
hours += thuesdayDiff;
schedule.ThuesdayOptionalStart = thuesdayStart;
schedule.ThuesdayOptionalEnd = thuesdayEnd;
}
//Wednesday
if (model.WednesdayStart != null && model.WednesdayEnd != null)
{
double wednesdayStart = (double)model.WednesdayStart;
double wednesdayEnd = (double)model.WednesdayEnd;
double wednesdayDiff = wednesdayEnd - wednesdayStart;
hours += wednesdayDiff;
schedule.WednesdayStart = wednesdayStart;
schedule.WednesdayEnd = wednesdayEnd;
if (model.WednesdayStart == 9 && model.WednesdayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.WednesdayOptionalStart != null && model.WednesdayOptionalEnd != null)
{
double wednesdayStart = (double)model.WednesdayOptionalStart;
double wednesdayEnd = (double)model.WednesdayOptionalEnd;
double wednesdayDiff = wednesdayEnd - wednesdayStart;
hours += wednesdayDiff;
schedule.WednesdayOptionalStart = wednesdayStart;
schedule.WednesdayOptionalEnd = wednesdayEnd;
}
//Thursday
if (model.ThursdayStart != null && model.ThursdayEnd != null)
{
double thursdayStart = (double)model.ThursdayStart;
double thursdayEnd = (double)model.ThursdayEnd;
double thursdayDiff = thursdayEnd - thursdayStart;
hours += thursdayDiff;
schedule.ThursdayStart = thursdayStart;
schedule.ThursdayEnd = thursdayEnd;
if (model.ThursdayStart == 9 && model.ThursdayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.ThursdayOptionalStart != null && model.ThursdayOptionalEnd != null)
{
double thursdayStart = (double)model.ThursdayOptionalStart;
double thursdayEnd = (double)model.ThursdayOptionalEnd;
double thursdayDiff = thursdayEnd - thursdayStart;
hours += thursdayDiff;
schedule.ThursdayOptionalStart = thursdayStart;
schedule.ThursdayOptionalEnd = thursdayEnd;
}
//Friday
if (model.FridayStart != null && model.FridayEnd != null)
{
double fridayStart = (double)model.FridayStart;
double fridayEnd = (double)model.FridayEnd;
double fridayDiff = fridayEnd - fridayStart;
hours += fridayDiff;
schedule.FridayStart = fridayStart;
schedule.FridayEnd = fridayEnd;
if (model.FridayStart == 9 && model.FridayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.FridayOptionalStart != null && model.FridayOptionalEnd != null)
{
double fridayStart = (double)model.FridayOptionalStart;
double fridayEnd = (double)model.FridayOptionalEnd;
double fridayDiff = fridayEnd - fridayStart;
hours += fridayDiff;
schedule.FridayOptionalStart = fridayStart;
schedule.FridayOptionalEnd = fridayEnd;
}
//Saturday
if (model.SaturdayStart != null && model.SaturdayEnd != null)
{
double saturdayStart = (double)model.SaturdayStart;
double saturdayEnd = (double)model.SaturdayEnd;
double saturdayDiff = saturdayEnd - saturdayStart;
hours += saturdayDiff;
schedule.SaturdayStart = saturdayStart;
schedule.SaturdayEnd = saturdayEnd;
if (model.SaturdayStart == 9 && model.SaturdayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.SaturdayOptionalStart != null && model.SaturdayOptionalEnd != null)
{
double saturdayStart = (double)model.SaturdayOptionalStart;
double saturdayEnd = (double)model.SaturdayOptionalEnd;
double saturdayDiff = saturdayEnd - saturdayStart;
hours += saturdayDiff;
schedule.SaturdayOptionalStart = saturdayStart;
schedule.SaturdayOptionalEnd = saturdayEnd;
}
//Sunday
if (model.SundayStart != null && model.SundayEnd != null)
{
double sundayStart = (double)model.SundayStart;
double sundayEnd = (double)model.SundayEnd;
double sundayDiff = sundayEnd - sundayStart;
hours += sundayDiff;
schedule.SundayStart = sundayStart;
schedule.SundayEnd = sundayEnd;
if (model.SundayStart == 9 && model.SundayEnd == 18 && employee.FullTimeAgent == true)
{
hours -= 1;
}
}
if (model.SundayOptionalStart != null && model.SundayOptionalEnd != null)
{
double sundayStart = (double)model.SundayOptionalStart;
double sundayEnd = (double)model.SundayOptionalEnd;
double sundayDiff = sundayEnd - sundayStart;
hours += sundayDiff;
schedule.SundayOptionalStart = sundayStart;
schedule.SundayOptionalEnd = sundayEnd;
}
schedule.Hours = hours;
db.EmployeeSchedules.Add(schedule);
db.SaveChanges();
employee.EmployeeSchedules.Add(schedule);
}
private void ChangeEmployeeSchedule(ScheduleEmployee schedule, ScheduleView model)
{
double hours = 0;
schedule.Hours = 0;
//Monday
if (model.MondayStart != null && model.MondayEnd != null)
{
double mondayStart = double.Parse(model.MondayStart);
double mondayEnd = double.Parse(model.MondayEnd);
double mondayDiff = mondayEnd - mondayStart;
//first set all to null
schedule.MondayStart = mondayStart;
schedule.MondayEnd = mondayEnd;
hours += mondayDiff;
}
else if (model.MondayStart == null && model.MondayEnd == null)
{
schedule.MondayStart = null;
schedule.MondayEnd = null;
}
if (model.MondayOptionalStart != null && model.MondayOptionalEnd != null)
{
double mondayStart = double.Parse(model.MondayOptionalStart);
double mondayEnd = double.Parse(model.MondayOptionalEnd);
double mondayDiff = mondayEnd - mondayStart;
//first set all to null
schedule.MondayOptionalStart = mondayStart;
schedule.MondayOptionalEnd = mondayEnd;
hours += mondayDiff;
}
else if (model.MondayOptionalStart == null && model.MondayOptionalEnd == null)
{
schedule.MondayOptionalStart = null;
schedule.MondayOptionalEnd = null;
}
//Tuesday
if (model.ThuesdayStart != null && model.ThuesdayEnd != null)
{
double tuesdayStart = double.Parse(model.ThuesdayStart);
double tuesdayEnd = double.Parse(model.ThuesdayEnd);
double tuesdayDiff = tuesdayEnd - tuesdayStart;
schedule.ThuesdayStart = tuesdayStart;
schedule.ThuesdayEnd = tuesdayEnd;
hours += tuesdayDiff;
}
else if (model.ThuesdayStart == null && model.ThuesdayStart == null)
{
schedule.ThuesdayStart = null;
schedule.ThuesdayStart = null;
}
if (model.ThuesdayOptionalStart != null && model.MondayOptionalEnd != null)
{
double tuesdayStart = double.Parse(model.ThuesdayOptionalStart);
double tuesdayEnd = double.Parse(model.MondayOptionalEnd);
double tuesdayDiff = tuesdayEnd - tuesdayStart;
schedule.ThuesdayOptionalStart = tuesdayStart;
schedule.MondayOptionalEnd = tuesdayEnd;
hours += tuesdayDiff;
}
else if (model.ThuesdayOptionalStart == null && model.ThuesdayOptionalEnd == null)
{
schedule.ThuesdayOptionalStart = null;
schedule.ThuesdayOptionalEnd = null;
}
//Wednesday
if (model.WednesdayStart != null && model.WednesdayEnd != null)
{
double wednesdayStart = double.Parse(model.WednesdayStart);
double wednesdayEnd = double.Parse(model.WednesdayEnd);
double wednesdayDiff = wednesdayEnd - wednesdayStart;
schedule.WednesdayStart = wednesdayStart;
schedule.WednesdayEnd = wednesdayEnd;
hours += wednesdayDiff;
}
else if (model.WednesdayStart == null && model.WednesdayEnd == null)
{
schedule.WednesdayStart = null;
schedule.WednesdayEnd = null;
}
if (model.WednesdayOptionalStart != null && model.WednesdayOptionalEnd != null)
{
double wednesdayStart = double.Parse(model.WednesdayOptionalStart);
double wednesdayEnd = double.Parse(model.WednesdayOptionalEnd);
double wednesdayDiff = wednesdayEnd - wednesdayStart;
schedule.WednesdayOptionalStart = wednesdayStart;
schedule.WednesdayOptionalEnd = wednesdayEnd;
hours += wednesdayDiff;
}
else if (model.WednesdayOptionalStart == null && model.WednesdayOptionalEnd == null)
{
schedule.WednesdayOptionalStart = null;
schedule.WednesdayOptionalEnd = null;
}
//Thursday
if (model.ThursdayStart != null && model.ThursdayEnd != null)
{
double thursdayStart = double.Parse(model.ThursdayStart);
double thursdayEnd = double.Parse(model.ThursdayEnd);
double thursdayDiff = thursdayEnd - thursdayStart;
schedule.ThursdayStart = thursdayStart;
schedule.ThursdayEnd = thursdayEnd;
hours += thursdayDiff;
}
else if (model.ThursdayStart == null && model.ThursdayEnd == null)
{
schedule.ThursdayStart = null;
schedule.ThursdayEnd = null;
}
if (model.ThursdayOptionalStart != null && model.ThursdayOptionalEnd != null)
{
double thursdayStart = double.Parse(model.ThursdayOptionalStart);
double thursdayEnd = double.Parse(model.ThursdayOptionalEnd);
double thursdayDiff = thursdayEnd - thursdayStart;
schedule.ThursdayOptionalStart = thursdayStart;
schedule.ThursdayOptionalEnd = thursdayEnd;
hours += thursdayDiff;
}
else if (model.ThursdayOptionalStart == null && model.ThursdayOptionalEnd == null)
{
schedule.ThursdayOptionalStart = null;
schedule.ThursdayOptionalEnd = null;
}
//Friday
if (model.FridayStart != null && model.FridayEnd != null)
{
double fridayStart = double.Parse(model.FridayStart);
double fridayEnd = double.Parse(model.FridayEnd);
double fridayDiff = fridayEnd - fridayStart;
schedule.FridayStart = fridayStart;
schedule.FridayEnd = fridayEnd;
hours += fridayDiff;
}
else if (model.FridayStart == null && model.FridayEnd == null)
{
schedule.FridayStart = null;
schedule.FridayEnd = null;
}
if (model.FridayOptionalStart != null && model.FridayOptionalEnd != null)
{
double fridayStart = double.Parse(model.FridayOptionalStart);
double fridayEnd = double.Parse(model.FridayOptionalEnd);
double fridayDiff = fridayEnd - fridayStart;
schedule.FridayOptionalStart = fridayStart;
schedule.FridayOptionalEnd = fridayEnd;
hours += fridayDiff;
}
else if (model.FridayOptionalStart == null && model.FridayOptionalEnd == null)
{
schedule.FridayOptionalStart = null;
schedule.FridayOptionalEnd = null;
}
//Saturday
if (model.SaturdayStart != null && model.SaturdayEnd != null)
{
double saturdayStart = double.Parse(model.SaturdayStart);
double saturdayEnd = double.Parse(model.SaturdayEnd);
double saturdayDiff = saturdayEnd - saturdayStart;
schedule.SaturdayStart = saturdayStart;
schedule.SaturdayEnd = saturdayEnd;
hours += saturdayDiff;
}
else if (model.SaturdayStart == null && model.SaturdayEnd == null)
{
schedule.SaturdayStart = null;
schedule.SaturdayEnd = null;
}
if (model.SaturdayOptionalStart != null && model.SaturdayOptionalEnd != null)
{
double saturdayStart = double.Parse(model.SaturdayOptionalStart);
double saturdayEnd = double.Parse(model.SaturdayOptionalEnd);
double saturdayDiff = saturdayEnd - saturdayStart;
schedule.SaturdayOptionalStart = saturdayStart;
schedule.SaturdayOptionalEnd = saturdayEnd;
hours += saturdayDiff;
}
else if (model.SaturdayOptionalStart == null && model.SaturdayOptionalEnd == null)
{
schedule.SaturdayOptionalStart = null;
schedule.SaturdayOptionalEnd = null;
}
//Sunday
if (model.SundayStart != null && model.SundayEnd != null)
{
double sundayStart = double.Parse(model.SundayStart);
double sundayEnd = double.Parse(model.SundayEnd);
double sundayDiff = sundayEnd - sundayStart;
schedule.SundayStart = sundayStart;
schedule.SundayEnd = sundayEnd;
hours += sundayDiff;
}
else if (model.SundayStart == null && model.SundayEnd == null)
{
schedule.SundayStart = null;
schedule.SundayEnd = null;
}
if (model.SundayOptionalStart != null && model.SundayOptionalEnd != null)
{
double sundayStart = double.Parse(model.SundayOptionalStart);
double sundayEnd = double.Parse(model.SundayOptionalEnd);
double sundayDiff = sundayEnd - sundayStart;
schedule.SundayOptionalStart = sundayStart;
schedule.SundayOptionalEnd = sundayEnd;
hours += sundayDiff;
}
else if (model.SundayOptionalStart == null && model.SundayOptionalEnd == null)
{
schedule.SundayOptionalStart = null;
schedule.SundayOptionalEnd = null;
}
schedule.Hours = hours;
}
}
} |
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Entidades;
using PDV.UTIL;
using PDV.VIEW.App_Context;
using PDV.VIEW.Forms.Cadastro;
using PDV.VIEW.Forms.Util;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Consultas
{
public partial class FCO_UnidadeMedida : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CONSULTA DE UNIDADE DE MEDIDA";
public FCO_UnidadeMedida()
{
InitializeComponent();
AtualizaUnidades("", "");
}
private void AtualizaUnidades(string Codigo, string Descricao)
{
gridControl1.DataSource = FuncoesUnidadeMedida.GetUnidadesMedida(Codigo, Descricao);
gridView1.OptionsBehavior.Editable = false;
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
gridView1.BestFitColumns();
AjustaHeaderTextGrid();
}
private void AjustaHeaderTextGrid()
{
Grids.FormatGrid(ref gridView1);
}
private void ovBTN_Novo_Click(object sender, EventArgs e)
{
FCA_UnidadeMedida t = new FCA_UnidadeMedida(new UnidadeMedida());
t.ShowDialog(this);
AtualizaUnidades("","");
}
private void ovBTN_Editar_Click(object sender, EventArgs e)
{
decimal IDUnidadeMedida = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idunidadedemedida").ToString());
FCA_UnidadeMedida t = new FCA_UnidadeMedida(FuncoesUnidadeMedida.GetUnidadeMedida(IDUnidadeMedida));
t.ShowDialog(this);
AtualizaUnidades("", "");
unidademetroButton.Enabled = false;
}
private void ovBTN_Excluir_Click(object sender, EventArgs e)
{
if (MessageBox.Show(this, "Deseja remover a Unidade de Medida selecionada?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
decimal IDUnidadeMedida = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idunidadedemedida").ToString());
try
{
if (!FuncoesUnidadeMedida.Remover(IDUnidadeMedida))
throw new Exception("Não foi possível remover a Unidade de Medida.");
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AtualizaUnidades("", "");
}
}
private void FCO_UnidadeMedida_Load(object sender, EventArgs e)
{
AtualizaUnidades("", "");
}
private void gridControl1_DoubleClick(object sender, EventArgs e)
{
decimal IDUnidadeMedida = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idunidadedemedida").ToString());
FCA_UnidadeMedida t = new FCA_UnidadeMedida(FuncoesUnidadeMedida.GetUnidadeMedida(IDUnidadeMedida));
t.ShowDialog(this);
AtualizaUnidades("", "");
unidademetroButton.Enabled = false;
}
private void gridControl1_Click(object sender, EventArgs e)
{
unidademetroButton.Enabled = true;
}
private void atualizarMetroButton_Click(object sender, EventArgs e)
{
AtualizaUnidades("","");
}
private void imprimriMetroButton_Click(object sender, EventArgs e)
{
gridView1.ShowPrintPreview();
}
}
}
|
using System.Web;
using System.Web.Optimization;
namespace NBTM
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"
));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*"
, "~/Scripts/jquery.validate*"
));
// DevExpress Bundles and relate. Don't use these unless absoluetly necessary
bundles.Add(new ScriptBundle("~/bundles/DX").Include(
"~/Scripts/globalize.js",
"~/Scripts/globalize.cultures.js",
"~/Scripts/knockout-{version}.js"
));
bundles.Add(new ScriptBundle("~/bundles/toastr").Include(
"~/Scripts/toastr.js"
));
bundles.Add(new ScriptBundle("~/bundles/sweetalert").Include(
"~/Scripts/sweet-alert.js"
));
// Main site CSS
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/Site.css",
"~/Content/Custom.css",
"~/Content/Forms.css",
"~/Content/Errors.css",
"~/Content/sweetalert/sweet-alert.css"
));
// jQuery CSS (DevExpress may or may not use these. Pick and choose)
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/core.css",
"~/Content/themes/base/resizable.css",
"~/Content/themes/base/selectable.css",
"~/Content/themes/base/accordion.css",
"~/Content/themes/base/autocomplete.css",
"~/Content/themes/base/button.css",
"~/Content/themes/base/dialog.css",
"~/Content/themes/base/slider.css",
"~/Content/themes/base/tabs.css",
"~/Content/themes/base/datepicker.css",
"~/Content/themes/base/progressbar.css",
"~/Content/themes/base/theme.css"));
//Toastr CSS
bundles.Add(new StyleBundle("~/Content/toastr").Include(
"~/Content/toastr.css"));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApplication1.Controllers
{
[EnableCors(methods: "*", headers: "*", origins: "*")]
public class RecipeController : ApiController
{[HttpGet]
public IHttpActionResult GettAllRecipe()
{
return Ok(DB.recipeList);
}
[HttpGet]
public IHttpActionResult gettRecipeDetails(string name)
{
foreach(var i in DB.recipeList)
{
if (name == i.NameRecipe)
return Ok(i);
}
return Ok(false);
}
[HttpPost]
public IHttpActionResult AddRecipe(Recipe r)
{
DB.recipeList.Add(new Recipe {NameRecipe=r.NameRecipe,CategoryRecipe=r.CategoryRecipe,Time=r.Time,Difficulty=r.Difficulty,DateAdd=r.DateAdd, Ingredients =r.Ingredients, Preparation =r.Preparation, UserName =r.UserName,Image=r.Image});
return Ok(r.NameRecipe);
}
public IHttpActionResult editRecipe(Recipe newR)
{
foreach (Recipe r in DB.recipeList)
if (r.NameRecipe == newR.NameRecipe)
{
r.CategoryRecipe = newR.CategoryRecipe;
r.Ingredients= newR.Ingredients;
r.Time = newR.Time;
r.Preparation = newR.Preparation;
r.Difficulty = newR.Difficulty;
r.Image = newR.Image;
return Ok("בוצע בהצלחה");
}
return Ok("נכשל");
}
}
} |
using AutoMapper;
using NameSearch.App.Factories;
using NameSearch.Extensions;
using NameSearch.Models.Domain;
using NameSearch.Models.Domain.Api.Response.Interfaces;
using NameSearch.Models.Entities;
using NameSearch.Repository.Interfaces;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace NameSearch.App.Helpers
{
/// <summary>
/// Run Person Search
/// </summary>
public class PersonSearchResultHelper
{
#region Dependencies
/// <summary>
/// The logger
/// </summary>
private readonly ILogger logger = Log.Logger.ForContext<PersonSearchResultHelper>();
/// <summary>
/// The mapper
/// </summary>
private readonly IMapper Mapper;
/// <summary>
/// The repository
/// </summary>
private readonly IEntityFrameworkRepository Repository;
/// <summary>
/// The serializer settings
/// </summary>
private readonly JsonSerializerSettings SerializerSettings;
#endregion Dependencies
/// <summary>
/// Initializes a new instance of the <see cref="PersonSearchResultHelper" /> class.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="serializerSettings">The serializer settings.</param>
/// <param name="mapper">The mapper.</param>
public PersonSearchResultHelper(IEntityFrameworkRepository repository,
JsonSerializerSettings serializerSettings,
IMapper mapper)
{
this.Repository = repository;
this.SerializerSettings = serializerSettings;
this.Mapper = mapper;
}
/// <summary>
/// Imports the specified j object.
/// </summary>
/// <param name="jObject">The j object.</param>
/// <returns></returns>
public PersonSearch Import(JObject jObject)
{
//todo map this
var search = new Search();
#region Create PersonSearchResult Entity
var personSearch = PersonSearchResultFactory.Create(search, null, jObject);
var log = logger.With("PersonSearchResult", personSearch);
#endregion Create PersonSearchResult Entity
#region Log Data Problems
if (!string.IsNullOrWhiteSpace(personSearch.Warnings))
{
log.WarningEvent("Search", "FindPerson api result returned with warning messages");
}
if (!string.IsNullOrWhiteSpace(personSearch.Error))
{
log.ErrorEvent("Search", "FindPerson api result returned with error message");
}
if (string.IsNullOrWhiteSpace(personSearch.Data))
{
log.ErrorEvent("Search", "FindPerson api result returned with no person data"); ;
}
#endregion Log Data Problems
#region Save Entity to Database
Repository.Create(personSearch);
Repository.Save();
#endregion Save Entity to Database
return personSearch;
}
/// <summary>
/// Processes the specified person search result.
/// </summary>
/// <param name="personSearch">The person search result.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">personSearch</exception>
public IEnumerable<Models.Entities.Person> Process(PersonSearch personSearch)
{
if (personSearch == null)
{
throw new ArgumentNullException(nameof(personSearch));
}
var log = logger.With("personSearch", personSearch);
var stopwatch = new Stopwatch();
stopwatch.Start();
#region Deserialize JSON into Model
IFindPersonResponse findPersonResponse;
try
{
findPersonResponse = JsonConvert.DeserializeObject<Models.Domain.Api.Response.FindPersonResponse>(personSearch.Data, SerializerSettings);
}
catch (JsonException ex)
{
//Log and throw
log.With("Data", personSearch.Data)
.ErrorEvent(ex, "Run", "Json Data Deserialization failed after {ms}ms", stopwatch.ElapsedMilliseconds);
throw;
}
#endregion Deserialize JSON into Model
var people = new List<Models.Entities.Person>();
foreach (var person in findPersonResponse.Person)
{
#region Map Model into Entity
var personEntity = Mapper.Map<Models.Entities.Person>(person);
personEntity.PersonSearchId = personSearch.Id;
people.Add(personEntity);
log.With("Person", personEntity);
#endregion Map Model into Entity
#region Save Entity to Database
Repository.Create(personEntity);
foreach (var addressEntity in personEntity.Addresses)
{
addressEntity.PersonId = personEntity.Id;
Repository.Create(addressEntity);
}
foreach (var associateEntity in personEntity.Associates)
{
associateEntity.PersonId = personEntity.Id;
Repository.Create(associateEntity);
}
foreach (var phoneEntity in personEntity.Phones)
{
phoneEntity.PersonId = personEntity.Id;
Repository.Create(phoneEntity);
}
Repository.Save();
log.With("Data", personSearch.Data)
.InformationEvent("Run", "Created Person record after {ms}ms", stopwatch.ElapsedMilliseconds);
#endregion Save Entity to Database
}
log.InformationEvent("Run", "Processing search result finished after {ms}ms", stopwatch.ElapsedMilliseconds);
return people;
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Xml;
using Ios_Android_Project.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Appium.Service;
using OpenQA.Selenium.Appium.Service.Options;
using Castle.Core.Configuration;
using Microsoft.Extensions.Configuration;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using System.Net;
namespace Ios_Android_Project.PageObjectModel
{
public class BaseClass
{
public AppiumDriver<AppiumWebElement> mobiledriver;
//public IOSDriver<IOSElement> iosDriver;
// public AndroidDriver<AppiumWebElement> androiddriver;
public TimeSpan ts = TimeSpan.FromSeconds(5);
AppiumLocalService appiumLocalService;
public BasePageFindElement Base;
public TestContext TestContext { get; set; }
public ExtentReports extent = null;
public BaseClass()
{
}
private void InvokeMethodWithConfig(IEnumerable<IConfigurationSection> config, Action TestMethod)
{
if (config !=null){
foreach (var configItem in config?.Select(x => new { key = x.Key, value = x.Value })?.ToList())
{
if (TestContext.Properties.Contains(configItem.key))
{
TestContext.Properties.Remove(configItem.key);
}
TestContext.Properties.Add(configItem.key, configItem.value);
}
try
{
TestInit();
TestMethod.Invoke();
}
catch (Exception)
{
throw;
}
finally
{
TestClean();
}
}
}
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsetting.json").Build();
protected string Selected_OS;
protected string BoxName;
protected string EnvName;
protected string DBType;
protected string UserType;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
protected void Run(Action TestMethod)
{
var methodBase = (new System.Diagnostics.StackTrace())?.GetFrame(1)?.GetMethod();
var mode = (methodBase.GetCustomAttributes(typeof(TestAttribute), true).FirstOrDefault() as TestAttribute)?.UserMode;
if (mode == null)
{
throw new Exception("Mode Not Defined in TestAttribute");
}
Console.WriteLine("Start Running " + methodBase.Name);
var SelectedMode = config.GetSection("SelectedMode").Value;
var Selectedmode = config.GetSection(SelectedMode)?.GetChildren()?.Select(x => new { key = x.Key, value = x.Value })?.ToList();
var SelectedEnvs = Selectedmode.Where(x => x.key == SelectedMode+"_SelectedEnvs").Select(x => x.value).SingleOrDefault().Split(',').Select(e => e.ToLowerInvariant().Trim())?.ToList();
var SelectedDevices = Selectedmode.Where(x => x.key == SelectedMode + "_SelectedDevice").Select(x => x.value).SingleOrDefault().Split(',').Select(e => e.ToLowerInvariant().Trim())?.ToList();
var SelectedBoxes = Selectedmode.Where(x => x.key == SelectedMode + "_SelectedBoxes").Select(x => x.value).SingleOrDefault().Split(',').Select(e => e.ToLowerInvariant().Trim())?.ToList();
var SelectedDB = Selectedmode.Where(x => x.key == SelectedMode + "_SelectedDB").Select(x => x.value).SingleOrDefault().Split(',').Select(e => e.ToLowerInvariant().Trim())?.ToList();
foreach (var SelectedOS in SelectedDevices)
{
Selected_OS = SelectedOS;
foreach (var SelectedEnv in SelectedEnvs)
{
EnvName = SelectedEnv;
// string relativeFilePath;
string settingName;
switch (mode)
{
case UserMode.Normal:
foreach (var SelectedBox in SelectedBoxes)
{
BoxName = SelectedBox;
UserType = "Normal";
foreach (var SelectedDBType in SelectedDB)
{
DBType = SelectedDBType;
settingName = SelectedBox + "-" + SelectedDBType + "-" + SelectedEnv ;
var Gerowersetting = config.GetSection(settingName)?.GetChildren();
//relativeFilePath = "RunSettingFiles\\" + SelectedBox + "-" + SelectedDBType + "-" + SelectedEnv + ".runsettings";
InvokeMethodWithConfig(Gerowersetting, TestMethod);
}
}
break;
case UserMode.Admin:
break;
case UserMode.SuperAdmin:
UserType = "SuperAdmin";
var SuperAdminsetting = config.GetSection("SuperAdminFile-" + SelectedEnv )?.GetChildren();
//relativeFilePath = "RunSettingFiles\\SuperAdminFile-" + SelectedEnv + ".runsettings";
InvokeMethodWithConfig(SuperAdminsetting, TestMethod);
break;
case UserMode.SystemAdmin:
throw new Exception("Config not found");
break;
default:
throw new Exception("Config not found");
break;
}
}
}
}
// [TestInitialize]
public void TestInit()
{
if (Selected_OS == "ios")
{
startupIos();
}
else
StartAppAndroid();
Base = new BasePageFindElement(mobiledriver);
ExtentStart();
// Authenticate();
}
//[TestCleanup]
public void TestClean()
{
mobiledriver.CloseApp();
mobiledriver.RemoveApp("com.wggesucht.android");
Console.WriteLine("Closing the Application");
appiumLocalService.Dispose();
Console.WriteLine("Closing Appium server");
ExtentClose();
}
public void Authenticate()
{
Base.contextSwitching();
Thread.Sleep(ts);
IWebElement username = mobiledriver.FindElement(By.CssSelector("#username_id"));
Console.WriteLine("Username found");
username.Click();
Thread.Sleep(ts);
username.SendKeys(TestContext.Properties["UserName"].ToString());
Console.WriteLine("Enter Username");
Thread.Sleep(ts);
IWebElement password = mobiledriver.FindElement(By.CssSelector("#password_id"));
password.Click();
password.SendKeys(TestContext.Properties["Password"].ToString());
Console.WriteLine("Enter Password");
Thread.Sleep(ts);
mobiledriver.HideKeyboard();
Thread.Sleep(ts);
IWebElement Authenticate = mobiledriver.FindElement(By.CssSelector("#authenticateBtn"));
Authenticate.Click();
Console.WriteLine("Login sucessfull");
Thread.Sleep(50000);
mobiledriver.SwitchTo().Frame("mainIframe");
}
public void startupIos()
{
var capabilties = new AppiumOptions();
capabilties.AddAdditionalCapability(IOSMobileCapabilityType.BundleId, "com.example.calculator");
capabilties.AddAdditionalCapability(MobileCapabilityType.PlatformName, "ios");
capabilties.AddAdditionalCapability(MobileCapabilityType.AutoWebview, "true");//for webview
capabilties.AddAdditionalCapability(MobileCapabilityType.DeviceName, "iphone 11 Pro Max");
capabilties.AddAdditionalCapability(MobileCapabilityType.AutomationName, "XCUITest");
capabilties.AddAdditionalCapability(MobileCapabilityType.PlatformVersion, "14.4");
capabilties.AddAdditionalCapability(MobileCapabilityType.Udid, "926C5081-E748-4EB5-BDB7-FC4126F641D5");
capabilties.AddAdditionalCapability(MobileCapabilityType.NewCommandTimeout, "2000");
capabilties.AddAdditionalCapability("connectHardwareKeyboard", "true");
//Defing option for server
var serveroptions = new OptionCollector();
var relaxedSecurityOption = new KeyValuePair<string, string>("--relaxed-security", "");
var crossOrigin = new KeyValuePair<string, string>("--allow-cors", "true");
FileInfo log = new FileInfo("Log.txt");
serveroptions.AddArguments(relaxedSecurityOption);
serveroptions.AddArguments(crossOrigin);
serveroptions.AddArguments(GeneralOptionList.OverrideSession());
serveroptions.AddArguments(GeneralOptionList.PreLaunch());
//Defining Appium server --need to pass the node path and appium path from mac machine
appiumLocalService = new AppiumServiceBuilder().
UsingDriverExecutable(new FileInfo("")).
WithAppiumJS(new FileInfo("")).
UsingPort(4723).WithIPAddress("127.0.0.1").
WithArguments(serveroptions).WithLogFile(log)
.Build();
//Starting appium server programatically
appiumLocalService.Start();
Console.WriteLine("Appium started");
//Initilazing Driver
mobiledriver = new IOSDriver<AppiumWebElement>(appiumLocalService, capabilties, TimeSpan.FromMinutes(5));
mobiledriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(90);
}
private void StartAppAndroid()
{
System.Environment.SetEnvironmentVariable("ANDROID_HOME", @"C:\Users\HP PROBOOK\AppData\Local\Android\Sdk");
System.Environment.SetEnvironmentVariable("JAVA_HOME", @"C:\Program Files\Java\jdk1.8.0_291");
Console.WriteLine("Application Started");
var capabilities = new AppiumOptions();
// automatic start of the emulator if not running
capabilities.AddAdditionalCapability(AndroidMobileCapabilityType.Avd, "Pixel_5_API_28");
capabilities.AddAdditionalCapability(AndroidMobileCapabilityType.AvdArgs, "-no-boot-anim -no-snapshot-load");
capabilities.AddAdditionalCapability(MobileCapabilityType.NoReset, false);
capabilities.AddAdditionalCapability(MobileCapabilityType.FullReset, true);
// connecting to a device or emulator
capabilities.AddAdditionalCapability(MobileCapabilityType.DeviceName, "Pixel_5_API_28");
capabilities.AddAdditionalCapability(MobileCapabilityType.AutomationName, "UiAutomator2");
// specifyig which app we want to install and launch
var packagePath = @"C:\Users\HP PROBOOK\Downloads\WG_Gesucht.apk";
packagePath = Path.GetFullPath(packagePath);
Console.WriteLine($"Package path: {packagePath}");
capabilities.AddAdditionalCapability(MobileCapabilityType.App, packagePath);
capabilities.AddAdditionalCapability(AndroidMobileCapabilityType.AppPackage, "com.wggesucht.android");
capabilities.AddAdditionalCapability(AndroidMobileCapabilityType.AppActivity, ".MainActivity");
// specify startup flags appium server to execute adb shell commands
var serveroptions = new OptionCollector();
var relaxedSecurityOption = new KeyValuePair<string, string>("--relaxed-security", "");
serveroptions.AddArguments(relaxedSecurityOption);
appiumLocalService = new AppiumServiceBuilder().UsingAnyFreePort().WithArguments(serveroptions).Build();
appiumLocalService.Start();
mobiledriver = new AndroidDriver<AppiumWebElement>(appiumLocalService, capabilities);
mobiledriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(120);
}
[Obsolete]
public void ExtentStart()
{
string pathProject = AppDomain.CurrentDomain.BaseDirectory;
string pathScreen = pathProject.Replace("\\bin\\Debug", "");
string path = pathScreen + "\\Android_IOS_Reports";
Directory.CreateDirectory(path);
string ReportName = Path.Combine(path, "ExtentReport" + "_");
extent = new ExtentReports();
ExtentV3HtmlReporter htmlReporter = new ExtentV3HtmlReporter(ReportName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html");
extent.AttachReporter(htmlReporter);
string hostname = Dns.GetHostName();
OperatingSystem os = Environment.OSVersion;
extent.AddSystemInfo("Operating System", os.ToString());
extent.AddSystemInfo("HostName", hostname);
extent.AddSystemInfo("Environment", "Production");
extent.AddSystemInfo("Device", "Google Nexus Device");
}
public void ExtentClose()
{
extent.Flush();
}
public string TakesScreenshot(string FileName)
{
string pathProject = AppDomain.CurrentDomain.BaseDirectory;
string pathScreen = pathProject.Replace("\\bin\\Debug", "");
string path = pathScreen + "\\AndroidScreenShots\\";
StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
TimeAndDate.Replace("/", "_");
TimeAndDate.Replace(":", "_");
TimeAndDate.Replace(" ", "_");
string imageName = FileName + TimeAndDate.ToString();
Directory.CreateDirectory(path);
string imageFileName = Path.Combine(path, imageName + "." + System.Drawing.Imaging.ImageFormat.Jpeg);
((ITakesScreenshot)mobiledriver).GetScreenshot().SaveAsFile(imageFileName);
return imageFileName;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
class Ksiazka : Pozycja
{
private int liczbaStron;
private List<Autor> listaAutorow = new List<Autor>();
public Ksiazka()
{
}
public Ksiazka(string tytul, int id, string wydawnictwo, int rokWydania, int liczbaStron) : base(tytul, id, wydawnictwo, rokWydania)
{
this.tytul = tytul;
this.id = id;
this.wydawnictwo = wydawnictwo;
this.rokWydania = rokWydania;
this.liczbaStron = liczbaStron;
}
public void DodajAutora(Autor autor)
{
if (listaAutorow == null)
{
listaAutorow[0] = autor;
}
else
{
listaAutorow.Add(autor);
}
}
public override void WypiszInfo()
{
//Console.WriteLine("\n");
Console.WriteLine("=Książka=");
Console.WriteLine($"\tTytuł: {this.tytul}");
Console.WriteLine($"\tId: {this.id}");
Console.WriteLine($"\tWydawnictwo: {this.wydawnictwo}");
Console.WriteLine($"\tRok wydania: {this.rokWydania}");
Console.WriteLine($"\tLiczba stron: {this.liczbaStron}");
Console.WriteLine($"\tLiczba autorów: {listaAutorow.Count}");
//Console.WriteLine("__");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NoteDoor : MonoBehaviour
{
public bool isOpen;
public bool switchCollider;
public LayerMask openLayer;
public LayerMask closeLayer;
public AudioClip openClip;
public AudioClip closeClip;
public GameObject effect;
private AudioManager aux;
private Collider2D col;
private Animator anim;
private void Awake()
{
aux = AudioManager.instance;
col = GetComponent<Collider2D>();
anim = GetComponent<Animator>();
}
private void Start()
{
OpenDoor(isOpen, false);
}
public void OpenDoor(bool open, bool playEffect)
{
isOpen = open;
if (switchCollider)
{
col.enabled = !open;
}
if (open)
{
anim.Play("DoorOpen");
if (playEffect)
{
if (openClip != null)
{
aux.PlaySound(openClip, true);
}
if (effect != null)
{
Instantiate(effect, col.bounds.center, effect.transform.rotation, transform);
}
}
gameObject.layer = openLayer.ToLayer();
}
else
{
anim.Play("DoorClose");
if (playEffect)
{
if (closeClip != null)
{
aux.PlaySound(closeClip, true);
}
if (effect != null)
{
Instantiate(effect, col.bounds.center, effect.transform.rotation, transform);
}
}
gameObject.layer = closeLayer.ToLayer();
}
}
public void SwitchDoor()
{
OpenDoor(!isOpen, true);
}
}
|
using PaintingCost.Entities;
using PaintingCost.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PaintingCost.DataProvider
{
public class DataProvider : IDataProvider
{
private IRepository _repository;
public DataProvider(IRepository repository)
{
_repository = repository;
}
public bool TryGetPaintingCost(int productId, int sectorId, double squareMeter, out double result, int year = 30)
{
result = 0;
Tuple<Product, Sector> scProduct = _repository.GetProductByIdOnSectorByID(productId, sectorId);
if (scProduct == null)
return false;
Product product = scProduct.Item1;
Sector sector = scProduct.Item2;
result = product.Price * squareMeter * Math.Floor(year / product.RedecorationCycle) * sector.CostMultiplier;
return true;
}
}
}
|
#region License
// Copyright (c) 2007, James M. Curran
//
// 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.
#endregion
namespace Castle.MonoRail.Framework.Filters
{
using Castle.MonoRail.Framework;
/// <summary>
/// Detects if controller is being accessed via a mobile device. <para/>
/// </summary>
/// <remarks>
/// Detects if controller is being accessed via a mobile device.
/// If so, it will change the layout name by prepending <c>"mobile-"</c> to the name, and by defining
/// a PropertyBag value <c>"_IsMobileDevice"</c>.<para/>
///
/// This assumes that for the most part, the layout contain a lot of extreneous
/// elements (fly-out menus, images) as well as the CSS include. By changing the
/// layout (and including a different CSS) the same view template can be reformated
/// to be presentable on a mobile device.<para/>
///
/// This will detect any mobile device that has a *.browser file defined either for the system
/// (in C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers) or locally (in ~\App_Browsers).
/// Since these tend to be out of date, it also triggers on "Windows CE" or "Smartphone" in the
/// user-agent.<para/>
///
/// TODO: An explicit test for iPhones should probably be added.<para/>
/// </remarks>
/// <example><code>
/// [Layout("default"), Rescue("generalerror")]
/// [Filter(ExecuteWhen.BeforeAction,typeof(MobileFilter))]
/// public class ShowController : SmartDispatcherController
/// </code>
/// If viewed from a mobile device, the layout will be changed to "mobile-default".
/// </example>
public class MobileFilter : IFilter
{
#region IFilter Members
/// <summary>
/// Called by Framework.
/// </summary>
/// <param name="exec">When this filter is being invoked. Must be BeforeAction</param>
/// <param name="context">Current context</param>
/// <param name="controller">The controller instance</param>
/// <param name="controllerContext">The controller context.</param>
/// <returns><c>true</c> Always</returns>
public bool Perform(ExecuteWhen exec, IEngineContext context, IController controller, IControllerContext controllerContext)
{
if (exec != ExecuteWhen.BeforeAction)
{
throw new ControllerException("MobileFilter can only be performed as a ExecuteWhen.BeforeAction");
}
if (context.UnderlyingContext.Request.Browser.IsMobileDevice ||
context.UnderlyingContext.Request.UserAgent.Contains("Windows CE") ||
context.UnderlyingContext.Request.UserAgent.Contains("Smartphone"))
{
controllerContext.LayoutNames[0] = "mobile-" + controllerContext.LayoutNames[0];
controllerContext.PropertyBag["_IsMobileDevice"] = "True";
}
return true;
}
#endregion
}
}
|
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Univariate
{
using System;
using Accord.Math;
using AForge;
/// <summary>
/// Discrete uniform distribution.
/// </summary>
///
/// <remarks>
/// <para>
/// In probability theory and statistics, the discrete uniform distribution is a
/// symmetric probability distribution whereby a finite number of values are equally
/// likely to be observed; every one of n values has equal probability 1/n. Another
/// way of saying "discrete uniform distribution" would be "a known, finite number of
/// outcomes equally likely to happen".</para>
///
/// <para>
/// A simple example of the discrete uniform distribution is throwing a fair die.
/// The possible values are 1, 2, 3, 4, 5, 6, and each time the die is thrown the
/// probability of a given score is 1/6. If two dice are thrown and their values
/// added, the resulting distribution is no longer uniform since not all sums have
/// equal probability.</para>
///
/// <para>
/// The discrete uniform distribution itself is inherently non-parametric. It is
/// convenient, however, to represent its values generally by an integer interval
/// [a,b], so that a,b become the main parameters of the distribution (often one
/// simply considers the interval [1,n] with the single parameter n). </para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Uniform_distribution_(discrete)">
/// Wikipedia, The Free Encyclopedia. Uniform distribution (discrete). Available on:
/// http://en.wikipedia.org/wiki/Uniform_distribution_(discrete) </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <code>
/// // Create an uniform (discrete) distribution in [2, 6]
/// var dist = new UniformDiscreteDistribution(a: 2, b: 6);
///
/// // Common measures
/// double mean = dist.Mean; // 4.0
/// double median = dist.Median; // 4.0
/// double var = dist.Variance; // 1.3333333333333333
///
/// // Cumulative distribution functions
/// double cdf = dist.DistributionFunction(k: 2); // 0.2
/// double ccdf = dist.ComplementaryDistributionFunction(k: 2); // 0.8
///
/// // Probability mass functions
/// double pmf1 = dist.ProbabilityMassFunction(k: 4); // 0.2
/// double pmf2 = dist.ProbabilityMassFunction(k: 5); // 0.2
/// double pmf3 = dist.ProbabilityMassFunction(k: 6); // 0.2
/// double lpmf = dist.LogProbabilityMassFunction(k: 2); // -1.6094379124341003
///
/// // Quantile function
/// int icdf1 = dist.InverseDistributionFunction(p: 0.17); // 2
/// int icdf2 = dist.InverseDistributionFunction(p: 0.46); // 4
/// int icdf3 = dist.InverseDistributionFunction(p: 0.87); // 6
///
/// // Hazard (failure rate) functions
/// double hf = dist.HazardFunction(x: 4); // 0.5
/// double chf = dist.CumulativeHazardFunction(x: 4); // 0.916290731874155
///
/// // String representation
/// string str = dist.ToString(CultureInfo.InvariantCulture); // "U(x; a = 2, b = 6)"
/// </code>
/// </example>
///
[Serializable]
public class UniformDiscreteDistribution : UnivariateDiscreteDistribution,
ISampleableDistribution<int>
{
// Distribution parameters
private int a;
private int b;
// Derived measures
private int n;
/// <summary>
/// Creates a discrete uniform distribution defined in the interval [a;b].
/// </summary>
///
/// <param name="a">The starting (minimum) value a.</param>
/// <param name="b">The ending (maximum) value b.</param>
///
public UniformDiscreteDistribution([Integer] int a, [Integer] int b)
{
if (a > b)
{
throw new ArgumentOutOfRangeException("b",
"The starting number a must be lower than b.");
}
this.a = a;
this.b = b;
this.n = b - a + 1;
}
/// <summary>
/// Gets the minimum value of the distribution (a).
/// </summary>
///
public double Minimum { get { return a; } }
/// <summary>
/// Gets the maximum value of the distribution (b).
/// </summary>
///
public double Maximum { get { return b; } }
/// <summary>
/// Gets the length of the distribution (b - a + 1).
/// </summary>
///
public double Length { get { return n; } }
/// <summary>
/// Gets the mean for this distribution.
/// </summary>
///
public override double Mean
{
get { return (a + b) / 2.0; }
}
/// <summary>
/// Gets the variance for this distribution.
/// </summary>
///
public override double Variance
{
get { return ((b - a) * (b - a)) / 12.0; }
}
/// <summary>
/// Gets the entropy for this distribution.
/// </summary>
///
public override double Entropy
{
get { return Math.Log(b - a); }
}
/// <summary>
/// Gets the support interval for this distribution.
/// </summary>
///
/// <value>
/// A <see cref="DoubleRange" /> containing
/// the support interval for this distribution.
/// </value>
///
public override IntRange Support
{
get { return new IntRange(a, b); }
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// this distribution evaluated at point <c>k</c>.
/// </summary>
///
/// <param name="k">A single point in the distribution range.</param>
///
/// <remarks>
/// The Cumulative Distribution Function (CDF) describes the cumulative
/// probability that a given value or any value smaller than it will occur.
/// </remarks>
///
public override double DistributionFunction(int k)
{
if (k < a)
return 0;
if (k >= b)
return 1;
return (k - a + 1.0) / n;
}
/// <summary>
/// Gets the probability mass function (pmf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="k">A single point in the distribution range.</param>
///
/// <returns>
/// The probability of <c>k</c> occurring
/// in the current distribution.
/// </returns>
///
/// <remarks>
/// The Probability Mass Function (PMF) describes the
/// probability that a given value <c>k</c> will occur.
/// </remarks>
///
public override double ProbabilityMassFunction(int k)
{
if (k >= a && k <= b)
return 1.0 / n;
else return 0;
}
/// <summary>
/// Gets the log-probability mass function (pmf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
/// <param name="k">A single point in the distribution range.</param>
/// <returns>
/// The logarithm of the probability of <c>k</c>
/// occurring in the current distribution.
/// </returns>
/// <remarks>
/// The Probability Mass Function (PMF) describes the
/// probability that a given value <c>k</c> will occur.
/// </remarks>
public override double LogProbabilityMassFunction(int k)
{
if (k >= a && k <= b)
return -Math.Log(n);
else return double.NegativeInfinity;
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting, such
/// as regularization constants and additional parameters.</param>
///
/// <remarks>
/// Although both double[] and double[][] arrays are supported,
/// providing a double[] for a multivariate distribution or a
/// double[][] for a univariate distribution may have a negative
/// impact in performance.
/// </remarks>
///
public override void Fit(double[] observations, double[] weights, Fitting.IFittingOptions options)
{
if (options != null)
throw new ArgumentException("No options may be specified.");
if (weights != null)
throw new ArgumentException("This distribution does not support weighted samples.");
a = (int)observations.Min();
b = (int)observations.Max();
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
///
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
///
public override object Clone()
{
return new UniformDiscreteDistribution(a, b);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format(formatProvider, "U(x; a = {0}, b = {1})",
a.ToString(format, formatProvider),
b.ToString(format, formatProvider));
}
/// <summary>
/// Generates a random observation from the current distribution.
/// </summary>
///
/// <returns>A random observations drawn from this distribution.</returns>
///
public override int Generate()
{
return Accord.Math.Random.Generator.Random.Next(a, b);
}
/// <summary>
/// Generates a random vector of observations from the current distribution.
/// </summary>
///
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>A random vector of observations drawn from this distribution.</returns>
///
public override int[] Generate(int samples)
{
int[] result = new int[samples];
for (int i = 0; i < result.Length; i++)
result[i] = Accord.Math.Random.Generator.Random.Next(a, b);
return result;
}
}
}
|
using System;
using CafeMana.DTO;
using CafeMana.BLL;
using System.Windows.Forms;
namespace CafeMana.VIEW
{
public partial class AddAccount : Form
{
public AddAccount()
{
InitializeComponent();
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
if (txbUserName.Text.Trim().Length > 0 && txbPassword.Text.Trim().Length > 0 && txbEmail.Text.Trim().Length > 0 && cbBoxRole.Text.Length > 0 && txbPassword.Text == txbConfirm.Text)
{
bool exist = false;
foreach (User user in Data.Instance.UsersList) if (user.Email == txbEmail.Text.Trim()) exist = true;
if (exist) throw null;
int _ID = UserBLL.Instance.RetreiveUserID();
string _UserName = txbUserName.Text;
var h1 = new DTO.Hash();
string _Password = h1.MD5(txbPassword.Text);
string _Email = txbEmail.Text;
string _Role = cbBoxRole.Text;
if(UserBLL.Instance.AddNewUser(new User() { ID = _ID, Name = _UserName, Role = _Role, Email = _Email, Password = _Password })) MessageBox.Show("Them Thanh Cong!");
else MessageBox.Show("Them That Bai!");
}
else throw null;
}
catch
{
MessageBox.Show("Loi Nhap Thong Tin!");
}
}
}
}
|
using System;
namespace RMAT3.Models
{
public class PolicyLocation
{
public Guid PolicyLocationId { get; set; }
public string AddedByUserId { get; set; }
public DateTime AddTs { get; set; }
public string UpdatedByUserId { get; set; }
public DateTime UpdatedTs { get; set; }
public bool IsActiveInd { get; set; }
public DateTime? PolicyLocationEffectiveDt { get; set; }
public DateTime? PolicyLocationExpirationDt { get; set; }
public string PolicyLocationNbr { get; set; }
public string PolicyNbr { get; set; }
public Guid LocationId { get; set; }
public virtual Location Location { get; set; }
public virtual Policy Policy { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using NieLada.Models;
namespace NieLada.Controllers
{
public class StylController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Styl
public async Task<ActionResult> Index()
{
return View(await db.Style.ToListAsync());
}
public ActionResult PokazStyla()
{
string img = "/Img/pobrane.jpg";
List<Styl> Style = new List<Styl> { new Styl { Nazwa = "Firmowy",
Opis = "Bukiet \"firmowy\" to nasz flagowy bukiet. Zawsze się podoba!",
ZdjecieUrl = img },
new Styl { Nazwa = "Zbity",
Opis = "Bukiet \"zbity\" to wypełniona po brzegi kwiatami kolorowa kulka:)!",
ZdjecieUrl = img },
new Styl { Nazwa = "Polny",
Opis = "Bukiet \"polny\" chłopsko-rolny",
ZdjecieUrl = img },
new Styl { Nazwa = "Biedermeier",
Opis = "Bukiet w stylu \"biedermeier\" rozjebuje umysł!",
ZdjecieUrl = img }};
return View(Style);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Tem.Action;
public interface ISSActionCallback {
void SSEventAction(SSAction source, SSActionEventType events = SSActionEventType.COMPLETED,
int intParam = 0, string strParam = null, Object objParam = null);
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PetSharing.Domain.Dtos
{
public class CommentDto
{
public int Id { get; set; }
public int PostId { get; set; }
public string UserId { get; set; }
public string UserPic { get; set; }
public string UserName { get; set; }
public int LikeCount { get; set; }
public string Text { get; set; }
public DateTime? Date { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*Написать программу — телефонный справочник —
создать двумерный массив 5*2,
хранящий список телефонных контактов:
первый элемент хранит имя контакта,
второй — номер телефона/e-mail.
*/
namespace l3p
{
class l3p2
{
public static void Contact_list()
{
string[,] list = { { "Михаил", "713-66-144"},
{ "Александр", "mail@mail.com"} };
Print_list(list);
}
//вывести список всех контактов
public static void Print_list(string[,] list)
{
for(int i = 0; i < list.GetUpperBound(0) + 1; i++)
{
Print_list(list, i);
}
}
//вывести один контакт из списка
public static void Print_list(string[,] list, int num_contact)
{
Console.WriteLine($"Имя: {list[num_contact, 0]} Почта/телефон: {list[num_contact, 1]}");
}
}
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class DynStation
{
public DynStation()
{
ArcAktenaufenthalt = new HashSet<ArcAktenaufenthalt>();
ArcArchiv = new HashSet<ArcArchiv>();
}
public int StationId { get; set; }
public string Bezeichnung { get; set; }
public bool? Aktiv { get; set; }
public int? Kisid { get; set; }
public string KurzBezeichnung { get; set; }
public int? HausId { get; set; }
public int? FachabteilungId { get; set; }
public virtual DynFachabteilung Fachabteilung { get; set; }
public virtual ICollection<ArcAktenaufenthalt> ArcAktenaufenthalt { get; set; }
public virtual ICollection<ArcArchiv> ArcArchiv { get; set; }
}
}
|
#define ACO_DEBUG
using SocketIO;
using UnityEngine.Assertions;
using System.Threading;
namespace ACO.Net.Protocol.SocketIO
{
public class Bridge<T> : Protocol.Bridge<T> where T : class
{
static Bridge()
{
baseErrors.Add("authDataEmpty", "Incorrect authorization data");
baseErrors.Add("noUserFinded", "Failed to authorize player");
}
public Bridge(DataFormat.Converter<T> dataConverter, Config config, Net.Protocol.SocketIO.Connector connector) : base(dataConverter, config)
{
this.connector = connector;
this.connector.onOpen -= Init;
this.connector.onOpen += Init;
Init();
}
protected Net.Protocol.SocketIO.Connector connector;
public virtual void Init()
{
if (this.connector.socket != null)
{
Init(this.connector.socket);
}
}
public virtual void Init(SocketIOComponent socket)
{
//UnityEngine.Debug.Log("Bridge initialized: "+prefix);
Assert.AreNotEqual(socket, null);
}
protected override void RecieveBase(string act, System.Action<string> callback)
{
connector.Subscribe(act, callback);
}
protected override void EmitBase(string message, string data, System.Action<string> callback)
{
ACO.ErrorCollector err = new ErrorCollector();
JSONObject j = JSONObject.Create(JSONObject.Type.OBJECT);
JSONObject testDataissue = new JSONObject(data);
if (testDataissue.ToString() == "null")
{
j.AddField("message", data);
}
else
{
j.AddField("message", testDataissue);
}
//UnityEngine.Debug.Log("PRESEND FINAL DATA: " + j.ToString());
string nnn = Thread.CurrentThread.Name;
this.connector.socket.Emit(message, j, (res) => {
//UnityEngine.Debug.Log(res.ToString());
string nnnn = Thread.CurrentThread.Name;
if (callback != null)
{
callback(res.ToString());
}
});
}
//protected void Emit(
// string act,
// JSONObject j,
// System.Action<JSONObject> onSuccess,
// System.Action<JSONObject> onFail,
// System.Action<JSONObject> onRecieve = null,
// string logMessage = ""
// )
//{
// Emit(act, j, (res) =>
// {
// if (onRecieve != null)
// {
// onRecieve(res);
// }
// if (IsOk(res))
// {
// if (onSuccess != null)
// {
// onSuccess(res);
// }
// }
// else
// {
// if (onFail != null)
// {
// onFail(res);
// }
// }
// }, logMessage);
//}
//protected void Emit(
// string act,
// JSONObject j,
// Dictionary<string, string> errors,
// System.Action<JSONObject> onSuccess,
// System.Action<JSONObject> onFail,
// System.Action<JSONObject> onRecieve = null,
// string logMessage = ""
// )
//{
// Emit(act, j, onSuccess, (res) => {
// ProcessFail(res, errors, (msg) => {
// if (onFail != null)
// {
// onFail(res);
// }
// }, prefix + ":" + act);
// },
// onRecieve, logMessage);
//}
//protected bool IsOk(JSONObject msg)
//{
// return msg[responseName].str == "ok";
//}
//protected void ProcessFail(JSONObject msg, Dictionary<string, string> dict, System.Action<string> action, string additionalInfo)
//{
// string res = msg[responseName].str;
// Assert.AreNotEqual(socket, null);
// string message = "Unknown error: ["+additionalInfo+"]: " + res;
// if (dict.ContainsKey(res))
// {
// message = dict[res];
// }
// else
// {
// UnityEngine.Debug.LogError(message);
// }
// if (action != null)
// {
// action(res);
// }
// LogError(message);
//}
/*public void SetLogger(System.Action<string> add, System.Action<string> end)
{
LogAdd = add; LogEnd = end;
}
public void SetErrorLogger(System.Action<string> log)
{
LogError = log;
}
public void ResetLogger()
{
LogAdd = def_logAdd;
LogEnd = def_logEnd;
}
public void ResetErrorLogger()
{
LogError = def_logError;
}*/
}
} |
using CourseProject.ViewModel;
using System.Windows;
using System.Windows.Controls;
namespace CourseProject.View
{
public partial class PersonAreaPage : Page
{
AccountViewModel personAreaViewModel = new AccountViewModel();
public PersonAreaPage()
{
InitializeComponent();
DataContext = personAreaViewModel;
}
private void saveChangesButton_Click(object sender, RoutedEventArgs e)
{
//infoLabel.Foreground = personAreaViewModel.ChangeDataOfUser
//(Info = "Изменения успешно сохранены!") ? Brushes.LimeGreen : Brushes.Red;
personAreaViewModel.ChangeDataOfUser();
}
private void deleteUserButton_Click(object sender, RoutedEventArgs e)
{
personAreaViewModel.DeleteUser();
}
private void imageButton_Click(object sender, RoutedEventArgs e)
{
personAreaViewModel.LoadImageFromFS();
}
}
}
|
using PMA.Store_Domain.Photos.Entities;
using PMA.Store_Framework.Domain;
namespace PMA.Store_Domain.Masters.Entities
{
public class MasterProductPhoto : BaseEntity
{
public MasterProduct MasterProducts { get; set; }
public long MasterProductsId { get; set; }
public Photo Photo { get; set; }
public long PhotoId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace Dao.Mercadeo
{
public interface ICampaniaProdPartesDao : IGenericDao<crmCampaniaProdPartes>
{
/// <summary>
/// Metodo que permite obtener todas las partes del producto(chasis)
/// </summary>
/// <param name="idProducto">Código de producto</param>
/// <param name="idColores">Código de colores</param>
/// <returns>Lista de chasis o partes de un producto</returns>
List<InvProductoPartes> GetProductoPartes(long idProducto, long[] idColores);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Autentica
{
class Respuesta
{
public String Token;
public int CodeStatus;
}
}
|
using MyCashFlow.Domains.DataObject;
using MyCashFlow.Identity.Context;
using MyCashFlow.Identity.Stores;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System;
namespace MyCashFlow.Identity.Initializer
{
// TODO: Change parent to DropCreateDatabaseIfModelChanges before release
public class DatabaseInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
AddCountries(context);
AddPaymentMethods(context);
AddTransactionTypes(context);
AddUsers(context);
AddProjects(context);
AddTransactions(context);
AddCurrency(context);
}
#region Helpers
private static void AddCountries(ApplicationDbContext context)
{
var countries = new List<Country>
{
new Country { Name = "Abkhazia", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 7840 },
new Country { Name = "Afghanistan", ISOCode2 = "AF", ISOCode3 = "AFG", TelephoneCountryCode = 93 },
new Country { Name = "Akrotiri and Dhekelia", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 357 },
new Country { Name = "Albania", ISOCode2 = "AL", ISOCode3 = "ALB", TelephoneCountryCode = 355 },
new Country { Name = "Alderney", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 44181 },
new Country { Name = "Algeria", ISOCode2 = "DZ", ISOCode3 = "DZD", TelephoneCountryCode = 213 },
new Country { Name = "Andorra", ISOCode2 = "AD", ISOCode3 = "AND", TelephoneCountryCode = 376 },
new Country { Name = "Angola", ISOCode2 = "AO", ISOCode3 = "AGO", TelephoneCountryCode = 244 },
new Country { Name = "Anguilla", ISOCode2 = "AI", ISOCode3 = "AIA", TelephoneCountryCode = 1264 },
new Country { Name = "Antigua and Barbuda", ISOCode2 = "AG", ISOCode3 = "ATG", TelephoneCountryCode = 1268 },
new Country { Name = "Argentina", ISOCode2 = "AR", ISOCode3 = "ARG", TelephoneCountryCode = 54 },
new Country { Name = "Armenia", ISOCode2 = "AM", ISOCode3 = "ARM", TelephoneCountryCode = 374 },
new Country { Name = "Aruba", ISOCode2 = "AW", ISOCode3 = "ABW", TelephoneCountryCode = 297},
new Country { Name = "Ascension Island", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 247 },
new Country { Name = "Australia", ISOCode2 = "AU", ISOCode3 = "AUS", TelephoneCountryCode = 61 },
new Country { Name = "Austria", ISOCode2 = "AT", ISOCode3 = "AUT", TelephoneCountryCode = 43 },
new Country { Name = "Azerbaijan", ISOCode2 = "AZ", ISOCode3 = "AZE", TelephoneCountryCode = 994 },
new Country { Name = "Bahamas, The", ISOCode2 = "BS", ISOCode3 = "BHS", TelephoneCountryCode = 1242 },
new Country { Name = "Bahrain", ISOCode2 = "BH", ISOCode3 = "BHR", TelephoneCountryCode = 973 },
new Country { Name = "Bangladesh", ISOCode2 = "BD", ISOCode3 = "BGD", TelephoneCountryCode = 880 },
new Country { Name = "Barbados", ISOCode2 = "BB", ISOCode3 = "BRB", TelephoneCountryCode = 1246 },
new Country { Name = "Belarus", ISOCode2 = "BY", ISOCode3 = "BLR", TelephoneCountryCode = 375 },
new Country { Name = "Belgium", ISOCode2 = "BE", ISOCode3 = "BEL", TelephoneCountryCode = 32 },
new Country { Name = "Belize", ISOCode2 = "BZ", ISOCode3 = "BLZ", TelephoneCountryCode = 501 },
new Country { Name = "Benin", ISOCode2 = "BJ", ISOCode3 = "BEN", TelephoneCountryCode = 229 },
new Country { Name = "Bermuda", ISOCode2 = "BM", ISOCode3 = "BMU", TelephoneCountryCode = 1441 },
new Country { Name = "Bhutan", ISOCode2 = "BT", ISOCode3 = "BTN", TelephoneCountryCode = 975 },
new Country { Name = "Bolivia", ISOCode2 = "BO", ISOCode3 = "BOL", TelephoneCountryCode = 591 },
new Country { Name = "Bonaire", ISOCode2 = "BQ", ISOCode3 = "BES", TelephoneCountryCode = 5997 },
new Country { Name = "Bosnia and Herzegovina", ISOCode2 = "BA", ISOCode3 = "BIH", TelephoneCountryCode = 387 },
new Country { Name = "Botswana", ISOCode2 = "BW", ISOCode3 = "BWA", TelephoneCountryCode = 267 },
new Country { Name = "Brazil", ISOCode2 = "BR", ISOCode3 = "BRA", TelephoneCountryCode = 55 },
new Country { Name = "British Indian Ocean Territory", ISOCode2 = "IO", ISOCode3 = "IOT", TelephoneCountryCode = 246 },
new Country { Name = "British Virgin Islands", ISOCode2 = "VG", ISOCode3 = "VGB", TelephoneCountryCode = 1284 },
new Country { Name = "Brunei", ISOCode2 = "BN", ISOCode3 = "BRN", TelephoneCountryCode = 673 },
new Country { Name = "Bulgaria", ISOCode2 = "BG", ISOCode3 = "BGR", TelephoneCountryCode = 359 },
new Country { Name = "Burkina Faso", ISOCode2 = "BF", ISOCode3 = "BFA", TelephoneCountryCode = 226 },
new Country { Name = "Burma", ISOCode2 = "MM", ISOCode3 = "MMR", TelephoneCountryCode = 95 },
new Country { Name = "Burundi", ISOCode2 = "BI", ISOCode3 = "BDI", TelephoneCountryCode = 257 },
new Country { Name = "Cambodia", ISOCode2 = "KH", ISOCode3 = "KHM", TelephoneCountryCode = 855 },
new Country { Name = "Cameroon", ISOCode2 = "CM", ISOCode3 = "CMR", TelephoneCountryCode = 237 },
new Country { Name = "Canada", ISOCode2 = "CA", ISOCode3 = "CAN", TelephoneCountryCode = 1 },
new Country { Name = "Cape Verde", ISOCode2 = "CV", ISOCode3 = "CPV", TelephoneCountryCode = 238 },
new Country { Name = "Cayman Islands", ISOCode2 = "KY", ISOCode3 = "CYM", TelephoneCountryCode = 1345 },
new Country { Name = "Central African Republic", ISOCode2 = "CF", ISOCode3 = "CAF", TelephoneCountryCode = 236 },
new Country { Name = "Chad", ISOCode2 = "TD", ISOCode3 = "TCD", TelephoneCountryCode = 235 },
new Country { Name = "Chile", ISOCode2 = "CL", ISOCode3 = "CHL", TelephoneCountryCode = 56 },
new Country { Name = "China, People's Republic of", ISOCode2 = "CN", ISOCode3 = "CHN", TelephoneCountryCode = 86 },
new Country { Name = "Cocos (Keeling) Islands", ISOCode2 = "CC", ISOCode3 = "CCK", TelephoneCountryCode = 61 },
new Country { Name = "Colombia", ISOCode2 = "CO", ISOCode3 = "COL", TelephoneCountryCode = 57 },
new Country { Name = "Comoros", ISOCode2 = "KM", ISOCode3 = "COM", TelephoneCountryCode = 269 },
new Country { Name = "Congo, Democratic Republic of the", ISOCode2 = "CD", ISOCode3 = "COD", TelephoneCountryCode = 243 },
new Country { Name = "Congo, Republic of the", ISOCode2 = "CG", ISOCode3 = "COG", TelephoneCountryCode = 242 },
new Country { Name = "Cook Islands", ISOCode2 = "CK", ISOCode3 = "COK", TelephoneCountryCode = 682 },
new Country { Name = "Costa Rica", ISOCode2 = "CR", ISOCode3 = "CRC", TelephoneCountryCode = 506 },
new Country { Name = "Côte d'Ivoire", ISOCode2 = "CI", ISOCode3 = "CIV", TelephoneCountryCode = 225 },
new Country { Name = "Croatia", ISOCode2 = "HR", ISOCode3 = "HRV", TelephoneCountryCode = 385 },
new Country { Name = "Cuba", ISOCode2 = "CU", ISOCode3 = "CUB", TelephoneCountryCode = 53 },
new Country { Name = "Curaçao", ISOCode2 = "CW", ISOCode3 = "CUW", TelephoneCountryCode = 5999 },
new Country { Name = "Cyprus", ISOCode2 = "CY", ISOCode3 = "CYP", TelephoneCountryCode = 357 },
new Country { Name = "Czech Republic", ISOCode2 = "CZ", ISOCode3 = "CZE", TelephoneCountryCode = 420 },
new Country { Name = "Denmark", ISOCode2 = "DK", ISOCode3 = "DNK", TelephoneCountryCode = 45 },
new Country { Name = "Djibouti", ISOCode2 = "DJ", ISOCode3 = "DJI", TelephoneCountryCode = 253 },
new Country { Name = "Dominica", ISOCode2 = "DM", ISOCode3 = "DMA", TelephoneCountryCode = 1767 },
new Country { Name = "Dominican Republic", ISOCode2 = "DO", ISOCode3 = "DOM", TelephoneCountryCode = 1809 },
new Country { Name = "East Timor", ISOCode2 = "TL", ISOCode3 = "TLS", TelephoneCountryCode = 670 },
new Country { Name = "Ecuador", ISOCode2 = "EC", ISOCode3 = "ECU", TelephoneCountryCode = 593 },
new Country { Name = "Egypt", ISOCode2 = "EG", ISOCode3 = "EGY", TelephoneCountryCode = 20 },
new Country { Name = "El Salvador", ISOCode2 = "SV", ISOCode3 = "SLV", TelephoneCountryCode = 503 },
new Country { Name = "Equatorial Guinea", ISOCode2 = "GQ", ISOCode3 = "GNQ", TelephoneCountryCode = 240 },
new Country { Name = "Eritrea", ISOCode2 = "ER", ISOCode3 = "ERI", TelephoneCountryCode = 291 },
new Country { Name = "Estonia", ISOCode2 = "EE", ISOCode3 = "EST", TelephoneCountryCode = 372 },
new Country { Name = "Ethiopia", ISOCode2 = "ET", ISOCode3 = "ETH", TelephoneCountryCode = 251 },
new Country { Name = "Falkland Islands", ISOCode2 = "FK", ISOCode3 = "FLK", TelephoneCountryCode = 500 },
new Country { Name = "Faroe Islands", ISOCode2 = "FO", ISOCode3 = "FRO", TelephoneCountryCode = 298 },
new Country { Name = "Fiji", ISOCode2 = "FJ", ISOCode3 = "FJI", TelephoneCountryCode = 679 },
new Country { Name = "Finland", ISOCode2 = "FI", ISOCode3 = "FIN", TelephoneCountryCode = 358 },
new Country { Name = "France", ISOCode2 = "FR", ISOCode3 = "FRA", TelephoneCountryCode = 33 },
new Country { Name = "French Polynesia", ISOCode2 = "PF", ISOCode3 = "PYF", TelephoneCountryCode = 689 },
new Country { Name = "Gabon", ISOCode2 = "GA", ISOCode3 = "GAB", TelephoneCountryCode = 241 },
new Country { Name = "Gambia, The", ISOCode2 = "GM", ISOCode3 = "GMB", TelephoneCountryCode = 220 },
new Country { Name = "Georgia", ISOCode2 = "GE", ISOCode3 = "GEO", TelephoneCountryCode = 995 },
new Country { Name = "Germany", ISOCode2 = "DE", ISOCode3 = "DEU", TelephoneCountryCode = 49 },
new Country { Name = "Ghana", ISOCode2 = "GH", ISOCode3 = "GHA", TelephoneCountryCode = 233 },
new Country { Name = "Gibraltar", ISOCode2 = "GI", ISOCode3 = "GIB", TelephoneCountryCode = 350 },
new Country { Name = "Greece", ISOCode2 = "GR", ISOCode3 = "GRC", TelephoneCountryCode = 30 },
new Country { Name = "Grenada", ISOCode2 = "GD", ISOCode3 = "GRD", TelephoneCountryCode = 1473 },
new Country { Name = "Guatemala", ISOCode2 = "GT", ISOCode3 = "GTM", TelephoneCountryCode = 502 },
new Country { Name = "Guernsey", ISOCode2 = "GG", ISOCode3 = "GGY", TelephoneCountryCode = 44 },
new Country { Name = "Guinea", ISOCode2 = "GN", ISOCode3 = "GIN", TelephoneCountryCode = 224 },
new Country { Name = "Guinea-Bissau", ISOCode2 = "GW", ISOCode3 = "GNB", TelephoneCountryCode = 245 },
new Country { Name = "Guyana", ISOCode2 = "GY", ISOCode3 = "GUY", TelephoneCountryCode = 592 },
new Country { Name = "Haiti", ISOCode2 = "HT", ISOCode3 = "HTI", TelephoneCountryCode = 509 },
new Country { Name = "Honduras", ISOCode2 = "HN", ISOCode3 = "HND", TelephoneCountryCode = 504 },
new Country { Name = "Hong Kong", ISOCode2 = "HK", ISOCode3 = "HKG", TelephoneCountryCode = 852 },
new Country { Name = "Hungary", ISOCode2 = "HU", ISOCode3 = "HUN", TelephoneCountryCode = 36 },
new Country { Name = "Iceland", ISOCode2 = "IS", ISOCode3 = "ISL", TelephoneCountryCode = 354 },
new Country { Name = "India", ISOCode2 = "IN", ISOCode3 = "IND", TelephoneCountryCode = 91 },
new Country { Name = "Indonesia", ISOCode2 = "ID", ISOCode3 = "IDN", TelephoneCountryCode = 62 },
new Country { Name = "Iran", ISOCode2 = "IR", ISOCode3 = "IRN", TelephoneCountryCode = 98 },
new Country { Name = "Iraq", ISOCode2 = "IQ", ISOCode3 = "IRQ", TelephoneCountryCode = 964 },
new Country { Name = "Ireland", ISOCode2 = "IE", ISOCode3 = "IRL", TelephoneCountryCode = 353 },
new Country { Name = "Isle of Man", ISOCode2 = "IM", ISOCode3 = "IMN", TelephoneCountryCode = 44 },
new Country { Name = "Israel", ISOCode2 = "IL", ISOCode3 = "ISR", TelephoneCountryCode = 972 },
new Country { Name = "Italy", ISOCode2 = "IT", ISOCode3 = "ITA", TelephoneCountryCode = 39 },
new Country { Name = "Jamaica", ISOCode2 = "JM", ISOCode3 = "JAM", TelephoneCountryCode = 1876 },
new Country { Name = "Japan", ISOCode2 = "JP", ISOCode3 = "JPN", TelephoneCountryCode = 81 },
new Country { Name = "Jersey", ISOCode2 = "JE", ISOCode3 = "JEY", TelephoneCountryCode = 44 },
new Country { Name = "Jordan", ISOCode2 = "JO", ISOCode3 = "JOR", TelephoneCountryCode = 962 },
new Country { Name = "Kazakhstan", ISOCode2 = "KZ", ISOCode3 = "KAZ", TelephoneCountryCode = 7 },
new Country { Name = "Kenya", ISOCode2 = "KE", ISOCode3 = "KEN", TelephoneCountryCode = 254 },
new Country { Name = "Kiribati", ISOCode2 = "KI", ISOCode3 = "KIR", TelephoneCountryCode = 686 },
new Country { Name = "Korea, North", ISOCode2 = "KP", ISOCode3 = "PRK", TelephoneCountryCode = 850 },
new Country { Name = "Korea, South", ISOCode2 = "KR", ISOCode3 = "KOR", TelephoneCountryCode = 82 },
new Country { Name = "Kosovo", ISOCode2 = "XK", ISOCode3 = null, TelephoneCountryCode = 381 },
new Country { Name = "Kuwait", ISOCode2 = "KW", ISOCode3 = "KWT", TelephoneCountryCode = 965 },
new Country { Name = "Kyrgyzstan", ISOCode2 = "KG", ISOCode3 = "KGZ", TelephoneCountryCode = 996 },
new Country { Name = "Laos", ISOCode2 = "LA", ISOCode3 = "LAO", TelephoneCountryCode = 856 },
new Country { Name = "Latvia", ISOCode2 = "LV", ISOCode3 = "LVA", TelephoneCountryCode = 371 },
new Country { Name = "Lebanon", ISOCode2 = "LB", ISOCode3 = "LBN", TelephoneCountryCode = 961 },
new Country { Name = "Lesotho", ISOCode2 = "LS", ISOCode3 = "LSO", TelephoneCountryCode = 266 },
new Country { Name = "Liberia", ISOCode2 = "LR", ISOCode3 = "LBR", TelephoneCountryCode = 231 },
new Country { Name = "Libya", ISOCode2 = "LY", ISOCode3 = "LBY", TelephoneCountryCode = 218 },
new Country { Name = "Liechtenstein", ISOCode2 = "LI", ISOCode3 = "LIE", TelephoneCountryCode = 423 },
new Country { Name = "Lithuania", ISOCode2 = "LT", ISOCode3 = "LTU", TelephoneCountryCode = 370 },
new Country { Name = "Luxembourg", ISOCode2 = "LU", ISOCode3 = "LUX", TelephoneCountryCode = 352 },
new Country { Name = "Macau", ISOCode2 = "MO", ISOCode3 = "MAC", TelephoneCountryCode = 853 },
new Country { Name = "Macedonia, Republic of", ISOCode2 = "MK", ISOCode3 = "MKD", TelephoneCountryCode = 389 },
new Country { Name = "Madagascar", ISOCode2 = "MG", ISOCode3 = "MDG", TelephoneCountryCode = 261 },
new Country { Name = "Malawi", ISOCode2 = "MW", ISOCode3 = "MWI", TelephoneCountryCode = 265 },
new Country { Name = "Malaysia", ISOCode2 = "MY", ISOCode3 = "MYS", TelephoneCountryCode = 60 },
new Country { Name = "Maldives", ISOCode2 = "MV", ISOCode3 = "MDV", TelephoneCountryCode = 960 },
new Country { Name = "Mali", ISOCode2 = "ML", ISOCode3 = "MLI", TelephoneCountryCode = 223 },
new Country { Name = "Malta", ISOCode2 = "MT", ISOCode3 = "MLT", TelephoneCountryCode = 356 },
new Country { Name = "Marshall Islands", ISOCode2 = "MH", ISOCode3 = "MHL", TelephoneCountryCode = 692 },
new Country { Name = "Mauritania", ISOCode2 = "MR", ISOCode3 = "MRT", TelephoneCountryCode = 222 },
new Country { Name = "Mauritius", ISOCode2 = "MU", ISOCode3 = "MUS", TelephoneCountryCode = 230 },
new Country { Name = "Mexico", ISOCode2 = "MX", ISOCode3 = "MEX", TelephoneCountryCode = 52 },
new Country { Name = "Micronesia", ISOCode2 = "FM", ISOCode3 = "FSM", TelephoneCountryCode = 691 },
new Country { Name = "Moldova", ISOCode2 = "MD", ISOCode3 = "MDA", TelephoneCountryCode = 373 },
new Country { Name = "Monaco", ISOCode2 = "MC", ISOCode3 = "MCO", TelephoneCountryCode = 377 },
new Country { Name = "Mongolia", ISOCode2 = "MN", ISOCode3 = "MNG", TelephoneCountryCode = 976 },
new Country { Name = "Montenegro", ISOCode2 = "ME", ISOCode3 = "MNE", TelephoneCountryCode = 382 },
new Country { Name = "Montserrat", ISOCode2 = "MS", ISOCode3 = "MSR", TelephoneCountryCode = 1664 },
new Country { Name = "Morocco", ISOCode2 = "MA", ISOCode3 = "MAR", TelephoneCountryCode = 212 },
new Country { Name = "Mozambique", ISOCode2 = "MZ", ISOCode3 = "MOZ", TelephoneCountryCode = 258 },
new Country { Name = "Nagorno-Karabakh Republic", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 37447 },
new Country { Name = "Namibia", ISOCode2 = "NA", ISOCode3 = "NAM", TelephoneCountryCode = 264 },
new Country { Name = "Nauru", ISOCode2 = "NR", ISOCode3 = "NRU", TelephoneCountryCode = 674 },
new Country { Name = "Nepal", ISOCode2 = "NP", ISOCode3 = "NPL", TelephoneCountryCode = 977 },
new Country { Name = "Netherlands", ISOCode2 = "NL", ISOCode3 = "NLD", TelephoneCountryCode = 31 },
new Country { Name = "New Caledonia", ISOCode2 = "NC", ISOCode3 = "NCL", TelephoneCountryCode = 687 },
new Country { Name = "New Zealand", ISOCode2 = "NZ", ISOCode3 = "NZL", TelephoneCountryCode = 64 },
new Country { Name = "Nicaragua", ISOCode2 = "NI", ISOCode3 = "NIC", TelephoneCountryCode = 505 },
new Country { Name = "Niger", ISOCode2 = "NE", ISOCode3 = "NER", TelephoneCountryCode = 227 },
new Country { Name = "Nigeria", ISOCode2 = "NG", ISOCode3 = "NGA", TelephoneCountryCode = 234 },
new Country { Name = "Niue", ISOCode2 = "NU", ISOCode3 = "NIU", TelephoneCountryCode = 683 },
new Country { Name = "Northern Cyprus", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 90392 },
new Country { Name = "Norway", ISOCode2 = "NO", ISOCode3 = "NOR", TelephoneCountryCode = 47 },
new Country { Name = "Oman", ISOCode2 = "OM", ISOCode3 = "OMN", TelephoneCountryCode = 968 },
new Country { Name = "Pakistan", ISOCode2 = "PK", ISOCode3 = "PAK", TelephoneCountryCode = 92 },
new Country { Name = "Palau", ISOCode2 = "PW", ISOCode3 = "PLW", TelephoneCountryCode = 680 },
new Country { Name = "Palestine", ISOCode2 = "PS", ISOCode3 = "PSE", TelephoneCountryCode = 970 },
new Country { Name = "Panama", ISOCode2 = "PA", ISOCode3 = "PAN", TelephoneCountryCode = 507 },
new Country { Name = "Papua New Guinea", ISOCode2 = "PG", ISOCode3 = "PNG", TelephoneCountryCode = 675 },
new Country { Name = "Paraguay", ISOCode2 = "PY", ISOCode3 = "PRY", TelephoneCountryCode = 595 },
new Country { Name = "Peru", ISOCode2 = "PE", ISOCode3 = "PER", TelephoneCountryCode = 51 },
new Country { Name = "Philippines", ISOCode2 = "PH", ISOCode3 = "PHL", TelephoneCountryCode = 63 },
new Country { Name = "Pitcairn Islands", ISOCode2 = "PN", ISOCode3 = "PCN", TelephoneCountryCode = 870 },
new Country { Name = "Poland", ISOCode2 = "PL", ISOCode3 = "PLN", TelephoneCountryCode = 48 },
new Country { Name = "Portugal", ISOCode2 = "PT", ISOCode3 = "PRT", TelephoneCountryCode = 351 },
new Country { Name = "Qatar", ISOCode2 = "QA", ISOCode3 = "QAT", TelephoneCountryCode = 974 },
new Country { Name = "Romania", ISOCode2 = "RO", ISOCode3 = "ROU", TelephoneCountryCode = 40 },
new Country { Name = "Russia", ISOCode2 = "RU", ISOCode3 = "RUS", TelephoneCountryCode = 7 },
new Country { Name = "Rwanda", ISOCode2 = "RW", ISOCode3 = "RWA", TelephoneCountryCode = 250 },
new Country { Name = "Saba", ISOCode2 = "BQ", ISOCode3 = null, TelephoneCountryCode = 5994 },
new Country { Name = "Sahrawi Republic", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = null },
new Country { Name = "Saint Helena", ISOCode2 = "SH", ISOCode3 = "SHN", TelephoneCountryCode = 290 },
new Country { Name = "Saint Kitts and Nevis", ISOCode2 = "KN", ISOCode3 = "KNA", TelephoneCountryCode = 1869 },
new Country { Name = "Saint Lucia", ISOCode2 = "LC", ISOCode3 = "LCA", TelephoneCountryCode = 1758 },
new Country { Name = "Saint Vincent and the Grenadines", ISOCode2 = "VC", ISOCode3 = "VCT", TelephoneCountryCode = 1784 },
new Country { Name = "Samoa", ISOCode2 = "WS", ISOCode3 = "WSM", TelephoneCountryCode = 685 },
new Country { Name = "San Marino", ISOCode2 = "SM", ISOCode3 = "SMR", TelephoneCountryCode = 378 },
new Country { Name = "São Tomé and Príncipe", ISOCode2 = "ST", ISOCode3 = "STP", TelephoneCountryCode = 239 },
new Country { Name = "Saudi Arabia", ISOCode2 = "SA", ISOCode3 = "SAU", TelephoneCountryCode = 966 },
new Country { Name = "Senegal", ISOCode2 = "SN", ISOCode3 = "SEN", TelephoneCountryCode = 221 },
new Country { Name = "Serbia", ISOCode2 = "RS", ISOCode3 = "SRB", TelephoneCountryCode = 381 },
new Country { Name = "Seychelles", ISOCode2 = "SC", ISOCode3 = "SYC", TelephoneCountryCode = 248 },
new Country { Name = "Sierra Leone", ISOCode2 = "SL", ISOCode3 = "SLE", TelephoneCountryCode = 232 },
new Country { Name = "Singapore", ISOCode2 = "SG", ISOCode3 = "SGP", TelephoneCountryCode = 65 },
new Country { Name = "Sint Eustatius", ISOCode2 = "BQ", ISOCode3 = "BES", TelephoneCountryCode = 5993 },
new Country { Name = "Sint Maarten", ISOCode2 = "SX", ISOCode3 = "SXM", TelephoneCountryCode = 1721 },
new Country { Name = "Slovakia", ISOCode2 = "SK", ISOCode3 = "SVK", TelephoneCountryCode = 421 },
new Country { Name = "Slovenia", ISOCode2 = "SI", ISOCode3 = "SVN", TelephoneCountryCode = 386 },
new Country { Name = "Solomon Islands", ISOCode2 = "SB", ISOCode3 = "SLB", TelephoneCountryCode = 677 },
new Country { Name = "Somalia", ISOCode2 = "SO", ISOCode3 = "SOM", TelephoneCountryCode = 252 },
new Country { Name = "Somaliland", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 252 },
new Country { Name = "South Africa", ISOCode2 = "ZA", ISOCode3 = "ZAF", TelephoneCountryCode = 27 },
new Country { Name = "South Georgia and the South Sandwich Islands", ISOCode2 = "GS", ISOCode3 = "SGS", TelephoneCountryCode = 500 },
new Country { Name = "South Ossetia", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 99534 },
new Country { Name = "Spain", ISOCode2 = "ES", ISOCode3 = "ESP", TelephoneCountryCode = 34 },
new Country { Name = "South Sudan", ISOCode2 = "SS", ISOCode3 = "SSD", TelephoneCountryCode = 211 },
new Country { Name = "Sri Lanka", ISOCode2 = "LK", ISOCode3 = "LKA", TelephoneCountryCode = 94 },
new Country { Name = "Sudan", ISOCode2 = "SD", ISOCode3 = "SDN", TelephoneCountryCode = 249 },
new Country { Name = "Suriname", ISOCode2 = "SR", ISOCode3 = "SUR", TelephoneCountryCode = 597 },
new Country { Name = "Swaziland", ISOCode2 = "SZ", ISOCode3 = "SWZ", TelephoneCountryCode = 268 },
new Country { Name = "Sweden", ISOCode2 = "SE", ISOCode3 = "SWE", TelephoneCountryCode = 46 },
new Country { Name = "Switzerland", ISOCode2 = "CH", ISOCode3 = "CHE", TelephoneCountryCode = 41 },
new Country { Name = "Syria", ISOCode2 = "SY", ISOCode3 = "SYR", TelephoneCountryCode = 963 },
new Country { Name = "Taiwan", ISOCode2 = "TW", ISOCode3 = "TWN", TelephoneCountryCode = 886 },
new Country { Name = "Tajikistan", ISOCode2 = "TJ", ISOCode3 = "TJK", TelephoneCountryCode = 992 },
new Country { Name = "Tanzania", ISOCode2 = "TZ", ISOCode3 = "TZA", TelephoneCountryCode = 255 },
new Country { Name = "Thailand", ISOCode2 = "TH", ISOCode3 = "THA", TelephoneCountryCode = 66 },
new Country { Name = "Togo", ISOCode2 = "TG", ISOCode3 = "TGO", TelephoneCountryCode = 228 },
new Country { Name = "Tonga", ISOCode2 = "TO", ISOCode3 = "TON", TelephoneCountryCode = 676 },
new Country { Name = "Transnistria", ISOCode2 = null, ISOCode3 = null, TelephoneCountryCode = 373 },
new Country { Name = "Trinidad and Tobago", ISOCode2 = "TT", ISOCode3 = "TTO", TelephoneCountryCode = 1868 },
new Country { Name = "Tristan da Cunha", ISOCode2 = "SH", ISOCode3 = "SHN", TelephoneCountryCode = 290 },
new Country { Name = "Tunisia", ISOCode2 = "TN", ISOCode3 = "TUN", TelephoneCountryCode = 216 },
new Country { Name = "Turkey", ISOCode2 = "TR", ISOCode3 = "TUR", TelephoneCountryCode = 90 },
new Country { Name = "Turkmenistan", ISOCode2 = "TM", ISOCode3 = "TKM", TelephoneCountryCode = 993 },
new Country { Name = "Turks and Caicos Islands", ISOCode2 = "TC", ISOCode3 = "TCA", TelephoneCountryCode = 1649 },
new Country { Name = "Tuvalu", ISOCode2 = "TV", ISOCode3 = "TUV", TelephoneCountryCode = 688 },
new Country { Name = "Uganda", ISOCode2 = "UG", ISOCode3 = "UGA", TelephoneCountryCode = 256 },
new Country { Name = "Ukraine", ISOCode2 = "UA", ISOCode3 = "UKR", TelephoneCountryCode = 380 },
new Country { Name = "United Arab Emirates", ISOCode2 = "AE", ISOCode3 = "ARE", TelephoneCountryCode = 971 },
new Country { Name = "United Kingdom", ISOCode2 = "GB", ISOCode3 = "GBR", TelephoneCountryCode = 44 },
new Country { Name = "United States", ISOCode2 = "US", ISOCode3 = "USA", TelephoneCountryCode = 1 },
new Country { Name = "Uruguay", ISOCode2 = "UY", ISOCode3 = "URY", TelephoneCountryCode = 598 },
new Country { Name = "Uzbekistan", ISOCode2 = "UZ", ISOCode3 = "UZB", TelephoneCountryCode = 998 },
new Country { Name = "Vanuatu", ISOCode2 = "VU", ISOCode3 = "VUT", TelephoneCountryCode = 678 },
new Country { Name = "Vatican City", ISOCode2 = "VA", ISOCode3 = "VAT", TelephoneCountryCode = 379 },
new Country { Name = "Venezuela", ISOCode2 = "VE", ISOCode3 = "VEN", TelephoneCountryCode = 58 },
new Country { Name = "Vietnam", ISOCode2 = "VN", ISOCode3 = "VNM", TelephoneCountryCode = 84 },
new Country { Name = "Wallis and Futuna", ISOCode2 = "WF", ISOCode3 = "WLF", TelephoneCountryCode = 681 },
new Country { Name = "Yemen", ISOCode2 = "YE", ISOCode3 = "YEM", TelephoneCountryCode = 967 },
new Country { Name = "Zambia", ISOCode2 = "ZM", ISOCode3 = "ZMB", TelephoneCountryCode = 260 },
new Country { Name = "Zimbabwe", ISOCode2 = "ZW", ISOCode3 = "ZWE", TelephoneCountryCode = 263 }
};
countries.ForEach(c => context.Countries.Add(c));
context.SaveChanges();
}
private static void AddPaymentMethods(ApplicationDbContext context)
{
var paymentMethods = new List<PaymentMethod>
{
new PaymentMethod { Name = "Cash" },
new PaymentMethod { Name = "Credit card" },
new PaymentMethod { Name = "Debit card" },
new PaymentMethod { Name = "Cheque" },
new PaymentMethod { Name = "Money transfer" },
new PaymentMethod { Name = "Mobile payment" }
};
paymentMethods.ForEach(pm => context.PaymentMethods.Add(pm));
context.SaveChanges();
}
private static void AddTransactionTypes(ApplicationDbContext context)
{
var transactionTypes = new List<TransactionType>
{
new TransactionType { Name = "Transportation" },
new TransactionType { Name = "Bank" },
new TransactionType { Name = "Insurance" },
new TransactionType { Name = "Living" },
new TransactionType { Name = "Household" },
new TransactionType { Name = "Travel & Leisure" },
new TransactionType { Name = "Salary" },
new TransactionType { Name = "Groceries" },
new TransactionType { Name = "Gift" },
new TransactionType { Name = "Savings" },
new TransactionType { Name = "Other" }
};
transactionTypes.ForEach(tt => context.TransactionTypes.Add(tt));
context.SaveChanges();
}
private static void AddUsers(ApplicationDbContext context)
{
var user = new User
{
UserName = "username",
Gender = Domains.Artificial.Gender.Male,
FirstName = "First name",
MiddleName = "Middle name",
LastName = "Last name",
AddressLine1 = "Address line 1",
AddressLine2 = "Address Line 2",
City = "City",
Zip = "Zip",
District = "District",
MobileNumber = "Mobile number",
CountryID = context.Countries.First(x => x.Name == "Slovakia").ID
};
var userStore = new CustomUserStore(context);
var userManager = new Microsoft.AspNet.Identity.UserManager<User, int>(userStore);
var result = userManager.CreateAsync(user, "Heslo1<>").Result;
}
private static void AddProjects(ApplicationDbContext context)
{
var creatorID = context.Users.First(x => x.UserName == "username").Id;
var projects = new List<Project>
{
new Project
{
Name = "Test project 1",
ValidFrom = DateTime.Now.AddMonths(-1).Date,
ValidTill = DateTime.Now.AddMonths(1).Date,
Budget = 3500,
TargetValue = null,
ActualValue = 3500,
SequenceNumber = 3,
CreatorID = creatorID
},
new Project
{
Name = "Test project 2",
ValidFrom = DateTime.Now.AddMonths(-2).Date,
ValidTill = null,
Budget = null,
TargetValue = 1000,
ActualValue = 100,
SequenceNumber = 1,
CreatorID = creatorID
},
new Project
{
Name = "Test project 3",
ValidFrom = null,
ValidTill = DateTime.Now.AddMonths(2).Date,
Budget = null,
TargetValue = 1000,
ActualValue = 750,
SequenceNumber = 4,
CreatorID = creatorID
},
new Project
{
Name = "Test project 4",
ValidFrom = null,
ValidTill = DateTime.Now.AddDays(-10).Date,
Budget = 10000,
TargetValue = null,
ActualValue = 5000,
SequenceNumber = 5,
CreatorID = creatorID
},
new Project
{
Name = "Test project 5",
ValidFrom = null,
ValidTill = null,
Budget = null,
TargetValue = null,
ActualValue = 0,
SequenceNumber = 2,
CreatorID = creatorID
}
};
projects.ForEach(p => context.Projects.Add(p));
context.SaveChanges();
}
private static void AddTransactions(ApplicationDbContext context)
{
var creatorID = context.Users.First(x => x.UserName == "username").Id;
var projectID = context.Projects.First(x => x.Name == "Test project 1").ProjectID;
var transactions = new List<Transaction>
{
new Transaction
{
Date = DateTime.Now.AddDays(-7).Date,
Amount = 15.49M,
Note = "Test transaction 1 for project 1",
Income = false,
ProjectID = projectID,
CreatorID = creatorID,
TransactionTypeID = context.TransactionTypes.First(x => x.Name == "Transportation").TransactionTypeID,
PaymentMethodID = context.PaymentMethods.First(x => x.Name == "Cash").PaymentMethodID
},
new Transaction
{
Date = DateTime.Now.AddDays(-6).Date,
Amount = 5000M,
Note = "Test transaction 2 for project 1",
Income = true,
ProjectID = projectID,
CreatorID = creatorID,
TransactionTypeID = context.TransactionTypes.First(x => x.Name == "Salary").TransactionTypeID,
PaymentMethodID = context.PaymentMethods.First(x => x.Name == "Money transfer").PaymentMethodID
},
new Transaction
{
Date = DateTime.Now.AddDays(-5).Date,
Amount = 142M,
Note = "Test transaction 1 without project",
Income = false,
ProjectID = null,
CreatorID = creatorID,
TransactionTypeID = context.TransactionTypes.First(x => x.Name == "Gift").TransactionTypeID,
PaymentMethodID = context.PaymentMethods.First(x => x.Name == "Credit card").PaymentMethodID
},
new Transaction
{
Date = DateTime.Now.AddDays(-5).Date,
Amount = 5M,
Note = "Test transaction 2 without project",
Income = false,
ProjectID = null,
CreatorID = creatorID,
TransactionTypeID = context.TransactionTypes.First(x => x.Name == "Transportation").TransactionTypeID,
PaymentMethodID = context.PaymentMethods.First(x => x.Name == "Mobile payment").PaymentMethodID
}
};
transactions.ForEach(t => context.Transactions.Add(t));
context.SaveChanges();
}
private static void AddCurrency(ApplicationDbContext context)
{
var currencies = new List<Currency>
{
new Currency { Name = "Abkhazian apsar", ISOCode = null, Sign = null },
new Currency { Name = "Russian ruble", ISOCode = "RUB", Sign = "руб.", FractionalUnit = "Kopek", FractionalUnitAmount = 100 },
new Currency { Name = "Afghan afghani", ISOCode = "AFN", Sign = "؋", FractionalUnit = "Pul", FractionalUnitAmount = 100 },
new Currency { Name = "Euro", ISOCode = "EUR", Sign = "€", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Albanian lek", ISOCode = "ALL", Sign = "L", FractionalUnit = "Qindarkë", FractionalUnitAmount = 100 },
new Currency { Name = "Alderney pound", ISOCode = null, Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "British pound", ISOCode = "GBP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Guernsey pound", ISOCode = "GGP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Algerian dinar", ISOCode = "DZD", Sign = "د.ج", FractionalUnit = "Santeem", FractionalUnitAmount = 100 },
new Currency { Name = "Angolan kwanza", ISOCode = "AOA", Sign = "Kz", FractionalUnit = "Cêntimo", FractionalUnitAmount = 100 },
new Currency { Name = "East Caribbean dollar", ISOCode = "XCD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Argentine peso", ISOCode = "ARS", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Armenian dram", ISOCode = "AMD", Sign = "դր.", FractionalUnit = "Luma", FractionalUnitAmount = 100 },
new Currency { Name = "Aruban florin", ISOCode = "AWG", Sign = "ƒ", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Ascension pound", ISOCode = null, Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Saint Helena pound", ISOCode = "SHP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Australian dollar", ISOCode = "AUD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Azerbaijani manat", ISOCode = "AZN", Sign = "₼", FractionalUnit = "Qəpik", FractionalUnitAmount = 100 },
new Currency { Name = "Bahamian dollar", ISOCode = "BSD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Bahraini dinar", ISOCode = "BHD", Sign = ".د.ب", FractionalUnit = "Fils", FractionalUnitAmount = 1000 },
new Currency { Name = "Bangladeshi taka", ISOCode = "BDT", Sign = "৳", FractionalUnit = "Paisa", FractionalUnitAmount = 100 },
new Currency { Name = "Barbadian dollar", ISOCode = "BBD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Belarusian ruble", ISOCode = "BYR", Sign = "Br", FractionalUnit = "Kapyeyka", FractionalUnitAmount = 100 },
new Currency { Name = "Belize dollar", ISOCode = "BZD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "West African CFA franc", ISOCode = "XOF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Bermudian dollar", ISOCode = "BMD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Bhutanese ngultrum", ISOCode = "BTN", Sign = "Nu.", FractionalUnit = "Chetrum", FractionalUnitAmount = 100 },
new Currency { Name = "Indian rupee", ISOCode = "INR", Sign = "₹", FractionalUnit = "Paisa", FractionalUnitAmount = 100 },
new Currency { Name = "Bolivian boliviano", ISOCode = "BOB", Sign = "Bs.", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Bosnia and Herzegovina convertible mark", ISOCode = "BAM", Sign = "КМ", FractionalUnit = "Fening", FractionalUnitAmount = 100 },
new Currency { Name = "Botswana pula", ISOCode = "BWP", Sign = "P", FractionalUnit = "Thebe", FractionalUnitAmount = 100 },
new Currency { Name = "Brazilian real", ISOCode = "BRL", Sign = "R$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "British Virgin Islands dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Brunei dollar", ISOCode = "BND", Sign = "$", FractionalUnit = "Sen", FractionalUnitAmount = 100 },
new Currency { Name = "Singapore dollar", ISOCode = "SGD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Bulgarian lev", ISOCode = "BGN", Sign = "лв", FractionalUnit = "Stotinka", FractionalUnitAmount = 100 },
new Currency { Name = "Burmese kyat", ISOCode = "MMK", Sign = "Ks", FractionalUnit = "Pya", FractionalUnitAmount = 100 },
new Currency { Name = "Burundian franc", ISOCode = "BIF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Cambodian riel", ISOCode = "KHR", Sign = "៛", FractionalUnit = "Sen", FractionalUnitAmount = 100 },
new Currency { Name = "Canadian dollar", ISOCode = "CAD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Cape Verdean escudo", ISOCode = "CVE", Sign = "Esc", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Cayman Islands dollar", ISOCode = "KYD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Central African CFA franc", ISOCode = "XAF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Chilean peso", ISOCode = "CLP", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Chinese yuan", ISOCode = "CNY", Sign = "元", FractionalUnit = "Fen", FractionalUnitAmount = 100 },
new Currency { Name = "Colombian peso", ISOCode = "COP", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Comorian franc", ISOCode = "KMF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Congolese franc", ISOCode = "CDF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "New Zealand dollar", ISOCode = "NZD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Cook Islands dollar", ISOCode = "CKD", Sign = "'$',", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Costa Rican colón", ISOCode = "CRC", Sign = "₡", FractionalUnit = "Céntimo", FractionalUnitAmount = 100 },
new Currency { Name = "Croatian kuna", ISOCode = "HRK", Sign = "kn", FractionalUnit = "Lipa", FractionalUnitAmount = 100 },
new Currency { Name = "Cuban convertible peso", ISOCode = "CUC", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Cuban peso", ISOCode = "CUP", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Netherlands Antillean guilder", ISOCode = "ANG", Sign = "ƒ", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Czech koruna", ISOCode = "CZK", Sign = "Kč", FractionalUnit = "Haléř", FractionalUnitAmount = 100 },
new Currency { Name = "Danish krone", ISOCode = "DKK", Sign = "kr", FractionalUnit = "Øre", FractionalUnitAmount = 100 },
new Currency { Name = "Djiboutian franc", ISOCode = "DJF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Dominican peso", ISOCode = "DOP", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "United States dollar", ISOCode = "USD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Egyptian pound", ISOCode = "EGP", Sign = "ج.م", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "Eritrean nakfa", ISOCode = "ERN", Sign = "Nfk", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Ethiopian birr", ISOCode = "ETB", Sign = "Br", FractionalUnit = "Santim", FractionalUnitAmount = 100 },
new Currency { Name = "Falkland Islands pound", ISOCode = "FKP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Faroese króna", ISOCode = "FOK", Sign = "kr", FractionalUnit = "Oyra", FractionalUnitAmount = 100 },
new Currency { Name = "Fijian dollar", ISOCode = "FJD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "CFP franc", ISOCode = "XPF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Gambian dalasi", ISOCode = "GMD", Sign = "D", FractionalUnit = "Butut", FractionalUnitAmount = 100 },
new Currency { Name = "Georgian lari", ISOCode = "GEL", Sign = "ლ", FractionalUnit = "Tetri", FractionalUnitAmount = 100 },
new Currency { Name = "Ghana cedi", ISOCode = "GHS", Sign = "₵", FractionalUnit = "Pesewa", FractionalUnitAmount = 100 },
new Currency { Name = "Gibraltar pound", ISOCode = "GIP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Guatemalan quetzal", ISOCode = "GTQ", Sign = "Q", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Guinean franc", ISOCode = "GNF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Guyanese dollar", ISOCode = "GYD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Haitian gourde", ISOCode = "HTG", Sign = "G", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Honduran lempira", ISOCode = "HNL", Sign = "L", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Hong Kong dollar", ISOCode = "HKD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Hungarian forint", ISOCode = "HUF", Sign = "Ft", FractionalUnit = "Fillér", FractionalUnitAmount = 100 },
new Currency { Name = "Icelandic króna", ISOCode = "ISK", Sign = "kr", FractionalUnit = "Eyrir", FractionalUnitAmount = 100 },
new Currency { Name = "Indonesian rupiah", ISOCode = "IDR", Sign = "Rp", FractionalUnit = "Sen", FractionalUnitAmount = 100 },
new Currency { Name = "Iranian rial", ISOCode = "IRR", Sign = "﷼", FractionalUnit = "Dinar", FractionalUnitAmount = 100 },
new Currency { Name = "Iraqi dinar", ISOCode = "IQD", Sign = "ع.د", FractionalUnit = "Fils", FractionalUnitAmount = 1000 },
new Currency { Name = "Manx pound", ISOCode = "IMP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Israeli new shekel", ISOCode = "ILS", Sign = "₪", FractionalUnit = "Agora", FractionalUnitAmount = 100 },
new Currency { Name = "Jamaican dollar", ISOCode = "JMD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Japanese yen", ISOCode = "JPY", Sign = "¥", FractionalUnit = "Sen", FractionalUnitAmount = 100 },
new Currency { Name = "Jersey pound", ISOCode = "JEP", Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Jordanian dinar", ISOCode = "JOD", Sign = "د.ا", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "Kazakhstani tenge", ISOCode = "KZT", Sign = "₸", FractionalUnit = "Tïın", FractionalUnitAmount = 100 },
new Currency { Name = "Kenyan shilling", ISOCode = "KES", Sign = "Sh", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Kiribati dollar", ISOCode = "KID", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "North Korean won", ISOCode = "KPW", Sign = "₩", FractionalUnit = "Chon", FractionalUnitAmount = 100 },
new Currency { Name = "South Korean won", ISOCode = "KRW", Sign = "₩", FractionalUnit = "Jeon", FractionalUnitAmount = 100 },
new Currency { Name = "Kuwaiti dinar", ISOCode = "KWD", Sign = "د.ك", FractionalUnit = "Fils", FractionalUnitAmount = 1000 },
new Currency { Name = "Kyrgyzstani som", ISOCode = "KGS", Sign = "лв", FractionalUnit = "Tyiyn", FractionalUnitAmount = 100 },
new Currency { Name = "Lao kip", ISOCode = "LAK", Sign = "₭", FractionalUnit = "Att", FractionalUnitAmount = 100 },
new Currency { Name = "Lebanese pound", ISOCode = "LBP", Sign = "ل.ل", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "Lesotho loti", ISOCode = "LSL", Sign = "L", FractionalUnit = "Sente", FractionalUnitAmount = 100 },
new Currency { Name = "South African rand", ISOCode = "ZAR", Sign = "R", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Liberian dollar", ISOCode = "LRD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Libyan dinar", ISOCode = "LYD", Sign = "ل.د", FractionalUnit = "Dirham", FractionalUnitAmount = 1000 },
new Currency { Name = "Swiss franc", ISOCode = "CHF", Sign = "Fr", FractionalUnit = "Rappen", FractionalUnitAmount = 100 },
new Currency { Name = "Lithuanian litas", ISOCode = "LTL", Sign = "Lt", FractionalUnit = "Centas", FractionalUnitAmount = 100 },
new Currency { Name = "Macanese pataca", ISOCode = "MOP", Sign = "P", FractionalUnit = "Avo", FractionalUnitAmount = 100 },
new Currency { Name = "Macedonian denar", ISOCode = "MKD", Sign = "ден", FractionalUnit = "Deni", FractionalUnitAmount = 100 },
new Currency { Name = "Malagasy ariary", ISOCode = "MGA", Sign = "Ar", FractionalUnit = "Iraimbilanja", FractionalUnitAmount = 5 },
new Currency { Name = "Malawian kwacha", ISOCode = "MWK", Sign = "MK", FractionalUnit = "Tambala", FractionalUnitAmount = 100 },
new Currency { Name = "Malaysian ringgit", ISOCode = "MYR", Sign = "RM", FractionalUnit = "Sen", FractionalUnitAmount = 100 },
new Currency { Name = "Maldivian rufiyaa", ISOCode = "MVR", Sign = "ރ", FractionalUnit = "Laari", FractionalUnitAmount = 100 },
new Currency { Name = "Mauritanian ouguiya", ISOCode = "MRO", Sign = "UM", FractionalUnit = "Khoums", FractionalUnitAmount = 5 },
new Currency { Name = "Mauritian rupee", ISOCode = "MUR", Sign = "₨", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Mexican peso", ISOCode = "MXN", Sign = "$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Micronesian dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Moldovan leu", ISOCode = "MDL", Sign = "L", FractionalUnit = "Ban", FractionalUnitAmount = 100 },
new Currency { Name = "Mongolian tögrög", ISOCode = "MNT", Sign = "₮", FractionalUnit = "Möngö", FractionalUnitAmount = 100 },
new Currency { Name = "Moroccan dirham", ISOCode = "MAD", Sign = "د.م.", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Mozambican metical", ISOCode = "MZN", Sign = "MT", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Nagorno-Karabakh dram", ISOCode = null, Sign = "դր.", FractionalUnit = "Luma", FractionalUnitAmount = 100 },
new Currency { Name = "Namibian dollar", ISOCode = "NAD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Nauruan dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Nepalese rupee", ISOCode = "NPR", Sign = "₨", FractionalUnit = "Paisa", FractionalUnitAmount = 100 },
new Currency { Name = "Nicaraguan córdoba", ISOCode = "NIO", Sign = "C$", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Nigerian naira", ISOCode = "NGN", Sign = "₦", FractionalUnit = "Kobo", FractionalUnitAmount = 100 },
new Currency { Name = "Niue dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Turkish lira", ISOCode = "TRY", Sign = "₺", FractionalUnit = "Kuruş", FractionalUnitAmount = 100 },
new Currency { Name = "Norwegian krone", ISOCode = "NOK", Sign = "kr", FractionalUnit = "Øre", FractionalUnitAmount = 100 },
new Currency { Name = "Omani rial", ISOCode = "OMR", Sign = "ر.ع.", FractionalUnit = "Baisa", FractionalUnitAmount = 1000 },
new Currency { Name = "Pakistani rupee", ISOCode = "PKR", Sign = "₨", FractionalUnit = "Paisa", FractionalUnitAmount = 100 },
new Currency { Name = "Palauan dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Panamanian balboa", ISOCode = "PAB", Sign = "B/.", FractionalUnit = "Centésimo", FractionalUnitAmount = 100 },
new Currency { Name = "Papua New Guinean kina", ISOCode = "PGK", Sign = "K", FractionalUnit = "Toea", FractionalUnitAmount = 100 },
new Currency { Name = "Paraguayan guaraní", ISOCode = "PYG", Sign = "₲", FractionalUnit = "Céntimo", FractionalUnitAmount = 100 },
new Currency { Name = "Peruvian nuevo sol", ISOCode = "PEN", Sign = "S/.", FractionalUnit = "Céntimo", FractionalUnitAmount = 100 },
new Currency { Name = "Philippine peso", ISOCode = "PHP", Sign = "₱", FractionalUnit = "Centavo", FractionalUnitAmount = 100 },
new Currency { Name = "Pitcairn Islands dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Polish złoty", ISOCode = "PLN", Sign = "zł", FractionalUnit = "Grosz", FractionalUnitAmount = 100 },
new Currency { Name = "Qatari riyal", ISOCode = "QAR", Sign = "ر.ق", FractionalUnit = "Dirham", FractionalUnitAmount = 100 },
new Currency { Name = "Romanian leu", ISOCode = "RON", Sign = "lei", FractionalUnit = "Ban", FractionalUnitAmount = 100 },
new Currency { Name = "Rwandan franc", ISOCode = "RWF", Sign = "Fr", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Sahrawi peseta", ISOCode = "EHP", Sign = "Ptas", FractionalUnit = "Centime", FractionalUnitAmount = 100 },
new Currency { Name = "Samoan tālā", ISOCode = "WST", Sign = "T", FractionalUnit = "Sene", FractionalUnitAmount = 100 },
new Currency { Name = "São Tomé and Príncipe dobra", ISOCode = "STD", Sign = "Db", FractionalUnit = "Cêntimo", FractionalUnitAmount = 100 },
new Currency { Name = "Saudi riyal", ISOCode = "SAR", Sign = "ر.س", FractionalUnit = "Halala", FractionalUnitAmount = 100 },
new Currency { Name = "Serbian dinar", ISOCode = "RSD", Sign = "дин.", FractionalUnit = "Para", FractionalUnitAmount = 100 },
new Currency { Name = "Seychellois rupee", ISOCode = "SCR", Sign = "₨", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Sierra Leonean leone", ISOCode = "SLL", Sign = "Le", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Solomon Islands dollar", ISOCode = "SBD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Somali shilling", ISOCode = "SOS", Sign = "Sh", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Somaliland shilling", ISOCode = "SLS", Sign = "Sh", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "South Georgia and the South Sandwich Islands pound", ISOCode = null, Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "South Sudanese pound", ISOCode = "SSP", Sign = "£", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "Sri Lankan rupee", ISOCode = "LKR", Sign = "රු", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Sudanese pound", ISOCode = "SDG", Sign = "£", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "Surinamese dollar", ISOCode = "SRD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Swazi lilangeni", ISOCode = "SZL", Sign = "L", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Swedish krona", ISOCode = "SEK", Sign = "kr", FractionalUnit = "Öre", FractionalUnitAmount = 100 },
new Currency { Name = "Syrian pound", ISOCode = "SYP", Sign = "ل.س", FractionalUnit = "Piastre", FractionalUnitAmount = 100 },
new Currency { Name = "New Taiwan dollar", ISOCode = "TWD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Tajikistani somoni", ISOCode = "TJS", Sign = "ЅМ", FractionalUnit = "Diram", FractionalUnitAmount = 100 },
new Currency { Name = "Tanzanian shilling", ISOCode = "TZS", Sign = "Sh", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Thai baht", ISOCode = "THB", Sign = "฿", FractionalUnit = "Satang", FractionalUnitAmount = 100 },
new Currency { Name = "Tongan paʻanga", ISOCode = "TOP", Sign = "T$", FractionalUnit = "Seniti", FractionalUnitAmount = 100 },
new Currency { Name = "Transnistrian ruble", ISOCode = "PRB", Sign = "р.", FractionalUnit = "Kopek", FractionalUnitAmount = 100 },
new Currency { Name = "Trinidad and Tobago dollar", ISOCode = "TTD", Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Tristan da Cunha pound", ISOCode = null, Sign = "£", FractionalUnit = "Penny", FractionalUnitAmount = 100 },
new Currency { Name = "Tunisian dinar", ISOCode = "TND", Sign = "د.ت", FractionalUnit = "Millime", FractionalUnitAmount = 1000 },
new Currency { Name = "Turkmenistan manat", ISOCode = "TMT", Sign = "m", FractionalUnit = "Tennesi", FractionalUnitAmount = 100 },
new Currency { Name = "Tuvaluan dollar", ISOCode = null, Sign = "$", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Ugandan shilling", ISOCode = "UGX", Sign = "Sh", FractionalUnit = "Cent", FractionalUnitAmount = 100 },
new Currency { Name = "Ukrainian hryvnia", ISOCode = "UAH", Sign = "₴", FractionalUnit = "Kopiyka", FractionalUnitAmount = 100 },
new Currency { Name = "United Arab Emirates dirham", ISOCode = "AED", Sign = "د.إ", FractionalUnit = "Fils", FractionalUnitAmount = 100 },
new Currency { Name = "Uruguayan peso", ISOCode = "UYU", Sign = "$", FractionalUnit = "Centésimo", FractionalUnitAmount = 100 },
new Currency { Name = "Uzbekistani som", ISOCode = "UZS", Sign = "лв", FractionalUnit = "Tiyin", FractionalUnitAmount = 100 },
new Currency { Name = "Vanuatu vatu", ISOCode = "VUV", Sign = "Vt", FractionalUnit = null, FractionalUnitAmount = null },
new Currency { Name = "Venezuelan bolívar", ISOCode = "VEF", Sign = "Bs", FractionalUnit = "Céntimo", FractionalUnitAmount = 100 },
new Currency { Name = "Vietnamese đồng", ISOCode = "VND", Sign = "₫", FractionalUnit = "Hào", FractionalUnitAmount = 10 },
new Currency { Name = "Yemeni rial", ISOCode = "YER", Sign = "﷼", FractionalUnit = "Fils", FractionalUnitAmount = 100 },
new Currency { Name = "Zambian kwacha", ISOCode = "ZMK", Sign = "ZK", FractionalUnit = "Ngwee", FractionalUnitAmount = 100 }
};
currencies.ForEach(c => context.Currencies.Add(c));
context.SaveChanges();
}
#endregion
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using Apergies.Model;
using HtmlAgilityPack;
using System.Xml.Linq;
using System.Threading;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Threading;
namespace Apergies
{
public class AllStrikesLoader
{
WebClient webc;
DataCache cache;
private List<StrikeRecord> strikeList;
public NotifyDataList dataNotifier;
public NotifyAttn attnNotifier;
public AllStrikesLoader()
{
//Constructor
webc = new WebClient();
webc.OpenReadCompleted += new OpenReadCompletedEventHandler(webc_OpenReadCompleted);
this.strikeList = new List<StrikeRecord>();
}
public void LoadStrikes(string url)
{
cache = new DataCache(GetSHA1(url));
webc.OpenReadAsync(new Uri(url));
}
public List<StrikeRecord> GetStrikes()
{
return strikeList;
}
void webc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
XDocument doc = XDocument.Load(e.Result);
var items = from item in doc.Descendants("item")
select new
{
Title = item.Element("title").Value,
Link = item.Element("link").Value,
};
foreach (var item in items)
{
this.strikeList.Add(new StrikeRecord(item.Title, item.Link));
cache.Marshall(this.strikeList);
}
}
catch (Exception ex)
{
MessageBox.Show("Παρουσιάστηκε σφάλμα κατα την ανάκτηση των δεδομένων");
this.strikeList = cache.Unmarshall();
}
}
else
{
attnNotifier();
this.strikeList = cache.Unmarshall();
}
dataNotifier();
}
private static String GetSHA1(String text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LojaWeb.Models
{
public class ItemCarrinho
{
public int IdCarrinho { get; set; }
public int IdProduto { get; set; }
public double Preco { get; set; }
public int Quantidade { get; set; }
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IImporterModel.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using ClosedXML.Excel;
using NHibernate;
namespace CGI.Reflex.Core.Importers.Models
{
public interface IImporterModel
{
void Prepare(IXLWorksheet ws, string title = null);
IImporterModel ToRow(IXLRow row);
IImporterModel FromRow(IXLRow row);
IImporterModel ToEntity(ISession session, object entity);
IImporterModel FromEntity(object entity);
IEnumerable<ValidationResult> Validate();
}
}
|
namespace TreeStore.Messaging
{
public interface IRelationship : IIdentifiable
{
IEntity From { get; }
IEntity To { get; }
}
} |
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 EmployeesDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DatabaseConnection objConnect;
string conString;
DataSet ds;
DataRow dRow;
int MaxRows;
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
{
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.EmployeesConnectionString;
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.GetConnection;
MaxRows = ds.Tables[0].Rows.Count;
NavigateRecords();
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
}
private void NavigateRecords()
{
dRow = ds.Tables[0].Rows[inc];
textBox1.Text = dRow.ItemArray.GetValue(1).ToString();
textBox2.Text = dRow.ItemArray.GetValue(2).ToString();
textBox3.Text = dRow.ItemArray.GetValue(3).ToString();
textBox4.Text = dRow.ItemArray.GetValue(4).ToString();
}
private void button1_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("No More Rows");
}
}
private void button2_Click(object sender, EventArgs e)
{
if(inc > 0)
{
inc--;
NavigateRecords();
}
else
{
MessageBox.Show("First Record");
}
}
private void button3_Click(object sender, EventArgs e)
{
if(inc != 0)
{
inc = 0;
NavigateRecords();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (inc != MaxRows)
{
inc = MaxRows;
NavigateRecords();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using MeterReading.Logic.Validators;
using MeterReadings.Repository;
using MeterReadings.Schema;
namespace MeterReading.Logic.Facades
{
public class MeterReadingFacade : IMeterReadingFacade
{
public MeterReadingFacade(
IMeterReadingsRepository meterReadingsRepository,
IMeterReadingLenientValidator meterReadingLenientValidator,
ICsvHelper csvHelper)
{
_meterReadingsRepository = meterReadingsRepository ??
throw new ArgumentNullException(nameof(meterReadingsRepository));
_meterReadingLenientValidator = meterReadingLenientValidator ??
throw new ArgumentNullException(nameof(meterReadingLenientValidator));
_csvHelper = csvHelper ??
throw new ArgumentNullException(nameof(csvHelper));
}
private readonly IMeterReadingsRepository _meterReadingsRepository;
private readonly IMeterReadingLenientValidator _meterReadingLenientValidator;
private readonly ICsvHelper _csvHelper;
public async Task<AddMeterStatusResponse> AddMeterReadings(Collection<HttpContent> contents)
{
// read csv
var readings = await _csvHelper.ReadCsvFromRequestIntoCollectionOfType<MeterReadingLenient>(contents);
var enumeratedMeterReadings = readings.ToList();
// run validator
foreach (var reading in enumeratedMeterReadings)
{
var errors = string.Join(", ", _meterReadingLenientValidator.Validate(reading).Errors.Select(error => error.ErrorMessage));
reading.Errors = !string.IsNullOrWhiteSpace(errors) ? errors : null;
}
// map to internal schema
var readingsToAdd = new List<MeterReadings.Schema.MeterReading>();
readingsToAdd.AddRange(enumeratedMeterReadings
.Where(reading => string.IsNullOrWhiteSpace(reading.Errors))
.Select(reading => reading.ToMeterReading()));
// call repo with readings that satisfy data contract validation
var successfullyAddedReadings = await _meterReadingsRepository.AddReadings(readingsToAdd);
var failuresDueToDataContractValidation = enumeratedMeterReadings.Where(reading => !string.IsNullOrWhiteSpace(reading.Errors));
var numberOfSuccessfullyAddedReading = successfullyAddedReadings.Count();
var errorMessages = new List<string>();
errorMessages.AddRange(failuresDueToDataContractValidation.Select(reading => $"{reading} - {reading.Errors}"));
var readingsRejectedByTheDatabase = readingsToAdd
.Where(readingToAdd => successfullyAddedReadings
.All(
addedReading =>
!(readingToAdd.AccountId == addedReading.AccountId &&
readingToAdd.MeterReadingDateTime == addedReading.MeterReadingDateTime &&
readingToAdd.MeterReadValue == addedReading.MeterReadValue)
));
errorMessages.AddRange(readingsRejectedByTheDatabase.Select(failedToAddReading => $"{failedToAddReading} - AccountId doesn't exist or reading has already been added"));
return new AddMeterStatusResponse()
{
SuccessfulCount = numberOfSuccessfullyAddedReading,
FailedCount = enumeratedMeterReadings.Count - numberOfSuccessfullyAddedReading,
Errors = errorMessages
};
}
public async Task<Guid?> AddMeterReading(MeterReadings.Schema.MeterReading meterReading)
{
var successfullyAddedReadings = await _meterReadingsRepository.AddReadings(new[] { meterReading });
return successfullyAddedReadings.FirstOrDefault()?.Id;
}
public Task<IEnumerable<MeterReadings.Schema.MeterReading>> GetReadings() => _meterReadingsRepository.GetReadings();
public Task DeleteReading(Guid id) => _meterReadingsRepository.DeleteReading(id);
public Task<MeterReadings.Schema.MeterReading> GetReading(Guid id) => _meterReadingsRepository.GetReading(id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Payroll.Business;
using Payroll.Common;
using Payroll.Models;
namespace Payroll.Controllers
{
public class EmployeesController : GenericController<Employee>
{
public EmployeesController(BusinessObject<Employee> businessObject, Message message)
: base(businessObject, message) { }
public override Task<IActionResult> Index(int page = 1, string filter = "", string sort = "", string order = "ASC")
{
var companies = _businessObject
.GetDAO()
.Context
.Company
.Where(a => !a.IsDeleted);
ViewBag.Companies = Utils
.GetOptions(companies);
ViewBag.Occupations = Utils
.GetOptions(_businessObject
.GetDAO()
.Context
.Occupation
.Where(a => !a.IsDeleted));
ViewBag.Genders = Utils.GetGenders();
ViewBag.DepartmentsByCompany = companies.AsEnumerable()
.Select(a => new
{
Key = a.Id,
Value = _businessObject
.GetDAO()
.Context
.Department
.Where(b => !b.IsDeleted)
.Where(c => c.CompanyId == a.Id)
.ToList()
})
.ToDictionary(t => t.Key, t => t.Value);
ViewBag.WorkplacesByCompany = companies.AsEnumerable()
.Select(a => new
{
Key = a.Id,
Value = _businessObject
.GetDAO()
.Context
.Workplace
.Where(b => !b.IsDeleted)
.Where(c => c.CompanyId == a.Id)
.ToList()
})
.ToDictionary(t => t.Key, t => t.Value);
ViewBag.JobRolesByCompany = companies.AsEnumerable()
.Select(a => new
{
Key = a.Id,
Value = _businessObject
.GetDAO()
.Context
.JobRole
.Where(b => !b.IsDeleted)
.Where(c => c.CompanyId == a.Id)
.ToList()
})
.ToDictionary(t => t.Key, t => t.Value);
ViewBag.FunctionsByCompany = companies.AsEnumerable()
.Select(a => new
{
Key = a.Id,
Value = _businessObject
.GetDAO()
.Context
.Function
.Where(b => !b.IsDeleted)
.Where(c => c.CompanyId == a.Id)
.ToList()
})
.ToDictionary(t => t.Key, t => t.Value);
ViewBag.ManagersByCompany = companies.AsEnumerable()
.Select(a => new
{
Key = a.Id,
Value = _businessObject
.GetDAO()
.Context
.Employee
.Include(b => b.Function)
.Where(b => !b.IsDeleted)
.Where(c => c.CompanyId == a.Id)
.Where(b => b.Function.IsManagerFunction)
.ToList()
})
.ToDictionary(t => t.Key, t => t.Value);
return base.Index(page, filter, sort, order);
}
public override async Task<IActionResult> Create(Employee data)
{
HandleItems(data);
return await base.Create(data);
}
public override async Task<IActionResult> Edit(Guid id, Employee data)
{
HandleItems(data);
return await base.Edit(id, data);
}
public IActionResult EmployeesByDepartment(string departmentId)
{
var employeesFromDB = _businessObject
.GetDAO()
.Context
.Employee
.Include(a => a.Department)
.Where(a => !a.IsDeleted)
.Where(a => a.DepartmentId.ToString() == departmentId)
.ToList();
employeesFromDB.ForEach(Utils.GetEmployeeOption);
var employees = Utils
.GetOptions(employeesFromDB);
return Ok(employees);
}
public IActionResult EmployeesByCompany(string companyId)
{
var employeesFromDB = _businessObject
.GetDAO()
.Context
.Employee
.Include(a => a.Company)
.Where(a => !a.IsDeleted)
.Where(a => a.CompanyId.ToString() == companyId)
.ToList();
employeesFromDB
.ForEach(Utils.GetEmployeeOption);
var employees = Utils
.GetOptions(employeesFromDB);
return Ok(employees);
}
public IActionResult ManagersByCompany(string companyId)
{
var employeesFromDB = _businessObject
.GetDAO()
.Context
.Employee
.Include(a => a.Function)
.Include(a => a.Company)
.Where(a => !a.IsDeleted)
.Where(a => a.CompanyId.ToString() == companyId)
.Where(a => a.Function.IsManagerFunction)
.ToList();
employeesFromDB
.ForEach(Utils.GetEmployeeOption);
var employees = Utils
.GetOptions(employeesFromDB);
return Ok(employees);
}
private void HandleItems(Employee data)
{
var itemsToAdd = new List<Certification>();
var names = HttpContext
.Request
.Form[Constants.CERTIFICATION_NAME];
var dates = HttpContext
.Request
.Form[Constants.CERTIFICATION_DATE];
for (int i = 0; i < names.Count; i++)
{
itemsToAdd.Add(new Certification
{
Name = names[i],
Date = DateTime.Parse(dates[i])
});
}
data.Certifications = itemsToAdd;
}
}
}
|
using System;
using System.Collections.Generic;
class OddNumber
{
static void Main()
{
long n = long.Parse(Console.ReadLine());
List<long> sequence = new List<long>();
for (int i = 0; i < n; i++)
{
sequence.Add(long.Parse(Console.ReadLine()));
}
sequence.Reverse();
List<long> checkedNumbers = new List<long>();
for (int i = 0; i < sequence.Count; i++)
{
int countOccurence = 0;
if (checkedNumbers.Contains(sequence[i]))
{
continue;
}
else
{
checkedNumbers.Add(sequence[i]);
}
foreach (long num in sequence)
{
if (num == sequence[i])
{
countOccurence++;
}
}
if (countOccurence % 2 != 0)
{
Console.WriteLine(sequence[i]);
break;
}
}
}
}
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using NetDaemon.Common.Exceptions;
namespace NetDaemon.Common.Fluent
{
/// <summary>
/// Base class for entity fluent types
/// </summary>
public class EntityBase //: EntityState
{
internal readonly ConcurrentQueue<FluentAction> _actions =
new();
internal FluentAction? _currentAction;
internal StateChangedInfo _currentState = new();
/// <summary>
/// The daemon used in the API
/// </summary>
protected INetDaemonApp App { get; }
/// <summary>
/// The daemon used in the API
/// </summary>
protected INetDaemon Daemon { get; }
/// <summary>
/// The EntityIds used
/// </summary>
protected IEnumerable<string> EntityIds { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="entityIds">The unique ids of the entities managed</param>
/// <param name="daemon">The Daemon that will handle API calls to Home Assistant</param>
/// <param name="app">The Daemon App calling fluent API</param>
public EntityBase(IEnumerable<string> entityIds, INetDaemon daemon, INetDaemonApp app)
{
EntityIds = entityIds;
Daemon = daemon;
App = app;
}
/// <inheritdoc/>
protected static string GetDomainFromEntity(string entity)
{
if (string.IsNullOrEmpty(entity))
throw new NetDaemonNullReferenceException(nameof(entity));
var entityParts = entity.Split('.');
if (entityParts.Length != 2)
throw new NetDaemonException($"entity_id is mal formatted {entity}");
return entityParts[0];
}
/// <inheritdoc/>
protected async Task CallServiceOnAllEntities(string service, dynamic? serviceData = null)
{
var taskList = new List<Task>();
foreach (var entityId in EntityIds)
{
var domain = GetDomainFromEntity(entityId);
serviceData ??= new FluentExpandoObject();
serviceData.entity_id = entityId;
var task = Daemon.CallServiceAsync(domain, service, serviceData);
taskList.Add(task);
}
if (taskList.Count > 0) await Task.WhenAny(Task.WhenAll(taskList.ToArray()), Task.Delay(5000)).ConfigureAwait(false);
}
}
} |
using System;
namespace Paydock.SDK.Entities
{
public class PaymentSource
{
public String Type { get; set; }
public String GatewayID { get; set; }
public Address Address { get; set; }
public BankCard Card { get; set; }
}
}
|
namespace SGDE.Domain.Converters
{
#region Using
using System.Collections.Generic;
using System.Linq;
using Entities;
using ViewModels;
#endregion
public class TypeDocumentConverter
{
public static TypeDocumentViewModel Convert(TypeDocument typeDocument)
{
if (typeDocument == null)
return null;
var typeDocumentViewModel = new TypeDocumentViewModel
{
id = typeDocument.Id,
addedDate = typeDocument.AddedDate,
modifiedDate = typeDocument.ModifiedDate,
iPAddress = typeDocument.IPAddress,
name = typeDocument.Name,
description = typeDocument.Description,
isRequired = typeDocument.IsRequired
};
return typeDocumentViewModel;
}
public static List<TypeDocumentViewModel> ConvertList(IEnumerable<TypeDocument> typeDocuments)
{
return typeDocuments?.Select(typeDocument =>
{
var model = new TypeDocumentViewModel
{
id = typeDocument.Id,
addedDate = typeDocument.AddedDate,
modifiedDate = typeDocument.ModifiedDate,
iPAddress = typeDocument.IPAddress,
name = typeDocument.Name,
description = typeDocument.Description,
isRequired = typeDocument.IsRequired
};
return model;
})
.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FormEsgi.Models
{
public class Question
{
public int QuestionId { get; set; }
public string question { get; set; }
public int TypeQuestionId { get; set; }
public int FormId { get; set; }
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class FeedBackScript : MonoBehaviour {
private int _checkpointTimerP1 = 0;
private int _checkpointTimerP2 = 0;
private bool _showPowerupFbP1 = false;
private bool _showPowerupFbP2 = false;
private Image _imageCheckPointP1;
private Image _imageCheckPointP2;
private Image _imageSpeedUpFBP1;
private Image _imageFireWallFBP1;
private Image _imageShieldFBP1;
private Image _imageSpeedUpFBP2;
private Image _imageFireWallFBP2;
private Image _imageShieldFBP2;
private Checkpoints _checkPoints;
private PowerUpScriptP1 _powerUpScriptP1;
private PowerUpScriptP2 _powerUpScriptP2;
private ConfirmScript _confirmScript;
public bool ShowPowerupFbP1 { set { _showPowerupFbP1 = value; } }
public bool ShowPowerupFbP2 { set { _showPowerupFbP2 = value; } }
// Use this for initialization
void Start () {
_imageCheckPointP1 = GameObject.Find("CheckPointP1").GetComponent<Image>();
_imageCheckPointP2 = GameObject.Find("CheckPointP2").GetComponent<Image>();
_imageSpeedUpFBP1 = GameObject.Find("SpeedUpFBP1").GetComponent<Image>();
_imageFireWallFBP1 = GameObject.Find("FireWallFBP1").GetComponent<Image>();
_imageShieldFBP1 = GameObject.Find("ShieldFBP1").GetComponent<Image>();
_imageSpeedUpFBP2 = GameObject.Find("SpeedUpFBP2").GetComponent<Image>();
_imageFireWallFBP2 = GameObject.Find("FireWallFBP2").GetComponent<Image>();
_imageShieldFBP2 = GameObject.Find("ShieldFBP2").GetComponent<Image>();
_checkPoints = GameObject.FindObjectOfType<Checkpoints>();
_powerUpScriptP1 = GameObject.FindObjectOfType<PowerUpScriptP1>();
_powerUpScriptP2 = GameObject.FindObjectOfType<PowerUpScriptP2>();
_confirmScript = FindObjectOfType<ConfirmScript>();
}
// Update is called once per frame
void Update () {
CheckCheckpointFB();
CheckPowerupFB();
}
void CheckCheckpointFB()
{
if (_confirmScript.Tutorial == false)
{
if (_checkPoints.CheckPointP1Hit)
{
_checkpointTimerP1++;
_imageCheckPointP1.enabled = true;
if (_checkpointTimerP1 >= Application.targetFrameRate * 2)
{
_checkpointTimerP1 = 0;
_checkPoints.CheckPointP1Hit = false;
_imageCheckPointP1.enabled = false;
}
}
if (_checkPoints.CheckPointP2Hit)
{
_checkpointTimerP2++;
_imageCheckPointP2.enabled = true;
if (_checkpointTimerP2 >= Application.targetFrameRate * 2)
{
_checkpointTimerP2 = 0;
_checkPoints.CheckPointP2Hit = false;
_imageCheckPointP2.enabled = false;
}
}
}
}
void CheckPowerupFB()
{
if (_showPowerupFbP1)
{
switch (_powerUpScriptP1.PowerUp)
{
case PowerUpScriptP1.Powerup.Boost:
_checkpointTimerP1++;
_imageSpeedUpFBP1.enabled = true;
if (_checkpointTimerP1 >= Application.targetFrameRate * 2)
{
_checkpointTimerP1 = 0;
_showPowerupFbP1 = false;
_imageSpeedUpFBP1.enabled = false;
}
break;
case PowerUpScriptP1.Powerup.Drill:
_checkpointTimerP1++;
_imageFireWallFBP1.enabled = true;
if (_checkpointTimerP1 >= Application.targetFrameRate * 2)
{
_checkpointTimerP1 = 0;
_showPowerupFbP1 = false;
_imageFireWallFBP1.enabled = false;
}
break;
case PowerUpScriptP1.Powerup.Invulnerability:
_checkpointTimerP1++;
_imageShieldFBP1.enabled = true;
if (_checkpointTimerP1 >= Application.targetFrameRate * 2)
{
_checkpointTimerP1 = 0;
_showPowerupFbP1 = false;
_imageShieldFBP1.enabled = false;
}
break;
default:
break;
}
if (_showPowerupFbP2)
{
switch (_powerUpScriptP2.PowerUp)
{
case PowerUpScriptP2.Powerup.Boost:
_checkpointTimerP2++;
_imageSpeedUpFBP2.enabled = true;
if (_checkpointTimerP2 >= Application.targetFrameRate * 2)
{
_checkpointTimerP2 = 0;
_showPowerupFbP2 = false;
_imageSpeedUpFBP2.enabled = false;
}
break;
case PowerUpScriptP2.Powerup.Drill:
_checkpointTimerP2++;
_imageFireWallFBP2.enabled = true;
if (_checkpointTimerP2 >= Application.targetFrameRate * 2)
{
_checkpointTimerP2 = 0;
_showPowerupFbP2 = false;
_imageFireWallFBP2.enabled = false;
}
break;
case PowerUpScriptP2.Powerup.Invulnerability:
_checkpointTimerP2++;
_imageShieldFBP2.enabled = true;
if (_checkpointTimerP1 >= Application.targetFrameRate * 2)
{
_checkpointTimerP2 = 0;
_showPowerupFbP2 = false;
_imageShieldFBP2.enabled = false;
}
break;
default:
break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoLamda
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
/*int[] array = new int[] { 1, 2, 3, 4, 5 };
string[] cities = new string[] {"Linz", "London","Paris","München","Wien","Eisenstatdt"};
Print(filter(array, x => x%2== 0));
Print(filter(cities, c => c == null ? false : c.ToUpper().StartsWith("L") ));
IEnumerable<string> qry = from c in cities
where c != null && c.StartsWith("L")
select c;
Print(qry);
Print(cities.Where(c => c != null && c.StartsWith('L')));*/
string text = string.Empty;
if(string.IsNullOrEmpty(text) == false)
{
Console.WriteLine(text);
}
if (text.HasContent())
{
}
}
static void Print<T>(IEnumerable<T> data)
{
foreach(var item in data)
{
Console.WriteLine(item);
}
}
static int[] Apply(int[] data, Func<int, int> f)
{
data.CheckArgument(nameof(data));
f.CheckArgument(nameof(f));
int[] result = new int[data.Length];
for (int i = 0; i>data.Length;i++)
{
result[i] = f(data[i]);
}
return result;
}
static T[] filter<T>(T[] data, Func<T,bool> filter)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (filter == null)
throw new ArgumentNullException(nameof(filter));
List<T> result = new List<T>();
for (int i = 0; i > data.Length; i++)
{
if (filter(data[i]))
{
result.Add(data[i]);
}
}
return result.ToArray();
}
}
}
|
using System;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using AForge.Vision.Motion;
using Accord.Video;
using Accord.Video.DirectShow;
using Accord.Video.FFMPEG;
namespace VideoSurveillance
{
public partial class MainForm : Form
{
private readonly VideoCaptureDevice camera;
private readonly VideoFileWriter videoWriter;
private readonly MotionDetector motionDetector;
private readonly Properties.Settings settings = Properties.Settings.Default;
private const string videoFileName = "video.mp4";
public MainForm()
{
InitializeComponent();
videoWriter = new VideoFileWriter();
camera = new VideoCaptureDevice();
var detector = new TwoFramesDifferenceDetector(true);
motionDetector = new MotionDetector(detector, new MotionAreaHighlighting());
}
private void MainForm_Closing(object sender, FormClosingEventArgs e)
{
if (camera.IsRunning)
{
MessageBox.Show("カメラが作動中です", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
return;
}
}
private void StartButton_Click(object sender, EventArgs e)
{
if (settings.CameraId == string.Empty)
{
MessageBox.Show("カメラが選択されていません", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (settings.VideoOutputDirectory == string.Empty)
{
MessageBox.Show("動画出力先フォルダが設定されていません", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else if (!Directory.Exists(settings.VideoOutputDirectory))
{
var message = $"動画出力先フォルダ {settings.VideoOutputDirectory} が存在しません";
MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
camera.Source = settings.CameraId;
var videoResolution = Array.Find(camera.VideoCapabilities, (c) => c.FrameSize == settings.VideoFrameSize);
if (videoResolution == null)
{
MessageBox.Show("カメラ設定が無効です。", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
camera.VideoResolution = videoResolution;
camera.NewFrame += new NewFrameEventHandler(Camera_NewFrame);
camera.PlayingFinished += new PlayingFinishedEventHandler(Camera_PlayingFinished);
var videoFilePath = Path.Combine(settings.VideoOutputDirectory, videoFileName);
videoWriter.Open(videoFilePath,
videoResolution.FrameSize.Width,
videoResolution.FrameSize.Height,
videoResolution.AverageFrameRate,
VideoCodec.MPEG4);
camera.Start();
startButton.Enabled = false;
stopButton.Enabled = true;
settingButton.Enabled = false;
cameraSelectionButton.Enabled = false;
}
private void StopButton_Click(object sender, EventArgs e)
{
if (camera.IsRunning)
{
camera.NewFrame -= new NewFrameEventHandler(Camera_NewFrame);
camera.SignalToStop();
}
startButton.Enabled = true;
stopButton.Enabled = false;
settingButton.Enabled = true;
cameraSelectionButton.Enabled = true;
}
private void Camera_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
using (var frame1 = eventArgs.Frame.Clone() as Bitmap)
using (var frame2 = eventArgs.Frame.Clone() as Bitmap)
{
var motionLevel = motionDetector.ProcessFrame(frame1);
Invoke(new Action(() =>
{
motionLevelLabel.Text = motionLevel.ToString("f4");
pictureBox.Image = frame1.Clone() as Bitmap;
}));
videoWriter.WriteVideoFrame(frame2);
}
}
private void Camera_PlayingFinished(object sender, ReasonToFinishPlaying reason)
{
Invoke(new Action(() =>
{
pictureBox.Image = null;
motionLevelLabel.Text = string.Empty;
}));
if (videoWriter.IsOpen)
{
videoWriter.Close();
}
}
private void SettingButton_Click(object sender, EventArgs e)
{
using (var form = new SettingForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
settings.VideoOutputDirectory = form.VideoOutputDirectory;
settings.Save();
}
}
}
private void CameraSelectionButton_Click(object sender, EventArgs e)
{
using (var form = new VideoCaptureDeviceForm())
{
form.FormBorderStyle = FormBorderStyle.FixedDialog;
if (settings.CameraId != string.Empty)
{
form.VideoDeviceMoniker = settings.CameraId;
form.CaptureSize = settings.VideoFrameSize;
}
if (form.ShowDialog() == DialogResult.OK)
{
settings.CameraId = form.VideoDeviceMoniker;
settings.VideoFrameSize = form.VideoDevice.VideoResolution.FrameSize;
settings.Save();
}
}
}
}
}
|
using System.Runtime.Serialization;
namespace SearchFoodServer.CompositeClass
{
[DataContract]
public class CompositeTypesCuisine
{
int _idTypesCuisine;
string _typesCuisine;
[DataMember]
public int IdTypesCuisineValue
{
get { return _idTypesCuisine; }
set { _idTypesCuisine = value; }
}
[DataMember]
public string TypesCuisineValue
{
get { return _typesCuisine; }
set { _typesCuisine = value; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace MySchool.LearningPlan.Domain.Entities
{
public class Theme : LearningEntity
{
public Theme(Guid learningEntityId,
int? nzqfYear,
int calendarYear,
string code,
string subjectCode) : base(learningEntityId, nzqfYear, calendarYear, code, subjectCode)
{
}
}
}
|
using System.Linq.Expressions;
namespace AutoMapper.Execution
{
using System;
public class DelegateBasedResolver<TSource, TMember> : IValueResolver
{
private readonly Func<TSource, ResolutionContext, TMember> _method;
public DelegateBasedResolver(Expression<Func<TSource, ResolutionContext, TMember>> method)
{
_method = method.Compile();
}
public object Resolve(object source, ResolutionContext context)
{
if (source != null && !(source is TSource))
{
throw new ArgumentException($"Expected obj to be of type {typeof(TSource)} but was {source.GetType()}");
}
var result = _method((TSource)source, context);
return result;
}
}
public class ExpressionBasedResolver<TSource, TMember> : IExpressionResolver
{
public LambdaExpression Expression { get; }
public LambdaExpression GetExpression => Expression;
private readonly Func<TSource, TMember> _method;
public ExpressionBasedResolver(Expression<Func<TSource, TMember>> expression)
{
Expression = expression;
_method = expression.Compile();
}
public Type MemberType => typeof(TMember);
public object Resolve(object source, ResolutionContext context)
{
if(source != null && !(source is TSource))
{
throw new ArgumentException($"Expected obj to be of type {typeof (TSource)} but was {source.GetType()}");
}
var result = _method((TSource)source);
return result;
}
}
} |
using System;
namespace algorithms {
public class algorithm {
public algorithm () { }
/**
* Binary Search: break each array size in half until we find the number we
* are looking for. O(log n)
*/
public bool binarySearch (int[] array, int number, int head, int tail) {
int pos = head + ((tail - head) / 2);
if (pos > array.Length - 1) {
return false;
} else {
if (number == array[pos]) {
return true;
} else if (number <= array[pos]) {
return binarySearch (array, number, head, pos - 1); // search first half
} else {
return binarySearch (array, number, pos + 1, tail);
}
}
}
/**
* Counting Sort: given an input array, create another array with
* length the same size as the input array that will be the sorted array
* and create another array to store the counts of each number that
* will be the length of the largest number + 1. i.e (largest value 3, length 4,
* [0, 1, 2, 3, 4]). O(n + k) where k is the size of the largest number.
*/
public void countingSort (int[] a, int[] b, int largest) {
int[] c = new int[largest + 1];
for (int i = 0; i < a.Length; i++) {
c[a[i]]++;
}
for (int i = 1; i < c.Length; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.Length - 1; i > 0; i--) {
b[c[a[i]] - 1] = a[i];
c[a[i]]--;
}
}
/**
* Bubble sort: Sawp each element of the array from start to finish.example
* Average case: O(n)
*
* worst Case: O(n2) when array is sorted in reverse order
*/
public void bubbleSort (int[] arr) {
int n = arr.Length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
/**
* If there is a value that is zero the change it to one in the array.
*/
public int[, ] manipulateZeroValue (int[, ] array) {
bool[] hasZero = new bool[array.GetLength (0)];
for (int i = 0; i < array.GetLength (0); i++) {
for (int j = 0; j < array.GetLength (1); j++) {
if (array[i, j] != 1) {
array[i, j] = 1;
}
}
}
return array;
}
/**
* Reverse an input array.
*/
public int[] reverseArray (int[] array) {
int count = 0;
int[] reversed = new int [array.Length];
for (int i = array.Length - 1; i > 0; i--) {
reversed[count] = array[i];
count++;
}
return reversed;
}
public void swap(int[] array, int current, int next) {
int temp = array[current];
array[current] = array[next];
array[next] = temp;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DD_PressurePlate : DD_Obstacle
{
private int mTotalCollisions = 0;
DD_PressurePlate()
{
Debug.Log("Pressure Plate Created");
SetObstacleType(ObstacleType.pressurePlate);
addObstacle();
}
private void OnTriggerEnter2D(Collider2D collision)
{
// Works regardless of entity
mTotalCollisions++;
if(mTotalCollisions == 1) {
// if there is already something on the pressure plate,
// pressure plate is already activated
Debug.Log("PressurePlate Activated");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
// Works regardless of entity
mTotalCollisions--;
if(mTotalCollisions == 0) {
// If last object removed
Debug.Log("Pressure Plate Deactivated");
}
}
}
|
using Infra;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeCSharp
{
public class _019_IsBalanceTree
{
/*
* http://leetcode.com/onlinejudge#question_110
*/
public bool IsBalanceTree(TreeNode root, ref int depth)
{
if (root == null)
{
depth = 0;
return true;
}
int leftDepth =0;
int rightDepth = 0;
if(!IsBalanceTree(root.LeftChild, ref leftDepth) ||
!IsBalanceTree(root.RightChild, ref rightDepth))
{
return false;
}
if (Math.Abs(rightDepth - leftDepth) > 1)
{
return false;
}
depth = Math.Max(leftDepth, rightDepth) + 1;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace luval_messagebox_inspector
{
public static class Logger
{
public static void WriteConsole(string format, params object[] parameters)
{
Console.WriteLine(format, parameters);
}
public static void WriteError(string format, params object[] parameters)
{
WriteToEventLog(EventLogEntryType.Error, format, parameters);
}
public static void WriteWarning(string format, params object[] parameters)
{
WriteToEventLog(EventLogEntryType.Warning, format, parameters);
}
public static void WriteInfo(string format, params object[] parameters)
{
WriteToEventLog(EventLogEntryType.Information, format, parameters);
}
public static void WriteToEventLog(EventLogEntryType type, string format, params object[] parameters)
{
using (EventLog eventLog = new EventLog("Application"))
{
var message = string.Format(format, parameters);
eventLog.Source = "Application";
eventLog.WriteEntry(message, type, 101, 1);
Console.WriteLine("Type: {0} Message: {1}", type, message);
}
}
}
}
|
namespace E01_Shapes
{
using System;
using E01_Shapes.AbstractClasses;
public class Circle : Shape
{
public Circle(double radius)
: base(radius)
{
}
public override double CalculateSurface()
{
return Math.Pow(this.Radius , 2) * System.Math.PI;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ComputerScreenUnstable : MonoBehaviour
{
public TMP_InputField inputField;
public GameController controller;
public AudioClip audioClip;
public AudioSource[] audioSource;
[HideInInspector] public float startingTime;
//[HideInInspector] public Random random;
//int flashingTextTimeScale = 0;
private void Awake()
{
audioSource[1].gameObject.SetActive(false);
}
/*private void Start()
{
startingTime = Time.fixedTime;
}*/
void Update()
{
//print(startingTime);
//if(Time.fixedTime >= 24.65 && Time.fixedTime <= 25)
if (Time.fixedTime >= startingTime + 2 && Time.fixedTime <= startingTime + 2.35)
{
audioSource[1].gameObject.SetActive(true);
}
//if (Time.fixedTime >= 25 && Time.fixedTime <= 25.5)
if (Time.fixedTime >= startingTime + 2.35 && Time.fixedTime <= startingTime + 2.45)
{
audioSource[0].Pause();
//audioSource[1].gameObject.SetActive(true);
//audioSource[1].clip = audioClip;
//audioSource[1].Play();
//print("1");
inputField.gameObject.SetActive(false);
controller.displayText.gameObject.SetActive(false);
controller.gameObject.SetActive(false);
}
/*if (Time.fixedTime >= 35 && Time.fixedTime <= 35.25)
{
inputField.gameObject.SetActive(true);
controller.displayText.gameObject.SetActive(true);
controller.gameObject.SetActive(true);
}
if (Time.fixedTime >= 35.27 && Time.fixedTime <= 35.75)
{
inputField.gameObject.SetActive(false);
controller.displayText.gameObject.SetActive(false);
controller.gameObject.SetActive(false);
}*/
/*if (Time.fixedTime >= 37.5 && Time.fixedTime <= 38.5)
{
inputField.gameObject.SetActive(true);
controller.displayText.gameObject.SetActive(true);
controller.gameObject.SetActive(true);
//inputField.gameObject.SetActive(false);
//controller.displayText.gameObject.SetActive(false);
//controller.gameObject.SetActive(false);
audioSource[0].Play();
//flashingTextTimeScale += 1;
}*/
/*if (Time.fixedTime >= 37.5 + 0.2 * flashingTextTimeScale && Time.fixedTime <= 37.75 + 0.2 * flashingTextTimeScale && flashingTextTimeScale % 2 == 1)
{
//inputField.gameObject.SetActive(true);
//controller.displayText.gameObject.SetActive(true);
//controller.gameObject.SetActive(true);
inputField.gameObject.SetActive(false);
controller.displayText.gameObject.SetActive(false);
controller.gameObject.SetActive(false);
if (flashingTextTimeScale != 5)
flashingTextTimeScale += 1;
//audioSource[0].Play();
}*/
//if (Time.fixedTime >= 38.5 && Time.fixedTime <= 39)
if (Time.fixedTime >= startingTime + 12.85 && Time.fixedTime <= startingTime + 13.45)
{
inputField.gameObject.SetActive(true);
controller.displayText.gameObject.SetActive(true);
controller.gameObject.SetActive(true);
audioSource[1].gameObject.SetActive(false);
audioSource[0].Play();
//print("2");
}
if (Time.fixedTime > startingTime + 14.35)
{
audioSource[0].Stop();
//audioSource[0].PlayOneShot(audioSource[0].clip, 0.3f);
audioSource[0].GetComponent<ComputerScreenUnstable>().enabled = false;
//print("3");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
//namespace MarsQA_1.Specflow_Pages.Helper
//{
// public class ConstantHelpers
// {
// //Base Url
// //public static string Url = "http://192.168.99.100:5000";
// ////ScreenshotPath
// //public static string ScreenshotPath = "";
// ////ExtentReportsPath
// //public static string ReportsPath = "";
// ////ReportXML Path
// //public static string ReportXMLPath = "";
// //public static string Url { get; internal set; }
// }
//}
|
using System;
using System.Collections.Generic;
using System.IO;
using Model;
namespace Controller
{
class LevelParser
{
private string _pathName = "";
private FileStream _inputStream;
private StreamReader _streamReader;
private GameBoard _gameBoard;
private Controller _controller;
public Model.GameBoard GameBoard
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public GameBoard LoadGameBoard(Controller _controller)
{
this._controller = _controller;
_gameBoard = new GameBoard(_controller);
_pathName = String.Concat("..\\..\\Map\\Map", ".txt");
List<Tile> previousLine = null;
int lineCounter = 0;
try
{
DetectDimensions();
_inputStream = new FileStream(_pathName, FileMode.Open, FileAccess.Read);
_streamReader = new StreamReader(_inputStream);
string lineString = _streamReader.ReadLine();
do
{
if (lineString != null)
{
List<Tile> currentLine;
currentLine = ProcesLine(lineString, lineCounter);
if (previousLine != null)
{
LinkLines(previousLine, currentLine);
}
else
{
_gameBoard.Origin = currentLine[0];
}
previousLine = currentLine;
lineCounter++;
lineString = _streamReader.ReadLine();
}
else
{
_streamReader.Close();
_inputStream.Close();
}
}
while (lineString != null);
return _gameBoard;
}
catch (Exception)
{
throw new FileLoadException();
}
}
private List<Tile> ProcesLine(string lineString, int y)
{
List<Tile> TileLine = new List<Tile>();
Tile previousTile = null;
for (int x = 0; x < lineString.Length; x++)
{
Tile tile;
switch (lineString[x])
{
case 'W':
tile = new Water();
break;
case 'D':
tile = new Dock();
break;
case 'R':
tile = new Track('-');
break;
case 'U':
tile = new Track('|');
break;
case '1':
tile = new Switch('S');
_gameBoard.Switch1 = (Switch)tile;
_gameBoard.Switch1.SwitchDirection = SwitchDirection.MIDDLE;
break;
case '2':
tile = new Switch('S');
_gameBoard.Switch2 = (Switch)tile;
_gameBoard.Switch2.SwitchDirection = SwitchDirection.MIDDLE;
break;
case '3':
tile = new Switch('S');
_gameBoard.Switch3 = (Switch)tile;
_gameBoard.Switch3.SwitchDirection = SwitchDirection.MIDDLE;
break;
case '4':
tile = new Switch('S');
_gameBoard.Switch4 = (Switch)tile;
_gameBoard.Switch4.SwitchDirection = SwitchDirection.MIDDLE;
break;
case '5':
tile = new Switch('S');
_gameBoard.Switch5 = (Switch)tile;
_gameBoard.Switch5.SwitchDirection = SwitchDirection.MIDDLE;
break;
case '8':
tile = new Water();
_gameBoard.ShipEnd = (Water)tile;
break;
case '9':
tile = new Water();
_gameBoard.ShipStart = (Water)tile;
break;
case 'A':
tile = new Start('A');
_gameBoard.PointA = tile;
break;
case 'B':
tile = new Start('B');
_gameBoard.PointB = tile;
break;
case 'C':
tile = new Start('C');
_gameBoard.PointC = tile;
break;
case 'O':
tile = new Warehouse();
break;
case '.':
tile = new EmptyTile();
break;
default:
tile = new EmptyTile();
break;
}
if (previousTile != null)
{
tile.TileToLeft = previousTile;
previousTile.TileToRight = tile;
}
previousTile = tile;
TileLine.Add(tile);
}
return TileLine;
}
private void LinkLines(List<Tile> previousLine, List<Tile> currentLine)
{
for (int n = 0; n < currentLine.Count; n++)
{
if ((previousLine[n] != null) && (currentLine[n] != null))
{
currentLine[n].TileAbove = previousLine[n];
previousLine[n].TileBelow = currentLine[n];
}
}
}
private void DetectDimensions()
{
_inputStream = new FileStream(_pathName, FileMode.Open, FileAccess.Read);
_streamReader = new StreamReader(_inputStream);
int x = 0;
int y = 0;
try
{
string lineString = _streamReader.ReadLine();
do
{
if (lineString != null)
{
if (lineString.Length > x)
{
x = lineString.Length;
}
y++;
lineString = _streamReader.ReadLine();
}
else
{
_streamReader.Close();
_inputStream.Close();
}
}
while (lineString != null);
_gameBoard.Width = x;
_gameBoard.Height = y;
}
catch (Exception)
{
throw new Exception();
}
}
}
}
|
using System.Text.RegularExpressions;
namespace Kit
{
public static class Validations
{
private static Regex EmailRegex => _EmailRegex.Value;
private static readonly Lazy<Regex> _EmailRegex = new Lazy<Regex>(() => new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.Compiled | RegexOptions.Singleline));
public static bool IsValidEmail(string email)
{
return !string.IsNullOrEmpty(email) && EmailRegex.IsMatch(email);
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using Xunit;
namespace NuGet.Packaging.Core.Test
{
public class NuSpecCoreReaderTests
{
[Fact]
public void GetPackageType_ReturnsDefaultIfPackageTypeIsNotSpecifiedInManfiest()
{
// Arrange
var contents =
@"<?xml version=""1.0""?>
<package>
<metadata/>
</package>";
var reader = new TestNuSpecCoreReader(contents);
// Act
var packageType = reader.GetPackageType();
// Assert
Assert.Same(PackageType.Default, packageType);
}
[Theory]
[InlineData(@"<?xml version=""1.0""?>
<package xmlns=""a-random-xsd"">
<metadata>
<id>Test</id>
<somestuff>some-value</somestuff>
<ver>123</ver>
</metadata>
</package>")]
[InlineData(@"<?xml version=""1.0""?>
<package xmlns=""a-random-xsd"">
<metadata>
<packageType version=""2.0"">Managed</packageType>
<id>Test</id>
<somestuff>some-value</somestuff>
<ver>123</ver>
</metadata>
</package>")]
public void GetMetadata_SkipsPackageTypeElement(string contents)
{
// Arrange
var reader = new TestNuSpecCoreReader(contents);
// Act
var metadata = reader.GetMetadata();
// Assert
Assert.Collection(metadata,
item =>
{
Assert.Equal("id", item.Key);
Assert.Equal("Test", item.Value);
},
item =>
{
Assert.Equal("somestuff", item.Key);
Assert.Equal("some-value", item.Value);
},
item =>
{
Assert.Equal("ver", item.Key);
Assert.Equal("123", item.Value);
});
}
[Theory]
[InlineData(
@"<?xml version=""1.0""?>
<package>
<metadata>
<packageType version=""2.0"">Managed</packageType>
</metadata>
</package>", "Managed", "2.0")]
[InlineData(
@"<?xml version=""1.0""?>
<package>
<metadata>
<packageType version=""3.5"">SomeFormat</packageType>
</metadata>
</package>", "SomeFormat", "3.5")]
[InlineData(
@"<?xml version=""1.0""?>
<package>
<metadata>
<packageType>RandomFormat123</packageType>
</metadata>
</package>", "RandomFormat123", "0.0")]
public void GetPackageType_ReadsPackageTypeFromManifest(string contents, string expectedType, string expectedVersion)
{
// Arrange
var reader = new TestNuSpecCoreReader(contents);
// Act
var packageType = reader.GetPackageType();
// Assert
Assert.Equal(expectedType, packageType.Name);
Assert.Equal(expectedVersion, packageType.Version.ToString());
}
[Fact]
public void GetPackageType_ThrowsIfPackageTypeVersionCannotBeRead()
{
// Arrange
var contents =
@"<?xml version=""1.0""?>
<package>
<metadata>
<packageType version=""3.5-alpha"">SomeFormat</packageType>
</metadata>
</package>";
var reader = new TestNuSpecCoreReader(contents);
// Act and Assert
Assert.Throws<FormatException>(() => reader.GetPackageType());
}
public class TestNuSpecCoreReader : NuspecCoreReaderBase
{
public TestNuSpecCoreReader(string content)
: base(new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace _24HR.Imaging.UnitTests
{
[TestFixture]
public class Pad
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.