text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CT.Data;
using CT.Data.Instance;
using CT.Instance;
using UnityEngine.UI;
namespace CT.UI.Upgrade
{
public class TurretUpgradeUI : UpgradeUI<TurretInstanceData>
{
public Text oldRangeText, newRangeText;
public Text oldFireRateText, newFireRateText;
public Text oldDamageText, newDamageText;
public Text oldUnitNameText, newUnitNameText;
public Image oldUnitImage, newUnitImage;
public Text oldUnitAmountText, newUnitAmountText;
public Text oldSpawnDeltaText, newSpawnDeltaText;
public GameObject unitLauncherOldUI, unitLauncherNewUI, turretOldUI, turretNewUI;
void OnDisable()
{
unitLauncherOldUI.SetActive(false);
unitLauncherNewUI.SetActive(false);
turretOldUI.SetActive(false);
turretNewUI.SetActive(false);
}
protected override void OnInit(TurretInstanceData instance)
{
//var data = instance.data as DefensiveData;
var current = instance.CurrentData;
oldRangeText.text = current.range.ToString();
if(current.defenseType == DefensiveData.DefenseType.Turret)
{
turretOldUI.SetActive(true);
oldFireRateText.text = current.fireRate.ToString();
oldDamageText.text = current.Damage.ToString();
}
else
{
unitLauncherOldUI.SetActive(true);
oldUnitNameText.text = current.unit.name;
oldUnitImage.sprite = current.unit.icon;
oldUnitAmountText.text = current.amount.ToString();
oldSpawnDeltaText.text = current.spawnDelta.ToString();
}
var next = instance.NextData;
if (next == null) return;
newRangeText.text = next.range.ToString();
if (next.defenseType == DefensiveData.DefenseType.Turret)
{
turretOldUI.SetActive(true);
oldFireRateText.text = next.fireRate.ToString();
oldDamageText.text = next.Damage.ToString();
}
else
{
unitLauncherOldUI.SetActive(true);
oldUnitNameText.text = next.unit.name;
newUnitImage.sprite = next.unit.icon;
oldUnitAmountText.text = next.amount.ToString();
oldSpawnDeltaText.text = next.spawnDelta.ToString();
}
}
[ContextMenu("Apply Basics")]
protected override void ApplyBasics()
{
base.ApplyBasics();
}
}
} |
using Microsoft.Data.Sqlite;
namespace TNBase.Repository.Migrations
{
/// <summary>
/// Remove deleted listener's personal data for GDPR purposes
/// </summary>
public class _4_MaskDeletedListeners : SqlMigration
{
public _4_MaskDeletedListeners(SqliteConnection connection) : base(connection)
{ }
public override void Up()
{
using var command = connection.CreateCommand();
command.CommandText = $@"UPDATE Listeners SET
Title='N/A',
Forename='Deleted',
Surname='Deleted',
Addr1=null,
Addr2=null,
Town=null,
County=null,
Postcode=null,
Telephone=null,
BirthdayDay=null,
BirthdayMonth=null,
Info=null,
StatusInfo=null
WHERE Status='DELETED' AND
MemStickPlayer=false AND
Stock=3 AND
(Magazine=0 OR (Magazine=1 AND MagazineStock=1))";
command.ExecuteNonQuery();
}
}
}
|
using BoatRegistration.Data.Model;
using Microsoft.EntityFrameworkCore;
namespace BoatRegistration.Data
{
public class BaseContext : DbContext
{
public DbSet<Boat> Boats { get; set; }
public BaseContext(DbContextOptions<BaseContext> options) : base(options)
{
this.Database.EnsureCreated();
}
}
}
|
using Enrollment.Common.Configuration.Json;
using System.Text.Json.Serialization;
namespace Enrollment.Common.Configuration.ExpressionDescriptors
{
[JsonConverter(typeof(DescriptorConverter))]
public abstract class OperatorDescriptorBase : IExpressionOperatorDescriptor
{
public string TypeString => this.GetType().AssemblyQualifiedName;
}
}
|
using ShCore.DataBase.ADOProvider.Attributes;
using ShCore.Extensions;
using ShCore.Utility;
using ShCore.Web.Inputs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Document.Entities
{
/// </summary>
[TableInfo(TableName = "[Districts]")]
public class District : MainDbEntityBase
{
#region Properties
[Field(IsKey = true, IsIdentity = true)]
[DataValueField]
public int PK_DistrictID { set; get; }
[Field(Name = "Tên", Important = true)]
[DataTextField]
public string Name { set; get; }
[Field(Name = "Loại")]
public string DistrictType { set; get; }
[Field(Name = "Ghi chú")]
public string Note { set; get; }
[Field(Name = "Ngày tạo")]
public DateTime CreatedDate { get; set; }
[Field(Name = "Người tạo")]
public Guid? CreatedByUser { get; set; }
[Field(Name = "Ngày sửa")]
public Guid? UpdatedDate { get; set; }
#endregion
public static List<District> GetAllData()
{
return Singleton<District>.Inst.GetAll().ToList<District>(false).OrderBy(x => x.PK_DistrictID).ToList(); ;
}
}
} |
using System.Collections;
using UnityEngine;
class moveCamera : MonoBehaviour
{
public float lerpTime = 0.3f;
public float currentLerpTime = 0;
public bool keyHitLeft = false;
public bool keyHitRight = false;
private Vector3 start, end, left, middle, right;
public int counter = 0;
private bool moving = false;
private void Start()
{
left = new Vector3(-4, 0, -1);
middle = new Vector3(0, 0, -1);
right = new Vector3(4, 0, -1);
}
void Update()
{
float x = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y)).x;
float y = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y)).y;
if (Input.GetMouseButtonDown(0) && x>=-9 && x<=-8 && y>=-4.5 && y<=-3.5 && (counter == -1 || counter == 0) && !moving) { keyHitLeft = true; moving = true; }
if (Input.GetMouseButtonDown(0) && x<=9 && x>=8 && y>=-4.5 && y<=-3.5 && (counter == 1 || counter == 0) && !moving) { keyHitRight = true; moving = true; }
if (keyHitLeft)
{
if (counter == 0)
{
start = middle;
end = left;
}
if (counter == -1)
{
start = left;
end = middle;
}
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime) { currentLerpTime = lerpTime; }
float perc = currentLerpTime / lerpTime;
transform.position = Vector3.Lerp(start, end, perc);
}
if (keyHitRight)
{
if (counter == 0)
{
start = middle;
end = right;
}
if (counter == 1)
{
start = right;
end = middle;
}
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime) { currentLerpTime = lerpTime; }
float perc = currentLerpTime / lerpTime;
transform.position = Vector3.Lerp(start, end, perc);
}
if (currentLerpTime == 0.3f)
{
if (keyHitLeft && counter == 0)
{
counter = -1;
keyHitLeft = false;
currentLerpTime = 0;
}
if (keyHitLeft && counter == -1)
{
counter = 0;
keyHitLeft = false;
currentLerpTime = 0;
}
if (keyHitRight && counter == 0)
{
counter = 1;
keyHitRight = false;
currentLerpTime = 0;
}
if (keyHitRight && counter == 1)
{
counter = 0;
keyHitRight = false;
currentLerpTime = 0;
}
moving = false;
}
}
} |
namespace PluginStudy.EntityFramework
{
using System.Data.Entity;
using PluginStudy.Domain.Entity;
public partial class PluginStudyDbContext : DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<StudentInfo> StudentInfo { get; set; }
public PluginStudyDbContext()
: base("name=PluginStudyDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
public bool isBig;
public int score;
private Animator animator;
bool isGet;
// Start is called before the first frame update
void Start()
{
isGet = false;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (isGet)
return;
switch (collision.tag)
{
case "Player":
case "Bullet":
animator.SetBool("isGet", true);
isGet = true;
StaticValues.AddScore(score);
AudioManager.Instance.PlaySE(isBig ? "coin_big" : "coin", 0.05f);
break;
}
}
}
|
using OnlineExaminationSystem.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace OnlineExaminationSystem.Business.Abstract
{
public interface IUserService
{
User GetById(int userId);
User GetByMail(string email);
User GetByName(string firstName);
User GetByLastName(string lastName);
List<User> GetList();
void Add(User user);
void Delete(User user);
void Update(User user);
}
}
|
using System;
namespace Viking.AssemblyVersioning
{
public class GenericSignature : IEquatable<GenericSignature>
{
public GenericSignature(Type[] signature) { Signature = signature; }
private Type[] Signature { get; }
public int SingatureLength => Signature.Length;
public bool IsParameterGeneric(int parameter) => Signature[parameter].IsGenericParameter;
public bool IsParameterSpecified(int parameter) => !IsParameterGeneric(parameter);
public Type GetSpecifiedParameter(int parameter)
{
if (!IsParameterSpecified(parameter))
throw new ArgumentException($"The parameter at index {parameter} is not specified: it is a generic parameter.");
return Signature[parameter];
}
public GenericParameter GetGenericParameter(int parameter) => new GenericParameter(Signature[parameter]);
//public override bool Equals(object obj) => obj is GenericSignature ? Equals(obj as GenericSignature) : false;
public bool Equals(GenericSignature other)
{
for (int i = 0; i < SingatureLength; ++i)
{
var generic = IsParameterGeneric(i);
if (other.IsParameterGeneric(i) != generic)
return false;
if (generic)
{
if (!GetGenericParameter(i).HasSameSignature(other.GetGenericParameter(i)))
return false;
}
else // Specified
{
if (!TypeSignature.TypesHaveSameSignatures(GetSpecifiedParameter(i), other.GetSpecifiedParameter(i)))
return false;
}
}
return true;
}
//public bool GenericSignatureCanBeRelaxedTo(GenericSignature other) => Equals(other);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GetSetGo.Models
{
public class Summary
{
ApplicationDbContext _context;
public Summary()
{
_context = new ApplicationDbContext();
}
public int TotalRentals
{
get { return _context.Rentals.Count(); }
}
public int TotalActiveRentals
{
get { return _context.Rentals.Where(r => r.ReturnedDateTime == null).Count(); }
}
public int TotalCustomers
{
get { return _context.Customers.Count(); }
}
public int TotalActiveCustomers
{
get { return _context.Customers.Where(c => c.RentedVehicleId != null).Count(); }
}
public int TotalInactiveCustomers
{
get { return _context.Customers.Where(c => c.RentedVehicleId == null).Count(); }
}
public int TotalVehicles
{
get { return _context.Vehicles.Count(); }
}
public int TotalActiveVehicles
{
get { return _context.Vehicles.Where(v => v.Availability == false).Count(); }
}
public int TotalAvailableVehicles
{
get { return _context.Vehicles.Where(v => v.Availability == true).Count(); }
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "DialogueObject", menuName = "CAS_JAM/DialogueObject", order = 0)]
public class DialogueObject : ScriptableObject
{
[Header("Dialogue")]
public List<DialogueSegment> dialogueSegments = new List<DialogueSegment>();
}
[System.Serializable]
public struct DialogueSegment
{
public string dialogueName;
[TextArea(3, 7)] public string dialogueText;
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TaxCalculatorExample.Core
{
public class TaxCalculator
{
public decimal Calculat(ICountryTaxCalculator obj)
{
decimal taxAmount = obj.CalculateTaxAmount();
return taxAmount;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using FIUChat.DatabaseAccessObject.CommandObjects;
using FIUChat.Enums;
using MongoDB.Bson;
using MongoDB.Driver;
namespace FIUChat.DatabaseAccessObject
{
public class MongoDB
{
private static readonly MongoDB mongoDB = new MongoDB();
private const string DBName = "FIUChat";
static MongoDB()
{
}
public static MongoDB Instance
{
get
{
return mongoDB;
}
}
/// <summary>
/// Connects to mongo db.
/// </summary>
/// <returns><c>true</c>, if to mongo db was connected, <c>false</c> otherwise.</returns>
/// <param name="entity">Entity.</param>
private async Task<MongoDBResultState> ExecuteMongoDBCommand<T>(T entity, MongoDBExecuteCommand mongoDBExecuteCommand)
where T: Command
{
MongoDBResultState mongoDBResultState = new MongoDBResultState();
try
{
var collection = this.ConnectToMongo(entity);
if (collection == null)
{
return new MongoDBResultState
{
Result = MongoDBResult.Failure,
Message = $"Unable to create collection {entity.GetType().Name}"
};
}
switch(mongoDBExecuteCommand)
{
case MongoDBExecuteCommand.Create:
await collection.InsertOneAsync(entity);
mongoDBResultState.Message = $"Successfully created {entity.GetType()} in the database.";
mongoDBResultState.Result = MongoDBResult.Success;
break;
case MongoDBExecuteCommand.Update:
await collection.ReplaceOneAsync(x => x.ID == entity.ID, entity);
mongoDBResultState.Message = $"Successfully updated {entity.GetType()} in the collection.";
mongoDBResultState.Result = MongoDBResult.Success;
break;
case MongoDBExecuteCommand.Delete:
await collection.DeleteOneAsync(x => x.ID == entity.ID);
mongoDBResultState.Message = $"Successfully deleted {entity.GetType()} in the collection.";
mongoDBResultState.Result = MongoDBResult.Success;
break;
default:
mongoDBResultState.Message = $"There was an unknown command executed with ID: {entity.ID}.";
mongoDBResultState.Result = MongoDBResult.Failure;
break;
}
}
catch(MongoDuplicateKeyException dupEx)
{
mongoDBResultState.Message = dupEx.Message;
mongoDBResultState.Result = MongoDBResult.AlreadyExists;
}
catch(Exception ex)
{
mongoDBResultState.Message = ex.Message;
mongoDBResultState.Result = MongoDBResult.Failure;
}
return mongoDBResultState;
}
/// <summary>
/// Finds the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="entity">Entity.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
private async Task<T> FindObject<T>(T entity)
where T : Command
{
T result;
try
{
var command = entity as Command;
var collection = this.ConnectToMongo(entity);
if (collection == null)
{
Console.WriteLine($"Collection: {entity.GetType()} does not exsit.");
return default(T);
}
result = (T)await collection.FindAsync(x => x.ID == command.ID);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
return default(T);
}
return result;
}
/// <summary>
/// Finds the object by expression.
/// </summary>
/// <returns>The object by expression.</returns>
/// <param name="entity">Entity.</param>
/// <param name="expression">Expression.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
private async Task<T> FindObjectByExpression<T>(T entity, Expression<Func<T, bool>> expression)
{
T result;
try
{
var command = entity as Command;
var collection = this.ConnectToMongo(entity);
if (collection == null)
{
Console.WriteLine($"Collection: {entity.GetType()} does not exsit.");
return default(T);
}
var filterDefinition = Builders<T>.Filter.Where(expression);
var results = await collection.Find(filterDefinition).ToListAsync();
result = results.FirstOrDefault();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return default(T);
}
return result;
}
/// <summary>
/// Connects to mongo.
/// </summary>
/// <returns>The to mongo.</returns>
/// <param name="entity">Entity.</param>
private IMongoCollection<T> ConnectToMongo<T>(T entity)
{
IMongoCollection<T> collection = null;
try
{
MongoClientSettings setting = new MongoClientSettings
{
Server = new MongoServerAddress("localhost", 27017)
};
MongoClient client = new MongoClient(setting);
var mongoDbServer = client.GetDatabase(DBName);
collection = mongoDbServer.GetCollection<T>($"{entity.GetType().Name}");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return collection;
}
/// <summary>
/// Sends the message to mongo db.
/// </summary>
/// <returns>The message to mongo db.</returns>
/// <param name="entity">Message.</param>
private async Task<MongoDBResultState> SendMessageToMongoDB<T>(T entity)
where T : Message
{
MongoDBResultState mongoDBResultState = new MongoDBResultState();
try
{
MongoClientSettings setting = new MongoClientSettings
{
Server = new MongoServerAddress("localhost", 27017)
};
MongoClient client = new MongoClient(setting);
var mongoDbServer = client.GetDatabase(DBName);
var collection = mongoDbServer.GetCollection<T>($"{entity.GroupChatName}Messages");
await collection.InsertOneAsync(entity);
mongoDBResultState.Result = MongoDBResult.Success;
mongoDBResultState.Message = $"Successfully stored message in the {entity.GroupChatName}Messages collection.";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
mongoDBResultState.Message = ex.Message;
mongoDBResultState.Result = MongoDBResult.Failure;
}
return mongoDBResultState;
}
/// <summary>
/// Creates the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="entity">Entity.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public async Task<MongoDBResultState> CreateObject<T>(T entity)
where T : Command
{
return await ExecuteMongoDBCommand(entity, MongoDBExecuteCommand.Create);
}
/// <summary>
/// Reads the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="entity">Id.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public async Task<T> ReadObject<T>(T entity)
where T : Command
{
return await this.FindObject(entity);
}
/// <summary>
/// Updates the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="entity">Entity.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public async Task<MongoDBResultState> UpdateObject<T>(T entity)
where T : Command
{
return await ExecuteMongoDBCommand(entity, MongoDBExecuteCommand.Update);
}
/// <summary>
/// Deletes the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="entity">Entity.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public async Task<MongoDBResultState> DeleteObject<T>(T entity)
where T : Command
{
return await ExecuteMongoDBCommand(entity, MongoDBExecuteCommand.Delete);
}
/// <summary>
/// Sends the message.
/// </summary>
/// <returns>The message.</returns>
/// <param name="message">Message.</param>
public async Task<MongoDBResultState> SendMessage(Message message)
{
return await this.SendMessageToMongoDB(message);
}
/// <summary>
/// Reads the object by expression.
/// </summary>
/// <returns>The object by expression.</returns>
/// <param name="entity">Entity.</param>
/// <param name="expression">Expression.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public async Task<T> ReadObjectByExpression<T>(T entity, Expression<Func<T, bool>> expression)
{
return await this.FindObjectByExpression(entity, expression);
}
}
}
|
using UnityEngine;
using System.Collections;
namespace Com.PDev.PCG {
public class Launcher : Photon.PunBehaviour {
#region Public Var
public bool loadDebugRoom = false;
[Tooltip("The UI Panel to let the user enter name, connect and play")]
public GameObject controlPanel;
[Tooltip("The UI Label to inform the user that the connection is in progress")]
public GameObject progressLabel;
/// <summary>
/// The maximum number of players per room. When a room is full, it can't be joined by new players, and so new room will be created.
/// </summary>
[Tooltip("The maximum number of players per room. When a room is full, it can't be joined by new players, and so new room will be created")]
public byte MaxPlayersPerRoom = 4;
// the PUN log level
public PhotonLogLevel Loglevel = PhotonLogLevel.Informational;
public string UserId;
public string previousRoom;
#endregion
#region Private Var
string previousRoomPlayerPrefKey = "PUN:PRC:PCG:PreviousRoom";
/// <summary>
/// Keep track of the asynchronous connection process
/// </summary>
bool isConnecting;
/// <summary>
/// This client's version number.
/// Users are separated from each other by gameversion (which allows you to make breaking changes).
/// </summary>
string _gameVersion = "1";
#endregion
#region MonoBehaviour CallBacks
void Awake(){
// #Critical
// we don't join the lobby. There is no need to join a lobby to get the list of rooms.
PhotonNetwork.autoJoinLobby = false;
// #Critical
// this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
PhotonNetwork.automaticallySyncScene = true;
PhotonNetwork.logLevel = Loglevel;
}
void Start(){
SetProgressViewVisible (false);
}
#endregion
#region Public Methods
public void Connect(){
isConnecting = true;
SetProgressViewVisible (true);
if (PhotonNetwork.connected) {
PhotonNetwork.JoinRandomRoom();
} else {
PhotonNetwork.ConnectUsingSettings (_gameVersion);
}
}
#endregion
#region Private Methods
private void SetProgressViewVisible(bool visible){
progressLabel.SetActive (visible);
controlPanel.SetActive (!visible);
}
#endregion
#region Pun Behaviour Callbacks
/*
public override void OnConnectedToMaster()
{
// after connect
this.UserId = PhotonNetwork.player.UserId;
////Debug.Log("UserID " + this.UserId);
if (PlayerPrefs.HasKey(previousRoomPlayerPrefKey))
{
Debug.Log("getting previous room from prefs: ");
this.previousRoom = PlayerPrefs.GetString(previousRoomPlayerPrefKey);
PlayerPrefs.DeleteKey(previousRoomPlayerPrefKey); // we don't keep this, it was only for initial recovery
}
// after timeout: re-join "old" room (if one is known)
if (!string.IsNullOrEmpty(this.previousRoom))
{
Debug.Log("ReJoining previous room: " + this.previousRoom);
PhotonNetwork.ReJoinRoom(this.previousRoom);
this.previousRoom = null; // we only will try to re-join once. if this fails, we will get into a random/new room
}
else
{
// else: join a random room
PhotonNetwork.JoinRandomRoom();
}
}
public override void OnJoinedLobby()
{
OnConnectedToMaster(); // this way, it does not matter if we join a lobby or not
}
public override void OnPhotonRandomJoinFailed(object[] codeAndMsg)
{
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = MaxPlayersPerRoom, PlayerTtl = 20000 }, null);
}
public override void OnJoinedRoom()
{
Debug.Log("Joined room: " + PhotonNetwork.room.Name);
this.previousRoom = PhotonNetwork.room.Name;
PlayerPrefs.SetString(previousRoomPlayerPrefKey,this.previousRoom);
if (PhotonNetwork.room.PlayerCount == MaxPlayersPerRoom) {
//Debug.Log("We Load the 'game2p' scene");
PhotonNetwork.LoadLevel ("game" + MaxPlayersPerRoom + "p");
} else if (loadDebugRoom == true) {
PhotonNetwork.LoadLevel ("gameTest");
}
}
public override void OnPhotonJoinRoomFailed(object[] codeAndMsg)
{
Debug.Log("OnPhotonJoinRoomFailed");
this.previousRoom = null;
PlayerPrefs.DeleteKey(previousRoomPlayerPrefKey);
}
public override void OnConnectionFail(DisconnectCause cause)
{
Debug.Log("Disconnected due to: " + cause + ". this.previousRoom: " + this.previousRoom);
}
public override void OnPhotonPlayerActivityChanged(PhotonPlayer otherPlayer)
{
Debug.Log("OnPhotonPlayerActivityChanged() for "+otherPlayer.NickName+" IsInactive: "+otherPlayer.IsInactive);
}
public override void OnDisconnectedFromPhoton(){
SetProgressViewVisible (false);
Debug.LogWarning("PCG/Launcher: OnDisconnectedFromPhoton() was called by PUN");
}
*/
public override void OnConnectedToMaster(){
Debug.Log ("PCG/Launcher: OnConnectedToMaster() was called by PUN");
if (isConnecting){
PhotonNetwork.JoinRandomRoom ();
}
}
public override void OnDisconnectedFromPhoton(){
SetProgressViewVisible (false);
Debug.LogWarning("PCG/Launcher: OnDisconnectedFromPhoton() was called by PUN");
}
public override void OnPhotonRandomJoinFailed( object[] codeAndMsg){
Debug.Log("DemoAnimator/Launcher:OnPhotonRandomJoinFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom(null, new RoomOptions() {maxPlayers = 4}, null);");
PhotonNetwork.CreateRoom (null, new RoomOptions () { MaxPlayers = MaxPlayersPerRoom }, null);
}
public override void OnJoinedRoom()
{
Debug.Log("DemoAnimator/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.");
// #Critical Only load the game when the room is full
if (PhotonNetwork.room.PlayerCount == MaxPlayersPerRoom) {
//Debug.Log("We Load the 'game2p' scene");
PhotonNetwork.LoadLevel ("game" + MaxPlayersPerRoom + "p");
} else if (loadDebugRoom == true) {
PhotonNetwork.LoadLevel ("gameTest");
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using OCP.AppFramework.Utility;
namespace OCP.BackgroundJob
{
/**
* Simple base class for a one time background job
*
* @since 15.0.0
*/
abstract class QueuedJob : Job
{
public QueuedJob(ITimeFactory time) : base(time)
{
}
/**
* run the job, then remove it from the joblist
*
* @param IJobList jobList
* @param ILogger|null logger
*
* @since 15.0.0
*/
public void execute(IJobList jobList, ILogger logger = null)
{
jobList.remove(this, this.argument);
execute(jobList, logger);
}
}
}
|
using LazyCache;
using LazyCache.Providers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Visualbean.Pokemon.Pokemon;
namespace Visualbean.Pokemon.UnitTest
{
[TestClass]
public class PokeApiClientTests
{
private const string PokemonName = "Test";
private readonly string pokemonJson = @"{
'name': 'Test',
'flavor_text_entries': [{
'flavor_text': 'Some Text',
'language': {
'name': 'en'
}
}]
}
";
[TestMethod]
public async Task GetPokemon_WithCorrectName_ReturnsResult()
{
(PokeApiClient client, _) = SetupPokeApiClient();
var result = await client.GetByNameAsync(PokemonName);
Assert.IsTrue(result.IsSuccess);
Assert.IsTrue(result.Value.Name == PokemonName);
}
[TestMethod]
public async Task GetPokemon_WithNotFoundResponse_ReturnsFailureResult()
{
(PokeApiClient client, _) = SetupPokeApiClient(HttpStatusCode.NotFound);
var result = await client.GetByNameAsync("SomeRandomNonExistentPokemonName");
Assert.IsTrue(result.IsFailure, "Not Found from the API should result in a Failure.");
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public async Task GetPokemon_WithAPIProblem_Throws()
{
(PokeApiClient client, _) = SetupPokeApiClient(HttpStatusCode.BadGateway);
await client.GetByNameAsync(PokemonName);
}
[TestMethod]
public async Task GetPokemon_WithSameNameDifferentCasing_ReturnsSameResult()
{
(PokeApiClient client, MockHttpMessageHandler handler) = SetupPokeApiClient();
var first = await client.GetByNameAsync(PokemonName);
var second = await client.GetByNameAsync(PokemonName.ToLower());
Assert.AreEqual(first.Value, second.Value, "Both objects should be the same.");
}
[TestMethod]
public async Task GetPokemon_WithSameName_ReturnsCachedResult()
{
(PokeApiClient client, MockHttpMessageHandler handler) = SetupPokeApiClient();
var first = await client.GetByNameAsync(PokemonName);
var second = await client.GetByNameAsync(PokemonName);
Assert.AreEqual(first.Value, second.Value, "Both objects should be the same.");
Assert.IsTrue(handler.NumberOfCalls == 1, "Second result should be cached.");
}
private (PokeApiClient client, MockHttpMessageHandler handler) SetupPokeApiClient(HttpStatusCode responseStatusCode = HttpStatusCode.OK)
{
var handler = new MockHttpMessageHandler(pokemonJson, responseStatusCode);
var cacheProvider = new Lazy<ICacheProvider>(() =>
new MemoryCacheProvider(
new MemoryCache(
new MemoryCacheOptions())
));
var client = new PokeApiClient(new HttpClient(handler), new CachingService(cacheProvider));
return (client, handler);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class scrHeavenlyLightningButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool mouseOn;
public Text text;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (mouseOn && Input.GetAxis("Slot One Input") != 0 && scrExperienceManager.ExperienceManager.heavenlyLightningUnlocked)
{
if (!scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
scrCompetenceManager.CompetenceManager.slotOneName = scrCompetenceManager.CompetenceManager.heavenlyLightningName;
if (scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
{
if (scrCompetenceManager.CompetenceManager.slotTwoName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotOneName;
scrCompetenceManager.CompetenceManager.slotOneName = scrCompetenceManager.CompetenceManager.slotTwoName;
scrCompetenceManager.CompetenceManager.slotTwoName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotOneImage.sprite;
scrCompetenceManager.CompetenceManager.slotOneImage.sprite = scrCompetenceManager.CompetenceManager.slotTwoImage.sprite;
scrCompetenceManager.CompetenceManager.slotTwoImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
if (scrCompetenceManager.CompetenceManager.slotThreeName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotOneName;
scrCompetenceManager.CompetenceManager.slotOneName = scrCompetenceManager.CompetenceManager.slotThreeName;
scrCompetenceManager.CompetenceManager.slotThreeName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotOneImage.sprite;
scrCompetenceManager.CompetenceManager.slotOneImage.sprite = scrCompetenceManager.CompetenceManager.slotThreeImage.sprite;
scrCompetenceManager.CompetenceManager.slotThreeImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
}
}
if (mouseOn && Input.GetAxis("Slot Two Input") != 0 && scrExperienceManager.ExperienceManager.heavenlyLightningUnlocked)
{
if (!scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
scrCompetenceManager.CompetenceManager.slotTwoName = scrCompetenceManager.CompetenceManager.heavenlyLightningName;
if (scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
{
if (scrCompetenceManager.CompetenceManager.slotOneName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotTwoName;
scrCompetenceManager.CompetenceManager.slotTwoName = scrCompetenceManager.CompetenceManager.slotOneName;
scrCompetenceManager.CompetenceManager.slotOneName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotTwoImage.sprite;
scrCompetenceManager.CompetenceManager.slotTwoImage.sprite = scrCompetenceManager.CompetenceManager.slotOneImage.sprite;
scrCompetenceManager.CompetenceManager.slotOneImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
if (scrCompetenceManager.CompetenceManager.slotThreeName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotTwoName;
scrCompetenceManager.CompetenceManager.slotTwoName = scrCompetenceManager.CompetenceManager.slotThreeName;
scrCompetenceManager.CompetenceManager.slotThreeName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotTwoImage.sprite;
scrCompetenceManager.CompetenceManager.slotTwoImage.sprite = scrCompetenceManager.CompetenceManager.slotThreeImage.sprite;
scrCompetenceManager.CompetenceManager.slotThreeImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
}
}
if (mouseOn && Input.GetAxis("Slot Three Input") != 0 && scrExperienceManager.ExperienceManager.heavenlyLightningUnlocked)
{
if (!scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
scrCompetenceManager.CompetenceManager.slotThreeName = scrCompetenceManager.CompetenceManager.heavenlyLightningName;
if (scrCompetenceManager.CompetenceManager.heavenlyLightningEquiped)
{
if (scrCompetenceManager.CompetenceManager.slotOneName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotThreeName;
scrCompetenceManager.CompetenceManager.slotThreeName = scrCompetenceManager.CompetenceManager.slotOneName;
scrCompetenceManager.CompetenceManager.slotOneName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotThreeImage.sprite;
scrCompetenceManager.CompetenceManager.slotThreeImage.sprite = scrCompetenceManager.CompetenceManager.slotOneImage.sprite;
scrCompetenceManager.CompetenceManager.slotOneImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
if (scrCompetenceManager.CompetenceManager.slotTwoName == scrCompetenceManager.CompetenceManager.heavenlyLightningName)
{
scrCompetenceManager.CompetenceManager.stockageName = scrCompetenceManager.CompetenceManager.slotThreeName;
scrCompetenceManager.CompetenceManager.slotThreeName = scrCompetenceManager.CompetenceManager.slotTwoName;
scrCompetenceManager.CompetenceManager.slotTwoName = scrCompetenceManager.CompetenceManager.stockageName;
scrCompetenceManager.CompetenceManager.StockageImage.sprite = scrCompetenceManager.CompetenceManager.slotThreeImage.sprite;
scrCompetenceManager.CompetenceManager.slotThreeImage.sprite = scrCompetenceManager.CompetenceManager.slotTwoImage.sprite;
scrCompetenceManager.CompetenceManager.slotTwoImage.sprite = scrCompetenceManager.CompetenceManager.StockageImage.sprite;
}
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
mouseOn = true;
if (scrExperienceManager.ExperienceManager.heavenlyLightningUnlocked)
text.text = "& To Use";
else
text.text = "Cost : 20 points";
}
public void OnPointerExit(PointerEventData eventData)
{
mouseOn = false;
text.text = "Heavenly Lightning";
}
}
|
using System;
using System.Windows;
using OverCR.StatX.Statistics;
using OverCR.StatX.Extensions;
using System.Windows.Input;
namespace OverCR.StatX
{
public partial class MainWindow
{
private MouseTracker MouseTracker { get; set; }
private KeyboardTracker KeyboardTracker { get; set; }
private NetworkTracker NetworkTracker { get; set; }
public MainWindow()
{
InitializeComponent();
}
private void KeyboardTracker_KeyPressesChanged(object sender, EventArgs e)
{
TotalKeyPressesDisplay.Value = KeyboardTracker.TotalKeyPresses;
App.StatisticsSaveFile.SetValue("TotalKeyPresses", KeyboardTracker.TotalKeyPresses);
}
private void KeyboardTracker_KeyPressureChanged(object sender, EventArgs e)
{
App.StatisticsSaveFile.SetValue("TotalKeyPressEnergy", KeyboardTracker.TotalKeypressEnergy);
}
private void MouseTracker_DistanceTraveledChanged(object sender, EventArgs e)
{
TotalMouseDistanceDisplay.Value = Math.Round(MouseTracker.TotalDistanceTraveled, 2);
App.StatisticsSaveFile.SetValue("TotalMouseTravelDistance", MouseTracker.TotalDistanceTraveled);
}
private void MouseTracker_DistanceScrolledChanged(object sender, EventArgs e)
{
TotalMouseScrollDistanceDisplay.Value = Math.Round(MouseTracker.TotalDistanceScrolled, 2);
App.StatisticsSaveFile.SetValue("TotalMouseScrollDistance", MouseTracker.TotalDistanceScrolled);
}
private void MouseTracker_MiddleClicksChanged(object sender, EventArgs e)
{
App.StatisticsSaveFile.SetValue("TotalMouseMiddleClicks", MouseTracker.TotalMiddleClicks);
}
private void MouseTracker_RightClicksChanged(object sender, EventArgs e)
{
App.StatisticsSaveFile.SetValue("TotalMouseRightClicks", MouseTracker.TotalRightClicks);
}
private void MouseTracker_LeftClicksChanged(object sender, EventArgs e)
{
App.StatisticsSaveFile.SetValue("TotalMouseLeftClicks", MouseTracker.TotalLeftClicks);
}
private void MouseTracker_ClicksChanged(object sender, EventArgs e)
{
TotalMouseClicksDisplay.Value = MouseTracker.TotalClicks;
}
private void NetworkTracker_SentDataChanged(object sender, EventArgs e)
{
var megaBytes = Math.Round(NetworkTracker.TotalBytesSent / 1024 / 1024, 2);
if (megaBytes > 1024)
{
var gigaBytes = Math.Round(megaBytes / 1024, 2);
if (gigaBytes > 1024)
{
var teraBytes = Math.Round(gigaBytes / 1024, 2);
SetTotalDataSent(teraBytes, "terabytes");
App.StatisticsSaveFile.SetValue("TotalDataSent", teraBytes);
App.StatisticsSaveFile.SetValue("TotalDataSentUnit", "terabytes");
}
else
{
SetTotalDataSent(gigaBytes, "gigabytes");
App.StatisticsSaveFile.SetValue("TotalDataSent", gigaBytes);
App.StatisticsSaveFile.SetValue("TotalDataSentUnit", "gigabytes");
}
}
else
{
SetTotalDataSent(megaBytes, "megabytes");
App.StatisticsSaveFile.SetValue("TotalDataSent", megaBytes);
App.StatisticsSaveFile.SetValue("TotalDataSentUnit", "megabytes");
}
App.StatisticsSaveFile.SetValue("TotalBytesSent", NetworkTracker.TotalBytesSent);
}
private void NetworkTracker_ReceivedDataChanged(object sender, EventArgs e)
{
var megaBytes = Math.Round(NetworkTracker.TotalBytesReceived / 1024 / 1024, 2);
if (megaBytes > 1024)
{
var gigaBytes = Math.Round(megaBytes / 1024, 2);
if (gigaBytes > 1024)
{
var teraBytes = Math.Round(gigaBytes / 1024, 2);
SetTotalDataReceived(teraBytes, "terabytes");
App.StatisticsSaveFile.SetValue("TotalDataReceived", teraBytes);
App.StatisticsSaveFile.SetValue("TotalDataReceivedUnit", "terabytes");
}
else
{
SetTotalDataReceived(gigaBytes, "gigabytes");
App.StatisticsSaveFile.SetValue("TotalDataReceived", gigaBytes);
App.StatisticsSaveFile.SetValue("TotalDataReceivedUnit", "gigabytes");
}
}
else
{
SetTotalDataReceived(megaBytes, "megabytes");
App.StatisticsSaveFile.SetValue("TotalDataReceived", megaBytes);
App.StatisticsSaveFile.SetValue("TotalDataReceivedUnit", "megabytes");
}
App.StatisticsSaveFile.SetValue("TotalBytesReceived", NetworkTracker.TotalBytesReceived);
}
private void SetTotalDataSent(double value, string unit)
{
Application.Current?.Dispatcher.Invoke(() =>
{
TotalDataSentDisplay.UnitName = unit;
TotalDataSentDisplay.Value = value;
});
}
private void SetTotalDataReceived(double value, string unit)
{
Application.Current?.Dispatcher.Invoke(() =>
{
TotalDataReceivedDisplay.UnitName = unit;
TotalDataReceivedDisplay.Value = value;
});
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
App.TrayIconProvider.CreateTrayIcon("StatX");
App.TrayIconProvider.NotifyIconClicked += TrayIconProvider_NotifyIconClicked;
this.DisableMaximization();
Application.Current.Exit += (s, a) =>
{
NetworkTracker.StopMonitoring();
};
NetworkTracker = new NetworkTracker();
NetworkTracker.ReloadStats();
NetworkTracker.SentDataChanged += NetworkTracker_SentDataChanged;
NetworkTracker.ReceivedDataChanged += NetworkTracker_ReceivedDataChanged;
NetworkTracker.StartMonitoring();
MouseTracker = new MouseTracker();
MouseTracker.ReloadStats();
MouseTracker.DistanceTraveledChanged += MouseTracker_DistanceTraveledChanged;
MouseTracker.DistanceScrolledChanged += MouseTracker_DistanceScrolledChanged;
MouseTracker.ClicksChanged += MouseTracker_ClicksChanged;
MouseTracker.LeftClicksChanged += MouseTracker_LeftClicksChanged;
MouseTracker.RightClicksChanged += MouseTracker_RightClicksChanged;
MouseTracker.MiddleClicksChanged += MouseTracker_MiddleClicksChanged;
KeyboardTracker = new KeyboardTracker();
KeyboardTracker.ReloadStats();
KeyboardTracker.KeyPressesChanged += KeyboardTracker_KeyPressesChanged;
KeyboardTracker.KeyPressEnergyChanged += KeyboardTracker_KeyPressureChanged;
KeyboardTracker_KeyPressesChanged(null, null);
KeyboardTracker_KeyPressureChanged(null, null);
MouseTracker_ClicksChanged(null, null);
MouseTracker_DistanceScrolledChanged(null, null);
MouseTracker_DistanceTraveledChanged(null, null);
NetworkTracker_SentDataChanged(null, null);
NetworkTracker_ReceivedDataChanged(null, null);
}
private void TrayIconProvider_NotifyIconClicked(object sender, EventArgs eventArgs)
{
ToggleVisibility();
}
private void ToggleVisibility()
{
if (Visibility == Visibility.Visible)
{
Visibility = Visibility.Hidden;
}
else
{
Visibility = Visibility.Visible;
Activate();
}
}
protected override void OnCloseButtonClicked(object sender, RoutedEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
var choiceWindow = ChoiceWindow.ShowChoice("Really exit?", "Your statistics won't be tracked until you restart this application!", this);
choiceWindow.YesClicked += (s, ev) =>
{
Close();
};
choiceWindow.ShowDialog();
}
else
{
ToggleVisibility();
}
}
}
} |
using System;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senai.Sistema.Carfel.ProjetoFinalDezoito.Models;
using Senai.Sistema.Carfel.ProjetoFinalDezoito.Repositorio;
namespace Senai.Sistema.Carfel.ProjetoFinalDezoito.Controllers {
public class ComentarioController : Controller {
public static UsuarioModel UsuarioAutenticado { get; private set; }
ComentarioRepositorio comentarioRepositorio = new ComentarioRepositorio ();
int contador = 0;
[HttpGet]
public IActionResult Cadastrar () {
if (string.IsNullOrEmpty (HttpContext.Session.GetString ("emailUsuario"))) {
return RedirectToAction ("Login", "Usuario");
}
ComentarioRepositorio comentarioRepositorio = new ComentarioRepositorio ();
ViewData["Comentarios"] = comentarioRepositorio.Listar ();
return View ();
}
[HttpPost]
public IActionResult Cadastrar (IFormCollection form) {
ComentarioModel comentario = new ComentarioModel ();
// comentario.Usuario = UsuarioAutenticado;
comentario.Descricao = form["descricao"];
comentario.DataCriacao = DateTime.Now;
comentario.Aprovado = false;
comentario.NomeUsuario = HttpContext.Session.GetString ("emailUsuario");
ComentarioRepositorio comRepo = new ComentarioRepositorio ();
comRepo.Criar (comentario);
TempData["Mensagem"] = "Comentário cadastrado com sucesso!";
ViewBag.Mensagem = "Comentário Cadastrado";
// using (StreamWriter sw = new StreamWriter ("comentarioDB.txt", true)) {
// sw.WriteLine ($"{comentario.Id};{HttpContext.Session.GetString("emailUsuario")};{comentario.Descricao};{comentario.DataCriacao};{comentario.Aprovado}");
// }
return RedirectToAction ("Cadastrar");
}
[HttpGet]
public IActionResult Listar () {
ComentarioRepositorio comentarioRepositorio = new ComentarioRepositorio ();
ViewData["Comentarios"] = comentarioRepositorio.Listar ();
return View ();
}
[HttpGet]
public IActionResult Excluir (int id) {
ComentarioRepositorio.Excluir (id);
TempData["Mensagem"] = "Comentario excluído";
return RedirectToAction ("Administrador", "Usuario");
}
[HttpGet]
public IActionResult Aprovar (int id) {
ComentarioRepositorio comentarioRepositorio = new ComentarioRepositorio();
ComentarioRepositorio.Aprovar (id);
TempData["Mensagem"] = "Comentario Aprovado";
ViewData["comentarios"] = comentarioRepositorio.Listar();
return RedirectToAction ("Administrador", "Usuario");
}
public IActionResult ListarParaADM () {
ComentarioRepositorio comentarioRepositorio = new ComentarioRepositorio ();
ViewData["Comentarios"] = comentarioRepositorio.ListarADM ();
return View ();
}
}
} |
using System;
namespace Model.Entities
{
public class TimesheetEntry
{
public int Id { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? EndTime { get; set; }
public string Note { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class CloudController : MonoBehaviour {
public float scrollSpeed = 10f;
public float tileSize = 600f;
public float initialOffset = 0f;
private Vector3 starPosition;
// Use this for initialization
void Start () {
starPosition = transform.position;
}
// Update is called once per frame
void Update () {
float newPosition = Mathf.Repeat(Time.time * scrollSpeed + initialOffset, tileSize);
transform.position = starPosition + Vector3.left * newPosition;
}
}
|
using com.sun.tools.@internal.xjc;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using MarsQA_1.Helper;
using Driver = MarsQA_1.Helper.Driver;
using NUnit.Framework;
namespace MarsQA_1.Pages
{
class AddCertification_Page
{
public void Find_Certificate_Tab()
{
//Find the Certificate tab
new WebDriverWait(Driver.driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("//a[text()='Languages']")));
Driver.driver.FindElement(By.XPath("//a[text()='Certifications']")).Click();
}
public void Add_New_Details()
{
//Find the Add new button
Thread.Sleep(2000);
Driver.driver.FindElement(By.XPath("//th[text()='Certificate']//parent::tr//following-sibling::th[@class='right aligned']//div[@class='ui teal button ']")).Click();
//Enter Certificate
Thread.Sleep(2000);
Driver.driver.FindElement(By.Name("certificationName")).SendKeys("CISCO");
//Certified From
Thread.Sleep(2000);
Driver.driver.FindElement(By.Name("certificationFrom")).SendKeys("India");
//Select dropdown for Year
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/div/div[2]/div[2]/select")).Click();
Driver.driver.FindElement(By.XPath("//option[text()='2017']")).Click();
}
public void Add_Certificate()
{
//Add Detail
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/div/div[3]/input[1]")).Click();
new WebDriverWait(Driver.driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[1]")));
IWebElement CISCO = Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[1]"));
if (CISCO.Text == "CISCO")
{
//Assert.Pass("Language Edit succsesfully");
Console.WriteLine("Add Certificate passed");
}
else
{
//Assert.Fail("Language Edit not succsesfully");
Console.WriteLine("Add certificate failed");
}
}
////Edit Certificate
public void Click_Edit_Button()
{
Thread.Sleep(2000);
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[4]/span[1]/i")).Click();
}
public void Edit_Certificate_Details()
{
//language.Click();
Driver.driver.FindElement(By.Name("certificationName")).Click();
//language clear;
Driver.driver.FindElement(By.Name("certificationName")).Clear();
//language new value add
Driver.driver.FindElement(By.Name("certificationName")).SendKeys("CISCO123");
//FromClick();
Driver.driver.FindElement(By.Name("certificationFrom")).Click();
//From clear;
Driver.driver.FindElement(By.Name("certificationFrom")).Clear();
//From new value add
Driver.driver.FindElement(By.Name("certificationFrom")).SendKeys("USA");
//Select dropdown
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td/div/div/div[3]/select")).Click();
Driver.driver.FindElement(By.XPath("//option[text()='2019']")).Click();
}
public void Add_Certificate_Details()
{
//click on the update button
Thread.Sleep(2000);
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td/div/span/input[1]")).Click();
new WebDriverWait(Driver.driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[1]")));
IWebElement CISCO123 = Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[1]"));
if (CISCO123.Text == "CISCO123")
{
//Assert.Pass("Language Edit succsesfully");
Console.WriteLine("Certificate Edit passed");
}
else
{
//Assert.Fail("Language Edit not succsesfully");
Console.WriteLine("certificate Edit failed");
}
}
public void DeleteCertficate()
{
//Delete the Record
new WebDriverWait(Driver.driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[4]/span[2]/i")));
Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[4]/span[2]/i")).Click();
//new WebDriverWait(Driver.driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[5]/div[1]/div[2]/div/table/tbody/tr/td[1]")));
Thread.Sleep(2000);
IWebElement CISCO123 = Driver.driver.FindElement(By.XPath("//*[@id='account-profile-section']/div/section[2]/div/div/div/div[3]/form/div[4]/div/div[2]/div/table"));
if (CISCO123.Text != "CISCO123")
{
Assert.Pass("Certificate Delete succsesfully");
//Console.WriteLine("passed");
}
else
{
Assert.Fail("Certificate Delete not succsesfully");
//Console.WriteLine("failed");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief 暗号化。
*/
/** NCrypt
*/
namespace NCrypt
{
/** MonoBehaviour_Security
*/
public class MonoBehaviour_Security : MonoBehaviour_Base , OnCoroutine_CallBack
{
/** リクエストタイプ。
*/
private enum RequestType
{
None = -1,
/** 暗号化。パブリックキー。
*/
EncryptPublicKey,
/** 複合化。プライベートキー。
*/
DecryptPrivateKey,
/** 証明作成。プライベートキー。
*/
CreateSignaturePrivateKey,
/** 署名検証。パブリックキー。
*/
VerifySignaturePublicKey,
/** 暗号化。パス。
*/
EncryptPass,
/** 複合化。パス。
*/
DecryptPass,
};
/** request_type
*/
[SerializeField]
private RequestType request_type;
/** request_binary
*/
[SerializeField]
private byte[] request_binary;
/** request_key
*/
[SerializeField]
private string request_key;
/** request_signature_binary
*/
private byte[] request_signature_binary;
/** request_pass
*/
[SerializeField]
private string request_pass;
/** request_salt
*/
[SerializeField]
private string request_salt;
/** [NFile.OnCoroutine_CallBack]コルーチン実行中。
戻り値 == false : キャンセル。
*/
public bool OnCoroutine(float a_progress)
{
if((this.IsCancel() == true)||(this.IsDeleteRequest() == true)){
return false;
}
this.SetResultProgress(a_progress);
return true;
}
/** [MonoBehaviour_Base]コールバック。初期化。
*/
protected override void OnInitialize()
{
//request_type
this.request_type = RequestType.None;
//request_binary
this.request_binary = null;
//request_key
this.request_key = null;
//request_signature_binary
this.request_signature_binary = null;
//request_pass
this.request_pass = null;
//request_salt
this.request_salt = null;
}
/** [MonoBehaviour_Base]コールバック。開始。
*/
protected override IEnumerator OnStart()
{
switch(this.request_type){
case RequestType.EncryptPublicKey:
case RequestType.DecryptPrivateKey:
case RequestType.CreateSignaturePrivateKey:
case RequestType.VerifySignaturePublicKey:
case RequestType.EncryptPass:
case RequestType.DecryptPass:
{
Tool.Log("MonoBehaviour_Security",this.request_type.ToString());
this.SetModeDo();
}yield break;
}
//不明なリクエスト。
this.SetResultErrorString("request_type == " + this.request_type.ToString());
this.SetModeDoError();
yield break;
}
/** [MonoBehaviour_Base]コールバック。実行。
*/
protected override IEnumerator OnDo()
{
switch(this.request_type){
case RequestType.EncryptPublicKey:
{
Coroutine_EncryptPublicKey t_coroutine = new Coroutine_EncryptPublicKey();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_key);
if(t_coroutine.result.binary != null){
this.SetResultBinary(t_coroutine.result.binary);
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
case RequestType.DecryptPrivateKey:
{
Coroutine_DecryptPrivateKey t_coroutine = new Coroutine_DecryptPrivateKey();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_key);
if(t_coroutine.result.binary != null){
this.SetResultBinary(t_coroutine.result.binary);
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
case RequestType.CreateSignaturePrivateKey:
{
Coroutine_CreateSignaturePrivateKey t_coroutine = new Coroutine_CreateSignaturePrivateKey();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_key);
if(t_coroutine.result.binary != null){
this.SetResultBinary(t_coroutine.result.binary);
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
case RequestType.VerifySignaturePublicKey:
{
Coroutine_VerifySignaturePublicKey t_coroutine = new Coroutine_VerifySignaturePublicKey();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_signature_binary,this.request_key);
if(t_coroutine.result.verify == true){
this.SetResultVerifySuccess();
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
case RequestType.EncryptPass:
{
Coroutine_EncryptPass t_coroutine = new Coroutine_EncryptPass();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_pass,this.request_salt);
if(t_coroutine.result.binary != null){
this.SetResultBinary(t_coroutine.result.binary);
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
case RequestType.DecryptPass:
{
Coroutine_DecryptPass t_coroutine = new Coroutine_DecryptPass();
yield return t_coroutine.CoroutineMain(this,this.request_binary,this.request_pass,this.request_salt);
if(t_coroutine.result.binary != null){
this.SetResultBinary(t_coroutine.result.binary);
this.SetModeDoSuccess();
}else{
this.SetResultErrorString(t_coroutine.result.errorstring);
}
}break;
}
this.SetModeDoError();
yield break;
}
/** [MonoBehaviour_Base]コールバック。エラー終了。
*/
protected override IEnumerator OnDoError()
{
this.SetResultProgress(1.0f);
this.SetModeFix();
yield break;
}
/** [MonoBehaviour_Base]コールバック。正常終了。
*/
protected override IEnumerator OnDoSuccess()
{
this.SetResultProgress(1.0f);
this.SetModeFix();
yield break;
}
/** リクエスト。暗号化。パブリックキー。
*/
public bool RequestEncryptPublicKey(byte[] a_binary,string a_key)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.EncryptPublicKey;
this.request_binary = a_binary;
this.request_key = a_key;
return true;
}
return false;
}
/** リクエスト。複合化。プライベートキー。
*/
public bool RequestDecryptPrivateKey(byte[] a_binary,string a_key)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.DecryptPrivateKey;
this.request_binary = a_binary;
this.request_key = a_key;
return true;
}
return false;
}
/** リクエスト。署名作成。プライベートキー。
*/
public bool RequestCreateSignaturePrivateKey(byte[] a_binary,string a_key)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.CreateSignaturePrivateKey;
this.request_binary = a_binary;
this.request_key = a_key;
return true;
}
return false;
}
/** リクエスト。署名検証。パブリックキー。
*/
public bool RequestVerifySignaturePublicKey(byte[] a_binary,byte[] a_signature_binary,string a_key)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.VerifySignaturePublicKey;
this.request_binary = a_binary;
this.request_signature_binary = a_signature_binary;
this.request_key = a_key;
return true;
}
return false;
}
/** リクエスト。暗号化。パス。
*/
public bool RequestEncryptPass(byte[] a_binary,string a_pass,string a_salt)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.EncryptPass;
this.request_binary = a_binary;
this.request_pass = a_pass;
this.request_salt = a_salt;
return true;
}
return false;
}
/** リクエスト。複合化。パス。
*/
public bool RequestDecryptPass(byte[] a_binary,string a_pass,string a_salt)
{
if(this.IsWaitRequest() == true){
this.SetModeStart();
this.ResetResultFlag();
this.request_type = RequestType.DecryptPass;
this.request_binary = a_binary;
this.request_pass = a_pass;
this.request_salt = a_salt;
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Kers.Models.Entities.KERScore;
using Kers.Models.Entities.UKCAReporting;
using Kers.Models.Abstract;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Kers.Models.Contexts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Kers.Controllers
{
[Route("api/[controller]")]
public class CountyEventController : BaseController
{
KERScoreContext _context;
KERSreportingContext _reportingContext;
IWebHostEnvironment environment;
private string DefaultTime = "12:34:56.1000000";
public CountyEventController(
KERSmainContext mainContext,
KERScoreContext context,
IKersUserRepository userRepo,
KERSreportingContext reportingContext,
IWebHostEnvironment env
):base(mainContext, context, userRepo){
_context = context;
_reportingContext = reportingContext;
this.environment = env;
}
[HttpGet]
[Route("range/{countyId?}/{skip?}/{take?}/{order?}")]
public virtual IActionResult GetRange(int skip = 0, int take = 10, string order = "start", int countyId = 0)
{
if(countyId == 0 ){
var user = CurrentUser();
countyId = user.RprtngProfile.PlanningUnitId;
}
IQueryable<CountyEvent> query = _context.CountyEvent
.Where( e => e.Units.Select( u => u.PlanningUnitId).Contains(countyId))
.Include( e => e.Location).ThenInclude( l => l.Address)
.Include( e => e.Units)
.Include( e => e.ProgramCategories);
if(order == "end"){
query = query.OrderByDescending(t => t.End);
}else if( order == "created"){
query = query.OrderByDescending(t => t.CreatedDateTime);
}else{
query = query.OrderByDescending(t => t.Start);
}
query = query.Skip(skip).Take(take);
var reslt = new List<CountyEventWithTime>();
foreach( var ce in query){
var e = new CountyEventWithTime(ce);
reslt.Add( e );
}
return new OkObjectResult(reslt);
}
[HttpGet]
[Route("GetCustom")]
public virtual IActionResult GetCustom(
[FromQuery] string search,
[FromQuery] DateTime start,
[FromQuery] DateTime end,
[FromQuery] int? day,
[FromQuery] string order,
[FromQuery] int? countyId
)
{
var reslt = new List<CountyEventWithTime>();
if(environment.IsDevelopment()){
List<CountyEvent> query;
query = _context.CountyEvent.Include( e => e.Location).ThenInclude( l => l.Address)
.Include( e => e.Units)
.Include( e => e.ProgramCategories).ToList();
query = query.Where( e => e.Start.Date >= start.Date && e.Start.Date <= end.Date).ToList();
if( countyId != null){
if(countyId == 0 ){
var user = CurrentUser();
countyId = user.RprtngProfile.PlanningUnitId;
}
query = query.Where( e => e.Units.Select( u => u.PlanningUnitId ).Contains(countyId??0)).ToList();
}
if( day != null){
query = query.Where( e => (int) e.Start.DayOfWeek == (day??0) ).ToList();
}
if( search != null && search != ""){
query = query.Where( e => e.Subject.Contains( search )).ToList();
}
if(order == "dsc"){
query = query.OrderByDescending(t => t.Start).ToList();
}else if( order == "asc"){
query = query.OrderBy(t => t.CreatedDateTime).ToList();
}else{
query = query.OrderBy(t => t.Subject).ToList();
}
foreach( var ce in query){
var e = new CountyEventWithTime(ce);
reslt.Add( e );
}
}else{
IQueryable<CountyEvent> query = _context.CountyEvent.Where( e => e.Start.Date >= start.Date && e.Start.Date <= end.Date);
if( countyId != null){
if(countyId == 0 ){
var user = CurrentUser();
countyId = user.RprtngProfile.PlanningUnitId;
}
query = query.Where( e => e.Units.Select( u => u.PlanningUnitId ).Contains(countyId??0));
}
if( day != null){
query = query.Where( e => (int) e.Start.DayOfWeek == (day??0) );
}
if( search != null && search != ""){
query = query.Where( e => e.Subject.Contains( search ));
}
query = query .Include( e => e.Location).ThenInclude( l => l.Address)
.Include( e => e.Units)
.Include( e => e.ProgramCategories);
if(order == "dsc"){
query = query.OrderByDescending(t => t.Start);
}else if( order == "asc"){
query = query.OrderBy(t => t.CreatedDateTime);
}else{
query = query.OrderBy(t => t.Subject);
}
foreach( var ce in query){
var e = new CountyEventWithTime(ce);
reslt.Add( e );
}
}
return new OkObjectResult(reslt);
}
[HttpPost("addcountyevent")]
[Authorize]
public IActionResult AddCountyEvent( [FromBody] CountyEventWithTime CntEvent){
if(CntEvent != null){
CountyEvent evnt = new CountyEvent();
evnt.Organizer = this.CurrentUser();
evnt.CreatedDateTime = DateTimeOffset.Now;
evnt.LastModifiedDateTime = DateTimeOffset.Now;
var starttime = this.DefaultTime;
evnt.IsAllDay = true;
var timezone = CntEvent.Etimezone ? " -04:00":" -05:00";
if(CntEvent.Starttime != ""){
starttime = CntEvent.Starttime+":00.1000000";
evnt.IsAllDay = false;
evnt.HasStartTime = true;
}
evnt.Start = DateTimeOffset.Parse(CntEvent.Start.ToString("yyyy-MM-dd ") + starttime + timezone);
if(CntEvent.End != null ){
var endtime = this.DefaultTime;
if(CntEvent.Endtime != ""){
endtime = CntEvent.Endtime+":00.1000000";
evnt.HasEndTime = true;
}
evnt.End = DateTimeOffset.Parse(CntEvent.End?.ToString("yyyy-MM-dd ") + endtime + timezone);
}
evnt.BodyPreview = evnt.Body = CntEvent.Body;
evnt.WebLink = CntEvent.WebLink;
evnt.Subject = CntEvent.Subject;
evnt.Location = CntEvent.Location;
evnt.Units = CntEvent.Units;
evnt.ProgramCategories = CntEvent.ProgramCategories;
CntEvent.ExtensionEventImages.ForEach(s => s.Created = DateTime.Now);
evnt.ExtensionEventImages = CntEvent.ExtensionEventImages;
this.context.Add(evnt);
this.context.SaveChanges();
this.Log(evnt,"CountyEvent", "County Event Added.", "CountyEvent");
return new OkObjectResult(new CountyEventWithTime(evnt));
}else{
this.Log( CntEvent,"CountyEvent", "Error in adding county event attempt.", "CountyEvent", "Error");
return new StatusCodeResult(500);
}
}
[HttpPut("updatecountyevent/{id}")]
[Authorize]
public IActionResult UpdateCountyEvent( int id, [FromBody] CountyEventWithTime CntEvent){
var evnt = context.CountyEvent.Where(a => a.Id == id)
.Include(a => a.Location)
.Include( a => a.ProgramCategories)
.Include( a => a.Units)
.Include( a => a.ExtensionEventImages)
.FirstOrDefault();
if(CntEvent != null && evnt != null ){
evnt.LastModifiedDateTime = DateTimeOffset.Now;
var starttime = this.DefaultTime;
evnt.IsAllDay = true;
var timezone = CntEvent.Etimezone ? " -04:00":" -05:00";
if(CntEvent.Starttime != null && CntEvent.Starttime != ""){
starttime = CntEvent.Starttime+":00.1000000";
evnt.IsAllDay = false;
evnt.HasStartTime = true;
}else{
evnt.HasEndTime = false;
}
evnt.Start = DateTimeOffset.Parse(CntEvent.Start.ToString("yyyy-MM-dd ") + starttime + timezone);
if(CntEvent.End != null ){
var endtime = this.DefaultTime;
if(CntEvent.Endtime != ""){
endtime = CntEvent.Endtime+":00.1000000";
evnt.HasEndTime = true;
}else{
evnt.HasEndTime = false;
}
evnt.End = DateTimeOffset.Parse(CntEvent.End?.ToString("yyyy-MM-dd ") + endtime + timezone);
}else{
evnt.End = null;
}
evnt.BodyPreview = evnt.Body = CntEvent.Body;
evnt.WebLink = CntEvent.WebLink;
evnt.Subject = CntEvent.Subject;
context.RemoveRange( evnt.ProgramCategories );
if(evnt.Location != null) context.Remove( evnt.Location );
evnt.Location = CntEvent.Location;
CntEvent.ExtensionEventImages.ForEach(s => s.Created = DateTime.Now);
if( evnt.ExtensionEventImages == null){
evnt.ExtensionEventImages = CntEvent.ExtensionEventImages;
}else{
evnt.ExtensionEventImages.AddRange(CntEvent.ExtensionEventImages);
}
evnt.Units = CntEvent.Units;
evnt.ProgramCategories = CntEvent.ProgramCategories;
this.Log(CntEvent,"CountyEvent", "County Event Updated.", "CountyEvent");
return new OkObjectResult(new CountyEventWithTime(evnt));
}else{
this.Log( CntEvent ,"CountyEvent", "Not Found CountyEvent in an update attempt.", "CountyEvent", "Error");
return new StatusCodeResult(500);
}
}
[HttpDelete("deletecountyevent/{id}")]
[Authorize]
public IActionResult DeleteExtensionEvent( int id ){
var entity = context.CountyEvent.Where(c => c.Id == id)
.Include( c => c.Units )
.Include( c => c.Location)
.Include( c => c.ExtensionEventImages)
.FirstOrDefault();
if(entity != null){
this.context.RemoveRange( this.context.CountyEventProgramCategory.Where(c => c.CountyEventId == id));
foreach( var im in entity.ExtensionEventImages ){
var imgs = this.context.UploadImage.Where( i => i.Id == im.UploadImageId).First();
this.context.Remove( this.context.UploadFile.Where( f => f.Id == imgs.UploadFileId).First());
this.context.Remove( imgs );
}
this.context.RemoveRange( entity.ExtensionEventImages);
if( entity.Location != null ) context.Remove(entity.Location);
context.CountyEvent.Remove(entity);
context.SaveChanges();
this.Log(entity,"CountyEvent", "CountyEvent Removed.", "CountyEvent");
return new OkResult();
}else{
this.Log( id ,"CountyEvent", "Not Found CountyEvent in a delete attempt.", "CountyEvent", "Error");
return new StatusCodeResult(500);
}
}
[HttpGet("migrate/{id}")]
public async Task<IActionResult> MigrateCountyEvent(int id){
try{
if( !(await context.CountyEvent.Where( t => t.classicCountyEventId == id).AnyAsync()) ){
var service = await this._reportingContext.zCesCountyEvent.Where( s => s.rID == id).FirstOrDefaultAsync();
if( service != null){
if( !this.context.CountyEvent.Where( t => t.classicCountyEventId == service.rID).Any() ){
var CountyEvent = ConvertCountyEvent(service);
this.context.Add(CountyEvent);
await this.context.SaveChangesAsync();
return new OkObjectResult(CountyEvent);
}
}
}
return new OkObjectResult(null);
}catch( Exception e ){
this.Log( e.Message ,"CountyEvent", "Migration Error.", "CountyEvent", "Error");
return new StatusCodeResult(500);
}
}
/*
[HttpGet("migrate/{id}")]
public async Task<IActionResult> MigrateCountyEvent(int id){
try{
if( !(await context.CountyEvent.Where( t => t.classicCountyEventId == id).AnyAsync()) ){
var service = await this.context.LegacyCountyEvents.Where( s => s.rID == id).FirstOrDefaultAsync();
if( service != null){
if( !this.context.CountyEvent.Where( t => t.classicCountyEventId == service.rID).Any() ){
var CountyEvent = ConvertCountyEvent(service);
this.context.Add(CountyEvent);
await this.context.SaveChangesAsync();
return new OkObjectResult(CountyEvent);
}
}
}
return new OkObjectResult(null);
}catch( Exception e ){
this.Log( e.Message ,"CountyEvent", "Migration Error.", "CountyEvent", "Error");
return new StatusCodeResult(500);
}
}
*/
[HttpGet("getlegacy/{limit}")]
public async Task<IActionResult> GetLegacyCountyEvents(int limit){
var leg = new List<zCesCountyEvent>();
var serv = _reportingContext.zCesCountyEvent
.Where( a => a.rDt != null
&&
a.rDt.Value.Year > 2019
&&
a.rDt.Value.Year < 2022
)
.OrderByDescending(r => r.rDt).ToListAsync();
foreach( var srv in await serv){
if( !context.CountyEvent.Where( t => t.classicCountyEventId == srv.rID).Any()){
leg.Add(srv);
}
}
/*
do{
var serv = await _reportingContext.zCesCountyEvent
.Where( a => a.rDt != null && a.rDt.Value.Year > 2018 )
.OrderBy(r => Guid.NewGuid()).LastAsync();
if( serv == null ) break;
if( !context.CountyEvent.Where( t => t.classicCountyEventId == serv.rID).Any()){
leg.Add(serv);
}
}while(leg.Count() < limit);
*/
/*
IQueryable<zCesCountyEvent> services;
List<int> converted = await context.CountyEvent.Where( t => t.classicCountyEventId != null && t.classicCountyEventId != 0).Select( t => t.classicCountyEventId??0).ToListAsync();
services = _reportingContext.zCesCountyEvent.Where( s => !converted.Contains( s.rID ));
var sc = await services.Take(limit).ToListAsync();
*/
return new OkObjectResult(leg);
}
/*
[HttpGet("getlegacy/{limit}/{notConverted?}/{order?}")]
public async Task<IActionResult> GetLegacyCountyEvents(int limit, Boolean notConverted = true, string order = "ASC"){
IOrderedQueryable<LegacyCountyEvents> services;
if( notConverted ){
List<int> converted = await context.CountyEvent.Where( t => t.classicCountyEventId != null && t.classicCountyEventId != 0).Select( t => t.classicCountyEventId??0).ToListAsync();
if( order == "ASC"){
services = context.LegacyCountyEvents.Where( s => !converted.Contains( s.rID )).OrderBy(a => a.rDt);
}else{
services = context.LegacyCountyEvents.Where( s => !converted.Contains( s.rID )).OrderByDescending(a => a.rDt);
}
}else{
if( order == "ASC"){
services = context.LegacyCountyEvents.OrderBy(a => a.rDt);
}else{
services = context.LegacyCountyEvents.OrderByDescending(a => a.rDt);
}
}
var sc = await services.Take(limit).ToListAsync();
return new OkObjectResult(sc);
} */
private CountyEvent ConvertCountyEvent( zCesCountyEvent legacy){
CountyEvent evnt = new CountyEvent();
evnt.Subject = legacy.eventTitle;
evnt.Body = evnt.BodyPreview = legacy.eventDescription;
evnt.classicCountyEventId = legacy.rID;
evnt.CreatedDateTime = Convert.ToDateTime(legacy.rDt);
evnt.LastModifiedDateTime = DateTimeOffset.Now;
var user = context.KersUser.Where( u => u.RprtngProfile.PersonId == legacy.rBy).FirstOrDefault();
if( user != null ){
evnt.Organizer = user;
}else{
evnt.OrganizerId = 2;
}
var unit = context.PlanningUnit.Where( u => u.Code == legacy.planningUnitID.ToString()).FirstOrDefault();
evnt.Units = new List<CountyEventPlanningUnit>();
bool isEastern = true;
if( unit != null){
var host = new CountyEventPlanningUnit();
host.CountyEvent = evnt;
host.PlanningUnitId = unit.Id;
host.IsHost = true;
evnt.Units.Add(host);
if( unit.TimeZoneId == "Central Standard Time" || unit.TimeZoneId == "America/Chicago"){
isEastern = false;
}
}
if(legacy.eventCounties != null && legacy.eventCounties != "NULL" && legacy.eventCounties != ""){
string[] cnts = legacy.eventCounties.Split(',');
foreach( var cnt in cnts){
if( cnt != ""){
var otherCounty = context.PlanningUnit.Where( u => u.Code == cnt ).FirstOrDefault();
if( otherCounty != null ){
var cntConnection = new CountyEventPlanningUnit();
cntConnection.PlanningUnitId = otherCounty.Id;
cntConnection.CountyEvent = evnt;
cntConnection.IsHost = false;
evnt.Units.Add(cntConnection);
}
}
}
}
var timezone = isEastern ? " -04:00":" -05:00";
var starttime = this.DefaultTime;
if(legacy.eventTimeBegin != null && legacy.eventTimeBegin != "" && legacy.eventTimeBegin != "NULL"){
starttime = legacy.eventTimeBegin.Insert(2, ":")+":00.1000000";
evnt.IsAllDay = false;
evnt.HasStartTime = true;
}else{
evnt.HasEndTime = false;
}
string[] beginDate = legacy.eventDateBegin.Split("/");
if(beginDate.Count() < 3 ) beginDate = legacy.eventDateBegin.Split("-");
if(beginDate[2].Count() < 3) beginDate[2] = "20"+beginDate[1];
evnt.Start = DateTimeOffset.Parse(beginDate[2] + "-" + beginDate[0] + "-" + beginDate[1] + " " + starttime + timezone);
if(
legacy.eventDateEnd != null
&&
legacy.eventDateEnd != "NULL"
&&
legacy.eventDateEnd != ""
&&
!(
legacy.eventDateEnd == legacy.eventDateBegin
&&
(legacy.eventTimeEnd == "NULL" || legacy.eventTimeEnd == null)
)
){
var endtime = this.DefaultTime;
if(legacy.eventTimeEnd != null && legacy.eventTimeEnd != "" && legacy.eventTimeEnd != "NULL"){
endtime = legacy.eventTimeEnd.Insert(2, ":")+":00.1000000";
evnt.HasEndTime = true;
}else{
evnt.HasEndTime = false;
}
string[] endDate = legacy.eventDateEnd.Split("/");
if(endDate.Count() < 3 ) endDate = legacy.eventDateEnd.Split("-");
if(endDate[2].Count() < 3) endDate[2] = "20"+endDate[1];
evnt.End = DateTimeOffset.Parse( endDate[2] + "-" + endDate[0] + "-" + endDate[1] + " " + endtime + timezone);
}else{
evnt.End = null;
}
if( legacy.eventUrl != "NULL" && legacy.eventUrl != "" && legacy.eventUrl != null){
evnt.WebLink = legacy.eventUrl;
}
evnt.ProgramCategories = new List<CountyEventProgramCategory>();
if(legacy.progANR == true || legacy.progHORT == true){
int? ANRcategoryId = context.ProgramCategory.Where( a => a.ShortName == "ANR").Select( c => c.Id ).FirstOrDefault();
if( ANRcategoryId != null ){
var AnrCat = new CountyEventProgramCategory();
AnrCat.ProgramCategoryId = ANRcategoryId??0;
AnrCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(AnrCat);
}
}
if(legacy.prog4HYD == true){
int? HcategoryId = context.ProgramCategory.Where( a => a.ShortName == "4-H").Select( c => c.Id ).FirstOrDefault();
if( HcategoryId != null ){
var HCat = new CountyEventProgramCategory();
HCat.ProgramCategoryId = HcategoryId??0;
HCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(HCat);
}
}
if(legacy.progFA == true){
int? FAcategoryId = context.ProgramCategory.Where( a => a.ShortName == "CED").Select( c => c.Id ).FirstOrDefault();
if( FAcategoryId != null ){
var FACat = new CountyEventProgramCategory();
FACat.ProgramCategoryId = FAcategoryId??0;
FACat.CountyEvent = evnt;
evnt.ProgramCategories.Add(FACat);
}
}
if(legacy.progFCS == true){
int? FCScategoryId = context.ProgramCategory.Where( a => a.ShortName == "FCS").Select( c => c.Id ).FirstOrDefault();
if( FCScategoryId != null ){
var FCSCat = new CountyEventProgramCategory();
FCSCat.ProgramCategoryId = FCScategoryId??0;
FCSCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(FCSCat);
}
}
if(legacy.progOther == true){
int? OcategoryId = context.ProgramCategory.Where( a => a.ShortName == "OTHR").Select( c => c.Id ).FirstOrDefault();
if( OcategoryId != null ){
var OCat = new CountyEventProgramCategory();
OCat.ProgramCategoryId = OcategoryId??0;
OCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(OCat);
}
}
evnt.Location = ProcessAddress(legacy, unit);
return evnt;
}
/*
private CountyEvent ConvertCountyEvent( LegacyCountyEvents legacy){
CountyEvent evnt = new CountyEvent();
evnt.Subject = legacy.eventTitle;
evnt.Body = evnt.BodyPreview = legacy.eventDescription;
evnt.classicCountyEventId = legacy.rID;
evnt.CreatedDateTime = Convert.ToDateTime(legacy.rDt);
evnt.LastModifiedDateTime = DateTimeOffset.Now;
var unit = context.PlanningUnit.Where( u => u.Code == legacy.planningUnitID.ToString()).FirstOrDefault();
evnt.Units = new List<CountyEventPlanningUnit>();
bool isEastern = true;
if( unit != null){
var host = new CountyEventPlanningUnit();
host.CountyEvent = evnt;
host.PlanningUnitId = unit.Id;
host.IsHost = true;
evnt.Units.Add(host);
if( unit.TimeZoneId == "Central Standard Time" || unit.TimeZoneId == "America/Chicago"){
isEastern = false;
}
}
if(legacy.eventCounties != null && legacy.eventCounties != "NULL" && legacy.eventCounties != ""){
string[] cnts = legacy.eventCounties.Split(',');
foreach( var cnt in cnts){
if( cnt != ""){
var otherCounty = context.PlanningUnit.Where( u => u.Code == cnt ).FirstOrDefault();
if( otherCounty != null ){
var cntConnection = new CountyEventPlanningUnit();
cntConnection.PlanningUnitId = otherCounty.Id;
cntConnection.CountyEvent = evnt;
cntConnection.IsHost = false;
evnt.Units.Add(cntConnection);
}
}
}
}
var timezone = isEastern ? " -04:00":" -05:00";
var starttime = this.DefaultTime;
if(legacy.eventTimeBegin != null && legacy.eventTimeBegin != "" && legacy.eventTimeBegin != "NULL"){
starttime = legacy.eventTimeBegin.Insert(2, ":")+":00.1000000";
evnt.IsAllDay = false;
evnt.HasStartTime = true;
}else{
evnt.HasEndTime = false;
}
string[] beginDate = legacy.eventDateBegin.Split("/");
evnt.Start = DateTimeOffset.Parse(beginDate[2] + "-" + beginDate[0] + "-" + beginDate[1] + " " + starttime + timezone);
if(
legacy.eventDateEnd != null
&&
legacy.eventDateEnd != "NULL"
&&
legacy.eventDateEnd != ""
&&
!(
legacy.eventDateEnd == legacy.eventDateBegin
&&
(legacy.eventTimeEnd == "NULL" || legacy.eventTimeEnd == null)
)
){
var endtime = this.DefaultTime;
if(legacy.eventTimeEnd != null && legacy.eventTimeEnd != "" && legacy.eventTimeEnd != "NULL"){
endtime = legacy.eventTimeEnd.Insert(2, ":")+":00.1000000";
evnt.HasEndTime = true;
}else{
evnt.HasEndTime = false;
}
string[] endDate = legacy.eventDateEnd.Split("/");
evnt.End = DateTimeOffset.Parse( endDate[2] + "-" + endDate[0] + "-" + endDate[1] + " " + endtime + timezone);
}else{
evnt.End = null;
}
if( legacy.eventUrl != "NULL" && legacy.eventUrl != "" && legacy.eventUrl != null){
evnt.WebLink = legacy.eventUrl;
}
evnt.ProgramCategories = new List<CountyEventProgramCategory>();
if(legacy.progANR == 1 || legacy.progHORT == 1){
int? ANRcategoryId = context.ProgramCategory.Where( a => a.ShortName == "ANR").Select( c => c.Id ).FirstOrDefault();
if( ANRcategoryId != null ){
var AnrCat = new CountyEventProgramCategory();
AnrCat.ProgramCategoryId = ANRcategoryId??0;
AnrCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(AnrCat);
}
}
if(legacy.prog4HYD == 1){
int? HcategoryId = context.ProgramCategory.Where( a => a.ShortName == "4-H").Select( c => c.Id ).FirstOrDefault();
if( HcategoryId != null ){
var HCat = new CountyEventProgramCategory();
HCat.ProgramCategoryId = HcategoryId??0;
HCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(HCat);
}
}
if(legacy.progFA == 1){
int? FAcategoryId = context.ProgramCategory.Where( a => a.ShortName == "CED").Select( c => c.Id ).FirstOrDefault();
if( FAcategoryId != null ){
var FACat = new CountyEventProgramCategory();
FACat.ProgramCategoryId = FAcategoryId??0;
FACat.CountyEvent = evnt;
evnt.ProgramCategories.Add(FACat);
}
}
if(legacy.progFCS == 1){
int? FCScategoryId = context.ProgramCategory.Where( a => a.ShortName == "FCS").Select( c => c.Id ).FirstOrDefault();
if( FCScategoryId != null ){
var FCSCat = new CountyEventProgramCategory();
FCSCat.ProgramCategoryId = FCScategoryId??0;
FCSCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(FCSCat);
}
}
if(legacy.progOther == 1){
int? OcategoryId = context.ProgramCategory.Where( a => a.ShortName == "OTHR").Select( c => c.Id ).FirstOrDefault();
if( OcategoryId != null ){
var OCat = new CountyEventProgramCategory();
OCat.ProgramCategoryId = OcategoryId??0;
OCat.CountyEvent = evnt;
evnt.ProgramCategories.Add(OCat);
}
}
evnt.Location = ProcessAddress(legacy, unit);
return evnt;
}
*/
private ExtensionEventLocation ProcessAddress( zCesCountyEvent legacy, PlanningUnit unit ){
var Location = new ExtensionEventLocation();
Location.Address = new PhysicalAddress();
Location.Address.Building = legacy.eventBldgName;
Location.Address.City = legacy.eventCity;
Location.Address.PostalCode = legacy.eventZip;
Location.Address.State = legacy.eventState;
Location.Address.Street = legacy.eventAddress;
if( unit != null ){
if(
!context.ExtensionEventLocationConnection
.Where( u =>
u.PlanningUnitId == unit.Id
&&
legacy.eventBldgName == "" ?
u.ExtensionEventLocation.Address.Street == legacy.eventAddress
:
u.ExtensionEventLocation.Address.Building == legacy.eventBldgName
)
.Any()
){
var loc = new ExtensionEventLocationConnection();
loc.ExtensionEventLocation = new ExtensionEventLocation();
loc.PlanningUnitId = unit.Id;
loc.ExtensionEventLocation.Address = new PhysicalAddress();
loc.ExtensionEventLocation.Address.Building = legacy.eventBldgName;
loc.ExtensionEventLocation.Address.City = legacy.eventCity;
loc.ExtensionEventLocation.Address.PostalCode = legacy.eventZip;
loc.ExtensionEventLocation.Address.State = legacy.eventState;
loc.ExtensionEventLocation.Address.Street = legacy.eventAddress == "NULL" ? null : legacy.eventAddress;
context.ExtensionEventLocationConnection.Add(loc);
context.SaveChanges();
}
return Location;
}
return null;
}
public IActionResult Error()
{
return View();
}
}
public class CountyEventWithTime:CountyEvent{
public string Starttime;
public string Endtime;
public bool Etimezone;
public CountyEventWithTime(){}
public CountyEventWithTime(CountyEvent m){
this.Id = m.Id;
this.Body = m.Body;
this.BodyPreview = m.BodyPreview;
this.Start = m.Start;
this.End = m.End;
this.IsAllDay = m.IsAllDay;
this.CreatedDateTime = m.CreatedDateTime;
this.LastModifiedDateTime = m.LastModifiedDateTime;
this.Subject = m.Subject;
this.IsCancelled = m.IsCancelled;
this.HasEndTime = m.HasEndTime;
this.HasStartTime = m.HasStartTime;
this.Units = m.Units;
this.ProgramCategories = m.ProgramCategories;
this.WebLink = m.WebLink;
this.Location = m.Location;
if(m.End != null){
TimeSpan tmzn = m.Start.Offset;
var hrs = tmzn.TotalHours;
this.Etimezone = hrs == -4;
if(this.End.HasValue ){
this.Endtime = this.End.Value.Hour.ToString("D2")+ ":" + this.End.Value.Minute.ToString("D2");
}
}
this.Starttime = this.Start.Hour.ToString("D2") + ":" + this.Start.Minute.ToString("D2");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bezlebub
{
public interface Locatable
{
int x { get; set; }
int y { get; set; }
}
public class StaticLocation : Locatable
{
public int x
{
get;
set;
}
public int y
{
get;
set;
}
public StaticLocation(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class BoundedLocation : Locatable
{
public int xMax
{
get;
set;
}
public int xMin
{
get;
set;
}
public int yMax
{
get;
set;
}
public int yMin
{
get;
set;
}
private int _x;
public int x
{
get
{
return _x;
}
set
{
if(value > xMax || value < xMin)
{
throw new ArgumentException("X setting out of bounds");
}
_x = value;
}
}
private int _y;
public int y
{
get
{
return _y;
}
set
{
if(value > yMax || value < yMin)
{
throw new ArgumentException("Y setting out of bounds");
}
_y = value;
}
}
public BoundedLocation(int x, int y, int xMax, int xMin, int yMax, int yMin)
{
this.x = x;
this.y = y;
this.xMax = xMax;
this.xMin = xMin;
this.yMax = yMax;
this.yMin = yMin;
}
}
}
|
namespace TicTacToe
{
public interface IPlayerReceiver
{
TicTacState[,] Grid { get; }
void MakeTurn(TicTacState state, int coordinateX, int coordinateY);
}
} |
namespace otus_architecture_lab_8
{
public class FileParserTxt : FileParcerBase
{
#region Methods
protected override bool CanParce(string path)
{
return path.EndsWith(".txt");
}
protected override void Parce(string path)
{
SimpleServiceLocator.Instance.GetService<ILogger>().Log($"FileParserTxt parce: {path}");
}
#endregion
}
}
|
using System;
namespace ten_guesses
{
class Program
{
static void Main(string[] args)
{
// Set a secret number to 653.
// Then program will then loop,
// where each loop will ask the user to enter what they think a secret integer is.
//If they get it right, print "Correct",
// otherwise print "Wrong, counter value is ".
// Give the user 10 chances to guess.
// Hint: You will need an if statement inside the loop.
//Bonus: Make the secret number randomly generate between 1 and 1000 each time the program is run.
// For bonus
Random random = new Random();
int secretNumber = random.Next(1,1000);
// int secretNumber = 653;
int userGuess = 0;
int guesses = 0;
int maxGuesses = 10;
int guessesRemaining;
while (secretNumber != userGuess && guesses < maxGuesses) {
System.Console.WriteLine("Guess the Secret Number!");
bool validInput = int.TryParse(Console.ReadLine(), out userGuess);
guesses += 1;
if (userGuess == secretNumber) {
System.Console.WriteLine("Got it!");
}
else {
System.Console.WriteLine("Not quite!");
guessesRemaining = maxGuesses - guesses;
if (guessesRemaining == 0) {
System.Console.WriteLine("All out of guesses!");
}
else {
System.Console.WriteLine("You have {0} guesses remaining!", guessesRemaining);
}
}
}
if (guesses == 10 && userGuess != secretNumber) {
System.Console.WriteLine("Better luck next time!");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectManipulation : MonoBehaviour
{
public Camera playerCam;
public GameObject selected;
public float rotationSpeed;
public bool leftClick;
public bool rightClick;
public float yaw;
public float pitch;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
leftClick = Input.GetMouseButton(0);
rightClick = Input.GetMouseButton(1);
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log(hit.transform.gameObject.name);
selected = hit.transform.gameObject;
}
}
if (Input.GetMouseButton(1) && selected != null)
{
yaw += Input.GetAxis("Mouse X") * rotationSpeed * -1;
pitch += Input.GetAxis("Mouse Y") * rotationSpeed;
selected.transform.eulerAngles = new Vector3(pitch, yaw, 0);
}
}
}
|
using FluentAssertions;
using System;
using System.Collections.Generic;
using Xunit;
namespace TDD_GarbageParser
{
public class GarbagePaserTest
{
[Fact]
public void ShouldParseSingleWord()
{
Parse("VIENNA").Should().Contain("VIENNA");
Parse("BOTTLE").Should().Contain("BOTTLE");
}
[Fact]
public void ShouldTransformToUppercase()
{
Parse("bottle").Should().Contain("BOTTLE");
}
[Fact]
public void ShouldRemovePlural()
{
Parse("bottles").Should().Contain("BOTTLE");
}
[Fact]
public void ShouldParseMultipleWords()
{
Parse("bottles,Vienna").Should().Equal("BOTTLE", "VIENNA");
}
private IList<string> Parse(string inputValues)
{
var values = inputValues.Split(',');
var parsedResults = new List<string>();
foreach(var value in values)
{
inputValues = RemovePlural(inputValues);
parsedResults.Add(inputValues.ToUpper());
}
return parsedResults;
}
private static string RemovePlural(string inputValues)
{
if (IsPlural(inputValues))
{
inputValues = inputValues.Remove(inputValues.Length - 1);
}
return inputValues;
}
private static bool IsPlural(string inputValues)
{
return inputValues.EndsWith('s');
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Net.Mail;
using HSoft.SQL;
using Obout.ComboBox;
using Obout.Grid;
using HSoft.ClientManager.Web;
public partial class Pages_Email_Promo_Send : System.Web.UI.Page
{
Grid grid1 = new Grid();
DataTable _dtPromos = new DataTable();
DateTime _dtlimit = DateTime.Now.Date.AddDays(1);
protected void Page_PreRender(object sender, EventArgs e)
{
if (Session["wx"] == null) { Session["wx"] = Request.QueryString["wx"]; }
if (Session["wy"] == null) { Session["wy"] = Request.QueryString["wy"]; }
}
protected void Page_Load(object sender, EventArgs e)
{
Tools.devlogincheat();
if (Session["ghirarchy"] == null) { Session["ghirarchy"] = String.Format("{0},", Session["guser"]); }
String ssql = String.Empty;
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
if (_dtPromos.Rows.Count==0)
{
ssql = "SELECT ep.*,e.EmailDescription " +
" FROM Email_Promo ep,Email e " +
" WHERE ep.isactive = 1 " +
" AND ep.isdeleted = 0 " +
" AND e.isdeleted = 0 " +
" AND ep.EmailId = e.Id " +
" ORDER BY EmailKey";
_dtPromos = _sql.GetTable(ssql);
}
grid1.ID = "grid1";
grid1.CallbackMode = false;
grid1.Serialize = true;
grid1.AutoGenerateColumns = false;
grid1.PageSize = -1;
// grid1.Height = int.Parse(Session["wy"].ToString()) - 40;
grid1.AllowAddingRecords = false;
grid1.AllowPaging = false;
grid1.FolderStyle = "styles/grid/premiere_blue";
grid1.UpdateCommand += new Obout.Grid.Grid.EventHandler(UpdateRecord);
grid1.Rebind += new Obout.Grid.Grid.DefaultEventHandler(RebindGrid);
grid1.RowCreated += new Obout.Grid.GridRowEventHandler(grid1_RowCreated);
grid1.ClientSideEvents.OnClientSelect = "onClientSelect";
// grid filter
GridFilteringSettings gfs = new GridFilteringSettings();
gfs.FilterPosition = GridFilterPosition.Top;
gfs.FilterLinksPosition = GridElementPosition.Top;
// gfs.InitialState = GridFilterState.Visible;
gfs.InitialState = GridFilterState.Hidden;
grid1.FilteringSettings = gfs;
grid1.AllowFiltering = true;
Column oCol0 = new Column();
oCol0.DataField = "";
oCol0.HeaderText = "";
oCol0.Width = "45";
oCol0.AllowEdit = true;
oCol0.AllowDelete = false;
Column oColi = new Column();
oColi.ID = "ID";
oColi.DataField = "Id";
oColi.Visible = false;
Column oCol1 = new Column();
oCol1.ID = "Name";
oCol1.DataField = "Name";
oCol1.HeaderText = "Name";
oCol1.Visible = true;
oCol1.ReadOnly = true;
oCol1.Width = "120";
oCol1.AllowSorting = true;
oCol1.Wrap = true;
oCol1.AllowFilter = true;
oCol1.FilterOptions.Add(new FilterOption(FilterOptionType.NoFilter));
oCol1.FilterOptions.Add(new FilterOption(FilterOptionType.Contains));
oCol1.FilterOptions.Add(new FilterOption(FilterOptionType.EqualTo));
oCol1.FilterOptions.Add(new FilterOption(FilterOptionType.StartsWith));
oCol1.FilterOptions.Add(new FilterOption(FilterOptionType.EndsWith));
Column oCol2 = new Column();
oCol2.ID = "Email";
oCol2.DataField = "Email";
oCol2.HeaderText = "Email";
oCol2.Visible = true;
oCol2.ReadOnly = true;
oCol2.Width = "180";
oCol2.AllowSorting = true;
oCol2.AllowFilter = true;
oCol2.FilterOptions.Add(new FilterOption(FilterOptionType.NoFilter));
oCol2.FilterOptions.Add(new FilterOption(FilterOptionType.Contains));
oCol2.FilterOptions.Add(new FilterOption(FilterOptionType.EqualTo));
oCol2.FilterOptions.Add(new FilterOption(FilterOptionType.StartsWith));
oCol2.FilterOptions.Add(new FilterOption(FilterOptionType.EndsWith));
grid1.Columns.Add(oCol0);
grid1.Columns.Add(oColi);
grid1.Columns.Add(oCol1);
List<CheckBoxColumn> oCole = new List<CheckBoxColumn>();
foreach (DataRow dr in _dtPromos.Rows)
{
CheckBoxColumn _col = new CheckBoxColumn(); ;
_col.ID = String.Format("em{0}", dr["EmailKey"]);
_col.DataField = String.Format("em{0}", dr["EmailKey"]);
_col.HeaderText = dr["EmailKey"].ToString();
_col.Visible = true;
_col.ReadOnly = false;
_col.Width = "40";
_col.AllowSorting = true;
_col.AllowFilter = false;
_col.ControlType = GridControlType.Obout;
oCole.Add(_col);
grid1.Columns.Add(_col);
}
Column oCol5 = new Column();
oCol5.ID = "EntryDate";
oCol5.DataField = "EntryDate";
oCol5.HeaderText = "Entry Date";
oCol5.Visible = true;
oCol5.ReadOnly = true;
oCol5.Width = "80";
oCol5.AllowSorting = true;
oCol5.AllowFilter = false;
oCol5.NullDisplayText = "missing!";
oCol5.DataFormatString = "{0:MM/dd/yyyy hh:mm tt}";
oCol5.DataFormatString = "{0:MM/dd/yyyy}";
Column oCol8 = new Column();
oCol8.ID = "Status";
oCol8.DataField = "Status";
oCol8.HeaderText = "Status";
oCol8.Visible = true;
oCol8.ReadOnly = true;
oCol8.Width = "90";
oCol8.AllowSorting = true;
oCol8.AllowFilter = false;
Column oCol9 = new Column();
oCol9.ID = "Priority";
oCol9.DataField = "Priority";
oCol9.HeaderText = "Priority";
oCol9.Visible = true;
oCol9.ReadOnly = true;
oCol9.Width = "100";
oCol9.AllowSorting = true;
oCol9.AllowFilter = false;
Column oCol10 = new Column();
oCol10.ID = "AssignedTo";
oCol10.DataField = "AssignedTo";
oCol10.HeaderText = "AssignedTo";
oCol10.Visible = true;
oCol10.ReadOnly = false;
oCol10.Width = "120";
oCol10.AllowSorting = false;
oCol10.AllowFilter = false;
Column oCol11 = new Column();
oCol11.ID = "LeadNote";
oCol11.DataField = "LeadNote";
oCol11.HeaderText = "Lead Note";
oCol11.Visible = true;
oCol11.ReadOnly = true;
oCol11.Width = "350";
oCol11.Wrap = true;
oCol11.AllowSorting = false;
oCol11.ParseHTML = true;
oCol11.AllowFilter = true;
oCol11.FilterOptions.Add(new FilterOption(FilterOptionType.NoFilter));
oCol11.FilterOptions.Add(new FilterOption(FilterOptionType.Contains));
Column oCol12 = new Column();
oCol12.ID = "SalesNote";
oCol12.DataField = "SalesNote";
oCol12.HeaderText = "Sales Note";
oCol12.Visible = true;
oCol12.ReadOnly = true;
oCol12.Width = "350";
oCol12.Wrap = true;
oCol12.AllowSorting = false;
oCol12.ParseHTML = true;
oCol12.AllowFilter = true;
oCol12.FilterOptions.Add(new FilterOption(FilterOptionType.NoFilter));
oCol12.FilterOptions.Add(new FilterOption(FilterOptionType.Contains));
grid1.Columns.Add(oCol5);
grid1.Columns.Add(oCol9);
grid1.Columns.Add(oCol11);
grid1.Columns.Add(oCol12);
grid1.Columns.Add(oCol8);
grid1.Columns.Add(oCol2);
grid1.Columns.Add(oCol10);
GridRuntimeTemplate HeadingTemplate = new GridRuntimeTemplate();
HeadingTemplate.ID = "HeadingTemplate1";
HeadingTemplate.Template = new Obout.Grid.RuntimeTemplate();
HeadingTemplate.Template.CreateTemplate += new Obout.Grid.GridRuntimeTemplateEventHandler(CreateHeadingTemplate);
grid1.TemplateSettings.HeadingTemplateId = "HeadingTemplate1";
grid1.Templates.Add(HeadingTemplate);
// add the grid to the controls collection of the PlaceHolder
phGrid1.Controls.Add(grid1);
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void grid1_RowCreated(object sender, GridRowEventArgs e)
{
int icount = 3;
if (e.Row.RowType == GridRowType.Header)
{
foreach (DataRow dr in _dtPromos.Rows)
{
e.Row.Cells[icount++].ToolTip = dr["EmailDescription"].ToString();
}
}
if (e.Row.RowType == GridRowType.DataRow)
{
// if (e.Row.Cells[16].Text == "0")
// {
// e.Row.Cells[0].BackColor = System.Drawing.Color.Red;
// e.Row.Cells[1]..Text = "test"; // e.Row.Cells[5].Text;
// }
}
}
public void CreateHeadingTemplate(Object sender, Obout.Grid.GridRuntimeTemplateEventArgs e)
{
List<ComboBox> _listComboBox = new List<ComboBox>();
_listComboBox.Add(new ComboBox());
_listComboBox[0].ID = String.Format("Header");
_listComboBox[0].Width = Unit.Pixel(150);
_listComboBox[0].Height = Unit.Pixel(15);
_listComboBox[0].Mode = ComboBoxMode.TextBox;
_listComboBox[0].Enabled = false;
_listComboBox[0].Items.Add(new ComboBoxItem("Lead Emails"));
_listComboBox[0].SelectedIndex = 0;
e.Container.Controls.Add(_listComboBox[0]);
}
void BindGrid()
{
String ssql = String.Empty;
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
String sassigned = Session["ghirarchy"].ToString();
sassigned = String.Format("{0}{1}", sassigned.Replace(",", "','"), Guid.Empty);
ssql = "SELECT TOP 50 ";
foreach (DataRow dr in _dtPromos.Rows)
{
ssql = String.Format("{0} " +
"(SELECT CONVERT(BIT,COUNT(*)) FROM Email_Lead el WHERE el.isdeleted = 0 AND el.LeadId = lf.Id AND UPPER(el.EmailId) = '{1}') em{2}, ",ssql,dr["EmailId"].ToString().ToUpper(),dr["EmailKey"]);
}
ssql = String.Format("{0} * " +
" FROM Lead_Flat lf, _LeadPriority lp " + // , _email_verify ev" +
" WHERE lf.isdeleted=0 " +
" AND PriorityId = lp.Id " +
" AND lp.[IsLead] = 1 " +
" AND lp.isdeleted = 0 " +
" AND lf.AssignedToId IN ('{1}') " +
// " AND lf.Customer = 5985 " +
// " AND ev.Email = lf.Email " +
// " AND ((ev.isValidated = 0) OR (ev.isValidated = 1 AND ev.iserror=0)) " +
" AND EntryDate <= '{2}' " +
" ORDER BY EntryDate DESC ", ssql, sassigned,_dtlimit);
DataTable _dtLeads = _sql.GetTable(ssql);
grid1.DataSource = _dtLeads;
grid1.DataBind();
_sql.Close();
}
void RebindGrid(object sender, EventArgs e) { BindGrid(); }
void UpdateRecord(object sender, GridRecordEventArgs e)
{
_dtlimit = DateTime.Parse(e.Record["EntryDate"].ToString()).Date.AddDays(1);
String ssql = String.Empty;
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
ssql = "SELECT ";
foreach (DataRow dr in _dtPromos.Rows)
{
ssql = String.Format("{0} " +
"(SELECT CONVERT(BIT,COUNT(*)) FROM Email_Lead el WHERE el.isdeleted = 0 AND el.LeadId = lf.Id AND UPPER(el.EmailId) = '{1}') em{2}, ", ssql, dr["EmailId"].ToString().ToUpper(), dr["EmailKey"]);
}
ssql = String.Format("{0} * " +
" FROM Lead_Flat lf, _LeadPriority lp " +
" WHERE lf.isdeleted=0 " +
" AND PriorityId = lp.Id " +
" AND lp.[IsLead] = 1 " +
" AND lp.isdeleted = 0 " +
" AND lf.Id = '{1}' " +
" ORDER BY EntryDate DESC ", ssql,e.Record["Id"].ToString());
DataRow _dtLead = _sql.GetTable(ssql).Rows[0];
DataRow _emp = _sql.GetTable(String.Format("SELECT * FROM Employee WHERE Id = '{0}'", _dtLead["AssignedToId"])).Rows[0];
String strName = _dtLead["Name"].ToString();
String stremail = _emp["EmailName"].ToString();
String strSignature = _emp["DisplayName"].ToString();
MailAddress _smtpfrom = new MailAddress(String.Format("emailer@uncleharry.biz", stremail), "Sales Uncleharry");
MailAddress _from = new MailAddress(String.Format("{0}@uncleharry.biz", stremail), "Sales Uncleharry");
MailAddress _to = new MailAddress(String.Format("{0}", _dtLead["EMail"]), strName);
// _to = new MailAddress("tatyana@uncleharry.biz", strName); // send to Tatyana for testing
// _to = new MailAddress("rene.hugentobler@gmail.com", strName);
MailAddress _sender = new MailAddress(String.Format("{0}@uncleharry.biz", stremail), "Sales Uncleharry");
SortedList<int, int> _emails = new SortedList<int, int>();
foreach (String _num in _dtLead["MsgHistory"].ToString().Split(','))
{
if (_num.Trim().Length > 0) { _emails.Add(int.Parse(_num.Trim()), int.Parse(_num.Trim())); }
}
Boolean _new = false;
foreach (DataRow dr in _dtPromos.Rows)
{
string ekey = String.Format("em{0}", dr["EmailKey"]);
if (_dtLead[ekey].ToString().ToLower() == "false")
{
if (e.Record[ekey].ToString().ToLower() == "true")
{
_new = true;
_emails.Add(int.Parse(ekey.ToLower().Split('m')[1]), int.Parse(ekey.ToLower().Split('m')[1]));
DataRow _drEmail = _sql.GetTable(String.Format("SELECT e.* FROM Email e, Email_Promo ep WHERE e.isdeleted = 0 AND ep.isdeleted = 0 AND ep.isactive = 1 AND ep.EmailKey = {0} AND ep.EmailId = e.Id", dr["EmailKey"])).Rows[0];
String sEmail = String.Format(_drEmail["EmailBody"].ToString(), strName, strSignature, stremail);
String ssubject = _drEmail["EmailSubject"].ToString();
try
{
Tools.sendMail(_smtpfrom, @"Taurec86@",_from, _to, ssubject, sEmail, true);
// SMTPServer.Send(message);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("{0}", ex.Message));
// ClientScript.RegisterStartupScript(this.GetType(), "newWindow", "OpenPopupWithHtml('" + ex.Message + "', 'ERROR');");
// return;
throw ex2;
}
ssql = String.Format("INSERT INTO Email_Lead(EmailId, LeadId, EmployeeId) VALUES ('{0}','{1}','{2}')", _drEmail["Id"], e.Record["Id"], Session["guser"]);
_sql.Execute(ssql);
}
}
}
if (_new)
{
String _history = String.Empty;
foreach (KeyValuePair<int, int> _key in _emails)
{
_history = String.Format("{0}{1},", _history, _key.Value);
}
ssql = String.Format("UPDATE t SET MsgHistory = '{0}' FROM Lead_Flat t WHERE Id = '{1}' ", _history.Substring(0, _history.Length - 1), e.Record["Id"]);
_sql.Execute(ssql);
}
// SMTPServer.Dispose();
_sql.Close();
}
} |
using GlobalDevelopment.SocialNetworks.Facebook.Interfaces;
using GlobalDevelopment.SocialNetworks.Facebook.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace GlobalDevelopment.Helpers
{
public static class FacebookHelper
{
public static string Get(string id, string accessToken)
{
string json = "Error";
try
{
HttpWebRequest request = WebRequest.Create(FacebookApi.ResourceUrl + id + "&access_token=" + accessToken) as HttpWebRequest;
/*using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return json = WebHelper.ReadResponse(response);
}*/
return WebHelper.ReadResponse(request.GetResponse());
}
catch(WebException er)
{
return json = WebHelper.ReadResponse(er.Response);
}
}
public static string GetField(string accessToken, string field)
{
string result = "Failed!";
try
{
HttpWebRequest request = WebRequest.Create(FacebookApi.ResourceUrl + "me?fields=" + field + "&access_token=" + accessToken) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
string jsonString = vals;
JToken ob = null;
var json = JObject.Parse(jsonString);
if (json.TryGetValue(field, out ob))
{
result = ob.ToString();
}
}
} catch(WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
return result;
}
public static string GetField(string target, string accessToken, string fields)
{
string result = "Failed!";
try
{
HttpWebRequest request = null;
if(fields == "" || fields == null)
{
request = WebRequest.Create(FacebookApi.ResourceUrl + target + "?access_token=" + accessToken) as HttpWebRequest;
} else
{
request = WebRequest.Create(FacebookApi.ResourceUrl + target + "?fields=" + fields + "&access_token=" + accessToken) as HttpWebRequest;
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
JToken ob = null;
var json = JObject.Parse(vals);
if (json.TryGetValue(fields, out ob))
{
result = ob.ToString();
} else
{
result = json.ToString();
}
}
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
return result;
}
public static string GetFieldJson(string accessToken, string fields)
{
string result = "Failed!";
try
{
HttpWebRequest request = null;
if (fields == "" || fields == null)
{
request = WebRequest.Create(FacebookApi.ResourceUrl + "me" + "?access_token=" + accessToken) as HttpWebRequest;
}
else
{
request = WebRequest.Create(FacebookApi.ResourceUrl + "me" + "?fields=" + fields + "&access_token=" + accessToken) as HttpWebRequest;
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
return result;
}
public static string GetFieldJson(string target, string accessToken, string fields)
{
string result = "Failed!";
try
{
HttpWebRequest request = null;
if (fields == "" || fields == null)
{
request = WebRequest.Create(FacebookApi.ResourceUrl + target + "?access_token=" + accessToken) as HttpWebRequest;
}
else
{
request = WebRequest.Create(FacebookApi.ResourceUrl + target + "?fields=" + fields + "&access_token=" + accessToken) as HttpWebRequest;
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
return result;
}
public static string GetEdge(string id, string edge)
{
WebResponse response = null;
string result = string.Empty;
try
{
WebRequest request = WebRequest.Create(string.Format(FacebookApi.ResourceUrl + "{0}/" + edge, id));
response = request.GetResponse();
result = response.ResponseUri.ToString();
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
finally
{
if (response != null) response.Close();
}
return result;
}
public static string GetEdge(string id, string edge, string accessToken)
{
WebResponse response = null;
string result = string.Empty;
try
{
WebRequest request = WebRequest.Create(string.Format(FacebookApi.ResourceUrl + "{0}/" + edge + "?access_token=" + accessToken, id));
response = request.GetResponse();
result = response.ResponseUri.ToString();
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
finally
{
if (response != null) response.Close();
}
return result;
}
public static string GetEdgeJson(string id, string edge)
{
WebResponse response = null;
string result = string.Empty;
try
{
WebRequest request = WebRequest.Create(string.Format(FacebookApi.ResourceUrl + "{0}/" + edge, id));
response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
finally
{
if (response != null) response.Close();
}
return result;
}
public static string GetEdgeJson(string id, string edge, string accessToken)
{
WebResponse response = null;
string result = string.Empty;
try
{
WebRequest request = WebRequest.Create(string.Format(FacebookApi.ResourceUrl + "{0}/" + edge + "?access_token=" + accessToken, id));
response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
finally
{
if (response != null) response.Close();
}
return result;
}
public static string GetEdgeJson(string id, string edge, string fields, string accessToken)
{
WebResponse response = null;
string result = string.Empty;
try
{
WebRequest request = WebRequest.Create(string.Format(FacebookApi.ResourceUrl + "{0}/" + edge + "?fields=" + fields + "&access_token=" + accessToken, id));
response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
catch (WebException er)
{
StreamReader reader = new StreamReader(er.Response.GetResponseStream());
string vals = reader.ReadToEnd();
result = vals;
}
finally
{
if (response != null) response.Close();
}
return result;
}
public static string Authorization(string url, string appID, string appSecret, string permissionScope)
{
string accessToken = "Invalid AccessToken";
Dictionary<string, string> QueryString = new Dictionary<string, string>();
QueryString.Add("client_id", appID);
QueryString.Add("redirect_uri", url);
QueryString.Add("scope", permissionScope);
if(HttpContext.Current.Request["code"] == null)
{
HttpContext.Current.Response.Redirect(FacebookApi.AuthorizeUrl + WebHelper.QueryBuilder(QueryString));
} else
{
QueryString.Add("code", WebHelper.GetQueryValue("code"));
QueryString.Add("client_secret", appSecret);
Dictionary<string, string> Tokens = new Dictionary<string, string>();
string responseUrl = FacebookApi.AccessTokenUrl + WebHelper.QueryBuilder(QueryString);
HttpWebRequest request = WebRequest.Create(responseUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string vals = WebHelper.ReadResponse(response);
foreach (string token in vals.Split('&'))
{
Tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
accessToken = Tokens["access_token"];
}
return accessToken;
}
public static JObject GetUser(string accessToken)
{
JObject UserJson = null;
HttpWebRequest request = WebRequest.Create(FacebookApi.ResourceUrl + "me?fields=" + FacebookApi.UserFields + "&access_token=" + accessToken) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string vals = WebHelper.ReadResponse(response);
UserJson = JObject.Parse(vals);
}
return UserJson;
}
public static JObject GetUser(string id, string accessToken)
{
JObject UserJson = null;
HttpWebRequest request = WebRequest.Create(FacebookApi.ResourceUrl + id +"?fields=" + FacebookApi.UserFields + "&access_token=" + accessToken) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string vals = WebHelper.ReadResponse(response);
UserJson = JObject.Parse(vals);
}
return UserJson;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VKDesktop.Api;
namespace VKDesktop.Start
{
/// <summary>
/// Interaction logic for AuthorisationDialog.xaml
/// </summary>
public partial class AuthorisationDialog : Window
{
public AuthorisationDialog()
{
InitializeComponent();
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
authorisationpage.Navigate("https://oauth.vk.com/authorize?client_id=3072479&scope=messages,friends&redirect_uri=vk.com&display=page&v=5.2&response_type=token");
authorisationpage.Navigated += authorisationpage_Navigated;
}
private void authorisationpage_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
string currenturl = e.Uri.ToString();
if (currenturl.Contains("access_token"))
{
var a = currenturl.SkipWhile(x => x != '=').Skip(1).TakeWhile(x => x != '&').ToArray();
foreach (var c in a)
{
Access.access_token += c;
}
}
Close();
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LeetCodeCSharp;
using System.Collections.Generic;
namespace LeetCodeCsharpTest
{
[TestClass]
public class Test_002FloodSurrondArea
{
[TestMethod]
public void TestFloodArea()
{
_002_FloodSurroundArea target = new _002_FloodSurroundArea();
/*["OOOOOO","OXXXXO","OXOOXO","OXOOXO","OXXXXO","OOOOOO"]*/
List<List<FloodNode>> input = new List<List<FloodNode>>();
for (int j = 0; j < 6; j++)
{
List<FloodNode> row1 = new List<FloodNode>();
for (int i = 0; i < 6; i++)
{
row1.Add(new FloodNode() { value = 'o' });
}
input.Add(row1);
}
input[1][1].value = 'x';
input[1][2].value = 'x';
input[1][3].value = 'x';
input[1][4].value = 'x';
input[2][1].value = 'x';
input[2][4].value = 'x';
input[3][1].value = 'x';
input[3][4].value = 'x';
input[4][1].value = 'x';
input[4][2].value = 'x';
input[4][3].value = 'x';
input[4][4].value = 'x';
List<List<FloodNode>> actual = target.FloodBitMap(input);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace truckeventsXamPL.Models
{
public class Evento_Usuario : BaseEntity
{
public string Id_Usuario { get; set; } = null;
public Guid? Id_Evento { get; set; }
public virtual Usuario Usuario { get; set; }
public virtual Evento Evento { get; set; } = null;
public bool? UsuarioConfirmado { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class BagScript : MonoBehaviour
{
public Sounds sound;
public Slider SliderWheat;
public Slider SliderApple;
public Slider SliderTomato;
public Slider SliderEggplant;
public Slider SliderPear;
public Slider SliderSunflower;
public Slider SliderCherry;
public Slider SliderAvo;
public Slider SliderKiwi;
public TextMeshProUGUI SliderValueWheat;
public TextMeshProUGUI SliderValueApple;
public TextMeshProUGUI SliderValueTomato;
public TextMeshProUGUI SliderValueEggplant;
public TextMeshProUGUI SliderValuePear;
public TextMeshProUGUI SliderValueSunflower;
public TextMeshProUGUI SliderValueCherry;
public TextMeshProUGUI SliderValueAvo;
public TextMeshProUGUI SliderValueKiwi;
public TMP_Text totalWheat, totalapple, totaltomato, totaleggplant, totalpear, totalsunflower, totalcherry, totalavo, totalkiwi;
public int plantingseed;
public int wheatprice, appleprice, tomatoprice, eggplantprice, pearprice, sunflowerprice, cherryprice, avoprice, kiwiprice;
public int wheatseed, appleseed, tomatoseed, eggplantseed, pearseed, sunflowerseed, cherryseed, avoseed, kiwiseed;
public GameObject error;
public TMP_Text t_wheat, t_apple, t_tomato, t_eggplant, t_pear, t_sunflower, t_cherry, t_avo, t_kiwi, t_monay, t_gem;
public int pot1, pot2, pot3, pot4, pot5, pot6, pot7;
public int Monay,Gems;
public bool canOpenPannel;
public bool MakePotsShine;
public DotANIM dot;
public TMP_Text t_planting;
// Start is called before the first frame update
void Start()
{
Monay = 30;
Gems = 5;
canOpenPannel = true;
MakePotsShine = false;
wheatprice = 10;
appleprice = 30;
tomatoprice = 60;
eggplantprice = 120;
pearprice = 300;
sunflowerprice = 750;
cherryprice = 2250;
avoprice = 7500;
kiwiprice = 20000;
}
public void starterPack()
{
Monay += 1250;
Gems += 250;
randomseed(20);
}
public void Leaves100()
{
Monay += 100;
}
public void Leaves2500()
{
Monay += 2500;
}
public void Leaves10000()
{
Monay += 10000;
}
public void amber70()
{
Gems += 35;
}
public void amber1000()
{
Gems += 500;
}
public void amber6000()
{
Gems += 3000;
}
public void randSeed5()
{
if (Gems < 500)
{
StartCoroutine("errr");
}
else
{
Gems = Gems - 500;
randomseed(5);
}
}
public void randSeed30()
{
if (Gems < 2665)
{
StartCoroutine("errr");
}
else
{
Gems = Gems - 2665;
randomseed(30);
}
}
public void randSeed50()
{
if (Gems < 4300)
{
StartCoroutine("errr");
}
else
{
Gems = Gems - 4300;
randomseed(50);
}
}
public void randomseed(int amount)
{
for (int i = 0; i < amount; i++)
{
int rand = Random.Range(1, 10);
//Debug.Log(rand);
if (rand == 1) wheatseed++;
if (rand == 2) appleseed++;
if (rand == 3) tomatoseed++;
if (rand == 4) eggplantseed++;
if (rand == 5) pearseed++;
if (rand == 6) sunflowerseed++;
if (rand == 7) cherryseed++;
if (rand == 8) avoseed++;
if (rand == 9) kiwiseed++;
}
}
// Update is called once per frame
void Update()
{
SliderValueWheat.text = SliderWheat.value.ToString();
SliderValueApple.text = SliderApple.value.ToString();
SliderValueCherry.text = SliderCherry.value.ToString();
SliderValueTomato.text = SliderTomato.value.ToString();
SliderValueEggplant.text = SliderEggplant.value.ToString();
SliderValuePear.text = SliderPear.value.ToString();
SliderValueSunflower.text = SliderSunflower.value.ToString();
SliderValueAvo.text = SliderAvo.value.ToString();
SliderValueKiwi.text = SliderKiwi.value.ToString();
totalapple.text = (appleprice * (int)SliderApple.value).ToString();
totalWheat.text = (wheatprice * (int)SliderWheat.value).ToString();
totalcherry.text = (cherryprice * (int)SliderCherry.value).ToString();
totaltomato.text = (tomatoprice * (int)SliderTomato.value).ToString();
totaleggplant.text = (eggplantprice * (int)SliderEggplant.value).ToString();
totalpear.text = (pearprice * (int)SliderPear.value).ToString();
totalsunflower.text = (sunflowerprice * (int)SliderSunflower.value).ToString();
totalavo.text = (avoprice * (int)SliderAvo.value).ToString();
totalkiwi.text = (kiwiprice * (int)SliderKiwi.value).ToString();
//Debug.Log(plantingseed);
if (plantingseed == 1)
{
}
t_monay.text = Monay.ToString();
t_gem.text = Gems.ToString();
t_apple.text = appleseed.ToString();
t_wheat.text = wheatseed.ToString();
t_cherry.text = cherryseed.ToString();
t_tomato.text = tomatoseed.ToString();
t_eggplant.text = eggplantseed.ToString();
t_pear.text = pearseed.ToString();
t_sunflower.text = sunflowerseed.ToString();
t_avo.text = avoseed.ToString();
t_kiwi.text = kiwiseed.ToString();
}
//Premium shop
//Pot shop
public void stopShine()
{
MakePotsShine = false;
plantingseed = 0;
canOpenPannel = true;
}
//Seed Shop
public void buyApple()
{
if (Monay < appleprice)
{
StartCoroutine("errr");
}
else
{
Monay -= appleprice * (int)SliderApple.value;
appleseed = appleseed + (int)SliderApple.value;
}
t_apple.text = appleseed.ToString();
}
public void buywheat()
{
if (Monay < wheatprice)
{
StartCoroutine("errr");
}
else
{
Monay -= wheatprice * (int)SliderWheat.value;
wheatseed = wheatseed + (int)SliderWheat.value;
}
t_wheat.text = wheatseed.ToString();
}
public void buycherry()
{
if (Monay < cherryprice)
{
StartCoroutine("errr");
}
else
{
Monay -= cherryprice * (int)SliderCherry.value;
cherryseed = cherryseed + (int)SliderCherry.value;
}
t_cherry.text = cherryseed.ToString();
}
public void buytomato()
{
if (Monay < tomatoprice)
{
StartCoroutine("errr");
}
else
{
Monay -= tomatoprice * (int)SliderTomato.value;
tomatoseed = tomatoseed + (int)SliderTomato.value;
}
t_tomato.text = tomatoseed.ToString();
}
public void buyeggplant()
{
if (Monay < eggplantprice)
{
StartCoroutine("errr");
}
else
{
Monay -= eggplantprice * (int)SliderEggplant.value;
eggplantseed = eggplantseed + (int)SliderEggplant.value;
}
t_eggplant.text = eggplantseed.ToString();
}
public void buypears()
{
if (Monay < pearprice)
{
StartCoroutine("errr");
}
else
{
Monay -= pearprice * (int)SliderPear.value;
pearseed = pearseed + (int)SliderPear.value;
}
t_pear.text = pearseed.ToString();
}
public void buysunflower()
{
if (Monay < sunflowerprice)
{
StartCoroutine("errr");
}
else
{
Monay -= sunflowerprice * (int)SliderSunflower.value;
sunflowerseed = sunflowerseed + (int)SliderSunflower.value;
}
t_sunflower.text = sunflowerseed.ToString();
}
public void buyavo()
{
if (Monay < avoprice)
{
StartCoroutine("errr");
}
else
{
Monay -= avoprice * (int)SliderAvo.value;
avoseed = avoseed + (int)SliderAvo.value;
}
t_avo.text = avoseed.ToString();
}
public void buykiwi()
{
if (Monay < kiwiprice)
{
StartCoroutine("errr");
}
else
{
Monay -= kiwiprice * (int)SliderKiwi.value;
kiwiseed = kiwiseed + (int)SliderKiwi.value;
}
t_kiwi.text = kiwiseed.ToString();
}
//planting
public void plantApple()
{
if (appleseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
t_planting.text = "Now planting an Apple seed!";
dot.planting();
//appleseed--;
plantingseed = 2;
}
t_apple.text = appleseed.ToString();
}
public void plantWheat()
{
if (wheatseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting a Wheat seed!";
plantingseed = 1;
//wheatseed--;
}
t_wheat.text = wheatseed.ToString();
}
public void plantcherry()
{
if (cherryseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting a Cherry seed!";
plantingseed = 7;
//cherryseed--;
}
t_cherry.text = cherryseed.ToString();
}
public void plantTomato()
{
if (tomatoseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting an Tomato seed!";
plantingseed = 3;
//tomatoseed--;
}
t_tomato.text = tomatoseed.ToString();
}
public void planteggplant()
{
if (eggplantseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting an Eggplant seed!";
plantingseed = 4;
//eggplantseed--;
}
t_eggplant.text = eggplantseed.ToString();
}
public void plantpear()
{
if (pearseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting a Pear seed!";
plantingseed = 5;
//pearseed--;
}
t_pear.text = pearseed.ToString();
}
public void plantsunflower()
{
if (sunflowerseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting a Sunflower seed!";
plantingseed = 6;
//sunflowerseed--;
}
t_sunflower.text = sunflowerseed.ToString();
}
public void plantavo()
{
if (avoseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting an Avocado seed!";
plantingseed = 8;
//avoseed--;
}
t_avo.text = avoseed.ToString();
}
public void plantkiwi()
{
if (kiwiseed < 1)
{
StartCoroutine("errr");
}
else
{
canOpenPannel = false;
MakePotsShine = true;
dot.planting();
t_planting.text = "Now planting a Kiwi seed!";
plantingseed = 9;
//kiwiseed--;
}
t_kiwi.text = kiwiseed.ToString();
}
public void WheatSlider()
{
SliderWheat.maxValue = Monay;
SliderWheat.value = Monay / wheatprice;
if (SliderWheat.value > 10)
{
SliderWheat.maxValue = 10;
SliderWheat.value = 1;
}
else
{
SliderWheat.maxValue = SliderWheat.value;
SliderWheat.value = 1;
}
}
public void AppleSlider()
{
SliderApple.maxValue = Monay;
SliderApple.value = Monay / appleprice;
if (SliderApple.value > 10)
{
SliderApple.maxValue = 10;
SliderApple.value = 1;
}
else
{
SliderApple.maxValue = SliderApple.value;
SliderApple.value = 1;
}
}
public void CherrySlider()
{
SliderCherry.maxValue = Monay;
SliderCherry.value = Monay / cherryprice;
if (SliderCherry.value > 10)
{
SliderCherry.maxValue = 10;
SliderCherry.value = 1;
}
else
{
SliderCherry.maxValue = SliderCherry.value;
SliderCherry.value = 1;
}
}
public void SunflowerSlider()
{
SliderSunflower.maxValue = Monay;
SliderSunflower.value = Monay / sunflowerprice;
if (SliderSunflower.value > 10)
{
SliderSunflower.maxValue = 10;
SliderSunflower.value = 1;
}
else
{
SliderSunflower.maxValue = SliderSunflower.value;
SliderSunflower.value = 1;
}
}
public void EggplantSlider()
{
SliderEggplant.maxValue = Monay;
SliderEggplant.value = Monay / eggplantprice;
if (SliderEggplant.value > 10)
{
SliderEggplant.maxValue = 10;
SliderEggplant.value = 1;
}
else
{
SliderEggplant.maxValue = SliderEggplant.value;
SliderEggplant.value = 1;
}
}
public void PearSlider()
{
SliderPear.maxValue = Monay;
SliderPear.value = Monay / pearprice;
if (SliderPear.value > 10)
{
SliderPear.maxValue = 10;
SliderPear.value = 1;
}
else
{
SliderPear.maxValue = SliderPear.value;
SliderPear.value = 1;
}
}
public void KiwiSlider()
{
SliderKiwi.maxValue = Monay;
SliderKiwi.value = Monay / kiwiprice;
if (SliderKiwi.value > 10)
{
SliderKiwi.maxValue = 10;
SliderKiwi.value = 1;
}
else
{
SliderKiwi.maxValue = SliderKiwi.value;
SliderKiwi.value = 1;
}
}
public void AvoSlider()
{
SliderAvo.maxValue = Monay;
SliderAvo.value = Monay / avoprice;
if (SliderAvo.value > 10)
{
SliderAvo.maxValue = 10;
SliderAvo.value = 1;
}
else
{
SliderAvo.maxValue = SliderAvo.value;
SliderAvo.value = 1;
}
}
public void TomatoSlider()
{
SliderTomato.maxValue = Monay;
SliderTomato.value = Monay / tomatoprice;
if (SliderTomato.value > 10)
{
SliderTomato.maxValue = 10;
SliderTomato.value = 1;
}
else
{
SliderTomato.maxValue = SliderTomato.value;
SliderTomato.value = 1;
}
}
public void cancelPlanting()
{
plantingseed = 8;
dot.NOplanting();
}
public void stoperror()
{
StopCoroutine("errr");
}
IEnumerator errr()
{
dot.errorOn();
sound.error();
yield return new WaitForSeconds(10);
dot.errorOff();
dot.seedbagUP();
}
}
|
using UnityEngine;
using System.Collections;
public class examplescene : MonoBehaviour {
// Use this for initialization
void Start () {
RenderSettings.skybox = (Material)Resources.Load("Skybox3");
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
int x = 50;
int y = 50;
int dy = 40;
int cnt = 0;
int sx = 300;
int sy = 30;
if (GUI.Button(new Rect(x, y+dy*cnt++, sx, sy), "Skybox 1 - hubble deep field")) {
RenderSettings.skybox = (Material)Resources.Load("Skybox1");
}
}
}
|
using D_API.DataContexts;
using D_API.Models.Auth;
using D_API.Types.Auth;
using DiegoG.TelegramBot;
using DiegoG.Utilities.Settings;
using Serilog;
using System.Linq;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using DiegoG.Utilities.IO;
using D_API.Types.Users;
namespace D_API.Dependencies.Interfaces
{
public interface IAuthCredentialsProvider
{
public Task<CredentialVerificationResults> Verify(UserValidCredentials credentials);
public Task<UserCreationResults> Create(UserCreationData newUser);
public Task<User?> FindUser(Guid key);
public bool EnsureRoot();
}
}
|
using System;
namespace NLuaTest.Mock
{
public class master
{
public static string read()
{
return "test-master";
}
public static string read(parameter test)
{
return test.field1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Data;
using TableTopCrucible.Core.Helper;
namespace TableTopCrucible.Core.WPF.Converters
{
public class EnumTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> value is Enum val ? val.GetValueForComboBox(val.GetType()) : value.ToString();
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException(nameof(EnumTextConverter));
}
}
}
|
using PointOfSalesV2.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace PointOfSalesV2.Repository
{
public class UnitProductEquivalenceRepository : Repository<UnitProductEquivalence>, IUnitProductEquivalenceRepository
{
public UnitProductEquivalenceRepository(MainDataContext context) : base(context)
{
}
public IEnumerable<UnitProductEquivalence> GetProductUnits(long productId)
{
throw new NotImplementedException();
}
}
}
|
using AutoMapper;
using Contoso.Forms.Configuration;
using Contoso.Forms.Configuration.Bindings;
using Contoso.Forms.Configuration.Directives;
using Contoso.Forms.Configuration.DataForm;
using Contoso.Forms.Configuration.ListForm;
using Contoso.Forms.Configuration.Navigation;
using Contoso.Forms.Configuration.SearchForm;
using Contoso.Forms.Configuration.TextForm;
using Contoso.Forms.Configuration.Validation;
using Contoso.Forms.Parameters;
using Contoso.Forms.Parameters.Bindings;
using Contoso.Forms.Parameters.Directives;
using Contoso.Forms.Parameters.DataForm;
using Contoso.Forms.Parameters.ListForm;
using Contoso.Forms.Parameters.Navigation;
using Contoso.Forms.Parameters.SearchForm;
using Contoso.Forms.Parameters.TextForm;
using Contoso.Forms.Parameters.Validation;
namespace Contoso.XPlatform.AutoMapperProfiles
{
public class FormsParameterToFormsDescriptorMappingProfile : Profile
{
public FormsParameterToFormsDescriptorMappingProfile()
{
CreateMap<DataFormSettingsParameters, DataFormSettingsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName));
CreateMap<DirectiveArgumentParameters, DirectiveArgumentDescriptor>()
.ForMember(dest => dest.Type, opts => opts.MapFrom(x => x.Type.AssemblyQualifiedName));
CreateMap<DirectiveDefinitionParameters, DirectiveDefinitionDescriptor>();
CreateMap<DirectiveParameters, DirectiveDescriptor>();
CreateMap<DropDownItemBindingParameters, DropDownItemBindingDescriptor>();
CreateMap<DropDownTemplateParameters, DropDownTemplateDescriptor>();
CreateMap<FieldValidationSettingsParameters, FieldValidationSettingsDescriptor>();
CreateMap<FormattedLabelItemParameters, FormattedLabelItemDescriptor>();
CreateMap<FormControlSettingsParameters, FormControlSettingsDescriptor>()
.ForMember(dest => dest.Type, opts => opts.MapFrom(x => x.Type.AssemblyQualifiedName));
CreateMap<FormGroupArraySettingsParameters, FormGroupArraySettingsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName))
.ForMember(dest => dest.Type, opts => opts.MapFrom(x => x.Type.AssemblyQualifiedName));
CreateMap<FormGroupBoxSettingsParameters, FormGroupBoxSettingsDescriptor>();
CreateMap<FormGroupSettingsParameters, FormGroupSettingsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName));
CreateMap<FormGroupTemplateParameters, FormGroupTemplateDescriptor>();
CreateMap<FormRequestDetailsParameters, FormRequestDetailsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName))
.ForMember(dest => dest.DataType, opts => opts.MapFrom(x => x.DataType.AssemblyQualifiedName));
CreateMap<FormsCollectionDisplayTemplateParameters, FormsCollectionDisplayTemplateDescriptor>();
CreateMap<HyperLinkLabelItemParameters, HyperLinkLabelItemDescriptor>();
CreateMap<HyperLinkSpanItemParameters, HyperLinkSpanItemDescriptor>();
CreateMap<LabelItemParameters, LabelItemDescriptor>();
CreateMap<ListFormSettingsParameters, ListFormSettingsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName));
CreateMap<MultiBindingParameters, MultiBindingDescriptor>();
CreateMap<MultiSelectFormControlSettingsParameters, MultiSelectFormControlSettingsDescriptor>()
.ForMember(dest => dest.Type, opts => opts.MapFrom(x => x.Type.AssemblyQualifiedName));
CreateMap<MultiSelectItemBindingParameters, MultiSelectItemBindingDescriptor>();
CreateMap<MultiSelectTemplateParameters, MultiSelectTemplateDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName));
CreateMap<NavigationBarParameters, NavigationBarDescriptor>();
CreateMap<NavigationMenuItemParameters, NavigationMenuItemDescriptor>();
CreateMap<RequestDetailsParameters, RequestDetailsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName))
.ForMember(dest => dest.DataType, opts => opts.MapFrom(x => x.DataType.AssemblyQualifiedName))
.ForMember(dest => dest.ModelReturnType, opts => opts.MapFrom(x => x.ModelReturnType.AssemblyQualifiedName))
.ForMember(dest => dest.DataReturnType, opts => opts.MapFrom(x => x.DataReturnType.AssemblyQualifiedName));
CreateMap<SearchFilterGroupParameters, SearchFilterGroupDescriptor>();
CreateMap<SearchFilterParameters, SearchFilterDescriptor>();
CreateMap<SearchFormSettingsParameters, SearchFormSettingsDescriptor>()
.ForMember(dest => dest.ModelType, opts => opts.MapFrom(x => x.ModelType.AssemblyQualifiedName));
CreateMap<SpanItemParameters, SpanItemDescriptor>();
CreateMap<TextFieldTemplateParameters, TextFieldTemplateDescriptor>();
CreateMap<TextFormSettingsParameters, TextFormSettingsDescriptor>();
CreateMap<TextGroupParameters, TextGroupDescriptor>();
CreateMap<TextItemBindingParameters, TextItemBindingDescriptor>();
CreateMap<ValidationMessageParameters, ValidationMessageDescriptor>();
CreateMap<ValidationRuleParameters, ValidationRuleDescriptor>();
CreateMap<ValidatorArgumentParameters, ValidatorArgumentDescriptor>()
.ForMember(dest => dest.Type, opts => opts.MapFrom(x => x.Type.AssemblyQualifiedName));
CreateMap<ValidatorDefinitionParameters, ValidatorDefinitionDescriptor>();
CreateMap<VariableDirectivesParameters, VariableDirectivesDescriptor>();
CreateMap<FormItemSettingsParameters, FormItemSettingsDescriptor>()
.Include<FormControlSettingsParameters, FormControlSettingsDescriptor>()
.Include<FormGroupArraySettingsParameters, FormGroupArraySettingsDescriptor>()
.Include<FormGroupBoxSettingsParameters, FormGroupBoxSettingsDescriptor>()
.Include<FormGroupSettingsParameters, FormGroupSettingsDescriptor>()
.Include<MultiSelectFormControlSettingsParameters, MultiSelectFormControlSettingsDescriptor>();
CreateMap<SearchFilterParametersBase, SearchFilterDescriptorBase>()
.Include<SearchFilterGroupParameters, SearchFilterGroupDescriptor>()
.Include<SearchFilterParameters, SearchFilterDescriptor>();
CreateMap<LabelItemParametersBase, LabelItemDescriptorBase>()
.Include<FormattedLabelItemParameters, FormattedLabelItemDescriptor>()
.Include<HyperLinkLabelItemParameters, HyperLinkLabelItemDescriptor>()
.Include<LabelItemParameters, LabelItemDescriptor>();
CreateMap<SpanItemParametersBase, SpanItemDescriptorBase>()
.Include<HyperLinkSpanItemParameters, HyperLinkSpanItemDescriptor>()
.Include<SpanItemParameters, SpanItemDescriptor>();
CreateMap<ItemBindingParameters, ItemBindingDescriptor>()
.Include<DropDownItemBindingParameters, DropDownItemBindingDescriptor>()
.Include<MultiSelectItemBindingParameters, MultiSelectItemBindingDescriptor>()
.Include<TextItemBindingParameters, TextItemBindingDescriptor>();
}
}
} |
using System;
namespace HomeWork6._4
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
// Copyright (C) 2018 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Globalization;
using KancolleSniffer.Util;
namespace KancolleSniffer.Model
{
public class NameAndTimer
{
public string Name { get; set; }
public AlarmTimer Timer { get; set; }
public NameAndTimer()
{
Timer = new AlarmTimer();
}
}
public class AlarmTimer
{
private readonly TimeSpan _spare;
private bool _finished;
private DateTime _endTime;
public bool Minus { private get; set; }
public bool IsFinished(DateTime now) => _endTime != DateTime.MinValue && _endTime - now < _spare || _finished;
public AlarmTimer(int spare = 60)
{
_spare = TimeSpan.FromSeconds(spare);
}
public void SetEndTime(double time)
{
SetEndTime((int)time == 0
? DateTime.MinValue
: new DateTime(1970, 1, 1).ToLocalTime().AddSeconds(time / 1000));
}
public void SetEndTime(DateTime time)
{
_endTime = time;
_finished = false;
}
public void Finish()
{
_finished = true;
}
public bool CheckAlarm(TimeStep step)
{
return _endTime != DateTime.MinValue && step.Prev < _endTime - _spare && _endTime - _spare <= step.Now;
}
public string ToString(DateTime now, bool endTime = false)
{
if (_endTime == DateTime.MinValue && !_finished)
return "";
if (endTime)
return _endTime.ToString(@"dd\ HH\:mm", CultureInfo.InvariantCulture);
var rest = _finished || _endTime - now < TimeSpan.Zero ? TimeSpan.Zero : _endTime - now;
return $"{(Minus && rest != TimeSpan.Zero ? "-" : "")}{(int)rest.TotalHours:d2}:" +
rest.ToString(@"mm\:ss", CultureInfo.InvariantCulture);
}
}
} |
using Microsoft.EntityFrameworkCore;
namespace LogReg.Models
{
public class HomeContext : DbContext
{
public HomeContext(DbContextOptions options) : base(options) { }
public DbSet<User> Users { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chess.Pieces
{
public class King : Piece
{
public King(Color color, int x, int y) : base(color, x, y)
{
}
protected override IEnumerable<(int X, int Y)> GetPossibleMovements(Board board)
{
return AllMovements(board, 1);
}
public bool IsInCheck(Board board, out Piece[] checkingPieces)
{
checkingPieces = board.GetPiecesThatCouldMoveTo(this, true).ToArray();
return checkingPieces.Length > 0;
}
public bool IsInCheckmate(Board board)
{
// king can not castle to get out of check
if (!IsInCheck(board, out var checkingPieces))
return false; // if not in check no movement is required to prevent checkmate
foreach (var movement in GetPossibleMovements(board))
if (!board.PreviewMove(this, movement.X, movement.Y).GetPiecesThatCouldMoveTo(Color.Invert(), movement.X, movement.Y, true).Any())
return false; // king could safely move here
if (checkingPieces.Length > 1)
return true; // king could not move away from check, there is no way to block or capture multiple checking pieces
var checkingPiece = checkingPieces.First();
if (board.GetPiecesThatCouldMoveTo(checkingPiece).Any())
return false; // checking piece could be captured, thus removing the check
if (checkingPiece is Knight)
return true; // knights move cant be blocked
if (checkingPiece is Pawn || checkingPiece is King)
return false; // those should be handled by king itself
// get empty fields between checking piece and king that could be blocked to remove check
var travelOverFields = Enumerable.Empty<(int X, int Y)>();
if (checkingPiece is Rook || checkingPiece is Queen && (checkingPiece.X == X || checkingPiece.Y == Y)) // only check queen if it would move like a rook
{
int count = Math.Max(Math.Abs(checkingPiece.X - X), Math.Abs(checkingPiece.Y - Y)) - 1;
travelOverFields = checkingPiece.X == X
? Enumerable.Range(Math.Min(checkingPiece.Y, Y) + 1, count).Select(y => (X, y))
: Enumerable.Range(Math.Min(checkingPiece.X, X) + 1, count).Select(x => (x, Y));
}
else if (checkingPiece is Bishop || checkingPiece is Queen)
{
int count = Math.Abs(checkingPiece.Y - Y) - 1;
var xValues = Enumerable.Range(Math.Min(checkingPiece.X, X) + 1, count);
var yValues = Enumerable.Range(Math.Min(checkingPiece.Y, Y) + 1, count);
// get X and Y values in the right order
if (checkingPiece.X > X != checkingPiece.Y > Y)
yValues = yValues.Reverse();
travelOverFields = xValues.Zip(yValues, (x, y) => (x, y));
}
foreach (var tile in travelOverFields)
if (board.GetPiecesThatCouldMoveTo(Color, tile.X, tile.Y).Any())
return false; // piece can move between king and checking piece
return true; // we tried everything to remove check, but there is nothing we can do
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Unpause : MonoBehaviour {
public BattleController controller;
public List<HeroController> unitList;
public GameObject obj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown(){
UnPause ();
}
public void UnPause(){
Debug.Log("Unpause");
GameData.readyToTween = false;
controller.DeactivateShade(0f,0.1f);
//sound.audio.PlayOneShot (sound.audio.clip);
GameData.gameState = "";
for (int i =0; i < unitList.Count; i++) {
if ( unitList[i].gameObject.activeInHierarchy )
unitList[i].CheckState();
}
iTween.MoveTo ( obj,iTween.Hash("position",new Vector3(3.74f,22f,-2f),"time", 0.1f,"onComplete","ReadyTween","onCompleteTarget",gameObject));
}
void ReadyTween(){
GameData.gameState = "";
GameData.readyToTween = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FodyExample6
{
class Program
{
static void Main(string[] args)
{
Person person = new Person() {FirstName = "Hubert", LastName = "Taler", BirthYear = 1975};
person.BirthYear = 1980;
person.Freeze();
try
{
person.BirthYear = 1981;
}
catch (Exception e)
{
Console.WriteLine("Could not modify person ");
}
}
}
public interface IFreezable
{
void Freeze();
}
public class Person : IFreezable
{
bool isFrozen;
public string FirstName { get; set; }
public string LastName { get; set; }
public int BirthYear { get; set; }
public void Freeze()
{
isFrozen = true;
}
}
}
|
using System;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
namespace ImageResizer
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
ErrorExit("Please follow the run command with an image path and a desired output width.");
}
string imagePath = args[0];
int desiredWidth;
bool widthTest = int.TryParse(args[1], out desiredWidth);
if (!widthTest)
{
ErrorExit("Invalid width entry");
}
try
{
Image image = Image.Load(imagePath);
Size newSize = new Size(desiredWidth, 0);
image.Mutate(x => x.Resize(newSize));
string[] splitPath = imagePath.Split('.');
string newFilename = $"{splitPath[0]}_{image.Width}x{image.Height}.{splitPath[1]}";
image.Save(newFilename);
}
catch
{
ErrorExit("Invalid file entry");
}
void ErrorExit(string message)
{
Console.WriteLine(message);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Environment.Exit(0);
}
}
}
}
|
using PNPUCore.Process;
using System;
using System.Net.Http.Headers;
namespace PNPUCore.Controle
{
interface IControle
{
string MakeControl();
IProcess GetProcessControle();
void SetProcessControle(IProcess value);
string GetLibControle();
string GetTooltipControle();
}
public class PControle : IControle
{
public string ToolTipControle { get; set; }
public string LibControle { get; set; }
private IProcess processControle;
protected string ResultatErreur;
public IProcess GetProcessControle()
{
return processControle;
}
public string GetLibControle()
{
return LibControle;
}
public string GetTooltipControle()
{
return ToolTipControle;
}
public void SetProcessControle(IProcess value)
{
processControle = value;
}
public string MakeControl()
{
throw new NotImplementedException();
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using DotNetNuke.Services.Localization;
#endregion
namespace DotNetNuke.UI.WebControls
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class LanguagesListTypeAttribute : Attribute
{
private readonly LanguagesListType _ListType;
/// <summary>
/// Initializes a new instance of the LanguagesListTypeAttribute class.
/// </summary>
/// <param name="type">The type of List</param>
public LanguagesListTypeAttribute(LanguagesListType type)
{
_ListType = type;
}
public LanguagesListType ListType
{
get
{
return _ListType;
}
}
}
}
|
using CodeOwls.PowerShell.Paths;
using CodeOwls.PowerShell.Provider.PathNodeProcessors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using TreeStore.Model;
namespace TreeStore.PsModule.PathNodes
{
/// <summary>
/// Represents an assigned facet propertyt.
/// Value propertyvan be cane be set, get and cleared.
/// </summary>
public class AssignedFacetPropertyNode : LeafNode,
IGetItem,
ISetItemProperty, IClearItemProperty
{
public class Item
{
private readonly Entity entity;
private readonly FacetProperty assignedProperty;
public Item(Entity entity, FacetProperty property)
{
this.entity = entity;
this.assignedProperty = property;
}
public string Name => this.assignedProperty.Name;
public bool HasValue => this.entity.TryGetFacetProperty(this.assignedProperty).hasValue;
public object? Value
{
get => this.entity.TryGetFacetProperty(this.assignedProperty).value;
set => this.entity.SetFacetProperty<object?>(this.assignedProperty, value);
}
public FacetPropertyTypeValues ValueType => this.assignedProperty.Type;
public TreeStoreItemType ItemType => TreeStoreItemType.AssignedFacetProperty;
}
private readonly ITreeStorePersistence model;
private readonly Entity entity;
private readonly FacetProperty assignedProperty;
public AssignedFacetPropertyNode(ITreeStorePersistence model, Entity entity, FacetProperty property)
{
this.model = model;
this.entity = entity;
this.assignedProperty = property;
}
public override string Name => this.assignedProperty.Name;
public override IEnumerable<PathNode> Resolve(IProviderContext providerContext, string name) => throw new NotImplementedException();
#region IGetItem
public override PSObject GetItem(IProviderContext providerContext) => PSObject.AsPSObject(new Item(this.entity, this.assignedProperty));
#endregion IGetItem
#region IGetChildItem Members
public override IEnumerable<PathNode> GetChildNodes(IProviderContext providerContext)
{
throw new NotImplementedException();
}
#endregion IGetChildItem Members
#region ISetItemProperty
public object SetItemPropertyParameters => new RuntimeDefinedParameterDictionary();
public void SetItemProperties(IProviderContext providerContext, IEnumerable<PSPropertyInfo> properties)
{
// only the value property can be changed
var valueProperty = properties.FirstOrDefault(p => p.Name.Equals(nameof(Item.Value), StringComparison.OrdinalIgnoreCase));
if (valueProperty is null)
return;
if (!this.assignedProperty.CanAssignValue(valueProperty.Value?.ToString() ?? null))
throw new InvalidOperationException($"value='{valueProperty.Value}' cant be assigned to property(name='{this.assignedProperty.Name}', type='{this.assignedProperty.Type}')");
// change value and update database
this.entity.SetFacetProperty(this.assignedProperty, valueProperty.Value);
providerContext.Persistence().Entities.Upsert(this.entity);
}
#endregion ISetItemProperty
#region IClearItemProperty
public object ClearItemPropertyParameters => new RuntimeDefinedParameterDictionary();
public void ClearItemProperty(IProviderContext providerContext, IEnumerable<string> propertyNames)
{
// only the value property can be changed
var valueProperty = propertyNames.FirstOrDefault(pn => pn.Equals(nameof(Item.Value), StringComparison.OrdinalIgnoreCase));
if (valueProperty is null)
return;
// change value and update database
this.entity.Values.Remove(this.assignedProperty.Id.ToString());
providerContext.Persistence().Entities.Upsert(this.entity);
}
#endregion IClearItemProperty
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioTrigger : MonoBehaviour
{
public string SFXName;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
if (AudioManager.instance.sounds[0].source != null)
{
AudioManager.instance.Play(SFXName);
}
}
}
}
|
using System.Collections.Generic;
using System.Text;
using TableTopCrucible.Domain.Models.ValueTypes;
namespace TableTopCrucible.Data.SaveFile.DataTransferObjects
{
public class VersionDTO
{
public int Major { get; set; }
public int Minor { get; set; }
public int Patch { get; set; }
public VersionDTO(Version source)
{
this.Major = source.Major;
this.Minor = source.Minor;
this.Patch = source.Patch;
}
public VersionDTO()
{
}
public Version ToEntity()
=> new Version(Major, Minor, Patch);
}
}
|
using CodeOwls.PowerShell.Paths;
using CodeOwls.PowerShell.Provider.PathNodeProcessors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using TreeStore.Model;
namespace TreeStore.PsModule.PathNodes
{
public class FacetPropertyNode : LeafNode,
IRemoveItem, ICopyItem, IRenameItem,
IGetItemProperty
{
public static readonly string[] ForbiddenNames = { nameof(Item.Id), nameof(Item.Name), nameof(Item.ItemType), nameof(Item.ValueType) };
public sealed class Item
{
private readonly FacetProperty facetProperty;
public Item(FacetProperty property)
{
this.facetProperty = property;
}
public Guid Id => this.facetProperty.Id;
public string Name
{
get => this.facetProperty.Name;
set => this.facetProperty.Name = value;
}
public FacetPropertyTypeValues ValueType => this.facetProperty.Type;
public TreeStoreItemType ItemType => TreeStoreItemType.FacetProperty;
}
private readonly FacetProperty facetProperty;
private readonly Tag tag;
public FacetPropertyNode(Tag tag, FacetProperty facetProperty)
{
this.tag = tag;
this.facetProperty = facetProperty;
}
public override string Name => this.facetProperty.Name;
public override IEnumerable<PathNode> Resolve(IProviderContext providerContext, string name)
{
throw new NotImplementedException();
}
#region IGetItem
public override PSObject GetItem(IProviderContext providerContext) => PSObject.AsPSObject(new Item(this.facetProperty));
#endregion IGetItem
#region IRemoveItem
public object RemoveItemParameters => new RuntimeDefinedParameterDictionary();
public void RemoveItem(IProviderContext providerContext, string path)
{
var persistence = providerContext.Persistence();
if (!providerContext.Force)
if (persistence.Entities.FindByTag(this.tag).Any())
{
providerContext.WriteError(
new ErrorRecord(new InvalidOperationException($"Can't delete facetProperty(name='{this.facetProperty.Name}'): It is used by at least one entity. Use -Force to delete anyway."),
errorId: "TagInUse",
errorCategory: ErrorCategory.InvalidOperation,
targetObject: this.GetItem(providerContext)));
return;
}
this.tag.Facet.RemoveProperty(this.facetProperty);
persistence.Tags.Upsert(this.tag);
}
#endregion IRemoveItem
#region ICopyItem
public object CopyItemParameters => new RuntimeDefinedParameterDictionary();
public void CopyItem(IProviderContext providerContext, string sourceItemName, string? destinationItemName, PathNode destinationNode)
{
if (destinationItemName is { } && !destinationItemName.EnsureValidName())
throw new InvalidOperationException($"facetProperty(name='{destinationItemName}' wasn't created: it contains invalid characters");
if (FacetPropertyNode.ForbiddenNames.Contains(destinationItemName, StringComparer.OrdinalIgnoreCase))
throw new InvalidOperationException($"facetProperty(name='{destinationItemName}') wasn't copied: name is reserved");
if (destinationNode is TagNode destinationContainerNodeValue)
{
destinationContainerNodeValue.AddProperty(providerContext, destinationItemName ?? this.facetProperty.Name, this.facetProperty.Type);
}
}
#endregion ICopyItem
#region IRenameItem
public object RenameItemParameters => new RuntimeDefinedParameterDictionary();
public void RenameItem(IProviderContext providerContext, string path, string newName)
{
if (this.facetProperty.Name.Equals(newName))
return;
if (!newName.EnsureValidName())
throw new InvalidOperationException($"facetProperty(name='{newName}' wasn't created: it contains invalid characters");
if (FacetPropertyNode.ForbiddenNames.Contains(newName, StringComparer.OrdinalIgnoreCase))
throw new InvalidOperationException($"facetProperty(name='{newName}') wasn't renamed: name is reserved");
if (this.tag.Facet.Properties.Any(p => p.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"rename failed: property name '{newName}' must be unique.");
this.facetProperty.Name = newName;
providerContext.Persistence().Tags.Upsert(this.tag);
}
#endregion IRenameItem
}
} |
using MVCApplication.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCApplication.Data
{
public class AppContext: DbContext
{
public DbSet<Entry> Entries { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Client> Clients { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Project>()
.HasKey(e => e.ProjectId)//configures the primary key property for this entity
.Property(e => e.ProjectId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<User>()
.HasKey(e => e.Id)//configures the primary key property for this entity
.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Client>()
.HasKey(e => e.Id)//configures the primary key property for this entity
.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
} |
namespace E02_MinimumEditDistance
{
using System;
using System.Text;
public class Startup
{
private const double ReplaceCost = 1;
private const double DeleteCost = 0.9;
private const double InsertCost = 0.8;
public static void Main(string[] args)
{
Console.WriteLine("Please enter the initial word:");
string initialWord = Console.ReadLine();
Console.WriteLine("Please enter the target word:");
string targetWord = Console.ReadLine();
Console.WriteLine();
int[,] matrixOfLcs = BuildMatrixOfLongestCommonSet(targetWord, initialWord);
Console.WriteLine("LcsMatrix:");
PrintLcsMatrix(matrixOfLcs, targetWord, initialWord);
double transformCost = CalcTransformCost(matrixOfLcs, targetWord, initialWord);
Console.WriteLine("The transformation cost is: {0}", transformCost);
Console.WriteLine();
}
private static void PrintLcsMatrix(int[,] matrixOfLcs, string targetWord, string initialWord)
{
var matrixToPrint = new StringBuilder();
matrixToPrint.Append(" ");
for (int i = 0; i < initialWord.Length; i++)
{
matrixToPrint.Append(initialWord[i] + ", ");
}
matrixToPrint.Length -= 2;
matrixToPrint.AppendLine();
for (int i = 0; i < matrixOfLcs.GetLength(0); i++)
{
if (i > 0)
{
matrixToPrint.Append(targetWord[i - 1] + ": ");
}
else
{
matrixToPrint.Append(" ");
}
for (int j = 0; j < matrixOfLcs.GetLength(1); j++)
{
matrixToPrint.Append(matrixOfLcs[i, j] + ", ");
}
matrixToPrint.Length -= 2;
matrixToPrint.AppendLine();
}
Console.WriteLine(matrixToPrint.ToString());
}
private static double CalcTransformCost(int[,] matrixOfLcs, string targetWord, string initialWord)
{
double transformCost = 0;
int currentX = matrixOfLcs.GetLength(0) - 1;
int currentY = matrixOfLcs.GetLength(1) - 1;
while (currentX != 0 && currentY != 0)
{
if (targetWord[currentX - 1] == initialWord[currentY - 1])
{
currentX--;
currentY--;
}
else if (matrixOfLcs[currentX - 1, currentY] == matrixOfLcs[currentX, currentY - 1])
{
transformCost += ReplaceCost;
currentX--;
currentY--;
}
else if (matrixOfLcs[currentX - 1, currentY] > matrixOfLcs[currentX, currentY - 1])
{
transformCost += InsertCost;
currentX--;
}
else
{
transformCost += DeleteCost;
currentY--;
}
}
if (currentX > 0)
{
transformCost += currentX * InsertCost;
}
if (currentY > 0)
{
transformCost += currentY * DeleteCost;
}
return transformCost;
}
private static int[,] BuildMatrixOfLongestCommonSet(string targetWord, string initialWord)
{
int[,] matrixOfLcs = new int[targetWord.Length + 1, initialWord.Length + 1];
for (int i = 1; i <= targetWord.Length; i++)
{
bool letterMatched = false;
for (int j = 1; j <= initialWord.Length; j++)
{
if ((!letterMatched) && (targetWord[i - 1] == initialWord[j - 1]))
{
matrixOfLcs[i, j] = matrixOfLcs[i, j - 1] + 1;
letterMatched = true;
}
else
{
matrixOfLcs[i, j] = Math.Max(matrixOfLcs[i - 1, j], matrixOfLcs[i, j - 1]);
}
}
}
return matrixOfLcs;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Exercise8
{
/* 8. Write a method that adds two positive integer numbers represented
* as arrays of digits (each array element arr[i] contains a digit;
* the last digit is kept in arr[0]). Each of the numbers that will
* be added could have up to 10 000 digits.
*/
class Program
{
static void Main(string[] args)
{
int temp = 7;
int [] number1 = new int [4];
int [] number2 = new int [3];
for (int i = 0; i < number1.Length; i++)
{
temp++;
number1[i] = temp;
if (temp == 9)
{
temp = 0;
}
}
temp = 3;
for (int i = 0; i < number2.Length; i++)
{
temp++;
number2[i] = temp;
if (temp == 9)
{
temp = 0;
}
}
Console.WriteLine("Array 1 :");
for (int i = 0; i < number1.Length; i++)
{
if(i % 20 == 0)
{
Console.WriteLine();
}
Console.Write("{0} ", number1[i]);
}
Console.WriteLine("\n\n + \n");
Console.WriteLine("Array 2 :");
for (int i = 0; i < number2.Length; i++)
{
if(i % 20 == 0)
{
Console.WriteLine();
}
Console.Write("{0} ", number2[i]);
}
Console.WriteLine("\n\nSum is:");
number1 = Sum(number1, number2);
temp = 0;
for (int i = number1.Length - 1; i > 0; i--)
{
if (number1[i] != 0)
{
temp = i;
break;
}
}
for (int i = 0; i <= number1.Length - 1/*temp + 1 */; i++)
{
if(i % 20 == 0)
{
Console.WriteLine();
}
Console.Write("{0} ", number1[i]);
}
Console.WriteLine();
}
static int [] Sum (int [] num1 , int [] num2)
{
int digit1 = 0, digit2;
int[] array = new int[100];
for (int i = 0; i < array.Length; i++)
{
if (num1.Length - 1 >= i && num2.Length - 1 >= i)
{
digit1 = num1[i] + num2[i] + digit1;
digit2 = digit1 % 10;
digit1 /= 10;
array[i] = digit2;
}
if(num1.Length - 1 < i && num2.Length - 1 < i)
{
break;
}
if (num1.Length - 1 >= i)
{
digit1 = num1[i] + digit1;
digit2 = digit1 % 10;
digit1 /= 10;
array[i] = digit2;
}
if (num2.Length - 1 >= i)
{
digit1 = num2[i] + digit1;
digit2 = digit1 % 10;
digit1 /= 10;
array[i] = digit2;
}
}
return array;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimedOnOff : MonoBehaviour {
// Generalize to if we want a timer for how long something is on or how long it's off.
public bool timeOn;
public float timer;
// Run a timer, which resets if the button gets turned off before its through.
IEnumerator Time() {
float timeLeft = timer;
while (timeLeft > 0) {
if (this.GetComponent<OnOff> ().getOnBool () != timeOn)
break;
yield return new WaitForSeconds (1);
timeLeft--;
}
if (timeLeft == 0) this.GetComponent<OnOff> ().setOnBool (!timeOn);
StopAllCoroutines ();
}
// Update is called once per frame
void Update () {
if (this.GetComponent<OnOff> ().getOnBool () == timeOn) {
StartCoroutine (Time());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreDemoModels.DomainModels;
using CoreDemoService.SDI;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CoreDemoWebAPI.Controllers
{
[Produces("application/json")]
public class HomeController : Controller
{
private readonly ISDICoreDemo _sdiCoreDemo;
public HomeController(ISDICoreDemo sDICoreDemo)
{
_sdiCoreDemo = sDICoreDemo;
}
[HttpGet]
[Route("api/Home/{name}")]
public async Task<IActionResult> HelloWorld(string name)
{
return Ok("Hello " + name + "!!!");
}
[HttpGet("api/GetAllDepartment")]
public async Task<IEnumerable<Depertment>> GetDepertments()
{
return await _sdiCoreDemo.Departments.GetAll();
}
}
} |
using System;
using System.Threading.Tasks;
using Executor.Console.Util;
namespace Executor.Console.Job
{
public class RandomDelayJob : VoidJob
{
private readonly string _name;
public RandomDelayJob(string name)
{
_name = name;
}
protected override async Task Execute()
{
var waitTimeMilliseconds = new Random().Next(1000);
Logger.Log($"[{ToString()}] Starting execution ({waitTimeMilliseconds})");
await Task.Delay(TimeSpan.FromMilliseconds(waitTimeMilliseconds));
Logger.Log($"[{ToString()}] Finishing execution");
}
public override string ToString()
{
return $"{GetType().Name}({_name})";
}
}
} |
using AutoMapper;
using Football.API.Dto;
using Football.API.Dto.QueryParams;
using Football.API.Services;
using Football.DAL;
using Football.DAL.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Football.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BroadcastsController : ControllerBase
{
private IUnitOfWork<MatchBroadcast> _unitOfWork;
private IMapper _mapper;
private IPaginationService _paginationService;
public BroadcastsController(IUnitOfWork<MatchBroadcast> unitOfWork,
IMapper mapper, IPaginationService paginationService)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
_paginationService = paginationService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<MatchBroadcastDto>>> Get()
{
var broadcasts = _mapper.Map<IEnumerable<MatchBroadcastDto>>(await
_unitOfWork.GetRepository().GetAll().Include(x => x.MatchTournament).ToListAsync());
return Ok(broadcasts);
}
// GET api/broadcasts/3
[HttpGet("{id}")]
public async Task<ActionResult<MatchBroadcastDto>> Get(int id)
{
var broadcast = _mapper.Map<MatchBroadcastDto>(await _unitOfWork.GetRepository().GetAll()
.Include(x => x.MatchTournament).SingleOrDefaultAsync(p => p.Id == id));
if (broadcast == null)
{
return NotFound();
}
return Ok(broadcast);
}
// POST api/broadcasts
[HttpPost]
public async Task<ActionResult<MatchBroadcastDto>> Post([FromBody] MatchBroadcastDto broadcastDto)
{
if (broadcastDto == null)
{
return BadRequest();
}
var matchBroadCastDto = _mapper.Map<MatchBroadcast>(broadcastDto);
_unitOfWork.GetRepository().Add(matchBroadCastDto);
_unitOfWork.SaveChanges();
return Ok(matchBroadCastDto);
}
// PUT api/broadcasts/
[HttpPut]
public async Task<ActionResult<MatchBroadcastDto>> Put([FromBody] MatchBroadcast matchBroadcastDto)
{
if (matchBroadcastDto == null)
{
return BadRequest();
}
if (_unitOfWork.GetRepository().GetAll().All(x => x.Id != matchBroadcastDto.Id))
{
return NotFound();
}
var broadcast = _mapper.Map<MatchBroadcast>(matchBroadcastDto);
_unitOfWork.GetRepository().Update(broadcast);
_unitOfWork.SaveChanges();
return Ok(broadcast);
}
// DELETE api/broadcasts/5
[HttpDelete("{id}")]
public async Task<ActionResult<MatchBroadcastDto>> Delete(int id)
{
MatchBroadcast broadCast = await _unitOfWork.GetRepository().FindByIdAsync(id);
if (broadCast == null)
{
return NotFound();
}
_unitOfWork.GetRepository().Remove(broadCast);
_unitOfWork.SaveChanges();
return Ok(_mapper.Map<MatchBroadcastDto>(broadCast));
}
[HttpGet("paginated")]
public async Task<ActionResult<PaginationDto<MatchBroadcastDto>>> GetAllBroadcasts(
[FromQuery] FullPaginationQueryParams fullPaginationQuery)
{
var broadcasts = _unitOfWork.GetRepository()
.GetAll()
.Include(x => x.MatchTournament);
return await _paginationService.GetPageAsync<MatchBroadcastDto, MatchBroadcast>(broadcasts, fullPaginationQuery);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.DirectInput;
using SharpDX.Windows;
using Device = SharpDX.Direct3D11.Device;
using Keyboard = VoxelEngine.Input.Keyboard;
using Mouse = VoxelEngine.Input.Mouse;
namespace VoxelEngine
{
public abstract class BaseGame : IDisposable
{
protected RenderForm _form;
protected GameTimeManager _gameTimeManager = new GameTimeManager();
protected FPSCounter _fpsCounter = new FPSCounter();
protected Device device;
protected DeviceContext context;
private SwapChain swapChain;
private RenderTargetView renderView;
private Texture2D backBuffer;
private Factory factory;
private List<IDisposable> _disposableList = new List<IDisposable>();
public RenderForm Form
{
get { return _form; }
}
private DirectInput _directInputInstance = null;
internal DirectInput DirectInput
{
get
{
if (_directInputInstance == null) _disposableList.Add(_directInputInstance = new DirectInputFactory().Create());
return _directInputInstance;
}
}
protected BaseGame()
{
_form = new RenderForm("SharpDX Direct3D 11 Sample")
{
Width = 800,
Height = 600
};
_disposableList.Add(_form);
//_form.FormClosing += delegate(object sender, FormClosingEventArgs args)
// {
// Unload(args.CloseReason);
// };
//_form.KeyDown += (sender, args) => { if (args.Alt) };
}
protected virtual void Initialize()
{
_disposableList.Add(Mouse.Initialize(this));
_disposableList.Add(Keyboard.Initialize(this));
// SwapChain description
var desc = new SwapChainDescription()
{
BufferCount = 1,
ModeDescription = new ModeDescription(
_form.ClientSize.Width,
_form.ClientSize.Height,
new Rational(60, 1),
Format.R8G8B8A8_UNorm),
IsWindowed = true,
OutputHandle = _form.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
// Create Device and SwapChain
Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
context = device.ImmediateContext;
// Ignore all windows events
factory = swapChain.GetParent<Factory>();
factory.MakeWindowAssociation(_form.Handle, WindowAssociationFlags.IgnoreAll);
// New RenderTargetView from the backbuffer
backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
renderView = new RenderTargetView(device, backBuffer);
context.Rasterizer.SetViewport(new Viewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0.0f, 1.0f));
context.OutputMerger.SetTargets(renderView);
}
protected virtual void Update(IGameTime time)
{
Mouse.Update(time);
Keyboard.Update(time);
}
protected abstract void Load();
protected abstract void Unload(CloseReason reason);
protected abstract void Draw(IGameTime time);
public void Run()
{
this.Initialize();
this.Load();
RenderLoop.Run(_form, () =>
{
//Thread.Sleep(16);
_gameTimeManager.Reset();
_fpsCounter.Frame(_gameTimeManager.ElapsedTime);
//context.ClearRenderTargetView(renderView, Color.Black);
Update(_gameTimeManager);
Draw(_gameTimeManager);
swapChain.Present(0, PresentFlags.None);
});
}
public void Exit()
{
_form.Close();
}
#region IDisposable
protected bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(_disposed) return;
if (disposing)
{
renderView.Dispose();
backBuffer.Dispose();
context.ClearState();
context.Flush();
device.Dispose();
context.Dispose();
swapChain.Dispose();
factory.Dispose();
foreach (var item in _disposableList)
{
item.Dispose();
}
}
_disposed = true;
}
#endregion
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System.Web.Mvc;
namespace Heckathon.Models
{
public class CityViewModel
{
public List<Models.CityDataModel> CityList =
new List<Models.CityDataModel>();
public int SelectedCityID { get; set; }
public IEnumerable<SelectListItem> CityIEnum
{
get
{
return new SelectList(CityList, "ID", "CityName");
}
}
}
public class StateProvinceViewModel
{
public List<Models.StateProvinceDataModel> StateProvinceList =
new List<Models.StateProvinceDataModel>();
public int SelectedStateProvinceID { get; set; }
public IEnumerable<SelectListItem> StateProvinceIEnum
{
get
{
return new SelectList(StateProvinceList, "ID", "StateOrProvinceName");
}
}
}
public class CountryViewModel
{
public List<Models.CountryDataModel> CountryList =
new List<Models.CountryDataModel>();
public int SelectedCountryID { get; set; }
public IEnumerable<SelectListItem> CountryIEnum
{
get
{
return new SelectList(CountryList, "ID", "CountryName");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace InternetShop.Models
{
public class Comment
{
public string MessageText { get; set; }
public string Advantages { set; get; }
public string Disadvantages { get; set; }
public int Estimate { set; get; }
public string SenderName { get; set; }
public string SenderEmail { get; set; }
public int ProductId { get; set; }
}
} |
namespace XShare.WebForms.Controls.YoutubeIfreme
{
using System;
using System.Web.UI;
public partial class YouTubeIframe : UserControl
{
public enum VideoQuality
{
Small,
Medium,
Large,
Hd720,
Hd1080,
Highres,
Default
}
public string VideoId
{
get; set;
}
public int Volume
{
get; set;
}
public bool Loop
{
get; set;
}
public string VQuality
{
get; set;
}
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(
this.Page,
typeof(System.Web.UI.Page),
"javascript",
$"loadIframe('{this.VideoId}', {this.Volume}, '{this.Loop.ToString().ToLower()}', '{this.VQuality.ToLower()}');", true);
}
}
} |
using BPiaoBao.AppServices.Contracts.Cashbag;
using BPiaoBao.AppServices.DataContracts.Cashbag;
using BPiaoBao.Client.UIExt;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace BPiaoBao.Client.Account.ViewModel
{
/// <summary>
/// 所有理财产品视图模型
/// </summary>
public class AllFinanceViewModel : BaseVM
{
#region 构造函数
/// <summary>
/// 初始化数据
/// </summary>
public override void Initialize()
{
if (CanExecuteQueryCommand())
ExecuteQueryCommand();
}
/// <summary>
/// Initializes a new instance of the <see cref="AllFinanceViewModel"/> class.
/// </summary>
public AllFinanceViewModel()
{
if (IsInDesignMode)
return;
Initialize();
}
#endregion
#region 公开属性
#region AllProducts
///// <summary>
///// The <see cref="AllProducts" /> property's name.
///// </summary>
//public const string AllProductsPropertyName = "AllProducts";
//private ObservableCollection<FinancialProductDto> allProducts = new ObservableCollection<FinancialProductDto>();
///// <summary>
///// 所有理财产品
///// </summary>
//public ObservableCollection<FinancialProductDto> AllProducts
//{
// get { return allProducts; }
// set
// {
// if (allProducts == value) return;
// RaisePropertyChanging(AllProductsPropertyName);
// allProducts = value;
// RaisePropertyChanged(AllProductsPropertyName);
// }
//}
#endregion
#region SoldOutFinancialProducts
/// <summary>
/// The <see cref="SoldOutFinancialProducts" /> property's name.
/// </summary>
private const string SoldOutFinancialProductsPropertyName = "SoldOutFinancialProducts";
private IEnumerable<FinancialProductDto> _soldOutFinancialProducts;
/// <summary>
/// 下架的理财产品
/// </summary>
public IEnumerable<FinancialProductDto> SoldOutFinancialProducts
{
get { return _soldOutFinancialProducts; }
set
{
if (_soldOutFinancialProducts == value) return;
RaisePropertyChanging(SoldOutFinancialProductsPropertyName);
_soldOutFinancialProducts = value;
RaisePropertyChanged(SoldOutFinancialProductsPropertyName);
}
}
#endregion
#region OnSaleFinancialProducts
/// <summary>
/// The <see cref="OnSaleFinancialProducts" /> property's name.
/// </summary>
private const string OnSaleFinancialProductsPropertyName = "OnSaleFinancialProducts";
private IEnumerable<FinancialProductDto> _onSaleFinancialProducts;
/// <summary>
/// 出售中的理财产品
/// </summary>
public IEnumerable<FinancialProductDto> OnSaleFinancialProducts
{
get { return _onSaleFinancialProducts; }
set
{
if (_onSaleFinancialProducts == value) return;
RaisePropertyChanging(OnSaleFinancialProductsPropertyName);
_onSaleFinancialProducts = value;
RaisePropertyChanged(OnSaleFinancialProductsPropertyName);
}
}
#endregion
#endregion
private bool _isWait;
public bool IsWait
{
get { return _isWait; }
set
{
if (_isWait == value) return;
_isWait = value;
RaisePropertyChanged("IsWait");
}
}
public ICommand BuyCommand
{
get
{
return new RelayCommand<string>(p =>
{
var model = OnSaleFinancialProducts.SingleOrDefault(x => x.ProductId == p);
if (model == null)
{
UIManager.ShowMessage("获取产品信息失败,请稍后再试!");
return;
}
LocalUIManager.OpenProductBuyWindow(new ProductBuyViewModel(model));
});
}
}
#region OpenProductsInfoCommand
private RelayCommand<FinancialProductDto> _openProductsInfoCommand;
/// <summary>
/// 理财产品详情信息
/// </summary>
public RelayCommand<FinancialProductDto> OpenProductsInfoCommand
{
get
{
return _openProductsInfoCommand ?? (_openProductsInfoCommand = new RelayCommand<FinancialProductDto>(ExecuteOpenProductsInfoCommand, CanExecuteOpenProductsInfoCommand));
}
}
private void ExecuteOpenProductsInfoCommand(FinancialProductDto info)
{
LocalUIManager.ShowFinancialProductInfo(info.ProductId);
}
private bool CanExecuteOpenProductsInfoCommand(FinancialProductDto info)
{
return info != null;
}
#endregion
#region QueryCommand
private RelayCommand _queryCommand;
/// <summary>
/// Gets the QueryCommand.
/// </summary>
public RelayCommand QueryCommand
{
get
{
return _queryCommand ?? (_queryCommand = new RelayCommand(ExecuteQueryCommand, CanExecuteQueryCommand));
}
}
private void ExecuteQueryCommand()
{
IsWait = true;
OnSaleFinancialProducts = null;
SoldOutFinancialProducts = null;
Action action = () => CommunicateManager.Invoke<IFinancialService>(p =>
{
var result = p.GetShelfProducts("5");
var enumerable = result as IList<FinancialProductDto> ?? result.ToList();
if (result != null)
{
foreach (var item in enumerable)
{
item.MaxAmount = 0;
item.CurrentAmount = 0;
}
}
SoldOutFinancialProducts = enumerable;
var temp = p.GetActiveProduct(null);
OnSaleFinancialProducts = temp;
//DispatcherHelper.UIDispatcher.Invoke(new Action(() =>
//{
// OnSaleFinancialProducts = temp;
//}));
}, UIManager.ShowErr);
Task.Factory.StartNew(action).ContinueWith(task =>
{
Action setBusyAction = () => { IsWait = false; };
DispatcherHelper.UIDispatcher.Invoke(setBusyAction);
});
}
private bool CanExecuteQueryCommand()
{
return !_isWait;
}
#endregion
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace CryptobotUi
{
partial class Startup
{
partial void OnConfiguring(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
} |
using Ganss.Excel.Exceptions;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Ganss.Excel
{
/// <summary>
/// Maps a <see cref="Type"/>'s properties to columns in an Excel sheet.
/// </summary>
public class TypeMapper
{
/// <summary>
/// Gets the type being mapped.
/// </summary>
public Type Type { get; private set; }
/// <summary>
/// Gets or sets the columns by name.
/// </summary>
/// <value>
/// The dictionary of columns by name.
/// </value>
public Dictionary<string, List<ColumnInfo>> ColumnsByName { get; set; } = new Dictionary<string, List<ColumnInfo>>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the columns by index.
/// </summary>
/// <value>
/// The dictionary of columns by index.
/// </value>
public Dictionary<int, List<ColumnInfo>> ColumnsByIndex { get; set; } = new Dictionary<int, List<ColumnInfo>>();
internal Func<string, string> NormalizeName { get; set; }
/// <summary>
/// Gets or sets the Before Mapping action.
/// </summary>
internal ActionInvoker BeforeMappingActionInvoker { get; set; }
/// <summary>
/// Gets or sets the After Mapping action.
/// </summary>
internal ActionInvoker AfterMappingActionInvoker { get; set; }
static readonly Regex OneTwoLetterRegex = new("^[A-Z]{1,2}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
/// <summary>
/// Creates a <see cref="TypeMapper"/> object from the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A <see cref="TypeMapper"/> object.</returns>
public static TypeMapper Create(Type type)
{
var typeMapper = new TypeMapper { Type = type };
typeMapper.Analyze();
return typeMapper;
}
/// <summary>
/// Creates a <see cref="TypeMapper"/> object from a list of cells.
/// </summary>
/// <param name="columns">The cells.</param>
/// <param name="useContentAsName"><c>true</c> if the cell's contents should be used as the column name; otherwise, <c>false</c>.</param>
/// <returns>A <see cref="TypeMapper"/> object.</returns>
public static TypeMapper Create(IEnumerable<ICell> columns, bool useContentAsName = true)
{
var typeMapper = new TypeMapper();
foreach (var col in columns)
{
var index = col.ColumnIndex;
var name = useContentAsName ? col.ToString() : ExcelMapper.IndexToLetter(index + 1);
var columnInfo = new DynamicColumnInfo(index, name);
typeMapper.ColumnsByIndex.Add(index, new List<ColumnInfo> { columnInfo });
if (!typeMapper.ColumnsByName.TryGetValue(name, out var columnInfos))
typeMapper.ColumnsByName.Add(name, new List<ColumnInfo> { columnInfo });
else
columnInfos.Add(columnInfo);
}
return typeMapper;
}
/// <summary>
/// Creates a <see cref="TypeMapper"/> object from an <see cref="ExpandoObject"/> object.
/// </summary>
/// <param name="o">The <see cref="ExpandoObject"/> object.</param>
/// <returns>A <see cref="TypeMapper"/> object.</returns>
public static TypeMapper Create(ExpandoObject o)
{
var typeMapper = new TypeMapper();
var eo = (IDictionary<string, object>)o;
var l = o.ToList();
eo.TryGetValue(IndexMapPropertyName, out var map);
var oneTwoLetter = map == null && eo.Keys.Where(k => k != IndexMapPropertyName).All(k => OneTwoLetterRegex.IsMatch(k));
for (int i = 0; i < o.Count(); i++)
{
var prop = l[i];
var name = prop.Key;
var ix = i;
if (name != IndexMapPropertyName)
{
if (map is Dictionary<string, int> indexMap)
{
if (indexMap.TryGetValue(name, out var im))
ix = im;
}
else if (oneTwoLetter)
{
ix = ExcelMapper.LetterToIndex(name) - 1;
}
var columnInfo = new DynamicColumnInfo(prop.Key, prop.Value != null ? prop.Value.GetType().ConvertToNullableType() : typeof(string));
typeMapper.ColumnsByIndex.Add(ix, new List<ColumnInfo> { columnInfo });
if (!typeMapper.ColumnsByName.TryGetValue(name, out var columnInfos))
typeMapper.ColumnsByName.Add(name, new List<ColumnInfo> { columnInfo });
else
columnInfos.Add(columnInfo);
}
}
return typeMapper;
}
const string IndexMapPropertyName = "__indexes__";
/// <summary>
/// Creates an <see cref="ExpandoObject"/> object that includes type mapping information.
/// </summary>
/// <returns>An <see cref="ExpandoObject"/> object.</returns>
public ExpandoObject CreateExpando()
{
var eo = new ExpandoObject();
var expando = (IDictionary<string, object>)eo;
var map = ColumnsByName.ToDictionary(c => c.Key, c => ColumnsByIndex.First(ci => ci.Value[0] == c.Value[0]).Key);
expando[IndexMapPropertyName] = map;
return eo;
}
/// <summary>
/// Gets or sets the constructor to initialize the mapped type. Only used if the mapped type has no default constructor.
/// </summary>
public ConstructorInfo Constructor { get; set; }
/// <summary>
/// Gets or sets the constructor parameters by name.
/// </summary>
public Dictionary<string, ParameterInfo> ConstructorParams { get; set; }
void Analyze()
{
var props = Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in props.Where(p => Attribute.GetCustomAttribute(p, typeof(IgnoreAttribute)) is not IgnoreAttribute))
{
var ci = new ColumnInfo(prop);
// make sure inherited attributes come before attributes defined on the type itself
// so the latter ones can overwrite the inherited ones in the dictionary below
// (see #192)
var selfAttribs = Attribute.GetCustomAttributes(prop, typeof(ColumnAttribute), inherit: false).Cast<ColumnAttribute>();
var inheritedAttribs = Attribute.GetCustomAttributes(prop, typeof(ColumnAttribute), inherit: true)
.Cast<ColumnAttribute>()
.Where(c => c.Inherit)
.Except(selfAttribs);
var attribs = inheritedAttribs.Concat(selfAttribs);
if (attribs.Any())
{
foreach (var columnAttribute in attribs)
{
ci = new ColumnInfo(prop);
if (!string.IsNullOrEmpty(columnAttribute.Name))
{
if (!ColumnsByName.ContainsKey(columnAttribute.Name))
ColumnsByName.Add(columnAttribute.Name, new List<ColumnInfo>());
ColumnsByName[columnAttribute.Name].Add(ci);
}
else if (!ColumnsByName.ContainsKey(prop.Name))
ColumnsByName.Add(prop.Name, new List<ColumnInfo>() { ci });
if (columnAttribute.Index > 0)
{
var idx = columnAttribute.Index - 1;
if (!ColumnsByIndex.ContainsKey(idx))
ColumnsByIndex.Add(idx, new List<ColumnInfo>());
ColumnsByIndex[idx].Add(ci);
}
ci.Directions = columnAttribute.Directions;
}
}
else if (!ColumnsByName.ContainsKey(prop.Name))
ColumnsByName.Add(prop.Name, new List<ColumnInfo>() { ci });
if (Attribute.GetCustomAttribute(prop, typeof(DataFormatAttribute)) is DataFormatAttribute dataFormatAttribute)
{
ci.BuiltinFormat = dataFormatAttribute.BuiltinFormat;
ci.CustomFormat = dataFormatAttribute.CustomFormat;
}
if (Attribute.GetCustomAttribute(prop, typeof(FormulaResultAttribute)) is FormulaResultAttribute)
ci.FormulaResult = true;
if (Attribute.GetCustomAttribute(prop, typeof(FormulaAttribute)) is FormulaAttribute)
ci.Formula = true;
if (Attribute.GetCustomAttribute(prop, typeof(JsonAttribute)) is JsonAttribute)
ci.Json = true;
}
var hasDefaultConstructor = Type.IsValueType || Type.GetConstructor(Type.EmptyTypes) != null;
if (!hasDefaultConstructor)
{
Constructor = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
if (Constructor != null)
{
ConstructorParams = Constructor.GetParameters()
.Select((p, i) => (Param: p, Index: i, HasProp: Array.Exists(props, r => string.Equals(r.Name, p.Name, StringComparison.OrdinalIgnoreCase))))
.Where(p => p.HasProp)
.ToDictionary(p => p.Param.Name, p => p.Param, StringComparer.OrdinalIgnoreCase);
}
}
}
/// <summary>
/// Gets the <see cref="ColumnInfo"/> for the specified column name.
/// </summary>
/// <param name="name">The column name.</param>
/// <returns>A <see cref="ColumnInfo"/> object or null if no <see cref="ColumnInfo"/> exists for the specified column name.</returns>
public List<ColumnInfo> GetColumnByName(string name)
{
ColumnsByName.TryGetValue(name, out List<ColumnInfo> col);
return col;
}
/// <summary>
/// Gets the <see cref="ColumnInfo"/> for the specified column index.
/// </summary>
/// <param name="index">The column index.</param>
/// <returns>A <see cref="ColumnInfo"/> object or null if no <see cref="ColumnInfo"/> exists for the specified column index.</returns>
public List<ColumnInfo> GetColumnByIndex(int index)
{
ColumnsByIndex.TryGetValue(index, out List<ColumnInfo> col);
return col;
}
}
}
|
using Crt.Model.Dtos.CodeLookup;
using System;
using System.Text.Json.Serialization;
namespace Crt.Model.Dtos.QtyAccmp
{
public class QtyAccmpDto
{
[JsonPropertyName("id")]
public decimal QtyAccmpId { get; set; }
public decimal ProjectId { get; set; }
public decimal FiscalYearLkupId { get; set; }
public decimal QtyAccmpLkupId { get; set; }
public decimal Forecast { get; set; }
public decimal? Schedule7 { get; set; }
public decimal Actual { get; set; }
public string Comment { get; set; }
public DateTime? EndDate { get; set; }
public virtual CodeLookupDto FiscalYearLkup { get; set; }
public virtual CodeLookupDto QtyAccmpLkup { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
#nullable disable
namespace dk.via.ftc.businesslayer.Models
{
public class Dispensary
{
public Dispensary()
{
PurchaseOrders = new HashSet<PurchaseOrder>();
}
[JsonPropertyName("DispensaryId")]
[Display(Name = "DispensaryId")]
public string DispensaryId { get; set; }
[JsonPropertyName("DispensaryName")]
[Display(Name = "Dispensary Name")]
public string DispensaryName { get; set; }
[JsonPropertyName("DispensaryLicense")]
[Display(Name = "Dispensary License")]
[Required]
//Using Remote validation attribute
[Remote("CheckLicense", "DispensaryController",HttpMethod ="POST", ErrorMessage = "Not a valid license.")]
public string DispensaryLicense { get; set; }
[JsonPropertyName("city")]
[Required]
public string City { get; set; }
[JsonPropertyName("state")]
[Required]
public string State { get; set; }
[JsonPropertyName("country")]
public string Country { get; set; }
public virtual ICollection<PurchaseOrder> PurchaseOrders { get; set; }
}
}
|
namespace Aqueduct.SitecoreLib.Examples.SampleApplication.Business.Domain.Widgets.Social
{
public class FacebookWidget : BaseWidget
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zelo.Common.CustomAttributes;
namespace Zelo.DBModel
{
[Table(Name = "ttopic")]
public class Ttopic
{
[Id(Name = "tpc_id", Strategy = GenerationType.INDENTITY)]
public int TpcId{ get; set; }
[Column(Name = "tpc_Gid")]
public string TpcGid{ get; set; }
[Column(Name = "tpc_cfGid")]
public string TpcCfGid{ get; set; }
[Column(Name = "tpc_ParentGid")]
public string TpcParentGid{ get; set; }
[Column(Name = "tpc_moderator")]
public string TpcModerator{ get; set; }
[Column(Name = "tpc_reviewer")]
public string TpcReviewer{ get; set; }
[Column(Name = "tpc_speaker")]
public string TpcSpeaker{ get; set; }
[Column(Name = "tpc_sponsor")]
public string TpcSponsor{ get; set; }
[Column(Name = "tpc_sponsorDesc")]
public string TpcSponsorDesc{ get; set; }
[Column(Name = "tpc_title")]
public string TpcTitle{ get; set; }
[Column(Name = "tpc_title_e")]
public string TpcTitleE{ get; set; }
[Column(Name = "tpc_detail")]
public string TpcDetail{ get; set; }
[Column(Name = "tpc_detail_e")]
public string TpcDetailE{ get; set; }
[Column(Name = "tpc_type")]
public string TpcType{ get; set; }
[Column(Name = "tpc_level")]
public string TpcLevel{ get; set; }
[Column(Name = "tpc_datetime_begin")]
public DateTime? TpcDatetimeBegin{ get; set; }
[Column(Name = "tpc_datetime_end")]
public DateTime? TpcDatetimeEnd{ get; set; }
[Column(Name = "tpc_createtime")]
public DateTime? TpcCreatetime{ get; set; }
[Column(Name = "tpc_updatetime")]
public DateTime? TpcUpdatetime{ get; set; }
[Column(Name = "tpc_isdel")]
public int? TpcIsdel{ get; set; }
}
}
|
/*
* Copyright © 2019 GGG KILLER <gggkiller2@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics.CodeAnalysis;
namespace Tsu.Numerics
{
/// <summary>
/// An utility class to help manipulate time as ticks
/// </summary>
#if IS_MICROPROFILER_PACKAGE
internal
#else
public
#endif
static class Duration
{
/// <summary>
/// The amount of tikcs in an hour
/// </summary>
public const Double TicksPerHour = TimeSpan.TicksPerHour;
/// <summary>
/// The amount of ticks in a minute
/// </summary>
public const Double TicksPerMinute = TicksPerHour / 60D;
/// <summary>
/// The amount of ticks in a second
/// </summary>
public const Double TicksPerSecond = TicksPerMinute / 60D;
/// <summary>
/// The amount of ticks in a millisecond
/// </summary>
public const Double TicksPerMillisecond = TicksPerSecond / 1000D;
/// <summary>
/// The amount of ticks in a microsecond
/// </summary>
public const Double TicksPerMicrosecond = TicksPerMillisecond / 1000D;
/// <summary>
/// The amount of ticks in a nanosecond
/// </summary>
public const Double TicksPerNanosecond = TicksPerMicrosecond / 1000D;
/// <summary>
/// Scales the provided value down and gets the duration from the ticks.
/// </summary>
/// <param name="ticks">The tick count.</param>
/// <param name="scaledDuration">The scaled down duration.</param>
/// <param name="suffix">The suffix.</param>
public static void GetFormatPair ( Int64 ticks, out Double scaledDuration, out String suffix )
{
if ( ticks > TicksPerHour )
{
scaledDuration = ticks / TicksPerHour;
suffix = "h";
return;
}
else if ( ticks > TicksPerMinute )
{
scaledDuration = ticks / TicksPerMinute;
suffix = "m";
return;
}
else if ( ticks > TicksPerSecond )
{
scaledDuration = ticks / TicksPerSecond;
suffix = "s";
return;
}
else if ( ticks > TicksPerMillisecond )
{
scaledDuration = ticks / TicksPerMillisecond;
suffix = "ms";
return;
}
else if ( ticks > TicksPerMicrosecond )
{
scaledDuration = ticks / TicksPerMicrosecond;
suffix = "μs";
return;
}
else
{
scaledDuration = ticks / TicksPerNanosecond;
suffix = "ns";
return;
}
}
/// <summary>
/// Formats the amount of ticks provided into a human
/// readable format.
/// </summary>
/// <param name="ticks"></param>
/// <param name="format"></param>
/// <returns></returns>
[SuppressMessage ( "Globalization", "CA1305:Specify IFormatProvider", Justification = "There's another overload accepting it." )]
public static String Format ( Int64 ticks, String format = "{0:##00.00}{1}" )
{
GetFormatPair ( ticks, out var scaledDuration, out var suffix );
return String.Format ( format, scaledDuration, suffix );
}
/// <summary>
/// Formats the amount of ticks provided into a human
/// readable format.
/// </summary>
/// <param name="ticks"></param>
/// <param name="formatProvider"></param>
/// <param name="format"></param>
/// <returns></returns>
public static String Format ( Int64 ticks, IFormatProvider formatProvider, String format = "{0:##00.00}{1}" )
{
GetFormatPair ( ticks, out var scaledDuration, out var suffix );
return String.Format ( formatProvider, format, scaledDuration, suffix );
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Rooms.Session
{
internal class FlatAccessibleComposer : MessageComposer
{
public string Username { get; }
public FlatAccessibleComposer(string username)
: base(ServerPacketHeader.FlatAccessibleMessageComposer)
{
Username = username;
}
public override void Compose(ServerPacket packet)
{
packet.WriteString(Username);
}
}
} |
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:BPiaoBao.Client.Account"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
You can also use Blend to do all this with the tool's support.
See http://www.galasoft.ch/mvvm
*/
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
namespace BPiaoBao.Client.Account.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
//共享的视图模型
SimpleIoc.Default.Register<HomeViewModel>();
SimpleIoc.Default.Register<BillRePayDetailViewModel>();
SimpleIoc.Default.Register<BillDetailViewModel>();
SimpleIoc.Default.Register<BankCardViewModel>();
}
//public ViewModelLocator()
//{
//}
/// <summary>
/// 主页视图模型
/// </summary>
public static HomeViewModel Home
{
get
{
return GetViewModel<HomeViewModel>();
}
}
/// <summary>
/// 账单还款明细视图模型
/// </summary>
public static BillRePayDetailViewModel BillRePayDetail
{
get
{
return GetViewModel<BillRePayDetailViewModel>();
}
}
/// <summary>
/// 账单消费视图模型
/// </summary>
public static BillDetailViewModel BillDetail
{
get
{
return GetViewModel<BillDetailViewModel>();
}
}
/// <summary>
/// 银行卡视图模型
/// </summary>
public static BankCardViewModel BankCard
{
get
{
return GetViewModel<BankCardViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
/// <summary>
/// 获取ViewModel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private static T GetViewModel<T>() where T : new()
{
return ServiceLocator.Current.GetInstance<T>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChartingObjects
{
public abstract class DataPointValue
{
/// <summary>
/// Determines the number of decimal places for rounding purposes.
/// </summary>
public byte decimalPrecision { get; set; }
/// <summary>
/// Generic label that will be later cast to an appropriate data type based on the valueDataType property.
/// </summary>
protected object _dataPointValue { get; set; }
/// <summary>
/// Abstract Class constructor...
/// </summary>
/// <param name="ValueDataType">Sets the value data type for retrieval from subclasses.</param>
/// <param name="dataPointValue">Generic value which will later be cast based on _valueDataType when a concrete class is instantiated.</param>
protected DataPointValue(object dataPointValue, byte DecimalPrecision)
{
this._dataPointValue = dataPointValue;
this.decimalPrecision = DecimalPrecision;
this.ConvertPointValueToDataType();
}
/// <summary>
/// Converts the generic value object to a strongly typed variable.
/// </summary>
protected abstract void ConvertPointValueToDataType();
/// <summary>
/// Returns the actual data point value.
/// </summary>
/// <returns></returns>
public abstract float? Value();
} // Class...
} // Namespace...
|
using System;
using System.ComponentModel;
using System.Data;
using DevExpress.XtraEditors.Controls;
using TLF.Framework.BaseFrame;
using TLF.Framework.Config;
namespace TLF.Framework.ControlLibrary
{
/// <summary>
///
/// </summary>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public partial class PRadioGroup : DevExpress.XtraEditors.RadioGroup
{
///////////////////////////////////////////////////////////////////////////////////////////////
// Constructor & Global Instance
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: 생성자 ::
/// <summary>
/// RadioGroup Control을 생성합니다.
/// </summary>
public PRadioGroup()
{
InitializeComponent();
}
#endregion
#region :: 전역변수 ::
private bool _checkModify = false;
private bool _showAllItemVisible = false;
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Properties
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: CheckModify :: EditValue의 변경 Check 여부를 설정합니다.
/// <summary>
/// EditValue의 변경 Check 여부를 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("EditValue의 변경 Check 여부를 설정합니다."), Browsable(true)]
public bool CheckModify
{
get { return _checkModify; }
set { _checkModify = value; }
}
#endregion
#region :: ShowAllItemVisible :: '전체선택' 숨김/보임을 설정합니다.
/// <summary>
/// '전체선택' 숨김/보임을 설정합니다.
/// </summary>
[Category(AppConfig.CONTROLCATEGORY)]
[Description("'전체' 숨김/보임을 설정합니다."), Browsable(true)]
public bool ShowAllItemVisible
{
get { return this._showAllItemVisible; }
set { this._showAllItemVisible = value; }
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Method(Public)
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: InitData(+1 Overloading) :: RadioGroup에 값을 넣습니다.
/// <summary>
/// RadioGroup에 값을 넣습니다.
/// </summary>
/// <param name="valueList">Value가 될 배열</param>
/// <param name="displayList">Text가 될 배열</param>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public void InitData(string[] valueList, string[] displayList)
{
if (valueList.Length != displayList.Length)
return;
using (DataTable dt = new DataTable())
{
dt.Columns.Add(AppConfig.VALUEMEMBER);
dt.Columns.Add(AppConfig.DISPLAYMEMBER);
for (int idx = 0; idx < valueList.Length; idx++)
{
DataRow dr = dt.NewRow();
dr[AppConfig.VALUEMEMBER] = valueList[idx];
dr[AppConfig.DISPLAYMEMBER] = displayList[idx];
dt.Rows.Add(dr);
}
this.InitData(dt, AppConfig.VALUEMEMBER, AppConfig.DISPLAYMEMBER);
}
}
/// <summary>
/// RadioGroup에 값을 넣습니다.
/// </summary>
/// <param name="dt">Datasource 가 될 DataTable</param>
/// <param name="valueMember">ValueMember 명</param>
/// <param name="displayMember">DisplayMemeber 명</param>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public void InitData(DataTable dt, string valueMember, string displayMember)
{
this.Properties.Items.Clear();
foreach (DataRow dr in dt.Rows)
{
RadioGroupItem rgi = new RadioGroupItem();
rgi.Value = dr[valueMember];
rgi.Description = dr[displayMember].ToString();
this.Properties.Items.Add(rgi);
}
if(_showAllItemVisible)
{
RadioGroupItem rgi = new RadioGroupItem();
rgi.Value = "";
rgi.Description = "전체";
this.Properties.Items.Insert(0, rgi);
}
this.SelectedIndex = this.Properties.Items.Count > 0 ? 0 : -1;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Override(Event, Properties, Method...)
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: OnLostFocus :: Focus를 잃을 때 현재값과 이전값을 비교한다.
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
if (_checkModify)
{
if (this.IsModified)
{
(this.FindForm() as UIFrame).IsModified = true;
}
}
}
#endregion
}
}
|
using System.Collections.Generic;
namespace Contoso.Forms.Configuration.Directives
{
public class DirectiveDefinitionDescriptor
{
public string ClassName { get; set; }
public string FunctionName { get; set; }
public Dictionary<string, DirectiveArgumentDescriptor> Arguments { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using ShareTradingModel;
using TestingFramework;
namespace Entities.Test
{
public class EntityTest<T>:TestBase
{
private ShareTradingEntities context;
//Write all common test for entity
public override void OnTestStartup()
{
context = new ShareTradingEntities();
}
public override void OnTestComplete()
{
//need to dispose every thing
}
}
}
|
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// 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.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.Linq;
using Rock.Model;
using Rock.Web.Cache;
namespace Rock.Communication
{
/// <summary>
/// Sends an email template using the Email communication channel
/// </summary>
public static class Email
{
/// <summary>
/// Sends the specified email template unique identifier.
/// </summary>
/// <param name="emailTemplateGuid">The email template unique identifier.</param>
/// <param name="recipients">The recipients.</param>
/// <param name="appRoot">The application root.</param>
/// <param name="themeRoot">The theme root.</param>
public static void Send( Guid emailTemplateGuid, Dictionary<string, Dictionary<string, object>> recipients, string appRoot = "", string themeRoot = "" )
{
if ( emailTemplateGuid != Guid.Empty && recipients != null && recipients.Any() )
{
var channelEntity = EntityTypeCache.Read( Rock.SystemGuid.EntityType.COMMUNICATION_CHANNEL_EMAIL.AsGuid() );
if ( channelEntity != null )
{
var channel = ChannelContainer.GetComponent( channelEntity.Name );
if ( channel != null )
{
var transport = channel.Transport;
if ( transport != null )
{
var template = new SystemEmailService().Get( emailTemplateGuid );
if ( template != null )
{
transport.Send( template, recipients, appRoot, themeRoot );
}
}
}
}
}
}
}
}
|
using BerlinClock.Classes.TimeDisplay;
using BerlinClock.Classes.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BerlinClock.Classes.Time
{
class Hours : IBerlinTime
{
List<ILightDisplay> lightDisplay = new List<ILightDisplay>()
{
new RedLight(),
new OffLight()
};
public string ReturnBerlinPointer(string time)
{
return TopHours(time) + "\r\n" + BottomHours(time);
}
private string TopHours(string time)
{
int topHours = time.TimeToHour() / 5;
var topHourPointer = new StringBuilder(4);
for (int i = 1; i <= 4; i++)
topHourPointer.Append(lightDisplay.FirstOrDefault(l => l.LightValidation(i <= topHours ? 1 : 0)).LightDisplay());
return topHourPointer.ToString();
}
private string BottomHours(string time)
{
int bottomHour = time.TimeToHour() % 5;
var bottomHourPointer = new StringBuilder(4);
for (int i = 1; i <= 4; i++)
bottomHourPointer.Append(lightDisplay.FirstOrDefault(l => l.LightValidation(i <= bottomHour ? 1 : 0)).LightDisplay());
return bottomHourPointer.ToString();
}
}
}
|
using SQLite;
namespace CapstoneTravelApp.DatabaseTables
{
public class User_Table
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int UserId { get; set; }
[NotNull]
[Unique]
public string UserName { get; set; }
[NotNull]
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotNull]
public string UserEmail { get; set; }
public User_Table() { }
}
}
|
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_22
{
using System;
using System.IO;
public class Program
{
public static void Search()
{
using (TemporaryFileStream fileStream1 =
new TemporaryFileStream(),
fileStream2 = new TemporaryFileStream())
{
// Use temporary file stream;
}
}
}
class TemporaryFileStream : IDisposable
{
public TemporaryFileStream(string fileName)
{
_File = new FileInfo(fileName);
_Stream = new FileStream(
File.FullName, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
}
public TemporaryFileStream()
: this(Path.GetTempFileName()) { }
~TemporaryFileStream()
{
Close();
}
public FileStream Stream
{
get { return _Stream; }
}
readonly private FileStream _Stream;
public FileInfo File
{
get { return _File; }
}
readonly private FileInfo _File;
public void Close()
{
if (Stream != null)
{
Stream.Close();
}
if (File != null)
{
File.Delete();
}
// Turn off calling the finalizer
System.GC.SuppressFinalize(this);
}
#region IDisposable Members
public void Dispose()
{
Close();
}
#endregion
}
} |
using Alarmy.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alarmy.Core
{
internal class AlarmService : IAlarmService, IDisposable
{
private readonly IEqualityComparer<IAlarm> valueComparer;
private readonly ITimer timer;
private readonly IAlarmRepository repository;
private readonly bool isStoppableRepository;
private readonly IDictionary<Guid, IAlarm> cache;
private bool pauseRepositoryUpdates;
public event EventHandler<AlarmEventArgs> OnAlarmAdd;
public event EventHandler<AlarmEventArgs> OnAlarmRemoval;
public event EventHandler<AlarmEventArgs> OnAlarmUpdate;
public event EventHandler<AlarmEventArgs> OnAlarmStatusChange;
public AlarmService(IAlarmRepository repository, ITimer checkTimer)
{
if (repository == null)
throw new ArgumentNullException("repository");
if (checkTimer == null)
throw new ArgumentNullException("checkTimer");
this.cache = new Dictionary<Guid, IAlarm>();
this.valueComparer = new AlarmEqualityComparer();
this.repository = repository;
this.isStoppableRepository = typeof(ISupportsStartStop).IsAssignableFrom(repository.GetType());
this.timer = checkTimer;
this.timer.Elapsed += timer_Elapsed;
}
public void Start()
{
this.timer.Start();
if (this.isStoppableRepository)
((ISupportsStartStop)this.repository).Start();
this.RefreshRepository();
}
public void Stop()
{
this.timer.Stop();
if (this.isStoppableRepository)
((ISupportsStartStop)this.repository).Stop();
}
public void Add(IAlarm alarm)
{
if (alarm == null)
throw new ArgumentNullException("alarm");
lock (this.cache)
{
this.cache.Add(alarm.Id, alarm);
this.UpdateRepository();
if (this.OnAlarmAdd != null)
this.OnAlarmAdd.Invoke(this, new AlarmEventArgs(alarm));
this.CheckAlarmStatus(alarm);
}
}
public void Remove(IAlarm alarm)
{
if (alarm == null)
throw new ArgumentNullException("alarm");
lock (this.cache)
{
this.cache.Remove(alarm.Id);
this.UpdateRepository();
if (this.OnAlarmRemoval != null)
this.OnAlarmRemoval.Invoke(this, new AlarmEventArgs(alarm));
}
}
public void Update(IAlarm alarm)
{
if (alarm == null)
throw new ArgumentNullException("alarm");
lock (this.cache)
{
this.cache[alarm.Id] = alarm;
this.UpdateRepository();
if (this.OnAlarmUpdate != null)
this.OnAlarmUpdate.Invoke(this, new AlarmEventArgs(alarm));
this.CheckAlarmStatus(alarm);
}
}
public IEnumerable<IAlarm> List()
{
return this.cache.Values;
}
public void Import(IEnumerable<IAlarm> alarms, bool deleteExisting)
{
lock (this.cache)
try
{
this.pauseRepositoryUpdates = true;
if (deleteExisting)
{
foreach (var alarm in this.cache.Values.ToArray())
{
this.Remove(alarm);
}
}
this.RefreshRepository();
var equityComparer = new AlarmMetadataEqualityComparer();
foreach(var alarm in alarms)
{
if (!this.cache.Values.Contains(alarm, equityComparer))
this.Add(alarm);
}
}
finally
{
this.pauseRepositoryUpdates = false;
this.UpdateRepository();
}
}
public void Dispose()
{
if (this.timer != null)
this.timer.Dispose();
}
private void timer_Elapsed(object sender, EventArgs e)
{
lock (this.cache)
{
if (!this.RefreshRepository())
foreach (var alarm in this.cache.Values)
{
this.CheckAlarmStatus(alarm);
}
}
}
private bool RefreshRepository()
{
lock (this.cache)
{
var alarmList = this.repository.Load();
if (alarmList == null)
return false;
var alarms = alarmList.ToDictionary(x => x.Id);
var deletedAlarmKeys = this.cache.Keys.Where(x => !alarms.ContainsKey(x)).ToArray();
foreach (var key in deletedAlarmKeys)
{
if (this.OnAlarmRemoval != null)
this.OnAlarmRemoval.Invoke(this, new AlarmEventArgs(this.cache[key]));
this.cache.Remove(key);
}
foreach (var alarm in alarms.Values)
{
IAlarm cachedAlarm = null;
if (this.cache.TryGetValue(alarm.Id, out cachedAlarm))
{
if (!this.valueComparer.Equals(cachedAlarm, alarm))
{
cachedAlarm.Import(alarm);
if (this.OnAlarmUpdate != null)
this.OnAlarmUpdate.Invoke(this, new AlarmEventArgs(cachedAlarm));
}
}
else
{
cachedAlarm = alarm;
this.cache.Add(alarm.Id, cachedAlarm);
if (this.OnAlarmAdd != null)
this.OnAlarmAdd.Invoke(this, new AlarmEventArgs(cachedAlarm));
}
this.CheckAlarmStatus(cachedAlarm);
}
return true;
}
}
private void UpdateRepository()
{
if (this.pauseRepositoryUpdates)
return;
this.repository.Save(this.cache.Values);
}
private void CheckAlarmStatus(IAlarm cachedAlarm)
{
if (cachedAlarm.CheckStatusChange())
{
if (this.OnAlarmStatusChange != null)
this.OnAlarmStatusChange.Invoke(this, new AlarmEventArgs(cachedAlarm));
}
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.Web;
using DotNetNuke.Web.Mvc.Framework.Modules;
using DotNetNuke.Web.Mvc.Routing;
using Moq;
using NUnit.Framework;
namespace DotNetNuke.Tests.Web.Mvc.Routing
{
[TestFixture]
public class HttpContextExtensionsTests
{
[Test]
public void GetModuleRequestResult_Returns_ModuleRequestResult_If_Present()
{
//Arrange
var httpContext = MockHelper.CreateMockHttpContext();
var expectedResult = new ModuleRequestResult();
httpContext.Items[HttpContextExtensions.ModuleRequestResultKey] = expectedResult;
//Act
var result = httpContext.GetModuleRequestResult();
//Assert
Assert.AreSame(expectedResult, result);
}
[Test]
public void GetModuleRequestResult_Returns_Null_If_Not_Present()
{
//Arrange
var httpContext = MockHelper.CreateMockHttpContext();
//Act
var result = httpContext.GetModuleRequestResult();
//Assert
Assert.IsNull(result);
}
[Test]
public void HasModuleRequestResult_Returns_True_If_Present()
{
// Arrange
HttpContextBase httpContext = MockHelper.CreateMockHttpContext();
var expectedResult = new ModuleRequestResult();
httpContext.Items[HttpContextExtensions.ModuleRequestResultKey] = expectedResult;
//Act and Assert
Assert.IsTrue(httpContext.HasModuleRequestResult());
}
[Test]
public void HasModuleRequestResult_Returns_False_If_Not_Present()
{
// Arrange
HttpContextBase httpContext = MockHelper.CreateMockHttpContext();
// Act and Assert
Assert.IsFalse(httpContext.HasModuleRequestResult());
}
[Test]
public void SetModuleRequestResult_Sets_ModuleRequestResult()
{
// Arrange
HttpContextBase context = MockHelper.CreateMockHttpContext();
var expectedResult = new ModuleRequestResult();
// Act
context.SetModuleRequestResult(expectedResult);
// Assert
var actual = context.Items[HttpContextExtensions.ModuleRequestResultKey];
Assert.IsNotNull(actual);
Assert.IsInstanceOf<ModuleRequestResult>(actual);
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.FunctionalTests.TestDoubles;
using Microsoft.Azure.WebJobs.Host.Loggers;
using Microsoft.Azure.WebJobs.Host.TestCommon;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace Microsoft.Azure.WebJobs.Host.FunctionalTests
{
static class Utility
{
public static IHostBuilder ConfigureDefaultTestHost<TProgram>(this IHostBuilder builder, StorageAccount account)
{
return builder.ConfigureDefaultTestHost<TProgram>(b =>
{
b.AddAzureStorage();
})
.ConfigureServices(services => services.AddFakeStorageAccountProvider(account));
}
public static IHostBuilder ConfigureFakeStorageAccount(this IHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddFakeStorageAccountProvider();
});
}
public static IServiceCollection AddFakeStorageAccountProvider(this IServiceCollection services)
{
// return services.AddFakeStorageAccountProvider(new XFakeStorageAccount()); $$$
throw new NotImplementedException();
}
public static IServiceCollection AddNullLoggerProviders(this IServiceCollection services)
{
return services
.AddSingleton<IFunctionOutputLoggerProvider, NullFunctionOutputLoggerProvider>()
.AddSingleton<IFunctionInstanceLoggerProvider, NullFunctionInstanceLoggerProvider>();
}
public static IServiceCollection AddFakeStorageAccountProvider(this IServiceCollection services, StorageAccount account)
{
throw new NotImplementedException();
/*
if (account is XFakeStorageAccount)
{
services.AddNullLoggerProviders();
}
return services.AddSingleton<XStorageAccountProvider>(new FakeStorageAccountProvider(account));
*/
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Requestrr.WebApi.Controllers.ChatClients
{
public class ChatClientsSettingsModel
{
[Required]
public string Client { get; set; }
[Required]
public string ClientId { get; set; }
[Required]
public string BotToken { get; set; }
public string StatusMessage { get; set; }
public string[] MonitoredChannels { get; set; }
public string[] TvShowRoles { get; set; }
public string[] MovieRoles { get; set; }
public bool EnableRequestsThroughDirectMessages { get; set; }
public bool AutomaticallyNotifyRequesters { get; set; }
public string NotificationMode { get; set; }
public string[] NotificationChannels { get; set; }
public bool AutomaticallyPurgeCommandMessages { get; set; }
public string Language { get; set; }
public string[] AvailableLanguages { get; set; }
}
public class ChatClientTestSettingsModel
{
[Required]
public string BotToken { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc;
namespace WebApiSample.Controllers
{
[ApiExplorerSettings(IgnoreApi = true), Route("")]
public class DefaultController : Controller
{
[HttpGet]
public IActionResult Get() => Redirect("swagger");
}
} |
using FatCat.Nes.OpCodes.Comparing;
using JetBrains.Annotations;
namespace FatCat.Nes.Tests.OpCodes.Comparing
{
[UsedImplicitly]
public class CompareXRegisterTests : CompareRegisterTests
{
protected override string ExpectedName => "CPX";
public CompareXRegisterTests() => opCode = new CompareXRegister(cpu, addressMode);
protected override void SetRegister(byte registerValue) => cpu.XRegister = registerValue;
}
} |
using Shop.BusinnesLogic.Convesions;
using Shop.BusinnesLogic.Models;
using Shop.BusinnesLogic.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Shop.Controllers
{
public class CategoryClientController : ApiController
{
private ICategoryClientService _categoryClientService;
public CategoryClientController(ICategoryClientService categoryClientService)
{
_categoryClientService = categoryClientService;
}
[HttpGet]
public IHttpActionResult GetAll()
{
var categoryLIst = _categoryClientService.Get().Select(c=>c.ToViewModel());
return Ok(categoryLIst);
}
[HttpGet]
public IHttpActionResult Get(int id)
{
var category = _categoryClientService.GetDetails(id).ToViewModel();
if (category == null)
return NotFound();
return Ok(category);
}
[HttpPost]
public IHttpActionResult Add([FromBody] CategoryClientViewModel model)
{
if (model == null)
BadRequest();
var category = model.ToDto();
int categoryId = _categoryClientService.Add(category);
return Ok();
}
[HttpPut]
public IHttpActionResult Update([FromBody] CategoryClientViewModel model)
{
if (model == null)
BadRequest();
var category = model.ToDto();
_categoryClientService.Update(category);
return Ok();
}
[HttpDelete]
public IHttpActionResult Delete(int id)
{
_categoryClientService.Delete(id);
return Ok();
}
}
}
|
using System.IO;
public class LineReader
{
protected FileInfo theSourceFile = null;
protected StreamReader reader = null;
public string text = " "; // assigned to allow first line to be read below
public string[] bits;
public void AssignFile(string fileName)
{
theSourceFile = new FileInfo(fileName);
reader = theSourceFile.OpenText();
}
public void ReadLine()
{
if (text != null)
{
text = reader.ReadLine();
}
}
public void SplitBits()
{
bits = text.Split(' ');
}
public void CloseFile()
{
reader.Close ();
}
}
|
namespace BlazorUtils.WebTest._0._5.Models
{
public class Course
{
public Course(string id, string prof)
{
Id = id;
Prof = prof;
}
public string Id { get; set; }
public string Prof { get; set; }
}
}
|
using MedManagerLibrary.Domain;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MedManagerLibrary.Data
{
public class AdministradoresData
{
private String conexion;
public AdministradoresData(String con)
{
this.conexion = con;
}
public Boolean existeAdmin( String contra)
{
SqlConnection conexion = new SqlConnection(this.conexion);
SqlDataAdapter daAdm = new SqlDataAdapter(new SqlCommand("select * FROM Administradores where contrasena="+contra, conexion));
DataSet dsAdm = new DataSet();
daAdm.Fill(dsAdm, "Administradores");
LinkedList<Administradores> admin = new LinkedList<Administradores>();
foreach (DataRow fila in dsAdm.Tables["Administradores"].Rows)
{
admin.AddLast(new Administradores(fila["contrasena"].ToString()));
}
if(admin.Count > 0)
return true;
else
return false;
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using JetBrains.Metadata.Reader.API;
using JetBrains.Metadata.Utils;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Model2.Assemblies.Interfaces;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.Impl.Resolve;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.Util;
using KaVE.Commons.Model.Naming;
using Moq;
namespace KaVE.RS.Commons.Tests_Unit.TestFactories
{
public static class TypeMockUtils
{
public static IType MockIType(string fqnOrAlias, string assemblyName, string assemblyVersion)
{
return MockIType(fqnOrAlias, EmptySubstitution.INSTANCE, assemblyName, assemblyVersion);
}
public static IType MockIType(string fqnOrAlias,
IEnumerable<KeyValuePair<string, IType>> typeParameters,
string assemblyName,
string assemblyVersion)
{
var parameters = new List<ITypeParameter>();
var parameterSubstitutes = new List<IType>();
foreach (var typeParameter in typeParameters)
{
var mockTypeParameter = new Mock<ITypeParameter>();
mockTypeParameter.Setup(tp => tp.ShortName).Returns(typeParameter.Key);
parameters.Add(mockTypeParameter.Object);
parameterSubstitutes.Add(typeParameter.Value);
}
return MockIType(
fqnOrAlias,
new SubstitutionImpl(parameters, parameterSubstitutes),
assemblyName,
assemblyVersion);
}
private static IType MockIType(string fqnOrAlias,
ISubstitution substitution,
string assemblyName,
string assemblyVersion)
{
var typeMock = new Mock<IDeclaredType>();
typeMock.Setup(t => t.Classify).Returns(TypeClassification.REFERENCE_TYPE);
var fqn = BuiltInTypeAliases.GetFullTypeNameFromTypeAlias(fqnOrAlias);
var mockTypeElement = MockTypeElement(fqn, assemblyName, assemblyVersion);
mockTypeElement.TypeParameters.AddRange(substitution.Domain);
typeMock.Setup(t => t.GetTypeElement()).Returns(mockTypeElement);
typeMock.Setup(t => t.GetLongPresentableName(CSharpLanguage.Instance)).Returns(fqnOrAlias);
typeMock.Setup(t => t.Assembly).Returns(MockAssemblyNameInfo(assemblyName, assemblyVersion));
var mockResolveResult = new Mock<IResolveResult>();
mockResolveResult.Setup(rr => rr.Substitution).Returns(substitution);
typeMock.Setup(t => t.Resolve()).Returns(mockResolveResult.Object);
return typeMock.Object;
}
public static IType MockTypeParamIType(string name)
{
var typeMock = new Mock<IDeclaredType>();
typeMock.Setup(t => t.Classify).Returns(TypeClassification.UNKNOWN);
return typeMock.Object;
}
public static ITypeElement MockTypeElement(string fqn, string assemblyName, string assemblyVersion)
{
return MockTypeElement(fqn, MockAssembly(assemblyName, assemblyVersion));
}
public static ITypeElement MockTypeElement(string fqn, IModule module)
{
if (fqn.Contains("[["))
{
fqn = fqn.Substring(0, fqn.IndexOf("[[", StringComparison.Ordinal));
}
var clrMock = new Mock<IClrTypeName>();
clrMock.Setup(clr => clr.FullName).Returns(fqn);
var teMock = new Mock<ITypeElement>();
teMock.Setup(te => te.GetClrName()).Returns(clrMock.Object);
teMock.Setup(te => te.Module).Returns(MockPsiModule(module));
teMock.Setup(te => te.TypeParameters).Returns(new List<ITypeParameter>());
return teMock.Object;
}
private static IPsiModule MockPsiModule(IModule containingProjectModule)
{
var moduleMock = new Mock<IPsiModule>();
moduleMock.Setup(m => m.ContainingProjectModule).Returns(containingProjectModule);
return moduleMock.Object;
}
public static IAssembly MockAssembly(string name, string version)
{
var mockAssembly = new Mock<IAssembly>();
mockAssembly.Setup(a => a.AssemblyName).Returns(MockAssemblyNameInfo(name, version));
return mockAssembly.Object;
}
public static IProject MockProject(string name)
{
var project = Mock.Of<IProject>();
Mock.Get(project).Setup(p => p.Name).Returns(name);
return project;
}
private static AssemblyNameInfo MockAssemblyNameInfo(string name, string version)
{
return AssemblyNameInfo.Create(name, new Version(version));
}
}
} |
using System;
using System.Collections.Generic;
namespace LRUCacheV1
{
public class LRUCache<T> where T : class
{
public long Size
{
get
{
return _items.Length;
}
}
private LRUItem<T> Newest;
private LRUItem<T> Oldest;
private long _cacheSize;
private LRUItem<T>[] _items;
public LRUCache(int cacheSize)
{
this._cacheSize = cacheSize;
this._items = new LRUItem<T>[] { };
}
public void Add(int key, T value)
{
var item = GetRef(key);
if (item != null)
{
Console.WriteLine($"Refreshing: {item.key}");
// Key is already present on the array
var oldNewest = Newest;
Newest = item;
item.next.last = item.last;
item.last.next = item.next;
if (Oldest == item)
{
Oldest = item.last;
Oldest.next = Newest;
}
item.last = Oldest;
item.next = oldNewest;
item.value = value;
oldNewest.last.next = item;
oldNewest.last = item;
}
else
{
var newItem = new LRUItem<T>()
{
key = key,
value = value
};
if (_items.Length + 1 > _cacheSize)
{
Console.WriteLine($"Adding {newItem.key} to a full Array (replacing {Oldest.key})");
// Adding items on a full array
var oldNewest = Newest;
var oldOldest = Oldest;
Newest = newItem;
newItem.last = oldOldest.last;
newItem.next = oldNewest;
oldOldest.last.next = Newest;
oldNewest.last = Newest;
Oldest = oldOldest.last;
var index = Array.IndexOf(_items, oldOldest);
_items[index] = Newest;
}
else
{
Console.WriteLine($"Adding {newItem.key}");
if (_items.Length == 0)
{
// Adding items when array is empty
Newest = newItem;
Oldest = newItem;
newItem.next = newItem;
newItem.last = newItem;
}
// Adding items on a non full array
var oldNewest = Newest;
newItem.last = Oldest;
newItem.next = oldNewest;
oldNewest.last.next = newItem;
oldNewest.last = newItem;
Newest = newItem;
var newItemPosition = _items.Length;
_items = _items.EnsureCapacity(_items.Length + 1);
_items[newItemPosition] = newItem;
}
_items.QuickSort();
}
}
public T Get(int key)
{
var item = _items.BinarySearch(key);
if (item != null)
{
RenewCache(item);
return item.value;
}
else
{
return null;
}
}
private void RenewCache(LRUItem<T> item)
{
Add(item.key, item.value);
}
private LRUItem<T> GetRef(int key)
{
return _items.BinarySearch(key);
}
public void PrintCache()
{
Console.WriteLine(new String('-', 100));
Console.WriteLine($"Newest: {Newest.key} - Oldest: {Oldest.key}");
var item = Newest;
do
{
Console.WriteLine($"<({item.last.key}) {item.key} ({item.next.key})>");
item = item.next;
} while (item != Newest);
Console.WriteLine(new String('-', 100));
}
}
public class LRUItem<T>
{
public int key;
public T value;
public LRUItem<T> next;
public LRUItem<T> last;
}
}
|
// Umbraco Inception allows you to specify the 'Allowed child node types' using the classes that create those document types.
// We want to keep our document type specifications in separate projects, alongside their associated templates, but this creates
// a problem. You can't create a circular reference where Type A in project A allows Type B in project B, and Type B also allows
// Type A. You can update the settings in the UI, but Inception resets them regularly.
// The way Inception uses the types to set the allowed child nodes is just by reading the alias from the UmbracoContentType attribute,
// so the solution is a shared library which lists all the aliases that can be specified as child node types. It doesn't matter
// that it's not the original class, so long as the aliases match. Note that the aliases are case-sensitive.
using System;
using Umbraco.Inception.Attributes;
namespace Escc.EastSussexGovUK.UmbracoDocumentTypes
{
[UmbracoContentType("", "task", null, false)]
public class TaskDocumentTypeAlias { }
[UmbracoContentType("", "Landing", null, false)]
public class LandingDocumentTypeAlias { }
[UmbracoContentType("", "location", null, false)]
public class LocationDocumentTypeAlias { }
[UmbracoContentType("", "Person", null, false)]
public class PersonDocumentTypeAlias { }
[UmbracoContentType("", "HoldingPage", null, false), Obsolete]
public class HoldingPageDocumentTypeAlias { }
[UmbracoContentType("", "landingPageWithPictures", null, false)]
public class LandingPageWithPicturesDocumentTypeAlias { }
[UmbracoContentType("", "Guide", null, false)]
public class GuideDocumentTypeAlias { }
[UmbracoContentType("", "standardLandingPage", null, false)]
public class StandardLandingPageDocumentTypeAlias { }
[UmbracoContentType("", "standardTopicPage", null, false)]
public class StandardTopicPageDocumentTypeAlias { }
[UmbracoContentType("", "standardDownloadPage", null, false)]
public class StandardDownloadPageDocumentTypeAlias { }
[UmbracoContentType("", "Map", null, false)]
public class MapDocumentTypeAlias { }
[UmbracoContentType("", "FormDownloadPage", null, false)]
public class FormDownloadPageDocumentTypeAlias { }
[UmbracoContentType("", "Childcare", null, false)]
public class ChildcareDocumentTypeAlias { }
[UmbracoContentType("", "CouncilOffice", null, false)]
public class CouncilOfficeDocumentTypeAlias { }
[UmbracoContentType("", "DayCentre", null, false)]
public class DayCentreDocumentTypeAlias { }
[UmbracoContentType("", "Library", null, false)]
public class LibraryDocumentTypeAlias { }
[UmbracoContentType("", "MobileLibraryStop", null, false)]
public class MobileLibraryStopDocumentTypeAlias { }
[UmbracoContentType("", "Park", null, false)]
public class ParkDocumentTypeAlias { }
[UmbracoContentType("", "RecyclingSite", null, false)]
public class RecyclingSiteDocumentTypeAlias { }
[UmbracoContentType("", "RegistrationOffice", null, false)]
public class RegistrationOfficeDocumentTypeAlias { }
[UmbracoContentType("", "SportLocation", null, false)]
public class SportLocationDocumentTypeAlias { }
[UmbracoContentType("", "CampaignLanding", null, false)]
public class CampaignLandingDocumentTypeAlias { }
[UmbracoContentType("", "CouncilPlanHomePage", null, false)]
public class CouncilPlanHomePageDocumentTypeAlias { }
}
|
using Microsoft.EntityFrameworkCore;
using MisMarcadores.Data.DataAccess;
using MisMarcadores.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MisMarcadores.Repository
{
public class EquiposRepository : GenericRepository<Equipo>, IEquiposRepository
{
public EquiposRepository(MisMarcadoresContext context) : base(context) { }
public void BorrarEquipo(Guid id)
{
Equipo equipo = context.Equipos.FirstOrDefault(d => d.Id == id);
var favoritos = context.Favoritos.Where(f => f.IdEquipo == equipo.Id);
foreach (var favorito in favoritos)
{
context.Favoritos.Remove(favorito);
}
var encuentros = context.Encuentros.Where(e => e.EquipoLocal.Nombre.Equals(equipo.Nombre) || e.EquipoVisitante.Nombre.Equals(equipo.Nombre));
foreach (var encuentro in encuentros)
{
context.Encuentros.Remove(encuentro);
}
context.Equipos.Remove(equipo);
}
public Equipo ObtenerEquipoPorDeporte(string nombreDeporte, string nombreEquipo)
{
return context.Equipos.Include(e => e.Deporte).FirstOrDefault(x => x.Deporte.Nombre.Equals(nombreDeporte) && x.Nombre.Equals(nombreEquipo));
}
public void ModificarEquipo(Equipo equipo)
{
var equipoOriginal = GetByID(equipo.Id);
context.Equipos.Attach(equipoOriginal);
var entry = context.Entry(equipoOriginal);
entry.CurrentValues.SetValues(equipo);
}
public Equipo ObtenerEquipoPorId(Guid id)
{
return context.Equipos.Include(e => e.Deporte).FirstOrDefault(e => e.Id.Equals(id));
}
public Equipo ObtenerEquipoPorNombre(string nombre)
{
return context.Equipos.Include(e => e.Deporte).FirstOrDefault(e => e.Nombre.Equals(nombre));
}
public List<Equipo> ObtenerEquipos()
{
return context.Equipos.Include(e => e.Deporte).ToList();
}
public List<Equipo> ObtenerEquiposPorDeporte(string deporte)
{
return context.Equipos.Where(x => x.Deporte.Nombre.Equals(deporte)).ToList();
}
}
}
|
using ReturnOfThePioneers.Cards;
using ReturnOfThePioneers.Common.Models;
using ReturnOfThePioneers.Items;
using System.Collections.Generic;
namespace ReturnOfThePioneers.Families {
public class Family : Entity {
public string Server { get; set; }
public string AccountId { get; set; }
public string SavedPoint { get; set; }
public string LastPoint { get; set; }
public List<string> LastTeam { get; set; } = new List<string>();
public List<FamilyCard> Cards { get; set; } = new List<FamilyCard>();
public List<FamilyItem> Items { get; set; } = new List<FamilyItem>();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.